~bzr-pqm/bzr/bzr.dev

« back to all changes in this revision

Viewing changes to bzrlib/bzrdir.py

Add source index to the index iteration API to allow mapping back to the origin of retrieved data.

Show diffs side-by-side

added added

removed removed

Lines of Context:
1
 
# Copyright (C) 2005 Canonical Ltd
2
 
 
 
1
# Copyright (C) 2005, 2006, 2007 Canonical Ltd
 
2
#
3
3
# This program is free software; you can redistribute it and/or modify
4
4
# it under the terms of the GNU General Public License as published by
5
5
# the Free Software Foundation; either version 2 of the License, or
6
6
# (at your option) any later version.
7
 
 
 
7
#
8
8
# This program is distributed in the hope that it will be useful,
9
9
# but WITHOUT ANY WARRANTY; without even the implied warranty of
10
10
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
11
11
# GNU General Public License for more details.
12
 
 
 
12
#
13
13
# You should have received a copy of the GNU General Public License
14
14
# along with this program; if not, write to the Free Software
15
15
# Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
20
20
directories.
21
21
"""
22
22
 
23
 
from copy import deepcopy
 
23
# TODO: Can we move specific formats into separate modules to make this file
 
24
# smaller?
 
25
 
 
26
from cStringIO import StringIO
24
27
import os
25
 
from cStringIO import StringIO
26
 
from unittest import TestSuite
 
28
import textwrap
 
29
 
 
30
from bzrlib.lazy_import import lazy_import
 
31
lazy_import(globals(), """
 
32
from stat import S_ISDIR
27
33
 
28
34
import bzrlib
29
 
import bzrlib.errors as errors
30
 
from bzrlib.lockable_files import LockableFiles
31
 
from bzrlib.osutils import safe_unicode
 
35
from bzrlib import (
 
36
    errors,
 
37
    lockable_files,
 
38
    lockdir,
 
39
    registry,
 
40
    remote,
 
41
    revision as _mod_revision,
 
42
    symbol_versioning,
 
43
    ui,
 
44
    urlutils,
 
45
    xml4,
 
46
    xml5,
 
47
    workingtree,
 
48
    workingtree_4,
 
49
    )
32
50
from bzrlib.osutils import (
33
 
                            abspath,
34
 
                            pathjoin,
35
 
                            safe_unicode,
36
 
                            sha_strings,
37
 
                            sha_string,
38
 
                            )
 
51
    sha_strings,
 
52
    sha_string,
 
53
    )
 
54
from bzrlib.smart.client import _SmartClient
 
55
from bzrlib.smart import protocol
 
56
from bzrlib.store.revision.text import TextRevisionStore
39
57
from bzrlib.store.text import TextStore
40
 
from bzrlib.store.weave import WeaveStore
41
 
from bzrlib.symbol_versioning import *
42
 
from bzrlib.trace import mutter
43
 
from bzrlib.transactions import PassThroughTransaction
44
 
from bzrlib.transport import get_transport
 
58
from bzrlib.store.versioned import WeaveStore
 
59
from bzrlib.transactions import WriteTransaction
 
60
from bzrlib.transport import (
 
61
    do_catching_redirections,
 
62
    get_transport,
 
63
    )
 
64
from bzrlib.weave import Weave
 
65
""")
 
66
 
 
67
from bzrlib.trace import (
 
68
    mutter,
 
69
    note,
 
70
    )
45
71
from bzrlib.transport.local import LocalTransport
46
 
from bzrlib.weave import Weave
47
 
from bzrlib.weavefile import read_weave, write_weave
48
 
from bzrlib.xml4 import serializer_v4
49
 
from bzrlib.xml5 import serializer_v5
50
72
 
51
73
 
52
74
class BzrDir(object):
61
83
        a transport connected to the directory this bzr was opened from.
62
84
    """
63
85
 
 
86
    def break_lock(self):
 
87
        """Invoke break_lock on the first object in the bzrdir.
 
88
 
 
89
        If there is a tree, the tree is opened and break_lock() called.
 
90
        Otherwise, branch is tried, and finally repository.
 
91
        """
 
92
        # XXX: This seems more like a UI function than something that really
 
93
        # belongs in this class.
 
94
        try:
 
95
            thing_to_unlock = self.open_workingtree()
 
96
        except (errors.NotLocalUrl, errors.NoWorkingTree):
 
97
            try:
 
98
                thing_to_unlock = self.open_branch()
 
99
            except errors.NotBranchError:
 
100
                try:
 
101
                    thing_to_unlock = self.open_repository()
 
102
                except errors.NoRepositoryPresent:
 
103
                    return
 
104
        thing_to_unlock.break_lock()
 
105
 
64
106
    def can_convert_format(self):
65
107
        """Return true if this bzrdir is one whose format we can convert from."""
66
108
        return True
67
109
 
68
 
    def _check_supported(self, format, allow_unsupported):
69
 
        """Check whether format is a supported format.
70
 
 
71
 
        If allow_unsupported is True, this is a no-op.
 
110
    def check_conversion_target(self, target_format):
 
111
        target_repo_format = target_format.repository_format
 
112
        source_repo_format = self._format.repository_format
 
113
        source_repo_format.check_conversion_target(target_repo_format)
 
114
 
 
115
    @staticmethod
 
116
    def _check_supported(format, allow_unsupported,
 
117
        recommend_upgrade=True,
 
118
        basedir=None):
 
119
        """Give an error or warning on old formats.
 
120
 
 
121
        :param format: may be any kind of format - workingtree, branch, 
 
122
        or repository.
 
123
 
 
124
        :param allow_unsupported: If true, allow opening 
 
125
        formats that are strongly deprecated, and which may 
 
126
        have limited functionality.
 
127
 
 
128
        :param recommend_upgrade: If true (default), warn
 
129
        the user through the ui object that they may wish
 
130
        to upgrade the object.
72
131
        """
 
132
        # TODO: perhaps move this into a base Format class; it's not BzrDir
 
133
        # specific. mbp 20070323
73
134
        if not allow_unsupported and not format.is_supported():
74
 
            raise errors.UnsupportedFormatError(format)
 
135
            # see open_downlevel to open legacy branches.
 
136
            raise errors.UnsupportedFormatError(format=format)
 
137
        if recommend_upgrade \
 
138
            and getattr(format, 'upgrade_recommended', False):
 
139
            ui.ui_factory.recommend_upgrade(
 
140
                format.get_format_description(),
 
141
                basedir)
75
142
 
76
 
    def clone(self, url, revision_id=None, basis=None, force_new_repo=False):
 
143
    def clone(self, url, revision_id=None, force_new_repo=False):
77
144
        """Clone this bzrdir and its contents to url verbatim.
78
145
 
79
146
        If urls last component does not exist, it will be created.
83
150
        :param force_new_repo: Do not use a shared repository for the target 
84
151
                               even if one is available.
85
152
        """
86
 
        self._make_tail(url)
87
 
        basis_repo, basis_branch, basis_tree = self._get_basis_components(basis)
88
 
        result = self._format.initialize(url)
 
153
        return self.clone_on_transport(get_transport(url),
 
154
                                       revision_id=revision_id,
 
155
                                       force_new_repo=force_new_repo)
 
156
 
 
157
    def clone_on_transport(self, transport, revision_id=None,
 
158
                           force_new_repo=False):
 
159
        """Clone this bzrdir and its contents to transport verbatim.
 
160
 
 
161
        If the target directory does not exist, it will be created.
 
162
 
 
163
        if revision_id is not None, then the clone operation may tune
 
164
            itself to download less data.
 
165
        :param force_new_repo: Do not use a shared repository for the target 
 
166
                               even if one is available.
 
167
        """
 
168
        transport.ensure_base()
 
169
        result = self._format.initialize_on_transport(transport)
89
170
        try:
90
171
            local_repo = self.find_repository()
91
172
        except errors.NoRepositoryPresent:
93
174
        if local_repo:
94
175
            # may need to copy content in
95
176
            if force_new_repo:
96
 
                local_repo.clone(result, revision_id=revision_id, basis=basis_repo)
 
177
                result_repo = local_repo.clone(
 
178
                    result,
 
179
                    revision_id=revision_id)
 
180
                result_repo.set_make_working_trees(local_repo.make_working_trees())
97
181
            else:
98
182
                try:
99
183
                    result_repo = result.find_repository()
100
184
                    # fetch content this dir needs.
101
 
                    if basis_repo:
102
 
                        # XXX FIXME RBC 20060214 need tests for this when the basis
103
 
                        # is incomplete
104
 
                        result_repo.fetch(basis_repo, revision_id=revision_id)
105
185
                    result_repo.fetch(local_repo, revision_id=revision_id)
106
186
                except errors.NoRepositoryPresent:
107
187
                    # needed to make one anyway.
108
 
                    local_repo.clone(result, revision_id=revision_id, basis=basis_repo)
 
188
                    result_repo = local_repo.clone(
 
189
                        result,
 
190
                        revision_id=revision_id)
 
191
                    result_repo.set_make_working_trees(local_repo.make_working_trees())
109
192
        # 1 if there is a branch present
110
193
        #   make sure its content is available in the target repository
111
194
        #   clone it.
114
197
        except errors.NotBranchError:
115
198
            pass
116
199
        try:
117
 
            self.open_workingtree().clone(result, basis=basis_tree)
 
200
            self.open_workingtree().clone(result)
118
201
        except (errors.NoWorkingTree, errors.NotLocalUrl):
119
202
            pass
120
203
        return result
121
204
 
122
 
    def _get_basis_components(self, basis):
123
 
        """Retrieve the basis components that are available at basis."""
124
 
        if basis is None:
125
 
            return None, None, None
126
 
        try:
127
 
            basis_tree = basis.open_workingtree()
128
 
            basis_branch = basis_tree.branch
129
 
            basis_repo = basis_branch.repository
130
 
        except (errors.NoWorkingTree, errors.NotLocalUrl):
131
 
            basis_tree = None
132
 
            try:
133
 
                basis_branch = basis.open_branch()
134
 
                basis_repo = basis_branch.repository
135
 
            except errors.NotBranchError:
136
 
                basis_branch = None
137
 
                try:
138
 
                    basis_repo = basis.open_repository()
139
 
                except errors.NoRepositoryPresent:
140
 
                    basis_repo = None
141
 
        return basis_repo, basis_branch, basis_tree
142
 
 
 
205
    # TODO: This should be given a Transport, and should chdir up; otherwise
 
206
    # this will open a new connection.
143
207
    def _make_tail(self, url):
144
 
        segments = url.split('/')
145
 
        if segments and segments[-1] not in ('', '.'):
146
 
            parent = '/'.join(segments[:-1])
147
 
            t = bzrlib.transport.get_transport(parent)
148
 
            try:
149
 
                t.mkdir(segments[-1])
150
 
            except errors.FileExists:
151
 
                pass
 
208
        t = get_transport(url)
 
209
        t.ensure_base()
152
210
 
153
 
    @staticmethod
154
 
    def create(base):
 
211
    @classmethod
 
212
    def create(cls, base, format=None, possible_transports=None):
155
213
        """Create a new BzrDir at the url 'base'.
156
214
        
157
215
        This will call the current default formats initialize with base
158
216
        as the only parameter.
159
217
 
160
 
        If you need a specific format, consider creating an instance
161
 
        of that and calling initialize().
 
218
        :param format: If supplied, the format of branch to create.  If not
 
219
            supplied, the default is used.
 
220
        :param possible_transports: If supplied, a list of transports that 
 
221
            can be reused to share a remote connection.
162
222
        """
163
 
        segments = base.split('/')
164
 
        if segments and segments[-1] not in ('', '.'):
165
 
            parent = '/'.join(segments[:-1])
166
 
            t = bzrlib.transport.get_transport(parent)
167
 
            try:
168
 
                t.mkdir(segments[-1])
169
 
            except errors.FileExists:
170
 
                pass
171
 
        return BzrDirFormat.get_default_format().initialize(safe_unicode(base))
 
223
        if cls is not BzrDir:
 
224
            raise AssertionError("BzrDir.create always creates the default"
 
225
                " format, not one of %r" % cls)
 
226
        t = get_transport(base, possible_transports)
 
227
        t.ensure_base()
 
228
        if format is None:
 
229
            format = BzrDirFormat.get_default_format()
 
230
        return format.initialize(base, possible_transports)
172
231
 
173
232
    def create_branch(self):
174
233
        """Create a branch in this BzrDir.
179
238
        raise NotImplementedError(self.create_branch)
180
239
 
181
240
    @staticmethod
182
 
    def create_branch_and_repo(base, force_new_repo=False):
 
241
    def create_branch_and_repo(base, force_new_repo=False, format=None):
183
242
        """Create a new BzrDir, Branch and Repository at the url 'base'.
184
243
 
185
244
        This will use the current default BzrDirFormat, and use whatever 
192
251
        :param base: The URL to create the branch at.
193
252
        :param force_new_repo: If True a new repository is always created.
194
253
        """
195
 
        bzrdir = BzrDir.create(base)
 
254
        bzrdir = BzrDir.create(base, format)
196
255
        bzrdir._find_or_create_repository(force_new_repo)
197
256
        return bzrdir.create_branch()
198
257
 
206
265
            return self.create_repository()
207
266
        
208
267
    @staticmethod
209
 
    def create_branch_convenience(base, force_new_repo=False, force_new_tree=None):
 
268
    def create_branch_convenience(base, force_new_repo=False,
 
269
                                  force_new_tree=None, format=None,
 
270
                                  possible_transports=None):
210
271
        """Create a new BzrDir, Branch and Repository at the url 'base'.
211
272
 
212
273
        This is a convenience function - it will use an existing repository
228
289
        :param force_new_repo: If True a new repository is always created.
229
290
        :param force_new_tree: If True or False force creation of a tree or 
230
291
                               prevent such creation respectively.
 
292
        :param format: Override for the for the bzrdir format to create.
 
293
        :param possible_transports: An optional reusable transports list.
231
294
        """
232
295
        if force_new_tree:
233
296
            # check for non local urls
234
 
            t = get_transport(safe_unicode(base))
 
297
            t = get_transport(base, possible_transports)
235
298
            if not isinstance(t, LocalTransport):
236
299
                raise errors.NotLocalUrl(base)
237
 
        bzrdir = BzrDir.create(base)
 
300
        bzrdir = BzrDir.create(base, format, possible_transports)
238
301
        repo = bzrdir._find_or_create_repository(force_new_repo)
239
302
        result = bzrdir.create_branch()
240
 
        if force_new_tree or (repo.make_working_trees() and 
 
303
        if force_new_tree or (repo.make_working_trees() and
241
304
                              force_new_tree is None):
242
305
            try:
243
306
                bzrdir.create_workingtree()
244
307
            except errors.NotLocalUrl:
245
308
                pass
246
309
        return result
247
 
        
 
310
 
248
311
    @staticmethod
249
 
    def create_repository(base, shared=False):
 
312
    def create_repository(base, shared=False, format=None):
250
313
        """Create a new BzrDir and Repository at the url 'base'.
251
314
 
252
 
        This will use the current default BzrDirFormat, and use whatever 
253
 
        repository format that that uses for bzrdirformat.create_repository.
 
315
        If no format is supplied, this will default to the current default
 
316
        BzrDirFormat by default, and use whatever repository format that that
 
317
        uses for bzrdirformat.create_repository.
254
318
 
255
 
        ;param shared: Create a shared repository rather than a standalone
 
319
        :param shared: Create a shared repository rather than a standalone
256
320
                       repository.
257
321
        The Repository object is returned.
258
322
 
260
324
        it should take no parameters and construct whatever repository format
261
325
        that child class desires.
262
326
        """
263
 
        bzrdir = BzrDir.create(base)
264
 
        return bzrdir.create_repository()
 
327
        bzrdir = BzrDir.create(base, format)
 
328
        return bzrdir.create_repository(shared)
265
329
 
266
330
    @staticmethod
267
 
    def create_standalone_workingtree(base):
 
331
    def create_standalone_workingtree(base, format=None):
268
332
        """Create a new BzrDir, WorkingTree, Branch and Repository at 'base'.
269
333
 
270
334
        'base' must be a local path or a file:// url.
273
337
        repository format that that uses for bzrdirformat.create_workingtree,
274
338
        create_branch and create_repository.
275
339
 
276
 
        The WorkingTree object is returned.
 
340
        :return: The WorkingTree object.
277
341
        """
278
 
        t = get_transport(safe_unicode(base))
 
342
        t = get_transport(base)
279
343
        if not isinstance(t, LocalTransport):
280
344
            raise errors.NotLocalUrl(base)
281
 
        bzrdir = BzrDir.create_branch_and_repo(safe_unicode(base),
282
 
                                               force_new_repo=True).bzrdir
 
345
        bzrdir = BzrDir.create_branch_and_repo(base,
 
346
                                               force_new_repo=True,
 
347
                                               format=format).bzrdir
283
348
        return bzrdir.create_workingtree()
284
349
 
285
350
    def create_workingtree(self, revision_id=None):
289
354
        """
290
355
        raise NotImplementedError(self.create_workingtree)
291
356
 
 
357
    def retire_bzrdir(self):
 
358
        """Permanently disable the bzrdir.
 
359
 
 
360
        This is done by renaming it to give the user some ability to recover
 
361
        if there was a problem.
 
362
 
 
363
        This will have horrible consequences if anyone has anything locked or
 
364
        in use.
 
365
        """
 
366
        for i in xrange(10000):
 
367
            try:
 
368
                to_path = '.bzr.retired.%d' % i
 
369
                self.root_transport.rename('.bzr', to_path)
 
370
                note("renamed %s to %s"
 
371
                    % (self.root_transport.abspath('.bzr'), to_path))
 
372
                break
 
373
            except (errors.TransportError, IOError, errors.PathError):
 
374
                pass
 
375
 
 
376
    def destroy_workingtree(self):
 
377
        """Destroy the working tree at this BzrDir.
 
378
 
 
379
        Formats that do not support this may raise UnsupportedOperation.
 
380
        """
 
381
        raise NotImplementedError(self.destroy_workingtree)
 
382
 
 
383
    def destroy_workingtree_metadata(self):
 
384
        """Destroy the control files for the working tree at this BzrDir.
 
385
 
 
386
        The contents of working tree files are not affected.
 
387
        Formats that do not support this may raise UnsupportedOperation.
 
388
        """
 
389
        raise NotImplementedError(self.destroy_workingtree_metadata)
 
390
 
292
391
    def find_repository(self):
293
392
        """Find the repository that should be used for a_bzrdir.
294
393
 
302
401
            pass
303
402
        next_transport = self.root_transport.clone('..')
304
403
        while True:
 
404
            # find the next containing bzrdir
305
405
            try:
306
406
                found_bzrdir = BzrDir.open_containing_from_transport(
307
407
                    next_transport)[0]
308
408
            except errors.NotBranchError:
 
409
                # none found
309
410
                raise errors.NoRepositoryPresent(self)
 
411
            # does it have a repository ?
310
412
            try:
311
413
                repository = found_bzrdir.open_repository()
312
414
            except errors.NoRepositoryPresent:
313
415
                next_transport = found_bzrdir.root_transport.clone('..')
314
 
                continue
315
 
            if ((found_bzrdir.root_transport.base == 
 
416
                if (found_bzrdir.root_transport.base == next_transport.base):
 
417
                    # top of the file system
 
418
                    break
 
419
                else:
 
420
                    continue
 
421
            if ((found_bzrdir.root_transport.base ==
316
422
                 self.root_transport.base) or repository.is_shared()):
317
423
                return repository
318
424
            else:
319
425
                raise errors.NoRepositoryPresent(self)
320
426
        raise errors.NoRepositoryPresent(self)
321
427
 
 
428
    def get_branch_reference(self):
 
429
        """Return the referenced URL for the branch in this bzrdir.
 
430
 
 
431
        :raises NotBranchError: If there is no Branch.
 
432
        :return: The URL the branch in this bzrdir references if it is a
 
433
            reference branch, or None for regular branches.
 
434
        """
 
435
        return None
 
436
 
322
437
    def get_branch_transport(self, branch_format):
323
438
        """Get the transport for use by branch format in this BzrDir.
324
439
 
325
440
        Note that bzr dirs that do not support format strings will raise
326
441
        IncompatibleFormat if the branch format they are given has
327
 
        a format string, and vice verca.
 
442
        a format string, and vice versa.
328
443
 
329
444
        If branch_format is None, the transport is returned with no 
330
445
        checking. if it is not None, then the returned transport is
337
452
 
338
453
        Note that bzr dirs that do not support format strings will raise
339
454
        IncompatibleFormat if the repository format they are given has
340
 
        a format string, and vice verca.
 
455
        a format string, and vice versa.
341
456
 
342
457
        If repository_format is None, the transport is returned with no 
343
458
        checking. if it is not None, then the returned transport is
349
464
        """Get the transport for use by workingtree format in this BzrDir.
350
465
 
351
466
        Note that bzr dirs that do not support format strings will raise
352
 
        IncompatibleFormat if the workingtree format they are given has
353
 
        a format string, and vice verca.
 
467
        IncompatibleFormat if the workingtree format they are given has a
 
468
        format string, and vice versa.
354
469
 
355
470
        If workingtree_format is None, the transport is returned with no 
356
471
        checking. if it is not None, then the returned transport is
371
486
        self.transport = _transport.clone('.bzr')
372
487
        self.root_transport = _transport
373
488
 
 
489
    def is_control_filename(self, filename):
 
490
        """True if filename is the name of a path which is reserved for bzrdir's.
 
491
        
 
492
        :param filename: A filename within the root transport of this bzrdir.
 
493
 
 
494
        This is true IF and ONLY IF the filename is part of the namespace reserved
 
495
        for bzr control dirs. Currently this is the '.bzr' directory in the root
 
496
        of the root_transport. it is expected that plugins will need to extend
 
497
        this in the future - for instance to make bzr talk with svn working
 
498
        trees.
 
499
        """
 
500
        # this might be better on the BzrDirFormat class because it refers to 
 
501
        # all the possible bzrdir disk formats. 
 
502
        # This method is tested via the workingtree is_control_filename tests- 
 
503
        # it was extracted from WorkingTree.is_control_filename. If the methods
 
504
        # contract is extended beyond the current trivial  implementation please
 
505
        # add new tests for it to the appropriate place.
 
506
        return filename == '.bzr' or filename.startswith('.bzr/')
 
507
 
374
508
    def needs_format_conversion(self, format=None):
375
509
        """Return true if this bzrdir needs convert_format run on it.
376
510
        
394
528
        _unsupported is a private parameter to the BzrDir class.
395
529
        """
396
530
        t = get_transport(base)
397
 
        mutter("trying to open %r with transport %r", base, t)
398
 
        format = BzrDirFormat.find_format(t)
399
 
        if not _unsupported and not format.is_supported():
400
 
            # see open_downlevel to open legacy branches.
401
 
            raise errors.UnsupportedFormatError(
402
 
                    'sorry, format %s not supported' % format,
403
 
                    ['use a different bzr version',
404
 
                     'or remove the .bzr directory'
405
 
                     ' and "bzr init" again'])
406
 
        return format.open(t, _found=True)
 
531
        return BzrDir.open_from_transport(t, _unsupported=_unsupported)
 
532
 
 
533
    @staticmethod
 
534
    def open_from_transport(transport, _unsupported=False,
 
535
                            _server_formats=True):
 
536
        """Open a bzrdir within a particular directory.
 
537
 
 
538
        :param transport: Transport containing the bzrdir.
 
539
        :param _unsupported: private.
 
540
        """
 
541
        base = transport.base
 
542
 
 
543
        def find_format(transport):
 
544
            return transport, BzrDirFormat.find_format(
 
545
                transport, _server_formats=_server_formats)
 
546
 
 
547
        def redirected(transport, e, redirection_notice):
 
548
            qualified_source = e.get_source_url()
 
549
            relpath = transport.relpath(qualified_source)
 
550
            if not e.target.endswith(relpath):
 
551
                # Not redirected to a branch-format, not a branch
 
552
                raise errors.NotBranchError(path=e.target)
 
553
            target = e.target[:-len(relpath)]
 
554
            note('%s is%s redirected to %s',
 
555
                 transport.base, e.permanently, target)
 
556
            # Let's try with a new transport
 
557
            qualified_target = e.get_target_url()[:-len(relpath)]
 
558
            # FIXME: If 'transport' has a qualifier, this should
 
559
            # be applied again to the new transport *iff* the
 
560
            # schemes used are the same. It's a bit tricky to
 
561
            # verify, so I'll punt for now
 
562
            # -- vila20070212
 
563
            return get_transport(target)
 
564
 
 
565
        try:
 
566
            transport, format = do_catching_redirections(find_format,
 
567
                                                         transport,
 
568
                                                         redirected)
 
569
        except errors.TooManyRedirections:
 
570
            raise errors.NotBranchError(base)
 
571
 
 
572
        BzrDir._check_supported(format, _unsupported)
 
573
        return format.open(transport, _found=True)
407
574
 
408
575
    def open_branch(self, unsupported=False):
409
576
        """Open the branch object at this BzrDir if one is present.
416
583
        raise NotImplementedError(self.open_branch)
417
584
 
418
585
    @staticmethod
419
 
    def open_containing(url):
 
586
    def open_containing(url, possible_transports=None):
420
587
        """Open an existing branch which contains url.
421
588
        
422
589
        :param url: url to search from.
423
590
        See open_containing_from_transport for more detail.
424
591
        """
425
 
        return BzrDir.open_containing_from_transport(get_transport(url))
 
592
        transport = get_transport(url, possible_transports)
 
593
        return BzrDir.open_containing_from_transport(transport)
426
594
    
427
595
    @staticmethod
428
596
    def open_containing_from_transport(a_transport):
435
603
        If there is one and it is either an unrecognised format or an unsupported 
436
604
        format, UnknownFormatError or UnsupportedFormatError are raised.
437
605
        If there is one, it is returned, along with the unused portion of url.
 
606
 
 
607
        :return: The BzrDir that contains the path, and a Unicode path 
 
608
                for the rest of the URL.
438
609
        """
439
610
        # this gets the normalised url back. I.e. '.' -> the full path.
440
611
        url = a_transport.base
441
612
        while True:
442
613
            try:
443
 
                format = BzrDirFormat.find_format(a_transport)
444
 
                return format.open(a_transport), a_transport.relpath(url)
 
614
                result = BzrDir.open_from_transport(a_transport)
 
615
                return result, urlutils.unescape(a_transport.relpath(url))
445
616
            except errors.NotBranchError, e:
446
 
                mutter('not a branch in: %r %s', a_transport.base, e)
447
 
            new_t = a_transport.clone('..')
 
617
                pass
 
618
            try:
 
619
                new_t = a_transport.clone('..')
 
620
            except errors.InvalidURLJoin:
 
621
                # reached the root, whatever that may be
 
622
                raise errors.NotBranchError(path=url)
448
623
            if new_t.base == a_transport.base:
449
624
                # reached the root, whatever that may be
450
625
                raise errors.NotBranchError(path=url)
451
626
            a_transport = new_t
452
627
 
 
628
    @classmethod
 
629
    def open_containing_tree_or_branch(klass, location):
 
630
        """Return the branch and working tree contained by a location.
 
631
 
 
632
        Returns (tree, branch, relpath).
 
633
        If there is no tree at containing the location, tree will be None.
 
634
        If there is no branch containing the location, an exception will be
 
635
        raised
 
636
        relpath is the portion of the path that is contained by the branch.
 
637
        """
 
638
        bzrdir, relpath = klass.open_containing(location)
 
639
        try:
 
640
            tree = bzrdir.open_workingtree()
 
641
        except (errors.NoWorkingTree, errors.NotLocalUrl):
 
642
            tree = None
 
643
            branch = bzrdir.open_branch()
 
644
        else:
 
645
            branch = tree.branch
 
646
        return tree, branch, relpath
 
647
 
453
648
    def open_repository(self, _unsupported=False):
454
649
        """Open the repository object at this BzrDir if one is present.
455
650
 
462
657
        """
463
658
        raise NotImplementedError(self.open_repository)
464
659
 
465
 
    def open_workingtree(self, _unsupported=False):
 
660
    def open_workingtree(self, _unsupported=False,
 
661
            recommend_upgrade=True):
466
662
        """Open the workingtree object at this BzrDir if one is present.
467
 
        
468
 
        TODO: static convenience version of this?
 
663
 
 
664
        :param recommend_upgrade: Optional keyword parameter, when True (the
 
665
            default), emit through the ui module a recommendation that the user
 
666
            upgrade the working tree when the workingtree being opened is old
 
667
            (but still fully supported).
469
668
        """
470
669
        raise NotImplementedError(self.open_workingtree)
471
670
 
472
 
    def sprout(self, url, revision_id=None, basis=None, force_new_repo=False):
 
671
    def has_branch(self):
 
672
        """Tell if this bzrdir contains a branch.
 
673
        
 
674
        Note: if you're going to open the branch, you should just go ahead
 
675
        and try, and not ask permission first.  (This method just opens the 
 
676
        branch and discards it, and that's somewhat expensive.) 
 
677
        """
 
678
        try:
 
679
            self.open_branch()
 
680
            return True
 
681
        except errors.NotBranchError:
 
682
            return False
 
683
 
 
684
    def has_workingtree(self):
 
685
        """Tell if this bzrdir contains a working tree.
 
686
 
 
687
        This will still raise an exception if the bzrdir has a workingtree that
 
688
        is remote & inaccessible.
 
689
        
 
690
        Note: if you're going to open the working tree, you should just go ahead
 
691
        and try, and not ask permission first.  (This method just opens the 
 
692
        workingtree and discards it, and that's somewhat expensive.) 
 
693
        """
 
694
        try:
 
695
            self.open_workingtree(recommend_upgrade=False)
 
696
            return True
 
697
        except errors.NoWorkingTree:
 
698
            return False
 
699
 
 
700
    def _cloning_metadir(self):
 
701
        """Produce a metadir suitable for cloning with"""
 
702
        result_format = self._format.__class__()
 
703
        try:
 
704
            try:
 
705
                branch = self.open_branch()
 
706
                source_repository = branch.repository
 
707
            except errors.NotBranchError:
 
708
                source_branch = None
 
709
                source_repository = self.open_repository()
 
710
        except errors.NoRepositoryPresent:
 
711
            source_repository = None
 
712
        else:
 
713
            # XXX TODO: This isinstance is here because we have not implemented
 
714
            # the fix recommended in bug # 103195 - to delegate this choice the
 
715
            # repository itself.
 
716
            repo_format = source_repository._format
 
717
            if not isinstance(repo_format, remote.RemoteRepositoryFormat):
 
718
                result_format.repository_format = repo_format
 
719
        try:
 
720
            # TODO: Couldn't we just probe for the format in these cases,
 
721
            # rather than opening the whole tree?  It would be a little
 
722
            # faster. mbp 20070401
 
723
            tree = self.open_workingtree(recommend_upgrade=False)
 
724
        except (errors.NoWorkingTree, errors.NotLocalUrl):
 
725
            result_format.workingtree_format = None
 
726
        else:
 
727
            result_format.workingtree_format = tree._format.__class__()
 
728
        return result_format, source_repository
 
729
 
 
730
    def cloning_metadir(self):
 
731
        """Produce a metadir suitable for cloning or sprouting with.
 
732
 
 
733
        These operations may produce workingtrees (yes, even though they're
 
734
        "cloning" something that doesn't have a tree, so a viable workingtree
 
735
        format must be selected.
 
736
        """
 
737
        format, repository = self._cloning_metadir()
 
738
        if format._workingtree_format is None:
 
739
            if repository is None:
 
740
                return format
 
741
            tree_format = repository._format._matchingbzrdir.workingtree_format
 
742
            format.workingtree_format = tree_format.__class__()
 
743
        return format
 
744
 
 
745
    def checkout_metadir(self):
 
746
        return self.cloning_metadir()
 
747
 
 
748
    def sprout(self, url, revision_id=None, force_new_repo=False,
 
749
               recurse='down', possible_transports=None):
473
750
        """Create a copy of this bzrdir prepared for use as a new line of
474
751
        development.
475
752
 
483
760
        if revision_id is not None, then the clone operation may tune
484
761
            itself to download less data.
485
762
        """
486
 
        self._make_tail(url)
487
 
        result = self._format.initialize(url)
488
 
        basis_repo, basis_branch, basis_tree = self._get_basis_components(basis)
 
763
        target_transport = get_transport(url, possible_transports)
 
764
        target_transport.ensure_base()
 
765
        cloning_format = self.cloning_metadir()
 
766
        result = cloning_format.initialize_on_transport(target_transport)
489
767
        try:
490
768
            source_branch = self.open_branch()
491
769
            source_repository = source_branch.repository
494
772
            try:
495
773
                source_repository = self.open_repository()
496
774
            except errors.NoRepositoryPresent:
497
 
                # copy the entire basis one if there is one
498
 
                # but there is no repository.
499
 
                source_repository = basis_repo
 
775
                source_repository = None
500
776
        if force_new_repo:
501
777
            result_repo = None
502
778
        else:
510
786
            # no repo available, make a new one
511
787
            result.create_repository()
512
788
        elif source_repository is not None and result_repo is None:
513
 
            # have soure, and want to make a new target repo
514
 
            source_repository.clone(result,
515
 
                                    revision_id=revision_id,
516
 
                                    basis=basis_repo)
 
789
            # have source, and want to make a new target repo
 
790
            result_repo = source_repository.sprout(result,
 
791
                                                   revision_id=revision_id)
517
792
        else:
518
793
            # fetch needed content into target.
519
 
            if basis_repo:
520
 
                # XXX FIXME RBC 20060214 need tests for this when the basis
521
 
                # is incomplete
522
 
                result_repo.fetch(basis_repo, revision_id=revision_id)
523
 
            result_repo.fetch(source_repository, revision_id=revision_id)
 
794
            if source_repository is not None:
 
795
                # would rather do 
 
796
                # source_repository.copy_content_into(result_repo,
 
797
                #                                     revision_id=revision_id)
 
798
                # so we can override the copy method
 
799
                result_repo.fetch(source_repository, revision_id=revision_id)
524
800
        if source_branch is not None:
525
801
            source_branch.sprout(result, revision_id=revision_id)
526
802
        else:
527
803
            result.create_branch()
528
 
        try:
529
 
            self.open_workingtree().clone(result,
530
 
                                          revision_id=revision_id, 
531
 
                                          basis=basis_tree)
532
 
        except (errors.NoWorkingTree, errors.NotLocalUrl):
533
 
            result.create_workingtree()
 
804
        if isinstance(target_transport, LocalTransport) and (
 
805
            result_repo is None or result_repo.make_working_trees()):
 
806
            wt = result.create_workingtree()
 
807
            wt.lock_write()
 
808
            try:
 
809
                if wt.path2id('') is None:
 
810
                    try:
 
811
                        wt.set_root_id(self.open_workingtree.get_root_id())
 
812
                    except errors.NoWorkingTree:
 
813
                        pass
 
814
            finally:
 
815
                wt.unlock()
 
816
        else:
 
817
            wt = None
 
818
        if recurse == 'down':
 
819
            if wt is not None:
 
820
                basis = wt.basis_tree()
 
821
                basis.lock_read()
 
822
                subtrees = basis.iter_references()
 
823
                recurse_branch = wt.branch
 
824
            elif source_branch is not None:
 
825
                basis = source_branch.basis_tree()
 
826
                basis.lock_read()
 
827
                subtrees = basis.iter_references()
 
828
                recurse_branch = source_branch
 
829
            else:
 
830
                subtrees = []
 
831
                basis = None
 
832
            try:
 
833
                for path, file_id in subtrees:
 
834
                    target = urlutils.join(url, urlutils.escape(path))
 
835
                    sublocation = source_branch.reference_parent(file_id, path)
 
836
                    sublocation.bzrdir.sprout(target,
 
837
                        basis.get_reference_revision(file_id, path),
 
838
                        force_new_repo=force_new_repo, recurse=recurse)
 
839
            finally:
 
840
                if basis is not None:
 
841
                    basis.unlock()
534
842
        return result
535
843
 
536
844
 
540
848
    def __init__(self, _transport, _format):
541
849
        """See BzrDir.__init__."""
542
850
        super(BzrDirPreSplitOut, self).__init__(_transport, _format)
543
 
        self._control_files = LockableFiles(self.get_branch_transport(None),
544
 
                                            'branch-lock')
545
 
 
546
 
    def clone(self, url, revision_id=None, basis=None, force_new_repo=False):
 
851
        assert self._format._lock_class == lockable_files.TransportLock
 
852
        assert self._format._lock_file_name == 'branch-lock'
 
853
        self._control_files = lockable_files.LockableFiles(
 
854
                                            self.get_branch_transport(None),
 
855
                                            self._format._lock_file_name,
 
856
                                            self._format._lock_class)
 
857
 
 
858
    def break_lock(self):
 
859
        """Pre-splitout bzrdirs do not suffer from stale locks."""
 
860
        raise NotImplementedError(self.break_lock)
 
861
 
 
862
    def clone(self, url, revision_id=None, force_new_repo=False):
547
863
        """See BzrDir.clone()."""
548
864
        from bzrlib.workingtree import WorkingTreeFormat2
549
865
        self._make_tail(url)
550
 
        result = self._format.initialize(url, _cloning=True)
551
 
        basis_repo, basis_branch, basis_tree = self._get_basis_components(basis)
552
 
        self.open_repository().clone(result, revision_id=revision_id, basis=basis_repo)
553
 
        self.open_branch().clone(result, revision_id=revision_id)
 
866
        result = self._format._initialize_for_clone(url)
 
867
        self.open_repository().clone(result, revision_id=revision_id)
 
868
        from_branch = self.open_branch()
 
869
        from_branch.clone(result, revision_id=revision_id)
554
870
        try:
555
 
            self.open_workingtree().clone(result, basis=basis_tree)
 
871
            self.open_workingtree().clone(result)
556
872
        except errors.NotLocalUrl:
557
873
            # make a new one, this format always has to have one.
558
 
            WorkingTreeFormat2().initialize(result)
 
874
            try:
 
875
                WorkingTreeFormat2().initialize(result)
 
876
            except errors.NotLocalUrl:
 
877
                # but we cannot do it for remote trees.
 
878
                to_branch = result.open_branch()
 
879
                WorkingTreeFormat2().stub_initialize_remote(to_branch.control_files)
559
880
        return result
560
881
 
561
882
    def create_branch(self):
571
892
    def create_workingtree(self, revision_id=None):
572
893
        """See BzrDir.create_workingtree."""
573
894
        # this looks buggy but is not -really-
 
895
        # because this format creates the workingtree when the bzrdir is
 
896
        # created
574
897
        # clone and sprout will have set the revision_id
575
898
        # and that will have set it for us, its only
576
899
        # specific uses of create_workingtree in isolation
577
900
        # that can do wonky stuff here, and that only
578
901
        # happens for creating checkouts, which cannot be 
579
902
        # done on this format anyway. So - acceptable wart.
580
 
        result = self.open_workingtree()
 
903
        result = self.open_workingtree(recommend_upgrade=False)
581
904
        if revision_id is not None:
582
 
            result.set_last_revision(revision_id)
 
905
            if revision_id == _mod_revision.NULL_REVISION:
 
906
                result.set_parent_ids([])
 
907
            else:
 
908
                result.set_parent_ids([revision_id])
583
909
        return result
584
910
 
 
911
    def destroy_workingtree(self):
 
912
        """See BzrDir.destroy_workingtree."""
 
913
        raise errors.UnsupportedOperation(self.destroy_workingtree, self)
 
914
 
 
915
    def destroy_workingtree_metadata(self):
 
916
        """See BzrDir.destroy_workingtree_metadata."""
 
917
        raise errors.UnsupportedOperation(self.destroy_workingtree_metadata, 
 
918
                                          self)
 
919
 
585
920
    def get_branch_transport(self, branch_format):
586
921
        """See BzrDir.get_branch_transport()."""
587
922
        if branch_format is None:
627
962
        self._check_supported(format, unsupported)
628
963
        return format.open(self, _found=True)
629
964
 
630
 
    def sprout(self, url, revision_id=None, basis=None):
 
965
    def sprout(self, url, revision_id=None, force_new_repo=False,
 
966
               possible_transports=None):
631
967
        """See BzrDir.sprout()."""
632
968
        from bzrlib.workingtree import WorkingTreeFormat2
633
969
        self._make_tail(url)
634
 
        result = self._format.initialize(url, _cloning=True)
635
 
        basis_repo, basis_branch, basis_tree = self._get_basis_components(basis)
 
970
        result = self._format._initialize_for_clone(url)
636
971
        try:
637
 
            self.open_repository().clone(result, revision_id=revision_id, basis=basis_repo)
 
972
            self.open_repository().clone(result, revision_id=revision_id)
638
973
        except errors.NoRepositoryPresent:
639
974
            pass
640
975
        try:
641
976
            self.open_branch().sprout(result, revision_id=revision_id)
642
977
        except errors.NotBranchError:
643
978
            pass
644
 
        try:
645
 
            self.open_workingtree().clone(result, basis=basis_tree)
646
 
        except (errors.NotBranchError, errors.NotLocalUrl):
647
 
            # we always want a working tree
648
 
            WorkingTreeFormat2().initialize(result)
 
979
        # we always want a working tree
 
980
        WorkingTreeFormat2().initialize(result)
649
981
        return result
650
982
 
651
983
 
665
997
 
666
998
    def open_repository(self):
667
999
        """See BzrDir.open_repository."""
668
 
        from bzrlib.repository import RepositoryFormat4
 
1000
        from bzrlib.repofmt.weaverepo import RepositoryFormat4
669
1001
        return RepositoryFormat4().open(self, _found=True)
670
1002
 
671
1003
 
677
1009
 
678
1010
    def open_repository(self):
679
1011
        """See BzrDir.open_repository."""
680
 
        from bzrlib.repository import RepositoryFormat5
 
1012
        from bzrlib.repofmt.weaverepo import RepositoryFormat5
681
1013
        return RepositoryFormat5().open(self, _found=True)
682
1014
 
683
 
    def open_workingtree(self, _unsupported=False):
 
1015
    def open_workingtree(self, _unsupported=False,
 
1016
            recommend_upgrade=True):
684
1017
        """See BzrDir.create_workingtree."""
685
1018
        from bzrlib.workingtree import WorkingTreeFormat2
686
 
        return WorkingTreeFormat2().open(self, _found=True)
 
1019
        wt_format = WorkingTreeFormat2()
 
1020
        # we don't warn here about upgrades; that ought to be handled for the
 
1021
        # bzrdir as a whole
 
1022
        return wt_format.open(self, _found=True)
687
1023
 
688
1024
 
689
1025
class BzrDir6(BzrDirPreSplitOut):
694
1030
 
695
1031
    def open_repository(self):
696
1032
        """See BzrDir.open_repository."""
697
 
        from bzrlib.repository import RepositoryFormat6
 
1033
        from bzrlib.repofmt.weaverepo import RepositoryFormat6
698
1034
        return RepositoryFormat6().open(self, _found=True)
699
1035
 
700
 
    def open_workingtree(self, _unsupported=False):
 
1036
    def open_workingtree(self, _unsupported=False,
 
1037
        recommend_upgrade=True):
701
1038
        """See BzrDir.create_workingtree."""
 
1039
        # we don't warn here about upgrades; that ought to be handled for the
 
1040
        # bzrdir as a whole
702
1041
        from bzrlib.workingtree import WorkingTreeFormat2
703
1042
        return WorkingTreeFormat2().open(self, _found=True)
704
1043
 
707
1046
    """A .bzr meta version 1 control object.
708
1047
    
709
1048
    This is the first control object where the 
710
 
    individual formats are really split out.
 
1049
    individual aspects are really split out: there are separate repository,
 
1050
    workingtree and branch subdirectories and any subset of the three can be
 
1051
    present within a BzrDir.
711
1052
    """
712
1053
 
713
1054
    def can_convert_format(self):
716
1057
 
717
1058
    def create_branch(self):
718
1059
        """See BzrDir.create_branch."""
719
 
        from bzrlib.branch import BranchFormat
720
 
        return BranchFormat.get_default_format().initialize(self)
 
1060
        return self._format.get_branch_format().initialize(self)
721
1061
 
722
1062
    def create_repository(self, shared=False):
723
1063
        """See BzrDir.create_repository."""
726
1066
    def create_workingtree(self, revision_id=None):
727
1067
        """See BzrDir.create_workingtree."""
728
1068
        from bzrlib.workingtree import WorkingTreeFormat
729
 
        return WorkingTreeFormat.get_default_format().initialize(self, revision_id)
 
1069
        return self._format.workingtree_format.initialize(self, revision_id)
 
1070
 
 
1071
    def destroy_workingtree(self):
 
1072
        """See BzrDir.destroy_workingtree."""
 
1073
        wt = self.open_workingtree(recommend_upgrade=False)
 
1074
        repository = wt.branch.repository
 
1075
        empty = repository.revision_tree(_mod_revision.NULL_REVISION)
 
1076
        wt.revert([], old_tree=empty)
 
1077
        self.destroy_workingtree_metadata()
 
1078
 
 
1079
    def destroy_workingtree_metadata(self):
 
1080
        self.transport.delete_tree('checkout')
 
1081
 
 
1082
    def find_branch_format(self):
 
1083
        """Find the branch 'format' for this bzrdir.
 
1084
 
 
1085
        This might be a synthetic object for e.g. RemoteBranch and SVN.
 
1086
        """
 
1087
        from bzrlib.branch import BranchFormat
 
1088
        return BranchFormat.find_format(self)
 
1089
 
 
1090
    def _get_mkdir_mode(self):
 
1091
        """Figure out the mode to use when creating a bzrdir subdir."""
 
1092
        temp_control = lockable_files.LockableFiles(self.transport, '',
 
1093
                                     lockable_files.TransportLock)
 
1094
        return temp_control._dir_mode
 
1095
 
 
1096
    def get_branch_reference(self):
 
1097
        """See BzrDir.get_branch_reference()."""
 
1098
        from bzrlib.branch import BranchFormat
 
1099
        format = BranchFormat.find_format(self)
 
1100
        return format.get_reference(self)
730
1101
 
731
1102
    def get_branch_transport(self, branch_format):
732
1103
        """See BzrDir.get_branch_transport()."""
737
1108
        except NotImplementedError:
738
1109
            raise errors.IncompatibleFormat(branch_format, self._format)
739
1110
        try:
740
 
            self.transport.mkdir('branch')
 
1111
            self.transport.mkdir('branch', mode=self._get_mkdir_mode())
741
1112
        except errors.FileExists:
742
1113
            pass
743
1114
        return self.transport.clone('branch')
751
1122
        except NotImplementedError:
752
1123
            raise errors.IncompatibleFormat(repository_format, self._format)
753
1124
        try:
754
 
            self.transport.mkdir('repository')
 
1125
            self.transport.mkdir('repository', mode=self._get_mkdir_mode())
755
1126
        except errors.FileExists:
756
1127
            pass
757
1128
        return self.transport.clone('repository')
765
1136
        except NotImplementedError:
766
1137
            raise errors.IncompatibleFormat(workingtree_format, self._format)
767
1138
        try:
768
 
            self.transport.mkdir('checkout')
 
1139
            self.transport.mkdir('checkout', mode=self._get_mkdir_mode())
769
1140
        except errors.FileExists:
770
1141
            pass
771
1142
        return self.transport.clone('checkout')
785
1156
                return True
786
1157
        except errors.NoRepositoryPresent:
787
1158
            pass
788
 
        # currently there are no other possible conversions for meta1 formats.
 
1159
        try:
 
1160
            if not isinstance(self.open_branch()._format,
 
1161
                              format.get_branch_format().__class__):
 
1162
                # the branch needs an upgrade.
 
1163
                return True
 
1164
        except errors.NotBranchError:
 
1165
            pass
 
1166
        try:
 
1167
            my_wt = self.open_workingtree(recommend_upgrade=False)
 
1168
            if not isinstance(my_wt._format,
 
1169
                              format.workingtree_format.__class__):
 
1170
                # the workingtree needs an upgrade.
 
1171
                return True
 
1172
        except (errors.NoWorkingTree, errors.NotLocalUrl):
 
1173
            pass
789
1174
        return False
790
1175
 
791
1176
    def open_branch(self, unsupported=False):
792
1177
        """See BzrDir.open_branch."""
793
 
        from bzrlib.branch import BranchFormat
794
 
        format = BranchFormat.find_format(self)
 
1178
        format = self.find_branch_format()
795
1179
        self._check_supported(format, unsupported)
796
1180
        return format.open(self, _found=True)
797
1181
 
802
1186
        self._check_supported(format, unsupported)
803
1187
        return format.open(self, _found=True)
804
1188
 
805
 
    def open_workingtree(self, unsupported=False):
 
1189
    def open_workingtree(self, unsupported=False,
 
1190
            recommend_upgrade=True):
806
1191
        """See BzrDir.open_workingtree."""
807
1192
        from bzrlib.workingtree import WorkingTreeFormat
808
1193
        format = WorkingTreeFormat.find_format(self)
809
 
        self._check_supported(format, unsupported)
 
1194
        self._check_supported(format, unsupported,
 
1195
            recommend_upgrade,
 
1196
            basedir=self.root_transport.base)
810
1197
        return format.open(self, _found=True)
811
1198
 
812
1199
 
833
1220
    _formats = {}
834
1221
    """The known formats."""
835
1222
 
836
 
    @classmethod
837
 
    def find_format(klass, transport):
838
 
        """Return the format registered for URL."""
 
1223
    _control_formats = []
 
1224
    """The registered control formats - .bzr, ....
 
1225
    
 
1226
    This is a list of BzrDirFormat objects.
 
1227
    """
 
1228
 
 
1229
    _control_server_formats = []
 
1230
    """The registered control server formats, e.g. RemoteBzrDirs.
 
1231
 
 
1232
    This is a list of BzrDirFormat objects.
 
1233
    """
 
1234
 
 
1235
    _lock_file_name = 'branch-lock'
 
1236
 
 
1237
    # _lock_class must be set in subclasses to the lock type, typ.
 
1238
    # TransportLock or LockDir
 
1239
 
 
1240
    @classmethod
 
1241
    def find_format(klass, transport, _server_formats=True):
 
1242
        """Return the format present at transport."""
 
1243
        if _server_formats:
 
1244
            formats = klass._control_server_formats + klass._control_formats
 
1245
        else:
 
1246
            formats = klass._control_formats
 
1247
        for format in formats:
 
1248
            try:
 
1249
                return format.probe_transport(transport)
 
1250
            except errors.NotBranchError:
 
1251
                # this format does not find a control dir here.
 
1252
                pass
 
1253
        raise errors.NotBranchError(path=transport.base)
 
1254
 
 
1255
    @classmethod
 
1256
    def probe_transport(klass, transport):
 
1257
        """Return the .bzrdir style format present in a directory."""
839
1258
        try:
840
1259
            format_string = transport.get(".bzr/branch-format").read()
 
1260
        except errors.NoSuchFile:
 
1261
            raise errors.NotBranchError(path=transport.base)
 
1262
 
 
1263
        try:
841
1264
            return klass._formats[format_string]
842
 
        except errors.NoSuchFile:
843
 
            raise errors.NotBranchError(path=transport.base)
844
1265
        except KeyError:
845
 
            raise errors.UnknownFormatError(format_string)
 
1266
            raise errors.UnknownFormatError(format=format_string)
846
1267
 
847
1268
    @classmethod
848
1269
    def get_default_format(klass):
853
1274
        """Return the ASCII format string that identifies this format."""
854
1275
        raise NotImplementedError(self.get_format_string)
855
1276
 
 
1277
    def get_format_description(self):
 
1278
        """Return the short description for this format."""
 
1279
        raise NotImplementedError(self.get_format_description)
 
1280
 
856
1281
    def get_converter(self, format=None):
857
1282
        """Return the converter to use to convert bzrdirs needing converts.
858
1283
 
859
1284
        This returns a bzrlib.bzrdir.Converter object.
860
1285
 
861
1286
        This should return the best upgrader to step this format towards the
862
 
        current default format. In the case of plugins we can/shouold provide
 
1287
        current default format. In the case of plugins we can/should provide
863
1288
        some means for them to extend the range of returnable converters.
864
1289
 
865
 
        :param format: Optional format to override the default foramt of the 
 
1290
        :param format: Optional format to override the default format of the 
866
1291
                       library.
867
1292
        """
868
1293
        raise NotImplementedError(self.get_converter)
869
1294
 
870
 
    def initialize(self, url):
871
 
        """Create a bzr control dir at this url and return an opened copy."""
 
1295
    def initialize(self, url, possible_transports=None):
 
1296
        """Create a bzr control dir at this url and return an opened copy.
 
1297
        
 
1298
        Subclasses should typically override initialize_on_transport
 
1299
        instead of this method.
 
1300
        """
 
1301
        return self.initialize_on_transport(get_transport(url,
 
1302
                                                          possible_transports))
 
1303
 
 
1304
    def initialize_on_transport(self, transport):
 
1305
        """Initialize a new bzrdir in the base directory of a Transport."""
872
1306
        # Since we don't have a .bzr directory, inherit the
873
1307
        # mode from the root directory
874
 
        t = get_transport(url)
875
 
        temp_control = LockableFiles(t, '')
 
1308
        temp_control = lockable_files.LockableFiles(transport,
 
1309
                            '', lockable_files.TransportLock)
876
1310
        temp_control._transport.mkdir('.bzr',
877
 
                                      # FIXME: RBC 20060121 dont peek under
 
1311
                                      # FIXME: RBC 20060121 don't peek under
878
1312
                                      # the covers
879
1313
                                      mode=temp_control._dir_mode)
880
1314
        file_mode = temp_control._file_mode
881
1315
        del temp_control
882
 
        mutter('created control directory in ' + t.base)
883
 
        control = t.clone('.bzr')
884
 
        lock_file = 'branch-lock'
 
1316
        mutter('created control directory in ' + transport.base)
 
1317
        control = transport.clone('.bzr')
885
1318
        utf8_files = [('README', 
886
1319
                       "This is a Bazaar-NG control directory.\n"
887
1320
                       "Do not change any files in this directory.\n"),
888
1321
                      ('branch-format', self.get_format_string()),
889
1322
                      ]
890
1323
        # NB: no need to escape relative paths that are url safe.
891
 
        control.put(lock_file, StringIO(), mode=file_mode)
892
 
        control_files = LockableFiles(control, lock_file)
 
1324
        control_files = lockable_files.LockableFiles(control,
 
1325
                            self._lock_file_name, self._lock_class)
 
1326
        control_files.create_lock()
893
1327
        control_files.lock_write()
894
1328
        try:
895
1329
            for file, content in utf8_files:
896
1330
                control_files.put_utf8(file, content)
897
1331
        finally:
898
1332
            control_files.unlock()
899
 
        return self.open(t, _found=True)
 
1333
        return self.open(transport, _found=True)
900
1334
 
901
1335
    def is_supported(self):
902
1336
        """Is this format supported?
907
1341
        """
908
1342
        return True
909
1343
 
 
1344
    def same_model(self, target_format):
 
1345
        return (self.repository_format.rich_root_data == 
 
1346
            target_format.rich_root_data)
 
1347
 
 
1348
    @classmethod
 
1349
    def known_formats(klass):
 
1350
        """Return all the known formats.
 
1351
        
 
1352
        Concrete formats should override _known_formats.
 
1353
        """
 
1354
        # There is double indirection here to make sure that control 
 
1355
        # formats used by more than one dir format will only be probed 
 
1356
        # once. This can otherwise be quite expensive for remote connections.
 
1357
        result = set()
 
1358
        for format in klass._control_formats:
 
1359
            result.update(format._known_formats())
 
1360
        return result
 
1361
    
 
1362
    @classmethod
 
1363
    def _known_formats(klass):
 
1364
        """Return the known format instances for this control format."""
 
1365
        return set(klass._formats.values())
 
1366
 
910
1367
    def open(self, transport, _found=False):
911
1368
        """Return an instance of this format for the dir transport points at.
912
1369
        
913
1370
        _found is a private parameter, do not use it.
914
1371
        """
915
1372
        if not _found:
916
 
            assert isinstance(BzrDirFormat.find_format(transport),
917
 
                              self.__class__)
 
1373
            found_format = BzrDirFormat.find_format(transport)
 
1374
            if not isinstance(found_format, self.__class__):
 
1375
                raise AssertionError("%s was asked to open %s, but it seems to need "
 
1376
                        "format %s" 
 
1377
                        % (self, transport, found_format))
918
1378
        return self._open(transport)
919
1379
 
920
1380
    def _open(self, transport):
930
1390
        klass._formats[format.get_format_string()] = format
931
1391
 
932
1392
    @classmethod
 
1393
    def register_control_format(klass, format):
 
1394
        """Register a format that does not use '.bzr' for its control dir.
 
1395
 
 
1396
        TODO: This should be pulled up into a 'ControlDirFormat' base class
 
1397
        which BzrDirFormat can inherit from, and renamed to register_format 
 
1398
        there. It has been done without that for now for simplicity of
 
1399
        implementation.
 
1400
        """
 
1401
        klass._control_formats.append(format)
 
1402
 
 
1403
    @classmethod
 
1404
    def register_control_server_format(klass, format):
 
1405
        """Register a control format for client-server environments.
 
1406
 
 
1407
        These formats will be tried before ones registered with
 
1408
        register_control_format.  This gives implementations that decide to the
 
1409
        chance to grab it before anything looks at the contents of the format
 
1410
        file.
 
1411
        """
 
1412
        klass._control_server_formats.append(format)
 
1413
 
 
1414
    @classmethod
 
1415
    @symbol_versioning.deprecated_method(symbol_versioning.zero_fourteen)
933
1416
    def set_default_format(klass, format):
 
1417
        klass._set_default_format(format)
 
1418
 
 
1419
    @classmethod
 
1420
    def _set_default_format(klass, format):
 
1421
        """Set default format (for testing behavior of defaults only)"""
934
1422
        klass._default_format = format
935
1423
 
936
1424
    def __str__(self):
941
1429
        assert klass._formats[format.get_format_string()] is format
942
1430
        del klass._formats[format.get_format_string()]
943
1431
 
 
1432
    @classmethod
 
1433
    def unregister_control_format(klass, format):
 
1434
        klass._control_formats.remove(format)
 
1435
 
944
1436
 
945
1437
class BzrDirFormat4(BzrDirFormat):
946
1438
    """Bzr dir format 4.
955
1447
    removed in format 5; write support for this format has been removed.
956
1448
    """
957
1449
 
 
1450
    _lock_class = lockable_files.TransportLock
 
1451
 
958
1452
    def get_format_string(self):
959
1453
        """See BzrDirFormat.get_format_string()."""
960
1454
        return "Bazaar-NG branch, format 0.0.4\n"
961
1455
 
 
1456
    def get_format_description(self):
 
1457
        """See BzrDirFormat.get_format_description()."""
 
1458
        return "All-in-one format 4"
 
1459
 
962
1460
    def get_converter(self, format=None):
963
1461
        """See BzrDirFormat.get_converter()."""
964
1462
        # there is one and only one upgrade path here.
965
1463
        return ConvertBzrDir4To5()
966
1464
        
967
 
    def initialize(self, url):
 
1465
    def initialize_on_transport(self, transport):
968
1466
        """Format 4 branches cannot be created."""
969
1467
        raise errors.UninitializableFormat(self)
970
1468
 
983
1481
 
984
1482
    def __return_repository_format(self):
985
1483
        """Circular import protection."""
986
 
        from bzrlib.repository import RepositoryFormat4
987
 
        return RepositoryFormat4(self)
 
1484
        from bzrlib.repofmt.weaverepo import RepositoryFormat4
 
1485
        return RepositoryFormat4()
988
1486
    repository_format = property(__return_repository_format)
989
1487
 
990
1488
 
999
1497
       Unhashed stores in the repository.
1000
1498
    """
1001
1499
 
 
1500
    _lock_class = lockable_files.TransportLock
 
1501
 
1002
1502
    def get_format_string(self):
1003
1503
        """See BzrDirFormat.get_format_string()."""
1004
1504
        return "Bazaar-NG branch, format 5\n"
1005
1505
 
 
1506
    def get_format_description(self):
 
1507
        """See BzrDirFormat.get_format_description()."""
 
1508
        return "All-in-one format 5"
 
1509
 
1006
1510
    def get_converter(self, format=None):
1007
1511
        """See BzrDirFormat.get_converter()."""
1008
1512
        # there is one and only one upgrade path here.
1009
1513
        return ConvertBzrDir5To6()
 
1514
 
 
1515
    def _initialize_for_clone(self, url):
 
1516
        return self.initialize_on_transport(get_transport(url), _cloning=True)
1010
1517
        
1011
 
    def initialize(self, url, _cloning=False):
 
1518
    def initialize_on_transport(self, transport, _cloning=False):
1012
1519
        """Format 5 dirs always have working tree, branch and repository.
1013
1520
        
1014
1521
        Except when they are being cloned.
1015
1522
        """
1016
1523
        from bzrlib.branch import BzrBranchFormat4
1017
 
        from bzrlib.repository import RepositoryFormat5
 
1524
        from bzrlib.repofmt.weaverepo import RepositoryFormat5
1018
1525
        from bzrlib.workingtree import WorkingTreeFormat2
1019
 
        result = super(BzrDirFormat5, self).initialize(url)
 
1526
        result = (super(BzrDirFormat5, self).initialize_on_transport(transport))
1020
1527
        RepositoryFormat5().initialize(result, _internal=True)
1021
1528
        if not _cloning:
1022
 
            BzrBranchFormat4().initialize(result)
1023
 
            WorkingTreeFormat2().initialize(result)
 
1529
            branch = BzrBranchFormat4().initialize(result)
 
1530
            try:
 
1531
                WorkingTreeFormat2().initialize(result)
 
1532
            except errors.NotLocalUrl:
 
1533
                # Even though we can't access the working tree, we need to
 
1534
                # create its control files.
 
1535
                WorkingTreeFormat2().stub_initialize_remote(branch.control_files)
1024
1536
        return result
1025
1537
 
1026
1538
    def _open(self, transport):
1029
1541
 
1030
1542
    def __return_repository_format(self):
1031
1543
        """Circular import protection."""
1032
 
        from bzrlib.repository import RepositoryFormat5
1033
 
        return RepositoryFormat5(self)
 
1544
        from bzrlib.repofmt.weaverepo import RepositoryFormat5
 
1545
        return RepositoryFormat5()
1034
1546
    repository_format = property(__return_repository_format)
1035
1547
 
1036
1548
 
1044
1556
     - Format 6 repositories [always]
1045
1557
    """
1046
1558
 
 
1559
    _lock_class = lockable_files.TransportLock
 
1560
 
1047
1561
    def get_format_string(self):
1048
1562
        """See BzrDirFormat.get_format_string()."""
1049
1563
        return "Bazaar-NG branch, format 6\n"
1050
1564
 
 
1565
    def get_format_description(self):
 
1566
        """See BzrDirFormat.get_format_description()."""
 
1567
        return "All-in-one format 6"
 
1568
 
1051
1569
    def get_converter(self, format=None):
1052
1570
        """See BzrDirFormat.get_converter()."""
1053
1571
        # there is one and only one upgrade path here.
1054
1572
        return ConvertBzrDir6ToMeta()
1055
1573
        
1056
 
    def initialize(self, url, _cloning=False):
 
1574
    def _initialize_for_clone(self, url):
 
1575
        return self.initialize_on_transport(get_transport(url), _cloning=True)
 
1576
 
 
1577
    def initialize_on_transport(self, transport, _cloning=False):
1057
1578
        """Format 6 dirs always have working tree, branch and repository.
1058
1579
        
1059
1580
        Except when they are being cloned.
1060
1581
        """
1061
1582
        from bzrlib.branch import BzrBranchFormat4
1062
 
        from bzrlib.repository import RepositoryFormat6
 
1583
        from bzrlib.repofmt.weaverepo import RepositoryFormat6
1063
1584
        from bzrlib.workingtree import WorkingTreeFormat2
1064
 
        result = super(BzrDirFormat6, self).initialize(url)
 
1585
        result = super(BzrDirFormat6, self).initialize_on_transport(transport)
1065
1586
        RepositoryFormat6().initialize(result, _internal=True)
1066
1587
        if not _cloning:
1067
 
            BzrBranchFormat4().initialize(result)
 
1588
            branch = BzrBranchFormat4().initialize(result)
1068
1589
            try:
1069
1590
                WorkingTreeFormat2().initialize(result)
1070
1591
            except errors.NotLocalUrl:
1071
 
                # emulate pre-check behaviour for working tree and silently 
1072
 
                # fail.
1073
 
                pass
 
1592
                # Even though we can't access the working tree, we need to
 
1593
                # create its control files.
 
1594
                WorkingTreeFormat2().stub_initialize_remote(branch.control_files)
1074
1595
        return result
1075
1596
 
1076
1597
    def _open(self, transport):
1079
1600
 
1080
1601
    def __return_repository_format(self):
1081
1602
        """Circular import protection."""
1082
 
        from bzrlib.repository import RepositoryFormat6
1083
 
        return RepositoryFormat6(self)
 
1603
        from bzrlib.repofmt.weaverepo import RepositoryFormat6
 
1604
        return RepositoryFormat6()
1084
1605
    repository_format = property(__return_repository_format)
1085
1606
 
1086
1607
 
1095
1616
     - Format 7 repositories [optional]
1096
1617
    """
1097
1618
 
 
1619
    _lock_class = lockdir.LockDir
 
1620
 
 
1621
    def __init__(self):
 
1622
        self._workingtree_format = None
 
1623
        self._branch_format = None
 
1624
 
 
1625
    def __eq__(self, other):
 
1626
        if other.__class__ is not self.__class__:
 
1627
            return False
 
1628
        if other.repository_format != self.repository_format:
 
1629
            return False
 
1630
        if other.workingtree_format != self.workingtree_format:
 
1631
            return False
 
1632
        return True
 
1633
 
 
1634
    def __ne__(self, other):
 
1635
        return not self == other
 
1636
 
 
1637
    def get_branch_format(self):
 
1638
        if self._branch_format is None:
 
1639
            from bzrlib.branch import BranchFormat
 
1640
            self._branch_format = BranchFormat.get_default_format()
 
1641
        return self._branch_format
 
1642
 
 
1643
    def set_branch_format(self, format):
 
1644
        self._branch_format = format
 
1645
 
1098
1646
    def get_converter(self, format=None):
1099
1647
        """See BzrDirFormat.get_converter()."""
1100
1648
        if format is None:
1108
1656
        """See BzrDirFormat.get_format_string()."""
1109
1657
        return "Bazaar-NG meta directory, format 1\n"
1110
1658
 
 
1659
    def get_format_description(self):
 
1660
        """See BzrDirFormat.get_format_description()."""
 
1661
        return "Meta directory format 1"
 
1662
 
1111
1663
    def _open(self, transport):
1112
1664
        """See BzrDirFormat._open."""
1113
1665
        return BzrDirMeta1(transport, self)
1122
1674
    def __set_repository_format(self, value):
1123
1675
        """Allow changint the repository format for metadir formats."""
1124
1676
        self._repository_format = value
 
1677
 
1125
1678
    repository_format = property(__return_repository_format, __set_repository_format)
1126
1679
 
1127
 
 
 
1680
    def __get_workingtree_format(self):
 
1681
        if self._workingtree_format is None:
 
1682
            from bzrlib.workingtree import WorkingTreeFormat
 
1683
            self._workingtree_format = WorkingTreeFormat.get_default_format()
 
1684
        return self._workingtree_format
 
1685
 
 
1686
    def __set_workingtree_format(self, wt_format):
 
1687
        self._workingtree_format = wt_format
 
1688
 
 
1689
    workingtree_format = property(__get_workingtree_format,
 
1690
                                  __set_workingtree_format)
 
1691
 
 
1692
 
 
1693
# Register bzr control format
 
1694
BzrDirFormat.register_control_format(BzrDirFormat)
 
1695
 
 
1696
# Register bzr formats
1128
1697
BzrDirFormat.register_format(BzrDirFormat4())
1129
1698
BzrDirFormat.register_format(BzrDirFormat5())
1130
 
BzrDirFormat.register_format(BzrDirMetaFormat1())
1131
 
__default_format = BzrDirFormat6()
 
1699
BzrDirFormat.register_format(BzrDirFormat6())
 
1700
__default_format = BzrDirMetaFormat1()
1132
1701
BzrDirFormat.register_format(__default_format)
1133
 
BzrDirFormat.set_default_format(__default_format)
1134
 
 
1135
 
 
1136
 
class BzrDirTestProviderAdapter(object):
1137
 
    """A tool to generate a suite testing multiple bzrdir formats at once.
1138
 
 
1139
 
    This is done by copying the test once for each transport and injecting
1140
 
    the transport_server, transport_readonly_server, and bzrdir_format
1141
 
    classes into each copy. Each copy is also given a new id() to make it
1142
 
    easy to identify.
1143
 
    """
1144
 
 
1145
 
    def __init__(self, transport_server, transport_readonly_server, formats):
1146
 
        self._transport_server = transport_server
1147
 
        self._transport_readonly_server = transport_readonly_server
1148
 
        self._formats = formats
1149
 
    
1150
 
    def adapt(self, test):
1151
 
        result = TestSuite()
1152
 
        for format in self._formats:
1153
 
            new_test = deepcopy(test)
1154
 
            new_test.transport_server = self._transport_server
1155
 
            new_test.transport_readonly_server = self._transport_readonly_server
1156
 
            new_test.bzrdir_format = format
1157
 
            def make_new_test_id():
1158
 
                new_id = "%s(%s)" % (new_test.id(), format.__class__.__name__)
1159
 
                return lambda: new_id
1160
 
            new_test.id = make_new_test_id()
1161
 
            result.addTest(new_test)
1162
 
        return result
1163
 
 
1164
 
 
1165
 
class ScratchDir(BzrDir6):
1166
 
    """Special test class: a bzrdir that cleans up itself..
1167
 
 
1168
 
    >>> d = ScratchDir()
1169
 
    >>> base = d.transport.base
1170
 
    >>> isdir(base)
1171
 
    True
1172
 
    >>> b.transport.__del__()
1173
 
    >>> isdir(base)
1174
 
    False
1175
 
    """
1176
 
 
1177
 
    def __init__(self, files=[], dirs=[], transport=None):
1178
 
        """Make a test branch.
1179
 
 
1180
 
        This creates a temporary directory and runs init-tree in it.
1181
 
 
1182
 
        If any files are listed, they are created in the working copy.
1183
 
        """
1184
 
        if transport is None:
1185
 
            transport = bzrlib.transport.local.ScratchTransport()
1186
 
            # local import for scope restriction
1187
 
            BzrDirFormat6().initialize(transport.base)
1188
 
            super(ScratchDir, self).__init__(transport, BzrDirFormat6())
1189
 
            self.create_repository()
1190
 
            self.create_branch()
1191
 
            self.create_workingtree()
1192
 
        else:
1193
 
            super(ScratchDir, self).__init__(transport, BzrDirFormat6())
1194
 
 
1195
 
        # BzrBranch creates a clone to .bzr and then forgets about the
1196
 
        # original transport. A ScratchTransport() deletes itself and
1197
 
        # everything underneath it when it goes away, so we need to
1198
 
        # grab a local copy to prevent that from happening
1199
 
        self._transport = transport
1200
 
 
1201
 
        for d in dirs:
1202
 
            self._transport.mkdir(d)
1203
 
            
1204
 
        for f in files:
1205
 
            self._transport.put(f, 'content of %s' % f)
1206
 
 
1207
 
    def clone(self):
1208
 
        """
1209
 
        >>> orig = ScratchDir(files=["file1", "file2"])
1210
 
        >>> os.listdir(orig.base)
1211
 
        [u'.bzr', u'file1', u'file2']
1212
 
        >>> clone = orig.clone()
1213
 
        >>> if os.name != 'nt':
1214
 
        ...   os.path.samefile(orig.base, clone.base)
1215
 
        ... else:
1216
 
        ...   orig.base == clone.base
1217
 
        ...
1218
 
        False
1219
 
        >>> os.listdir(clone.base)
1220
 
        [u'.bzr', u'file1', u'file2']
1221
 
        """
1222
 
        from shutil import copytree
1223
 
        from bzrlib.osutils import mkdtemp
1224
 
        base = mkdtemp()
1225
 
        os.rmdir(base)
1226
 
        copytree(self.base, base, symlinks=True)
1227
 
        return ScratchDir(
1228
 
            transport=bzrlib.transport.local.ScratchTransport(base))
 
1702
BzrDirFormat._default_format = __default_format
1229
1703
 
1230
1704
 
1231
1705
class Converter(object):
1274
1748
                self.bzrdir.transport.mkdir('weaves')
1275
1749
        except errors.NoSuchFile:
1276
1750
            self.bzrdir.transport.mkdir('weaves')
 
1751
        # deliberately not a WeaveFile as we want to build it up slowly.
1277
1752
        self.inv_weave = Weave('inventory')
1278
1753
        # holds in-memory weaves for all files
1279
1754
        self.text_weaves = {}
1317
1792
        self.bzrdir.transport.delete_tree('text-store')
1318
1793
 
1319
1794
    def _convert_working_inv(self):
1320
 
        inv = serializer_v4.read_inventory(self.branch.control_files.get('inventory'))
1321
 
        new_inv_xml = serializer_v5.write_inventory_to_string(inv)
 
1795
        inv = xml4.serializer_v4.read_inventory(
 
1796
                    self.branch.control_files.get('inventory'))
 
1797
        new_inv_xml = xml5.serializer_v5.write_inventory_to_string(inv)
1322
1798
        # FIXME inventory is a working tree change.
1323
 
        self.branch.control_files.put('inventory', new_inv_xml)
 
1799
        self.branch.control_files.put('inventory', StringIO(new_inv_xml))
1324
1800
 
1325
1801
    def _write_all_weaves(self):
1326
1802
        controlweaves = WeaveStore(self.bzrdir.transport, prefixed=False)
1327
1803
        weave_transport = self.bzrdir.transport.clone('weaves')
1328
1804
        weaves = WeaveStore(weave_transport, prefixed=False)
1329
 
        transaction = PassThroughTransaction()
 
1805
        transaction = WriteTransaction()
1330
1806
 
1331
 
        controlweaves.put_weave('inventory', self.inv_weave, transaction)
1332
 
        i = 0
1333
1807
        try:
 
1808
            i = 0
1334
1809
            for file_id, file_weave in self.text_weaves.items():
1335
1810
                self.pb.update('writing weave', i, len(self.text_weaves))
1336
 
                weaves.put_weave(file_id, file_weave, transaction)
 
1811
                weaves._put_weave(file_id, file_weave, transaction)
1337
1812
                i += 1
 
1813
            self.pb.update('inventory', 0, 1)
 
1814
            controlweaves._put_weave('inventory', self.inv_weave, transaction)
 
1815
            self.pb.update('inventory', 1, 1)
1338
1816
        finally:
1339
1817
            self.pb.clear()
1340
1818
 
1344
1822
        self.bzrdir.transport.mkdir('revision-store')
1345
1823
        revision_transport = self.bzrdir.transport.clone('revision-store')
1346
1824
        # TODO permissions
1347
 
        revision_store = TextStore(revision_transport,
1348
 
                                   prefixed=False,
1349
 
                                   compressed=True)
 
1825
        _revision_store = TextRevisionStore(TextStore(revision_transport,
 
1826
                                                      prefixed=False,
 
1827
                                                      compressed=True))
1350
1828
        try:
 
1829
            transaction = WriteTransaction()
1351
1830
            for i, rev_id in enumerate(self.converted_revs):
1352
1831
                self.pb.update('write revision', i, len(self.converted_revs))
1353
 
                rev_tmp = StringIO()
1354
 
                serializer_v5.write_revision(self.revisions[rev_id], rev_tmp)
1355
 
                rev_tmp.seek(0)
1356
 
                revision_store.add(rev_tmp, rev_id)
 
1832
                _revision_store.add_revision(self.revisions[rev_id], transaction)
1357
1833
        finally:
1358
1834
            self.pb.clear()
1359
1835
            
1365
1841
        self.pb.update('loading revision',
1366
1842
                       len(self.revisions),
1367
1843
                       len(self.known_revisions))
1368
 
        if not self.branch.repository.revision_store.has_id(rev_id):
 
1844
        if not self.branch.repository.has_revision(rev_id):
1369
1845
            self.pb.clear()
1370
1846
            self.pb.note('revision {%s} not present in branch; '
1371
1847
                         'will be converted as a ghost',
1372
1848
                         rev_id)
1373
1849
            self.absent_revisions.add(rev_id)
1374
1850
        else:
1375
 
            rev_xml = self.branch.repository.revision_store.get(rev_id).read()
1376
 
            rev = serializer_v4.read_revision_from_string(rev_xml)
 
1851
            rev = self.branch.repository._revision_store.get_revision(rev_id,
 
1852
                self.branch.repository.get_transaction())
1377
1853
            for parent_id in rev.parent_ids:
1378
1854
                self.known_revisions.add(parent_id)
1379
1855
                self.to_read.append(parent_id)
1382
1858
    def _load_old_inventory(self, rev_id):
1383
1859
        assert rev_id not in self.converted_revs
1384
1860
        old_inv_xml = self.branch.repository.inventory_store.get(rev_id).read()
1385
 
        inv = serializer_v4.read_inventory_from_string(old_inv_xml)
 
1861
        inv = xml4.serializer_v4.read_inventory_from_string(old_inv_xml)
 
1862
        inv.revision_id = rev_id
1386
1863
        rev = self.revisions[rev_id]
1387
1864
        if rev.inventory_sha1:
1388
1865
            assert rev.inventory_sha1 == sha_string(old_inv_xml), \
1392
1869
    def _load_updated_inventory(self, rev_id):
1393
1870
        assert rev_id in self.converted_revs
1394
1871
        inv_xml = self.inv_weave.get_text(rev_id)
1395
 
        inv = serializer_v5.read_inventory_from_string(inv_xml)
 
1872
        inv = xml5.serializer_v5.read_inventory_from_string(inv_xml)
1396
1873
        return inv
1397
1874
 
1398
1875
    def _convert_one_rev(self, rev_id):
1408
1885
    def _store_new_weave(self, rev, inv, present_parents):
1409
1886
        # the XML is now updated with text versions
1410
1887
        if __debug__:
1411
 
            for file_id in inv:
1412
 
                ie = inv[file_id]
1413
 
                if ie.kind == 'root_directory':
1414
 
                    continue
1415
 
                assert hasattr(ie, 'revision'), \
 
1888
            entries = inv.iter_entries()
 
1889
            entries.next()
 
1890
            for path, ie in entries:
 
1891
                assert getattr(ie, 'revision', None) is not None, \
1416
1892
                    'no revision on {%s} in {%s}' % \
1417
1893
                    (file_id, rev.revision_id)
1418
 
        new_inv_xml = serializer_v5.write_inventory_to_string(inv)
 
1894
        new_inv_xml = xml5.serializer_v5.write_inventory_to_string(inv)
1419
1895
        new_inv_sha1 = sha_string(new_inv_xml)
1420
 
        self.inv_weave.add(rev.revision_id, 
1421
 
                           present_parents,
1422
 
                           new_inv_xml.splitlines(True),
1423
 
                           new_inv_sha1)
 
1896
        self.inv_weave.add_lines(rev.revision_id, 
 
1897
                                 present_parents,
 
1898
                                 new_inv_xml.splitlines(True))
1424
1899
        rev.inventory_sha1 = new_inv_sha1
1425
1900
 
1426
1901
    def _convert_revision_contents(self, rev, inv, present_parents):
1431
1906
        mutter('converting texts of revision {%s}',
1432
1907
               rev_id)
1433
1908
        parent_invs = map(self._load_updated_inventory, present_parents)
1434
 
        for file_id in inv:
1435
 
            ie = inv[file_id]
 
1909
        entries = inv.iter_entries()
 
1910
        entries.next()
 
1911
        for path, ie in entries:
1436
1912
            self._convert_file_version(rev, ie, parent_invs)
1437
1913
 
1438
1914
    def _convert_file_version(self, rev, ie, parent_invs):
1441
1917
        The file needs to be added into the weave if it is a merge
1442
1918
        of >=2 parents or if it's changed from its parent.
1443
1919
        """
1444
 
        if ie.kind == 'root_directory':
1445
 
            return
1446
1920
        file_id = ie.file_id
1447
1921
        rev_id = rev.revision_id
1448
1922
        w = self.text_weaves.get(file_id)
1450
1924
            w = Weave(file_id)
1451
1925
            self.text_weaves[file_id] = w
1452
1926
        text_changed = False
1453
 
        previous_entries = ie.find_previous_heads(parent_invs, w)
 
1927
        previous_entries = ie.find_previous_heads(parent_invs,
 
1928
                                                  None,
 
1929
                                                  None,
 
1930
                                                  entry_vf=w)
1454
1931
        for old_revision in previous_entries:
1455
1932
                # if this fails, its a ghost ?
1456
 
                assert old_revision in self.converted_revs 
 
1933
                assert old_revision in self.converted_revs, \
 
1934
                    "Revision {%s} not in converted_revs" % old_revision
1457
1935
        self.snapshot_ie(previous_entries, ie, w, rev_id)
1458
1936
        del ie.text_id
1459
1937
        assert getattr(ie, 'revision', None) is not None
1471
1949
            if ie._unchanged(previous_ie):
1472
1950
                ie.revision = previous_ie.revision
1473
1951
                return
1474
 
        parent_indexes = map(w.lookup, previous_revisions)
1475
1952
        if ie.has_text():
1476
1953
            text = self.branch.repository.text_store.get(ie.text_id)
1477
1954
            file_lines = text.readlines()
1478
1955
            assert sha_strings(file_lines) == ie.text_sha1
1479
1956
            assert sum(map(len, file_lines)) == ie.text_size
1480
 
            w.add(rev_id, parent_indexes, file_lines, ie.text_sha1)
 
1957
            w.add_lines(rev_id, previous_revisions, file_lines)
1481
1958
            self.text_count += 1
1482
1959
        else:
1483
 
            w.add(rev_id, parent_indexes, [], None)
 
1960
            w.add_lines(rev_id, previous_revisions, [])
1484
1961
        ie.revision = rev_id
1485
1962
 
1486
1963
    def _make_order(self):
1518
1995
        return BzrDir.open(self.bzrdir.root_transport.base)
1519
1996
 
1520
1997
    def _convert_to_prefixed(self):
1521
 
        from bzrlib.store import hash_prefix
 
1998
        from bzrlib.store import TransportStore
1522
1999
        self.bzrdir.transport.delete('branch-format')
1523
2000
        for store_name in ["weaves", "revision-store"]:
1524
 
            self.pb.note("adding prefixes to %s" % store_name) 
 
2001
            self.pb.note("adding prefixes to %s" % store_name)
1525
2002
            store_transport = self.bzrdir.transport.clone(store_name)
1526
 
            for filename in store_transport.list_dir('.'):
 
2003
            store = TransportStore(store_transport, prefixed=True)
 
2004
            for urlfilename in store_transport.list_dir('.'):
 
2005
                filename = urlutils.unescape(urlfilename)
1527
2006
                if (filename.endswith(".weave") or
1528
2007
                    filename.endswith(".gz") or
1529
2008
                    filename.endswith(".sig")):
1530
2009
                    file_id = os.path.splitext(filename)[0]
1531
2010
                else:
1532
2011
                    file_id = filename
1533
 
                prefix_dir = hash_prefix(file_id)
 
2012
                prefix_dir = store.hash_prefix(file_id)
1534
2013
                # FIXME keep track of the dirs made RBC 20060121
1535
2014
                try:
1536
2015
                    store_transport.move(filename, prefix_dir + '/' + filename)
1545
2024
 
1546
2025
    def convert(self, to_convert, pb):
1547
2026
        """See Converter.convert()."""
 
2027
        from bzrlib.repofmt.weaverepo import RepositoryFormat7
 
2028
        from bzrlib.branch import BzrBranchFormat5
1548
2029
        self.bzrdir = to_convert
1549
2030
        self.pb = pb
1550
2031
        self.count = 0
1562
2043
            pass
1563
2044
        # find out whats there
1564
2045
        self.step('Finding branch files')
1565
 
        last_revision = self.bzrdir.open_workingtree().last_revision()
 
2046
        last_revision = self.bzrdir.open_branch().last_revision()
1566
2047
        bzrcontents = self.bzrdir.transport.list_dir('.')
1567
2048
        for name in bzrcontents:
1568
2049
            if name.startswith('basis-inventory.'):
1569
2050
                self.garbage_inventories.append(name)
1570
2051
        # create new directories for repository, working tree and branch
1571
 
        dir_mode = self.bzrdir._control_files._dir_mode
 
2052
        self.dir_mode = self.bzrdir._control_files._dir_mode
1572
2053
        self.file_mode = self.bzrdir._control_files._file_mode
1573
2054
        repository_names = [('inventory.weave', True),
1574
2055
                            ('revision-store', True),
1575
2056
                            ('weaves', True)]
1576
2057
        self.step('Upgrading repository  ')
1577
 
        self.bzrdir.transport.mkdir('repository', mode=dir_mode)
 
2058
        self.bzrdir.transport.mkdir('repository', mode=self.dir_mode)
1578
2059
        self.make_lock('repository')
1579
2060
        # we hard code the formats here because we are converting into
1580
2061
        # the meta format. The meta format upgrader can take this to a 
1581
2062
        # future format within each component.
1582
 
        self.put_format('repository', bzrlib.repository.RepositoryFormat7())
 
2063
        self.put_format('repository', RepositoryFormat7())
1583
2064
        for entry in repository_names:
1584
2065
            self.move_entry('repository', entry)
1585
2066
 
1586
2067
        self.step('Upgrading branch      ')
1587
 
        self.bzrdir.transport.mkdir('branch', mode=dir_mode)
 
2068
        self.bzrdir.transport.mkdir('branch', mode=self.dir_mode)
1588
2069
        self.make_lock('branch')
1589
 
        self.put_format('branch', bzrlib.branch.BzrBranchFormat5())
 
2070
        self.put_format('branch', BzrBranchFormat5())
1590
2071
        branch_files = [('revision-history', True),
1591
2072
                        ('branch-name', True),
1592
2073
                        ('parent', False)]
1593
2074
        for entry in branch_files:
1594
2075
            self.move_entry('branch', entry)
1595
2076
 
1596
 
        self.step('Upgrading working tree')
1597
 
        self.bzrdir.transport.mkdir('checkout', mode=dir_mode)
1598
 
        self.make_lock('checkout')
1599
 
        self.put_format('checkout', bzrlib.workingtree.WorkingTreeFormat3())
1600
 
        self.bzrdir.transport.delete_multi(self.garbage_inventories, self.pb)
1601
2077
        checkout_files = [('pending-merges', True),
1602
2078
                          ('inventory', True),
1603
2079
                          ('stat-cache', False)]
1604
 
        for entry in checkout_files:
1605
 
            self.move_entry('checkout', entry)
1606
 
        if last_revision is not None:
1607
 
            self.bzrdir._control_files.put_utf8('checkout/last-revision',
1608
 
                                                last_revision)
1609
 
        self.bzrdir._control_files.put_utf8('branch-format', BzrDirMetaFormat1().get_format_string())
 
2080
        # If a mandatory checkout file is not present, the branch does not have
 
2081
        # a functional checkout. Do not create a checkout in the converted
 
2082
        # branch.
 
2083
        for name, mandatory in checkout_files:
 
2084
            if mandatory and name not in bzrcontents:
 
2085
                has_checkout = False
 
2086
                break
 
2087
        else:
 
2088
            has_checkout = True
 
2089
        if not has_checkout:
 
2090
            self.pb.note('No working tree.')
 
2091
            # If some checkout files are there, we may as well get rid of them.
 
2092
            for name, mandatory in checkout_files:
 
2093
                if name in bzrcontents:
 
2094
                    self.bzrdir.transport.delete(name)
 
2095
        else:
 
2096
            from bzrlib.workingtree import WorkingTreeFormat3
 
2097
            self.step('Upgrading working tree')
 
2098
            self.bzrdir.transport.mkdir('checkout', mode=self.dir_mode)
 
2099
            self.make_lock('checkout')
 
2100
            self.put_format(
 
2101
                'checkout', WorkingTreeFormat3())
 
2102
            self.bzrdir.transport.delete_multi(
 
2103
                self.garbage_inventories, self.pb)
 
2104
            for entry in checkout_files:
 
2105
                self.move_entry('checkout', entry)
 
2106
            if last_revision is not None:
 
2107
                self.bzrdir._control_files.put_utf8(
 
2108
                    'checkout/last-revision', last_revision)
 
2109
        self.bzrdir._control_files.put_utf8(
 
2110
            'branch-format', BzrDirMetaFormat1().get_format_string())
1610
2111
        return BzrDir.open(self.bzrdir.root_transport.base)
1611
2112
 
1612
2113
    def make_lock(self, name):
1613
2114
        """Make a lock for the new control dir name."""
1614
2115
        self.step('Make %s lock' % name)
1615
 
        self.bzrdir.transport.put('%s/lock' % name, StringIO(), mode=self.file_mode)
 
2116
        ld = lockdir.LockDir(self.bzrdir.transport,
 
2117
                             '%s/lock' % name,
 
2118
                             file_modebits=self.file_mode,
 
2119
                             dir_modebits=self.dir_mode)
 
2120
        ld.create()
1616
2121
 
1617
2122
    def move_entry(self, new_dir, entry):
1618
2123
        """Move then entry name into new_dir."""
1656
2161
                self.pb.note('starting repository conversion')
1657
2162
                converter = CopyConverter(self.target_format.repository_format)
1658
2163
                converter.convert(repo, pb)
 
2164
        try:
 
2165
            branch = self.bzrdir.open_branch()
 
2166
        except errors.NotBranchError:
 
2167
            pass
 
2168
        else:
 
2169
            # TODO: conversions of Branch and Tree should be done by
 
2170
            # InterXFormat lookups
 
2171
            # Avoid circular imports
 
2172
            from bzrlib import branch as _mod_branch
 
2173
            if (branch._format.__class__ is _mod_branch.BzrBranchFormat5 and
 
2174
                self.target_format.get_branch_format().__class__ is
 
2175
                _mod_branch.BzrBranchFormat6):
 
2176
                branch_converter = _mod_branch.Converter5to6()
 
2177
                branch_converter.convert(branch)
 
2178
        try:
 
2179
            tree = self.bzrdir.open_workingtree(recommend_upgrade=False)
 
2180
        except (errors.NoWorkingTree, errors.NotLocalUrl):
 
2181
            pass
 
2182
        else:
 
2183
            # TODO: conversions of Branch and Tree should be done by
 
2184
            # InterXFormat lookups
 
2185
            if (isinstance(tree, workingtree.WorkingTree3) and
 
2186
                not isinstance(tree, workingtree_4.WorkingTree4) and
 
2187
                isinstance(self.target_format.workingtree_format,
 
2188
                    workingtree_4.WorkingTreeFormat4)):
 
2189
                workingtree_4.Converter3to4().convert(tree)
1659
2190
        return to_convert
 
2191
 
 
2192
 
 
2193
# This is not in remote.py because it's small, and needs to be registered.
 
2194
# Putting it in remote.py creates a circular import problem.
 
2195
# we can make it a lazy object if the control formats is turned into something
 
2196
# like a registry.
 
2197
class RemoteBzrDirFormat(BzrDirMetaFormat1):
 
2198
    """Format representing bzrdirs accessed via a smart server"""
 
2199
 
 
2200
    def get_format_description(self):
 
2201
        return 'bzr remote bzrdir'
 
2202
    
 
2203
    @classmethod
 
2204
    def probe_transport(klass, transport):
 
2205
        """Return a RemoteBzrDirFormat object if it looks possible."""
 
2206
        try:
 
2207
            client = transport.get_smart_client()
 
2208
        except (NotImplementedError, AttributeError,
 
2209
                errors.TransportNotPossible):
 
2210
            # no smart server, so not a branch for this format type.
 
2211
            raise errors.NotBranchError(path=transport.base)
 
2212
        else:
 
2213
            # Send a 'hello' request in protocol version one, and decline to
 
2214
            # open it if the server doesn't support our required version (2) so
 
2215
            # that the VFS-based transport will do it.
 
2216
            request = client.get_request()
 
2217
            smart_protocol = protocol.SmartClientRequestProtocolOne(request)
 
2218
            server_version = smart_protocol.query_version()
 
2219
            if server_version != 2:
 
2220
                raise errors.NotBranchError(path=transport.base)
 
2221
            return klass()
 
2222
 
 
2223
    def initialize_on_transport(self, transport):
 
2224
        try:
 
2225
            # hand off the request to the smart server
 
2226
            shared_medium = transport.get_shared_medium()
 
2227
        except errors.NoSmartMedium:
 
2228
            # TODO: lookup the local format from a server hint.
 
2229
            local_dir_format = BzrDirMetaFormat1()
 
2230
            return local_dir_format.initialize_on_transport(transport)
 
2231
        client = _SmartClient(shared_medium)
 
2232
        path = client.remote_path_from_transport(transport)
 
2233
        response = _SmartClient(shared_medium).call('BzrDirFormat.initialize',
 
2234
                                                    path)
 
2235
        assert response[0] in ('ok', ), 'unexpected response code %s' % (response,)
 
2236
        return remote.RemoteBzrDir(transport)
 
2237
 
 
2238
    def _open(self, transport):
 
2239
        return remote.RemoteBzrDir(transport)
 
2240
 
 
2241
    def __eq__(self, other):
 
2242
        if not isinstance(other, RemoteBzrDirFormat):
 
2243
            return False
 
2244
        return self.get_format_description() == other.get_format_description()
 
2245
 
 
2246
 
 
2247
BzrDirFormat.register_control_server_format(RemoteBzrDirFormat)
 
2248
 
 
2249
 
 
2250
class BzrDirFormatInfo(object):
 
2251
 
 
2252
    def __init__(self, native, deprecated, hidden):
 
2253
        self.deprecated = deprecated
 
2254
        self.native = native
 
2255
        self.hidden = hidden
 
2256
 
 
2257
 
 
2258
class BzrDirFormatRegistry(registry.Registry):
 
2259
    """Registry of user-selectable BzrDir subformats.
 
2260
    
 
2261
    Differs from BzrDirFormat._control_formats in that it provides sub-formats,
 
2262
    e.g. BzrDirMeta1 with weave repository.  Also, it's more user-oriented.
 
2263
    """
 
2264
 
 
2265
    def register_metadir(self, key,
 
2266
             repository_format, help, native=True, deprecated=False,
 
2267
             branch_format=None,
 
2268
             tree_format=None,
 
2269
             hidden=False):
 
2270
        """Register a metadir subformat.
 
2271
 
 
2272
        These all use a BzrDirMetaFormat1 bzrdir, but can be parameterized
 
2273
        by the Repository format.
 
2274
 
 
2275
        :param repository_format: The fully-qualified repository format class
 
2276
            name as a string.
 
2277
        :param branch_format: Fully-qualified branch format class name as
 
2278
            a string.
 
2279
        :param tree_format: Fully-qualified tree format class name as
 
2280
            a string.
 
2281
        """
 
2282
        # This should be expanded to support setting WorkingTree and Branch
 
2283
        # formats, once BzrDirMetaFormat1 supports that.
 
2284
        def _load(full_name):
 
2285
            mod_name, factory_name = full_name.rsplit('.', 1)
 
2286
            try:
 
2287
                mod = __import__(mod_name, globals(), locals(),
 
2288
                        [factory_name])
 
2289
            except ImportError, e:
 
2290
                raise ImportError('failed to load %s: %s' % (full_name, e))
 
2291
            try:
 
2292
                factory = getattr(mod, factory_name)
 
2293
            except AttributeError:
 
2294
                raise AttributeError('no factory %s in module %r'
 
2295
                    % (full_name, mod))
 
2296
            return factory()
 
2297
 
 
2298
        def helper():
 
2299
            bd = BzrDirMetaFormat1()
 
2300
            if branch_format is not None:
 
2301
                bd.set_branch_format(_load(branch_format))
 
2302
            if tree_format is not None:
 
2303
                bd.workingtree_format = _load(tree_format)
 
2304
            if repository_format is not None:
 
2305
                bd.repository_format = _load(repository_format)
 
2306
            return bd
 
2307
        self.register(key, helper, help, native, deprecated, hidden)
 
2308
 
 
2309
    def register(self, key, factory, help, native=True, deprecated=False,
 
2310
                 hidden=False):
 
2311
        """Register a BzrDirFormat factory.
 
2312
        
 
2313
        The factory must be a callable that takes one parameter: the key.
 
2314
        It must produce an instance of the BzrDirFormat when called.
 
2315
 
 
2316
        This function mainly exists to prevent the info object from being
 
2317
        supplied directly.
 
2318
        """
 
2319
        registry.Registry.register(self, key, factory, help, 
 
2320
            BzrDirFormatInfo(native, deprecated, hidden))
 
2321
 
 
2322
    def register_lazy(self, key, module_name, member_name, help, native=True,
 
2323
                      deprecated=False, hidden=False):
 
2324
        registry.Registry.register_lazy(self, key, module_name, member_name, 
 
2325
            help, BzrDirFormatInfo(native, deprecated, hidden))
 
2326
 
 
2327
    def set_default(self, key):
 
2328
        """Set the 'default' key to be a clone of the supplied key.
 
2329
        
 
2330
        This method must be called once and only once.
 
2331
        """
 
2332
        registry.Registry.register(self, 'default', self.get(key), 
 
2333
            self.get_help(key), info=self.get_info(key))
 
2334
 
 
2335
    def set_default_repository(self, key):
 
2336
        """Set the FormatRegistry default and Repository default.
 
2337
        
 
2338
        This is a transitional method while Repository.set_default_format
 
2339
        is deprecated.
 
2340
        """
 
2341
        if 'default' in self:
 
2342
            self.remove('default')
 
2343
        self.set_default(key)
 
2344
        format = self.get('default')()
 
2345
        assert isinstance(format, BzrDirMetaFormat1)
 
2346
 
 
2347
    def make_bzrdir(self, key):
 
2348
        return self.get(key)()
 
2349
 
 
2350
    def help_topic(self, topic):
 
2351
        output = textwrap.dedent("""\
 
2352
            Bazaar directory formats
 
2353
            ------------------------
 
2354
 
 
2355
            These formats can be used for creating branches, working trees, and
 
2356
            repositories.
 
2357
 
 
2358
            """)
 
2359
        default_help = self.get_help('default')
 
2360
        help_pairs = []
 
2361
        for key in self.keys():
 
2362
            if key == 'default':
 
2363
                continue
 
2364
            help = self.get_help(key)
 
2365
            if help == default_help:
 
2366
                default_realkey = key
 
2367
            else:
 
2368
                help_pairs.append((key, help))
 
2369
 
 
2370
        def wrapped(key, help, info):
 
2371
            if info.native:
 
2372
                help = '(native) ' + help
 
2373
            return '  %s:\n%s\n\n' % (key, 
 
2374
                    textwrap.fill(help, initial_indent='    ', 
 
2375
                    subsequent_indent='    '))
 
2376
        output += wrapped('%s/default' % default_realkey, default_help,
 
2377
                          self.get_info('default'))
 
2378
        deprecated_pairs = []
 
2379
        for key, help in help_pairs:
 
2380
            info = self.get_info(key)
 
2381
            if info.hidden:
 
2382
                continue
 
2383
            elif info.deprecated:
 
2384
                deprecated_pairs.append((key, help))
 
2385
            else:
 
2386
                output += wrapped(key, help, info)
 
2387
        if len(deprecated_pairs) > 0:
 
2388
            output += "Deprecated formats\n------------------\n\n"
 
2389
            for key, help in deprecated_pairs:
 
2390
                info = self.get_info(key)
 
2391
                output += wrapped(key, help, info)
 
2392
 
 
2393
        return output
 
2394
 
 
2395
 
 
2396
format_registry = BzrDirFormatRegistry()
 
2397
format_registry.register('weave', BzrDirFormat6,
 
2398
    'Pre-0.8 format.  Slower than knit and does not'
 
2399
    ' support checkouts or shared repositories.',
 
2400
    deprecated=True)
 
2401
format_registry.register_metadir('knit',
 
2402
    'bzrlib.repofmt.knitrepo.RepositoryFormatKnit1',
 
2403
    'Format using knits.  Recommended for interoperation with bzr <= 0.14.',
 
2404
    branch_format='bzrlib.branch.BzrBranchFormat5',
 
2405
    tree_format='bzrlib.workingtree.WorkingTreeFormat3')
 
2406
format_registry.register_metadir('metaweave',
 
2407
    'bzrlib.repofmt.weaverepo.RepositoryFormat7',
 
2408
    'Transitional format in 0.8.  Slower than knit.',
 
2409
    branch_format='bzrlib.branch.BzrBranchFormat5',
 
2410
    tree_format='bzrlib.workingtree.WorkingTreeFormat3',
 
2411
    deprecated=True)
 
2412
format_registry.register_metadir('dirstate',
 
2413
    'bzrlib.repofmt.knitrepo.RepositoryFormatKnit1',
 
2414
    help='New in 0.15: Fast local operations. Compatible with bzr 0.8 and '
 
2415
        'above when accessed over the network.',
 
2416
    branch_format='bzrlib.branch.BzrBranchFormat5',
 
2417
    # this uses bzrlib.workingtree.WorkingTreeFormat4 because importing
 
2418
    # directly from workingtree_4 triggers a circular import.
 
2419
    tree_format='bzrlib.workingtree.WorkingTreeFormat4',
 
2420
    )
 
2421
format_registry.register_metadir('dirstate-tags',
 
2422
    'bzrlib.repofmt.knitrepo.RepositoryFormatKnit1',
 
2423
    help='New in 0.15: Fast local operations and improved scaling for '
 
2424
        'network operations. Additionally adds support for tags.'
 
2425
        ' Incompatible with bzr < 0.15.',
 
2426
    branch_format='bzrlib.branch.BzrBranchFormat6',
 
2427
    tree_format='bzrlib.workingtree.WorkingTreeFormat4',
 
2428
    )
 
2429
format_registry.register_metadir('dirstate-with-subtree',
 
2430
    'bzrlib.repofmt.knitrepo.RepositoryFormatKnit3',
 
2431
    help='New in 0.15: Fast local operations and improved scaling for '
 
2432
        'network operations. Additionally adds support for versioning nested '
 
2433
        'bzr branches. Incompatible with bzr < 0.15.',
 
2434
    branch_format='bzrlib.branch.BzrBranchFormat6',
 
2435
    tree_format='bzrlib.workingtree.WorkingTreeFormat4',
 
2436
    hidden=True,
 
2437
    )
 
2438
format_registry.set_default('dirstate')