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