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