/brz/remove-bazaar

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