/brz/remove-bazaar

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