/brz/remove-bazaar

To get this branch, use:
bzr branch http://gegoxaren.bato24.eu/bzr/brz/remove-bazaar
2241.1.4 by Martin Pool
Moved old weave-based repository formats into bzrlib.repofmt.weaverepo.
1
# Copyright (C) 2005, 2006, 2007 Canonical Ltd
1887.1.1 by Adeodato Simó
Do not separate paragraphs in the copyright statement with blank lines,
2
#
1534.4.39 by Robert Collins
Basic BzrDir support.
3
# This program is free software; you can redistribute it and/or modify
4
# it under the terms of the GNU General Public License as published by
5
# the Free Software Foundation; either version 2 of the License, or
6
# (at your option) any later version.
1887.1.1 by Adeodato Simó
Do not separate paragraphs in the copyright statement with blank lines,
7
#
1534.4.39 by Robert Collins
Basic BzrDir support.
8
# This program is distributed in the hope that it will be useful,
9
# but WITHOUT ANY WARRANTY; without even the implied warranty of
10
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
11
# GNU General Public License for more details.
1887.1.1 by Adeodato Simó
Do not separate paragraphs in the copyright statement with blank lines,
12
#
1534.4.39 by Robert Collins
Basic BzrDir support.
13
# You should have received a copy of the GNU General Public License
14
# along with this program; if not, write to the Free Software
15
# Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
16
17
"""BzrDir logic. The BzrDir is the basic control directory used by bzr.
18
19
At format 7 this was split out into Branch, Repository and Checkout control
20
directories.
2830.1.1 by Ian Clatworthy
bzrdir.py code clean-ups
21
22
Note: This module has a lot of ``open`` functions/methods that return
23
references to in-memory objects. As a rule, there are no matching ``close``
24
methods. To free any associated resources, simply stop referencing the
25
objects returned.
1534.4.39 by Robert Collins
Basic BzrDir support.
26
"""
27
2830.1.1 by Ian Clatworthy
bzrdir.py code clean-ups
28
# TODO: Move old formats into a plugin to make this file smaller.
1910.7.17 by Andrew Bennetts
Various cosmetic changes.
29
1773.4.1 by Martin Pool
Add pyflakes makefile target; fix many warnings
30
from cStringIO import StringIO
1534.5.7 by Robert Collins
Start factoring out the upgrade policy logic.
31
import os
1996.3.3 by John Arbash Meinel
Shave off another 40ms by demand loading branch and bzrdir
32
33
from bzrlib.lazy_import import lazy_import
34
lazy_import(globals(), """
1773.4.1 by Martin Pool
Add pyflakes makefile target; fix many warnings
35
from stat import S_ISDIR
2711.2.1 by Martin Pool
Deprecate BzrDir.create_repository
36
import textwrap
37
from warnings import warn
1534.4.39 by Robert Collins
Basic BzrDir support.
38
39
import bzrlib
1996.3.3 by John Arbash Meinel
Shave off another 40ms by demand loading branch and bzrdir
40
from bzrlib import (
41
    errors,
2776.1.5 by Robert Collins
Add reasonably comprehensive tests for path last modified and per file graph behaviour.
42
    graph,
1996.3.3 by John Arbash Meinel
Shave off another 40ms by demand loading branch and bzrdir
43
    lockable_files,
44
    lockdir,
2204.4.1 by Aaron Bentley
Add 'formats' help topic
45
    registry,
2018.5.25 by Andrew Bennetts
Make sure RemoteBzrDirFormat is always registered (John Arbash Meinel, Robert Collins, Andrew Bennetts).
46
    remote,
1996.3.12 by John Arbash Meinel
Change how 'revision' is imported to avoid problems later
47
    revision as _mod_revision,
2204.4.12 by Aaron Bentley
Deprecate bzrdir.BzrDirFormat.set_default_format
48
    symbol_versioning,
2323.6.4 by Martin Pool
BzrDir._check_supported now also takes care of recommending upgrades, which
49
    ui,
1996.3.3 by John Arbash Meinel
Shave off another 40ms by demand loading branch and bzrdir
50
    urlutils,
1996.3.6 by John Arbash Meinel
Find a few places that weren't importing their dependencies.
51
    xml4,
52
    xml5,
2255.12.1 by Robert Collins
Implement upgrade for working trees.
53
    workingtree,
54
    workingtree_4,
1996.3.3 by John Arbash Meinel
Shave off another 40ms by demand loading branch and bzrdir
55
    )
1534.5.7 by Robert Collins
Start factoring out the upgrade policy logic.
56
from bzrlib.osutils import (
1996.3.3 by John Arbash Meinel
Shave off another 40ms by demand loading branch and bzrdir
57
    sha_strings,
58
    sha_string,
59
    )
2018.5.159 by Andrew Bennetts
Rename SmartClient to _SmartClient.
60
from bzrlib.smart.client import _SmartClient
2432.3.1 by Andrew Bennetts
Try a version 1 hello probe to determine if we can use RemoteBzrDir on a particular transport, allowing smooth interoperation with older servers.
61
from bzrlib.smart import protocol
1563.2.28 by Robert Collins
Add total_size to the revision_store api.
62
from bzrlib.store.revision.text import TextRevisionStore
1534.5.7 by Robert Collins
Start factoring out the upgrade policy logic.
63
from bzrlib.store.text import TextStore
1563.2.25 by Robert Collins
Merge in upstream.
64
from bzrlib.store.versioned import WeaveStore
1563.2.34 by Robert Collins
Remove the commit and rollback transaction methods as misleading, and implement a WriteTransaction
65
from bzrlib.transactions import WriteTransaction
2164.2.21 by Vincent Ladeuil
Take bundles into account.
66
from bzrlib.transport import (
67
    do_catching_redirections,
68
    get_transport,
69
    )
1534.5.7 by Robert Collins
Start factoring out the upgrade policy logic.
70
from bzrlib.weave import Weave
1996.3.3 by John Arbash Meinel
Shave off another 40ms by demand loading branch and bzrdir
71
""")
72
2164.2.1 by v.ladeuil+lp at free
First rough http branch redirection implementation.
73
from bzrlib.trace import (
74
    mutter,
75
    note,
76
    )
1996.3.3 by John Arbash Meinel
Shave off another 40ms by demand loading branch and bzrdir
77
from bzrlib.transport.local import LocalTransport
2711.2.1 by Martin Pool
Deprecate BzrDir.create_repository
78
from bzrlib.symbol_versioning import (
79
    deprecated_function,
80
    deprecated_method,
81
    zero_ninetyone,
82
    )
1534.4.39 by Robert Collins
Basic BzrDir support.
83
84
85
class BzrDir(object):
86
    """A .bzr control diretory.
87
    
88
    BzrDir instances let you create or open any of the things that can be
89
    found within .bzr - checkouts, branches and repositories.
90
    
1534.4.40 by Robert Collins
Add RepositoryFormats and allow bzrdir.open or create _repository to be used.
91
    transport
92
        the transport which this bzr dir is rooted at (i.e. file:///.../.bzr/)
1534.4.50 by Robert Collins
Got the bzrdir api straightened out, plenty of refactoring to use it pending, but the api is up and running.
93
    root_transport
2830.1.1 by Ian Clatworthy
bzrdir.py code clean-ups
94
        a transport connected to the directory this bzr was opened from
95
        (i.e. the parent directory holding the .bzr directory).
1534.4.39 by Robert Collins
Basic BzrDir support.
96
    """
97
1687.1.12 by Robert Collins
Hook in the full break-lock ui.
98
    def break_lock(self):
99
        """Invoke break_lock on the first object in the bzrdir.
100
101
        If there is a tree, the tree is opened and break_lock() called.
102
        Otherwise, branch is tried, and finally repository.
103
        """
1752.2.52 by Andrew Bennetts
Flesh out more Remote* methods needed to open and initialise remote branches/trees/repositories.
104
        # XXX: This seems more like a UI function than something that really
105
        # belongs in this class.
1687.1.12 by Robert Collins
Hook in the full break-lock ui.
106
        try:
107
            thing_to_unlock = self.open_workingtree()
108
        except (errors.NotLocalUrl, errors.NoWorkingTree):
109
            try:
110
                thing_to_unlock = self.open_branch()
111
            except errors.NotBranchError:
112
                try:
113
                    thing_to_unlock = self.open_repository()
114
                except errors.NoRepositoryPresent:
115
                    return
116
        thing_to_unlock.break_lock()
117
1534.5.16 by Robert Collins
Review feedback.
118
    def can_convert_format(self):
119
        """Return true if this bzrdir is one whose format we can convert from."""
1534.5.7 by Robert Collins
Start factoring out the upgrade policy logic.
120
        return True
121
1910.2.12 by Aaron Bentley
Implement knit repo format 2
122
    def check_conversion_target(self, target_format):
123
        target_repo_format = target_format.repository_format
124
        source_repo_format = self._format.repository_format
125
        source_repo_format.check_conversion_target(target_repo_format)
126
1596.2.1 by Robert Collins
Fix BzrDir.open_containing of unsupported branches.
127
    @staticmethod
2323.6.4 by Martin Pool
BzrDir._check_supported now also takes care of recommending upgrades, which
128
    def _check_supported(format, allow_unsupported,
129
        recommend_upgrade=True,
130
        basedir=None):
131
        """Give an error or warning on old formats.
132
133
        :param format: may be any kind of format - workingtree, branch, 
134
        or repository.
135
136
        :param allow_unsupported: If true, allow opening 
137
        formats that are strongly deprecated, and which may 
138
        have limited functionality.
139
140
        :param recommend_upgrade: If true (default), warn
141
        the user through the ui object that they may wish
142
        to upgrade the object.
1534.4.44 by Robert Collins
Make a new BzrDir format that uses a versioned branch format in a branch/ subdirectory.
143
        """
2323.5.19 by Martin Pool
No upgrade recommendation on source when cloning
144
        # TODO: perhaps move this into a base Format class; it's not BzrDir
145
        # specific. mbp 20070323
1534.4.44 by Robert Collins
Make a new BzrDir format that uses a versioned branch format in a branch/ subdirectory.
146
        if not allow_unsupported and not format.is_supported():
1596.2.1 by Robert Collins
Fix BzrDir.open_containing of unsupported branches.
147
            # see open_downlevel to open legacy branches.
1740.5.6 by Martin Pool
Clean up many exception classes.
148
            raise errors.UnsupportedFormatError(format=format)
2323.6.4 by Martin Pool
BzrDir._check_supported now also takes care of recommending upgrades, which
149
        if recommend_upgrade \
150
            and getattr(format, 'upgrade_recommended', False):
151
            ui.ui_factory.recommend_upgrade(
152
                format.get_format_description(),
153
                basedir)
1534.4.44 by Robert Collins
Make a new BzrDir format that uses a versioned branch format in a branch/ subdirectory.
154
2387.1.1 by Robert Collins
Remove the --basis parameter to clone etc. (Robert Collins)
155
    def clone(self, url, revision_id=None, force_new_repo=False):
1534.4.50 by Robert Collins
Got the bzrdir api straightened out, plenty of refactoring to use it pending, but the api is up and running.
156
        """Clone this bzrdir and its contents to url verbatim.
157
2830.1.1 by Ian Clatworthy
bzrdir.py code clean-ups
158
        If url's last component does not exist, it will be created.
1534.4.50 by Robert Collins
Got the bzrdir api straightened out, plenty of refactoring to use it pending, but the api is up and running.
159
160
        if revision_id is not None, then the clone operation may tune
161
            itself to download less data.
1534.6.6 by Robert Collins
Move find_repository to bzrdir, its not quite ideal there but its simpler and until someone chooses to vary the search by branch type its completely sufficient.
162
        :param force_new_repo: Do not use a shared repository for the target 
163
                               even if one is available.
1534.4.50 by Robert Collins
Got the bzrdir api straightened out, plenty of refactoring to use it pending, but the api is up and running.
164
        """
2475.3.1 by John Arbash Meinel
Fix bug #75721. Update the BzrDir api to add clone_on_transport()
165
        return self.clone_on_transport(get_transport(url),
166
                                       revision_id=revision_id,
167
                                       force_new_repo=force_new_repo)
168
169
    def clone_on_transport(self, transport, revision_id=None,
170
                           force_new_repo=False):
171
        """Clone this bzrdir and its contents to transport verbatim.
172
173
        If the target directory does not exist, it will be created.
174
175
        if revision_id is not None, then the clone operation may tune
176
            itself to download less data.
177
        :param force_new_repo: Do not use a shared repository for the target 
178
                               even if one is available.
179
        """
2475.3.3 by John Arbash Meinel
Change calls to try/mkdir('.')/except FileExists to ensure_base()
180
        transport.ensure_base()
2475.3.1 by John Arbash Meinel
Fix bug #75721. Update the BzrDir api to add clone_on_transport()
181
        result = self._format.initialize_on_transport(transport)
1534.4.50 by Robert Collins
Got the bzrdir api straightened out, plenty of refactoring to use it pending, but the api is up and running.
182
        try:
1534.6.6 by Robert Collins
Move find_repository to bzrdir, its not quite ideal there but its simpler and until someone chooses to vary the search by branch type its completely sufficient.
183
            local_repo = self.find_repository()
1534.4.50 by Robert Collins
Got the bzrdir api straightened out, plenty of refactoring to use it pending, but the api is up and running.
184
        except errors.NoRepositoryPresent:
1534.6.6 by Robert Collins
Move find_repository to bzrdir, its not quite ideal there but its simpler and until someone chooses to vary the search by branch type its completely sufficient.
185
            local_repo = None
186
        if local_repo:
187
            # may need to copy content in
188
            if force_new_repo:
1707.1.1 by Robert Collins
Bugfixes to bzrdir.sprout and clone. Sprout was failing to reset the
189
                result_repo = local_repo.clone(
190
                    result,
2387.1.1 by Robert Collins
Remove the --basis parameter to clone etc. (Robert Collins)
191
                    revision_id=revision_id)
1707.1.1 by Robert Collins
Bugfixes to bzrdir.sprout and clone. Sprout was failing to reset the
192
                result_repo.set_make_working_trees(local_repo.make_working_trees())
1534.6.6 by Robert Collins
Move find_repository to bzrdir, its not quite ideal there but its simpler and until someone chooses to vary the search by branch type its completely sufficient.
193
            else:
194
                try:
195
                    result_repo = result.find_repository()
196
                    # fetch content this dir needs.
197
                    result_repo.fetch(local_repo, revision_id=revision_id)
198
                except errors.NoRepositoryPresent:
199
                    # needed to make one anyway.
1707.1.1 by Robert Collins
Bugfixes to bzrdir.sprout and clone. Sprout was failing to reset the
200
                    result_repo = local_repo.clone(
201
                        result,
2387.1.1 by Robert Collins
Remove the --basis parameter to clone etc. (Robert Collins)
202
                        revision_id=revision_id)
1707.1.1 by Robert Collins
Bugfixes to bzrdir.sprout and clone. Sprout was failing to reset the
203
                    result_repo.set_make_working_trees(local_repo.make_working_trees())
1534.6.6 by Robert Collins
Move find_repository to bzrdir, its not quite ideal there but its simpler and until someone chooses to vary the search by branch type its completely sufficient.
204
        # 1 if there is a branch present
205
        #   make sure its content is available in the target repository
206
        #   clone it.
1534.4.50 by Robert Collins
Got the bzrdir api straightened out, plenty of refactoring to use it pending, but the api is up and running.
207
        try:
208
            self.open_branch().clone(result, revision_id=revision_id)
209
        except errors.NotBranchError:
210
            pass
211
        try:
2387.1.1 by Robert Collins
Remove the --basis parameter to clone etc. (Robert Collins)
212
            self.open_workingtree().clone(result)
1508.1.19 by Robert Collins
Give format3 working trees their own last-revision marker.
213
        except (errors.NoWorkingTree, errors.NotLocalUrl):
1534.4.50 by Robert Collins
Got the bzrdir api straightened out, plenty of refactoring to use it pending, but the api is up and running.
214
            pass
215
        return result
216
1685.1.61 by Martin Pool
[broken] Change BzrDir._make_tail to use urlutils.split
217
    # TODO: This should be given a Transport, and should chdir up; otherwise
218
    # this will open a new connection.
1534.4.50 by Robert Collins
Got the bzrdir api straightened out, plenty of refactoring to use it pending, but the api is up and running.
219
    def _make_tail(self, url):
2475.3.3 by John Arbash Meinel
Change calls to try/mkdir('.')/except FileExists to ensure_base()
220
        t = get_transport(url)
221
        t.ensure_base()
2475.3.1 by John Arbash Meinel
Fix bug #75721. Update the BzrDir api to add clone_on_transport()
222
1553.5.71 by Martin Pool
Change branch format 5 to use LockDirs, not transport locks
223
    @classmethod
2476.3.8 by Vincent Ladeuil
Mark transports that need to be instrumented or refactored to check
224
    def create(cls, base, format=None, possible_transports=None):
1534.4.40 by Robert Collins
Add RepositoryFormats and allow bzrdir.open or create _repository to be used.
225
        """Create a new BzrDir at the url 'base'.
1534.4.39 by Robert Collins
Basic BzrDir support.
226
        
2204.4.13 by Aaron Bentley
Update all test cases to avoid set_default_format
227
        :param format: If supplied, the format of branch to create.  If not
228
            supplied, the default is used.
2476.3.8 by Vincent Ladeuil
Mark transports that need to be instrumented or refactored to check
229
        :param possible_transports: If supplied, a list of transports that 
230
            can be reused to share a remote connection.
1534.4.39 by Robert Collins
Basic BzrDir support.
231
        """
1553.5.71 by Martin Pool
Change branch format 5 to use LockDirs, not transport locks
232
        if cls is not BzrDir:
2204.4.13 by Aaron Bentley
Update all test cases to avoid set_default_format
233
            raise AssertionError("BzrDir.create always creates the default"
234
                " format, not one of %r" % cls)
2476.3.8 by Vincent Ladeuil
Mark transports that need to be instrumented or refactored to check
235
        t = get_transport(base, possible_transports)
2475.3.3 by John Arbash Meinel
Change calls to try/mkdir('.')/except FileExists to ensure_base()
236
        t.ensure_base()
2204.4.13 by Aaron Bentley
Update all test cases to avoid set_default_format
237
        if format is None:
238
            format = BzrDirFormat.get_default_format()
2830.1.1 by Ian Clatworthy
bzrdir.py code clean-ups
239
        return format.initialize_on_transport(t)
1534.4.39 by Robert Collins
Basic BzrDir support.
240
1534.4.41 by Robert Collins
Branch now uses BzrDir reasonably sanely.
241
    def create_branch(self):
242
        """Create a branch in this BzrDir.
243
2830.1.1 by Ian Clatworthy
bzrdir.py code clean-ups
244
        The bzrdir's format will control what branch format is created.
1534.4.41 by Robert Collins
Branch now uses BzrDir reasonably sanely.
245
        For more control see BranchFormatXX.create(a_bzrdir).
246
        """
247
        raise NotImplementedError(self.create_branch)
248
2796.2.6 by Aaron Bentley
Implement destroy_branch
249
    def destroy_branch(self):
2796.2.16 by Aaron Bentley
Documentation updates from review
250
        """Destroy the branch in this BzrDir"""
2796.2.6 by Aaron Bentley
Implement destroy_branch
251
        raise NotImplementedError(self.destroy_branch)
252
1534.4.41 by Robert Collins
Branch now uses BzrDir reasonably sanely.
253
    @staticmethod
2204.4.13 by Aaron Bentley
Update all test cases to avoid set_default_format
254
    def create_branch_and_repo(base, force_new_repo=False, format=None):
1534.4.41 by Robert Collins
Branch now uses BzrDir reasonably sanely.
255
        """Create a new BzrDir, Branch and Repository at the url 'base'.
256
2830.1.1 by Ian Clatworthy
bzrdir.py code clean-ups
257
        This will use the current default BzrDirFormat unless one is
258
        specified, and use whatever 
1534.4.41 by Robert Collins
Branch now uses BzrDir reasonably sanely.
259
        repository format that that uses via bzrdir.create_branch and
1534.6.6 by Robert Collins
Move find_repository to bzrdir, its not quite ideal there but its simpler and until someone chooses to vary the search by branch type its completely sufficient.
260
        create_repository. If a shared repository is available that is used
261
        preferentially.
1534.4.41 by Robert Collins
Branch now uses BzrDir reasonably sanely.
262
263
        The created Branch object is returned.
1534.6.6 by Robert Collins
Move find_repository to bzrdir, its not quite ideal there but its simpler and until someone chooses to vary the search by branch type its completely sufficient.
264
265
        :param base: The URL to create the branch at.
266
        :param force_new_repo: If True a new repository is always created.
2830.1.1 by Ian Clatworthy
bzrdir.py code clean-ups
267
        :param format: If supplied, the format of branch to create.  If not
268
            supplied, the default is used.
1534.4.41 by Robert Collins
Branch now uses BzrDir reasonably sanely.
269
        """
2204.4.13 by Aaron Bentley
Update all test cases to avoid set_default_format
270
        bzrdir = BzrDir.create(base, format)
1534.6.11 by Robert Collins
Review feedback.
271
        bzrdir._find_or_create_repository(force_new_repo)
1534.4.41 by Robert Collins
Branch now uses BzrDir reasonably sanely.
272
        return bzrdir.create_branch()
1534.6.11 by Robert Collins
Review feedback.
273
274
    def _find_or_create_repository(self, force_new_repo):
275
        """Create a new repository if needed, returning the repository."""
276
        if force_new_repo:
277
            return self.create_repository()
278
        try:
279
            return self.find_repository()
280
        except errors.NoRepositoryPresent:
281
            return self.create_repository()
2476.3.6 by Vincent Ladeuil
Fix the 'init connects multiple times' in a different way.
282
        
1534.4.40 by Robert Collins
Add RepositoryFormats and allow bzrdir.open or create _repository to be used.
283
    @staticmethod
2476.3.6 by Vincent Ladeuil
Fix the 'init connects multiple times' in a different way.
284
    def create_branch_convenience(base, force_new_repo=False,
285
                                  force_new_tree=None, format=None,
2476.3.11 by Vincent Ladeuil
Cosmetic changes.
286
                                  possible_transports=None):
1534.6.10 by Robert Collins
Finish use of repositories support.
287
        """Create a new BzrDir, Branch and Repository at the url 'base'.
288
289
        This is a convenience function - it will use an existing repository
290
        if possible, can be told explicitly whether to create a working tree or
1534.6.12 by Robert Collins
Typo found by John Meinel.
291
        not.
1534.6.10 by Robert Collins
Finish use of repositories support.
292
2830.1.1 by Ian Clatworthy
bzrdir.py code clean-ups
293
        This will use the current default BzrDirFormat unless one is
294
        specified, and use whatever 
1534.6.10 by Robert Collins
Finish use of repositories support.
295
        repository format that that uses via bzrdir.create_branch and
296
        create_repository. If a shared repository is available that is used
297
        preferentially. Whatever repository is used, its tree creation policy
298
        is followed.
299
300
        The created Branch object is returned.
301
        If a working tree cannot be made due to base not being a file:// url,
1563.1.6 by Robert Collins
Add tests for sftp push, and NonLocalTets for BzrDir.create_branch_convenience, before fixing the failure of it to work on non-local urls.
302
        no error is raised unless force_new_tree is True, in which case no 
303
        data is created on disk and NotLocalUrl is raised.
1534.6.10 by Robert Collins
Finish use of repositories support.
304
305
        :param base: The URL to create the branch at.
306
        :param force_new_repo: If True a new repository is always created.
307
        :param force_new_tree: If True or False force creation of a tree or 
308
                               prevent such creation respectively.
2830.1.1 by Ian Clatworthy
bzrdir.py code clean-ups
309
        :param format: Override for the bzrdir format to create.
2476.3.8 by Vincent Ladeuil
Mark transports that need to be instrumented or refactored to check
310
        :param possible_transports: An optional reusable transports list.
1534.6.10 by Robert Collins
Finish use of repositories support.
311
        """
1563.1.6 by Robert Collins
Add tests for sftp push, and NonLocalTets for BzrDir.create_branch_convenience, before fixing the failure of it to work on non-local urls.
312
        if force_new_tree:
313
            # check for non local urls
2485.8.45 by Vincent Ladeuil
Take jam's remarks into account.
314
            t = get_transport(base, possible_transports)
2476.3.6 by Vincent Ladeuil
Fix the 'init connects multiple times' in a different way.
315
            if not isinstance(t, LocalTransport):
316
                raise errors.NotLocalUrl(base)
2476.3.8 by Vincent Ladeuil
Mark transports that need to be instrumented or refactored to check
317
        bzrdir = BzrDir.create(base, format, possible_transports)
1534.6.11 by Robert Collins
Review feedback.
318
        repo = bzrdir._find_or_create_repository(force_new_repo)
1534.6.10 by Robert Collins
Finish use of repositories support.
319
        result = bzrdir.create_branch()
2476.3.4 by Vincent Ladeuil
Add tests.
320
        if force_new_tree or (repo.make_working_trees() and
1534.6.10 by Robert Collins
Finish use of repositories support.
321
                              force_new_tree is None):
1563.1.6 by Robert Collins
Add tests for sftp push, and NonLocalTets for BzrDir.create_branch_convenience, before fixing the failure of it to work on non-local urls.
322
            try:
323
                bzrdir.create_workingtree()
324
            except errors.NotLocalUrl:
325
                pass
1534.6.10 by Robert Collins
Finish use of repositories support.
326
        return result
2476.3.4 by Vincent Ladeuil
Add tests.
327
1551.8.2 by Aaron Bentley
Add create_checkout_convenience
328
    @staticmethod
2711.2.1 by Martin Pool
Deprecate BzrDir.create_repository
329
    @deprecated_function(zero_ninetyone)
2204.4.13 by Aaron Bentley
Update all test cases to avoid set_default_format
330
    def create_repository(base, shared=False, format=None):
1534.4.40 by Robert Collins
Add RepositoryFormats and allow bzrdir.open or create _repository to be used.
331
        """Create a new BzrDir and Repository at the url 'base'.
332
2204.4.13 by Aaron Bentley
Update all test cases to avoid set_default_format
333
        If no format is supplied, this will default to the current default
334
        BzrDirFormat by default, and use whatever repository format that that
335
        uses for bzrdirformat.create_repository.
1534.4.40 by Robert Collins
Add RepositoryFormats and allow bzrdir.open or create _repository to be used.
336
1910.7.17 by Andrew Bennetts
Various cosmetic changes.
337
        :param shared: Create a shared repository rather than a standalone
1534.6.1 by Robert Collins
allow API creation of shared repositories
338
                       repository.
1534.4.40 by Robert Collins
Add RepositoryFormats and allow bzrdir.open or create _repository to be used.
339
        The Repository object is returned.
340
341
        This must be overridden as an instance method in child classes, where
342
        it should take no parameters and construct whatever repository format
343
        that child class desires.
2711.2.1 by Martin Pool
Deprecate BzrDir.create_repository
344
345
        This method is deprecated, please call create_repository on a bzrdir
346
        instance instead.
1534.4.40 by Robert Collins
Add RepositoryFormats and allow bzrdir.open or create _repository to be used.
347
        """
2204.4.13 by Aaron Bentley
Update all test cases to avoid set_default_format
348
        bzrdir = BzrDir.create(base, format)
1841.2.1 by Jelmer Vernooij
Fix handling of `shared' parameter in BzrDir.create_repository().
349
        return bzrdir.create_repository(shared)
1534.4.40 by Robert Collins
Add RepositoryFormats and allow bzrdir.open or create _repository to be used.
350
1534.4.42 by Robert Collins
add working tree to the BzrDir facilities.
351
    @staticmethod
2204.4.13 by Aaron Bentley
Update all test cases to avoid set_default_format
352
    def create_standalone_workingtree(base, format=None):
1534.4.42 by Robert Collins
add working tree to the BzrDir facilities.
353
        """Create a new BzrDir, WorkingTree, Branch and Repository at 'base'.
354
355
        'base' must be a local path or a file:// url.
356
2830.1.1 by Ian Clatworthy
bzrdir.py code clean-ups
357
        This will use the current default BzrDirFormat unless one is
358
        specified, and use whatever 
1534.4.42 by Robert Collins
add working tree to the BzrDir facilities.
359
        repository format that that uses for bzrdirformat.create_workingtree,
360
        create_branch and create_repository.
361
2830.1.1 by Ian Clatworthy
bzrdir.py code clean-ups
362
        :param format: Override for the bzrdir format to create.
1910.7.17 by Andrew Bennetts
Various cosmetic changes.
363
        :return: The WorkingTree object.
1534.4.42 by Robert Collins
add working tree to the BzrDir facilities.
364
        """
2485.8.45 by Vincent Ladeuil
Take jam's remarks into account.
365
        t = get_transport(base)
1534.4.42 by Robert Collins
add working tree to the BzrDir facilities.
366
        if not isinstance(t, LocalTransport):
367
            raise errors.NotLocalUrl(base)
2485.8.45 by Vincent Ladeuil
Take jam's remarks into account.
368
        bzrdir = BzrDir.create_branch_and_repo(base,
2204.4.13 by Aaron Bentley
Update all test cases to avoid set_default_format
369
                                               force_new_repo=True,
370
                                               format=format).bzrdir
1534.4.42 by Robert Collins
add working tree to the BzrDir facilities.
371
        return bzrdir.create_workingtree()
372
1508.1.21 by Robert Collins
Implement -r limit for checkout command.
373
    def create_workingtree(self, revision_id=None):
374
        """Create a working tree at this BzrDir.
375
        
376
        revision_id: create it as of this revision id.
377
        """
1534.4.42 by Robert Collins
add working tree to the BzrDir facilities.
378
        raise NotImplementedError(self.create_workingtree)
379
2830.1.2 by Ian Clatworthy
Incorporate feedback from poolie's review
380
    def retire_bzrdir(self, limit=10000):
2255.14.1 by Martin Pool
Add BzrDir.retire_bzrdir and partly fix subsume
381
        """Permanently disable the bzrdir.
382
383
        This is done by renaming it to give the user some ability to recover
384
        if there was a problem.
385
386
        This will have horrible consequences if anyone has anything locked or
387
        in use.
2830.1.2 by Ian Clatworthy
Incorporate feedback from poolie's review
388
        :param limit: number of times to retry
2255.14.1 by Martin Pool
Add BzrDir.retire_bzrdir and partly fix subsume
389
        """
2830.1.2 by Ian Clatworthy
Incorporate feedback from poolie's review
390
        i  = 0
391
        while True:
2255.14.1 by Martin Pool
Add BzrDir.retire_bzrdir and partly fix subsume
392
            try:
393
                to_path = '.bzr.retired.%d' % i
394
                self.root_transport.rename('.bzr', to_path)
395
                note("renamed %s to %s"
396
                    % (self.root_transport.abspath('.bzr'), to_path))
2830.1.1 by Ian Clatworthy
bzrdir.py code clean-ups
397
                return
2255.14.1 by Martin Pool
Add BzrDir.retire_bzrdir and partly fix subsume
398
            except (errors.TransportError, IOError, errors.PathError):
2830.1.2 by Ian Clatworthy
Incorporate feedback from poolie's review
399
                i += 1
400
                if i > limit:
401
                    raise
402
                else:
403
                    pass
2255.14.1 by Martin Pool
Add BzrDir.retire_bzrdir and partly fix subsume
404
1551.8.37 by Aaron Bentley
Cleaner implementation of destroy_working_tree
405
    def destroy_workingtree(self):
1551.8.36 by Aaron Bentley
Introduce BzrDir.destroy_workingtree
406
        """Destroy the working tree at this BzrDir.
407
408
        Formats that do not support this may raise UnsupportedOperation.
409
        """
410
        raise NotImplementedError(self.destroy_workingtree)
411
1551.8.37 by Aaron Bentley
Cleaner implementation of destroy_working_tree
412
    def destroy_workingtree_metadata(self):
413
        """Destroy the control files for the working tree at this BzrDir.
414
415
        The contents of working tree files are not affected.
416
        Formats that do not support this may raise UnsupportedOperation.
417
        """
418
        raise NotImplementedError(self.destroy_workingtree_metadata)
419
1534.6.6 by Robert Collins
Move find_repository to bzrdir, its not quite ideal there but its simpler and until someone chooses to vary the search by branch type its completely sufficient.
420
    def find_repository(self):
2830.1.1 by Ian Clatworthy
bzrdir.py code clean-ups
421
        """Find the repository that should be used.
1534.6.6 by Robert Collins
Move find_repository to bzrdir, its not quite ideal there but its simpler and until someone chooses to vary the search by branch type its completely sufficient.
422
423
        This does not require a branch as we use it to find the repo for
424
        new branches as well as to hook existing branches up to their
425
        repository.
426
        """
427
        try:
428
            return self.open_repository()
429
        except errors.NoRepositoryPresent:
430
            pass
431
        next_transport = self.root_transport.clone('..')
432
        while True:
1725.2.5 by Robert Collins
Bugfix create_branch_convenience at the root of a file system to not loop
433
            # find the next containing bzrdir
1534.6.6 by Robert Collins
Move find_repository to bzrdir, its not quite ideal there but its simpler and until someone chooses to vary the search by branch type its completely sufficient.
434
            try:
1534.6.11 by Robert Collins
Review feedback.
435
                found_bzrdir = BzrDir.open_containing_from_transport(
1534.6.6 by Robert Collins
Move find_repository to bzrdir, its not quite ideal there but its simpler and until someone chooses to vary the search by branch type its completely sufficient.
436
                    next_transport)[0]
437
            except errors.NotBranchError:
1725.2.5 by Robert Collins
Bugfix create_branch_convenience at the root of a file system to not loop
438
                # none found
1534.6.6 by Robert Collins
Move find_repository to bzrdir, its not quite ideal there but its simpler and until someone chooses to vary the search by branch type its completely sufficient.
439
                raise errors.NoRepositoryPresent(self)
1725.2.5 by Robert Collins
Bugfix create_branch_convenience at the root of a file system to not loop
440
            # does it have a repository ?
1534.6.6 by Robert Collins
Move find_repository to bzrdir, its not quite ideal there but its simpler and until someone chooses to vary the search by branch type its completely sufficient.
441
            try:
442
                repository = found_bzrdir.open_repository()
443
            except errors.NoRepositoryPresent:
444
                next_transport = found_bzrdir.root_transport.clone('..')
1725.2.5 by Robert Collins
Bugfix create_branch_convenience at the root of a file system to not loop
445
                if (found_bzrdir.root_transport.base == next_transport.base):
446
                    # top of the file system
447
                    break
448
                else:
449
                    continue
2018.6.1 by Robert Collins
Implement a BzrDir.open_branch smart server method for opening a branch without VFS.
450
            if ((found_bzrdir.root_transport.base ==
1534.6.6 by Robert Collins
Move find_repository to bzrdir, its not quite ideal there but its simpler and until someone chooses to vary the search by branch type its completely sufficient.
451
                 self.root_transport.base) or repository.is_shared()):
452
                return repository
453
            else:
454
                raise errors.NoRepositoryPresent(self)
455
        raise errors.NoRepositoryPresent(self)
456
2414.2.1 by Andrew Bennetts
Some miscellaneous new APIs, tests and other changes from the hpss branch.
457
    def get_branch_reference(self):
458
        """Return the referenced URL for the branch in this bzrdir.
459
460
        :raises NotBranchError: If there is no Branch.
461
        :return: The URL the branch in this bzrdir references if it is a
462
            reference branch, or None for regular branches.
463
        """
464
        return None
465
1534.4.44 by Robert Collins
Make a new BzrDir format that uses a versioned branch format in a branch/ subdirectory.
466
    def get_branch_transport(self, branch_format):
467
        """Get the transport for use by branch format in this BzrDir.
468
469
        Note that bzr dirs that do not support format strings will raise
470
        IncompatibleFormat if the branch format they are given has
1759.2.1 by Jelmer Vernooij
Fix some types (found using aspell).
471
        a format string, and vice versa.
1534.4.44 by Robert Collins
Make a new BzrDir format that uses a versioned branch format in a branch/ subdirectory.
472
473
        If branch_format is None, the transport is returned with no 
2830.1.1 by Ian Clatworthy
bzrdir.py code clean-ups
474
        checking. If it is not None, then the returned transport is
1534.4.44 by Robert Collins
Make a new BzrDir format that uses a versioned branch format in a branch/ subdirectory.
475
        guaranteed to point to an existing directory ready for use.
476
        """
477
        raise NotImplementedError(self.get_branch_transport)
478
        
1534.4.47 by Robert Collins
Split out repository into .bzr/repository
479
    def get_repository_transport(self, repository_format):
480
        """Get the transport for use by repository format in this BzrDir.
481
482
        Note that bzr dirs that do not support format strings will raise
483
        IncompatibleFormat if the repository format they are given has
1759.2.1 by Jelmer Vernooij
Fix some types (found using aspell).
484
        a format string, and vice versa.
1534.4.47 by Robert Collins
Split out repository into .bzr/repository
485
486
        If repository_format is None, the transport is returned with no 
2830.1.1 by Ian Clatworthy
bzrdir.py code clean-ups
487
        checking. If it is not None, then the returned transport is
1534.4.47 by Robert Collins
Split out repository into .bzr/repository
488
        guaranteed to point to an existing directory ready for use.
489
        """
490
        raise NotImplementedError(self.get_repository_transport)
491
        
1534.4.53 by Robert Collins
Review feedback from John Meinel.
492
    def get_workingtree_transport(self, tree_format):
1534.4.45 by Robert Collins
Start WorkingTree -> .bzr/checkout transition
493
        """Get the transport for use by workingtree format in this BzrDir.
494
495
        Note that bzr dirs that do not support format strings will raise
2100.3.11 by Aaron Bentley
Add join --reference support
496
        IncompatibleFormat if the workingtree format they are given has a
497
        format string, and vice versa.
1534.4.45 by Robert Collins
Start WorkingTree -> .bzr/checkout transition
498
499
        If workingtree_format is None, the transport is returned with no 
2830.1.1 by Ian Clatworthy
bzrdir.py code clean-ups
500
        checking. If it is not None, then the returned transport is
1534.4.45 by Robert Collins
Start WorkingTree -> .bzr/checkout transition
501
        guaranteed to point to an existing directory ready for use.
502
        """
503
        raise NotImplementedError(self.get_workingtree_transport)
504
        
1534.4.39 by Robert Collins
Basic BzrDir support.
505
    def __init__(self, _transport, _format):
506
        """Initialize a Bzr control dir object.
507
        
508
        Only really common logic should reside here, concrete classes should be
509
        made with varying behaviours.
510
1534.4.53 by Robert Collins
Review feedback from John Meinel.
511
        :param _format: the format that is creating this BzrDir instance.
512
        :param _transport: the transport this dir is based at.
1534.4.39 by Robert Collins
Basic BzrDir support.
513
        """
514
        self._format = _format
1534.4.41 by Robert Collins
Branch now uses BzrDir reasonably sanely.
515
        self.transport = _transport.clone('.bzr')
1534.4.50 by Robert Collins
Got the bzrdir api straightened out, plenty of refactoring to use it pending, but the api is up and running.
516
        self.root_transport = _transport
1534.4.39 by Robert Collins
Basic BzrDir support.
517
1713.1.9 by Robert Collins
Paired performance tuning of bzr add. (Robert Collins, Martin Pool).
518
    def is_control_filename(self, filename):
519
        """True if filename is the name of a path which is reserved for bzrdir's.
520
        
521
        :param filename: A filename within the root transport of this bzrdir.
522
523
        This is true IF and ONLY IF the filename is part of the namespace reserved
524
        for bzr control dirs. Currently this is the '.bzr' directory in the root
525
        of the root_transport. it is expected that plugins will need to extend
526
        this in the future - for instance to make bzr talk with svn working
527
        trees.
528
        """
529
        # this might be better on the BzrDirFormat class because it refers to 
530
        # all the possible bzrdir disk formats. 
531
        # This method is tested via the workingtree is_control_filename tests- 
2830.1.1 by Ian Clatworthy
bzrdir.py code clean-ups
532
        # it was extracted from WorkingTree.is_control_filename. If the method's
533
        # contract is extended beyond the current trivial implementation, please
1713.1.9 by Robert Collins
Paired performance tuning of bzr add. (Robert Collins, Martin Pool).
534
        # add new tests for it to the appropriate place.
535
        return filename == '.bzr' or filename.startswith('.bzr/')
536
1534.5.16 by Robert Collins
Review feedback.
537
    def needs_format_conversion(self, format=None):
538
        """Return true if this bzrdir needs convert_format run on it.
1534.5.7 by Robert Collins
Start factoring out the upgrade policy logic.
539
        
540
        For instance, if the repository format is out of date but the 
541
        branch and working tree are not, this should return True.
1534.5.13 by Robert Collins
Correct buggy test.
542
543
        :param format: Optional parameter indicating a specific desired
1534.5.16 by Robert Collins
Review feedback.
544
                       format we plan to arrive at.
1534.5.7 by Robert Collins
Start factoring out the upgrade policy logic.
545
        """
1556.1.4 by Robert Collins
Add a new format for what will become knit, and the surrounding logic to upgrade repositories within metadirs, and tests for the same.
546
        raise NotImplementedError(self.needs_format_conversion)
1534.5.7 by Robert Collins
Start factoring out the upgrade policy logic.
547
1534.4.39 by Robert Collins
Basic BzrDir support.
548
    @staticmethod
549
    def open_unsupported(base):
550
        """Open a branch which is not supported."""
551
        return BzrDir.open(base, _unsupported=True)
552
        
553
    @staticmethod
2806.2.2 by Vincent Ladeuil
Fix #128076 and #131396 by reusing bound branch transport.
554
    def open(base, _unsupported=False, possible_transports=None):
2830.1.1 by Ian Clatworthy
bzrdir.py code clean-ups
555
        """Open an existing bzrdir, rooted at 'base' (url).
1534.4.39 by Robert Collins
Basic BzrDir support.
556
        
2830.1.1 by Ian Clatworthy
bzrdir.py code clean-ups
557
        :param _unsupported: a private parameter to the BzrDir class.
1534.4.39 by Robert Collins
Basic BzrDir support.
558
        """
2806.2.2 by Vincent Ladeuil
Fix #128076 and #131396 by reusing bound branch transport.
559
        t = get_transport(base, possible_transports=possible_transports)
1910.11.1 by Andrew Bennetts
Add BzrDir.open_from_transport, refactored from duplicate code, no explicit tests.
560
        return BzrDir.open_from_transport(t, _unsupported=_unsupported)
561
562
    @staticmethod
2018.5.169 by Andrew Bennetts
Add a _server_formats flag to BzrDir.open_from_transport and BzrDirFormat.find_format, make RemoteBranch.control_files into a property.
563
    def open_from_transport(transport, _unsupported=False,
564
                            _server_formats=True):
1910.11.1 by Andrew Bennetts
Add BzrDir.open_from_transport, refactored from duplicate code, no explicit tests.
565
        """Open a bzrdir within a particular directory.
566
567
        :param transport: Transport containing the bzrdir.
568
        :param _unsupported: private.
569
        """
2164.2.21 by Vincent Ladeuil
Take bundles into account.
570
        base = transport.base
571
572
        def find_format(transport):
2018.5.169 by Andrew Bennetts
Add a _server_formats flag to BzrDir.open_from_transport and BzrDirFormat.find_format, make RemoteBranch.control_files into a property.
573
            return transport, BzrDirFormat.find_format(
574
                transport, _server_formats=_server_formats)
2164.2.21 by Vincent Ladeuil
Take bundles into account.
575
576
        def redirected(transport, e, redirection_notice):
577
            qualified_source = e.get_source_url()
578
            relpath = transport.relpath(qualified_source)
579
            if not e.target.endswith(relpath):
580
                # Not redirected to a branch-format, not a branch
581
                raise errors.NotBranchError(path=e.target)
582
            target = e.target[:-len(relpath)]
583
            note('%s is%s redirected to %s',
584
                 transport.base, e.permanently, target)
585
            # Let's try with a new transport
2164.2.22 by Vincent Ladeuil
Take Aaron's review comments into account.
586
            # FIXME: If 'transport' has a qualifier, this should
2164.2.21 by Vincent Ladeuil
Take bundles into account.
587
            # be applied again to the new transport *iff* the
2830.1.2 by Ian Clatworthy
Incorporate feedback from poolie's review
588
            # schemes used are the same. Uncomment this code
589
            # once the function (and tests) exist.
2164.2.21 by Vincent Ladeuil
Take bundles into account.
590
            # -- vila20070212
2830.1.2 by Ian Clatworthy
Incorporate feedback from poolie's review
591
            #target = urlutils.copy_url_qualifiers(original, target)
2164.2.21 by Vincent Ladeuil
Take bundles into account.
592
            return get_transport(target)
593
2164.2.22 by Vincent Ladeuil
Take Aaron's review comments into account.
594
        try:
2164.2.28 by Vincent Ladeuil
TestingHTTPServer.test_case_server renamed from test_case to avoid confusions.
595
            transport, format = do_catching_redirections(find_format,
596
                                                         transport,
2164.2.22 by Vincent Ladeuil
Take Aaron's review comments into account.
597
                                                         redirected)
598
        except errors.TooManyRedirections:
599
            raise errors.NotBranchError(base)
2164.2.21 by Vincent Ladeuil
Take bundles into account.
600
1596.2.1 by Robert Collins
Fix BzrDir.open_containing of unsupported branches.
601
        BzrDir._check_supported(format, _unsupported)
1910.11.1 by Andrew Bennetts
Add BzrDir.open_from_transport, refactored from duplicate code, no explicit tests.
602
        return format.open(transport, _found=True)
1534.4.41 by Robert Collins
Branch now uses BzrDir reasonably sanely.
603
1534.4.44 by Robert Collins
Make a new BzrDir format that uses a versioned branch format in a branch/ subdirectory.
604
    def open_branch(self, unsupported=False):
1534.4.41 by Robert Collins
Branch now uses BzrDir reasonably sanely.
605
        """Open the branch object at this BzrDir if one is present.
1534.4.44 by Robert Collins
Make a new BzrDir format that uses a versioned branch format in a branch/ subdirectory.
606
607
        If unsupported is True, then no longer supported branch formats can
608
        still be opened.
1534.4.41 by Robert Collins
Branch now uses BzrDir reasonably sanely.
609
        
610
        TODO: static convenience version of this?
611
        """
612
        raise NotImplementedError(self.open_branch)
1534.4.39 by Robert Collins
Basic BzrDir support.
613
614
    @staticmethod
2485.8.37 by Vincent Ladeuil
Fix merge multiple connections. Test suite *not* passing (sftp
615
    def open_containing(url, possible_transports=None):
1534.4.39 by Robert Collins
Basic BzrDir support.
616
        """Open an existing branch which contains url.
617
        
1534.6.3 by Robert Collins
find_repository sufficiently robust.
618
        :param url: url to search from.
1534.6.11 by Robert Collins
Review feedback.
619
        See open_containing_from_transport for more detail.
1534.6.3 by Robert Collins
find_repository sufficiently robust.
620
        """
2485.8.37 by Vincent Ladeuil
Fix merge multiple connections. Test suite *not* passing (sftp
621
        transport = get_transport(url, possible_transports)
622
        return BzrDir.open_containing_from_transport(transport)
1534.6.3 by Robert Collins
find_repository sufficiently robust.
623
    
624
    @staticmethod
1534.6.11 by Robert Collins
Review feedback.
625
    def open_containing_from_transport(a_transport):
2830.1.1 by Ian Clatworthy
bzrdir.py code clean-ups
626
        """Open an existing branch which contains a_transport.base.
1534.6.3 by Robert Collins
find_repository sufficiently robust.
627
628
        This probes for a branch at a_transport, and searches upwards from there.
1534.4.39 by Robert Collins
Basic BzrDir support.
629
630
        Basically we keep looking up until we find the control directory or
631
        run into the root.  If there isn't one, raises NotBranchError.
632
        If there is one and it is either an unrecognised format or an unsupported 
633
        format, UnknownFormatError or UnsupportedFormatError are raised.
634
        If there is one, it is returned, along with the unused portion of url.
1685.1.27 by John Arbash Meinel
BzrDir works in URLs, but WorkingTree works in unicode paths
635
1685.1.28 by John Arbash Meinel
Changing open_containing to always return a unicode path.
636
        :return: The BzrDir that contains the path, and a Unicode path 
637
                for the rest of the URL.
1534.4.39 by Robert Collins
Basic BzrDir support.
638
        """
639
        # this gets the normalised url back. I.e. '.' -> the full path.
1534.6.3 by Robert Collins
find_repository sufficiently robust.
640
        url = a_transport.base
1534.4.39 by Robert Collins
Basic BzrDir support.
641
        while True:
642
            try:
1910.11.1 by Andrew Bennetts
Add BzrDir.open_from_transport, refactored from duplicate code, no explicit tests.
643
                result = BzrDir.open_from_transport(a_transport)
644
                return result, urlutils.unescape(a_transport.relpath(url))
1534.4.39 by Robert Collins
Basic BzrDir support.
645
            except errors.NotBranchError, e:
1685.1.60 by Martin Pool
[broken] NotBranchError should unescape the url if possible
646
                pass
2018.14.1 by Andrew Bennetts
Update to current hpss branch? Fix lots of test failures.
647
            try:
648
                new_t = a_transport.clone('..')
649
            except errors.InvalidURLJoin:
650
                # reached the root, whatever that may be
651
                raise errors.NotBranchError(path=url)
1534.6.3 by Robert Collins
find_repository sufficiently robust.
652
            if new_t.base == a_transport.base:
1534.4.39 by Robert Collins
Basic BzrDir support.
653
                # reached the root, whatever that may be
654
                raise errors.NotBranchError(path=url)
1534.6.3 by Robert Collins
find_repository sufficiently robust.
655
            a_transport = new_t
1534.4.39 by Robert Collins
Basic BzrDir support.
656
2215.3.2 by Aaron Bentley
Add open_containing_tree_or_branch
657
    @classmethod
658
    def open_containing_tree_or_branch(klass, location):
659
        """Return the branch and working tree contained by a location.
660
661
        Returns (tree, branch, relpath).
662
        If there is no tree at containing the location, tree will be None.
663
        If there is no branch containing the location, an exception will be
664
        raised
665
        relpath is the portion of the path that is contained by the branch.
666
        """
667
        bzrdir, relpath = klass.open_containing(location)
668
        try:
669
            tree = bzrdir.open_workingtree()
2215.3.5 by Aaron Bentley
Add support for remote ls
670
        except (errors.NoWorkingTree, errors.NotLocalUrl):
2215.3.2 by Aaron Bentley
Add open_containing_tree_or_branch
671
            tree = None
672
            branch = bzrdir.open_branch()
673
        else:
674
            branch = tree.branch
675
        return tree, branch, relpath
676
1534.4.47 by Robert Collins
Split out repository into .bzr/repository
677
    def open_repository(self, _unsupported=False):
1534.4.40 by Robert Collins
Add RepositoryFormats and allow bzrdir.open or create _repository to be used.
678
        """Open the repository object at this BzrDir if one is present.
1534.4.47 by Robert Collins
Split out repository into .bzr/repository
679
2830.1.1 by Ian Clatworthy
bzrdir.py code clean-ups
680
        This will not follow the Branch object pointer - it's strictly a direct
1534.4.47 by Robert Collins
Split out repository into .bzr/repository
681
        open facility. Most client code should use open_branch().repository to
682
        get at a repository.
683
2830.1.1 by Ian Clatworthy
bzrdir.py code clean-ups
684
        :param _unsupported: a private parameter, not part of the api.
1534.4.40 by Robert Collins
Add RepositoryFormats and allow bzrdir.open or create _repository to be used.
685
        TODO: static convenience version of this?
686
        """
687
        raise NotImplementedError(self.open_repository)
688
2400.2.2 by Robert Collins
Document BzrDir.open_workingtree's new recommend_upgrade parameter.
689
    def open_workingtree(self, _unsupported=False,
690
            recommend_upgrade=True):
1534.4.42 by Robert Collins
add working tree to the BzrDir facilities.
691
        """Open the workingtree object at this BzrDir if one is present.
2400.2.2 by Robert Collins
Document BzrDir.open_workingtree's new recommend_upgrade parameter.
692
693
        :param recommend_upgrade: Optional keyword parameter, when True (the
694
            default), emit through the ui module a recommendation that the user
695
            upgrade the working tree when the workingtree being opened is old
696
            (but still fully supported).
1534.4.42 by Robert Collins
add working tree to the BzrDir facilities.
697
        """
698
        raise NotImplementedError(self.open_workingtree)
699
1662.1.19 by Martin Pool
Better error message when initting existing tree
700
    def has_branch(self):
701
        """Tell if this bzrdir contains a branch.
702
        
703
        Note: if you're going to open the branch, you should just go ahead
704
        and try, and not ask permission first.  (This method just opens the 
705
        branch and discards it, and that's somewhat expensive.) 
706
        """
707
        try:
708
            self.open_branch()
709
            return True
710
        except errors.NotBranchError:
711
            return False
712
713
    def has_workingtree(self):
714
        """Tell if this bzrdir contains a working tree.
715
716
        This will still raise an exception if the bzrdir has a workingtree that
717
        is remote & inaccessible.
718
        
719
        Note: if you're going to open the working tree, you should just go ahead
720
        and try, and not ask permission first.  (This method just opens the 
721
        workingtree and discards it, and that's somewhat expensive.) 
722
        """
723
        try:
2323.6.4 by Martin Pool
BzrDir._check_supported now also takes care of recommending upgrades, which
724
            self.open_workingtree(recommend_upgrade=False)
1662.1.19 by Martin Pool
Better error message when initting existing tree
725
            return True
726
        except errors.NoWorkingTree:
727
            return False
728
2018.5.96 by Andrew Bennetts
Merge from bzr.dev, resolving the worst of the semantic conflicts, but there's
729
    def _cloning_metadir(self):
2830.1.1 by Ian Clatworthy
bzrdir.py code clean-ups
730
        """Produce a metadir suitable for cloning with."""
2387.1.1 by Robert Collins
Remove the --basis parameter to clone etc. (Robert Collins)
731
        result_format = self._format.__class__()
732
        try:
1910.2.41 by Aaron Bentley
Clean up clone format creation
733
            try:
2387.1.1 by Robert Collins
Remove the --basis parameter to clone etc. (Robert Collins)
734
                branch = self.open_branch()
735
                source_repository = branch.repository
1910.2.41 by Aaron Bentley
Clean up clone format creation
736
            except errors.NotBranchError:
737
                source_branch = None
2387.1.1 by Robert Collins
Remove the --basis parameter to clone etc. (Robert Collins)
738
                source_repository = self.open_repository()
2305.3.1 by Andrew Bennetts
Tidy up BzrDir.cloning_metadir: bogus try/except, and basis argument isn't actually used.
739
        except errors.NoRepositoryPresent:
2100.3.24 by Aaron Bentley
Get all tests passing again
740
            source_repository = None
2305.3.1 by Andrew Bennetts
Tidy up BzrDir.cloning_metadir: bogus try/except, and basis argument isn't actually used.
741
        else:
2018.5.138 by Robert Collins
Merge bzr.dev.
742
            # XXX TODO: This isinstance is here because we have not implemented
743
            # the fix recommended in bug # 103195 - to delegate this choice the
744
            # repository itself.
2018.5.94 by Andrew Bennetts
Various small changes in aid of making tests pass (including deleting one invalid test).
745
            repo_format = source_repository._format
746
            if not isinstance(repo_format, remote.RemoteRepositoryFormat):
747
                result_format.repository_format = repo_format
2100.3.28 by Aaron Bentley
Make sprout recursive
748
        try:
2323.5.19 by Martin Pool
No upgrade recommendation on source when cloning
749
            # TODO: Couldn't we just probe for the format in these cases,
750
            # rather than opening the whole tree?  It would be a little
751
            # faster. mbp 20070401
752
            tree = self.open_workingtree(recommend_upgrade=False)
2100.3.28 by Aaron Bentley
Make sprout recursive
753
        except (errors.NoWorkingTree, errors.NotLocalUrl):
754
            result_format.workingtree_format = None
755
        else:
756
            result_format.workingtree_format = tree._format.__class__()
2100.3.21 by Aaron Bentley
Work on checking out by-reference trees
757
        return result_format, source_repository
758
2018.5.96 by Andrew Bennetts
Merge from bzr.dev, resolving the worst of the semantic conflicts, but there's
759
    def cloning_metadir(self):
2100.3.32 by Aaron Bentley
fix tree format, basis_tree call, in sprout
760
        """Produce a metadir suitable for cloning or sprouting with.
1910.2.41 by Aaron Bentley
Clean up clone format creation
761
2100.3.32 by Aaron Bentley
fix tree format, basis_tree call, in sprout
762
        These operations may produce workingtrees (yes, even though they're
2830.1.1 by Ian Clatworthy
bzrdir.py code clean-ups
763
        "cloning" something that doesn't have a tree), so a viable workingtree
2100.3.32 by Aaron Bentley
fix tree format, basis_tree call, in sprout
764
        format must be selected.
765
        """
2100.3.21 by Aaron Bentley
Work on checking out by-reference trees
766
        format, repository = self._cloning_metadir()
2100.3.32 by Aaron Bentley
fix tree format, basis_tree call, in sprout
767
        if format._workingtree_format is None:
2100.3.34 by Aaron Bentley
Fix BzrDir.cloning_metadir with no format
768
            if repository is None:
769
                return format
2100.3.21 by Aaron Bentley
Work on checking out by-reference trees
770
            tree_format = repository._format._matchingbzrdir.workingtree_format
2100.3.28 by Aaron Bentley
Make sprout recursive
771
            format.workingtree_format = tree_format.__class__()
2100.3.21 by Aaron Bentley
Work on checking out by-reference trees
772
        return format
773
2100.3.32 by Aaron Bentley
fix tree format, basis_tree call, in sprout
774
    def checkout_metadir(self):
775
        return self.cloning_metadir()
776
2387.1.1 by Robert Collins
Remove the --basis parameter to clone etc. (Robert Collins)
777
    def sprout(self, url, revision_id=None, force_new_repo=False,
2485.8.56 by Vincent Ladeuil
Fix bug #112173 and bzr branch multiple connections.
778
               recurse='down', possible_transports=None):
1534.4.50 by Robert Collins
Got the bzrdir api straightened out, plenty of refactoring to use it pending, but the api is up and running.
779
        """Create a copy of this bzrdir prepared for use as a new line of
780
        development.
781
2830.1.1 by Ian Clatworthy
bzrdir.py code clean-ups
782
        If url's last component does not exist, it will be created.
1534.4.50 by Robert Collins
Got the bzrdir api straightened out, plenty of refactoring to use it pending, but the api is up and running.
783
784
        Attributes related to the identity of the source branch like
785
        branch nickname will be cleaned, a working tree is created
786
        whether one existed before or not; and a local branch is always
787
        created.
788
789
        if revision_id is not None, then the clone operation may tune
790
            itself to download less data.
791
        """
2485.8.56 by Vincent Ladeuil
Fix bug #112173 and bzr branch multiple connections.
792
        target_transport = get_transport(url, possible_transports)
2475.3.3 by John Arbash Meinel
Change calls to try/mkdir('.')/except FileExists to ensure_base()
793
        target_transport.ensure_base()
2305.3.1 by Andrew Bennetts
Tidy up BzrDir.cloning_metadir: bogus try/except, and basis argument isn't actually used.
794
        cloning_format = self.cloning_metadir()
2475.3.1 by John Arbash Meinel
Fix bug #75721. Update the BzrDir api to add clone_on_transport()
795
        result = cloning_format.initialize_on_transport(target_transport)
1534.4.50 by Robert Collins
Got the bzrdir api straightened out, plenty of refactoring to use it pending, but the api is up and running.
796
        try:
797
            source_branch = self.open_branch()
798
            source_repository = source_branch.repository
799
        except errors.NotBranchError:
800
            source_branch = None
801
            try:
802
                source_repository = self.open_repository()
803
            except errors.NoRepositoryPresent:
2387.1.1 by Robert Collins
Remove the --basis parameter to clone etc. (Robert Collins)
804
                source_repository = None
1534.6.9 by Robert Collins
sprouting into shared repositories
805
        if force_new_repo:
806
            result_repo = None
807
        else:
808
            try:
809
                result_repo = result.find_repository()
810
            except errors.NoRepositoryPresent:
811
                result_repo = None
812
        if source_repository is None and result_repo is not None:
813
            pass
814
        elif source_repository is None and result_repo is None:
815
            # no repo available, make a new one
816
            result.create_repository()
817
        elif source_repository is not None and result_repo is None:
1707.1.1 by Robert Collins
Bugfixes to bzrdir.sprout and clone. Sprout was failing to reset the
818
            # have source, and want to make a new target repo
2485.8.56 by Vincent Ladeuil
Fix bug #112173 and bzr branch multiple connections.
819
            result_repo = source_repository.sprout(result,
820
                                                   revision_id=revision_id)
2440.1.1 by Martin Pool
Add new Repository.sprout,
821
        else:
1534.6.9 by Robert Collins
sprouting into shared repositories
822
            # fetch needed content into target.
1910.4.10 by Andrew Bennetts
Skip various test_sprout* tests when sprouting to non-local bzrdirs that can't have working trees; plus fix a test method naming clash and the bug it revealed in bzrdir.sprout.
823
            if source_repository is not None:
2018.18.20 by Martin Pool
Route branch operations through remote copy_content_into
824
                # would rather do 
2485.8.56 by Vincent Ladeuil
Fix bug #112173 and bzr branch multiple connections.
825
                # source_repository.copy_content_into(result_repo,
826
                #                                     revision_id=revision_id)
2018.18.20 by Martin Pool
Route branch operations through remote copy_content_into
827
                # so we can override the copy method
1910.4.10 by Andrew Bennetts
Skip various test_sprout* tests when sprouting to non-local bzrdirs that can't have working trees; plus fix a test method naming clash and the bug it revealed in bzrdir.sprout.
828
                result_repo.fetch(source_repository, revision_id=revision_id)
1534.4.50 by Robert Collins
Got the bzrdir api straightened out, plenty of refactoring to use it pending, but the api is up and running.
829
        if source_branch is not None:
830
            source_branch.sprout(result, revision_id=revision_id)
831
        else:
832
            result.create_branch()
2485.8.56 by Vincent Ladeuil
Fix bug #112173 and bzr branch multiple connections.
833
        if isinstance(target_transport, LocalTransport) and (
834
            result_repo is None or result_repo.make_working_trees()):
1731.1.33 by Aaron Bentley
Revert no-special-root changes
835
            wt = result.create_workingtree()
2255.2.77 by Robert Collins
Tune working inventory generation more: walk the blocks, skipping deleted rows.
836
            wt.lock_write()
837
            try:
838
                if wt.path2id('') is None:
839
                    try:
840
                        wt.set_root_id(self.open_workingtree.get_root_id())
841
                    except errors.NoWorkingTree:
842
                        pass
843
            finally:
844
                wt.unlock()
2100.3.28 by Aaron Bentley
Make sprout recursive
845
        else:
846
            wt = None
847
        if recurse == 'down':
848
            if wt is not None:
2255.2.226 by Robert Collins
Get merge_nested finally working: change nested tree iterators to take file_ids, and ensure the right branch is connected to in the merge logic. May not be suitable for shared repositories yet.
849
                basis = wt.basis_tree()
850
                basis.lock_read()
851
                subtrees = basis.iter_references()
2100.3.28 by Aaron Bentley
Make sprout recursive
852
                recurse_branch = wt.branch
853
            elif source_branch is not None:
2255.2.226 by Robert Collins
Get merge_nested finally working: change nested tree iterators to take file_ids, and ensure the right branch is connected to in the merge logic. May not be suitable for shared repositories yet.
854
                basis = source_branch.basis_tree()
855
                basis.lock_read()
856
                subtrees = basis.iter_references()
2100.3.28 by Aaron Bentley
Make sprout recursive
857
                recurse_branch = source_branch
858
            else:
2255.2.226 by Robert Collins
Get merge_nested finally working: change nested tree iterators to take file_ids, and ensure the right branch is connected to in the merge logic. May not be suitable for shared repositories yet.
859
                subtrees = []
860
                basis = None
861
            try:
862
                for path, file_id in subtrees:
863
                    target = urlutils.join(url, urlutils.escape(path))
864
                    sublocation = source_branch.reference_parent(file_id, path)
865
                    sublocation.bzrdir.sprout(target,
866
                        basis.get_reference_revision(file_id, path),
867
                        force_new_repo=force_new_repo, recurse=recurse)
868
            finally:
869
                if basis is not None:
870
                    basis.unlock()
1534.4.50 by Robert Collins
Got the bzrdir api straightened out, plenty of refactoring to use it pending, but the api is up and running.
871
        return result
872
1534.4.40 by Robert Collins
Add RepositoryFormats and allow bzrdir.open or create _repository to be used.
873
1534.4.44 by Robert Collins
Make a new BzrDir format that uses a versioned branch format in a branch/ subdirectory.
874
class BzrDirPreSplitOut(BzrDir):
875
    """A common class for the all-in-one formats."""
876
1534.5.3 by Robert Collins
Make format 4/5/6 branches share a single LockableFiles instance across wt/branch/repository.
877
    def __init__(self, _transport, _format):
878
        """See BzrDir.__init__."""
879
        super(BzrDirPreSplitOut, self).__init__(_transport, _format)
1996.3.3 by John Arbash Meinel
Shave off another 40ms by demand loading branch and bzrdir
880
        assert self._format._lock_class == lockable_files.TransportLock
1553.5.69 by Martin Pool
BzrDirFormat subclasses can now control what kind of overall lock is used.
881
        assert self._format._lock_file_name == 'branch-lock'
1996.3.3 by John Arbash Meinel
Shave off another 40ms by demand loading branch and bzrdir
882
        self._control_files = lockable_files.LockableFiles(
883
                                            self.get_branch_transport(None),
1553.5.69 by Martin Pool
BzrDirFormat subclasses can now control what kind of overall lock is used.
884
                                            self._format._lock_file_name,
885
                                            self._format._lock_class)
1534.5.3 by Robert Collins
Make format 4/5/6 branches share a single LockableFiles instance across wt/branch/repository.
886
1687.1.12 by Robert Collins
Hook in the full break-lock ui.
887
    def break_lock(self):
888
        """Pre-splitout bzrdirs do not suffer from stale locks."""
889
        raise NotImplementedError(self.break_lock)
890
2387.1.1 by Robert Collins
Remove the --basis parameter to clone etc. (Robert Collins)
891
    def clone(self, url, revision_id=None, force_new_repo=False):
1534.4.50 by Robert Collins
Got the bzrdir api straightened out, plenty of refactoring to use it pending, but the api is up and running.
892
        """See BzrDir.clone()."""
893
        from bzrlib.workingtree import WorkingTreeFormat2
894
        self._make_tail(url)
1651.1.6 by Martin Pool
Clean up clone-bzrdir code
895
        result = self._format._initialize_for_clone(url)
2387.1.1 by Robert Collins
Remove the --basis parameter to clone etc. (Robert Collins)
896
        self.open_repository().clone(result, revision_id=revision_id)
1692.7.9 by Martin Pool
Don't create broken standalone branches over sftp (Malone #43064)
897
        from_branch = self.open_branch()
898
        from_branch.clone(result, revision_id=revision_id)
1534.4.50 by Robert Collins
Got the bzrdir api straightened out, plenty of refactoring to use it pending, but the api is up and running.
899
        try:
2387.1.1 by Robert Collins
Remove the --basis parameter to clone etc. (Robert Collins)
900
            self.open_workingtree().clone(result)
1534.4.50 by Robert Collins
Got the bzrdir api straightened out, plenty of refactoring to use it pending, but the api is up and running.
901
        except errors.NotLocalUrl:
902
            # make a new one, this format always has to have one.
1563.2.38 by Robert Collins
make push preserve tree formats.
903
            try:
904
                WorkingTreeFormat2().initialize(result)
905
            except errors.NotLocalUrl:
1692.7.9 by Martin Pool
Don't create broken standalone branches over sftp (Malone #43064)
906
                # but we cannot do it for remote trees.
907
                to_branch = result.open_branch()
908
                WorkingTreeFormat2().stub_initialize_remote(to_branch.control_files)
1534.4.50 by Robert Collins
Got the bzrdir api straightened out, plenty of refactoring to use it pending, but the api is up and running.
909
        return result
910
1534.4.44 by Robert Collins
Make a new BzrDir format that uses a versioned branch format in a branch/ subdirectory.
911
    def create_branch(self):
912
        """See BzrDir.create_branch."""
1534.4.50 by Robert Collins
Got the bzrdir api straightened out, plenty of refactoring to use it pending, but the api is up and running.
913
        return self.open_branch()
914
2796.2.6 by Aaron Bentley
Implement destroy_branch
915
    def destroy_branch(self):
2796.2.16 by Aaron Bentley
Documentation updates from review
916
        """See BzrDir.destroy_branch."""
2796.2.6 by Aaron Bentley
Implement destroy_branch
917
        raise errors.UnsupportedOperation(self.destroy_branch, self)
918
1534.6.1 by Robert Collins
allow API creation of shared repositories
919
    def create_repository(self, shared=False):
1534.4.50 by Robert Collins
Got the bzrdir api straightened out, plenty of refactoring to use it pending, but the api is up and running.
920
        """See BzrDir.create_repository."""
1534.6.1 by Robert Collins
allow API creation of shared repositories
921
        if shared:
922
            raise errors.IncompatibleFormat('shared repository', self._format)
1534.4.50 by Robert Collins
Got the bzrdir api straightened out, plenty of refactoring to use it pending, but the api is up and running.
923
        return self.open_repository()
924
1508.1.21 by Robert Collins
Implement -r limit for checkout command.
925
    def create_workingtree(self, revision_id=None):
1534.4.50 by Robert Collins
Got the bzrdir api straightened out, plenty of refactoring to use it pending, but the api is up and running.
926
        """See BzrDir.create_workingtree."""
1508.1.21 by Robert Collins
Implement -r limit for checkout command.
927
        # this looks buggy but is not -really-
2323.6.4 by Martin Pool
BzrDir._check_supported now also takes care of recommending upgrades, which
928
        # because this format creates the workingtree when the bzrdir is
929
        # created
1508.1.21 by Robert Collins
Implement -r limit for checkout command.
930
        # clone and sprout will have set the revision_id
931
        # and that will have set it for us, its only
932
        # specific uses of create_workingtree in isolation
933
        # that can do wonky stuff here, and that only
934
        # happens for creating checkouts, which cannot be 
935
        # done on this format anyway. So - acceptable wart.
2323.6.4 by Martin Pool
BzrDir._check_supported now also takes care of recommending upgrades, which
936
        result = self.open_workingtree(recommend_upgrade=False)
1508.1.24 by Robert Collins
Add update command for use with checkouts.
937
        if revision_id is not None:
1996.3.12 by John Arbash Meinel
Change how 'revision' is imported to avoid problems later
938
            if revision_id == _mod_revision.NULL_REVISION:
1551.8.20 by Aaron Bentley
Fix BzrDir.create_workingtree for NULL_REVISION
939
                result.set_parent_ids([])
940
            else:
941
                result.set_parent_ids([revision_id])
1508.1.21 by Robert Collins
Implement -r limit for checkout command.
942
        return result
1534.4.44 by Robert Collins
Make a new BzrDir format that uses a versioned branch format in a branch/ subdirectory.
943
1551.8.37 by Aaron Bentley
Cleaner implementation of destroy_working_tree
944
    def destroy_workingtree(self):
1551.8.36 by Aaron Bentley
Introduce BzrDir.destroy_workingtree
945
        """See BzrDir.destroy_workingtree."""
946
        raise errors.UnsupportedOperation(self.destroy_workingtree, self)
947
1551.8.37 by Aaron Bentley
Cleaner implementation of destroy_working_tree
948
    def destroy_workingtree_metadata(self):
949
        """See BzrDir.destroy_workingtree_metadata."""
950
        raise errors.UnsupportedOperation(self.destroy_workingtree_metadata, 
951
                                          self)
952
1534.4.44 by Robert Collins
Make a new BzrDir format that uses a versioned branch format in a branch/ subdirectory.
953
    def get_branch_transport(self, branch_format):
954
        """See BzrDir.get_branch_transport()."""
955
        if branch_format is None:
956
            return self.transport
957
        try:
958
            branch_format.get_format_string()
959
        except NotImplementedError:
960
            return self.transport
961
        raise errors.IncompatibleFormat(branch_format, self._format)
962
1534.4.47 by Robert Collins
Split out repository into .bzr/repository
963
    def get_repository_transport(self, repository_format):
964
        """See BzrDir.get_repository_transport()."""
965
        if repository_format is None:
966
            return self.transport
967
        try:
968
            repository_format.get_format_string()
969
        except NotImplementedError:
970
            return self.transport
971
        raise errors.IncompatibleFormat(repository_format, self._format)
972
1534.4.45 by Robert Collins
Start WorkingTree -> .bzr/checkout transition
973
    def get_workingtree_transport(self, workingtree_format):
974
        """See BzrDir.get_workingtree_transport()."""
975
        if workingtree_format is None:
976
            return self.transport
977
        try:
978
            workingtree_format.get_format_string()
979
        except NotImplementedError:
980
            return self.transport
981
        raise errors.IncompatibleFormat(workingtree_format, self._format)
982
1556.1.4 by Robert Collins
Add a new format for what will become knit, and the surrounding logic to upgrade repositories within metadirs, and tests for the same.
983
    def needs_format_conversion(self, format=None):
984
        """See BzrDir.needs_format_conversion()."""
985
        # if the format is not the same as the system default,
986
        # an upgrade is needed.
987
        if format is None:
988
            format = BzrDirFormat.get_default_format()
989
        return not isinstance(self._format, format.__class__)
990
1534.4.44 by Robert Collins
Make a new BzrDir format that uses a versioned branch format in a branch/ subdirectory.
991
    def open_branch(self, unsupported=False):
992
        """See BzrDir.open_branch."""
993
        from bzrlib.branch import BzrBranchFormat4
994
        format = BzrBranchFormat4()
995
        self._check_supported(format, unsupported)
996
        return format.open(self, _found=True)
997
2485.8.56 by Vincent Ladeuil
Fix bug #112173 and bzr branch multiple connections.
998
    def sprout(self, url, revision_id=None, force_new_repo=False,
999
               possible_transports=None):
1534.4.50 by Robert Collins
Got the bzrdir api straightened out, plenty of refactoring to use it pending, but the api is up and running.
1000
        """See BzrDir.sprout()."""
1001
        from bzrlib.workingtree import WorkingTreeFormat2
1002
        self._make_tail(url)
1651.1.6 by Martin Pool
Clean up clone-bzrdir code
1003
        result = self._format._initialize_for_clone(url)
1534.4.50 by Robert Collins
Got the bzrdir api straightened out, plenty of refactoring to use it pending, but the api is up and running.
1004
        try:
2387.1.1 by Robert Collins
Remove the --basis parameter to clone etc. (Robert Collins)
1005
            self.open_repository().clone(result, revision_id=revision_id)
1534.4.50 by Robert Collins
Got the bzrdir api straightened out, plenty of refactoring to use it pending, but the api is up and running.
1006
        except errors.NoRepositoryPresent:
1007
            pass
1008
        try:
1009
            self.open_branch().sprout(result, revision_id=revision_id)
1010
        except errors.NotBranchError:
1011
            pass
1587.1.5 by Robert Collins
Put bzr branch behaviour back to the 0.7 ignore-working-tree state.
1012
        # we always want a working tree
1013
        WorkingTreeFormat2().initialize(result)
1534.4.50 by Robert Collins
Got the bzrdir api straightened out, plenty of refactoring to use it pending, but the api is up and running.
1014
        return result
1015
1534.4.44 by Robert Collins
Make a new BzrDir format that uses a versioned branch format in a branch/ subdirectory.
1016
1017
class BzrDir4(BzrDirPreSplitOut):
1508.1.25 by Robert Collins
Update per review comments.
1018
    """A .bzr version 4 control object.
1019
    
1020
    This is a deprecated format and may be removed after sept 2006.
1021
    """
1534.4.40 by Robert Collins
Add RepositoryFormats and allow bzrdir.open or create _repository to be used.
1022
1534.6.1 by Robert Collins
allow API creation of shared repositories
1023
    def create_repository(self, shared=False):
1534.4.40 by Robert Collins
Add RepositoryFormats and allow bzrdir.open or create _repository to be used.
1024
        """See BzrDir.create_repository."""
1556.1.4 by Robert Collins
Add a new format for what will become knit, and the surrounding logic to upgrade repositories within metadirs, and tests for the same.
1025
        return self._format.repository_format.initialize(self, shared)
1534.4.40 by Robert Collins
Add RepositoryFormats and allow bzrdir.open or create _repository to be used.
1026
1534.5.16 by Robert Collins
Review feedback.
1027
    def needs_format_conversion(self, format=None):
1028
        """Format 4 dirs are always in need of conversion."""
1534.5.7 by Robert Collins
Start factoring out the upgrade policy logic.
1029
        return True
1030
1534.4.40 by Robert Collins
Add RepositoryFormats and allow bzrdir.open or create _repository to be used.
1031
    def open_repository(self):
1032
        """See BzrDir.open_repository."""
2241.1.4 by Martin Pool
Moved old weave-based repository formats into bzrlib.repofmt.weaverepo.
1033
        from bzrlib.repofmt.weaverepo import RepositoryFormat4
1534.4.40 by Robert Collins
Add RepositoryFormats and allow bzrdir.open or create _repository to be used.
1034
        return RepositoryFormat4().open(self, _found=True)
1035
1036
1534.4.44 by Robert Collins
Make a new BzrDir format that uses a versioned branch format in a branch/ subdirectory.
1037
class BzrDir5(BzrDirPreSplitOut):
1508.1.25 by Robert Collins
Update per review comments.
1038
    """A .bzr version 5 control object.
1039
1040
    This is a deprecated format and may be removed after sept 2006.
1041
    """
1534.4.40 by Robert Collins
Add RepositoryFormats and allow bzrdir.open or create _repository to be used.
1042
1043
    def open_repository(self):
1044
        """See BzrDir.open_repository."""
2241.1.4 by Martin Pool
Moved old weave-based repository formats into bzrlib.repofmt.weaverepo.
1045
        from bzrlib.repofmt.weaverepo import RepositoryFormat5
1534.4.40 by Robert Collins
Add RepositoryFormats and allow bzrdir.open or create _repository to be used.
1046
        return RepositoryFormat5().open(self, _found=True)
1047
2323.6.4 by Martin Pool
BzrDir._check_supported now also takes care of recommending upgrades, which
1048
    def open_workingtree(self, _unsupported=False,
1049
            recommend_upgrade=True):
1534.4.42 by Robert Collins
add working tree to the BzrDir facilities.
1050
        """See BzrDir.create_workingtree."""
1051
        from bzrlib.workingtree import WorkingTreeFormat2
2323.6.4 by Martin Pool
BzrDir._check_supported now also takes care of recommending upgrades, which
1052
        wt_format = WorkingTreeFormat2()
1053
        # we don't warn here about upgrades; that ought to be handled for the
1054
        # bzrdir as a whole
1055
        return wt_format.open(self, _found=True)
1534.4.42 by Robert Collins
add working tree to the BzrDir facilities.
1056
1534.4.40 by Robert Collins
Add RepositoryFormats and allow bzrdir.open or create _repository to be used.
1057
1534.4.44 by Robert Collins
Make a new BzrDir format that uses a versioned branch format in a branch/ subdirectory.
1058
class BzrDir6(BzrDirPreSplitOut):
1508.1.25 by Robert Collins
Update per review comments.
1059
    """A .bzr version 6 control object.
1060
1061
    This is a deprecated format and may be removed after sept 2006.
1062
    """
1534.4.40 by Robert Collins
Add RepositoryFormats and allow bzrdir.open or create _repository to be used.
1063
1534.4.44 by Robert Collins
Make a new BzrDir format that uses a versioned branch format in a branch/ subdirectory.
1064
    def open_repository(self):
1065
        """See BzrDir.open_repository."""
2241.1.4 by Martin Pool
Moved old weave-based repository formats into bzrlib.repofmt.weaverepo.
1066
        from bzrlib.repofmt.weaverepo import RepositoryFormat6
1534.4.44 by Robert Collins
Make a new BzrDir format that uses a versioned branch format in a branch/ subdirectory.
1067
        return RepositoryFormat6().open(self, _found=True)
1068
2323.6.4 by Martin Pool
BzrDir._check_supported now also takes care of recommending upgrades, which
1069
    def open_workingtree(self, _unsupported=False,
1070
        recommend_upgrade=True):
1534.4.44 by Robert Collins
Make a new BzrDir format that uses a versioned branch format in a branch/ subdirectory.
1071
        """See BzrDir.create_workingtree."""
2323.6.4 by Martin Pool
BzrDir._check_supported now also takes care of recommending upgrades, which
1072
        # we don't warn here about upgrades; that ought to be handled for the
1073
        # bzrdir as a whole
1534.4.44 by Robert Collins
Make a new BzrDir format that uses a versioned branch format in a branch/ subdirectory.
1074
        from bzrlib.workingtree import WorkingTreeFormat2
1075
        return WorkingTreeFormat2().open(self, _found=True)
1076
1077
1078
class BzrDirMeta1(BzrDir):
1079
    """A .bzr meta version 1 control object.
1080
    
1081
    This is the first control object where the 
1553.5.67 by Martin Pool
doc
1082
    individual aspects are really split out: there are separate repository,
1083
    workingtree and branch subdirectories and any subset of the three can be
1084
    present within a BzrDir.
1534.4.44 by Robert Collins
Make a new BzrDir format that uses a versioned branch format in a branch/ subdirectory.
1085
    """
1086
1534.5.16 by Robert Collins
Review feedback.
1087
    def can_convert_format(self):
1088
        """See BzrDir.can_convert_format()."""
1556.1.4 by Robert Collins
Add a new format for what will become knit, and the surrounding logic to upgrade repositories within metadirs, and tests for the same.
1089
        return True
1534.5.10 by Robert Collins
Make upgrade driver unaware of the specific formats in play.
1090
1534.4.41 by Robert Collins
Branch now uses BzrDir reasonably sanely.
1091
    def create_branch(self):
1092
        """See BzrDir.create_branch."""
2230.3.55 by Aaron Bentley
Updates from review
1093
        return self._format.get_branch_format().initialize(self)
1534.4.41 by Robert Collins
Branch now uses BzrDir reasonably sanely.
1094
2796.2.6 by Aaron Bentley
Implement destroy_branch
1095
    def destroy_branch(self):
1096
        """See BzrDir.create_branch."""
1097
        self.transport.delete_tree('branch')
1098
1534.6.1 by Robert Collins
allow API creation of shared repositories
1099
    def create_repository(self, shared=False):
1534.4.40 by Robert Collins
Add RepositoryFormats and allow bzrdir.open or create _repository to be used.
1100
        """See BzrDir.create_repository."""
1556.1.4 by Robert Collins
Add a new format for what will become knit, and the surrounding logic to upgrade repositories within metadirs, and tests for the same.
1101
        return self._format.repository_format.initialize(self, shared)
1534.4.40 by Robert Collins
Add RepositoryFormats and allow bzrdir.open or create _repository to be used.
1102
1508.1.21 by Robert Collins
Implement -r limit for checkout command.
1103
    def create_workingtree(self, revision_id=None):
1534.4.42 by Robert Collins
add working tree to the BzrDir facilities.
1104
        """See BzrDir.create_workingtree."""
1534.4.46 by Robert Collins
Nearly complete .bzr/checkout splitout.
1105
        from bzrlib.workingtree import WorkingTreeFormat
2100.3.10 by Aaron Bentley
Ensure added references are serialized properly, beef up Workingtreee3
1106
        return self._format.workingtree_format.initialize(self, revision_id)
1534.4.42 by Robert Collins
add working tree to the BzrDir facilities.
1107
1551.8.37 by Aaron Bentley
Cleaner implementation of destroy_working_tree
1108
    def destroy_workingtree(self):
1551.8.36 by Aaron Bentley
Introduce BzrDir.destroy_workingtree
1109
        """See BzrDir.destroy_workingtree."""
2323.6.4 by Martin Pool
BzrDir._check_supported now also takes care of recommending upgrades, which
1110
        wt = self.open_workingtree(recommend_upgrade=False)
1551.8.37 by Aaron Bentley
Cleaner implementation of destroy_working_tree
1111
        repository = wt.branch.repository
2094.3.5 by John Arbash Meinel
Fix imports to ensure modules are loaded before they are used
1112
        empty = repository.revision_tree(_mod_revision.NULL_REVISION)
2748.3.2 by Aaron Bentley
Fix revert, remove-tree, and various tests to use None for 'no files specified'
1113
        wt.revert(old_tree=empty)
1551.8.37 by Aaron Bentley
Cleaner implementation of destroy_working_tree
1114
        self.destroy_workingtree_metadata()
1115
1116
    def destroy_workingtree_metadata(self):
1117
        self.transport.delete_tree('checkout')
1551.8.36 by Aaron Bentley
Introduce BzrDir.destroy_workingtree
1118
2414.2.1 by Andrew Bennetts
Some miscellaneous new APIs, tests and other changes from the hpss branch.
1119
    def find_branch_format(self):
1120
        """Find the branch 'format' for this bzrdir.
1121
1122
        This might be a synthetic object for e.g. RemoteBranch and SVN.
1123
        """
1124
        from bzrlib.branch import BranchFormat
1125
        return BranchFormat.find_format(self)
1126
1666.1.4 by Robert Collins
* 'Metadir' is now the default disk format. This improves behaviour in
1127
    def _get_mkdir_mode(self):
1128
        """Figure out the mode to use when creating a bzrdir subdir."""
1996.3.3 by John Arbash Meinel
Shave off another 40ms by demand loading branch and bzrdir
1129
        temp_control = lockable_files.LockableFiles(self.transport, '',
1130
                                     lockable_files.TransportLock)
1666.1.4 by Robert Collins
* 'Metadir' is now the default disk format. This improves behaviour in
1131
        return temp_control._dir_mode
1132
2414.2.1 by Andrew Bennetts
Some miscellaneous new APIs, tests and other changes from the hpss branch.
1133
    def get_branch_reference(self):
1134
        """See BzrDir.get_branch_reference()."""
1135
        from bzrlib.branch import BranchFormat
1136
        format = BranchFormat.find_format(self)
1137
        return format.get_reference(self)
1138
1534.4.44 by Robert Collins
Make a new BzrDir format that uses a versioned branch format in a branch/ subdirectory.
1139
    def get_branch_transport(self, branch_format):
1140
        """See BzrDir.get_branch_transport()."""
1141
        if branch_format is None:
1142
            return self.transport.clone('branch')
1143
        try:
1144
            branch_format.get_format_string()
1145
        except NotImplementedError:
1146
            raise errors.IncompatibleFormat(branch_format, self._format)
1147
        try:
1666.1.4 by Robert Collins
* 'Metadir' is now the default disk format. This improves behaviour in
1148
            self.transport.mkdir('branch', mode=self._get_mkdir_mode())
1534.4.44 by Robert Collins
Make a new BzrDir format that uses a versioned branch format in a branch/ subdirectory.
1149
        except errors.FileExists:
1150
            pass
1151
        return self.transport.clone('branch')
1152
1534.4.47 by Robert Collins
Split out repository into .bzr/repository
1153
    def get_repository_transport(self, repository_format):
1154
        """See BzrDir.get_repository_transport()."""
1155
        if repository_format is None:
1156
            return self.transport.clone('repository')
1157
        try:
1158
            repository_format.get_format_string()
1159
        except NotImplementedError:
1160
            raise errors.IncompatibleFormat(repository_format, self._format)
1161
        try:
1666.1.4 by Robert Collins
* 'Metadir' is now the default disk format. This improves behaviour in
1162
            self.transport.mkdir('repository', mode=self._get_mkdir_mode())
1534.4.47 by Robert Collins
Split out repository into .bzr/repository
1163
        except errors.FileExists:
1164
            pass
1165
        return self.transport.clone('repository')
1166
1534.4.45 by Robert Collins
Start WorkingTree -> .bzr/checkout transition
1167
    def get_workingtree_transport(self, workingtree_format):
1168
        """See BzrDir.get_workingtree_transport()."""
1169
        if workingtree_format is None:
1170
            return self.transport.clone('checkout')
1171
        try:
1172
            workingtree_format.get_format_string()
1173
        except NotImplementedError:
1174
            raise errors.IncompatibleFormat(workingtree_format, self._format)
1175
        try:
1666.1.4 by Robert Collins
* 'Metadir' is now the default disk format. This improves behaviour in
1176
            self.transport.mkdir('checkout', mode=self._get_mkdir_mode())
1534.4.45 by Robert Collins
Start WorkingTree -> .bzr/checkout transition
1177
        except errors.FileExists:
1178
            pass
1179
        return self.transport.clone('checkout')
1180
1534.5.16 by Robert Collins
Review feedback.
1181
    def needs_format_conversion(self, format=None):
1182
        """See BzrDir.needs_format_conversion()."""
1556.1.4 by Robert Collins
Add a new format for what will become knit, and the surrounding logic to upgrade repositories within metadirs, and tests for the same.
1183
        if format is None:
1184
            format = BzrDirFormat.get_default_format()
1185
        if not isinstance(self._format, format.__class__):
1186
            # it is not a meta dir format, conversion is needed.
1187
            return True
1188
        # we might want to push this down to the repository?
1189
        try:
1190
            if not isinstance(self.open_repository()._format,
1191
                              format.repository_format.__class__):
1192
                # the repository needs an upgrade.
1193
                return True
1194
        except errors.NoRepositoryPresent:
1195
            pass
2230.3.29 by Aaron Bentley
Implement conversion to branch 6
1196
        try:
1197
            if not isinstance(self.open_branch()._format,
2230.3.55 by Aaron Bentley
Updates from review
1198
                              format.get_branch_format().__class__):
2255.12.1 by Robert Collins
Implement upgrade for working trees.
1199
                # the branch needs an upgrade.
1200
                return True
1201
        except errors.NotBranchError:
1202
            pass
1203
        try:
2323.6.4 by Martin Pool
BzrDir._check_supported now also takes care of recommending upgrades, which
1204
            my_wt = self.open_workingtree(recommend_upgrade=False)
1205
            if not isinstance(my_wt._format,
2255.12.1 by Robert Collins
Implement upgrade for working trees.
1206
                              format.workingtree_format.__class__):
1207
                # the workingtree needs an upgrade.
1208
                return True
2255.2.196 by Robert Collins
Fix test_upgrade defects related to non local or absent working trees.
1209
        except (errors.NoWorkingTree, errors.NotLocalUrl):
2255.12.1 by Robert Collins
Implement upgrade for working trees.
1210
            pass
1534.5.10 by Robert Collins
Make upgrade driver unaware of the specific formats in play.
1211
        return False
1212
1534.4.44 by Robert Collins
Make a new BzrDir format that uses a versioned branch format in a branch/ subdirectory.
1213
    def open_branch(self, unsupported=False):
1534.4.41 by Robert Collins
Branch now uses BzrDir reasonably sanely.
1214
        """See BzrDir.open_branch."""
2414.2.1 by Andrew Bennetts
Some miscellaneous new APIs, tests and other changes from the hpss branch.
1215
        format = self.find_branch_format()
1534.4.44 by Robert Collins
Make a new BzrDir format that uses a versioned branch format in a branch/ subdirectory.
1216
        self._check_supported(format, unsupported)
1217
        return format.open(self, _found=True)
1534.4.41 by Robert Collins
Branch now uses BzrDir reasonably sanely.
1218
1534.4.47 by Robert Collins
Split out repository into .bzr/repository
1219
    def open_repository(self, unsupported=False):
1534.4.40 by Robert Collins
Add RepositoryFormats and allow bzrdir.open or create _repository to be used.
1220
        """See BzrDir.open_repository."""
1534.4.47 by Robert Collins
Split out repository into .bzr/repository
1221
        from bzrlib.repository import RepositoryFormat
1222
        format = RepositoryFormat.find_format(self)
1223
        self._check_supported(format, unsupported)
1224
        return format.open(self, _found=True)
1534.4.40 by Robert Collins
Add RepositoryFormats and allow bzrdir.open or create _repository to be used.
1225
2323.6.4 by Martin Pool
BzrDir._check_supported now also takes care of recommending upgrades, which
1226
    def open_workingtree(self, unsupported=False,
1227
            recommend_upgrade=True):
1508.1.21 by Robert Collins
Implement -r limit for checkout command.
1228
        """See BzrDir.open_workingtree."""
1534.4.46 by Robert Collins
Nearly complete .bzr/checkout splitout.
1229
        from bzrlib.workingtree import WorkingTreeFormat
1230
        format = WorkingTreeFormat.find_format(self)
2323.6.4 by Martin Pool
BzrDir._check_supported now also takes care of recommending upgrades, which
1231
        self._check_supported(format, unsupported,
1232
            recommend_upgrade,
2323.6.5 by Martin Pool
Recommended-upgrade message should give base dir not the control dir url
1233
            basedir=self.root_transport.base)
1534.4.46 by Robert Collins
Nearly complete .bzr/checkout splitout.
1234
        return format.open(self, _found=True)
1534.4.42 by Robert Collins
add working tree to the BzrDir facilities.
1235
1534.4.39 by Robert Collins
Basic BzrDir support.
1236
1237
class BzrDirFormat(object):
1238
    """An encapsulation of the initialization and open routines for a format.
1239
1240
    Formats provide three things:
1241
     * An initialization routine,
1242
     * a format string,
1243
     * an open routine.
1244
2830.1.1 by Ian Clatworthy
bzrdir.py code clean-ups
1245
    Formats are placed in a dict by their format string for reference 
1534.4.39 by Robert Collins
Basic BzrDir support.
1246
    during bzrdir opening. These should be subclasses of BzrDirFormat
1247
    for consistency.
1248
1249
    Once a format is deprecated, just deprecate the initialize and open
1250
    methods on the format class. Do not deprecate the object, as the 
1251
    object will be created every system load.
1252
    """
1253
1254
    _default_format = None
1534.4.40 by Robert Collins
Add RepositoryFormats and allow bzrdir.open or create _repository to be used.
1255
    """The default format used for new .bzr dirs."""
1534.4.39 by Robert Collins
Basic BzrDir support.
1256
1257
    _formats = {}
1258
    """The known formats."""
1259
1733.1.7 by Jelmer Vernooij
Change set of control dir formats to list.
1260
    _control_formats = []
1733.1.6 by Jelmer Vernooij
Fix a couple of minor issues after review by Martin.
1261
    """The registered control formats - .bzr, ....
1262
    
1733.1.7 by Jelmer Vernooij
Change set of control dir formats to list.
1263
    This is a list of BzrDirFormat objects.
1733.1.6 by Jelmer Vernooij
Fix a couple of minor issues after review by Martin.
1264
    """
1733.1.1 by Robert Collins
Support non '.bzr' control directories in bzrdir.
1265
2018.5.169 by Andrew Bennetts
Add a _server_formats flag to BzrDir.open_from_transport and BzrDirFormat.find_format, make RemoteBranch.control_files into a property.
1266
    _control_server_formats = []
1267
    """The registered control server formats, e.g. RemoteBzrDirs.
1268
1269
    This is a list of BzrDirFormat objects.
1270
    """
1271
1553.5.69 by Martin Pool
BzrDirFormat subclasses can now control what kind of overall lock is used.
1272
    _lock_file_name = 'branch-lock'
1273
1274
    # _lock_class must be set in subclasses to the lock type, typ.
1275
    # TransportLock or LockDir
1276
1534.4.39 by Robert Collins
Basic BzrDir support.
1277
    @classmethod
2018.5.169 by Andrew Bennetts
Add a _server_formats flag to BzrDir.open_from_transport and BzrDirFormat.find_format, make RemoteBranch.control_files into a property.
1278
    def find_format(klass, transport, _server_formats=True):
1733.1.1 by Robert Collins
Support non '.bzr' control directories in bzrdir.
1279
        """Return the format present at transport."""
2018.5.169 by Andrew Bennetts
Add a _server_formats flag to BzrDir.open_from_transport and BzrDirFormat.find_format, make RemoteBranch.control_files into a property.
1280
        if _server_formats:
1281
            formats = klass._control_server_formats + klass._control_formats
1282
        else:
1283
            formats = klass._control_formats
1284
        for format in formats:
1733.1.1 by Robert Collins
Support non '.bzr' control directories in bzrdir.
1285
            try:
1286
                return format.probe_transport(transport)
1287
            except errors.NotBranchError:
1288
                # this format does not find a control dir here.
1289
                pass
1290
        raise errors.NotBranchError(path=transport.base)
1291
1292
    @classmethod
1293
    def probe_transport(klass, transport):
1752.2.52 by Andrew Bennetts
Flesh out more Remote* methods needed to open and initialise remote branches/trees/repositories.
1294
        """Return the .bzrdir style format present in a directory."""
1534.4.39 by Robert Collins
Basic BzrDir support.
1295
        try:
2164.2.18 by Vincent Ladeuil
Take Aaron comments into account.
1296
            format_string = transport.get(".bzr/branch-format").read()
1733.2.3 by Michael Ellerman
Don't coallesce try blocks, it can lead to confusing exceptions.
1297
        except errors.NoSuchFile:
1298
            raise errors.NotBranchError(path=transport.base)
1299
1300
        try:
1534.4.39 by Robert Collins
Basic BzrDir support.
1301
            return klass._formats[format_string]
1302
        except KeyError:
1740.5.6 by Martin Pool
Clean up many exception classes.
1303
            raise errors.UnknownFormatError(format=format_string)
1534.4.39 by Robert Collins
Basic BzrDir support.
1304
1305
    @classmethod
1306
    def get_default_format(klass):
1307
        """Return the current default format."""
1308
        return klass._default_format
1309
1310
    def get_format_string(self):
1311
        """Return the ASCII format string that identifies this format."""
1312
        raise NotImplementedError(self.get_format_string)
1313
1624.3.19 by Olaf Conradi
New call get_format_description to give a user-friendly description of a
1314
    def get_format_description(self):
1315
        """Return the short description for this format."""
1316
        raise NotImplementedError(self.get_format_description)
1317
1534.5.16 by Robert Collins
Review feedback.
1318
    def get_converter(self, format=None):
1319
        """Return the converter to use to convert bzrdirs needing converts.
1534.5.10 by Robert Collins
Make upgrade driver unaware of the specific formats in play.
1320
1321
        This returns a bzrlib.bzrdir.Converter object.
1322
1323
        This should return the best upgrader to step this format towards the
1759.2.1 by Jelmer Vernooij
Fix some types (found using aspell).
1324
        current default format. In the case of plugins we can/should provide
1534.5.10 by Robert Collins
Make upgrade driver unaware of the specific formats in play.
1325
        some means for them to extend the range of returnable converters.
1534.5.13 by Robert Collins
Correct buggy test.
1326
1759.2.1 by Jelmer Vernooij
Fix some types (found using aspell).
1327
        :param format: Optional format to override the default format of the 
1534.5.13 by Robert Collins
Correct buggy test.
1328
                       library.
1534.5.10 by Robert Collins
Make upgrade driver unaware of the specific formats in play.
1329
        """
1534.5.16 by Robert Collins
Review feedback.
1330
        raise NotImplementedError(self.get_converter)
1534.5.10 by Robert Collins
Make upgrade driver unaware of the specific formats in play.
1331
2476.3.8 by Vincent Ladeuil
Mark transports that need to be instrumented or refactored to check
1332
    def initialize(self, url, possible_transports=None):
1608.2.8 by Martin Pool
Separate out BzrDir.initialize_on_transport so it
1333
        """Create a bzr control dir at this url and return an opened copy.
1334
        
1335
        Subclasses should typically override initialize_on_transport
1336
        instead of this method.
1337
        """
2476.3.8 by Vincent Ladeuil
Mark transports that need to be instrumented or refactored to check
1338
        return self.initialize_on_transport(get_transport(url,
1339
                                                          possible_transports))
1608.2.8 by Martin Pool
Separate out BzrDir.initialize_on_transport so it
1340
1651.1.6 by Martin Pool
Clean up clone-bzrdir code
1341
    def initialize_on_transport(self, transport):
1608.2.8 by Martin Pool
Separate out BzrDir.initialize_on_transport so it
1342
        """Initialize a new bzrdir in the base directory of a Transport."""
1759.2.1 by Jelmer Vernooij
Fix some types (found using aspell).
1343
        # Since we don't have a .bzr directory, inherit the
1534.4.39 by Robert Collins
Basic BzrDir support.
1344
        # mode from the root directory
1996.3.3 by John Arbash Meinel
Shave off another 40ms by demand loading branch and bzrdir
1345
        temp_control = lockable_files.LockableFiles(transport,
1346
                            '', lockable_files.TransportLock)
1534.4.39 by Robert Collins
Basic BzrDir support.
1347
        temp_control._transport.mkdir('.bzr',
1759.2.2 by Jelmer Vernooij
Revert some of my spelling fixes and fix some typos after review by Aaron.
1348
                                      # FIXME: RBC 20060121 don't peek under
1534.4.39 by Robert Collins
Basic BzrDir support.
1349
                                      # the covers
1350
                                      mode=temp_control._dir_mode)
1351
        file_mode = temp_control._file_mode
1352
        del temp_control
1608.2.8 by Martin Pool
Separate out BzrDir.initialize_on_transport so it
1353
        mutter('created control directory in ' + transport.base)
1354
        control = transport.clone('.bzr')
1534.4.39 by Robert Collins
Basic BzrDir support.
1355
        utf8_files = [('README', 
1356
                       "This is a Bazaar-NG control directory.\n"
1357
                       "Do not change any files in this directory.\n"),
1358
                      ('branch-format', self.get_format_string()),
1359
                      ]
1360
        # NB: no need to escape relative paths that are url safe.
1996.3.3 by John Arbash Meinel
Shave off another 40ms by demand loading branch and bzrdir
1361
        control_files = lockable_files.LockableFiles(control,
1362
                            self._lock_file_name, self._lock_class)
1553.5.60 by Martin Pool
New LockableFiles.create_lock() method
1363
        control_files.create_lock()
1534.4.39 by Robert Collins
Basic BzrDir support.
1364
        control_files.lock_write()
1365
        try:
1366
            for file, content in utf8_files:
1367
                control_files.put_utf8(file, content)
1368
        finally:
1369
            control_files.unlock()
1608.2.8 by Martin Pool
Separate out BzrDir.initialize_on_transport so it
1370
        return self.open(transport, _found=True)
1534.4.39 by Robert Collins
Basic BzrDir support.
1371
1372
    def is_supported(self):
1373
        """Is this format supported?
1374
1375
        Supported formats must be initializable and openable.
1376
        Unsupported formats may not support initialization or committing or 
1377
        some other features depending on the reason for not being supported.
1378
        """
1379
        return True
1380
1910.2.14 by Aaron Bentley
Fail when trying to use interrepository on Knit2 and Knit1
1381
    def same_model(self, target_format):
1382
        return (self.repository_format.rich_root_data == 
1383
            target_format.rich_root_data)
1384
1733.1.3 by Robert Collins
Extend the test suite to run bzrdir conformance tests on non .bzr based control dirs.
1385
    @classmethod
1386
    def known_formats(klass):
1387
        """Return all the known formats.
1388
        
1389
        Concrete formats should override _known_formats.
1390
        """
1733.1.6 by Jelmer Vernooij
Fix a couple of minor issues after review by Martin.
1391
        # There is double indirection here to make sure that control 
1392
        # formats used by more than one dir format will only be probed 
1393
        # once. This can otherwise be quite expensive for remote connections.
1733.1.3 by Robert Collins
Extend the test suite to run bzrdir conformance tests on non .bzr based control dirs.
1394
        result = set()
1395
        for format in klass._control_formats:
1396
            result.update(format._known_formats())
1397
        return result
1398
    
1399
    @classmethod
1400
    def _known_formats(klass):
1401
        """Return the known format instances for this control format."""
1402
        return set(klass._formats.values())
1403
1534.4.39 by Robert Collins
Basic BzrDir support.
1404
    def open(self, transport, _found=False):
1405
        """Return an instance of this format for the dir transport points at.
1406
        
1407
        _found is a private parameter, do not use it.
1408
        """
1409
        if not _found:
2090.2.2 by Martin Pool
Fix an assertion with side effects
1410
            found_format = BzrDirFormat.find_format(transport)
1411
            if not isinstance(found_format, self.__class__):
1412
                raise AssertionError("%s was asked to open %s, but it seems to need "
1413
                        "format %s" 
1414
                        % (self, transport, found_format))
1534.4.40 by Robert Collins
Add RepositoryFormats and allow bzrdir.open or create _repository to be used.
1415
        return self._open(transport)
1416
1417
    def _open(self, transport):
1418
        """Template method helper for opening BzrDirectories.
1419
1420
        This performs the actual open and any additional logic or parameter
1421
        passing.
1422
        """
1423
        raise NotImplementedError(self._open)
1534.4.39 by Robert Collins
Basic BzrDir support.
1424
1425
    @classmethod
1426
    def register_format(klass, format):
1427
        klass._formats[format.get_format_string()] = format
1428
1429
    @classmethod
1733.1.1 by Robert Collins
Support non '.bzr' control directories in bzrdir.
1430
    def register_control_format(klass, format):
2164.2.13 by v.ladeuil+lp at free
Add tests for redirection. Preserve transport decorations.
1431
        """Register a format that does not use '.bzr' for its control dir.
1733.1.1 by Robert Collins
Support non '.bzr' control directories in bzrdir.
1432
1433
        TODO: This should be pulled up into a 'ControlDirFormat' base class
1434
        which BzrDirFormat can inherit from, and renamed to register_format 
1435
        there. It has been done without that for now for simplicity of
1436
        implementation.
1437
        """
1733.1.7 by Jelmer Vernooij
Change set of control dir formats to list.
1438
        klass._control_formats.append(format)
1733.1.1 by Robert Collins
Support non '.bzr' control directories in bzrdir.
1439
1440
    @classmethod
2018.5.163 by Andrew Bennetts
Deal with various review comments from Robert.
1441
    def register_control_server_format(klass, format):
1442
        """Register a control format for client-server environments.
1443
1444
        These formats will be tried before ones registered with
1445
        register_control_format.  This gives implementations that decide to the
1446
        chance to grab it before anything looks at the contents of the format
1447
        file.
1448
        """
2018.5.169 by Andrew Bennetts
Add a _server_formats flag to BzrDir.open_from_transport and BzrDirFormat.find_format, make RemoteBranch.control_files into a property.
1449
        klass._control_server_formats.append(format)
2018.5.163 by Andrew Bennetts
Deal with various review comments from Robert.
1450
1451
    @classmethod
2204.4.12 by Aaron Bentley
Deprecate bzrdir.BzrDirFormat.set_default_format
1452
    @symbol_versioning.deprecated_method(symbol_versioning.zero_fourteen)
1534.4.39 by Robert Collins
Basic BzrDir support.
1453
    def set_default_format(klass, format):
2204.5.2 by Aaron Bentley
Tweak set_default_format
1454
        klass._set_default_format(format)
1534.4.39 by Robert Collins
Basic BzrDir support.
1455
2204.4.13 by Aaron Bentley
Update all test cases to avoid set_default_format
1456
    @classmethod
1457
    def _set_default_format(klass, format):
1458
        """Set default format (for testing behavior of defaults only)"""
1459
        klass._default_format = format
1460
1534.5.1 by Robert Collins
Give info some reasonable output and tests.
1461
    def __str__(self):
2830.1.1 by Ian Clatworthy
bzrdir.py code clean-ups
1462
        # Trim the newline
1463
        return self.get_format_string().rstrip()
1534.5.1 by Robert Collins
Give info some reasonable output and tests.
1464
1534.4.39 by Robert Collins
Basic BzrDir support.
1465
    @classmethod
1466
    def unregister_format(klass, format):
1467
        assert klass._formats[format.get_format_string()] is format
1468
        del klass._formats[format.get_format_string()]
1469
1733.1.1 by Robert Collins
Support non '.bzr' control directories in bzrdir.
1470
    @classmethod
1471
    def unregister_control_format(klass, format):
1472
        klass._control_formats.remove(format)
1473
1474
1534.4.39 by Robert Collins
Basic BzrDir support.
1475
class BzrDirFormat4(BzrDirFormat):
1476
    """Bzr dir format 4.
1477
1478
    This format is a combined format for working tree, branch and repository.
1479
    It has:
1534.4.50 by Robert Collins
Got the bzrdir api straightened out, plenty of refactoring to use it pending, but the api is up and running.
1480
     - Format 1 working trees [always]
1481
     - Format 4 branches [always]
1482
     - Format 4 repositories [always]
1534.4.39 by Robert Collins
Basic BzrDir support.
1483
1484
    This format is deprecated: it indexes texts using a text it which is
1485
    removed in format 5; write support for this format has been removed.
1486
    """
1487
1996.3.3 by John Arbash Meinel
Shave off another 40ms by demand loading branch and bzrdir
1488
    _lock_class = lockable_files.TransportLock
1553.5.69 by Martin Pool
BzrDirFormat subclasses can now control what kind of overall lock is used.
1489
1534.4.39 by Robert Collins
Basic BzrDir support.
1490
    def get_format_string(self):
1491
        """See BzrDirFormat.get_format_string()."""
1492
        return "Bazaar-NG branch, format 0.0.4\n"
1493
1624.3.19 by Olaf Conradi
New call get_format_description to give a user-friendly description of a
1494
    def get_format_description(self):
1495
        """See BzrDirFormat.get_format_description()."""
1496
        return "All-in-one format 4"
1497
1534.5.16 by Robert Collins
Review feedback.
1498
    def get_converter(self, format=None):
1499
        """See BzrDirFormat.get_converter()."""
1534.5.13 by Robert Collins
Correct buggy test.
1500
        # there is one and only one upgrade path here.
1534.5.10 by Robert Collins
Make upgrade driver unaware of the specific formats in play.
1501
        return ConvertBzrDir4To5()
1502
        
1651.1.6 by Martin Pool
Clean up clone-bzrdir code
1503
    def initialize_on_transport(self, transport):
1534.4.39 by Robert Collins
Basic BzrDir support.
1504
        """Format 4 branches cannot be created."""
1505
        raise errors.UninitializableFormat(self)
1506
1507
    def is_supported(self):
1508
        """Format 4 is not supported.
1509
1510
        It is not supported because the model changed from 4 to 5 and the
1511
        conversion logic is expensive - so doing it on the fly was not 
1512
        feasible.
1513
        """
1514
        return False
1515
1534.4.40 by Robert Collins
Add RepositoryFormats and allow bzrdir.open or create _repository to be used.
1516
    def _open(self, transport):
1517
        """See BzrDirFormat._open."""
1518
        return BzrDir4(transport, self)
1519
1556.1.4 by Robert Collins
Add a new format for what will become knit, and the surrounding logic to upgrade repositories within metadirs, and tests for the same.
1520
    def __return_repository_format(self):
1521
        """Circular import protection."""
2241.1.4 by Martin Pool
Moved old weave-based repository formats into bzrlib.repofmt.weaverepo.
1522
        from bzrlib.repofmt.weaverepo import RepositoryFormat4
1910.2.12 by Aaron Bentley
Implement knit repo format 2
1523
        return RepositoryFormat4()
1556.1.4 by Robert Collins
Add a new format for what will become knit, and the surrounding logic to upgrade repositories within metadirs, and tests for the same.
1524
    repository_format = property(__return_repository_format)
1525
1534.4.39 by Robert Collins
Basic BzrDir support.
1526
1527
class BzrDirFormat5(BzrDirFormat):
1528
    """Bzr control format 5.
1529
1530
    This format is a combined format for working tree, branch and repository.
1531
    It has:
1534.4.50 by Robert Collins
Got the bzrdir api straightened out, plenty of refactoring to use it pending, but the api is up and running.
1532
     - Format 2 working trees [always] 
1533
     - Format 4 branches [always] 
1534.4.53 by Robert Collins
Review feedback from John Meinel.
1534
     - Format 5 repositories [always]
1534.4.50 by Robert Collins
Got the bzrdir api straightened out, plenty of refactoring to use it pending, but the api is up and running.
1535
       Unhashed stores in the repository.
1534.4.39 by Robert Collins
Basic BzrDir support.
1536
    """
1537
1996.3.3 by John Arbash Meinel
Shave off another 40ms by demand loading branch and bzrdir
1538
    _lock_class = lockable_files.TransportLock
1553.5.69 by Martin Pool
BzrDirFormat subclasses can now control what kind of overall lock is used.
1539
1534.4.39 by Robert Collins
Basic BzrDir support.
1540
    def get_format_string(self):
1541
        """See BzrDirFormat.get_format_string()."""
1542
        return "Bazaar-NG branch, format 5\n"
1543
1624.3.19 by Olaf Conradi
New call get_format_description to give a user-friendly description of a
1544
    def get_format_description(self):
1545
        """See BzrDirFormat.get_format_description()."""
1546
        return "All-in-one format 5"
1547
1534.5.16 by Robert Collins
Review feedback.
1548
    def get_converter(self, format=None):
1549
        """See BzrDirFormat.get_converter()."""
1534.5.13 by Robert Collins
Correct buggy test.
1550
        # there is one and only one upgrade path here.
1534.5.10 by Robert Collins
Make upgrade driver unaware of the specific formats in play.
1551
        return ConvertBzrDir5To6()
1651.1.6 by Martin Pool
Clean up clone-bzrdir code
1552
1553
    def _initialize_for_clone(self, url):
1554
        return self.initialize_on_transport(get_transport(url), _cloning=True)
1534.5.10 by Robert Collins
Make upgrade driver unaware of the specific formats in play.
1555
        
1608.2.8 by Martin Pool
Separate out BzrDir.initialize_on_transport so it
1556
    def initialize_on_transport(self, transport, _cloning=False):
1534.4.50 by Robert Collins
Got the bzrdir api straightened out, plenty of refactoring to use it pending, but the api is up and running.
1557
        """Format 5 dirs always have working tree, branch and repository.
1558
        
1559
        Except when they are being cloned.
1560
        """
1561
        from bzrlib.branch import BzrBranchFormat4
2241.1.4 by Martin Pool
Moved old weave-based repository formats into bzrlib.repofmt.weaverepo.
1562
        from bzrlib.repofmt.weaverepo import RepositoryFormat5
1534.4.50 by Robert Collins
Got the bzrdir api straightened out, plenty of refactoring to use it pending, but the api is up and running.
1563
        from bzrlib.workingtree import WorkingTreeFormat2
1651.1.6 by Martin Pool
Clean up clone-bzrdir code
1564
        result = (super(BzrDirFormat5, self).initialize_on_transport(transport))
1534.4.50 by Robert Collins
Got the bzrdir api straightened out, plenty of refactoring to use it pending, but the api is up and running.
1565
        RepositoryFormat5().initialize(result, _internal=True)
1566
        if not _cloning:
1910.5.1 by Andrew Bennetts
Make some old formats create at least a stub working tree rather than incomplete bzrdirs, and change some tests to use the test suite transport rather than hard-coded to local-only.
1567
            branch = BzrBranchFormat4().initialize(result)
1568
            try:
1569
                WorkingTreeFormat2().initialize(result)
1570
            except errors.NotLocalUrl:
1571
                # Even though we can't access the working tree, we need to
1572
                # create its control files.
1573
                WorkingTreeFormat2().stub_initialize_remote(branch.control_files)
1534.4.50 by Robert Collins
Got the bzrdir api straightened out, plenty of refactoring to use it pending, but the api is up and running.
1574
        return result
1575
1534.4.40 by Robert Collins
Add RepositoryFormats and allow bzrdir.open or create _repository to be used.
1576
    def _open(self, transport):
1577
        """See BzrDirFormat._open."""
1578
        return BzrDir5(transport, self)
1579
1556.1.4 by Robert Collins
Add a new format for what will become knit, and the surrounding logic to upgrade repositories within metadirs, and tests for the same.
1580
    def __return_repository_format(self):
1581
        """Circular import protection."""
2241.1.4 by Martin Pool
Moved old weave-based repository formats into bzrlib.repofmt.weaverepo.
1582
        from bzrlib.repofmt.weaverepo import RepositoryFormat5
1910.2.12 by Aaron Bentley
Implement knit repo format 2
1583
        return RepositoryFormat5()
1556.1.4 by Robert Collins
Add a new format for what will become knit, and the surrounding logic to upgrade repositories within metadirs, and tests for the same.
1584
    repository_format = property(__return_repository_format)
1585
1534.4.39 by Robert Collins
Basic BzrDir support.
1586
1587
class BzrDirFormat6(BzrDirFormat):
1588
    """Bzr control format 6.
1589
1590
    This format is a combined format for working tree, branch and repository.
1591
    It has:
1534.4.50 by Robert Collins
Got the bzrdir api straightened out, plenty of refactoring to use it pending, but the api is up and running.
1592
     - Format 2 working trees [always] 
1593
     - Format 4 branches [always] 
1594
     - Format 6 repositories [always]
1534.4.39 by Robert Collins
Basic BzrDir support.
1595
    """
1596
1996.3.3 by John Arbash Meinel
Shave off another 40ms by demand loading branch and bzrdir
1597
    _lock_class = lockable_files.TransportLock
1553.5.69 by Martin Pool
BzrDirFormat subclasses can now control what kind of overall lock is used.
1598
1534.4.39 by Robert Collins
Basic BzrDir support.
1599
    def get_format_string(self):
1600
        """See BzrDirFormat.get_format_string()."""
1601
        return "Bazaar-NG branch, format 6\n"
1602
1624.3.19 by Olaf Conradi
New call get_format_description to give a user-friendly description of a
1603
    def get_format_description(self):
1604
        """See BzrDirFormat.get_format_description()."""
1605
        return "All-in-one format 6"
1606
1534.5.16 by Robert Collins
Review feedback.
1607
    def get_converter(self, format=None):
1608
        """See BzrDirFormat.get_converter()."""
1534.5.13 by Robert Collins
Correct buggy test.
1609
        # there is one and only one upgrade path here.
1534.5.10 by Robert Collins
Make upgrade driver unaware of the specific formats in play.
1610
        return ConvertBzrDir6ToMeta()
1611
        
1651.1.6 by Martin Pool
Clean up clone-bzrdir code
1612
    def _initialize_for_clone(self, url):
1613
        return self.initialize_on_transport(get_transport(url), _cloning=True)
1614
1608.2.8 by Martin Pool
Separate out BzrDir.initialize_on_transport so it
1615
    def initialize_on_transport(self, transport, _cloning=False):
1534.4.50 by Robert Collins
Got the bzrdir api straightened out, plenty of refactoring to use it pending, but the api is up and running.
1616
        """Format 6 dirs always have working tree, branch and repository.
1617
        
1618
        Except when they are being cloned.
1619
        """
1620
        from bzrlib.branch import BzrBranchFormat4
2241.1.4 by Martin Pool
Moved old weave-based repository formats into bzrlib.repofmt.weaverepo.
1621
        from bzrlib.repofmt.weaverepo import RepositoryFormat6
1534.4.50 by Robert Collins
Got the bzrdir api straightened out, plenty of refactoring to use it pending, but the api is up and running.
1622
        from bzrlib.workingtree import WorkingTreeFormat2
1651.1.6 by Martin Pool
Clean up clone-bzrdir code
1623
        result = super(BzrDirFormat6, self).initialize_on_transport(transport)
1534.4.50 by Robert Collins
Got the bzrdir api straightened out, plenty of refactoring to use it pending, but the api is up and running.
1624
        RepositoryFormat6().initialize(result, _internal=True)
1625
        if not _cloning:
1910.5.1 by Andrew Bennetts
Make some old formats create at least a stub working tree rather than incomplete bzrdirs, and change some tests to use the test suite transport rather than hard-coded to local-only.
1626
            branch = BzrBranchFormat4().initialize(result)
1534.4.50 by Robert Collins
Got the bzrdir api straightened out, plenty of refactoring to use it pending, but the api is up and running.
1627
            try:
1628
                WorkingTreeFormat2().initialize(result)
1629
            except errors.NotLocalUrl:
1910.5.1 by Andrew Bennetts
Make some old formats create at least a stub working tree rather than incomplete bzrdirs, and change some tests to use the test suite transport rather than hard-coded to local-only.
1630
                # Even though we can't access the working tree, we need to
1631
                # create its control files.
1632
                WorkingTreeFormat2().stub_initialize_remote(branch.control_files)
1534.4.50 by Robert Collins
Got the bzrdir api straightened out, plenty of refactoring to use it pending, but the api is up and running.
1633
        return result
1634
1534.4.40 by Robert Collins
Add RepositoryFormats and allow bzrdir.open or create _repository to be used.
1635
    def _open(self, transport):
1636
        """See BzrDirFormat._open."""
1637
        return BzrDir6(transport, self)
1638
1556.1.4 by Robert Collins
Add a new format for what will become knit, and the surrounding logic to upgrade repositories within metadirs, and tests for the same.
1639
    def __return_repository_format(self):
1640
        """Circular import protection."""
2241.1.4 by Martin Pool
Moved old weave-based repository formats into bzrlib.repofmt.weaverepo.
1641
        from bzrlib.repofmt.weaverepo import RepositoryFormat6
1910.2.12 by Aaron Bentley
Implement knit repo format 2
1642
        return RepositoryFormat6()
1556.1.4 by Robert Collins
Add a new format for what will become knit, and the surrounding logic to upgrade repositories within metadirs, and tests for the same.
1643
    repository_format = property(__return_repository_format)
1644
1534.4.39 by Robert Collins
Basic BzrDir support.
1645
1534.4.44 by Robert Collins
Make a new BzrDir format that uses a versioned branch format in a branch/ subdirectory.
1646
class BzrDirMetaFormat1(BzrDirFormat):
1647
    """Bzr meta control format 1
1648
1649
    This is the first format with split out working tree, branch and repository
1650
    disk storage.
1651
    It has:
1534.4.50 by Robert Collins
Got the bzrdir api straightened out, plenty of refactoring to use it pending, but the api is up and running.
1652
     - Format 3 working trees [optional]
1653
     - Format 5 branches [optional]
1654
     - Format 7 repositories [optional]
1534.4.44 by Robert Collins
Make a new BzrDir format that uses a versioned branch format in a branch/ subdirectory.
1655
    """
1656
1996.3.3 by John Arbash Meinel
Shave off another 40ms by demand loading branch and bzrdir
1657
    _lock_class = lockdir.LockDir
1553.5.69 by Martin Pool
BzrDirFormat subclasses can now control what kind of overall lock is used.
1658
2100.3.10 by Aaron Bentley
Ensure added references are serialized properly, beef up Workingtreee3
1659
    def __init__(self):
1660
        self._workingtree_format = None
2230.3.1 by Aaron Bentley
Get branch6 creation working
1661
        self._branch_format = None
2100.3.10 by Aaron Bentley
Ensure added references are serialized properly, beef up Workingtreee3
1662
2100.3.15 by Aaron Bentley
get test suite passing
1663
    def __eq__(self, other):
1664
        if other.__class__ is not self.__class__:
1665
            return False
1666
        if other.repository_format != self.repository_format:
1667
            return False
1668
        if other.workingtree_format != self.workingtree_format:
1669
            return False
1670
        return True
1671
2100.3.35 by Aaron Bentley
equality operations on bzrdir
1672
    def __ne__(self, other):
1673
        return not self == other
1674
2230.3.55 by Aaron Bentley
Updates from review
1675
    def get_branch_format(self):
2230.3.1 by Aaron Bentley
Get branch6 creation working
1676
        if self._branch_format is None:
1677
            from bzrlib.branch import BranchFormat
1678
            self._branch_format = BranchFormat.get_default_format()
1679
        return self._branch_format
1680
2230.3.55 by Aaron Bentley
Updates from review
1681
    def set_branch_format(self, format):
2230.3.1 by Aaron Bentley
Get branch6 creation working
1682
        self._branch_format = format
1683
1556.1.4 by Robert Collins
Add a new format for what will become knit, and the surrounding logic to upgrade repositories within metadirs, and tests for the same.
1684
    def get_converter(self, format=None):
1685
        """See BzrDirFormat.get_converter()."""
1686
        if format is None:
1687
            format = BzrDirFormat.get_default_format()
1688
        if not isinstance(self, format.__class__):
1689
            # converting away from metadir is not implemented
1690
            raise NotImplementedError(self.get_converter)
1691
        return ConvertMetaToMeta(format)
1692
1534.4.44 by Robert Collins
Make a new BzrDir format that uses a versioned branch format in a branch/ subdirectory.
1693
    def get_format_string(self):
1694
        """See BzrDirFormat.get_format_string()."""
1695
        return "Bazaar-NG meta directory, format 1\n"
1696
1624.3.19 by Olaf Conradi
New call get_format_description to give a user-friendly description of a
1697
    def get_format_description(self):
1698
        """See BzrDirFormat.get_format_description()."""
1699
        return "Meta directory format 1"
1700
1534.4.44 by Robert Collins
Make a new BzrDir format that uses a versioned branch format in a branch/ subdirectory.
1701
    def _open(self, transport):
1702
        """See BzrDirFormat._open."""
2230.3.24 by Aaron Bentley
Remove format-on-open code
1703
        return BzrDirMeta1(transport, self)
1534.4.44 by Robert Collins
Make a new BzrDir format that uses a versioned branch format in a branch/ subdirectory.
1704
1556.1.4 by Robert Collins
Add a new format for what will become knit, and the surrounding logic to upgrade repositories within metadirs, and tests for the same.
1705
    def __return_repository_format(self):
1706
        """Circular import protection."""
1707
        if getattr(self, '_repository_format', None):
1708
            return self._repository_format
1709
        from bzrlib.repository import RepositoryFormat
1710
        return RepositoryFormat.get_default_format()
1711
1712
    def __set_repository_format(self, value):
1713
        """Allow changint the repository format for metadir formats."""
1714
        self._repository_format = value
1553.5.72 by Martin Pool
Clean up test for Branch5 lockdirs
1715
1556.1.4 by Robert Collins
Add a new format for what will become knit, and the surrounding logic to upgrade repositories within metadirs, and tests for the same.
1716
    repository_format = property(__return_repository_format, __set_repository_format)
1717
2100.3.10 by Aaron Bentley
Ensure added references are serialized properly, beef up Workingtreee3
1718
    def __get_workingtree_format(self):
1719
        if self._workingtree_format is None:
1720
            from bzrlib.workingtree import WorkingTreeFormat
1721
            self._workingtree_format = WorkingTreeFormat.get_default_format()
1722
        return self._workingtree_format
1723
1724
    def __set_workingtree_format(self, wt_format):
1725
        self._workingtree_format = wt_format
1726
1727
    workingtree_format = property(__get_workingtree_format,
1728
                                  __set_workingtree_format)
1729
1534.4.44 by Robert Collins
Make a new BzrDir format that uses a versioned branch format in a branch/ subdirectory.
1730
2164.2.19 by Vincent Ladeuil
Revert BzrDirFormat1 registering.
1731
# Register bzr control format
1732
BzrDirFormat.register_control_format(BzrDirFormat)
2164.2.13 by v.ladeuil+lp at free
Add tests for redirection. Preserve transport decorations.
1733
1734
# Register bzr formats
1534.4.39 by Robert Collins
Basic BzrDir support.
1735
BzrDirFormat.register_format(BzrDirFormat4())
1736
BzrDirFormat.register_format(BzrDirFormat5())
1666.1.4 by Robert Collins
* 'Metadir' is now the default disk format. This improves behaviour in
1737
BzrDirFormat.register_format(BzrDirFormat6())
1738
__default_format = BzrDirMetaFormat1()
1534.4.39 by Robert Collins
Basic BzrDir support.
1739
BzrDirFormat.register_format(__default_format)
2204.4.13 by Aaron Bentley
Update all test cases to avoid set_default_format
1740
BzrDirFormat._default_format = __default_format
1534.4.39 by Robert Collins
Basic BzrDir support.
1741
1742
1534.5.7 by Robert Collins
Start factoring out the upgrade policy logic.
1743
class Converter(object):
1744
    """Converts a disk format object from one format to another."""
1745
1534.5.10 by Robert Collins
Make upgrade driver unaware of the specific formats in play.
1746
    def convert(self, to_convert, pb):
1747
        """Perform the conversion of to_convert, giving feedback via pb.
1534.5.7 by Robert Collins
Start factoring out the upgrade policy logic.
1748
1534.5.10 by Robert Collins
Make upgrade driver unaware of the specific formats in play.
1749
        :param to_convert: The disk object to convert.
1534.5.7 by Robert Collins
Start factoring out the upgrade policy logic.
1750
        :param pb: a progress bar to use for progress information.
1751
        """
1752
1556.1.4 by Robert Collins
Add a new format for what will become knit, and the surrounding logic to upgrade repositories within metadirs, and tests for the same.
1753
    def step(self, message):
1754
        """Update the pb by a step."""
1755
        self.count +=1
1756
        self.pb.update(message, self.count, self.total)
1757
1534.5.7 by Robert Collins
Start factoring out the upgrade policy logic.
1758
1759
class ConvertBzrDir4To5(Converter):
1760
    """Converts format 4 bzr dirs to format 5."""
1761
1534.5.10 by Robert Collins
Make upgrade driver unaware of the specific formats in play.
1762
    def __init__(self):
1763
        super(ConvertBzrDir4To5, self).__init__()
1534.5.7 by Robert Collins
Start factoring out the upgrade policy logic.
1764
        self.converted_revs = set()
1765
        self.absent_revisions = set()
1766
        self.text_count = 0
1767
        self.revisions = {}
1768
        
1534.5.10 by Robert Collins
Make upgrade driver unaware of the specific formats in play.
1769
    def convert(self, to_convert, pb):
1534.5.7 by Robert Collins
Start factoring out the upgrade policy logic.
1770
        """See Converter.convert()."""
1534.5.10 by Robert Collins
Make upgrade driver unaware of the specific formats in play.
1771
        self.bzrdir = to_convert
1772
        self.pb = pb
1534.5.7 by Robert Collins
Start factoring out the upgrade policy logic.
1773
        self.pb.note('starting upgrade from format 4 to 5')
1774
        if isinstance(self.bzrdir.transport, LocalTransport):
1775
            self.bzrdir.get_workingtree_transport(None).delete('stat-cache')
1776
        self._convert_to_weaves()
1777
        return BzrDir.open(self.bzrdir.root_transport.base)
1778
1779
    def _convert_to_weaves(self):
1780
        self.pb.note('note: upgrade may be faster if all store files are ungzipped first')
1781
        try:
1782
            # TODO permissions
1783
            stat = self.bzrdir.transport.stat('weaves')
1784
            if not S_ISDIR(stat.st_mode):
1785
                self.bzrdir.transport.delete('weaves')
1786
                self.bzrdir.transport.mkdir('weaves')
1787
        except errors.NoSuchFile:
1788
            self.bzrdir.transport.mkdir('weaves')
1563.2.10 by Robert Collins
Change weave store to be a versioned store, using WeaveFiles which maintain integrity without needing explicit 'put' operations.
1789
        # deliberately not a WeaveFile as we want to build it up slowly.
1534.5.7 by Robert Collins
Start factoring out the upgrade policy logic.
1790
        self.inv_weave = Weave('inventory')
1791
        # holds in-memory weaves for all files
1792
        self.text_weaves = {}
1793
        self.bzrdir.transport.delete('branch-format')
1794
        self.branch = self.bzrdir.open_branch()
1795
        self._convert_working_inv()
1796
        rev_history = self.branch.revision_history()
1797
        # to_read is a stack holding the revisions we still need to process;
1798
        # appending to it adds new highest-priority revisions
1799
        self.known_revisions = set(rev_history)
1800
        self.to_read = rev_history[-1:]
1801
        while self.to_read:
1802
            rev_id = self.to_read.pop()
1803
            if (rev_id not in self.revisions
1804
                and rev_id not in self.absent_revisions):
1805
                self._load_one_rev(rev_id)
1806
        self.pb.clear()
1807
        to_import = self._make_order()
1808
        for i, rev_id in enumerate(to_import):
1809
            self.pb.update('converting revision', i, len(to_import))
1810
            self._convert_one_rev(rev_id)
1811
        self.pb.clear()
1812
        self._write_all_weaves()
1813
        self._write_all_revs()
1814
        self.pb.note('upgraded to weaves:')
1815
        self.pb.note('  %6d revisions and inventories', len(self.revisions))
1816
        self.pb.note('  %6d revisions not present', len(self.absent_revisions))
1817
        self.pb.note('  %6d texts', self.text_count)
1818
        self._cleanup_spare_files_after_format4()
1819
        self.branch.control_files.put_utf8('branch-format', BzrDirFormat5().get_format_string())
1820
1821
    def _cleanup_spare_files_after_format4(self):
1822
        # FIXME working tree upgrade foo.
1823
        for n in 'merged-patches', 'pending-merged-patches':
1824
            try:
1825
                ## assert os.path.getsize(p) == 0
1826
                self.bzrdir.transport.delete(n)
1827
            except errors.NoSuchFile:
1828
                pass
1829
        self.bzrdir.transport.delete_tree('inventory-store')
1830
        self.bzrdir.transport.delete_tree('text-store')
1831
1832
    def _convert_working_inv(self):
1996.3.6 by John Arbash Meinel
Find a few places that weren't importing their dependencies.
1833
        inv = xml4.serializer_v4.read_inventory(
1834
                    self.branch.control_files.get('inventory'))
2817.2.1 by Robert Collins
* Inventory serialisation no longer double-sha's the content.
1835
        new_inv_xml = xml5.serializer_v5.write_inventory_to_string(inv, working=True)
1534.5.7 by Robert Collins
Start factoring out the upgrade policy logic.
1836
        # FIXME inventory is a working tree change.
1955.3.4 by John Arbash Meinel
Fix 2 calls to 'put()' that were using strings instead of files
1837
        self.branch.control_files.put('inventory', StringIO(new_inv_xml))
1534.5.7 by Robert Collins
Start factoring out the upgrade policy logic.
1838
1839
    def _write_all_weaves(self):
1840
        controlweaves = WeaveStore(self.bzrdir.transport, prefixed=False)
1841
        weave_transport = self.bzrdir.transport.clone('weaves')
1842
        weaves = WeaveStore(weave_transport, prefixed=False)
1563.2.34 by Robert Collins
Remove the commit and rollback transaction methods as misleading, and implement a WriteTransaction
1843
        transaction = WriteTransaction()
1534.5.7 by Robert Collins
Start factoring out the upgrade policy logic.
1844
1845
        try:
1563.2.10 by Robert Collins
Change weave store to be a versioned store, using WeaveFiles which maintain integrity without needing explicit 'put' operations.
1846
            i = 0
1534.5.7 by Robert Collins
Start factoring out the upgrade policy logic.
1847
            for file_id, file_weave in self.text_weaves.items():
1848
                self.pb.update('writing weave', i, len(self.text_weaves))
1563.2.10 by Robert Collins
Change weave store to be a versioned store, using WeaveFiles which maintain integrity without needing explicit 'put' operations.
1849
                weaves._put_weave(file_id, file_weave, transaction)
1534.5.7 by Robert Collins
Start factoring out the upgrade policy logic.
1850
                i += 1
1563.2.10 by Robert Collins
Change weave store to be a versioned store, using WeaveFiles which maintain integrity without needing explicit 'put' operations.
1851
            self.pb.update('inventory', 0, 1)
1852
            controlweaves._put_weave('inventory', self.inv_weave, transaction)
1853
            self.pb.update('inventory', 1, 1)
1534.5.7 by Robert Collins
Start factoring out the upgrade policy logic.
1854
        finally:
1855
            self.pb.clear()
1856
1857
    def _write_all_revs(self):
1858
        """Write all revisions out in new form."""
1859
        self.bzrdir.transport.delete_tree('revision-store')
1860
        self.bzrdir.transport.mkdir('revision-store')
1861
        revision_transport = self.bzrdir.transport.clone('revision-store')
1862
        # TODO permissions
1563.2.28 by Robert Collins
Add total_size to the revision_store api.
1863
        _revision_store = TextRevisionStore(TextStore(revision_transport,
1864
                                                      prefixed=False,
1865
                                                      compressed=True))
1534.5.7 by Robert Collins
Start factoring out the upgrade policy logic.
1866
        try:
1996.3.3 by John Arbash Meinel
Shave off another 40ms by demand loading branch and bzrdir
1867
            transaction = WriteTransaction()
1534.5.7 by Robert Collins
Start factoring out the upgrade policy logic.
1868
            for i, rev_id in enumerate(self.converted_revs):
1869
                self.pb.update('write revision', i, len(self.converted_revs))
1563.2.28 by Robert Collins
Add total_size to the revision_store api.
1870
                _revision_store.add_revision(self.revisions[rev_id], transaction)
1534.5.7 by Robert Collins
Start factoring out the upgrade policy logic.
1871
        finally:
1872
            self.pb.clear()
1873
            
1874
    def _load_one_rev(self, rev_id):
1875
        """Load a revision object into memory.
1876
1877
        Any parents not either loaded or abandoned get queued to be
1878
        loaded."""
1879
        self.pb.update('loading revision',
1880
                       len(self.revisions),
1881
                       len(self.known_revisions))
1563.2.22 by Robert Collins
Move responsibility for repository.has_revision into RevisionStore
1882
        if not self.branch.repository.has_revision(rev_id):
1534.5.7 by Robert Collins
Start factoring out the upgrade policy logic.
1883
            self.pb.clear()
1884
            self.pb.note('revision {%s} not present in branch; '
1885
                         'will be converted as a ghost',
1886
                         rev_id)
1887
            self.absent_revisions.add(rev_id)
1888
        else:
1563.2.28 by Robert Collins
Add total_size to the revision_store api.
1889
            rev = self.branch.repository._revision_store.get_revision(rev_id,
1890
                self.branch.repository.get_transaction())
1534.5.7 by Robert Collins
Start factoring out the upgrade policy logic.
1891
            for parent_id in rev.parent_ids:
1892
                self.known_revisions.add(parent_id)
1893
                self.to_read.append(parent_id)
1894
            self.revisions[rev_id] = rev
1895
1896
    def _load_old_inventory(self, rev_id):
1897
        assert rev_id not in self.converted_revs
1898
        old_inv_xml = self.branch.repository.inventory_store.get(rev_id).read()
1996.3.6 by John Arbash Meinel
Find a few places that weren't importing their dependencies.
1899
        inv = xml4.serializer_v4.read_inventory_from_string(old_inv_xml)
1910.2.36 by Aaron Bentley
Get upgrade from format4 under test and fixed for all formats
1900
        inv.revision_id = rev_id
1534.5.7 by Robert Collins
Start factoring out the upgrade policy logic.
1901
        rev = self.revisions[rev_id]
1902
        if rev.inventory_sha1:
1903
            assert rev.inventory_sha1 == sha_string(old_inv_xml), \
1904
                'inventory sha mismatch for {%s}' % rev_id
1905
        return inv
1906
1907
    def _load_updated_inventory(self, rev_id):
1908
        assert rev_id in self.converted_revs
1909
        inv_xml = self.inv_weave.get_text(rev_id)
1996.3.6 by John Arbash Meinel
Find a few places that weren't importing their dependencies.
1910
        inv = xml5.serializer_v5.read_inventory_from_string(inv_xml)
1534.5.7 by Robert Collins
Start factoring out the upgrade policy logic.
1911
        return inv
1912
1913
    def _convert_one_rev(self, rev_id):
1914
        """Convert revision and all referenced objects to new format."""
1915
        rev = self.revisions[rev_id]
1916
        inv = self._load_old_inventory(rev_id)
1917
        present_parents = [p for p in rev.parent_ids
1918
                           if p not in self.absent_revisions]
1919
        self._convert_revision_contents(rev, inv, present_parents)
2817.2.1 by Robert Collins
* Inventory serialisation no longer double-sha's the content.
1920
        self._store_new_inv(rev, inv, present_parents)
1534.5.7 by Robert Collins
Start factoring out the upgrade policy logic.
1921
        self.converted_revs.add(rev_id)
1922
2817.2.1 by Robert Collins
* Inventory serialisation no longer double-sha's the content.
1923
    def _store_new_inv(self, rev, inv, present_parents):
1534.5.7 by Robert Collins
Start factoring out the upgrade policy logic.
1924
        # the XML is now updated with text versions
1925
        if __debug__:
1907.1.8 by Aaron Bentley
Remove is_root
1926
            entries = inv.iter_entries()
1927
            entries.next()
1928
            for path, ie in entries:
1963.2.6 by Robey Pointer
pychecker is on crack; go back to using 'is None'.
1929
                assert getattr(ie, 'revision', None) is not None, \
1534.5.7 by Robert Collins
Start factoring out the upgrade policy logic.
1930
                    'no revision on {%s} in {%s}' % \
1931
                    (file_id, rev.revision_id)
1996.3.6 by John Arbash Meinel
Find a few places that weren't importing their dependencies.
1932
        new_inv_xml = xml5.serializer_v5.write_inventory_to_string(inv)
1534.5.7 by Robert Collins
Start factoring out the upgrade policy logic.
1933
        new_inv_sha1 = sha_string(new_inv_xml)
2817.2.1 by Robert Collins
* Inventory serialisation no longer double-sha's the content.
1934
        self.inv_weave.add_lines(rev.revision_id,
1563.2.28 by Robert Collins
Add total_size to the revision_store api.
1935
                                 present_parents,
1936
                                 new_inv_xml.splitlines(True))
1534.5.7 by Robert Collins
Start factoring out the upgrade policy logic.
1937
        rev.inventory_sha1 = new_inv_sha1
1938
1939
    def _convert_revision_contents(self, rev, inv, present_parents):
1940
        """Convert all the files within a revision.
1941
1942
        Also upgrade the inventory to refer to the text revision ids."""
1943
        rev_id = rev.revision_id
1944
        mutter('converting texts of revision {%s}',
1945
               rev_id)
1946
        parent_invs = map(self._load_updated_inventory, present_parents)
1731.1.62 by Aaron Bentley
Changes from review comments
1947
        entries = inv.iter_entries()
1948
        entries.next()
1949
        for path, ie in entries:
1534.5.7 by Robert Collins
Start factoring out the upgrade policy logic.
1950
            self._convert_file_version(rev, ie, parent_invs)
1951
1952
    def _convert_file_version(self, rev, ie, parent_invs):
1953
        """Convert one version of one file.
1954
1955
        The file needs to be added into the weave if it is a merge
1956
        of >=2 parents or if it's changed from its parent.
1957
        """
1958
        file_id = ie.file_id
1959
        rev_id = rev.revision_id
1960
        w = self.text_weaves.get(file_id)
1961
        if w is None:
1962
            w = Weave(file_id)
1963
            self.text_weaves[file_id] = w
1964
        text_changed = False
2776.1.5 by Robert Collins
Add reasonably comprehensive tests for path last modified and per file graph behaviour.
1965
        parent_candiate_entries = ie.parent_candidates(parent_invs)
1966
        for old_revision in parent_candiate_entries.keys():
1967
            # if this fails, its a ghost ?
1968
            assert old_revision in self.converted_revs, \
1969
                "Revision {%s} not in converted_revs" % old_revision
1970
        heads = graph.Graph(self).heads(parent_candiate_entries.keys())
1971
        # XXX: Note that this is unordered - and this is tolerable because 
1972
        # the previous code was also unordered.
1973
        previous_entries = dict((head, parent_candiate_entries[head]) for head
1974
            in heads)
1534.5.7 by Robert Collins
Start factoring out the upgrade policy logic.
1975
        self.snapshot_ie(previous_entries, ie, w, rev_id)
1976
        del ie.text_id
1977
        assert getattr(ie, 'revision', None) is not None
1978
2776.1.5 by Robert Collins
Add reasonably comprehensive tests for path last modified and per file graph behaviour.
1979
    def get_parents(self, revision_ids):
1980
        for revision_id in revision_ids:
1981
            yield self.revisions[revision_id].parent_ids
1982
1534.5.7 by Robert Collins
Start factoring out the upgrade policy logic.
1983
    def snapshot_ie(self, previous_revisions, ie, w, rev_id):
1984
        # TODO: convert this logic, which is ~= snapshot to
1985
        # a call to:. This needs the path figured out. rather than a work_tree
1986
        # a v4 revision_tree can be given, or something that looks enough like
1987
        # one to give the file content to the entry if it needs it.
1988
        # and we need something that looks like a weave store for snapshot to 
1989
        # save against.
1990
        #ie.snapshot(rev, PATH, previous_revisions, REVISION_TREE, InMemoryWeaveStore(self.text_weaves))
1991
        if len(previous_revisions) == 1:
1992
            previous_ie = previous_revisions.values()[0]
1993
            if ie._unchanged(previous_ie):
1994
                ie.revision = previous_ie.revision
1995
                return
1996
        if ie.has_text():
2661.1.1 by Robert Collins
Ancient unused Repository.text_store attribute has been removed. (Robert Collins)
1997
            text = self.branch.repository.weave_store.get(ie.text_id)
1534.5.7 by Robert Collins
Start factoring out the upgrade policy logic.
1998
            file_lines = text.readlines()
1999
            assert sha_strings(file_lines) == ie.text_sha1
2000
            assert sum(map(len, file_lines)) == ie.text_size
1563.2.18 by Robert Collins
get knit repositories really using knits for text storage.
2001
            w.add_lines(rev_id, previous_revisions, file_lines)
1534.5.7 by Robert Collins
Start factoring out the upgrade policy logic.
2002
            self.text_count += 1
2003
        else:
1563.2.18 by Robert Collins
get knit repositories really using knits for text storage.
2004
            w.add_lines(rev_id, previous_revisions, [])
1534.5.7 by Robert Collins
Start factoring out the upgrade policy logic.
2005
        ie.revision = rev_id
2006
2007
    def _make_order(self):
2008
        """Return a suitable order for importing revisions.
2009
2010
        The order must be such that an revision is imported after all
2011
        its (present) parents.
2012
        """
2013
        todo = set(self.revisions.keys())
2014
        done = self.absent_revisions.copy()
1534.5.11 by Robert Collins
Implement upgrades to Metaformat trees.
2015
        order = []
1534.5.7 by Robert Collins
Start factoring out the upgrade policy logic.
2016
        while todo:
2017
            # scan through looking for a revision whose parents
2018
            # are all done
2019
            for rev_id in sorted(list(todo)):
2020
                rev = self.revisions[rev_id]
2021
                parent_ids = set(rev.parent_ids)
2022
                if parent_ids.issubset(done):
2023
                    # can take this one now
1534.5.11 by Robert Collins
Implement upgrades to Metaformat trees.
2024
                    order.append(rev_id)
1534.5.7 by Robert Collins
Start factoring out the upgrade policy logic.
2025
                    todo.remove(rev_id)
2026
                    done.add(rev_id)
1534.5.11 by Robert Collins
Implement upgrades to Metaformat trees.
2027
        return order
1534.5.7 by Robert Collins
Start factoring out the upgrade policy logic.
2028
2029
2030
class ConvertBzrDir5To6(Converter):
2031
    """Converts format 5 bzr dirs to format 6."""
2032
1534.5.10 by Robert Collins
Make upgrade driver unaware of the specific formats in play.
2033
    def convert(self, to_convert, pb):
2034
        """See Converter.convert()."""
1534.5.7 by Robert Collins
Start factoring out the upgrade policy logic.
2035
        self.bzrdir = to_convert
1534.5.10 by Robert Collins
Make upgrade driver unaware of the specific formats in play.
2036
        self.pb = pb
1534.5.7 by Robert Collins
Start factoring out the upgrade policy logic.
2037
        self.pb.note('starting upgrade from format 5 to 6')
2038
        self._convert_to_prefixed()
2039
        return BzrDir.open(self.bzrdir.root_transport.base)
2040
2041
    def _convert_to_prefixed(self):
1608.2.1 by Martin Pool
[merge] Storage filename escaping
2042
        from bzrlib.store import TransportStore
1534.5.7 by Robert Collins
Start factoring out the upgrade policy logic.
2043
        self.bzrdir.transport.delete('branch-format')
2044
        for store_name in ["weaves", "revision-store"]:
1608.2.1 by Martin Pool
[merge] Storage filename escaping
2045
            self.pb.note("adding prefixes to %s" % store_name)
1534.5.7 by Robert Collins
Start factoring out the upgrade policy logic.
2046
            store_transport = self.bzrdir.transport.clone(store_name)
1608.2.1 by Martin Pool
[merge] Storage filename escaping
2047
            store = TransportStore(store_transport, prefixed=True)
1608.1.1 by Martin Pool
[patch] LocalTransport.list_dir should return url-quoted strings (ddaa)
2048
            for urlfilename in store_transport.list_dir('.'):
1685.1.45 by John Arbash Meinel
Moved url functions into bzrlib.urlutils
2049
                filename = urlutils.unescape(urlfilename)
1534.5.7 by Robert Collins
Start factoring out the upgrade policy logic.
2050
                if (filename.endswith(".weave") or
2051
                    filename.endswith(".gz") or
2052
                    filename.endswith(".sig")):
2053
                    file_id = os.path.splitext(filename)[0]
2054
                else:
2055
                    file_id = filename
1608.2.1 by Martin Pool
[merge] Storage filename escaping
2056
                prefix_dir = store.hash_prefix(file_id)
1534.5.7 by Robert Collins
Start factoring out the upgrade policy logic.
2057
                # FIXME keep track of the dirs made RBC 20060121
2058
                try:
2059
                    store_transport.move(filename, prefix_dir + '/' + filename)
2060
                except errors.NoSuchFile: # catches missing dirs strangely enough
2061
                    store_transport.mkdir(prefix_dir)
2062
                    store_transport.move(filename, prefix_dir + '/' + filename)
2063
        self.bzrdir._control_files.put_utf8('branch-format', BzrDirFormat6().get_format_string())
2064
2065
1534.5.10 by Robert Collins
Make upgrade driver unaware of the specific formats in play.
2066
class ConvertBzrDir6ToMeta(Converter):
2067
    """Converts format 6 bzr dirs to metadirs."""
2068
2069
    def convert(self, to_convert, pb):
2070
        """See Converter.convert()."""
2241.1.11 by Martin Pool
Get rid of RepositoryFormat*_instance objects. Instead the format
2071
        from bzrlib.repofmt.weaverepo import RepositoryFormat7
2094.3.5 by John Arbash Meinel
Fix imports to ensure modules are loaded before they are used
2072
        from bzrlib.branch import BzrBranchFormat5
1534.5.10 by Robert Collins
Make upgrade driver unaware of the specific formats in play.
2073
        self.bzrdir = to_convert
2074
        self.pb = pb
1534.5.11 by Robert Collins
Implement upgrades to Metaformat trees.
2075
        self.count = 0
2076
        self.total = 20 # the steps we know about
2077
        self.garbage_inventories = []
2078
1534.5.13 by Robert Collins
Correct buggy test.
2079
        self.pb.note('starting upgrade from format 6 to metadir')
1534.5.11 by Robert Collins
Implement upgrades to Metaformat trees.
2080
        self.bzrdir._control_files.put_utf8('branch-format', "Converting to format 6")
2081
        # its faster to move specific files around than to open and use the apis...
2082
        # first off, nuke ancestry.weave, it was never used.
2083
        try:
2084
            self.step('Removing ancestry.weave')
2085
            self.bzrdir.transport.delete('ancestry.weave')
2086
        except errors.NoSuchFile:
2087
            pass
2088
        # find out whats there
2089
        self.step('Finding branch files')
1666.1.3 by Robert Collins
Fix and test upgrades from bzrdir 6 over SFTP.
2090
        last_revision = self.bzrdir.open_branch().last_revision()
1534.5.11 by Robert Collins
Implement upgrades to Metaformat trees.
2091
        bzrcontents = self.bzrdir.transport.list_dir('.')
2092
        for name in bzrcontents:
2093
            if name.startswith('basis-inventory.'):
2094
                self.garbage_inventories.append(name)
2095
        # create new directories for repository, working tree and branch
1553.5.79 by Martin Pool
upgrade to metadir should create LockDirs not files
2096
        self.dir_mode = self.bzrdir._control_files._dir_mode
1534.5.11 by Robert Collins
Implement upgrades to Metaformat trees.
2097
        self.file_mode = self.bzrdir._control_files._file_mode
2098
        repository_names = [('inventory.weave', True),
2099
                            ('revision-store', True),
2100
                            ('weaves', True)]
2101
        self.step('Upgrading repository  ')
1553.5.79 by Martin Pool
upgrade to metadir should create LockDirs not files
2102
        self.bzrdir.transport.mkdir('repository', mode=self.dir_mode)
1534.5.11 by Robert Collins
Implement upgrades to Metaformat trees.
2103
        self.make_lock('repository')
2104
        # we hard code the formats here because we are converting into
2105
        # the meta format. The meta format upgrader can take this to a 
2106
        # future format within each component.
2241.1.11 by Martin Pool
Get rid of RepositoryFormat*_instance objects. Instead the format
2107
        self.put_format('repository', RepositoryFormat7())
1534.5.11 by Robert Collins
Implement upgrades to Metaformat trees.
2108
        for entry in repository_names:
2109
            self.move_entry('repository', entry)
2110
2111
        self.step('Upgrading branch      ')
1553.5.79 by Martin Pool
upgrade to metadir should create LockDirs not files
2112
        self.bzrdir.transport.mkdir('branch', mode=self.dir_mode)
1534.5.11 by Robert Collins
Implement upgrades to Metaformat trees.
2113
        self.make_lock('branch')
2094.3.5 by John Arbash Meinel
Fix imports to ensure modules are loaded before they are used
2114
        self.put_format('branch', BzrBranchFormat5())
1534.5.11 by Robert Collins
Implement upgrades to Metaformat trees.
2115
        branch_files = [('revision-history', True),
2116
                        ('branch-name', True),
2117
                        ('parent', False)]
2118
        for entry in branch_files:
2119
            self.move_entry('branch', entry)
2120
2121
        checkout_files = [('pending-merges', True),
2122
                          ('inventory', True),
2123
                          ('stat-cache', False)]
1959.3.1 by John Arbash Meinel
David Allouche: bzr upgrade should work if there is no working tree
2124
        # If a mandatory checkout file is not present, the branch does not have
2125
        # a functional checkout. Do not create a checkout in the converted
2126
        # branch.
2127
        for name, mandatory in checkout_files:
2128
            if mandatory and name not in bzrcontents:
2129
                has_checkout = False
2130
                break
2131
        else:
2132
            has_checkout = True
2133
        if not has_checkout:
2134
            self.pb.note('No working tree.')
2135
            # If some checkout files are there, we may as well get rid of them.
2136
            for name, mandatory in checkout_files:
2137
                if name in bzrcontents:
2138
                    self.bzrdir.transport.delete(name)
2139
        else:
2123.2.1 by John Arbash Meinel
Fix bug #70716, make bzrlib.bzrdir directly import bzrlib.workingtree
2140
            from bzrlib.workingtree import WorkingTreeFormat3
1959.3.1 by John Arbash Meinel
David Allouche: bzr upgrade should work if there is no working tree
2141
            self.step('Upgrading working tree')
2142
            self.bzrdir.transport.mkdir('checkout', mode=self.dir_mode)
2143
            self.make_lock('checkout')
2144
            self.put_format(
2123.2.1 by John Arbash Meinel
Fix bug #70716, make bzrlib.bzrdir directly import bzrlib.workingtree
2145
                'checkout', WorkingTreeFormat3())
1959.3.1 by John Arbash Meinel
David Allouche: bzr upgrade should work if there is no working tree
2146
            self.bzrdir.transport.delete_multi(
2147
                self.garbage_inventories, self.pb)
2148
            for entry in checkout_files:
2149
                self.move_entry('checkout', entry)
2150
            if last_revision is not None:
2151
                self.bzrdir._control_files.put_utf8(
2152
                    'checkout/last-revision', last_revision)
2153
        self.bzrdir._control_files.put_utf8(
2154
            'branch-format', BzrDirMetaFormat1().get_format_string())
1534.5.10 by Robert Collins
Make upgrade driver unaware of the specific formats in play.
2155
        return BzrDir.open(self.bzrdir.root_transport.base)
2156
1534.5.11 by Robert Collins
Implement upgrades to Metaformat trees.
2157
    def make_lock(self, name):
2158
        """Make a lock for the new control dir name."""
2159
        self.step('Make %s lock' % name)
1996.3.3 by John Arbash Meinel
Shave off another 40ms by demand loading branch and bzrdir
2160
        ld = lockdir.LockDir(self.bzrdir.transport,
2161
                             '%s/lock' % name,
2162
                             file_modebits=self.file_mode,
2163
                             dir_modebits=self.dir_mode)
1553.5.79 by Martin Pool
upgrade to metadir should create LockDirs not files
2164
        ld.create()
1534.5.11 by Robert Collins
Implement upgrades to Metaformat trees.
2165
2166
    def move_entry(self, new_dir, entry):
2167
        """Move then entry name into new_dir."""
2168
        name = entry[0]
2169
        mandatory = entry[1]
2170
        self.step('Moving %s' % name)
2171
        try:
2172
            self.bzrdir.transport.move(name, '%s/%s' % (new_dir, name))
2173
        except errors.NoSuchFile:
2174
            if mandatory:
2175
                raise
2176
2177
    def put_format(self, dirname, format):
2178
        self.bzrdir._control_files.put_utf8('%s/format' % dirname, format.get_format_string())
2179
1556.1.4 by Robert Collins
Add a new format for what will become knit, and the surrounding logic to upgrade repositories within metadirs, and tests for the same.
2180
2181
class ConvertMetaToMeta(Converter):
2182
    """Converts the components of metadirs."""
2183
2184
    def __init__(self, target_format):
2185
        """Create a metadir to metadir converter.
2186
2187
        :param target_format: The final metadir format that is desired.
2188
        """
2189
        self.target_format = target_format
2190
2191
    def convert(self, to_convert, pb):
2192
        """See Converter.convert()."""
2193
        self.bzrdir = to_convert
2194
        self.pb = pb
2195
        self.count = 0
2196
        self.total = 1
2197
        self.step('checking repository format')
2198
        try:
2199
            repo = self.bzrdir.open_repository()
2200
        except errors.NoRepositoryPresent:
2201
            pass
2202
        else:
2203
            if not isinstance(repo._format, self.target_format.repository_format.__class__):
2204
                from bzrlib.repository import CopyConverter
2205
                self.pb.note('starting repository conversion')
2206
                converter = CopyConverter(self.target_format.repository_format)
2207
                converter.convert(repo, pb)
2230.3.29 by Aaron Bentley
Implement conversion to branch 6
2208
        try:
2209
            branch = self.bzrdir.open_branch()
2210
        except errors.NotBranchError:
2211
            pass
2212
        else:
2255.12.1 by Robert Collins
Implement upgrade for working trees.
2213
            # TODO: conversions of Branch and Tree should be done by
2214
            # InterXFormat lookups
2230.3.29 by Aaron Bentley
Implement conversion to branch 6
2215
            # Avoid circular imports
2216
            from bzrlib import branch as _mod_branch
2217
            if (branch._format.__class__ is _mod_branch.BzrBranchFormat5 and
2230.3.55 by Aaron Bentley
Updates from review
2218
                self.target_format.get_branch_format().__class__ is
2230.3.29 by Aaron Bentley
Implement conversion to branch 6
2219
                _mod_branch.BzrBranchFormat6):
2220
                branch_converter = _mod_branch.Converter5to6()
2221
                branch_converter.convert(branch)
2255.12.1 by Robert Collins
Implement upgrade for working trees.
2222
        try:
2323.6.4 by Martin Pool
BzrDir._check_supported now also takes care of recommending upgrades, which
2223
            tree = self.bzrdir.open_workingtree(recommend_upgrade=False)
2255.2.196 by Robert Collins
Fix test_upgrade defects related to non local or absent working trees.
2224
        except (errors.NoWorkingTree, errors.NotLocalUrl):
2255.12.1 by Robert Collins
Implement upgrade for working trees.
2225
            pass
2226
        else:
2227
            # TODO: conversions of Branch and Tree should be done by
2228
            # InterXFormat lookups
2229
            if (isinstance(tree, workingtree.WorkingTree3) and
2255.2.212 by Robert Collins
Fix upgrade bug exposed via repository tests, dont replace dirstate format trees during upgrade.
2230
                not isinstance(tree, workingtree_4.WorkingTree4) and
2255.12.1 by Robert Collins
Implement upgrade for working trees.
2231
                isinstance(self.target_format.workingtree_format,
2232
                    workingtree_4.WorkingTreeFormat4)):
2233
                workingtree_4.Converter3to4().convert(tree)
1556.1.4 by Robert Collins
Add a new format for what will become knit, and the surrounding logic to upgrade repositories within metadirs, and tests for the same.
2234
        return to_convert
1731.2.18 by Aaron Bentley
Get extract in repository under test
2235
2236
2018.5.25 by Andrew Bennetts
Make sure RemoteBzrDirFormat is always registered (John Arbash Meinel, Robert Collins, Andrew Bennetts).
2237
# This is not in remote.py because it's small, and needs to be registered.
2238
# Putting it in remote.py creates a circular import problem.
2018.5.28 by Robert Collins
Fix RemoteBzrDirFormat probe api usage.
2239
# we can make it a lazy object if the control formats is turned into something
2240
# like a registry.
2018.5.25 by Andrew Bennetts
Make sure RemoteBzrDirFormat is always registered (John Arbash Meinel, Robert Collins, Andrew Bennetts).
2241
class RemoteBzrDirFormat(BzrDirMetaFormat1):
2242
    """Format representing bzrdirs accessed via a smart server"""
2243
2244
    def get_format_description(self):
2245
        return 'bzr remote bzrdir'
2246
    
2018.5.28 by Robert Collins
Fix RemoteBzrDirFormat probe api usage.
2247
    @classmethod
2248
    def probe_transport(klass, transport):
2249
        """Return a RemoteBzrDirFormat object if it looks possible."""
2018.5.25 by Andrew Bennetts
Make sure RemoteBzrDirFormat is always registered (John Arbash Meinel, Robert Collins, Andrew Bennetts).
2250
        try:
2432.3.1 by Andrew Bennetts
Try a version 1 hello probe to determine if we can use RemoteBzrDir on a particular transport, allowing smooth interoperation with older servers.
2251
            client = transport.get_smart_client()
2018.5.25 by Andrew Bennetts
Make sure RemoteBzrDirFormat is always registered (John Arbash Meinel, Robert Collins, Andrew Bennetts).
2252
        except (NotImplementedError, AttributeError,
2253
                errors.TransportNotPossible):
2018.5.28 by Robert Collins
Fix RemoteBzrDirFormat probe api usage.
2254
            # no smart server, so not a branch for this format type.
2255
            raise errors.NotBranchError(path=transport.base)
2018.5.25 by Andrew Bennetts
Make sure RemoteBzrDirFormat is always registered (John Arbash Meinel, Robert Collins, Andrew Bennetts).
2256
        else:
2432.3.3 by Andrew Bennetts
Update comment according to Martin's suggestion.
2257
            # Send a 'hello' request in protocol version one, and decline to
2258
            # open it if the server doesn't support our required version (2) so
2259
            # that the VFS-based transport will do it.
2432.3.1 by Andrew Bennetts
Try a version 1 hello probe to determine if we can use RemoteBzrDir on a particular transport, allowing smooth interoperation with older servers.
2260
            request = client.get_request()
2261
            smart_protocol = protocol.SmartClientRequestProtocolOne(request)
2432.3.2 by Andrew Bennetts
Add test, and tidy implementation.
2262
            server_version = smart_protocol.query_version()
2263
            if server_version != 2:
2432.3.1 by Andrew Bennetts
Try a version 1 hello probe to determine if we can use RemoteBzrDir on a particular transport, allowing smooth interoperation with older servers.
2264
                raise errors.NotBranchError(path=transport.base)
2018.5.28 by Robert Collins
Fix RemoteBzrDirFormat probe api usage.
2265
            return klass()
2018.5.25 by Andrew Bennetts
Make sure RemoteBzrDirFormat is always registered (John Arbash Meinel, Robert Collins, Andrew Bennetts).
2266
2018.5.42 by Robert Collins
Various hopefully improvements, but wsgi is broken, handing over to spiv :).
2267
    def initialize_on_transport(self, transport):
2018.5.128 by Robert Collins
Have RemoteBzrDirFormat create a local format object when it is asked to initialize something on a non-smart transport - allowing sprout to work cleanly.
2268
        try:
2269
            # hand off the request to the smart server
2485.8.54 by Vincent Ladeuil
Refactor medium uses by making a distinction betweem shared and real medium.
2270
            shared_medium = transport.get_shared_medium()
2018.5.128 by Robert Collins
Have RemoteBzrDirFormat create a local format object when it is asked to initialize something on a non-smart transport - allowing sprout to work cleanly.
2271
        except errors.NoSmartMedium:
2272
            # TODO: lookup the local format from a server hint.
2273
            local_dir_format = BzrDirMetaFormat1()
2274
            return local_dir_format.initialize_on_transport(transport)
2485.8.54 by Vincent Ladeuil
Refactor medium uses by making a distinction betweem shared and real medium.
2275
        client = _SmartClient(shared_medium)
2018.5.42 by Robert Collins
Various hopefully improvements, but wsgi is broken, handing over to spiv :).
2276
        path = client.remote_path_from_transport(transport)
2485.8.54 by Vincent Ladeuil
Refactor medium uses by making a distinction betweem shared and real medium.
2277
        response = _SmartClient(shared_medium).call('BzrDirFormat.initialize',
2278
                                                    path)
2018.5.52 by Wouter van Heyst
Provide more information when encountering unexpected responses from a smart
2279
        assert response[0] in ('ok', ), 'unexpected response code %s' % (response,)
2018.5.42 by Robert Collins
Various hopefully improvements, but wsgi is broken, handing over to spiv :).
2280
        return remote.RemoteBzrDir(transport)
2281
2018.5.25 by Andrew Bennetts
Make sure RemoteBzrDirFormat is always registered (John Arbash Meinel, Robert Collins, Andrew Bennetts).
2282
    def _open(self, transport):
2283
        return remote.RemoteBzrDir(transport)
2284
2285
    def __eq__(self, other):
2286
        if not isinstance(other, RemoteBzrDirFormat):
2287
            return False
2288
        return self.get_format_description() == other.get_format_description()
2289
2290
2018.5.163 by Andrew Bennetts
Deal with various review comments from Robert.
2291
BzrDirFormat.register_control_server_format(RemoteBzrDirFormat)
2018.5.45 by Andrew Bennetts
Merge from bzr.dev
2292
2293
2204.4.4 by Aaron Bentley
Use BzrDirFormatInfo to distinguish native and deprecated formats
2294
class BzrDirFormatInfo(object):
2295
1551.13.2 by Aaron Bentley
Hide dirstate-with-subtree format
2296
    def __init__(self, native, deprecated, hidden):
2204.4.4 by Aaron Bentley
Use BzrDirFormatInfo to distinguish native and deprecated formats
2297
        self.deprecated = deprecated
2298
        self.native = native
1551.13.2 by Aaron Bentley
Hide dirstate-with-subtree format
2299
        self.hidden = hidden
2204.4.4 by Aaron Bentley
Use BzrDirFormatInfo to distinguish native and deprecated formats
2300
2301
2204.4.1 by Aaron Bentley
Add 'formats' help topic
2302
class BzrDirFormatRegistry(registry.Registry):
2303
    """Registry of user-selectable BzrDir subformats.
2304
    
2305
    Differs from BzrDirFormat._control_formats in that it provides sub-formats,
2306
    e.g. BzrDirMeta1 with weave repository.  Also, it's more user-oriented.
2307
    """
2308
2255.2.158 by Martin Pool
Most of the integration of dirstate and subtree
2309
    def register_metadir(self, key,
2310
             repository_format, help, native=True, deprecated=False,
2311
             branch_format=None,
1551.13.2 by Aaron Bentley
Hide dirstate-with-subtree format
2312
             tree_format=None,
2313
             hidden=False):
2204.4.1 by Aaron Bentley
Add 'formats' help topic
2314
        """Register a metadir subformat.
2241.1.4 by Martin Pool
Moved old weave-based repository formats into bzrlib.repofmt.weaverepo.
2315
2316
        These all use a BzrDirMetaFormat1 bzrdir, but can be parameterized
2317
        by the Repository format.
2318
2255.2.158 by Martin Pool
Most of the integration of dirstate and subtree
2319
        :param repository_format: The fully-qualified repository format class
2320
            name as a string.
2321
        :param branch_format: Fully-qualified branch format class name as
2322
            a string.
2323
        :param tree_format: Fully-qualified tree format class name as
2324
            a string.
2204.4.1 by Aaron Bentley
Add 'formats' help topic
2325
        """
2326
        # This should be expanded to support setting WorkingTree and Branch
2327
        # formats, once BzrDirMetaFormat1 supports that.
2255.2.158 by Martin Pool
Most of the integration of dirstate and subtree
2328
        def _load(full_name):
2329
            mod_name, factory_name = full_name.rsplit('.', 1)
2241.1.21 by Martin Pool
Change register_metadir to take fully-qualified repository class name.
2330
            try:
2331
                mod = __import__(mod_name, globals(), locals(),
2255.2.158 by Martin Pool
Most of the integration of dirstate and subtree
2332
                        [factory_name])
2241.1.21 by Martin Pool
Change register_metadir to take fully-qualified repository class name.
2333
            except ImportError, e:
2255.2.158 by Martin Pool
Most of the integration of dirstate and subtree
2334
                raise ImportError('failed to load %s: %s' % (full_name, e))
2241.1.21 by Martin Pool
Change register_metadir to take fully-qualified repository class name.
2335
            try:
2255.2.158 by Martin Pool
Most of the integration of dirstate and subtree
2336
                factory = getattr(mod, factory_name)
2241.1.4 by Martin Pool
Moved old weave-based repository formats into bzrlib.repofmt.weaverepo.
2337
            except AttributeError:
2255.2.158 by Martin Pool
Most of the integration of dirstate and subtree
2338
                raise AttributeError('no factory %s in module %r'
2339
                    % (full_name, mod))
2340
            return factory()
2341
2342
        def helper():
2204.4.1 by Aaron Bentley
Add 'formats' help topic
2343
            bd = BzrDirMetaFormat1()
2230.3.1 by Aaron Bentley
Get branch6 creation working
2344
            if branch_format is not None:
2255.2.158 by Martin Pool
Most of the integration of dirstate and subtree
2345
                bd.set_branch_format(_load(branch_format))
2346
            if tree_format is not None:
2347
                bd.workingtree_format = _load(tree_format)
2348
            if repository_format is not None:
2349
                bd.repository_format = _load(repository_format)
2204.4.1 by Aaron Bentley
Add 'formats' help topic
2350
            return bd
1551.13.2 by Aaron Bentley
Hide dirstate-with-subtree format
2351
        self.register(key, helper, help, native, deprecated, hidden)
2204.4.1 by Aaron Bentley
Add 'formats' help topic
2352
1551.13.2 by Aaron Bentley
Hide dirstate-with-subtree format
2353
    def register(self, key, factory, help, native=True, deprecated=False,
2354
                 hidden=False):
2204.4.1 by Aaron Bentley
Add 'formats' help topic
2355
        """Register a BzrDirFormat factory.
2356
        
2357
        The factory must be a callable that takes one parameter: the key.
2358
        It must produce an instance of the BzrDirFormat when called.
2359
2360
        This function mainly exists to prevent the info object from being
2361
        supplied directly.
2362
        """
2204.4.4 by Aaron Bentley
Use BzrDirFormatInfo to distinguish native and deprecated formats
2363
        registry.Registry.register(self, key, factory, help, 
1551.13.2 by Aaron Bentley
Hide dirstate-with-subtree format
2364
            BzrDirFormatInfo(native, deprecated, hidden))
2204.4.1 by Aaron Bentley
Add 'formats' help topic
2365
2204.4.7 by Aaron Bentley
restore register_lazy, remove register_factory, other updates
2366
    def register_lazy(self, key, module_name, member_name, help, native=True,
1551.13.2 by Aaron Bentley
Hide dirstate-with-subtree format
2367
                      deprecated=False, hidden=False):
2204.4.7 by Aaron Bentley
restore register_lazy, remove register_factory, other updates
2368
        registry.Registry.register_lazy(self, key, module_name, member_name, 
1551.13.2 by Aaron Bentley
Hide dirstate-with-subtree format
2369
            help, BzrDirFormatInfo(native, deprecated, hidden))
2204.4.1 by Aaron Bentley
Add 'formats' help topic
2370
2371
    def set_default(self, key):
2372
        """Set the 'default' key to be a clone of the supplied key.
2373
        
2374
        This method must be called once and only once.
2375
        """
2204.4.4 by Aaron Bentley
Use BzrDirFormatInfo to distinguish native and deprecated formats
2376
        registry.Registry.register(self, 'default', self.get(key), 
2377
            self.get_help(key), info=self.get_info(key))
2204.4.1 by Aaron Bentley
Add 'formats' help topic
2378
2204.4.11 by Aaron Bentley
deprecate Repository.set_default_format, update upgrade tests
2379
    def set_default_repository(self, key):
2380
        """Set the FormatRegistry default and Repository default.
2381
        
2382
        This is a transitional method while Repository.set_default_format
2383
        is deprecated.
2384
        """
2385
        if 'default' in self:
2386
            self.remove('default')
2387
        self.set_default(key)
2388
        format = self.get('default')()
2389
        assert isinstance(format, BzrDirMetaFormat1)
2390
2204.4.1 by Aaron Bentley
Add 'formats' help topic
2391
    def make_bzrdir(self, key):
2204.4.7 by Aaron Bentley
restore register_lazy, remove register_factory, other updates
2392
        return self.get(key)()
2204.4.1 by Aaron Bentley
Add 'formats' help topic
2393
2394
    def help_topic(self, topic):
2395
        output = textwrap.dedent("""\
2396
            These formats can be used for creating branches, working trees, and
2397
            repositories.
2204.4.2 by Aaron Bentley
Tweak topic appearance
2398
2204.4.1 by Aaron Bentley
Add 'formats' help topic
2399
            """)
2711.2.4 by Martin Pool
Fix unbound variable error in BzrDirFormatRegistry.get_help (test order dependent)
2400
        default_realkey = None
2204.4.1 by Aaron Bentley
Add 'formats' help topic
2401
        default_help = self.get_help('default')
2402
        help_pairs = []
2403
        for key in self.keys():
2404
            if key == 'default':
2405
                continue
2406
            help = self.get_help(key)
2407
            if help == default_help:
2408
                default_realkey = key
2409
            else:
2410
                help_pairs.append((key, help))
2411
2204.4.4 by Aaron Bentley
Use BzrDirFormatInfo to distinguish native and deprecated formats
2412
        def wrapped(key, help, info):
2413
            if info.native:
2414
                help = '(native) ' + help
2666.1.1 by Ian Clatworthy
Bazaar User Reference generated from online help
2415
            return ':%s:\n%s\n\n' % (key, 
2204.4.1 by Aaron Bentley
Add 'formats' help topic
2416
                    textwrap.fill(help, initial_indent='    ', 
2417
                    subsequent_indent='    '))
2711.2.4 by Martin Pool
Fix unbound variable error in BzrDirFormatRegistry.get_help (test order dependent)
2418
        if default_realkey is not None:
2419
            output += wrapped(default_realkey, '(default) %s' % default_help,
2420
                              self.get_info('default'))
2204.4.4 by Aaron Bentley
Use BzrDirFormatInfo to distinguish native and deprecated formats
2421
        deprecated_pairs = []
2204.4.1 by Aaron Bentley
Add 'formats' help topic
2422
        for key, help in help_pairs:
2204.4.4 by Aaron Bentley
Use BzrDirFormatInfo to distinguish native and deprecated formats
2423
            info = self.get_info(key)
1551.13.2 by Aaron Bentley
Hide dirstate-with-subtree format
2424
            if info.hidden:
2425
                continue
2426
            elif info.deprecated:
2204.4.4 by Aaron Bentley
Use BzrDirFormatInfo to distinguish native and deprecated formats
2427
                deprecated_pairs.append((key, help))
2428
            else:
2429
                output += wrapped(key, help, info)
2430
        if len(deprecated_pairs) > 0:
2666.1.1 by Ian Clatworthy
Bazaar User Reference generated from online help
2431
            output += "Deprecated formats are shown below.\n\n"
2204.4.4 by Aaron Bentley
Use BzrDirFormatInfo to distinguish native and deprecated formats
2432
            for key, help in deprecated_pairs:
2433
                info = self.get_info(key)
2434
                output += wrapped(key, help, info)
2435
2204.4.1 by Aaron Bentley
Add 'formats' help topic
2436
        return output
2437
2438
2439
format_registry = BzrDirFormatRegistry()
2204.4.7 by Aaron Bentley
restore register_lazy, remove register_factory, other updates
2440
format_registry.register('weave', BzrDirFormat6,
2204.4.4 by Aaron Bentley
Use BzrDirFormatInfo to distinguish native and deprecated formats
2441
    'Pre-0.8 format.  Slower than knit and does not'
2241.1.6 by Martin Pool
Move Knit repositories into the submodule bzrlib.repofmt.knitrepo and
2442
    ' support checkouts or shared repositories.',
2443
    deprecated=True)
2444
format_registry.register_metadir('knit',
2241.1.21 by Martin Pool
Change register_metadir to take fully-qualified repository class name.
2445
    'bzrlib.repofmt.knitrepo.RepositoryFormatKnit1',
2255.12.1 by Robert Collins
Implement upgrade for working trees.
2446
    'Format using knits.  Recommended for interoperation with bzr <= 0.14.',
2447
    branch_format='bzrlib.branch.BzrBranchFormat5',
2255.2.199 by Robert Collins
Fix definition of knit format; typos are not good.
2448
    tree_format='bzrlib.workingtree.WorkingTreeFormat3')
2241.1.21 by Martin Pool
Change register_metadir to take fully-qualified repository class name.
2449
format_registry.register_metadir('metaweave',
2450
    'bzrlib.repofmt.weaverepo.RepositoryFormat7',
2230.3.30 by Aaron Bentley
Fix whitespace issues
2451
    'Transitional format in 0.8.  Slower than knit.',
2255.12.1 by Robert Collins
Implement upgrade for working trees.
2452
    branch_format='bzrlib.branch.BzrBranchFormat5',
2255.2.209 by Robert Collins
Remove circular imports in bzrdir format definitions.
2453
    tree_format='bzrlib.workingtree.WorkingTreeFormat3',
2204.4.4 by Aaron Bentley
Use BzrDirFormatInfo to distinguish native and deprecated formats
2454
    deprecated=True)
2255.12.1 by Robert Collins
Implement upgrade for working trees.
2455
format_registry.register_metadir('dirstate',
2456
    'bzrlib.repofmt.knitrepo.RepositoryFormatKnit1',
2457
    help='New in 0.15: Fast local operations. Compatible with bzr 0.8 and '
2458
        'above when accessed over the network.',
2459
    branch_format='bzrlib.branch.BzrBranchFormat5',
2255.2.209 by Robert Collins
Remove circular imports in bzrdir format definitions.
2460
    # this uses bzrlib.workingtree.WorkingTreeFormat4 because importing
2461
    # directly from workingtree_4 triggers a circular import.
2462
    tree_format='bzrlib.workingtree.WorkingTreeFormat4',
2255.12.1 by Robert Collins
Implement upgrade for working trees.
2463
    )
1551.13.1 by Aaron Bentley
Introduce dirstate-tags format
2464
format_registry.register_metadir('dirstate-tags',
2465
    'bzrlib.repofmt.knitrepo.RepositoryFormatKnit1',
2466
    help='New in 0.15: Fast local operations and improved scaling for '
1551.13.2 by Aaron Bentley
Hide dirstate-with-subtree format
2467
        'network operations. Additionally adds support for tags.'
2468
        ' Incompatible with bzr < 0.15.',
1551.13.1 by Aaron Bentley
Introduce dirstate-tags format
2469
    branch_format='bzrlib.branch.BzrBranchFormat6',
2470
    tree_format='bzrlib.workingtree.WorkingTreeFormat4',
2471
    )
2255.12.1 by Robert Collins
Implement upgrade for working trees.
2472
format_registry.register_metadir('dirstate-with-subtree',
2473
    'bzrlib.repofmt.knitrepo.RepositoryFormatKnit3',
2474
    help='New in 0.15: Fast local operations and improved scaling for '
2475
        'network operations. Additionally adds support for versioning nested '
2476
        'bzr branches. Incompatible with bzr < 0.15.',
2477
    branch_format='bzrlib.branch.BzrBranchFormat6',
2255.2.209 by Robert Collins
Remove circular imports in bzrdir format definitions.
2478
    tree_format='bzrlib.workingtree.WorkingTreeFormat4',
1551.13.2 by Aaron Bentley
Hide dirstate-with-subtree format
2479
    hidden=True,
2255.12.1 by Robert Collins
Implement upgrade for working trees.
2480
    )
2696.3.1 by Martin Pool
(broken) start switching format to dirstate-tags
2481
format_registry.set_default('dirstate-tags')