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