/brz/remove-bazaar

To get this branch, use:
bzr branch http://gegoxaren.bato24.eu/bzr/brz/remove-bazaar

« back to all changes in this revision

Viewing changes to bzrlib/bzrdir.py

  • Committer: Robert Collins
  • Date: 2006-02-13 06:45:04 UTC
  • mto: (1534.5.2 bzr-dir)
  • mto: This revision was merged to the branch mainline in revision 1554.
  • Revision ID: robertc@robertcollins.net-20060213064504-0bb16aece9d8abd9
allow API creation of shared repositories

Show diffs side-by-side

added added

removed removed

Lines of Context:
 
1
# Copyright (C) 2005 Canonical Ltd
 
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
 
24
from cStringIO import StringIO
 
25
from unittest import TestSuite
 
26
 
 
27
 
 
28
import bzrlib
 
29
import bzrlib.errors as errors
 
30
from bzrlib.lockable_files import LockableFiles
 
31
from bzrlib.osutils import safe_unicode
 
32
from bzrlib.trace import mutter
 
33
from bzrlib.symbol_versioning import *
 
34
from bzrlib.transport import get_transport
 
35
from bzrlib.transport.local import LocalTransport
 
36
 
 
37
 
 
38
class BzrDir(object):
 
39
    """A .bzr control diretory.
 
40
    
 
41
    BzrDir instances let you create or open any of the things that can be
 
42
    found within .bzr - checkouts, branches and repositories.
 
43
    
 
44
    transport
 
45
        the transport which this bzr dir is rooted at (i.e. file:///.../.bzr/)
 
46
    root_transport
 
47
        a transport connected to the directory this bzr was opened from.
 
48
    """
 
49
 
 
50
    def _check_supported(self, format, allow_unsupported):
 
51
        """Check whether format is a supported format.
 
52
 
 
53
        If allow_unsupported is True, this is a no-op.
 
54
        """
 
55
        if not allow_unsupported and not format.is_supported():
 
56
            raise errors.UnsupportedFormatError(format)
 
57
 
 
58
    def clone(self, url, revision_id=None, basis=None):
 
59
        """Clone this bzrdir and its contents to url verbatim.
 
60
 
 
61
        If urls last component does not exist, it will be created.
 
62
 
 
63
        if revision_id is not None, then the clone operation may tune
 
64
            itself to download less data.
 
65
        """
 
66
        self._make_tail(url)
 
67
        result = self._format.initialize(url)
 
68
        basis_repo, basis_branch, basis_tree = self._get_basis_components(basis)
 
69
        try:
 
70
            self.open_repository().clone(result, revision_id=revision_id, basis=basis_repo)
 
71
        except errors.NoRepositoryPresent:
 
72
            pass
 
73
        try:
 
74
            self.open_branch().clone(result, revision_id=revision_id)
 
75
        except errors.NotBranchError:
 
76
            pass
 
77
        try:
 
78
            self.open_workingtree().clone(result, basis=basis_tree)
 
79
        except (errors.NotBranchError, errors.NotLocalUrl):
 
80
            pass
 
81
        return result
 
82
 
 
83
    def _get_basis_components(self, basis):
 
84
        """Retrieve the basis components that are available at basis."""
 
85
        if basis is None:
 
86
            return None, None, None
 
87
        try:
 
88
            basis_tree = basis.open_workingtree()
 
89
            basis_branch = basis_tree.branch
 
90
            basis_repo = basis_branch.repository
 
91
        except (errors.NoWorkingTree, errors.NotLocalUrl):
 
92
            basis_tree = None
 
93
            try:
 
94
                basis_branch = basis.open_branch()
 
95
                basis_repo = basis_branch.repository
 
96
            except errors.NotBranchError:
 
97
                basis_branch = None
 
98
                try:
 
99
                    basis_repo = basis.open_repository()
 
100
                except errors.NoRepositoryPresent:
 
101
                    basis_repo = None
 
102
        return basis_repo, basis_branch, basis_tree
 
103
 
 
104
    def _make_tail(self, url):
 
105
        segments = url.split('/')
 
106
        if segments and segments[-1] not in ('', '.'):
 
107
            parent = '/'.join(segments[:-1])
 
108
            t = bzrlib.transport.get_transport(parent)
 
109
            try:
 
110
                t.mkdir(segments[-1])
 
111
            except errors.FileExists:
 
112
                pass
 
113
 
 
114
    @staticmethod
 
115
    def create(base):
 
116
        """Create a new BzrDir at the url 'base'.
 
117
        
 
118
        This will call the current default formats initialize with base
 
119
        as the only parameter.
 
120
 
 
121
        If you need a specific format, consider creating an instance
 
122
        of that and calling initialize().
 
123
        """
 
124
        segments = base.split('/')
 
125
        if segments and segments[-1] not in ('', '.'):
 
126
            parent = '/'.join(segments[:-1])
 
127
            t = bzrlib.transport.get_transport(parent)
 
128
            try:
 
129
                t.mkdir(segments[-1])
 
130
            except errors.FileExists:
 
131
                pass
 
132
        return BzrDirFormat.get_default_format().initialize(safe_unicode(base))
 
133
 
 
134
    def create_branch(self):
 
135
        """Create a branch in this BzrDir.
 
136
 
 
137
        The bzrdirs format will control what branch format is created.
 
138
        For more control see BranchFormatXX.create(a_bzrdir).
 
139
        """
 
140
        raise NotImplementedError(self.create_branch)
 
141
 
 
142
    @staticmethod
 
143
    def create_branch_and_repo(base):
 
144
        """Create a new BzrDir, Branch and Repository at the url 'base'.
 
145
 
 
146
        This will use the current default BzrDirFormat, and use whatever 
 
147
        repository format that that uses via bzrdir.create_branch and
 
148
        create_repository.
 
149
 
 
150
        The created Branch object is returned.
 
151
        """
 
152
        bzrdir = BzrDir.create(base)
 
153
        bzrdir.create_repository()
 
154
        return bzrdir.create_branch()
 
155
        
 
156
    @staticmethod
 
157
    def create_repository(base, shared=False):
 
158
        """Create a new BzrDir and Repository at the url 'base'.
 
159
 
 
160
        This will use the current default BzrDirFormat, and use whatever 
 
161
        repository format that that uses for bzrdirformat.create_repository.
 
162
 
 
163
        ;param shared: Create a shared repository rather than a standalone
 
164
                       repository.
 
165
        The Repository object is returned.
 
166
 
 
167
        This must be overridden as an instance method in child classes, where
 
168
        it should take no parameters and construct whatever repository format
 
169
        that child class desires.
 
170
        """
 
171
        bzrdir = BzrDir.create(base)
 
172
        return bzrdir.create_repository()
 
173
 
 
174
    @staticmethod
 
175
    def create_standalone_workingtree(base):
 
176
        """Create a new BzrDir, WorkingTree, Branch and Repository at 'base'.
 
177
 
 
178
        'base' must be a local path or a file:// url.
 
179
 
 
180
        This will use the current default BzrDirFormat, and use whatever 
 
181
        repository format that that uses for bzrdirformat.create_workingtree,
 
182
        create_branch and create_repository.
 
183
 
 
184
        The WorkingTree object is returned.
 
185
        """
 
186
        t = get_transport(safe_unicode(base))
 
187
        if not isinstance(t, LocalTransport):
 
188
            raise errors.NotLocalUrl(base)
 
189
        bzrdir = BzrDir.create_branch_and_repo(safe_unicode(base)).bzrdir
 
190
        return bzrdir.create_workingtree()
 
191
 
 
192
    def create_workingtree(self):
 
193
        """Create a working tree at this BzrDir"""
 
194
        raise NotImplementedError(self.create_workingtree)
 
195
 
 
196
    def get_branch_transport(self, branch_format):
 
197
        """Get the transport for use by branch format in this BzrDir.
 
198
 
 
199
        Note that bzr dirs that do not support format strings will raise
 
200
        IncompatibleFormat if the branch format they are given has
 
201
        a format string, and vice verca.
 
202
 
 
203
        If branch_format is None, the transport is returned with no 
 
204
        checking. if it is not None, then the returned transport is
 
205
        guaranteed to point to an existing directory ready for use.
 
206
        """
 
207
        raise NotImplementedError(self.get_branch_transport)
 
208
        
 
209
    def get_repository_transport(self, repository_format):
 
210
        """Get the transport for use by repository format in this BzrDir.
 
211
 
 
212
        Note that bzr dirs that do not support format strings will raise
 
213
        IncompatibleFormat if the repository format they are given has
 
214
        a format string, and vice verca.
 
215
 
 
216
        If repository_format is None, the transport is returned with no 
 
217
        checking. if it is not None, then the returned transport is
 
218
        guaranteed to point to an existing directory ready for use.
 
219
        """
 
220
        raise NotImplementedError(self.get_repository_transport)
 
221
        
 
222
    def get_workingtree_transport(self, tree_format):
 
223
        """Get the transport for use by workingtree format in this BzrDir.
 
224
 
 
225
        Note that bzr dirs that do not support format strings will raise
 
226
        IncompatibleFormat if the workingtree format they are given has
 
227
        a format string, and vice verca.
 
228
 
 
229
        If workingtree_format is None, the transport is returned with no 
 
230
        checking. if it is not None, then the returned transport is
 
231
        guaranteed to point to an existing directory ready for use.
 
232
        """
 
233
        raise NotImplementedError(self.get_workingtree_transport)
 
234
        
 
235
    def __init__(self, _transport, _format):
 
236
        """Initialize a Bzr control dir object.
 
237
        
 
238
        Only really common logic should reside here, concrete classes should be
 
239
        made with varying behaviours.
 
240
 
 
241
        :param _format: the format that is creating this BzrDir instance.
 
242
        :param _transport: the transport this dir is based at.
 
243
        """
 
244
        self._format = _format
 
245
        self.transport = _transport.clone('.bzr')
 
246
        self.root_transport = _transport
 
247
 
 
248
    @staticmethod
 
249
    def open_unsupported(base):
 
250
        """Open a branch which is not supported."""
 
251
        return BzrDir.open(base, _unsupported=True)
 
252
        
 
253
    @staticmethod
 
254
    def open(base, _unsupported=False):
 
255
        """Open an existing bzrdir, rooted at 'base' (url)
 
256
        
 
257
        _unsupported is a private parameter to the BzrDir class.
 
258
        """
 
259
        t = get_transport(base)
 
260
        mutter("trying to open %r with transport %r", base, t)
 
261
        format = BzrDirFormat.find_format(t)
 
262
        if not _unsupported and not format.is_supported():
 
263
            # see open_downlevel to open legacy branches.
 
264
            raise errors.UnsupportedFormatError(
 
265
                    'sorry, format %s not supported' % format,
 
266
                    ['use a different bzr version',
 
267
                     'or remove the .bzr directory'
 
268
                     ' and "bzr init" again'])
 
269
        return format.open(t, _found=True)
 
270
 
 
271
    def open_branch(self, unsupported=False):
 
272
        """Open the branch object at this BzrDir if one is present.
 
273
 
 
274
        If unsupported is True, then no longer supported branch formats can
 
275
        still be opened.
 
276
        
 
277
        TODO: static convenience version of this?
 
278
        """
 
279
        raise NotImplementedError(self.open_branch)
 
280
 
 
281
    @staticmethod
 
282
    def open_containing(url):
 
283
        """Open an existing branch which contains url.
 
284
        
 
285
        This probes for a branch at url, and searches upwards from there.
 
286
 
 
287
        Basically we keep looking up until we find the control directory or
 
288
        run into the root.  If there isn't one, raises NotBranchError.
 
289
        If there is one and it is either an unrecognised format or an unsupported 
 
290
        format, UnknownFormatError or UnsupportedFormatError are raised.
 
291
        If there is one, it is returned, along with the unused portion of url.
 
292
        """
 
293
        t = get_transport(url)
 
294
        # this gets the normalised url back. I.e. '.' -> the full path.
 
295
        url = t.base
 
296
        while True:
 
297
            try:
 
298
                format = BzrDirFormat.find_format(t)
 
299
                return format.open(t), t.relpath(url)
 
300
            except errors.NotBranchError, e:
 
301
                mutter('not a branch in: %r %s', t.base, e)
 
302
            new_t = t.clone('..')
 
303
            if new_t.base == t.base:
 
304
                # reached the root, whatever that may be
 
305
                raise errors.NotBranchError(path=url)
 
306
            t = new_t
 
307
 
 
308
    def open_repository(self, _unsupported=False):
 
309
        """Open the repository object at this BzrDir if one is present.
 
310
 
 
311
        This will not follow the Branch object pointer - its strictly a direct
 
312
        open facility. Most client code should use open_branch().repository to
 
313
        get at a repository.
 
314
 
 
315
        _unsupported is a private parameter, not part of the api.
 
316
        TODO: static convenience version of this?
 
317
        """
 
318
        raise NotImplementedError(self.open_repository)
 
319
 
 
320
    def open_workingtree(self, _unsupported=False):
 
321
        """Open the workingtree object at this BzrDir if one is present.
 
322
        
 
323
        TODO: static convenience version of this?
 
324
        """
 
325
        raise NotImplementedError(self.open_workingtree)
 
326
 
 
327
    def sprout(self, url, revision_id=None, basis=None):
 
328
        """Create a copy of this bzrdir prepared for use as a new line of
 
329
        development.
 
330
 
 
331
        If urls last component does not exist, it will be created.
 
332
 
 
333
        Attributes related to the identity of the source branch like
 
334
        branch nickname will be cleaned, a working tree is created
 
335
        whether one existed before or not; and a local branch is always
 
336
        created.
 
337
 
 
338
        if revision_id is not None, then the clone operation may tune
 
339
            itself to download less data.
 
340
        """
 
341
        self._make_tail(url)
 
342
        result = self._format.initialize(url)
 
343
        basis_repo, basis_branch, basis_tree = self._get_basis_components(basis)
 
344
        try:
 
345
            source_branch = self.open_branch()
 
346
            source_repository = source_branch.repository
 
347
        except errors.NotBranchError:
 
348
            source_branch = None
 
349
            try:
 
350
                source_repository = self.open_repository()
 
351
            except errors.NoRepositoryPresent:
 
352
                # copy the basis one if there is one
 
353
                source_repository = basis_repo
 
354
        if source_repository is not None:
 
355
            source_repository.clone(result,
 
356
                                    revision_id=revision_id,
 
357
                                    basis=basis_repo)
 
358
        else:
 
359
            # no repo available, make a new one
 
360
            result.create_repository()
 
361
        if source_branch is not None:
 
362
            source_branch.sprout(result, revision_id=revision_id)
 
363
        else:
 
364
            result.create_branch()
 
365
        try:
 
366
            self.open_workingtree().clone(result,
 
367
                                          revision_id=revision_id, 
 
368
                                          basis=basis_tree)
 
369
        except (errors.NotBranchError, errors.NotLocalUrl):
 
370
            result.create_workingtree()
 
371
        return result
 
372
 
 
373
 
 
374
class BzrDirPreSplitOut(BzrDir):
 
375
    """A common class for the all-in-one formats."""
 
376
 
 
377
    def clone(self, url, revision_id=None, basis=None):
 
378
        """See BzrDir.clone()."""
 
379
        from bzrlib.workingtree import WorkingTreeFormat2
 
380
        self._make_tail(url)
 
381
        result = self._format.initialize(url, _cloning=True)
 
382
        basis_repo, basis_branch, basis_tree = self._get_basis_components(basis)
 
383
        self.open_repository().clone(result, revision_id=revision_id, basis=basis_repo)
 
384
        self.open_branch().clone(result, revision_id=revision_id)
 
385
        try:
 
386
            self.open_workingtree().clone(result, basis=basis_tree)
 
387
        except errors.NotLocalUrl:
 
388
            # make a new one, this format always has to have one.
 
389
            WorkingTreeFormat2().initialize(result)
 
390
        return result
 
391
 
 
392
    def create_branch(self):
 
393
        """See BzrDir.create_branch."""
 
394
        return self.open_branch()
 
395
 
 
396
    def create_repository(self, shared=False):
 
397
        """See BzrDir.create_repository."""
 
398
        if shared:
 
399
            raise errors.IncompatibleFormat('shared repository', self._format)
 
400
        return self.open_repository()
 
401
 
 
402
    def create_workingtree(self):
 
403
        """See BzrDir.create_workingtree."""
 
404
        return self.open_workingtree()
 
405
 
 
406
    def get_branch_transport(self, branch_format):
 
407
        """See BzrDir.get_branch_transport()."""
 
408
        if branch_format is None:
 
409
            return self.transport
 
410
        try:
 
411
            branch_format.get_format_string()
 
412
        except NotImplementedError:
 
413
            return self.transport
 
414
        raise errors.IncompatibleFormat(branch_format, self._format)
 
415
 
 
416
    def get_repository_transport(self, repository_format):
 
417
        """See BzrDir.get_repository_transport()."""
 
418
        if repository_format is None:
 
419
            return self.transport
 
420
        try:
 
421
            repository_format.get_format_string()
 
422
        except NotImplementedError:
 
423
            return self.transport
 
424
        raise errors.IncompatibleFormat(repository_format, self._format)
 
425
 
 
426
    def get_workingtree_transport(self, workingtree_format):
 
427
        """See BzrDir.get_workingtree_transport()."""
 
428
        if workingtree_format is None:
 
429
            return self.transport
 
430
        try:
 
431
            workingtree_format.get_format_string()
 
432
        except NotImplementedError:
 
433
            return self.transport
 
434
        raise errors.IncompatibleFormat(workingtree_format, self._format)
 
435
 
 
436
    def open_branch(self, unsupported=False):
 
437
        """See BzrDir.open_branch."""
 
438
        from bzrlib.branch import BzrBranchFormat4
 
439
        format = BzrBranchFormat4()
 
440
        self._check_supported(format, unsupported)
 
441
        return format.open(self, _found=True)
 
442
 
 
443
    def sprout(self, url, revision_id=None, basis=None):
 
444
        """See BzrDir.sprout()."""
 
445
        from bzrlib.workingtree import WorkingTreeFormat2
 
446
        self._make_tail(url)
 
447
        result = self._format.initialize(url, _cloning=True)
 
448
        basis_repo, basis_branch, basis_tree = self._get_basis_components(basis)
 
449
        try:
 
450
            self.open_repository().clone(result, revision_id=revision_id, basis=basis_repo)
 
451
        except errors.NoRepositoryPresent:
 
452
            pass
 
453
        try:
 
454
            self.open_branch().sprout(result, revision_id=revision_id)
 
455
        except errors.NotBranchError:
 
456
            pass
 
457
        try:
 
458
            self.open_workingtree().clone(result, basis=basis_tree)
 
459
        except (errors.NotBranchError, errors.NotLocalUrl):
 
460
            # we always want a working tree
 
461
            WorkingTreeFormat2().initialize(result)
 
462
        return result
 
463
 
 
464
 
 
465
class BzrDir4(BzrDirPreSplitOut):
 
466
    """A .bzr version 4 control object."""
 
467
 
 
468
    def create_repository(self, shared=False):
 
469
        """See BzrDir.create_repository."""
 
470
        from bzrlib.repository import RepositoryFormat4
 
471
        return RepositoryFormat4().initialize(self, shared)
 
472
 
 
473
    def open_repository(self):
 
474
        """See BzrDir.open_repository."""
 
475
        from bzrlib.repository import RepositoryFormat4
 
476
        return RepositoryFormat4().open(self, _found=True)
 
477
 
 
478
 
 
479
class BzrDir5(BzrDirPreSplitOut):
 
480
    """A .bzr version 5 control object."""
 
481
 
 
482
    def open_repository(self):
 
483
        """See BzrDir.open_repository."""
 
484
        from bzrlib.repository import RepositoryFormat5
 
485
        return RepositoryFormat5().open(self, _found=True)
 
486
 
 
487
    def open_workingtree(self, _unsupported=False):
 
488
        """See BzrDir.create_workingtree."""
 
489
        from bzrlib.workingtree import WorkingTreeFormat2
 
490
        return WorkingTreeFormat2().open(self, _found=True)
 
491
 
 
492
 
 
493
class BzrDir6(BzrDirPreSplitOut):
 
494
    """A .bzr version 6 control object."""
 
495
 
 
496
    def open_repository(self):
 
497
        """See BzrDir.open_repository."""
 
498
        from bzrlib.repository import RepositoryFormat6
 
499
        return RepositoryFormat6().open(self, _found=True)
 
500
 
 
501
    def open_workingtree(self, _unsupported=False):
 
502
        """See BzrDir.create_workingtree."""
 
503
        from bzrlib.workingtree import WorkingTreeFormat2
 
504
        return WorkingTreeFormat2().open(self, _found=True)
 
505
 
 
506
 
 
507
class BzrDirMeta1(BzrDir):
 
508
    """A .bzr meta version 1 control object.
 
509
    
 
510
    This is the first control object where the 
 
511
    individual formats are really split out.
 
512
    """
 
513
 
 
514
    def create_branch(self):
 
515
        """See BzrDir.create_branch."""
 
516
        from bzrlib.branch import BranchFormat
 
517
        return BranchFormat.get_default_format().initialize(self)
 
518
 
 
519
    def create_repository(self, shared=False):
 
520
        """See BzrDir.create_repository."""
 
521
        from bzrlib.repository import RepositoryFormat
 
522
        return RepositoryFormat.get_default_format().initialize(self, shared)
 
523
 
 
524
    def create_workingtree(self):
 
525
        """See BzrDir.create_workingtree."""
 
526
        from bzrlib.workingtree import WorkingTreeFormat
 
527
        return WorkingTreeFormat.get_default_format().initialize(self)
 
528
 
 
529
    def get_branch_transport(self, branch_format):
 
530
        """See BzrDir.get_branch_transport()."""
 
531
        if branch_format is None:
 
532
            return self.transport.clone('branch')
 
533
        try:
 
534
            branch_format.get_format_string()
 
535
        except NotImplementedError:
 
536
            raise errors.IncompatibleFormat(branch_format, self._format)
 
537
        try:
 
538
            self.transport.mkdir('branch')
 
539
        except errors.FileExists:
 
540
            pass
 
541
        return self.transport.clone('branch')
 
542
 
 
543
    def get_repository_transport(self, repository_format):
 
544
        """See BzrDir.get_repository_transport()."""
 
545
        if repository_format is None:
 
546
            return self.transport.clone('repository')
 
547
        try:
 
548
            repository_format.get_format_string()
 
549
        except NotImplementedError:
 
550
            raise errors.IncompatibleFormat(repository_format, self._format)
 
551
        try:
 
552
            self.transport.mkdir('repository')
 
553
        except errors.FileExists:
 
554
            pass
 
555
        return self.transport.clone('repository')
 
556
 
 
557
    def get_workingtree_transport(self, workingtree_format):
 
558
        """See BzrDir.get_workingtree_transport()."""
 
559
        if workingtree_format is None:
 
560
            return self.transport.clone('checkout')
 
561
        try:
 
562
            workingtree_format.get_format_string()
 
563
        except NotImplementedError:
 
564
            raise errors.IncompatibleFormat(workingtree_format, self._format)
 
565
        try:
 
566
            self.transport.mkdir('checkout')
 
567
        except errors.FileExists:
 
568
            pass
 
569
        return self.transport.clone('checkout')
 
570
 
 
571
    def open_branch(self, unsupported=False):
 
572
        """See BzrDir.open_branch."""
 
573
        from bzrlib.branch import BranchFormat
 
574
        format = BranchFormat.find_format(self)
 
575
        self._check_supported(format, unsupported)
 
576
        return format.open(self, _found=True)
 
577
 
 
578
    def open_repository(self, unsupported=False):
 
579
        """See BzrDir.open_repository."""
 
580
        from bzrlib.repository import RepositoryFormat
 
581
        format = RepositoryFormat.find_format(self)
 
582
        self._check_supported(format, unsupported)
 
583
        return format.open(self, _found=True)
 
584
 
 
585
    def open_workingtree(self, unsupported=False):
 
586
        """See BzrDir.create_workingtree."""
 
587
        from bzrlib.workingtree import WorkingTreeFormat
 
588
        format = WorkingTreeFormat.find_format(self)
 
589
        self._check_supported(format, unsupported)
 
590
        return format.open(self, _found=True)
 
591
 
 
592
 
 
593
class BzrDirFormat(object):
 
594
    """An encapsulation of the initialization and open routines for a format.
 
595
 
 
596
    Formats provide three things:
 
597
     * An initialization routine,
 
598
     * a format string,
 
599
     * an open routine.
 
600
 
 
601
    Formats are placed in an dict by their format string for reference 
 
602
    during bzrdir opening. These should be subclasses of BzrDirFormat
 
603
    for consistency.
 
604
 
 
605
    Once a format is deprecated, just deprecate the initialize and open
 
606
    methods on the format class. Do not deprecate the object, as the 
 
607
    object will be created every system load.
 
608
    """
 
609
 
 
610
    _default_format = None
 
611
    """The default format used for new .bzr dirs."""
 
612
 
 
613
    _formats = {}
 
614
    """The known formats."""
 
615
 
 
616
    @classmethod
 
617
    def find_format(klass, transport):
 
618
        """Return the format registered for URL."""
 
619
        try:
 
620
            format_string = transport.get(".bzr/branch-format").read()
 
621
            return klass._formats[format_string]
 
622
        except errors.NoSuchFile:
 
623
            raise errors.NotBranchError(path=transport.base)
 
624
        except KeyError:
 
625
            raise errors.UnknownFormatError(format_string)
 
626
 
 
627
    @classmethod
 
628
    def get_default_format(klass):
 
629
        """Return the current default format."""
 
630
        return klass._default_format
 
631
 
 
632
    def get_format_string(self):
 
633
        """Return the ASCII format string that identifies this format."""
 
634
        raise NotImplementedError(self.get_format_string)
 
635
 
 
636
    def initialize(self, url):
 
637
        """Create a bzr control dir at this url and return an opened copy."""
 
638
        # Since we don't have a .bzr directory, inherit the
 
639
        # mode from the root directory
 
640
        t = get_transport(url)
 
641
        temp_control = LockableFiles(t, '')
 
642
        temp_control._transport.mkdir('.bzr',
 
643
                                      # FIXME: RBC 20060121 dont peek under
 
644
                                      # the covers
 
645
                                      mode=temp_control._dir_mode)
 
646
        file_mode = temp_control._file_mode
 
647
        del temp_control
 
648
        mutter('created control directory in ' + t.base)
 
649
        control = t.clone('.bzr')
 
650
        lock_file = 'branch-lock'
 
651
        utf8_files = [('README', 
 
652
                       "This is a Bazaar-NG control directory.\n"
 
653
                       "Do not change any files in this directory.\n"),
 
654
                      ('branch-format', self.get_format_string()),
 
655
                      ]
 
656
        # NB: no need to escape relative paths that are url safe.
 
657
        control.put(lock_file, StringIO(), mode=file_mode)
 
658
        control_files = LockableFiles(control, lock_file)
 
659
        control_files.lock_write()
 
660
        try:
 
661
            for file, content in utf8_files:
 
662
                control_files.put_utf8(file, content)
 
663
        finally:
 
664
            control_files.unlock()
 
665
        return self.open(t, _found=True)
 
666
 
 
667
    def is_supported(self):
 
668
        """Is this format supported?
 
669
 
 
670
        Supported formats must be initializable and openable.
 
671
        Unsupported formats may not support initialization or committing or 
 
672
        some other features depending on the reason for not being supported.
 
673
        """
 
674
        return True
 
675
 
 
676
    def open(self, transport, _found=False):
 
677
        """Return an instance of this format for the dir transport points at.
 
678
        
 
679
        _found is a private parameter, do not use it.
 
680
        """
 
681
        if not _found:
 
682
            assert isinstance(BzrDirFormat.find_format(transport),
 
683
                              self.__class__)
 
684
        return self._open(transport)
 
685
 
 
686
    def _open(self, transport):
 
687
        """Template method helper for opening BzrDirectories.
 
688
 
 
689
        This performs the actual open and any additional logic or parameter
 
690
        passing.
 
691
        """
 
692
        raise NotImplementedError(self._open)
 
693
 
 
694
    @classmethod
 
695
    def register_format(klass, format):
 
696
        klass._formats[format.get_format_string()] = format
 
697
 
 
698
    @classmethod
 
699
    def set_default_format(klass, format):
 
700
        klass._default_format = format
 
701
 
 
702
    @classmethod
 
703
    def unregister_format(klass, format):
 
704
        assert klass._formats[format.get_format_string()] is format
 
705
        del klass._formats[format.get_format_string()]
 
706
 
 
707
 
 
708
class BzrDirFormat4(BzrDirFormat):
 
709
    """Bzr dir format 4.
 
710
 
 
711
    This format is a combined format for working tree, branch and repository.
 
712
    It has:
 
713
     - Format 1 working trees [always]
 
714
     - Format 4 branches [always]
 
715
     - Format 4 repositories [always]
 
716
 
 
717
    This format is deprecated: it indexes texts using a text it which is
 
718
    removed in format 5; write support for this format has been removed.
 
719
    """
 
720
 
 
721
    def get_format_string(self):
 
722
        """See BzrDirFormat.get_format_string()."""
 
723
        return "Bazaar-NG branch, format 0.0.4\n"
 
724
 
 
725
    def initialize(self, url):
 
726
        """Format 4 branches cannot be created."""
 
727
        raise errors.UninitializableFormat(self)
 
728
 
 
729
    def is_supported(self):
 
730
        """Format 4 is not supported.
 
731
 
 
732
        It is not supported because the model changed from 4 to 5 and the
 
733
        conversion logic is expensive - so doing it on the fly was not 
 
734
        feasible.
 
735
        """
 
736
        return False
 
737
 
 
738
    def _open(self, transport):
 
739
        """See BzrDirFormat._open."""
 
740
        return BzrDir4(transport, self)
 
741
 
 
742
 
 
743
class BzrDirFormat5(BzrDirFormat):
 
744
    """Bzr control format 5.
 
745
 
 
746
    This format is a combined format for working tree, branch and repository.
 
747
    It has:
 
748
     - Format 2 working trees [always] 
 
749
     - Format 4 branches [always] 
 
750
     - Format 5 repositories [always]
 
751
       Unhashed stores in the repository.
 
752
    """
 
753
 
 
754
    def get_format_string(self):
 
755
        """See BzrDirFormat.get_format_string()."""
 
756
        return "Bazaar-NG branch, format 5\n"
 
757
 
 
758
    def initialize(self, url, _cloning=False):
 
759
        """Format 5 dirs always have working tree, branch and repository.
 
760
        
 
761
        Except when they are being cloned.
 
762
        """
 
763
        from bzrlib.branch import BzrBranchFormat4
 
764
        from bzrlib.repository import RepositoryFormat5
 
765
        from bzrlib.workingtree import WorkingTreeFormat2
 
766
        result = super(BzrDirFormat5, self).initialize(url)
 
767
        RepositoryFormat5().initialize(result, _internal=True)
 
768
        if not _cloning:
 
769
            BzrBranchFormat4().initialize(result)
 
770
            WorkingTreeFormat2().initialize(result)
 
771
        return result
 
772
 
 
773
    def _open(self, transport):
 
774
        """See BzrDirFormat._open."""
 
775
        return BzrDir5(transport, self)
 
776
 
 
777
 
 
778
class BzrDirFormat6(BzrDirFormat):
 
779
    """Bzr control format 6.
 
780
 
 
781
    This format is a combined format for working tree, branch and repository.
 
782
    It has:
 
783
     - Format 2 working trees [always] 
 
784
     - Format 4 branches [always] 
 
785
     - Format 6 repositories [always]
 
786
    """
 
787
 
 
788
    def get_format_string(self):
 
789
        """See BzrDirFormat.get_format_string()."""
 
790
        return "Bazaar-NG branch, format 6\n"
 
791
 
 
792
    def initialize(self, url, _cloning=False):
 
793
        """Format 6 dirs always have working tree, branch and repository.
 
794
        
 
795
        Except when they are being cloned.
 
796
        """
 
797
        from bzrlib.branch import BzrBranchFormat4
 
798
        from bzrlib.repository import RepositoryFormat6
 
799
        from bzrlib.workingtree import WorkingTreeFormat2
 
800
        result = super(BzrDirFormat6, self).initialize(url)
 
801
        RepositoryFormat6().initialize(result, _internal=True)
 
802
        if not _cloning:
 
803
            BzrBranchFormat4().initialize(result)
 
804
            try:
 
805
                WorkingTreeFormat2().initialize(result)
 
806
            except errors.NotLocalUrl:
 
807
                # emulate pre-check behaviour for working tree and silently 
 
808
                # fail.
 
809
                pass
 
810
        return result
 
811
 
 
812
    def _open(self, transport):
 
813
        """See BzrDirFormat._open."""
 
814
        return BzrDir6(transport, self)
 
815
 
 
816
 
 
817
class BzrDirMetaFormat1(BzrDirFormat):
 
818
    """Bzr meta control format 1
 
819
 
 
820
    This is the first format with split out working tree, branch and repository
 
821
    disk storage.
 
822
    It has:
 
823
     - Format 3 working trees [optional]
 
824
     - Format 5 branches [optional]
 
825
     - Format 7 repositories [optional]
 
826
    """
 
827
 
 
828
    def get_format_string(self):
 
829
        """See BzrDirFormat.get_format_string()."""
 
830
        return "Bazaar-NG meta directory, format 1\n"
 
831
 
 
832
    def _open(self, transport):
 
833
        """See BzrDirFormat._open."""
 
834
        return BzrDirMeta1(transport, self)
 
835
 
 
836
 
 
837
BzrDirFormat.register_format(BzrDirFormat4())
 
838
BzrDirFormat.register_format(BzrDirFormat5())
 
839
BzrDirFormat.register_format(BzrDirMetaFormat1())
 
840
__default_format = BzrDirFormat6()
 
841
BzrDirFormat.register_format(__default_format)
 
842
BzrDirFormat.set_default_format(__default_format)
 
843
 
 
844
 
 
845
class BzrDirTestProviderAdapter(object):
 
846
    """A tool to generate a suite testing multiple bzrdir formats at once.
 
847
 
 
848
    This is done by copying the test once for each transport and injecting
 
849
    the transport_server, transport_readonly_server, and bzrdir_format
 
850
    classes into each copy. Each copy is also given a new id() to make it
 
851
    easy to identify.
 
852
    """
 
853
 
 
854
    def __init__(self, transport_server, transport_readonly_server, formats):
 
855
        self._transport_server = transport_server
 
856
        self._transport_readonly_server = transport_readonly_server
 
857
        self._formats = formats
 
858
    
 
859
    def adapt(self, test):
 
860
        result = TestSuite()
 
861
        for format in self._formats:
 
862
            new_test = deepcopy(test)
 
863
            new_test.transport_server = self._transport_server
 
864
            new_test.transport_readonly_server = self._transport_readonly_server
 
865
            new_test.bzrdir_format = format
 
866
            def make_new_test_id():
 
867
                new_id = "%s(%s)" % (new_test.id(), format.__class__.__name__)
 
868
                return lambda: new_id
 
869
            new_test.id = make_new_test_id()
 
870
            result.addTest(new_test)
 
871
        return result
 
872
 
 
873
 
 
874
class ScratchDir(BzrDir6):
 
875
    """Special test class: a bzrdir that cleans up itself..
 
876
 
 
877
    >>> d = ScratchDir()
 
878
    >>> base = d.transport.base
 
879
    >>> isdir(base)
 
880
    True
 
881
    >>> b.transport.__del__()
 
882
    >>> isdir(base)
 
883
    False
 
884
    """
 
885
 
 
886
    def __init__(self, files=[], dirs=[], transport=None):
 
887
        """Make a test branch.
 
888
 
 
889
        This creates a temporary directory and runs init-tree in it.
 
890
 
 
891
        If any files are listed, they are created in the working copy.
 
892
        """
 
893
        if transport is None:
 
894
            transport = bzrlib.transport.local.ScratchTransport()
 
895
            # local import for scope restriction
 
896
            BzrDirFormat6().initialize(transport.base)
 
897
            super(ScratchDir, self).__init__(transport, BzrDirFormat6())
 
898
            self.create_repository()
 
899
            self.create_branch()
 
900
            self.create_workingtree()
 
901
        else:
 
902
            super(ScratchDir, self).__init__(transport, BzrDirFormat6())
 
903
 
 
904
        # BzrBranch creates a clone to .bzr and then forgets about the
 
905
        # original transport. A ScratchTransport() deletes itself and
 
906
        # everything underneath it when it goes away, so we need to
 
907
        # grab a local copy to prevent that from happening
 
908
        self._transport = transport
 
909
 
 
910
        for d in dirs:
 
911
            self._transport.mkdir(d)
 
912
            
 
913
        for f in files:
 
914
            self._transport.put(f, 'content of %s' % f)
 
915
 
 
916
    def clone(self):
 
917
        """
 
918
        >>> orig = ScratchDir(files=["file1", "file2"])
 
919
        >>> os.listdir(orig.base)
 
920
        [u'.bzr', u'file1', u'file2']
 
921
        >>> clone = orig.clone()
 
922
        >>> if os.name != 'nt':
 
923
        ...   os.path.samefile(orig.base, clone.base)
 
924
        ... else:
 
925
        ...   orig.base == clone.base
 
926
        ...
 
927
        False
 
928
        >>> os.listdir(clone.base)
 
929
        [u'.bzr', u'file1', u'file2']
 
930
        """
 
931
        from shutil import copytree
 
932
        from bzrlib.osutils import mkdtemp
 
933
        base = mkdtemp()
 
934
        os.rmdir(base)
 
935
        copytree(self.base, base, symlinks=True)
 
936
        return ScratchDir(
 
937
            transport=bzrlib.transport.local.ScratchTransport(base))