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