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