/brz/remove-bazaar

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