/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:
2090.2.2 by Martin Pool
Fix an assertion with side effects
1179
            found_format = BzrDirFormat.find_format(transport)
1180
            if not isinstance(found_format, self.__class__):
1181
                raise AssertionError("%s was asked to open %s, but it seems to need "
1182
                        "format %s" 
1183
                        % (self, transport, found_format))
1534.4.40 by Robert Collins
Add RepositoryFormats and allow bzrdir.open or create _repository to be used.
1184
        return self._open(transport)
1185
1186
    def _open(self, transport):
1187
        """Template method helper for opening BzrDirectories.
1188
1189
        This performs the actual open and any additional logic or parameter
1190
        passing.
1191
        """
1192
        raise NotImplementedError(self._open)
1534.4.39 by Robert Collins
Basic BzrDir support.
1193
1194
    @classmethod
1195
    def register_format(klass, format):
1196
        klass._formats[format.get_format_string()] = format
1197
1198
    @classmethod
1733.1.1 by Robert Collins
Support non '.bzr' control directories in bzrdir.
1199
    def register_control_format(klass, format):
1200
        """Register a format that does not use '.bzrdir' for its control dir.
1201
1202
        TODO: This should be pulled up into a 'ControlDirFormat' base class
1203
        which BzrDirFormat can inherit from, and renamed to register_format 
1204
        there. It has been done without that for now for simplicity of
1205
        implementation.
1206
        """
1733.1.7 by Jelmer Vernooij
Change set of control dir formats to list.
1207
        klass._control_formats.append(format)
1733.1.1 by Robert Collins
Support non '.bzr' control directories in bzrdir.
1208
1209
    @classmethod
1534.4.39 by Robert Collins
Basic BzrDir support.
1210
    def set_default_format(klass, format):
1211
        klass._default_format = format
1212
1534.5.1 by Robert Collins
Give info some reasonable output and tests.
1213
    def __str__(self):
1214
        return self.get_format_string()[:-1]
1215
1534.4.39 by Robert Collins
Basic BzrDir support.
1216
    @classmethod
1217
    def unregister_format(klass, format):
1218
        assert klass._formats[format.get_format_string()] is format
1219
        del klass._formats[format.get_format_string()]
1220
1733.1.1 by Robert Collins
Support non '.bzr' control directories in bzrdir.
1221
    @classmethod
1222
    def unregister_control_format(klass, format):
1223
        klass._control_formats.remove(format)
1224
1225
1226
# register BzrDirFormat as a control format
1227
BzrDirFormat.register_control_format(BzrDirFormat)
1228
1534.4.39 by Robert Collins
Basic BzrDir support.
1229
1230
class BzrDirFormat4(BzrDirFormat):
1231
    """Bzr dir format 4.
1232
1233
    This format is a combined format for working tree, branch and repository.
1234
    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.
1235
     - Format 1 working trees [always]
1236
     - Format 4 branches [always]
1237
     - Format 4 repositories [always]
1534.4.39 by Robert Collins
Basic BzrDir support.
1238
1239
    This format is deprecated: it indexes texts using a text it which is
1240
    removed in format 5; write support for this format has been removed.
1241
    """
1242
1996.3.3 by John Arbash Meinel
Shave off another 40ms by demand loading branch and bzrdir
1243
    _lock_class = lockable_files.TransportLock
1553.5.69 by Martin Pool
BzrDirFormat subclasses can now control what kind of overall lock is used.
1244
1534.4.39 by Robert Collins
Basic BzrDir support.
1245
    def get_format_string(self):
1246
        """See BzrDirFormat.get_format_string()."""
1247
        return "Bazaar-NG branch, format 0.0.4\n"
1248
1624.3.19 by Olaf Conradi
New call get_format_description to give a user-friendly description of a
1249
    def get_format_description(self):
1250
        """See BzrDirFormat.get_format_description()."""
1251
        return "All-in-one format 4"
1252
1534.5.16 by Robert Collins
Review feedback.
1253
    def get_converter(self, format=None):
1254
        """See BzrDirFormat.get_converter()."""
1534.5.13 by Robert Collins
Correct buggy test.
1255
        # 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.
1256
        return ConvertBzrDir4To5()
1257
        
1651.1.6 by Martin Pool
Clean up clone-bzrdir code
1258
    def initialize_on_transport(self, transport):
1534.4.39 by Robert Collins
Basic BzrDir support.
1259
        """Format 4 branches cannot be created."""
1260
        raise errors.UninitializableFormat(self)
1261
1262
    def is_supported(self):
1263
        """Format 4 is not supported.
1264
1265
        It is not supported because the model changed from 4 to 5 and the
1266
        conversion logic is expensive - so doing it on the fly was not 
1267
        feasible.
1268
        """
1269
        return False
1270
1534.4.40 by Robert Collins
Add RepositoryFormats and allow bzrdir.open or create _repository to be used.
1271
    def _open(self, transport):
1272
        """See BzrDirFormat._open."""
1273
        return BzrDir4(transport, self)
1274
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.
1275
    def __return_repository_format(self):
1276
        """Circular import protection."""
1277
        from bzrlib.repository import RepositoryFormat4
1910.2.12 by Aaron Bentley
Implement knit repo format 2
1278
        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.
1279
    repository_format = property(__return_repository_format)
1280
1534.4.39 by Robert Collins
Basic BzrDir support.
1281
1282
class BzrDirFormat5(BzrDirFormat):
1283
    """Bzr control format 5.
1284
1285
    This format is a combined format for working tree, branch and repository.
1286
    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.
1287
     - Format 2 working trees [always] 
1288
     - Format 4 branches [always] 
1534.4.53 by Robert Collins
Review feedback from John Meinel.
1289
     - 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.
1290
       Unhashed stores in the repository.
1534.4.39 by Robert Collins
Basic BzrDir support.
1291
    """
1292
1996.3.3 by John Arbash Meinel
Shave off another 40ms by demand loading branch and bzrdir
1293
    _lock_class = lockable_files.TransportLock
1553.5.69 by Martin Pool
BzrDirFormat subclasses can now control what kind of overall lock is used.
1294
1534.4.39 by Robert Collins
Basic BzrDir support.
1295
    def get_format_string(self):
1296
        """See BzrDirFormat.get_format_string()."""
1297
        return "Bazaar-NG branch, format 5\n"
1298
1624.3.19 by Olaf Conradi
New call get_format_description to give a user-friendly description of a
1299
    def get_format_description(self):
1300
        """See BzrDirFormat.get_format_description()."""
1301
        return "All-in-one format 5"
1302
1534.5.16 by Robert Collins
Review feedback.
1303
    def get_converter(self, format=None):
1304
        """See BzrDirFormat.get_converter()."""
1534.5.13 by Robert Collins
Correct buggy test.
1305
        # 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.
1306
        return ConvertBzrDir5To6()
1651.1.6 by Martin Pool
Clean up clone-bzrdir code
1307
1308
    def _initialize_for_clone(self, url):
1309
        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.
1310
        
1608.2.8 by Martin Pool
Separate out BzrDir.initialize_on_transport so it
1311
    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.
1312
        """Format 5 dirs always have working tree, branch and repository.
1313
        
1314
        Except when they are being cloned.
1315
        """
1316
        from bzrlib.branch import BzrBranchFormat4
1317
        from bzrlib.repository import RepositoryFormat5
1318
        from bzrlib.workingtree import WorkingTreeFormat2
1651.1.6 by Martin Pool
Clean up clone-bzrdir code
1319
        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.
1320
        RepositoryFormat5().initialize(result, _internal=True)
1321
        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.
1322
            branch = BzrBranchFormat4().initialize(result)
1323
            try:
1324
                WorkingTreeFormat2().initialize(result)
1325
            except errors.NotLocalUrl:
1326
                # Even though we can't access the working tree, we need to
1327
                # create its control files.
1328
                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.
1329
        return result
1330
1534.4.40 by Robert Collins
Add RepositoryFormats and allow bzrdir.open or create _repository to be used.
1331
    def _open(self, transport):
1332
        """See BzrDirFormat._open."""
1333
        return BzrDir5(transport, self)
1334
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.
1335
    def __return_repository_format(self):
1336
        """Circular import protection."""
1337
        from bzrlib.repository import RepositoryFormat5
1910.2.12 by Aaron Bentley
Implement knit repo format 2
1338
        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.
1339
    repository_format = property(__return_repository_format)
1340
1534.4.39 by Robert Collins
Basic BzrDir support.
1341
1342
class BzrDirFormat6(BzrDirFormat):
1343
    """Bzr control format 6.
1344
1345
    This format is a combined format for working tree, branch and repository.
1346
    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.
1347
     - Format 2 working trees [always] 
1348
     - Format 4 branches [always] 
1349
     - Format 6 repositories [always]
1534.4.39 by Robert Collins
Basic BzrDir support.
1350
    """
1351
1996.3.3 by John Arbash Meinel
Shave off another 40ms by demand loading branch and bzrdir
1352
    _lock_class = lockable_files.TransportLock
1553.5.69 by Martin Pool
BzrDirFormat subclasses can now control what kind of overall lock is used.
1353
1534.4.39 by Robert Collins
Basic BzrDir support.
1354
    def get_format_string(self):
1355
        """See BzrDirFormat.get_format_string()."""
1356
        return "Bazaar-NG branch, format 6\n"
1357
1624.3.19 by Olaf Conradi
New call get_format_description to give a user-friendly description of a
1358
    def get_format_description(self):
1359
        """See BzrDirFormat.get_format_description()."""
1360
        return "All-in-one format 6"
1361
1534.5.16 by Robert Collins
Review feedback.
1362
    def get_converter(self, format=None):
1363
        """See BzrDirFormat.get_converter()."""
1534.5.13 by Robert Collins
Correct buggy test.
1364
        # 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.
1365
        return ConvertBzrDir6ToMeta()
1366
        
1651.1.6 by Martin Pool
Clean up clone-bzrdir code
1367
    def _initialize_for_clone(self, url):
1368
        return self.initialize_on_transport(get_transport(url), _cloning=True)
1369
1608.2.8 by Martin Pool
Separate out BzrDir.initialize_on_transport so it
1370
    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.
1371
        """Format 6 dirs always have working tree, branch and repository.
1372
        
1373
        Except when they are being cloned.
1374
        """
1375
        from bzrlib.branch import BzrBranchFormat4
1376
        from bzrlib.repository import RepositoryFormat6
1377
        from bzrlib.workingtree import WorkingTreeFormat2
1651.1.6 by Martin Pool
Clean up clone-bzrdir code
1378
        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.
1379
        RepositoryFormat6().initialize(result, _internal=True)
1380
        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.
1381
            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.
1382
            try:
1383
                WorkingTreeFormat2().initialize(result)
1384
            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.
1385
                # Even though we can't access the working tree, we need to
1386
                # create its control files.
1387
                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.
1388
        return result
1389
1534.4.40 by Robert Collins
Add RepositoryFormats and allow bzrdir.open or create _repository to be used.
1390
    def _open(self, transport):
1391
        """See BzrDirFormat._open."""
1392
        return BzrDir6(transport, self)
1393
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.
1394
    def __return_repository_format(self):
1395
        """Circular import protection."""
1396
        from bzrlib.repository import RepositoryFormat6
1910.2.12 by Aaron Bentley
Implement knit repo format 2
1397
        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.
1398
    repository_format = property(__return_repository_format)
1399
1534.4.39 by Robert Collins
Basic BzrDir support.
1400
1534.4.44 by Robert Collins
Make a new BzrDir format that uses a versioned branch format in a branch/ subdirectory.
1401
class BzrDirMetaFormat1(BzrDirFormat):
1402
    """Bzr meta control format 1
1403
1404
    This is the first format with split out working tree, branch and repository
1405
    disk storage.
1406
    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.
1407
     - Format 3 working trees [optional]
1408
     - Format 5 branches [optional]
1409
     - 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.
1410
    """
1411
1996.3.3 by John Arbash Meinel
Shave off another 40ms by demand loading branch and bzrdir
1412
    _lock_class = lockdir.LockDir
1553.5.69 by Martin Pool
BzrDirFormat subclasses can now control what kind of overall lock is used.
1413
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.
1414
    def get_converter(self, format=None):
1415
        """See BzrDirFormat.get_converter()."""
1416
        if format is None:
1417
            format = BzrDirFormat.get_default_format()
1418
        if not isinstance(self, format.__class__):
1419
            # converting away from metadir is not implemented
1420
            raise NotImplementedError(self.get_converter)
1421
        return ConvertMetaToMeta(format)
1422
1534.4.44 by Robert Collins
Make a new BzrDir format that uses a versioned branch format in a branch/ subdirectory.
1423
    def get_format_string(self):
1424
        """See BzrDirFormat.get_format_string()."""
1425
        return "Bazaar-NG meta directory, format 1\n"
1426
1624.3.19 by Olaf Conradi
New call get_format_description to give a user-friendly description of a
1427
    def get_format_description(self):
1428
        """See BzrDirFormat.get_format_description()."""
1429
        return "Meta directory format 1"
1430
1534.4.44 by Robert Collins
Make a new BzrDir format that uses a versioned branch format in a branch/ subdirectory.
1431
    def _open(self, transport):
1432
        """See BzrDirFormat._open."""
1433
        return BzrDirMeta1(transport, self)
1434
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.
1435
    def __return_repository_format(self):
1436
        """Circular import protection."""
1437
        if getattr(self, '_repository_format', None):
1438
            return self._repository_format
1439
        from bzrlib.repository import RepositoryFormat
1440
        return RepositoryFormat.get_default_format()
1441
1442
    def __set_repository_format(self, value):
1443
        """Allow changint the repository format for metadir formats."""
1444
        self._repository_format = value
1553.5.72 by Martin Pool
Clean up test for Branch5 lockdirs
1445
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.
1446
    repository_format = property(__return_repository_format, __set_repository_format)
1447
1534.4.44 by Robert Collins
Make a new BzrDir format that uses a versioned branch format in a branch/ subdirectory.
1448
1534.4.39 by Robert Collins
Basic BzrDir support.
1449
BzrDirFormat.register_format(BzrDirFormat4())
1450
BzrDirFormat.register_format(BzrDirFormat5())
1666.1.4 by Robert Collins
* 'Metadir' is now the default disk format. This improves behaviour in
1451
BzrDirFormat.register_format(BzrDirFormat6())
1452
__default_format = BzrDirMetaFormat1()
1534.4.39 by Robert Collins
Basic BzrDir support.
1453
BzrDirFormat.register_format(__default_format)
1454
BzrDirFormat.set_default_format(__default_format)
1455
1456
1457
class BzrDirTestProviderAdapter(object):
1458
    """A tool to generate a suite testing multiple bzrdir formats at once.
1459
1460
    This is done by copying the test once for each transport and injecting
1461
    the transport_server, transport_readonly_server, and bzrdir_format
1462
    classes into each copy. Each copy is also given a new id() to make it
1463
    easy to identify.
1464
    """
1465
1466
    def __init__(self, transport_server, transport_readonly_server, formats):
1467
        self._transport_server = transport_server
1468
        self._transport_readonly_server = transport_readonly_server
1469
        self._formats = formats
1470
    
1471
    def adapt(self, test):
1996.3.3 by John Arbash Meinel
Shave off another 40ms by demand loading branch and bzrdir
1472
        result = unittest.TestSuite()
1534.4.39 by Robert Collins
Basic BzrDir support.
1473
        for format in self._formats:
1474
            new_test = deepcopy(test)
1475
            new_test.transport_server = self._transport_server
1476
            new_test.transport_readonly_server = self._transport_readonly_server
1477
            new_test.bzrdir_format = format
1478
            def make_new_test_id():
1479
                new_id = "%s(%s)" % (new_test.id(), format.__class__.__name__)
1480
                return lambda: new_id
1481
            new_test.id = make_new_test_id()
1482
            result.addTest(new_test)
1483
        return result
1534.4.41 by Robert Collins
Branch now uses BzrDir reasonably sanely.
1484
1485
1534.5.7 by Robert Collins
Start factoring out the upgrade policy logic.
1486
class Converter(object):
1487
    """Converts a disk format object from one format to another."""
1488
1534.5.10 by Robert Collins
Make upgrade driver unaware of the specific formats in play.
1489
    def convert(self, to_convert, pb):
1490
        """Perform the conversion of to_convert, giving feedback via pb.
1534.5.7 by Robert Collins
Start factoring out the upgrade policy logic.
1491
1534.5.10 by Robert Collins
Make upgrade driver unaware of the specific formats in play.
1492
        :param to_convert: The disk object to convert.
1534.5.7 by Robert Collins
Start factoring out the upgrade policy logic.
1493
        :param pb: a progress bar to use for progress information.
1494
        """
1495
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.
1496
    def step(self, message):
1497
        """Update the pb by a step."""
1498
        self.count +=1
1499
        self.pb.update(message, self.count, self.total)
1500
1534.5.7 by Robert Collins
Start factoring out the upgrade policy logic.
1501
1502
class ConvertBzrDir4To5(Converter):
1503
    """Converts format 4 bzr dirs to format 5."""
1504
1534.5.10 by Robert Collins
Make upgrade driver unaware of the specific formats in play.
1505
    def __init__(self):
1506
        super(ConvertBzrDir4To5, self).__init__()
1534.5.7 by Robert Collins
Start factoring out the upgrade policy logic.
1507
        self.converted_revs = set()
1508
        self.absent_revisions = set()
1509
        self.text_count = 0
1510
        self.revisions = {}
1511
        
1534.5.10 by Robert Collins
Make upgrade driver unaware of the specific formats in play.
1512
    def convert(self, to_convert, pb):
1534.5.7 by Robert Collins
Start factoring out the upgrade policy logic.
1513
        """See Converter.convert()."""
1534.5.10 by Robert Collins
Make upgrade driver unaware of the specific formats in play.
1514
        self.bzrdir = to_convert
1515
        self.pb = pb
1534.5.7 by Robert Collins
Start factoring out the upgrade policy logic.
1516
        self.pb.note('starting upgrade from format 4 to 5')
1517
        if isinstance(self.bzrdir.transport, LocalTransport):
1518
            self.bzrdir.get_workingtree_transport(None).delete('stat-cache')
1519
        self._convert_to_weaves()
1520
        return BzrDir.open(self.bzrdir.root_transport.base)
1521
1522
    def _convert_to_weaves(self):
1523
        self.pb.note('note: upgrade may be faster if all store files are ungzipped first')
1524
        try:
1525
            # TODO permissions
1526
            stat = self.bzrdir.transport.stat('weaves')
1527
            if not S_ISDIR(stat.st_mode):
1528
                self.bzrdir.transport.delete('weaves')
1529
                self.bzrdir.transport.mkdir('weaves')
1530
        except errors.NoSuchFile:
1531
            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.
1532
        # 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.
1533
        self.inv_weave = Weave('inventory')
1534
        # holds in-memory weaves for all files
1535
        self.text_weaves = {}
1536
        self.bzrdir.transport.delete('branch-format')
1537
        self.branch = self.bzrdir.open_branch()
1538
        self._convert_working_inv()
1539
        rev_history = self.branch.revision_history()
1540
        # to_read is a stack holding the revisions we still need to process;
1541
        # appending to it adds new highest-priority revisions
1542
        self.known_revisions = set(rev_history)
1543
        self.to_read = rev_history[-1:]
1544
        while self.to_read:
1545
            rev_id = self.to_read.pop()
1546
            if (rev_id not in self.revisions
1547
                and rev_id not in self.absent_revisions):
1548
                self._load_one_rev(rev_id)
1549
        self.pb.clear()
1550
        to_import = self._make_order()
1551
        for i, rev_id in enumerate(to_import):
1552
            self.pb.update('converting revision', i, len(to_import))
1553
            self._convert_one_rev(rev_id)
1554
        self.pb.clear()
1555
        self._write_all_weaves()
1556
        self._write_all_revs()
1557
        self.pb.note('upgraded to weaves:')
1558
        self.pb.note('  %6d revisions and inventories', len(self.revisions))
1559
        self.pb.note('  %6d revisions not present', len(self.absent_revisions))
1560
        self.pb.note('  %6d texts', self.text_count)
1561
        self._cleanup_spare_files_after_format4()
1562
        self.branch.control_files.put_utf8('branch-format', BzrDirFormat5().get_format_string())
1563
1564
    def _cleanup_spare_files_after_format4(self):
1565
        # FIXME working tree upgrade foo.
1566
        for n in 'merged-patches', 'pending-merged-patches':
1567
            try:
1568
                ## assert os.path.getsize(p) == 0
1569
                self.bzrdir.transport.delete(n)
1570
            except errors.NoSuchFile:
1571
                pass
1572
        self.bzrdir.transport.delete_tree('inventory-store')
1573
        self.bzrdir.transport.delete_tree('text-store')
1574
1575
    def _convert_working_inv(self):
1996.3.6 by John Arbash Meinel
Find a few places that weren't importing their dependencies.
1576
        inv = xml4.serializer_v4.read_inventory(
1577
                    self.branch.control_files.get('inventory'))
1578
        new_inv_xml = xml5.serializer_v5.write_inventory_to_string(inv)
1534.5.7 by Robert Collins
Start factoring out the upgrade policy logic.
1579
        # 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
1580
        self.branch.control_files.put('inventory', StringIO(new_inv_xml))
1534.5.7 by Robert Collins
Start factoring out the upgrade policy logic.
1581
1582
    def _write_all_weaves(self):
1583
        controlweaves = WeaveStore(self.bzrdir.transport, prefixed=False)
1584
        weave_transport = self.bzrdir.transport.clone('weaves')
1585
        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
1586
        transaction = WriteTransaction()
1534.5.7 by Robert Collins
Start factoring out the upgrade policy logic.
1587
1588
        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.
1589
            i = 0
1534.5.7 by Robert Collins
Start factoring out the upgrade policy logic.
1590
            for file_id, file_weave in self.text_weaves.items():
1591
                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.
1592
                weaves._put_weave(file_id, file_weave, transaction)
1534.5.7 by Robert Collins
Start factoring out the upgrade policy logic.
1593
                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.
1594
            self.pb.update('inventory', 0, 1)
1595
            controlweaves._put_weave('inventory', self.inv_weave, transaction)
1596
            self.pb.update('inventory', 1, 1)
1534.5.7 by Robert Collins
Start factoring out the upgrade policy logic.
1597
        finally:
1598
            self.pb.clear()
1599
1600
    def _write_all_revs(self):
1601
        """Write all revisions out in new form."""
1602
        self.bzrdir.transport.delete_tree('revision-store')
1603
        self.bzrdir.transport.mkdir('revision-store')
1604
        revision_transport = self.bzrdir.transport.clone('revision-store')
1605
        # TODO permissions
1563.2.28 by Robert Collins
Add total_size to the revision_store api.
1606
        _revision_store = TextRevisionStore(TextStore(revision_transport,
1607
                                                      prefixed=False,
1608
                                                      compressed=True))
1534.5.7 by Robert Collins
Start factoring out the upgrade policy logic.
1609
        try:
1996.3.3 by John Arbash Meinel
Shave off another 40ms by demand loading branch and bzrdir
1610
            transaction = WriteTransaction()
1534.5.7 by Robert Collins
Start factoring out the upgrade policy logic.
1611
            for i, rev_id in enumerate(self.converted_revs):
1612
                self.pb.update('write revision', i, len(self.converted_revs))
1563.2.28 by Robert Collins
Add total_size to the revision_store api.
1613
                _revision_store.add_revision(self.revisions[rev_id], transaction)
1534.5.7 by Robert Collins
Start factoring out the upgrade policy logic.
1614
        finally:
1615
            self.pb.clear()
1616
            
1617
    def _load_one_rev(self, rev_id):
1618
        """Load a revision object into memory.
1619
1620
        Any parents not either loaded or abandoned get queued to be
1621
        loaded."""
1622
        self.pb.update('loading revision',
1623
                       len(self.revisions),
1624
                       len(self.known_revisions))
1563.2.22 by Robert Collins
Move responsibility for repository.has_revision into RevisionStore
1625
        if not self.branch.repository.has_revision(rev_id):
1534.5.7 by Robert Collins
Start factoring out the upgrade policy logic.
1626
            self.pb.clear()
1627
            self.pb.note('revision {%s} not present in branch; '
1628
                         'will be converted as a ghost',
1629
                         rev_id)
1630
            self.absent_revisions.add(rev_id)
1631
        else:
1563.2.28 by Robert Collins
Add total_size to the revision_store api.
1632
            rev = self.branch.repository._revision_store.get_revision(rev_id,
1633
                self.branch.repository.get_transaction())
1534.5.7 by Robert Collins
Start factoring out the upgrade policy logic.
1634
            for parent_id in rev.parent_ids:
1635
                self.known_revisions.add(parent_id)
1636
                self.to_read.append(parent_id)
1637
            self.revisions[rev_id] = rev
1638
1639
    def _load_old_inventory(self, rev_id):
1640
        assert rev_id not in self.converted_revs
1641
        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.
1642
        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
1643
        inv.revision_id = rev_id
1534.5.7 by Robert Collins
Start factoring out the upgrade policy logic.
1644
        rev = self.revisions[rev_id]
1645
        if rev.inventory_sha1:
1646
            assert rev.inventory_sha1 == sha_string(old_inv_xml), \
1647
                'inventory sha mismatch for {%s}' % rev_id
1648
        return inv
1649
1650
    def _load_updated_inventory(self, rev_id):
1651
        assert rev_id in self.converted_revs
1652
        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.
1653
        inv = xml5.serializer_v5.read_inventory_from_string(inv_xml)
1534.5.7 by Robert Collins
Start factoring out the upgrade policy logic.
1654
        return inv
1655
1656
    def _convert_one_rev(self, rev_id):
1657
        """Convert revision and all referenced objects to new format."""
1658
        rev = self.revisions[rev_id]
1659
        inv = self._load_old_inventory(rev_id)
1660
        present_parents = [p for p in rev.parent_ids
1661
                           if p not in self.absent_revisions]
1662
        self._convert_revision_contents(rev, inv, present_parents)
1663
        self._store_new_weave(rev, inv, present_parents)
1664
        self.converted_revs.add(rev_id)
1665
1666
    def _store_new_weave(self, rev, inv, present_parents):
1667
        # the XML is now updated with text versions
1668
        if __debug__:
1907.1.8 by Aaron Bentley
Remove is_root
1669
            entries = inv.iter_entries()
1670
            entries.next()
1671
            for path, ie in entries:
1963.2.6 by Robey Pointer
pychecker is on crack; go back to using 'is None'.
1672
                assert getattr(ie, 'revision', None) is not None, \
1534.5.7 by Robert Collins
Start factoring out the upgrade policy logic.
1673
                    'no revision on {%s} in {%s}' % \
1674
                    (file_id, rev.revision_id)
1996.3.6 by John Arbash Meinel
Find a few places that weren't importing their dependencies.
1675
        new_inv_xml = xml5.serializer_v5.write_inventory_to_string(inv)
1534.5.7 by Robert Collins
Start factoring out the upgrade policy logic.
1676
        new_inv_sha1 = sha_string(new_inv_xml)
1563.2.28 by Robert Collins
Add total_size to the revision_store api.
1677
        self.inv_weave.add_lines(rev.revision_id, 
1678
                                 present_parents,
1679
                                 new_inv_xml.splitlines(True))
1534.5.7 by Robert Collins
Start factoring out the upgrade policy logic.
1680
        rev.inventory_sha1 = new_inv_sha1
1681
1682
    def _convert_revision_contents(self, rev, inv, present_parents):
1683
        """Convert all the files within a revision.
1684
1685
        Also upgrade the inventory to refer to the text revision ids."""
1686
        rev_id = rev.revision_id
1687
        mutter('converting texts of revision {%s}',
1688
               rev_id)
1689
        parent_invs = map(self._load_updated_inventory, present_parents)
1731.1.62 by Aaron Bentley
Changes from review comments
1690
        entries = inv.iter_entries()
1691
        entries.next()
1692
        for path, ie in entries:
1534.5.7 by Robert Collins
Start factoring out the upgrade policy logic.
1693
            self._convert_file_version(rev, ie, parent_invs)
1694
1695
    def _convert_file_version(self, rev, ie, parent_invs):
1696
        """Convert one version of one file.
1697
1698
        The file needs to be added into the weave if it is a merge
1699
        of >=2 parents or if it's changed from its parent.
1700
        """
1701
        file_id = ie.file_id
1702
        rev_id = rev.revision_id
1703
        w = self.text_weaves.get(file_id)
1704
        if w is None:
1705
            w = Weave(file_id)
1706
            self.text_weaves[file_id] = w
1707
        text_changed = False
1596.2.20 by Robert Collins
optimise commit to only access weaves for merged, or altered files during commit.
1708
        previous_entries = ie.find_previous_heads(parent_invs,
1709
                                                  None,
1710
                                                  None,
1711
                                                  entry_vf=w)
1534.5.7 by Robert Collins
Start factoring out the upgrade policy logic.
1712
        for old_revision in previous_entries:
1713
                # if this fails, its a ghost ?
1731.1.33 by Aaron Bentley
Revert no-special-root changes
1714
                assert old_revision in self.converted_revs, \
1715
                    "Revision {%s} not in converted_revs" % old_revision
1534.5.7 by Robert Collins
Start factoring out the upgrade policy logic.
1716
        self.snapshot_ie(previous_entries, ie, w, rev_id)
1717
        del ie.text_id
1718
        assert getattr(ie, 'revision', None) is not None
1719
1720
    def snapshot_ie(self, previous_revisions, ie, w, rev_id):
1721
        # TODO: convert this logic, which is ~= snapshot to
1722
        # a call to:. This needs the path figured out. rather than a work_tree
1723
        # a v4 revision_tree can be given, or something that looks enough like
1724
        # one to give the file content to the entry if it needs it.
1725
        # and we need something that looks like a weave store for snapshot to 
1726
        # save against.
1727
        #ie.snapshot(rev, PATH, previous_revisions, REVISION_TREE, InMemoryWeaveStore(self.text_weaves))
1728
        if len(previous_revisions) == 1:
1729
            previous_ie = previous_revisions.values()[0]
1730
            if ie._unchanged(previous_ie):
1731
                ie.revision = previous_ie.revision
1732
                return
1733
        if ie.has_text():
1734
            text = self.branch.repository.text_store.get(ie.text_id)
1735
            file_lines = text.readlines()
1736
            assert sha_strings(file_lines) == ie.text_sha1
1737
            assert sum(map(len, file_lines)) == ie.text_size
1563.2.18 by Robert Collins
get knit repositories really using knits for text storage.
1738
            w.add_lines(rev_id, previous_revisions, file_lines)
1534.5.7 by Robert Collins
Start factoring out the upgrade policy logic.
1739
            self.text_count += 1
1740
        else:
1563.2.18 by Robert Collins
get knit repositories really using knits for text storage.
1741
            w.add_lines(rev_id, previous_revisions, [])
1534.5.7 by Robert Collins
Start factoring out the upgrade policy logic.
1742
        ie.revision = rev_id
1743
1744
    def _make_order(self):
1745
        """Return a suitable order for importing revisions.
1746
1747
        The order must be such that an revision is imported after all
1748
        its (present) parents.
1749
        """
1750
        todo = set(self.revisions.keys())
1751
        done = self.absent_revisions.copy()
1534.5.11 by Robert Collins
Implement upgrades to Metaformat trees.
1752
        order = []
1534.5.7 by Robert Collins
Start factoring out the upgrade policy logic.
1753
        while todo:
1754
            # scan through looking for a revision whose parents
1755
            # are all done
1756
            for rev_id in sorted(list(todo)):
1757
                rev = self.revisions[rev_id]
1758
                parent_ids = set(rev.parent_ids)
1759
                if parent_ids.issubset(done):
1760
                    # can take this one now
1534.5.11 by Robert Collins
Implement upgrades to Metaformat trees.
1761
                    order.append(rev_id)
1534.5.7 by Robert Collins
Start factoring out the upgrade policy logic.
1762
                    todo.remove(rev_id)
1763
                    done.add(rev_id)
1534.5.11 by Robert Collins
Implement upgrades to Metaformat trees.
1764
        return order
1534.5.7 by Robert Collins
Start factoring out the upgrade policy logic.
1765
1766
1767
class ConvertBzrDir5To6(Converter):
1768
    """Converts format 5 bzr dirs to format 6."""
1769
1534.5.10 by Robert Collins
Make upgrade driver unaware of the specific formats in play.
1770
    def convert(self, to_convert, pb):
1771
        """See Converter.convert()."""
1534.5.7 by Robert Collins
Start factoring out the upgrade policy logic.
1772
        self.bzrdir = to_convert
1534.5.10 by Robert Collins
Make upgrade driver unaware of the specific formats in play.
1773
        self.pb = pb
1534.5.7 by Robert Collins
Start factoring out the upgrade policy logic.
1774
        self.pb.note('starting upgrade from format 5 to 6')
1775
        self._convert_to_prefixed()
1776
        return BzrDir.open(self.bzrdir.root_transport.base)
1777
1778
    def _convert_to_prefixed(self):
1608.2.1 by Martin Pool
[merge] Storage filename escaping
1779
        from bzrlib.store import TransportStore
1534.5.7 by Robert Collins
Start factoring out the upgrade policy logic.
1780
        self.bzrdir.transport.delete('branch-format')
1781
        for store_name in ["weaves", "revision-store"]:
1608.2.1 by Martin Pool
[merge] Storage filename escaping
1782
            self.pb.note("adding prefixes to %s" % store_name)
1534.5.7 by Robert Collins
Start factoring out the upgrade policy logic.
1783
            store_transport = self.bzrdir.transport.clone(store_name)
1608.2.1 by Martin Pool
[merge] Storage filename escaping
1784
            store = TransportStore(store_transport, prefixed=True)
1608.1.1 by Martin Pool
[patch] LocalTransport.list_dir should return url-quoted strings (ddaa)
1785
            for urlfilename in store_transport.list_dir('.'):
1685.1.45 by John Arbash Meinel
Moved url functions into bzrlib.urlutils
1786
                filename = urlutils.unescape(urlfilename)
1534.5.7 by Robert Collins
Start factoring out the upgrade policy logic.
1787
                if (filename.endswith(".weave") or
1788
                    filename.endswith(".gz") or
1789
                    filename.endswith(".sig")):
1790
                    file_id = os.path.splitext(filename)[0]
1791
                else:
1792
                    file_id = filename
1608.2.1 by Martin Pool
[merge] Storage filename escaping
1793
                prefix_dir = store.hash_prefix(file_id)
1534.5.7 by Robert Collins
Start factoring out the upgrade policy logic.
1794
                # FIXME keep track of the dirs made RBC 20060121
1795
                try:
1796
                    store_transport.move(filename, prefix_dir + '/' + filename)
1797
                except errors.NoSuchFile: # catches missing dirs strangely enough
1798
                    store_transport.mkdir(prefix_dir)
1799
                    store_transport.move(filename, prefix_dir + '/' + filename)
1800
        self.bzrdir._control_files.put_utf8('branch-format', BzrDirFormat6().get_format_string())
1801
1802
1534.5.10 by Robert Collins
Make upgrade driver unaware of the specific formats in play.
1803
class ConvertBzrDir6ToMeta(Converter):
1804
    """Converts format 6 bzr dirs to metadirs."""
1805
1806
    def convert(self, to_convert, pb):
1807
        """See Converter.convert()."""
1808
        self.bzrdir = to_convert
1809
        self.pb = pb
1534.5.11 by Robert Collins
Implement upgrades to Metaformat trees.
1810
        self.count = 0
1811
        self.total = 20 # the steps we know about
1812
        self.garbage_inventories = []
1813
1534.5.13 by Robert Collins
Correct buggy test.
1814
        self.pb.note('starting upgrade from format 6 to metadir')
1534.5.11 by Robert Collins
Implement upgrades to Metaformat trees.
1815
        self.bzrdir._control_files.put_utf8('branch-format', "Converting to format 6")
1816
        # its faster to move specific files around than to open and use the apis...
1817
        # first off, nuke ancestry.weave, it was never used.
1818
        try:
1819
            self.step('Removing ancestry.weave')
1820
            self.bzrdir.transport.delete('ancestry.weave')
1821
        except errors.NoSuchFile:
1822
            pass
1823
        # find out whats there
1824
        self.step('Finding branch files')
1666.1.3 by Robert Collins
Fix and test upgrades from bzrdir 6 over SFTP.
1825
        last_revision = self.bzrdir.open_branch().last_revision()
1534.5.11 by Robert Collins
Implement upgrades to Metaformat trees.
1826
        bzrcontents = self.bzrdir.transport.list_dir('.')
1827
        for name in bzrcontents:
1828
            if name.startswith('basis-inventory.'):
1829
                self.garbage_inventories.append(name)
1830
        # create new directories for repository, working tree and branch
1553.5.79 by Martin Pool
upgrade to metadir should create LockDirs not files
1831
        self.dir_mode = self.bzrdir._control_files._dir_mode
1534.5.11 by Robert Collins
Implement upgrades to Metaformat trees.
1832
        self.file_mode = self.bzrdir._control_files._file_mode
1833
        repository_names = [('inventory.weave', True),
1834
                            ('revision-store', True),
1835
                            ('weaves', True)]
1836
        self.step('Upgrading repository  ')
1553.5.79 by Martin Pool
upgrade to metadir should create LockDirs not files
1837
        self.bzrdir.transport.mkdir('repository', mode=self.dir_mode)
1534.5.11 by Robert Collins
Implement upgrades to Metaformat trees.
1838
        self.make_lock('repository')
1839
        # we hard code the formats here because we are converting into
1840
        # the meta format. The meta format upgrader can take this to a 
1841
        # future format within each component.
1842
        self.put_format('repository', bzrlib.repository.RepositoryFormat7())
1843
        for entry in repository_names:
1844
            self.move_entry('repository', entry)
1845
1846
        self.step('Upgrading branch      ')
1553.5.79 by Martin Pool
upgrade to metadir should create LockDirs not files
1847
        self.bzrdir.transport.mkdir('branch', mode=self.dir_mode)
1534.5.11 by Robert Collins
Implement upgrades to Metaformat trees.
1848
        self.make_lock('branch')
1849
        self.put_format('branch', bzrlib.branch.BzrBranchFormat5())
1850
        branch_files = [('revision-history', True),
1851
                        ('branch-name', True),
1852
                        ('parent', False)]
1853
        for entry in branch_files:
1854
            self.move_entry('branch', entry)
1855
1856
        checkout_files = [('pending-merges', True),
1857
                          ('inventory', True),
1858
                          ('stat-cache', False)]
1959.3.1 by John Arbash Meinel
David Allouche: bzr upgrade should work if there is no working tree
1859
        # If a mandatory checkout file is not present, the branch does not have
1860
        # a functional checkout. Do not create a checkout in the converted
1861
        # branch.
1862
        for name, mandatory in checkout_files:
1863
            if mandatory and name not in bzrcontents:
1864
                has_checkout = False
1865
                break
1866
        else:
1867
            has_checkout = True
1868
        if not has_checkout:
1869
            self.pb.note('No working tree.')
1870
            # If some checkout files are there, we may as well get rid of them.
1871
            for name, mandatory in checkout_files:
1872
                if name in bzrcontents:
1873
                    self.bzrdir.transport.delete(name)
1874
        else:
2123.2.1 by John Arbash Meinel
Fix bug #70716, make bzrlib.bzrdir directly import bzrlib.workingtree
1875
            from bzrlib.workingtree import WorkingTreeFormat3
1959.3.1 by John Arbash Meinel
David Allouche: bzr upgrade should work if there is no working tree
1876
            self.step('Upgrading working tree')
1877
            self.bzrdir.transport.mkdir('checkout', mode=self.dir_mode)
1878
            self.make_lock('checkout')
1879
            self.put_format(
2123.2.1 by John Arbash Meinel
Fix bug #70716, make bzrlib.bzrdir directly import bzrlib.workingtree
1880
                'checkout', WorkingTreeFormat3())
1959.3.1 by John Arbash Meinel
David Allouche: bzr upgrade should work if there is no working tree
1881
            self.bzrdir.transport.delete_multi(
1882
                self.garbage_inventories, self.pb)
1883
            for entry in checkout_files:
1884
                self.move_entry('checkout', entry)
1885
            if last_revision is not None:
1886
                self.bzrdir._control_files.put_utf8(
1887
                    'checkout/last-revision', last_revision)
1888
        self.bzrdir._control_files.put_utf8(
1889
            'branch-format', BzrDirMetaFormat1().get_format_string())
1534.5.10 by Robert Collins
Make upgrade driver unaware of the specific formats in play.
1890
        return BzrDir.open(self.bzrdir.root_transport.base)
1891
1534.5.11 by Robert Collins
Implement upgrades to Metaformat trees.
1892
    def make_lock(self, name):
1893
        """Make a lock for the new control dir name."""
1894
        self.step('Make %s lock' % name)
1996.3.3 by John Arbash Meinel
Shave off another 40ms by demand loading branch and bzrdir
1895
        ld = lockdir.LockDir(self.bzrdir.transport,
1896
                             '%s/lock' % name,
1897
                             file_modebits=self.file_mode,
1898
                             dir_modebits=self.dir_mode)
1553.5.79 by Martin Pool
upgrade to metadir should create LockDirs not files
1899
        ld.create()
1534.5.11 by Robert Collins
Implement upgrades to Metaformat trees.
1900
1901
    def move_entry(self, new_dir, entry):
1902
        """Move then entry name into new_dir."""
1903
        name = entry[0]
1904
        mandatory = entry[1]
1905
        self.step('Moving %s' % name)
1906
        try:
1907
            self.bzrdir.transport.move(name, '%s/%s' % (new_dir, name))
1908
        except errors.NoSuchFile:
1909
            if mandatory:
1910
                raise
1911
1912
    def put_format(self, dirname, format):
1913
        self.bzrdir._control_files.put_utf8('%s/format' % dirname, format.get_format_string())
1914
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.
1915
1916
class ConvertMetaToMeta(Converter):
1917
    """Converts the components of metadirs."""
1918
1919
    def __init__(self, target_format):
1920
        """Create a metadir to metadir converter.
1921
1922
        :param target_format: The final metadir format that is desired.
1923
        """
1924
        self.target_format = target_format
1925
1926
    def convert(self, to_convert, pb):
1927
        """See Converter.convert()."""
1928
        self.bzrdir = to_convert
1929
        self.pb = pb
1930
        self.count = 0
1931
        self.total = 1
1932
        self.step('checking repository format')
1933
        try:
1934
            repo = self.bzrdir.open_repository()
1935
        except errors.NoRepositoryPresent:
1936
            pass
1937
        else:
1938
            if not isinstance(repo._format, self.target_format.repository_format.__class__):
1939
                from bzrlib.repository import CopyConverter
1940
                self.pb.note('starting repository conversion')
1941
                converter = CopyConverter(self.target_format.repository_format)
1942
                converter.convert(repo, pb)
1943
        return to_convert