~bzr-pqm/bzr/bzr.dev

1553.5.48 by Martin Pool
Fix some LockableFiles deprecation warnings
1
# Copyright (C) 2005, 2006 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.
21
"""
22
1773.4.3 by Martin Pool
[merge] bzr.dev
23
# TODO: remove unittest dependency; put that stuff inside the test suite
24
1910.7.17 by Andrew Bennetts
Various cosmetic changes.
25
# TODO: The Format probe_transport seems a bit redundant with just trying to
26
# open the bzrdir. -- mbp
27
#
28
# TODO: Can we move specific formats into separate modules to make this file
29
# smaller?
30
1773.4.1 by Martin Pool
Add pyflakes makefile target; fix many warnings
31
from cStringIO import StringIO
1534.5.7 by Robert Collins
Start factoring out the upgrade policy logic.
32
import os
1996.3.3 by John Arbash Meinel
Shave off another 40ms by demand loading branch and bzrdir
33
34
from bzrlib.lazy_import import lazy_import
35
lazy_import(globals(), """
36
from copy import deepcopy
1773.4.1 by Martin Pool
Add pyflakes makefile target; fix many warnings
37
from stat import S_ISDIR
1996.3.3 by John Arbash Meinel
Shave off another 40ms by demand loading branch and bzrdir
38
import unittest
1534.4.39 by Robert Collins
Basic BzrDir support.
39
40
import bzrlib
1996.3.3 by John Arbash Meinel
Shave off another 40ms by demand loading branch and bzrdir
41
from bzrlib import (
42
    errors,
43
    lockable_files,
44
    lockdir,
1996.3.12 by John Arbash Meinel
Change how 'revision' is imported to avoid problems later
45
    revision as _mod_revision,
1996.3.3 by John Arbash Meinel
Shave off another 40ms by demand loading branch and bzrdir
46
    urlutils,
1996.3.6 by John Arbash Meinel
Find a few places that weren't importing their dependencies.
47
    xml4,
48
    xml5,
1996.3.3 by John Arbash Meinel
Shave off another 40ms by demand loading branch and bzrdir
49
    )
1534.5.7 by Robert Collins
Start factoring out the upgrade policy logic.
50
from bzrlib.osutils import (
1996.3.3 by John Arbash Meinel
Shave off another 40ms by demand loading branch and bzrdir
51
    safe_unicode,
52
    sha_strings,
53
    sha_string,
54
    )
1563.2.28 by Robert Collins
Add total_size to the revision_store api.
55
from bzrlib.store.revision.text import TextRevisionStore
1534.5.7 by Robert Collins
Start factoring out the upgrade policy logic.
56
from bzrlib.store.text import TextStore
1563.2.25 by Robert Collins
Merge in upstream.
57
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
58
from bzrlib.transactions import WriteTransaction
1685.1.45 by John Arbash Meinel
Moved url functions into bzrlib.urlutils
59
from bzrlib.transport import get_transport
1534.5.7 by Robert Collins
Start factoring out the upgrade policy logic.
60
from bzrlib.weave import Weave
1996.3.3 by John Arbash Meinel
Shave off another 40ms by demand loading branch and bzrdir
61
""")
62
63
from bzrlib.trace import mutter
64
from bzrlib.transport.local import LocalTransport
1534.4.39 by Robert Collins
Basic BzrDir support.
65
66
67
class BzrDir(object):
68
    """A .bzr control diretory.
69
    
70
    BzrDir instances let you create or open any of the things that can be
71
    found within .bzr - checkouts, branches and repositories.
72
    
1534.4.40 by Robert Collins
Add RepositoryFormats and allow bzrdir.open or create _repository to be used.
73
    transport
74
        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.
75
    root_transport
76
        a transport connected to the directory this bzr was opened from.
1534.4.39 by Robert Collins
Basic BzrDir support.
77
    """
78
1687.1.12 by Robert Collins
Hook in the full break-lock ui.
79
    def break_lock(self):
80
        """Invoke break_lock on the first object in the bzrdir.
81
82
        If there is a tree, the tree is opened and break_lock() called.
83
        Otherwise, branch is tried, and finally repository.
84
        """
85
        try:
86
            thing_to_unlock = self.open_workingtree()
87
        except (errors.NotLocalUrl, errors.NoWorkingTree):
88
            try:
89
                thing_to_unlock = self.open_branch()
90
            except errors.NotBranchError:
91
                try:
92
                    thing_to_unlock = self.open_repository()
93
                except errors.NoRepositoryPresent:
94
                    return
95
        thing_to_unlock.break_lock()
96
1534.5.16 by Robert Collins
Review feedback.
97
    def can_convert_format(self):
98
        """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.
99
        return True
100
1910.2.12 by Aaron Bentley
Implement knit repo format 2
101
    def check_conversion_target(self, target_format):
102
        target_repo_format = target_format.repository_format
103
        source_repo_format = self._format.repository_format
104
        source_repo_format.check_conversion_target(target_repo_format)
105
1596.2.1 by Robert Collins
Fix BzrDir.open_containing of unsupported branches.
106
    @staticmethod
107
    def _check_supported(format, allow_unsupported):
1534.4.44 by Robert Collins
Make a new BzrDir format that uses a versioned branch format in a branch/ subdirectory.
108
        """Check whether format is a supported format.
109
110
        If allow_unsupported is True, this is a no-op.
111
        """
112
        if not allow_unsupported and not format.is_supported():
1596.2.1 by Robert Collins
Fix BzrDir.open_containing of unsupported branches.
113
            # see open_downlevel to open legacy branches.
1740.5.6 by Martin Pool
Clean up many exception classes.
114
            raise errors.UnsupportedFormatError(format=format)
1534.4.44 by Robert Collins
Make a new BzrDir format that uses a versioned branch format in a branch/ subdirectory.
115
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.
116
    def clone(self, url, revision_id=None, basis=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.
117
        """Clone this bzrdir and its contents to url verbatim.
118
119
        If urls last component does not exist, it will be created.
120
121
        if revision_id is not None, then the clone operation may tune
122
            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.
123
        :param force_new_repo: Do not use a shared repository for the target 
124
                               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.
125
        """
126
        self._make_tail(url)
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.
127
        basis_repo, basis_branch, basis_tree = self._get_basis_components(basis)
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.
128
        result = self._format.initialize(url)
129
        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.
130
            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.
131
        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.
132
            local_repo = None
133
        if local_repo:
134
            # may need to copy content in
135
            if force_new_repo:
1707.1.1 by Robert Collins
Bugfixes to bzrdir.sprout and clone. Sprout was failing to reset the
136
                result_repo = local_repo.clone(
137
                    result,
138
                    revision_id=revision_id,
139
                    basis=basis_repo)
140
                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.
141
            else:
142
                try:
143
                    result_repo = result.find_repository()
144
                    # fetch content this dir needs.
145
                    if basis_repo:
146
                        # XXX FIXME RBC 20060214 need tests for this when the basis
147
                        # is incomplete
148
                        result_repo.fetch(basis_repo, revision_id=revision_id)
149
                    result_repo.fetch(local_repo, revision_id=revision_id)
150
                except errors.NoRepositoryPresent:
151
                    # needed to make one anyway.
1707.1.1 by Robert Collins
Bugfixes to bzrdir.sprout and clone. Sprout was failing to reset the
152
                    result_repo = local_repo.clone(
153
                        result,
154
                        revision_id=revision_id,
155
                        basis=basis_repo)
156
                    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.
157
        # 1 if there is a branch present
158
        #   make sure its content is available in the target repository
159
        #   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.
160
        try:
161
            self.open_branch().clone(result, revision_id=revision_id)
162
        except errors.NotBranchError:
163
            pass
164
        try:
165
            self.open_workingtree().clone(result, basis=basis_tree)
1508.1.19 by Robert Collins
Give format3 working trees their own last-revision marker.
166
        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.
167
            pass
168
        return result
169
170
    def _get_basis_components(self, basis):
171
        """Retrieve the basis components that are available at basis."""
172
        if basis is None:
173
            return None, None, None
174
        try:
175
            basis_tree = basis.open_workingtree()
176
            basis_branch = basis_tree.branch
177
            basis_repo = basis_branch.repository
178
        except (errors.NoWorkingTree, errors.NotLocalUrl):
179
            basis_tree = None
180
            try:
181
                basis_branch = basis.open_branch()
182
                basis_repo = basis_branch.repository
183
            except errors.NotBranchError:
184
                basis_branch = None
185
                try:
186
                    basis_repo = basis.open_repository()
187
                except errors.NoRepositoryPresent:
188
                    basis_repo = None
189
        return basis_repo, basis_branch, basis_tree
190
1685.1.61 by Martin Pool
[broken] Change BzrDir._make_tail to use urlutils.split
191
    # TODO: This should be given a Transport, and should chdir up; otherwise
192
    # 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.
193
    def _make_tail(self, url):
1685.1.61 by Martin Pool
[broken] Change BzrDir._make_tail to use urlutils.split
194
        head, tail = urlutils.split(url)
195
        if tail and tail != '.':
1996.3.3 by John Arbash Meinel
Shave off another 40ms by demand loading branch and bzrdir
196
            t = get_transport(head)
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.
197
            try:
1685.1.61 by Martin Pool
[broken] Change BzrDir._make_tail to use urlutils.split
198
                t.mkdir(tail)
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.
199
            except errors.FileExists:
200
                pass
201
1685.1.63 by Martin Pool
Small Transport fixups
202
    # TODO: Should take a Transport
1553.5.71 by Martin Pool
Change branch format 5 to use LockDirs, not transport locks
203
    @classmethod
204
    def create(cls, base):
1534.4.40 by Robert Collins
Add RepositoryFormats and allow bzrdir.open or create _repository to be used.
205
        """Create a new BzrDir at the url 'base'.
1534.4.39 by Robert Collins
Basic BzrDir support.
206
        
207
        This will call the current default formats initialize with base
208
        as the only parameter.
209
210
        If you need a specific format, consider creating an instance
211
        of that and calling initialize().
212
        """
1553.5.71 by Martin Pool
Change branch format 5 to use LockDirs, not transport locks
213
        if cls is not BzrDir:
214
            raise AssertionError("BzrDir.create always creates the default format, "
215
                    "not one of %r" % cls)
1685.1.62 by Martin Pool
[broken] Change BzrDir.create to use urlutils.split
216
        head, tail = urlutils.split(base)
217
        if tail and tail != '.':
1996.3.3 by John Arbash Meinel
Shave off another 40ms by demand loading branch and bzrdir
218
            t = get_transport(head)
1534.4.41 by Robert Collins
Branch now uses BzrDir reasonably sanely.
219
            try:
1685.1.62 by Martin Pool
[broken] Change BzrDir.create to use urlutils.split
220
                t.mkdir(tail)
1534.4.41 by Robert Collins
Branch now uses BzrDir reasonably sanely.
221
            except errors.FileExists:
222
                pass
1534.4.39 by Robert Collins
Basic BzrDir support.
223
        return BzrDirFormat.get_default_format().initialize(safe_unicode(base))
224
1534.4.41 by Robert Collins
Branch now uses BzrDir reasonably sanely.
225
    def create_branch(self):
226
        """Create a branch in this BzrDir.
227
228
        The bzrdirs format will control what branch format is created.
229
        For more control see BranchFormatXX.create(a_bzrdir).
230
        """
231
        raise NotImplementedError(self.create_branch)
232
233
    @staticmethod
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.
234
    def create_branch_and_repo(base, force_new_repo=False):
1534.4.41 by Robert Collins
Branch now uses BzrDir reasonably sanely.
235
        """Create a new BzrDir, Branch and Repository at the url 'base'.
236
237
        This will use the current default BzrDirFormat, and use whatever 
238
        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.
239
        create_repository. If a shared repository is available that is used
240
        preferentially.
1534.4.41 by Robert Collins
Branch now uses BzrDir reasonably sanely.
241
242
        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.
243
244
        :param base: The URL to create the branch at.
245
        :param force_new_repo: If True a new repository is always created.
1534.4.41 by Robert Collins
Branch now uses BzrDir reasonably sanely.
246
        """
247
        bzrdir = BzrDir.create(base)
1534.6.11 by Robert Collins
Review feedback.
248
        bzrdir._find_or_create_repository(force_new_repo)
1534.4.41 by Robert Collins
Branch now uses BzrDir reasonably sanely.
249
        return bzrdir.create_branch()
1534.6.11 by Robert Collins
Review feedback.
250
251
    def _find_or_create_repository(self, force_new_repo):
252
        """Create a new repository if needed, returning the repository."""
253
        if force_new_repo:
254
            return self.create_repository()
255
        try:
256
            return self.find_repository()
257
        except errors.NoRepositoryPresent:
258
            return self.create_repository()
1534.4.41 by Robert Collins
Branch now uses BzrDir reasonably sanely.
259
        
1534.4.40 by Robert Collins
Add RepositoryFormats and allow bzrdir.open or create _repository to be used.
260
    @staticmethod
1558.5.3 by Aaron Bentley
Init command can produce sharing branches
261
    def create_branch_convenience(base, force_new_repo=False,
262
                                  force_new_tree=None, format=None):
1534.6.10 by Robert Collins
Finish use of repositories support.
263
        """Create a new BzrDir, Branch and Repository at the url 'base'.
264
265
        This is a convenience function - it will use an existing repository
266
        if possible, can be told explicitly whether to create a working tree or
1534.6.12 by Robert Collins
Typo found by John Meinel.
267
        not.
1534.6.10 by Robert Collins
Finish use of repositories support.
268
269
        This will use the current default BzrDirFormat, and use whatever 
270
        repository format that that uses via bzrdir.create_branch and
271
        create_repository. If a shared repository is available that is used
272
        preferentially. Whatever repository is used, its tree creation policy
273
        is followed.
274
275
        The created Branch object is returned.
276
        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.
277
        no error is raised unless force_new_tree is True, in which case no 
278
        data is created on disk and NotLocalUrl is raised.
1534.6.10 by Robert Collins
Finish use of repositories support.
279
280
        :param base: The URL to create the branch at.
281
        :param force_new_repo: If True a new repository is always created.
282
        :param force_new_tree: If True or False force creation of a tree or 
283
                               prevent such creation respectively.
1558.5.3 by Aaron Bentley
Init command can produce sharing branches
284
        :param format: Override for the for the bzrdir format to create
1534.6.10 by Robert Collins
Finish use of repositories support.
285
        """
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.
286
        if force_new_tree:
287
            # check for non local urls
288
            t = get_transport(safe_unicode(base))
289
            if not isinstance(t, LocalTransport):
290
                raise errors.NotLocalUrl(base)
1558.5.3 by Aaron Bentley
Init command can produce sharing branches
291
        if format is None:
292
            bzrdir = BzrDir.create(base)
293
        else:
294
            bzrdir = format.initialize(base)
1534.6.11 by Robert Collins
Review feedback.
295
        repo = bzrdir._find_or_create_repository(force_new_repo)
1534.6.10 by Robert Collins
Finish use of repositories support.
296
        result = bzrdir.create_branch()
297
        if force_new_tree or (repo.make_working_trees() and 
298
                              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.
299
            try:
300
                bzrdir.create_workingtree()
301
            except errors.NotLocalUrl:
302
                pass
1534.6.10 by Robert Collins
Finish use of repositories support.
303
        return result
1551.8.4 by Aaron Bentley
Tweak import style
304
        
1551.8.2 by Aaron Bentley
Add create_checkout_convenience
305
    @staticmethod
1534.6.1 by Robert Collins
allow API creation of shared repositories
306
    def create_repository(base, shared=False):
1534.4.40 by Robert Collins
Add RepositoryFormats and allow bzrdir.open or create _repository to be used.
307
        """Create a new BzrDir and Repository at the url 'base'.
308
309
        This will use the current default BzrDirFormat, and use whatever 
310
        repository format that that uses for bzrdirformat.create_repository.
311
1910.7.17 by Andrew Bennetts
Various cosmetic changes.
312
        :param shared: Create a shared repository rather than a standalone
1534.6.1 by Robert Collins
allow API creation of shared repositories
313
                       repository.
1534.4.40 by Robert Collins
Add RepositoryFormats and allow bzrdir.open or create _repository to be used.
314
        The Repository object is returned.
315
316
        This must be overridden as an instance method in child classes, where
317
        it should take no parameters and construct whatever repository format
318
        that child class desires.
319
        """
320
        bzrdir = BzrDir.create(base)
1841.2.1 by Jelmer Vernooij
Fix handling of `shared' parameter in BzrDir.create_repository().
321
        return bzrdir.create_repository(shared)
1534.4.40 by Robert Collins
Add RepositoryFormats and allow bzrdir.open or create _repository to be used.
322
1534.4.42 by Robert Collins
add working tree to the BzrDir facilities.
323
    @staticmethod
324
    def create_standalone_workingtree(base):
325
        """Create a new BzrDir, WorkingTree, Branch and Repository at 'base'.
326
327
        'base' must be a local path or a file:// url.
328
329
        This will use the current default BzrDirFormat, and use whatever 
330
        repository format that that uses for bzrdirformat.create_workingtree,
331
        create_branch and create_repository.
332
1910.7.17 by Andrew Bennetts
Various cosmetic changes.
333
        :return: The WorkingTree object.
1534.4.42 by Robert Collins
add working tree to the BzrDir facilities.
334
        """
1534.4.46 by Robert Collins
Nearly complete .bzr/checkout splitout.
335
        t = get_transport(safe_unicode(base))
1534.4.42 by Robert Collins
add working tree to the BzrDir facilities.
336
        if not isinstance(t, LocalTransport):
337
            raise errors.NotLocalUrl(base)
1534.6.10 by Robert Collins
Finish use of repositories support.
338
        bzrdir = BzrDir.create_branch_and_repo(safe_unicode(base),
339
                                               force_new_repo=True).bzrdir
1534.4.42 by Robert Collins
add working tree to the BzrDir facilities.
340
        return bzrdir.create_workingtree()
341
1508.1.21 by Robert Collins
Implement -r limit for checkout command.
342
    def create_workingtree(self, revision_id=None):
343
        """Create a working tree at this BzrDir.
344
        
345
        revision_id: create it as of this revision id.
346
        """
1534.4.42 by Robert Collins
add working tree to the BzrDir facilities.
347
        raise NotImplementedError(self.create_workingtree)
348
1551.8.37 by Aaron Bentley
Cleaner implementation of destroy_working_tree
349
    def destroy_workingtree(self):
1551.8.36 by Aaron Bentley
Introduce BzrDir.destroy_workingtree
350
        """Destroy the working tree at this BzrDir.
351
352
        Formats that do not support this may raise UnsupportedOperation.
353
        """
354
        raise NotImplementedError(self.destroy_workingtree)
355
1551.8.37 by Aaron Bentley
Cleaner implementation of destroy_working_tree
356
    def destroy_workingtree_metadata(self):
357
        """Destroy the control files for the working tree at this BzrDir.
358
359
        The contents of working tree files are not affected.
360
        Formats that do not support this may raise UnsupportedOperation.
361
        """
362
        raise NotImplementedError(self.destroy_workingtree_metadata)
363
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.
364
    def find_repository(self):
365
        """Find the repository that should be used for a_bzrdir.
366
367
        This does not require a branch as we use it to find the repo for
368
        new branches as well as to hook existing branches up to their
369
        repository.
370
        """
371
        try:
372
            return self.open_repository()
373
        except errors.NoRepositoryPresent:
374
            pass
375
        next_transport = self.root_transport.clone('..')
376
        while True:
1725.2.5 by Robert Collins
Bugfix create_branch_convenience at the root of a file system to not loop
377
            # 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.
378
            try:
1534.6.11 by Robert Collins
Review feedback.
379
                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.
380
                    next_transport)[0]
381
            except errors.NotBranchError:
1725.2.5 by Robert Collins
Bugfix create_branch_convenience at the root of a file system to not loop
382
                # 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.
383
                raise errors.NoRepositoryPresent(self)
1725.2.5 by Robert Collins
Bugfix create_branch_convenience at the root of a file system to not loop
384
            # 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.
385
            try:
386
                repository = found_bzrdir.open_repository()
387
            except errors.NoRepositoryPresent:
388
                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
389
                if (found_bzrdir.root_transport.base == next_transport.base):
390
                    # top of the file system
391
                    break
392
                else:
393
                    continue
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.
394
            if ((found_bzrdir.root_transport.base == 
395
                 self.root_transport.base) or repository.is_shared()):
396
                return repository
397
            else:
398
                raise errors.NoRepositoryPresent(self)
399
        raise errors.NoRepositoryPresent(self)
400
1534.4.44 by Robert Collins
Make a new BzrDir format that uses a versioned branch format in a branch/ subdirectory.
401
    def get_branch_transport(self, branch_format):
402
        """Get the transport for use by branch format in this BzrDir.
403
404
        Note that bzr dirs that do not support format strings will raise
405
        IncompatibleFormat if the branch format they are given has
1759.2.1 by Jelmer Vernooij
Fix some types (found using aspell).
406
        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.
407
408
        If branch_format is None, the transport is returned with no 
409
        checking. if it is not None, then the returned transport is
410
        guaranteed to point to an existing directory ready for use.
411
        """
412
        raise NotImplementedError(self.get_branch_transport)
413
        
1534.4.47 by Robert Collins
Split out repository into .bzr/repository
414
    def get_repository_transport(self, repository_format):
415
        """Get the transport for use by repository format in this BzrDir.
416
417
        Note that bzr dirs that do not support format strings will raise
418
        IncompatibleFormat if the repository format they are given has
1759.2.1 by Jelmer Vernooij
Fix some types (found using aspell).
419
        a format string, and vice versa.
1534.4.47 by Robert Collins
Split out repository into .bzr/repository
420
421
        If repository_format is None, the transport is returned with no 
422
        checking. if it is not None, then the returned transport is
423
        guaranteed to point to an existing directory ready for use.
424
        """
425
        raise NotImplementedError(self.get_repository_transport)
426
        
1534.4.53 by Robert Collins
Review feedback from John Meinel.
427
    def get_workingtree_transport(self, tree_format):
1534.4.45 by Robert Collins
Start WorkingTree -> .bzr/checkout transition
428
        """Get the transport for use by workingtree format in this BzrDir.
429
430
        Note that bzr dirs that do not support format strings will raise
431
        IncompatibleFormat if the workingtree format they are given has
1759.2.1 by Jelmer Vernooij
Fix some types (found using aspell).
432
        a format string, and vice versa.
1534.4.45 by Robert Collins
Start WorkingTree -> .bzr/checkout transition
433
434
        If workingtree_format is None, the transport is returned with no 
435
        checking. if it is not None, then the returned transport is
436
        guaranteed to point to an existing directory ready for use.
437
        """
438
        raise NotImplementedError(self.get_workingtree_transport)
439
        
1534.4.39 by Robert Collins
Basic BzrDir support.
440
    def __init__(self, _transport, _format):
441
        """Initialize a Bzr control dir object.
442
        
443
        Only really common logic should reside here, concrete classes should be
444
        made with varying behaviours.
445
1534.4.53 by Robert Collins
Review feedback from John Meinel.
446
        :param _format: the format that is creating this BzrDir instance.
447
        :param _transport: the transport this dir is based at.
1534.4.39 by Robert Collins
Basic BzrDir support.
448
        """
449
        self._format = _format
1534.4.41 by Robert Collins
Branch now uses BzrDir reasonably sanely.
450
        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.
451
        self.root_transport = _transport
1534.4.39 by Robert Collins
Basic BzrDir support.
452
1713.1.9 by Robert Collins
Paired performance tuning of bzr add. (Robert Collins, Martin Pool).
453
    def is_control_filename(self, filename):
454
        """True if filename is the name of a path which is reserved for bzrdir's.
455
        
456
        :param filename: A filename within the root transport of this bzrdir.
457
458
        This is true IF and ONLY IF the filename is part of the namespace reserved
459
        for bzr control dirs. Currently this is the '.bzr' directory in the root
460
        of the root_transport. it is expected that plugins will need to extend
461
        this in the future - for instance to make bzr talk with svn working
462
        trees.
463
        """
464
        # this might be better on the BzrDirFormat class because it refers to 
465
        # all the possible bzrdir disk formats. 
466
        # This method is tested via the workingtree is_control_filename tests- 
1759.2.1 by Jelmer Vernooij
Fix some types (found using aspell).
467
        # it was extracted from WorkingTree.is_control_filename. If the methods
1713.1.9 by Robert Collins
Paired performance tuning of bzr add. (Robert Collins, Martin Pool).
468
        # contract is extended beyond the current trivial  implementation please
469
        # add new tests for it to the appropriate place.
470
        return filename == '.bzr' or filename.startswith('.bzr/')
471
1534.5.16 by Robert Collins
Review feedback.
472
    def needs_format_conversion(self, format=None):
473
        """Return true if this bzrdir needs convert_format run on it.
1534.5.7 by Robert Collins
Start factoring out the upgrade policy logic.
474
        
475
        For instance, if the repository format is out of date but the 
476
        branch and working tree are not, this should return True.
1534.5.13 by Robert Collins
Correct buggy test.
477
478
        :param format: Optional parameter indicating a specific desired
1534.5.16 by Robert Collins
Review feedback.
479
                       format we plan to arrive at.
1534.5.7 by Robert Collins
Start factoring out the upgrade policy logic.
480
        """
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.
481
        raise NotImplementedError(self.needs_format_conversion)
1534.5.7 by Robert Collins
Start factoring out the upgrade policy logic.
482
1534.4.39 by Robert Collins
Basic BzrDir support.
483
    @staticmethod
484
    def open_unsupported(base):
485
        """Open a branch which is not supported."""
486
        return BzrDir.open(base, _unsupported=True)
487
        
488
    @staticmethod
489
    def open(base, _unsupported=False):
1534.4.53 by Robert Collins
Review feedback from John Meinel.
490
        """Open an existing bzrdir, rooted at 'base' (url)
1534.4.39 by Robert Collins
Basic BzrDir support.
491
        
492
        _unsupported is a private parameter to the BzrDir class.
493
        """
494
        t = get_transport(base)
1910.11.1 by Andrew Bennetts
Add BzrDir.open_from_transport, refactored from duplicate code, no explicit tests.
495
        return BzrDir.open_from_transport(t, _unsupported=_unsupported)
496
497
    @staticmethod
498
    def open_from_transport(transport, _unsupported=False):
499
        """Open a bzrdir within a particular directory.
500
501
        :param transport: Transport containing the bzrdir.
502
        :param _unsupported: private.
503
        """
504
        format = BzrDirFormat.find_format(transport)
1596.2.1 by Robert Collins
Fix BzrDir.open_containing of unsupported branches.
505
        BzrDir._check_supported(format, _unsupported)
1910.11.1 by Andrew Bennetts
Add BzrDir.open_from_transport, refactored from duplicate code, no explicit tests.
506
        return format.open(transport, _found=True)
1534.4.41 by Robert Collins
Branch now uses BzrDir reasonably sanely.
507
1534.4.44 by Robert Collins
Make a new BzrDir format that uses a versioned branch format in a branch/ subdirectory.
508
    def open_branch(self, unsupported=False):
1534.4.41 by Robert Collins
Branch now uses BzrDir reasonably sanely.
509
        """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.
510
511
        If unsupported is True, then no longer supported branch formats can
512
        still be opened.
1534.4.41 by Robert Collins
Branch now uses BzrDir reasonably sanely.
513
        
514
        TODO: static convenience version of this?
515
        """
516
        raise NotImplementedError(self.open_branch)
1534.4.39 by Robert Collins
Basic BzrDir support.
517
518
    @staticmethod
519
    def open_containing(url):
520
        """Open an existing branch which contains url.
521
        
1534.6.3 by Robert Collins
find_repository sufficiently robust.
522
        :param url: url to search from.
1534.6.11 by Robert Collins
Review feedback.
523
        See open_containing_from_transport for more detail.
1534.6.3 by Robert Collins
find_repository sufficiently robust.
524
        """
1534.6.11 by Robert Collins
Review feedback.
525
        return BzrDir.open_containing_from_transport(get_transport(url))
1534.6.3 by Robert Collins
find_repository sufficiently robust.
526
    
527
    @staticmethod
1534.6.11 by Robert Collins
Review feedback.
528
    def open_containing_from_transport(a_transport):
1534.6.3 by Robert Collins
find_repository sufficiently robust.
529
        """Open an existing branch which contains a_transport.base
530
531
        This probes for a branch at a_transport, and searches upwards from there.
1534.4.39 by Robert Collins
Basic BzrDir support.
532
533
        Basically we keep looking up until we find the control directory or
534
        run into the root.  If there isn't one, raises NotBranchError.
535
        If there is one and it is either an unrecognised format or an unsupported 
536
        format, UnknownFormatError or UnsupportedFormatError are raised.
537
        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
538
1685.1.28 by John Arbash Meinel
Changing open_containing to always return a unicode path.
539
        :return: The BzrDir that contains the path, and a Unicode path 
540
                for the rest of the URL.
1534.4.39 by Robert Collins
Basic BzrDir support.
541
        """
542
        # this gets the normalised url back. I.e. '.' -> the full path.
1534.6.3 by Robert Collins
find_repository sufficiently robust.
543
        url = a_transport.base
1534.4.39 by Robert Collins
Basic BzrDir support.
544
        while True:
545
            try:
1910.11.1 by Andrew Bennetts
Add BzrDir.open_from_transport, refactored from duplicate code, no explicit tests.
546
                result = BzrDir.open_from_transport(a_transport)
547
                return result, urlutils.unescape(a_transport.relpath(url))
1534.4.39 by Robert Collins
Basic BzrDir support.
548
            except errors.NotBranchError, e:
1685.1.60 by Martin Pool
[broken] NotBranchError should unescape the url if possible
549
                pass
1534.6.3 by Robert Collins
find_repository sufficiently robust.
550
            new_t = a_transport.clone('..')
551
            if new_t.base == a_transport.base:
1534.4.39 by Robert Collins
Basic BzrDir support.
552
                # reached the root, whatever that may be
553
                raise errors.NotBranchError(path=url)
1534.6.3 by Robert Collins
find_repository sufficiently robust.
554
            a_transport = new_t
1534.4.39 by Robert Collins
Basic BzrDir support.
555
1534.4.47 by Robert Collins
Split out repository into .bzr/repository
556
    def open_repository(self, _unsupported=False):
1534.4.40 by Robert Collins
Add RepositoryFormats and allow bzrdir.open or create _repository to be used.
557
        """Open the repository object at this BzrDir if one is present.
1534.4.47 by Robert Collins
Split out repository into .bzr/repository
558
559
        This will not follow the Branch object pointer - its strictly a direct
560
        open facility. Most client code should use open_branch().repository to
561
        get at a repository.
562
563
        _unsupported is 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.
564
        TODO: static convenience version of this?
565
        """
566
        raise NotImplementedError(self.open_repository)
567
1534.4.46 by Robert Collins
Nearly complete .bzr/checkout splitout.
568
    def open_workingtree(self, _unsupported=False):
1534.4.42 by Robert Collins
add working tree to the BzrDir facilities.
569
        """Open the workingtree object at this BzrDir if one is present.
570
        
571
        TODO: static convenience version of this?
572
        """
573
        raise NotImplementedError(self.open_workingtree)
574
1662.1.19 by Martin Pool
Better error message when initting existing tree
575
    def has_branch(self):
576
        """Tell if this bzrdir contains a branch.
577
        
578
        Note: if you're going to open the branch, you should just go ahead
579
        and try, and not ask permission first.  (This method just opens the 
580
        branch and discards it, and that's somewhat expensive.) 
581
        """
582
        try:
583
            self.open_branch()
584
            return True
585
        except errors.NotBranchError:
586
            return False
587
588
    def has_workingtree(self):
589
        """Tell if this bzrdir contains a working tree.
590
591
        This will still raise an exception if the bzrdir has a workingtree that
592
        is remote & inaccessible.
593
        
594
        Note: if you're going to open the working tree, you should just go ahead
595
        and try, and not ask permission first.  (This method just opens the 
596
        workingtree and discards it, and that's somewhat expensive.) 
597
        """
598
        try:
599
            self.open_workingtree()
600
            return True
601
        except errors.NoWorkingTree:
602
            return False
603
1910.2.41 by Aaron Bentley
Clean up clone format creation
604
    def cloning_metadir(self, basis=None):
605
        """Produce a metadir suitable for cloning with"""
606
        def related_repository(bzrdir):
607
            try:
608
                branch = bzrdir.open_branch()
609
                return branch.repository
610
            except errors.NotBranchError:
611
                source_branch = None
612
                return bzrdir.open_repository()
613
        result_format = self._format.__class__()
614
        try:
615
            try:
616
                source_repository = related_repository(self)
617
            except errors.NoRepositoryPresent:
618
                if basis is None:
619
                    raise
620
                source_repository = related_repository(self)
621
            result_format.repository_format = source_repository._format
622
        except errors.NoRepositoryPresent:
623
            pass
624
        return result_format
625
1534.6.9 by Robert Collins
sprouting into shared repositories
626
    def sprout(self, url, revision_id=None, basis=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.
627
        """Create a copy of this bzrdir prepared for use as a new line of
628
        development.
629
630
        If urls last component does not exist, it will be created.
631
632
        Attributes related to the identity of the source branch like
633
        branch nickname will be cleaned, a working tree is created
634
        whether one existed before or not; and a local branch is always
635
        created.
636
637
        if revision_id is not None, then the clone operation may tune
638
            itself to download less data.
639
        """
640
        self._make_tail(url)
1910.2.41 by Aaron Bentley
Clean up clone format creation
641
        cloning_format = self.cloning_metadir(basis)
642
        result = cloning_format.initialize(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.
643
        basis_repo, basis_branch, basis_tree = self._get_basis_components(basis)
644
        try:
645
            source_branch = self.open_branch()
646
            source_repository = source_branch.repository
647
        except errors.NotBranchError:
648
            source_branch = None
649
            try:
650
                source_repository = self.open_repository()
651
            except errors.NoRepositoryPresent:
1534.6.9 by Robert Collins
sprouting into shared repositories
652
                # copy the entire basis one if there is one
653
                # but there is no 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.
654
                source_repository = basis_repo
1534.6.9 by Robert Collins
sprouting into shared repositories
655
        if force_new_repo:
656
            result_repo = None
657
        else:
658
            try:
659
                result_repo = result.find_repository()
660
            except errors.NoRepositoryPresent:
661
                result_repo = None
662
        if source_repository is None and result_repo is not None:
663
            pass
664
        elif source_repository is None and result_repo is None:
665
            # no repo available, make a new one
666
            result.create_repository()
667
        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
668
            # have source, and want to make a new target repo
1759.2.2 by Jelmer Vernooij
Revert some of my spelling fixes and fix some typos after review by Aaron.
669
            # we don't clone the repo because that preserves attributes
1707.1.1 by Robert Collins
Bugfixes to bzrdir.sprout and clone. Sprout was failing to reset the
670
            # like is_shared(), and we have not yet implemented a 
671
            # repository sprout().
672
            result_repo = result.create_repository()
673
        if result_repo is not None:
1534.6.9 by Robert Collins
sprouting into shared repositories
674
            # fetch needed content into target.
675
            if basis_repo:
676
                # XXX FIXME RBC 20060214 need tests for this when the basis
677
                # is incomplete
678
                result_repo.fetch(basis_repo, revision_id=revision_id)
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.
679
            if source_repository is not None:
680
                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.
681
        if source_branch is not None:
682
            source_branch.sprout(result, revision_id=revision_id)
683
        else:
684
            result.create_branch()
1685.1.20 by John Arbash Meinel
More changes to get 'bzr branch' and 'bzr pull' to work
685
        # TODO: jam 20060426 we probably need a test in here in the
686
        #       case that the newly sprouted branch is a remote one
1558.5.8 by Aaron Bentley
Bugfix when result_repo is None
687
        if result_repo is None or result_repo.make_working_trees():
1731.1.33 by Aaron Bentley
Revert no-special-root changes
688
            wt = result.create_workingtree()
689
            if wt.inventory.root is None:
690
                try:
691
                    wt.set_root_id(self.open_workingtree.get_root_id())
692
                except errors.NoWorkingTree:
693
                    pass
1534.4.50 by Robert Collins
Got the bzrdir api straightened out, plenty of refactoring to use it pending, but the api is up and running.
694
        return result
695
1534.4.40 by Robert Collins
Add RepositoryFormats and allow bzrdir.open or create _repository to be used.
696
1534.4.44 by Robert Collins
Make a new BzrDir format that uses a versioned branch format in a branch/ subdirectory.
697
class BzrDirPreSplitOut(BzrDir):
698
    """A common class for the all-in-one formats."""
699
1534.5.3 by Robert Collins
Make format 4/5/6 branches share a single LockableFiles instance across wt/branch/repository.
700
    def __init__(self, _transport, _format):
701
        """See BzrDir.__init__."""
702
        super(BzrDirPreSplitOut, self).__init__(_transport, _format)
1996.3.3 by John Arbash Meinel
Shave off another 40ms by demand loading branch and bzrdir
703
        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.
704
        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
705
        self._control_files = lockable_files.LockableFiles(
706
                                            self.get_branch_transport(None),
1553.5.69 by Martin Pool
BzrDirFormat subclasses can now control what kind of overall lock is used.
707
                                            self._format._lock_file_name,
708
                                            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.
709
1687.1.12 by Robert Collins
Hook in the full break-lock ui.
710
    def break_lock(self):
711
        """Pre-splitout bzrdirs do not suffer from stale locks."""
712
        raise NotImplementedError(self.break_lock)
713
1534.6.8 by Robert Collins
Test the use of clone on empty bzrdir with force_new_repo.
714
    def clone(self, url, revision_id=None, basis=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.
715
        """See BzrDir.clone()."""
716
        from bzrlib.workingtree import WorkingTreeFormat2
717
        self._make_tail(url)
1651.1.6 by Martin Pool
Clean up clone-bzrdir code
718
        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.
719
        basis_repo, basis_branch, basis_tree = self._get_basis_components(basis)
720
        self.open_repository().clone(result, revision_id=revision_id, basis=basis_repo)
1692.7.9 by Martin Pool
Don't create broken standalone branches over sftp (Malone #43064)
721
        from_branch = self.open_branch()
722
        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.
723
        try:
724
            self.open_workingtree().clone(result, basis=basis_tree)
725
        except errors.NotLocalUrl:
726
            # make a new one, this format always has to have one.
1563.2.38 by Robert Collins
make push preserve tree formats.
727
            try:
728
                WorkingTreeFormat2().initialize(result)
729
            except errors.NotLocalUrl:
1692.7.9 by Martin Pool
Don't create broken standalone branches over sftp (Malone #43064)
730
                # but we cannot do it for remote trees.
731
                to_branch = result.open_branch()
732
                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.
733
        return result
734
1534.4.44 by Robert Collins
Make a new BzrDir format that uses a versioned branch format in a branch/ subdirectory.
735
    def create_branch(self):
736
        """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.
737
        return self.open_branch()
738
1534.6.1 by Robert Collins
allow API creation of shared repositories
739
    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.
740
        """See BzrDir.create_repository."""
1534.6.1 by Robert Collins
allow API creation of shared repositories
741
        if shared:
742
            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.
743
        return self.open_repository()
744
1508.1.21 by Robert Collins
Implement -r limit for checkout command.
745
    def create_workingtree(self, revision_id=None):
1534.4.50 by Robert Collins
Got the bzrdir api straightened out, plenty of refactoring to use it pending, but the api is up and running.
746
        """See BzrDir.create_workingtree."""
1508.1.21 by Robert Collins
Implement -r limit for checkout command.
747
        # this looks buggy but is not -really-
748
        # clone and sprout will have set the revision_id
749
        # and that will have set it for us, its only
750
        # specific uses of create_workingtree in isolation
751
        # that can do wonky stuff here, and that only
752
        # happens for creating checkouts, which cannot be 
753
        # done on this format anyway. So - acceptable wart.
754
        result = self.open_workingtree()
1508.1.24 by Robert Collins
Add update command for use with checkouts.
755
        if revision_id is not None:
1996.3.12 by John Arbash Meinel
Change how 'revision' is imported to avoid problems later
756
            if revision_id == _mod_revision.NULL_REVISION:
1551.8.20 by Aaron Bentley
Fix BzrDir.create_workingtree for NULL_REVISION
757
                result.set_parent_ids([])
758
            else:
759
                result.set_parent_ids([revision_id])
1508.1.21 by Robert Collins
Implement -r limit for checkout command.
760
        return result
1534.4.44 by Robert Collins
Make a new BzrDir format that uses a versioned branch format in a branch/ subdirectory.
761
1551.8.37 by Aaron Bentley
Cleaner implementation of destroy_working_tree
762
    def destroy_workingtree(self):
1551.8.36 by Aaron Bentley
Introduce BzrDir.destroy_workingtree
763
        """See BzrDir.destroy_workingtree."""
764
        raise errors.UnsupportedOperation(self.destroy_workingtree, self)
765
1551.8.37 by Aaron Bentley
Cleaner implementation of destroy_working_tree
766
    def destroy_workingtree_metadata(self):
767
        """See BzrDir.destroy_workingtree_metadata."""
768
        raise errors.UnsupportedOperation(self.destroy_workingtree_metadata, 
769
                                          self)
770
1534.4.44 by Robert Collins
Make a new BzrDir format that uses a versioned branch format in a branch/ subdirectory.
771
    def get_branch_transport(self, branch_format):
772
        """See BzrDir.get_branch_transport()."""
773
        if branch_format is None:
774
            return self.transport
775
        try:
776
            branch_format.get_format_string()
777
        except NotImplementedError:
778
            return self.transport
779
        raise errors.IncompatibleFormat(branch_format, self._format)
780
1534.4.47 by Robert Collins
Split out repository into .bzr/repository
781
    def get_repository_transport(self, repository_format):
782
        """See BzrDir.get_repository_transport()."""
783
        if repository_format is None:
784
            return self.transport
785
        try:
786
            repository_format.get_format_string()
787
        except NotImplementedError:
788
            return self.transport
789
        raise errors.IncompatibleFormat(repository_format, self._format)
790
1534.4.45 by Robert Collins
Start WorkingTree -> .bzr/checkout transition
791
    def get_workingtree_transport(self, workingtree_format):
792
        """See BzrDir.get_workingtree_transport()."""
793
        if workingtree_format is None:
794
            return self.transport
795
        try:
796
            workingtree_format.get_format_string()
797
        except NotImplementedError:
798
            return self.transport
799
        raise errors.IncompatibleFormat(workingtree_format, self._format)
800
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.
801
    def needs_format_conversion(self, format=None):
802
        """See BzrDir.needs_format_conversion()."""
803
        # if the format is not the same as the system default,
804
        # an upgrade is needed.
805
        if format is None:
806
            format = BzrDirFormat.get_default_format()
807
        return not isinstance(self._format, format.__class__)
808
1534.4.44 by Robert Collins
Make a new BzrDir format that uses a versioned branch format in a branch/ subdirectory.
809
    def open_branch(self, unsupported=False):
810
        """See BzrDir.open_branch."""
811
        from bzrlib.branch import BzrBranchFormat4
812
        format = BzrBranchFormat4()
813
        self._check_supported(format, unsupported)
814
        return format.open(self, _found=True)
815
1910.4.15 by Robert Collins
Fix a minor bug in BzrDirPreSplitOut.sprout - it did not define the force_new_repo parameter - and we were not testing that it did or didn't until the test cleanup.
816
    def sprout(self, url, revision_id=None, basis=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.
817
        """See BzrDir.sprout()."""
818
        from bzrlib.workingtree import WorkingTreeFormat2
819
        self._make_tail(url)
1651.1.6 by Martin Pool
Clean up clone-bzrdir code
820
        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.
821
        basis_repo, basis_branch, basis_tree = self._get_basis_components(basis)
822
        try:
823
            self.open_repository().clone(result, revision_id=revision_id, basis=basis_repo)
824
        except errors.NoRepositoryPresent:
825
            pass
826
        try:
827
            self.open_branch().sprout(result, revision_id=revision_id)
828
        except errors.NotBranchError:
829
            pass
1587.1.5 by Robert Collins
Put bzr branch behaviour back to the 0.7 ignore-working-tree state.
830
        # we always want a working tree
831
        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.
832
        return result
833
1534.4.44 by Robert Collins
Make a new BzrDir format that uses a versioned branch format in a branch/ subdirectory.
834
835
class BzrDir4(BzrDirPreSplitOut):
1508.1.25 by Robert Collins
Update per review comments.
836
    """A .bzr version 4 control object.
837
    
838
    This is a deprecated format and may be removed after sept 2006.
839
    """
1534.4.40 by Robert Collins
Add RepositoryFormats and allow bzrdir.open or create _repository to be used.
840
1534.6.1 by Robert Collins
allow API creation of shared repositories
841
    def create_repository(self, shared=False):
1534.4.40 by Robert Collins
Add RepositoryFormats and allow bzrdir.open or create _repository to be used.
842
        """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.
843
        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.
844
1534.5.16 by Robert Collins
Review feedback.
845
    def needs_format_conversion(self, format=None):
846
        """Format 4 dirs are always in need of conversion."""
1534.5.7 by Robert Collins
Start factoring out the upgrade policy logic.
847
        return True
848
1534.4.40 by Robert Collins
Add RepositoryFormats and allow bzrdir.open or create _repository to be used.
849
    def open_repository(self):
850
        """See BzrDir.open_repository."""
851
        from bzrlib.repository import RepositoryFormat4
852
        return RepositoryFormat4().open(self, _found=True)
853
854
1534.4.44 by Robert Collins
Make a new BzrDir format that uses a versioned branch format in a branch/ subdirectory.
855
class BzrDir5(BzrDirPreSplitOut):
1508.1.25 by Robert Collins
Update per review comments.
856
    """A .bzr version 5 control object.
857
858
    This is a deprecated format and may be removed after sept 2006.
859
    """
1534.4.40 by Robert Collins
Add RepositoryFormats and allow bzrdir.open or create _repository to be used.
860
861
    def open_repository(self):
862
        """See BzrDir.open_repository."""
863
        from bzrlib.repository import RepositoryFormat5
864
        return RepositoryFormat5().open(self, _found=True)
865
1534.4.46 by Robert Collins
Nearly complete .bzr/checkout splitout.
866
    def open_workingtree(self, _unsupported=False):
1534.4.42 by Robert Collins
add working tree to the BzrDir facilities.
867
        """See BzrDir.create_workingtree."""
868
        from bzrlib.workingtree import WorkingTreeFormat2
869
        return WorkingTreeFormat2().open(self, _found=True)
870
1534.4.40 by Robert Collins
Add RepositoryFormats and allow bzrdir.open or create _repository to be used.
871
1534.4.44 by Robert Collins
Make a new BzrDir format that uses a versioned branch format in a branch/ subdirectory.
872
class BzrDir6(BzrDirPreSplitOut):
1508.1.25 by Robert Collins
Update per review comments.
873
    """A .bzr version 6 control object.
874
875
    This is a deprecated format and may be removed after sept 2006.
876
    """
1534.4.40 by Robert Collins
Add RepositoryFormats and allow bzrdir.open or create _repository to be used.
877
1534.4.44 by Robert Collins
Make a new BzrDir format that uses a versioned branch format in a branch/ subdirectory.
878
    def open_repository(self):
879
        """See BzrDir.open_repository."""
880
        from bzrlib.repository import RepositoryFormat6
881
        return RepositoryFormat6().open(self, _found=True)
882
1534.4.46 by Robert Collins
Nearly complete .bzr/checkout splitout.
883
    def open_workingtree(self, _unsupported=False):
1534.4.44 by Robert Collins
Make a new BzrDir format that uses a versioned branch format in a branch/ subdirectory.
884
        """See BzrDir.create_workingtree."""
885
        from bzrlib.workingtree import WorkingTreeFormat2
886
        return WorkingTreeFormat2().open(self, _found=True)
887
888
889
class BzrDirMeta1(BzrDir):
890
    """A .bzr meta version 1 control object.
891
    
892
    This is the first control object where the 
1553.5.67 by Martin Pool
doc
893
    individual aspects are really split out: there are separate repository,
894
    workingtree and branch subdirectories and any subset of the three can be
895
    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.
896
    """
897
1534.5.16 by Robert Collins
Review feedback.
898
    def can_convert_format(self):
899
        """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.
900
        return True
1534.5.10 by Robert Collins
Make upgrade driver unaware of the specific formats in play.
901
1534.4.41 by Robert Collins
Branch now uses BzrDir reasonably sanely.
902
    def create_branch(self):
903
        """See BzrDir.create_branch."""
1534.4.44 by Robert Collins
Make a new BzrDir format that uses a versioned branch format in a branch/ subdirectory.
904
        from bzrlib.branch import BranchFormat
905
        return BranchFormat.get_default_format().initialize(self)
1534.4.41 by Robert Collins
Branch now uses BzrDir reasonably sanely.
906
1534.6.1 by Robert Collins
allow API creation of shared repositories
907
    def create_repository(self, shared=False):
1534.4.40 by Robert Collins
Add RepositoryFormats and allow bzrdir.open or create _repository to be used.
908
        """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.
909
        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.
910
1508.1.21 by Robert Collins
Implement -r limit for checkout command.
911
    def create_workingtree(self, revision_id=None):
1534.4.42 by Robert Collins
add working tree to the BzrDir facilities.
912
        """See BzrDir.create_workingtree."""
1534.4.46 by Robert Collins
Nearly complete .bzr/checkout splitout.
913
        from bzrlib.workingtree import WorkingTreeFormat
1508.1.21 by Robert Collins
Implement -r limit for checkout command.
914
        return WorkingTreeFormat.get_default_format().initialize(self, revision_id)
1534.4.42 by Robert Collins
add working tree to the BzrDir facilities.
915
1551.8.37 by Aaron Bentley
Cleaner implementation of destroy_working_tree
916
    def destroy_workingtree(self):
1551.8.36 by Aaron Bentley
Introduce BzrDir.destroy_workingtree
917
        """See BzrDir.destroy_workingtree."""
918
        wt = self.open_workingtree()
1551.8.37 by Aaron Bentley
Cleaner implementation of destroy_working_tree
919
        repository = wt.branch.repository
920
        empty = repository.revision_tree(bzrlib.revision.NULL_REVISION)
921
        wt.revert([], old_tree=empty)
922
        self.destroy_workingtree_metadata()
923
924
    def destroy_workingtree_metadata(self):
925
        self.transport.delete_tree('checkout')
1551.8.36 by Aaron Bentley
Introduce BzrDir.destroy_workingtree
926
1666.1.4 by Robert Collins
* 'Metadir' is now the default disk format. This improves behaviour in
927
    def _get_mkdir_mode(self):
928
        """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
929
        temp_control = lockable_files.LockableFiles(self.transport, '',
930
                                     lockable_files.TransportLock)
1666.1.4 by Robert Collins
* 'Metadir' is now the default disk format. This improves behaviour in
931
        return temp_control._dir_mode
932
1534.4.44 by Robert Collins
Make a new BzrDir format that uses a versioned branch format in a branch/ subdirectory.
933
    def get_branch_transport(self, branch_format):
934
        """See BzrDir.get_branch_transport()."""
935
        if branch_format is None:
936
            return self.transport.clone('branch')
937
        try:
938
            branch_format.get_format_string()
939
        except NotImplementedError:
940
            raise errors.IncompatibleFormat(branch_format, self._format)
941
        try:
1666.1.4 by Robert Collins
* 'Metadir' is now the default disk format. This improves behaviour in
942
            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.
943
        except errors.FileExists:
944
            pass
945
        return self.transport.clone('branch')
946
1534.4.47 by Robert Collins
Split out repository into .bzr/repository
947
    def get_repository_transport(self, repository_format):
948
        """See BzrDir.get_repository_transport()."""
949
        if repository_format is None:
950
            return self.transport.clone('repository')
951
        try:
952
            repository_format.get_format_string()
953
        except NotImplementedError:
954
            raise errors.IncompatibleFormat(repository_format, self._format)
955
        try:
1666.1.4 by Robert Collins
* 'Metadir' is now the default disk format. This improves behaviour in
956
            self.transport.mkdir('repository', mode=self._get_mkdir_mode())
1534.4.47 by Robert Collins
Split out repository into .bzr/repository
957
        except errors.FileExists:
958
            pass
959
        return self.transport.clone('repository')
960
1534.4.45 by Robert Collins
Start WorkingTree -> .bzr/checkout transition
961
    def get_workingtree_transport(self, workingtree_format):
962
        """See BzrDir.get_workingtree_transport()."""
963
        if workingtree_format is None:
964
            return self.transport.clone('checkout')
965
        try:
966
            workingtree_format.get_format_string()
967
        except NotImplementedError:
968
            raise errors.IncompatibleFormat(workingtree_format, self._format)
969
        try:
1666.1.4 by Robert Collins
* 'Metadir' is now the default disk format. This improves behaviour in
970
            self.transport.mkdir('checkout', mode=self._get_mkdir_mode())
1534.4.45 by Robert Collins
Start WorkingTree -> .bzr/checkout transition
971
        except errors.FileExists:
972
            pass
973
        return self.transport.clone('checkout')
974
1534.5.16 by Robert Collins
Review feedback.
975
    def needs_format_conversion(self, format=None):
976
        """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.
977
        if format is None:
978
            format = BzrDirFormat.get_default_format()
979
        if not isinstance(self._format, format.__class__):
980
            # it is not a meta dir format, conversion is needed.
981
            return True
982
        # we might want to push this down to the repository?
983
        try:
984
            if not isinstance(self.open_repository()._format,
985
                              format.repository_format.__class__):
986
                # the repository needs an upgrade.
987
                return True
988
        except errors.NoRepositoryPresent:
989
            pass
990
        # currently there are no other possible conversions for meta1 formats.
1534.5.10 by Robert Collins
Make upgrade driver unaware of the specific formats in play.
991
        return False
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):
1534.4.41 by Robert Collins
Branch now uses BzrDir reasonably sanely.
994
        """See BzrDir.open_branch."""
1534.4.44 by Robert Collins
Make a new BzrDir format that uses a versioned branch format in a branch/ subdirectory.
995
        from bzrlib.branch import BranchFormat
996
        format = BranchFormat.find_format(self)
997
        self._check_supported(format, unsupported)
998
        return format.open(self, _found=True)
1534.4.41 by Robert Collins
Branch now uses BzrDir reasonably sanely.
999
1534.4.47 by Robert Collins
Split out repository into .bzr/repository
1000
    def open_repository(self, unsupported=False):
1534.4.40 by Robert Collins
Add RepositoryFormats and allow bzrdir.open or create _repository to be used.
1001
        """See BzrDir.open_repository."""
1534.4.47 by Robert Collins
Split out repository into .bzr/repository
1002
        from bzrlib.repository import RepositoryFormat
1003
        format = RepositoryFormat.find_format(self)
1004
        self._check_supported(format, unsupported)
1005
        return format.open(self, _found=True)
1534.4.40 by Robert Collins
Add RepositoryFormats and allow bzrdir.open or create _repository to be used.
1006
1534.4.46 by Robert Collins
Nearly complete .bzr/checkout splitout.
1007
    def open_workingtree(self, unsupported=False):
1508.1.21 by Robert Collins
Implement -r limit for checkout command.
1008
        """See BzrDir.open_workingtree."""
1534.4.46 by Robert Collins
Nearly complete .bzr/checkout splitout.
1009
        from bzrlib.workingtree import WorkingTreeFormat
1010
        format = WorkingTreeFormat.find_format(self)
1011
        self._check_supported(format, unsupported)
1012
        return format.open(self, _found=True)
1534.4.42 by Robert Collins
add working tree to the BzrDir facilities.
1013
1534.4.39 by Robert Collins
Basic BzrDir support.
1014
1015
class BzrDirFormat(object):
1016
    """An encapsulation of the initialization and open routines for a format.
1017
1018
    Formats provide three things:
1019
     * An initialization routine,
1020
     * a format string,
1021
     * an open routine.
1022
1023
    Formats are placed in an dict by their format string for reference 
1024
    during bzrdir opening. These should be subclasses of BzrDirFormat
1025
    for consistency.
1026
1027
    Once a format is deprecated, just deprecate the initialize and open
1028
    methods on the format class. Do not deprecate the object, as the 
1029
    object will be created every system load.
1030
    """
1031
1032
    _default_format = None
1534.4.40 by Robert Collins
Add RepositoryFormats and allow bzrdir.open or create _repository to be used.
1033
    """The default format used for new .bzr dirs."""
1534.4.39 by Robert Collins
Basic BzrDir support.
1034
1035
    _formats = {}
1036
    """The known formats."""
1037
1733.1.7 by Jelmer Vernooij
Change set of control dir formats to list.
1038
    _control_formats = []
1733.1.6 by Jelmer Vernooij
Fix a couple of minor issues after review by Martin.
1039
    """The registered control formats - .bzr, ....
1040
    
1733.1.7 by Jelmer Vernooij
Change set of control dir formats to list.
1041
    This is a list of BzrDirFormat objects.
1733.1.6 by Jelmer Vernooij
Fix a couple of minor issues after review by Martin.
1042
    """
1733.1.1 by Robert Collins
Support non '.bzr' control directories in bzrdir.
1043
1553.5.69 by Martin Pool
BzrDirFormat subclasses can now control what kind of overall lock is used.
1044
    _lock_file_name = 'branch-lock'
1045
1046
    # _lock_class must be set in subclasses to the lock type, typ.
1047
    # TransportLock or LockDir
1048
1534.4.39 by Robert Collins
Basic BzrDir support.
1049
    @classmethod
1050
    def find_format(klass, transport):
1733.1.1 by Robert Collins
Support non '.bzr' control directories in bzrdir.
1051
        """Return the format present at transport."""
1052
        for format in klass._control_formats:
1053
            try:
1054
                return format.probe_transport(transport)
1055
            except errors.NotBranchError:
1056
                # this format does not find a control dir here.
1057
                pass
1058
        raise errors.NotBranchError(path=transport.base)
1059
1060
    @classmethod
1061
    def probe_transport(klass, transport):
1062
        """Return the .bzrdir style transport present at URL."""
1534.4.39 by Robert Collins
Basic BzrDir support.
1063
        try:
1064
            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.
1065
        except errors.NoSuchFile:
1066
            raise errors.NotBranchError(path=transport.base)
1067
1068
        try:
1534.4.39 by Robert Collins
Basic BzrDir support.
1069
            return klass._formats[format_string]
1070
        except KeyError:
1740.5.6 by Martin Pool
Clean up many exception classes.
1071
            raise errors.UnknownFormatError(format=format_string)
1534.4.39 by Robert Collins
Basic BzrDir support.
1072
1073
    @classmethod
1074
    def get_default_format(klass):
1075
        """Return the current default format."""
1076
        return klass._default_format
1077
1078
    def get_format_string(self):
1079
        """Return the ASCII format string that identifies this format."""
1080
        raise NotImplementedError(self.get_format_string)
1081
1624.3.19 by Olaf Conradi
New call get_format_description to give a user-friendly description of a
1082
    def get_format_description(self):
1083
        """Return the short description for this format."""
1084
        raise NotImplementedError(self.get_format_description)
1085
1534.5.16 by Robert Collins
Review feedback.
1086
    def get_converter(self, format=None):
1087
        """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.
1088
1089
        This returns a bzrlib.bzrdir.Converter object.
1090
1091
        This should return the best upgrader to step this format towards the
1759.2.1 by Jelmer Vernooij
Fix some types (found using aspell).
1092
        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.
1093
        some means for them to extend the range of returnable converters.
1534.5.13 by Robert Collins
Correct buggy test.
1094
1759.2.1 by Jelmer Vernooij
Fix some types (found using aspell).
1095
        :param format: Optional format to override the default format of the 
1534.5.13 by Robert Collins
Correct buggy test.
1096
                       library.
1534.5.10 by Robert Collins
Make upgrade driver unaware of the specific formats in play.
1097
        """
1534.5.16 by Robert Collins
Review feedback.
1098
        raise NotImplementedError(self.get_converter)
1534.5.10 by Robert Collins
Make upgrade driver unaware of the specific formats in play.
1099
1651.1.6 by Martin Pool
Clean up clone-bzrdir code
1100
    def initialize(self, url):
1608.2.8 by Martin Pool
Separate out BzrDir.initialize_on_transport so it
1101
        """Create a bzr control dir at this url and return an opened copy.
1102
        
1103
        Subclasses should typically override initialize_on_transport
1104
        instead of this method.
1105
        """
1651.1.6 by Martin Pool
Clean up clone-bzrdir code
1106
        return self.initialize_on_transport(get_transport(url))
1608.2.8 by Martin Pool
Separate out BzrDir.initialize_on_transport so it
1107
1651.1.6 by Martin Pool
Clean up clone-bzrdir code
1108
    def initialize_on_transport(self, transport):
1608.2.8 by Martin Pool
Separate out BzrDir.initialize_on_transport so it
1109
        """Initialize a new bzrdir in the base directory of a Transport."""
1759.2.1 by Jelmer Vernooij
Fix some types (found using aspell).
1110
        # Since we don't have a .bzr directory, inherit the
1534.4.39 by Robert Collins
Basic BzrDir support.
1111
        # mode from the root directory
1996.3.3 by John Arbash Meinel
Shave off another 40ms by demand loading branch and bzrdir
1112
        temp_control = lockable_files.LockableFiles(transport,
1113
                            '', lockable_files.TransportLock)
1534.4.39 by Robert Collins
Basic BzrDir support.
1114
        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.
1115
                                      # FIXME: RBC 20060121 don't peek under
1534.4.39 by Robert Collins
Basic BzrDir support.
1116
                                      # the covers
1117
                                      mode=temp_control._dir_mode)
1118
        file_mode = temp_control._file_mode
1119
        del temp_control
1608.2.8 by Martin Pool
Separate out BzrDir.initialize_on_transport so it
1120
        mutter('created control directory in ' + transport.base)
1121
        control = transport.clone('.bzr')
1534.4.39 by Robert Collins
Basic BzrDir support.
1122
        utf8_files = [('README', 
1123
                       "This is a Bazaar-NG control directory.\n"
1124
                       "Do not change any files in this directory.\n"),
1125
                      ('branch-format', self.get_format_string()),
1126
                      ]
1127
        # 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
1128
        control_files = lockable_files.LockableFiles(control,
1129
                            self._lock_file_name, self._lock_class)
1553.5.60 by Martin Pool
New LockableFiles.create_lock() method
1130
        control_files.create_lock()
1534.4.39 by Robert Collins
Basic BzrDir support.
1131
        control_files.lock_write()
1132
        try:
1133
            for file, content in utf8_files:
1134
                control_files.put_utf8(file, content)
1135
        finally:
1136
            control_files.unlock()
1608.2.8 by Martin Pool
Separate out BzrDir.initialize_on_transport so it
1137
        return self.open(transport, _found=True)
1534.4.39 by Robert Collins
Basic BzrDir support.
1138
1139
    def is_supported(self):
1140
        """Is this format supported?
1141
1142
        Supported formats must be initializable and openable.
1143
        Unsupported formats may not support initialization or committing or 
1144
        some other features depending on the reason for not being supported.
1145
        """
1146
        return True
1147
1910.2.14 by Aaron Bentley
Fail when trying to use interrepository on Knit2 and Knit1
1148
    def same_model(self, target_format):
1149
        return (self.repository_format.rich_root_data == 
1150
            target_format.rich_root_data)
1151
1733.1.3 by Robert Collins
Extend the test suite to run bzrdir conformance tests on non .bzr based control dirs.
1152
    @classmethod
1153
    def known_formats(klass):
1154
        """Return all the known formats.
1155
        
1156
        Concrete formats should override _known_formats.
1157
        """
1733.1.6 by Jelmer Vernooij
Fix a couple of minor issues after review by Martin.
1158
        # There is double indirection here to make sure that control 
1159
        # formats used by more than one dir format will only be probed 
1160
        # 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.
1161
        result = set()
1162
        for format in klass._control_formats:
1163
            result.update(format._known_formats())
1164
        return result
1165
    
1166
    @classmethod
1167
    def _known_formats(klass):
1168
        """Return the known format instances for this control format."""
1169
        return set(klass._formats.values())
1170
1534.4.39 by Robert Collins
Basic BzrDir support.
1171
    def open(self, transport, _found=False):
1172
        """Return an instance of this format for the dir transport points at.
1173
        
1174
        _found is a private parameter, do not use it.
1175
        """
1176
        if not _found:
2090.2.2 by Martin Pool
Fix an assertion with side effects
1177
            found_format = BzrDirFormat.find_format(transport)
1178
            if not isinstance(found_format, self.__class__):
1179
                raise AssertionError("%s was asked to open %s, but it seems to need "
1180
                        "format %s" 
1181
                        % (self, transport, found_format))
1534.4.40 by Robert Collins
Add RepositoryFormats and allow bzrdir.open or create _repository to be used.
1182
        return self._open(transport)
1183
1184
    def _open(self, transport):
1185
        """Template method helper for opening BzrDirectories.
1186
1187
        This performs the actual open and any additional logic or parameter
1188
        passing.
1189
        """
1190
        raise NotImplementedError(self._open)
1534.4.39 by Robert Collins
Basic BzrDir support.
1191
1192
    @classmethod
1193
    def register_format(klass, format):
1194
        klass._formats[format.get_format_string()] = format
1195
1196
    @classmethod
1733.1.1 by Robert Collins
Support non '.bzr' control directories in bzrdir.
1197
    def register_control_format(klass, format):
1198
        """Register a format that does not use '.bzrdir' for its control dir.
1199
1200
        TODO: This should be pulled up into a 'ControlDirFormat' base class
1201
        which BzrDirFormat can inherit from, and renamed to register_format 
1202
        there. It has been done without that for now for simplicity of
1203
        implementation.
1204
        """
1733.1.7 by Jelmer Vernooij
Change set of control dir formats to list.
1205
        klass._control_formats.append(format)
1733.1.1 by Robert Collins
Support non '.bzr' control directories in bzrdir.
1206
1207
    @classmethod
1534.4.39 by Robert Collins
Basic BzrDir support.
1208
    def set_default_format(klass, format):
1209
        klass._default_format = format
1210
1534.5.1 by Robert Collins
Give info some reasonable output and tests.
1211
    def __str__(self):
1212
        return self.get_format_string()[:-1]
1213
1534.4.39 by Robert Collins
Basic BzrDir support.
1214
    @classmethod
1215
    def unregister_format(klass, format):
1216
        assert klass._formats[format.get_format_string()] is format
1217
        del klass._formats[format.get_format_string()]
1218
1733.1.1 by Robert Collins
Support non '.bzr' control directories in bzrdir.
1219
    @classmethod
1220
    def unregister_control_format(klass, format):
1221
        klass._control_formats.remove(format)
1222
1223
1224
# register BzrDirFormat as a control format
1225
BzrDirFormat.register_control_format(BzrDirFormat)
1226
1534.4.39 by Robert Collins
Basic BzrDir support.
1227
1228
class BzrDirFormat4(BzrDirFormat):
1229
    """Bzr dir format 4.
1230
1231
    This format is a combined format for working tree, branch and repository.
1232
    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.
1233
     - Format 1 working trees [always]
1234
     - Format 4 branches [always]
1235
     - Format 4 repositories [always]
1534.4.39 by Robert Collins
Basic BzrDir support.
1236
1237
    This format is deprecated: it indexes texts using a text it which is
1238
    removed in format 5; write support for this format has been removed.
1239
    """
1240
1996.3.3 by John Arbash Meinel
Shave off another 40ms by demand loading branch and bzrdir
1241
    _lock_class = lockable_files.TransportLock
1553.5.69 by Martin Pool
BzrDirFormat subclasses can now control what kind of overall lock is used.
1242
1534.4.39 by Robert Collins
Basic BzrDir support.
1243
    def get_format_string(self):
1244
        """See BzrDirFormat.get_format_string()."""
1245
        return "Bazaar-NG branch, format 0.0.4\n"
1246
1624.3.19 by Olaf Conradi
New call get_format_description to give a user-friendly description of a
1247
    def get_format_description(self):
1248
        """See BzrDirFormat.get_format_description()."""
1249
        return "All-in-one format 4"
1250
1534.5.16 by Robert Collins
Review feedback.
1251
    def get_converter(self, format=None):
1252
        """See BzrDirFormat.get_converter()."""
1534.5.13 by Robert Collins
Correct buggy test.
1253
        # 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.
1254
        return ConvertBzrDir4To5()
1255
        
1651.1.6 by Martin Pool
Clean up clone-bzrdir code
1256
    def initialize_on_transport(self, transport):
1534.4.39 by Robert Collins
Basic BzrDir support.
1257
        """Format 4 branches cannot be created."""
1258
        raise errors.UninitializableFormat(self)
1259
1260
    def is_supported(self):
1261
        """Format 4 is not supported.
1262
1263
        It is not supported because the model changed from 4 to 5 and the
1264
        conversion logic is expensive - so doing it on the fly was not 
1265
        feasible.
1266
        """
1267
        return False
1268
1534.4.40 by Robert Collins
Add RepositoryFormats and allow bzrdir.open or create _repository to be used.
1269
    def _open(self, transport):
1270
        """See BzrDirFormat._open."""
1271
        return BzrDir4(transport, self)
1272
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.
1273
    def __return_repository_format(self):
1274
        """Circular import protection."""
1275
        from bzrlib.repository import RepositoryFormat4
1910.2.12 by Aaron Bentley
Implement knit repo format 2
1276
        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.
1277
    repository_format = property(__return_repository_format)
1278
1534.4.39 by Robert Collins
Basic BzrDir support.
1279
1280
class BzrDirFormat5(BzrDirFormat):
1281
    """Bzr control format 5.
1282
1283
    This format is a combined format for working tree, branch and repository.
1284
    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.
1285
     - Format 2 working trees [always] 
1286
     - Format 4 branches [always] 
1534.4.53 by Robert Collins
Review feedback from John Meinel.
1287
     - 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.
1288
       Unhashed stores in the repository.
1534.4.39 by Robert Collins
Basic BzrDir support.
1289
    """
1290
1996.3.3 by John Arbash Meinel
Shave off another 40ms by demand loading branch and bzrdir
1291
    _lock_class = lockable_files.TransportLock
1553.5.69 by Martin Pool
BzrDirFormat subclasses can now control what kind of overall lock is used.
1292
1534.4.39 by Robert Collins
Basic BzrDir support.
1293
    def get_format_string(self):
1294
        """See BzrDirFormat.get_format_string()."""
1295
        return "Bazaar-NG branch, format 5\n"
1296
1624.3.19 by Olaf Conradi
New call get_format_description to give a user-friendly description of a
1297
    def get_format_description(self):
1298
        """See BzrDirFormat.get_format_description()."""
1299
        return "All-in-one format 5"
1300
1534.5.16 by Robert Collins
Review feedback.
1301
    def get_converter(self, format=None):
1302
        """See BzrDirFormat.get_converter()."""
1534.5.13 by Robert Collins
Correct buggy test.
1303
        # 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.
1304
        return ConvertBzrDir5To6()
1651.1.6 by Martin Pool
Clean up clone-bzrdir code
1305
1306
    def _initialize_for_clone(self, url):
1307
        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.
1308
        
1608.2.8 by Martin Pool
Separate out BzrDir.initialize_on_transport so it
1309
    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.
1310
        """Format 5 dirs always have working tree, branch and repository.
1311
        
1312
        Except when they are being cloned.
1313
        """
1314
        from bzrlib.branch import BzrBranchFormat4
1315
        from bzrlib.repository import RepositoryFormat5
1316
        from bzrlib.workingtree import WorkingTreeFormat2
1651.1.6 by Martin Pool
Clean up clone-bzrdir code
1317
        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.
1318
        RepositoryFormat5().initialize(result, _internal=True)
1319
        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.
1320
            branch = BzrBranchFormat4().initialize(result)
1321
            try:
1322
                WorkingTreeFormat2().initialize(result)
1323
            except errors.NotLocalUrl:
1324
                # Even though we can't access the working tree, we need to
1325
                # create its control files.
1326
                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.
1327
        return result
1328
1534.4.40 by Robert Collins
Add RepositoryFormats and allow bzrdir.open or create _repository to be used.
1329
    def _open(self, transport):
1330
        """See BzrDirFormat._open."""
1331
        return BzrDir5(transport, self)
1332
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.
1333
    def __return_repository_format(self):
1334
        """Circular import protection."""
1335
        from bzrlib.repository import RepositoryFormat5
1910.2.12 by Aaron Bentley
Implement knit repo format 2
1336
        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.
1337
    repository_format = property(__return_repository_format)
1338
1534.4.39 by Robert Collins
Basic BzrDir support.
1339
1340
class BzrDirFormat6(BzrDirFormat):
1341
    """Bzr control format 6.
1342
1343
    This format is a combined format for working tree, branch and repository.
1344
    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.
1345
     - Format 2 working trees [always] 
1346
     - Format 4 branches [always] 
1347
     - Format 6 repositories [always]
1534.4.39 by Robert Collins
Basic BzrDir support.
1348
    """
1349
1996.3.3 by John Arbash Meinel
Shave off another 40ms by demand loading branch and bzrdir
1350
    _lock_class = lockable_files.TransportLock
1553.5.69 by Martin Pool
BzrDirFormat subclasses can now control what kind of overall lock is used.
1351
1534.4.39 by Robert Collins
Basic BzrDir support.
1352
    def get_format_string(self):
1353
        """See BzrDirFormat.get_format_string()."""
1354
        return "Bazaar-NG branch, format 6\n"
1355
1624.3.19 by Olaf Conradi
New call get_format_description to give a user-friendly description of a
1356
    def get_format_description(self):
1357
        """See BzrDirFormat.get_format_description()."""
1358
        return "All-in-one format 6"
1359
1534.5.16 by Robert Collins
Review feedback.
1360
    def get_converter(self, format=None):
1361
        """See BzrDirFormat.get_converter()."""
1534.5.13 by Robert Collins
Correct buggy test.
1362
        # 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.
1363
        return ConvertBzrDir6ToMeta()
1364
        
1651.1.6 by Martin Pool
Clean up clone-bzrdir code
1365
    def _initialize_for_clone(self, url):
1366
        return self.initialize_on_transport(get_transport(url), _cloning=True)
1367
1608.2.8 by Martin Pool
Separate out BzrDir.initialize_on_transport so it
1368
    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.
1369
        """Format 6 dirs always have working tree, branch and repository.
1370
        
1371
        Except when they are being cloned.
1372
        """
1373
        from bzrlib.branch import BzrBranchFormat4
1374
        from bzrlib.repository import RepositoryFormat6
1375
        from bzrlib.workingtree import WorkingTreeFormat2
1651.1.6 by Martin Pool
Clean up clone-bzrdir code
1376
        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.
1377
        RepositoryFormat6().initialize(result, _internal=True)
1378
        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.
1379
            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.
1380
            try:
1381
                WorkingTreeFormat2().initialize(result)
1382
            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.
1383
                # Even though we can't access the working tree, we need to
1384
                # create its control files.
1385
                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.
1386
        return result
1387
1534.4.40 by Robert Collins
Add RepositoryFormats and allow bzrdir.open or create _repository to be used.
1388
    def _open(self, transport):
1389
        """See BzrDirFormat._open."""
1390
        return BzrDir6(transport, self)
1391
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.
1392
    def __return_repository_format(self):
1393
        """Circular import protection."""
1394
        from bzrlib.repository import RepositoryFormat6
1910.2.12 by Aaron Bentley
Implement knit repo format 2
1395
        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.
1396
    repository_format = property(__return_repository_format)
1397
1534.4.39 by Robert Collins
Basic BzrDir support.
1398
1534.4.44 by Robert Collins
Make a new BzrDir format that uses a versioned branch format in a branch/ subdirectory.
1399
class BzrDirMetaFormat1(BzrDirFormat):
1400
    """Bzr meta control format 1
1401
1402
    This is the first format with split out working tree, branch and repository
1403
    disk storage.
1404
    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.
1405
     - Format 3 working trees [optional]
1406
     - Format 5 branches [optional]
1407
     - 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.
1408
    """
1409
1996.3.3 by John Arbash Meinel
Shave off another 40ms by demand loading branch and bzrdir
1410
    _lock_class = lockdir.LockDir
1553.5.69 by Martin Pool
BzrDirFormat subclasses can now control what kind of overall lock is used.
1411
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.
1412
    def get_converter(self, format=None):
1413
        """See BzrDirFormat.get_converter()."""
1414
        if format is None:
1415
            format = BzrDirFormat.get_default_format()
1416
        if not isinstance(self, format.__class__):
1417
            # converting away from metadir is not implemented
1418
            raise NotImplementedError(self.get_converter)
1419
        return ConvertMetaToMeta(format)
1420
1534.4.44 by Robert Collins
Make a new BzrDir format that uses a versioned branch format in a branch/ subdirectory.
1421
    def get_format_string(self):
1422
        """See BzrDirFormat.get_format_string()."""
1423
        return "Bazaar-NG meta directory, format 1\n"
1424
1624.3.19 by Olaf Conradi
New call get_format_description to give a user-friendly description of a
1425
    def get_format_description(self):
1426
        """See BzrDirFormat.get_format_description()."""
1427
        return "Meta directory format 1"
1428
1534.4.44 by Robert Collins
Make a new BzrDir format that uses a versioned branch format in a branch/ subdirectory.
1429
    def _open(self, transport):
1430
        """See BzrDirFormat._open."""
1431
        return BzrDirMeta1(transport, self)
1432
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.
1433
    def __return_repository_format(self):
1434
        """Circular import protection."""
1435
        if getattr(self, '_repository_format', None):
1436
            return self._repository_format
1437
        from bzrlib.repository import RepositoryFormat
1438
        return RepositoryFormat.get_default_format()
1439
1440
    def __set_repository_format(self, value):
1441
        """Allow changint the repository format for metadir formats."""
1442
        self._repository_format = value
1553.5.72 by Martin Pool
Clean up test for Branch5 lockdirs
1443
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.
1444
    repository_format = property(__return_repository_format, __set_repository_format)
1445
1534.4.44 by Robert Collins
Make a new BzrDir format that uses a versioned branch format in a branch/ subdirectory.
1446
1534.4.39 by Robert Collins
Basic BzrDir support.
1447
BzrDirFormat.register_format(BzrDirFormat4())
1448
BzrDirFormat.register_format(BzrDirFormat5())
1666.1.4 by Robert Collins
* 'Metadir' is now the default disk format. This improves behaviour in
1449
BzrDirFormat.register_format(BzrDirFormat6())
1450
__default_format = BzrDirMetaFormat1()
1534.4.39 by Robert Collins
Basic BzrDir support.
1451
BzrDirFormat.register_format(__default_format)
1452
BzrDirFormat.set_default_format(__default_format)
1453
1454
1455
class BzrDirTestProviderAdapter(object):
1456
    """A tool to generate a suite testing multiple bzrdir formats at once.
1457
1458
    This is done by copying the test once for each transport and injecting
1459
    the transport_server, transport_readonly_server, and bzrdir_format
1460
    classes into each copy. Each copy is also given a new id() to make it
1461
    easy to identify.
1462
    """
1463
1464
    def __init__(self, transport_server, transport_readonly_server, formats):
1465
        self._transport_server = transport_server
1466
        self._transport_readonly_server = transport_readonly_server
1467
        self._formats = formats
1468
    
1469
    def adapt(self, test):
1996.3.3 by John Arbash Meinel
Shave off another 40ms by demand loading branch and bzrdir
1470
        result = unittest.TestSuite()
1534.4.39 by Robert Collins
Basic BzrDir support.
1471
        for format in self._formats:
1472
            new_test = deepcopy(test)
1473
            new_test.transport_server = self._transport_server
1474
            new_test.transport_readonly_server = self._transport_readonly_server
1475
            new_test.bzrdir_format = format
1476
            def make_new_test_id():
1477
                new_id = "%s(%s)" % (new_test.id(), format.__class__.__name__)
1478
                return lambda: new_id
1479
            new_test.id = make_new_test_id()
1480
            result.addTest(new_test)
1481
        return result
1534.4.41 by Robert Collins
Branch now uses BzrDir reasonably sanely.
1482
1483
1534.5.7 by Robert Collins
Start factoring out the upgrade policy logic.
1484
class Converter(object):
1485
    """Converts a disk format object from one format to another."""
1486
1534.5.10 by Robert Collins
Make upgrade driver unaware of the specific formats in play.
1487
    def convert(self, to_convert, pb):
1488
        """Perform the conversion of to_convert, giving feedback via pb.
1534.5.7 by Robert Collins
Start factoring out the upgrade policy logic.
1489
1534.5.10 by Robert Collins
Make upgrade driver unaware of the specific formats in play.
1490
        :param to_convert: The disk object to convert.
1534.5.7 by Robert Collins
Start factoring out the upgrade policy logic.
1491
        :param pb: a progress bar to use for progress information.
1492
        """
1493
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.
1494
    def step(self, message):
1495
        """Update the pb by a step."""
1496
        self.count +=1
1497
        self.pb.update(message, self.count, self.total)
1498
1534.5.7 by Robert Collins
Start factoring out the upgrade policy logic.
1499
1500
class ConvertBzrDir4To5(Converter):
1501
    """Converts format 4 bzr dirs to format 5."""
1502
1534.5.10 by Robert Collins
Make upgrade driver unaware of the specific formats in play.
1503
    def __init__(self):
1504
        super(ConvertBzrDir4To5, self).__init__()
1534.5.7 by Robert Collins
Start factoring out the upgrade policy logic.
1505
        self.converted_revs = set()
1506
        self.absent_revisions = set()
1507
        self.text_count = 0
1508
        self.revisions = {}
1509
        
1534.5.10 by Robert Collins
Make upgrade driver unaware of the specific formats in play.
1510
    def convert(self, to_convert, pb):
1534.5.7 by Robert Collins
Start factoring out the upgrade policy logic.
1511
        """See Converter.convert()."""
1534.5.10 by Robert Collins
Make upgrade driver unaware of the specific formats in play.
1512
        self.bzrdir = to_convert
1513
        self.pb = pb
1534.5.7 by Robert Collins
Start factoring out the upgrade policy logic.
1514
        self.pb.note('starting upgrade from format 4 to 5')
1515
        if isinstance(self.bzrdir.transport, LocalTransport):
1516
            self.bzrdir.get_workingtree_transport(None).delete('stat-cache')
1517
        self._convert_to_weaves()
1518
        return BzrDir.open(self.bzrdir.root_transport.base)
1519
1520
    def _convert_to_weaves(self):
1521
        self.pb.note('note: upgrade may be faster if all store files are ungzipped first')
1522
        try:
1523
            # TODO permissions
1524
            stat = self.bzrdir.transport.stat('weaves')
1525
            if not S_ISDIR(stat.st_mode):
1526
                self.bzrdir.transport.delete('weaves')
1527
                self.bzrdir.transport.mkdir('weaves')
1528
        except errors.NoSuchFile:
1529
            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.
1530
        # 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.
1531
        self.inv_weave = Weave('inventory')
1532
        # holds in-memory weaves for all files
1533
        self.text_weaves = {}
1534
        self.bzrdir.transport.delete('branch-format')
1535
        self.branch = self.bzrdir.open_branch()
1536
        self._convert_working_inv()
1537
        rev_history = self.branch.revision_history()
1538
        # to_read is a stack holding the revisions we still need to process;
1539
        # appending to it adds new highest-priority revisions
1540
        self.known_revisions = set(rev_history)
1541
        self.to_read = rev_history[-1:]
1542
        while self.to_read:
1543
            rev_id = self.to_read.pop()
1544
            if (rev_id not in self.revisions
1545
                and rev_id not in self.absent_revisions):
1546
                self._load_one_rev(rev_id)
1547
        self.pb.clear()
1548
        to_import = self._make_order()
1549
        for i, rev_id in enumerate(to_import):
1550
            self.pb.update('converting revision', i, len(to_import))
1551
            self._convert_one_rev(rev_id)
1552
        self.pb.clear()
1553
        self._write_all_weaves()
1554
        self._write_all_revs()
1555
        self.pb.note('upgraded to weaves:')
1556
        self.pb.note('  %6d revisions and inventories', len(self.revisions))
1557
        self.pb.note('  %6d revisions not present', len(self.absent_revisions))
1558
        self.pb.note('  %6d texts', self.text_count)
1559
        self._cleanup_spare_files_after_format4()
1560
        self.branch.control_files.put_utf8('branch-format', BzrDirFormat5().get_format_string())
1561
1562
    def _cleanup_spare_files_after_format4(self):
1563
        # FIXME working tree upgrade foo.
1564
        for n in 'merged-patches', 'pending-merged-patches':
1565
            try:
1566
                ## assert os.path.getsize(p) == 0
1567
                self.bzrdir.transport.delete(n)
1568
            except errors.NoSuchFile:
1569
                pass
1570
        self.bzrdir.transport.delete_tree('inventory-store')
1571
        self.bzrdir.transport.delete_tree('text-store')
1572
1573
    def _convert_working_inv(self):
1996.3.6 by John Arbash Meinel
Find a few places that weren't importing their dependencies.
1574
        inv = xml4.serializer_v4.read_inventory(
1575
                    self.branch.control_files.get('inventory'))
1576
        new_inv_xml = xml5.serializer_v5.write_inventory_to_string(inv)
1534.5.7 by Robert Collins
Start factoring out the upgrade policy logic.
1577
        # 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
1578
        self.branch.control_files.put('inventory', StringIO(new_inv_xml))
1534.5.7 by Robert Collins
Start factoring out the upgrade policy logic.
1579
1580
    def _write_all_weaves(self):
1581
        controlweaves = WeaveStore(self.bzrdir.transport, prefixed=False)
1582
        weave_transport = self.bzrdir.transport.clone('weaves')
1583
        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
1584
        transaction = WriteTransaction()
1534.5.7 by Robert Collins
Start factoring out the upgrade policy logic.
1585
1586
        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.
1587
            i = 0
1534.5.7 by Robert Collins
Start factoring out the upgrade policy logic.
1588
            for file_id, file_weave in self.text_weaves.items():
1589
                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.
1590
                weaves._put_weave(file_id, file_weave, transaction)
1534.5.7 by Robert Collins
Start factoring out the upgrade policy logic.
1591
                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.
1592
            self.pb.update('inventory', 0, 1)
1593
            controlweaves._put_weave('inventory', self.inv_weave, transaction)
1594
            self.pb.update('inventory', 1, 1)
1534.5.7 by Robert Collins
Start factoring out the upgrade policy logic.
1595
        finally:
1596
            self.pb.clear()
1597
1598
    def _write_all_revs(self):
1599
        """Write all revisions out in new form."""
1600
        self.bzrdir.transport.delete_tree('revision-store')
1601
        self.bzrdir.transport.mkdir('revision-store')
1602
        revision_transport = self.bzrdir.transport.clone('revision-store')
1603
        # TODO permissions
1563.2.28 by Robert Collins
Add total_size to the revision_store api.
1604
        _revision_store = TextRevisionStore(TextStore(revision_transport,
1605
                                                      prefixed=False,
1606
                                                      compressed=True))
1534.5.7 by Robert Collins
Start factoring out the upgrade policy logic.
1607
        try:
1996.3.3 by John Arbash Meinel
Shave off another 40ms by demand loading branch and bzrdir
1608
            transaction = WriteTransaction()
1534.5.7 by Robert Collins
Start factoring out the upgrade policy logic.
1609
            for i, rev_id in enumerate(self.converted_revs):
1610
                self.pb.update('write revision', i, len(self.converted_revs))
1563.2.28 by Robert Collins
Add total_size to the revision_store api.
1611
                _revision_store.add_revision(self.revisions[rev_id], transaction)
1534.5.7 by Robert Collins
Start factoring out the upgrade policy logic.
1612
        finally:
1613
            self.pb.clear()
1614
            
1615
    def _load_one_rev(self, rev_id):
1616
        """Load a revision object into memory.
1617
1618
        Any parents not either loaded or abandoned get queued to be
1619
        loaded."""
1620
        self.pb.update('loading revision',
1621
                       len(self.revisions),
1622
                       len(self.known_revisions))
1563.2.22 by Robert Collins
Move responsibility for repository.has_revision into RevisionStore
1623
        if not self.branch.repository.has_revision(rev_id):
1534.5.7 by Robert Collins
Start factoring out the upgrade policy logic.
1624
            self.pb.clear()
1625
            self.pb.note('revision {%s} not present in branch; '
1626
                         'will be converted as a ghost',
1627
                         rev_id)
1628
            self.absent_revisions.add(rev_id)
1629
        else:
1563.2.28 by Robert Collins
Add total_size to the revision_store api.
1630
            rev = self.branch.repository._revision_store.get_revision(rev_id,
1631
                self.branch.repository.get_transaction())
1534.5.7 by Robert Collins
Start factoring out the upgrade policy logic.
1632
            for parent_id in rev.parent_ids:
1633
                self.known_revisions.add(parent_id)
1634
                self.to_read.append(parent_id)
1635
            self.revisions[rev_id] = rev
1636
1637
    def _load_old_inventory(self, rev_id):
1638
        assert rev_id not in self.converted_revs
1639
        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.
1640
        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
1641
        inv.revision_id = rev_id
1534.5.7 by Robert Collins
Start factoring out the upgrade policy logic.
1642
        rev = self.revisions[rev_id]
1643
        if rev.inventory_sha1:
1644
            assert rev.inventory_sha1 == sha_string(old_inv_xml), \
1645
                'inventory sha mismatch for {%s}' % rev_id
1646
        return inv
1647
1648
    def _load_updated_inventory(self, rev_id):
1649
        assert rev_id in self.converted_revs
1650
        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.
1651
        inv = xml5.serializer_v5.read_inventory_from_string(inv_xml)
1534.5.7 by Robert Collins
Start factoring out the upgrade policy logic.
1652
        return inv
1653
1654
    def _convert_one_rev(self, rev_id):
1655
        """Convert revision and all referenced objects to new format."""
1656
        rev = self.revisions[rev_id]
1657
        inv = self._load_old_inventory(rev_id)
1658
        present_parents = [p for p in rev.parent_ids
1659
                           if p not in self.absent_revisions]
1660
        self._convert_revision_contents(rev, inv, present_parents)
1661
        self._store_new_weave(rev, inv, present_parents)
1662
        self.converted_revs.add(rev_id)
1663
1664
    def _store_new_weave(self, rev, inv, present_parents):
1665
        # the XML is now updated with text versions
1666
        if __debug__:
1907.1.8 by Aaron Bentley
Remove is_root
1667
            entries = inv.iter_entries()
1668
            entries.next()
1669
            for path, ie in entries:
1963.2.6 by Robey Pointer
pychecker is on crack; go back to using 'is None'.
1670
                assert getattr(ie, 'revision', None) is not None, \
1534.5.7 by Robert Collins
Start factoring out the upgrade policy logic.
1671
                    'no revision on {%s} in {%s}' % \
1672
                    (file_id, rev.revision_id)
1996.3.6 by John Arbash Meinel
Find a few places that weren't importing their dependencies.
1673
        new_inv_xml = xml5.serializer_v5.write_inventory_to_string(inv)
1534.5.7 by Robert Collins
Start factoring out the upgrade policy logic.
1674
        new_inv_sha1 = sha_string(new_inv_xml)
1563.2.28 by Robert Collins
Add total_size to the revision_store api.
1675
        self.inv_weave.add_lines(rev.revision_id, 
1676
                                 present_parents,
1677
                                 new_inv_xml.splitlines(True))
1534.5.7 by Robert Collins
Start factoring out the upgrade policy logic.
1678
        rev.inventory_sha1 = new_inv_sha1
1679
1680
    def _convert_revision_contents(self, rev, inv, present_parents):
1681
        """Convert all the files within a revision.
1682
1683
        Also upgrade the inventory to refer to the text revision ids."""
1684
        rev_id = rev.revision_id
1685
        mutter('converting texts of revision {%s}',
1686
               rev_id)
1687
        parent_invs = map(self._load_updated_inventory, present_parents)
1731.1.62 by Aaron Bentley
Changes from review comments
1688
        entries = inv.iter_entries()
1689
        entries.next()
1690
        for path, ie in entries:
1534.5.7 by Robert Collins
Start factoring out the upgrade policy logic.
1691
            self._convert_file_version(rev, ie, parent_invs)
1692
1693
    def _convert_file_version(self, rev, ie, parent_invs):
1694
        """Convert one version of one file.
1695
1696
        The file needs to be added into the weave if it is a merge
1697
        of >=2 parents or if it's changed from its parent.
1698
        """
1699
        file_id = ie.file_id
1700
        rev_id = rev.revision_id
1701
        w = self.text_weaves.get(file_id)
1702
        if w is None:
1703
            w = Weave(file_id)
1704
            self.text_weaves[file_id] = w
1705
        text_changed = False
1596.2.20 by Robert Collins
optimise commit to only access weaves for merged, or altered files during commit.
1706
        previous_entries = ie.find_previous_heads(parent_invs,
1707
                                                  None,
1708
                                                  None,
1709
                                                  entry_vf=w)
1534.5.7 by Robert Collins
Start factoring out the upgrade policy logic.
1710
        for old_revision in previous_entries:
1711
                # if this fails, its a ghost ?
1731.1.33 by Aaron Bentley
Revert no-special-root changes
1712
                assert old_revision in self.converted_revs, \
1713
                    "Revision {%s} not in converted_revs" % old_revision
1534.5.7 by Robert Collins
Start factoring out the upgrade policy logic.
1714
        self.snapshot_ie(previous_entries, ie, w, rev_id)
1715
        del ie.text_id
1716
        assert getattr(ie, 'revision', None) is not None
1717
1718
    def snapshot_ie(self, previous_revisions, ie, w, rev_id):
1719
        # TODO: convert this logic, which is ~= snapshot to
1720
        # a call to:. This needs the path figured out. rather than a work_tree
1721
        # a v4 revision_tree can be given, or something that looks enough like
1722
        # one to give the file content to the entry if it needs it.
1723
        # and we need something that looks like a weave store for snapshot to 
1724
        # save against.
1725
        #ie.snapshot(rev, PATH, previous_revisions, REVISION_TREE, InMemoryWeaveStore(self.text_weaves))
1726
        if len(previous_revisions) == 1:
1727
            previous_ie = previous_revisions.values()[0]
1728
            if ie._unchanged(previous_ie):
1729
                ie.revision = previous_ie.revision
1730
                return
1731
        if ie.has_text():
1732
            text = self.branch.repository.text_store.get(ie.text_id)
1733
            file_lines = text.readlines()
1734
            assert sha_strings(file_lines) == ie.text_sha1
1735
            assert sum(map(len, file_lines)) == ie.text_size
1563.2.18 by Robert Collins
get knit repositories really using knits for text storage.
1736
            w.add_lines(rev_id, previous_revisions, file_lines)
1534.5.7 by Robert Collins
Start factoring out the upgrade policy logic.
1737
            self.text_count += 1
1738
        else:
1563.2.18 by Robert Collins
get knit repositories really using knits for text storage.
1739
            w.add_lines(rev_id, previous_revisions, [])
1534.5.7 by Robert Collins
Start factoring out the upgrade policy logic.
1740
        ie.revision = rev_id
1741
1742
    def _make_order(self):
1743
        """Return a suitable order for importing revisions.
1744
1745
        The order must be such that an revision is imported after all
1746
        its (present) parents.
1747
        """
1748
        todo = set(self.revisions.keys())
1749
        done = self.absent_revisions.copy()
1534.5.11 by Robert Collins
Implement upgrades to Metaformat trees.
1750
        order = []
1534.5.7 by Robert Collins
Start factoring out the upgrade policy logic.
1751
        while todo:
1752
            # scan through looking for a revision whose parents
1753
            # are all done
1754
            for rev_id in sorted(list(todo)):
1755
                rev = self.revisions[rev_id]
1756
                parent_ids = set(rev.parent_ids)
1757
                if parent_ids.issubset(done):
1758
                    # can take this one now
1534.5.11 by Robert Collins
Implement upgrades to Metaformat trees.
1759
                    order.append(rev_id)
1534.5.7 by Robert Collins
Start factoring out the upgrade policy logic.
1760
                    todo.remove(rev_id)
1761
                    done.add(rev_id)
1534.5.11 by Robert Collins
Implement upgrades to Metaformat trees.
1762
        return order
1534.5.7 by Robert Collins
Start factoring out the upgrade policy logic.
1763
1764
1765
class ConvertBzrDir5To6(Converter):
1766
    """Converts format 5 bzr dirs to format 6."""
1767
1534.5.10 by Robert Collins
Make upgrade driver unaware of the specific formats in play.
1768
    def convert(self, to_convert, pb):
1769
        """See Converter.convert()."""
1534.5.7 by Robert Collins
Start factoring out the upgrade policy logic.
1770
        self.bzrdir = to_convert
1534.5.10 by Robert Collins
Make upgrade driver unaware of the specific formats in play.
1771
        self.pb = pb
1534.5.7 by Robert Collins
Start factoring out the upgrade policy logic.
1772
        self.pb.note('starting upgrade from format 5 to 6')
1773
        self._convert_to_prefixed()
1774
        return BzrDir.open(self.bzrdir.root_transport.base)
1775
1776
    def _convert_to_prefixed(self):
1608.2.1 by Martin Pool
[merge] Storage filename escaping
1777
        from bzrlib.store import TransportStore
1534.5.7 by Robert Collins
Start factoring out the upgrade policy logic.
1778
        self.bzrdir.transport.delete('branch-format')
1779
        for store_name in ["weaves", "revision-store"]:
1608.2.1 by Martin Pool
[merge] Storage filename escaping
1780
            self.pb.note("adding prefixes to %s" % store_name)
1534.5.7 by Robert Collins
Start factoring out the upgrade policy logic.
1781
            store_transport = self.bzrdir.transport.clone(store_name)
1608.2.1 by Martin Pool
[merge] Storage filename escaping
1782
            store = TransportStore(store_transport, prefixed=True)
1608.1.1 by Martin Pool
[patch] LocalTransport.list_dir should return url-quoted strings (ddaa)
1783
            for urlfilename in store_transport.list_dir('.'):
1685.1.45 by John Arbash Meinel
Moved url functions into bzrlib.urlutils
1784
                filename = urlutils.unescape(urlfilename)
1534.5.7 by Robert Collins
Start factoring out the upgrade policy logic.
1785
                if (filename.endswith(".weave") or
1786
                    filename.endswith(".gz") or
1787
                    filename.endswith(".sig")):
1788
                    file_id = os.path.splitext(filename)[0]
1789
                else:
1790
                    file_id = filename
1608.2.1 by Martin Pool
[merge] Storage filename escaping
1791
                prefix_dir = store.hash_prefix(file_id)
1534.5.7 by Robert Collins
Start factoring out the upgrade policy logic.
1792
                # FIXME keep track of the dirs made RBC 20060121
1793
                try:
1794
                    store_transport.move(filename, prefix_dir + '/' + filename)
1795
                except errors.NoSuchFile: # catches missing dirs strangely enough
1796
                    store_transport.mkdir(prefix_dir)
1797
                    store_transport.move(filename, prefix_dir + '/' + filename)
1798
        self.bzrdir._control_files.put_utf8('branch-format', BzrDirFormat6().get_format_string())
1799
1800
1534.5.10 by Robert Collins
Make upgrade driver unaware of the specific formats in play.
1801
class ConvertBzrDir6ToMeta(Converter):
1802
    """Converts format 6 bzr dirs to metadirs."""
1803
1804
    def convert(self, to_convert, pb):
1805
        """See Converter.convert()."""
1806
        self.bzrdir = to_convert
1807
        self.pb = pb
1534.5.11 by Robert Collins
Implement upgrades to Metaformat trees.
1808
        self.count = 0
1809
        self.total = 20 # the steps we know about
1810
        self.garbage_inventories = []
1811
1534.5.13 by Robert Collins
Correct buggy test.
1812
        self.pb.note('starting upgrade from format 6 to metadir')
1534.5.11 by Robert Collins
Implement upgrades to Metaformat trees.
1813
        self.bzrdir._control_files.put_utf8('branch-format', "Converting to format 6")
1814
        # its faster to move specific files around than to open and use the apis...
1815
        # first off, nuke ancestry.weave, it was never used.
1816
        try:
1817
            self.step('Removing ancestry.weave')
1818
            self.bzrdir.transport.delete('ancestry.weave')
1819
        except errors.NoSuchFile:
1820
            pass
1821
        # find out whats there
1822
        self.step('Finding branch files')
1666.1.3 by Robert Collins
Fix and test upgrades from bzrdir 6 over SFTP.
1823
        last_revision = self.bzrdir.open_branch().last_revision()
1534.5.11 by Robert Collins
Implement upgrades to Metaformat trees.
1824
        bzrcontents = self.bzrdir.transport.list_dir('.')
1825
        for name in bzrcontents:
1826
            if name.startswith('basis-inventory.'):
1827
                self.garbage_inventories.append(name)
1828
        # create new directories for repository, working tree and branch
1553.5.79 by Martin Pool
upgrade to metadir should create LockDirs not files
1829
        self.dir_mode = self.bzrdir._control_files._dir_mode
1534.5.11 by Robert Collins
Implement upgrades to Metaformat trees.
1830
        self.file_mode = self.bzrdir._control_files._file_mode
1831
        repository_names = [('inventory.weave', True),
1832
                            ('revision-store', True),
1833
                            ('weaves', True)]
1834
        self.step('Upgrading repository  ')
1553.5.79 by Martin Pool
upgrade to metadir should create LockDirs not files
1835
        self.bzrdir.transport.mkdir('repository', mode=self.dir_mode)
1534.5.11 by Robert Collins
Implement upgrades to Metaformat trees.
1836
        self.make_lock('repository')
1837
        # we hard code the formats here because we are converting into
1838
        # the meta format. The meta format upgrader can take this to a 
1839
        # future format within each component.
1840
        self.put_format('repository', bzrlib.repository.RepositoryFormat7())
1841
        for entry in repository_names:
1842
            self.move_entry('repository', entry)
1843
1844
        self.step('Upgrading branch      ')
1553.5.79 by Martin Pool
upgrade to metadir should create LockDirs not files
1845
        self.bzrdir.transport.mkdir('branch', mode=self.dir_mode)
1534.5.11 by Robert Collins
Implement upgrades to Metaformat trees.
1846
        self.make_lock('branch')
1847
        self.put_format('branch', bzrlib.branch.BzrBranchFormat5())
1848
        branch_files = [('revision-history', True),
1849
                        ('branch-name', True),
1850
                        ('parent', False)]
1851
        for entry in branch_files:
1852
            self.move_entry('branch', entry)
1853
1854
        checkout_files = [('pending-merges', True),
1855
                          ('inventory', True),
1856
                          ('stat-cache', False)]
1959.3.1 by John Arbash Meinel
David Allouche: bzr upgrade should work if there is no working tree
1857
        # If a mandatory checkout file is not present, the branch does not have
1858
        # a functional checkout. Do not create a checkout in the converted
1859
        # branch.
1860
        for name, mandatory in checkout_files:
1861
            if mandatory and name not in bzrcontents:
1862
                has_checkout = False
1863
                break
1864
        else:
1865
            has_checkout = True
1866
        if not has_checkout:
1867
            self.pb.note('No working tree.')
1868
            # If some checkout files are there, we may as well get rid of them.
1869
            for name, mandatory in checkout_files:
1870
                if name in bzrcontents:
1871
                    self.bzrdir.transport.delete(name)
1872
        else:
2123.2.1 by John Arbash Meinel
Fix bug #70716, make bzrlib.bzrdir directly import bzrlib.workingtree
1873
            from bzrlib.workingtree import WorkingTreeFormat3
1959.3.1 by John Arbash Meinel
David Allouche: bzr upgrade should work if there is no working tree
1874
            self.step('Upgrading working tree')
1875
            self.bzrdir.transport.mkdir('checkout', mode=self.dir_mode)
1876
            self.make_lock('checkout')
1877
            self.put_format(
2123.2.1 by John Arbash Meinel
Fix bug #70716, make bzrlib.bzrdir directly import bzrlib.workingtree
1878
                'checkout', WorkingTreeFormat3())
1959.3.1 by John Arbash Meinel
David Allouche: bzr upgrade should work if there is no working tree
1879
            self.bzrdir.transport.delete_multi(
1880
                self.garbage_inventories, self.pb)
1881
            for entry in checkout_files:
1882
                self.move_entry('checkout', entry)
1883
            if last_revision is not None:
1884
                self.bzrdir._control_files.put_utf8(
1885
                    'checkout/last-revision', last_revision)
1886
        self.bzrdir._control_files.put_utf8(
1887
            'branch-format', BzrDirMetaFormat1().get_format_string())
1534.5.10 by Robert Collins
Make upgrade driver unaware of the specific formats in play.
1888
        return BzrDir.open(self.bzrdir.root_transport.base)
1889
1534.5.11 by Robert Collins
Implement upgrades to Metaformat trees.
1890
    def make_lock(self, name):
1891
        """Make a lock for the new control dir name."""
1892
        self.step('Make %s lock' % name)
1996.3.3 by John Arbash Meinel
Shave off another 40ms by demand loading branch and bzrdir
1893
        ld = lockdir.LockDir(self.bzrdir.transport,
1894
                             '%s/lock' % name,
1895
                             file_modebits=self.file_mode,
1896
                             dir_modebits=self.dir_mode)
1553.5.79 by Martin Pool
upgrade to metadir should create LockDirs not files
1897
        ld.create()
1534.5.11 by Robert Collins
Implement upgrades to Metaformat trees.
1898
1899
    def move_entry(self, new_dir, entry):
1900
        """Move then entry name into new_dir."""
1901
        name = entry[0]
1902
        mandatory = entry[1]
1903
        self.step('Moving %s' % name)
1904
        try:
1905
            self.bzrdir.transport.move(name, '%s/%s' % (new_dir, name))
1906
        except errors.NoSuchFile:
1907
            if mandatory:
1908
                raise
1909
1910
    def put_format(self, dirname, format):
1911
        self.bzrdir._control_files.put_utf8('%s/format' % dirname, format.get_format_string())
1912
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.
1913
1914
class ConvertMetaToMeta(Converter):
1915
    """Converts the components of metadirs."""
1916
1917
    def __init__(self, target_format):
1918
        """Create a metadir to metadir converter.
1919
1920
        :param target_format: The final metadir format that is desired.
1921
        """
1922
        self.target_format = target_format
1923
1924
    def convert(self, to_convert, pb):
1925
        """See Converter.convert()."""
1926
        self.bzrdir = to_convert
1927
        self.pb = pb
1928
        self.count = 0
1929
        self.total = 1
1930
        self.step('checking repository format')
1931
        try:
1932
            repo = self.bzrdir.open_repository()
1933
        except errors.NoRepositoryPresent:
1934
            pass
1935
        else:
1936
            if not isinstance(repo._format, self.target_format.repository_format.__class__):
1937
                from bzrlib.repository import CopyConverter
1938
                self.pb.note('starting repository conversion')
1939
                converter = CopyConverter(self.target_format.repository_format)
1940
                converter.convert(repo, pb)
1941
        return to_convert