~bzr-pqm/bzr/bzr.dev

« back to all changes in this revision

Viewing changes to bzrlib/bzrdir.py

  • Committer: Canonical.com Patch Queue Manager
  • Date: 2006-08-17 07:52:09 UTC
  • mfrom: (1910.3.4 trivial)
  • Revision ID: pqm@pqm.ubuntu.com-20060817075209-e85a1f9e05ff8b87
(andrew) Trivial fixes to NotImplemented errors.

Show diffs side-by-side

added added

removed removed

Lines of Context:
1
 
# Copyright (C) 2005, 2006, 2007 Canonical Ltd
 
1
# Copyright (C) 2005, 2006 Canonical Ltd
2
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
18
18
 
19
19
At format 7 this was split out into Branch, Repository and Checkout control
20
20
directories.
21
 
 
22
 
Note: This module has a lot of ``open`` functions/methods that return
23
 
references to in-memory objects. As a rule, there are no matching ``close``
24
 
methods. To free any associated resources, simply stop referencing the
25
 
objects returned.
26
21
"""
27
22
 
28
 
# TODO: Move old formats into a plugin to make this file smaller.
 
23
# TODO: remove unittest dependency; put that stuff inside the test suite
29
24
 
 
25
from copy import deepcopy
30
26
from cStringIO import StringIO
31
27
import os
32
 
 
33
 
from bzrlib.lazy_import import lazy_import
34
 
lazy_import(globals(), """
35
28
from stat import S_ISDIR
36
 
import textwrap
37
 
from warnings import warn
 
29
from unittest import TestSuite
38
30
 
39
31
import bzrlib
40
 
from bzrlib import (
41
 
    errors,
42
 
    graph,
43
 
    lockable_files,
44
 
    lockdir,
45
 
    registry,
46
 
    remote,
47
 
    revision as _mod_revision,
48
 
    symbol_versioning,
49
 
    ui,
50
 
    urlutils,
51
 
    xml4,
52
 
    xml5,
53
 
    workingtree,
54
 
    workingtree_4,
55
 
    )
 
32
import bzrlib.errors as errors
 
33
from bzrlib.lockable_files import LockableFiles, TransportLock
 
34
from bzrlib.lockdir import LockDir
56
35
from bzrlib.osutils import (
57
 
    sha_strings,
58
 
    sha_string,
59
 
    )
60
 
from bzrlib.smart.client import _SmartClient
61
 
from bzrlib.smart import protocol
 
36
                            abspath,
 
37
                            pathjoin,
 
38
                            safe_unicode,
 
39
                            sha_strings,
 
40
                            sha_string,
 
41
                            )
62
42
from bzrlib.store.revision.text import TextRevisionStore
63
43
from bzrlib.store.text import TextStore
64
44
from bzrlib.store.versioned import WeaveStore
 
45
from bzrlib.trace import mutter
65
46
from bzrlib.transactions import WriteTransaction
66
 
from bzrlib.transport import (
67
 
    do_catching_redirections,
68
 
    get_transport,
69
 
    )
 
47
from bzrlib.transport import get_transport
 
48
from bzrlib.transport.local import LocalTransport
 
49
import bzrlib.urlutils as urlutils
70
50
from bzrlib.weave import Weave
71
 
""")
72
 
 
73
 
from bzrlib.trace import (
74
 
    mutter,
75
 
    note,
76
 
    )
77
 
from bzrlib.transport.local import LocalTransport
78
 
from bzrlib.symbol_versioning import (
79
 
    deprecated_function,
80
 
    deprecated_method,
81
 
    zero_ninetyone,
82
 
    )
 
51
from bzrlib.xml4 import serializer_v4
 
52
import bzrlib.xml5
83
53
 
84
54
 
85
55
class BzrDir(object):
91
61
    transport
92
62
        the transport which this bzr dir is rooted at (i.e. file:///.../.bzr/)
93
63
    root_transport
94
 
        a transport connected to the directory this bzr was opened from
95
 
        (i.e. the parent directory holding the .bzr directory).
 
64
        a transport connected to the directory this bzr was opened from.
96
65
    """
97
66
 
98
67
    def break_lock(self):
101
70
        If there is a tree, the tree is opened and break_lock() called.
102
71
        Otherwise, branch is tried, and finally repository.
103
72
        """
104
 
        # XXX: This seems more like a UI function than something that really
105
 
        # belongs in this class.
106
73
        try:
107
74
            thing_to_unlock = self.open_workingtree()
108
75
        except (errors.NotLocalUrl, errors.NoWorkingTree):
119
86
        """Return true if this bzrdir is one whose format we can convert from."""
120
87
        return True
121
88
 
122
 
    def check_conversion_target(self, target_format):
123
 
        target_repo_format = target_format.repository_format
124
 
        source_repo_format = self._format.repository_format
125
 
        source_repo_format.check_conversion_target(target_repo_format)
126
 
 
127
89
    @staticmethod
128
 
    def _check_supported(format, allow_unsupported,
129
 
        recommend_upgrade=True,
130
 
        basedir=None):
131
 
        """Give an error or warning on old formats.
132
 
 
133
 
        :param format: may be any kind of format - workingtree, branch, 
134
 
        or repository.
135
 
 
136
 
        :param allow_unsupported: If true, allow opening 
137
 
        formats that are strongly deprecated, and which may 
138
 
        have limited functionality.
139
 
 
140
 
        :param recommend_upgrade: If true (default), warn
141
 
        the user through the ui object that they may wish
142
 
        to upgrade the object.
 
90
    def _check_supported(format, allow_unsupported):
 
91
        """Check whether format is a supported format.
 
92
 
 
93
        If allow_unsupported is True, this is a no-op.
143
94
        """
144
 
        # TODO: perhaps move this into a base Format class; it's not BzrDir
145
 
        # specific. mbp 20070323
146
95
        if not allow_unsupported and not format.is_supported():
147
96
            # see open_downlevel to open legacy branches.
148
97
            raise errors.UnsupportedFormatError(format=format)
149
 
        if recommend_upgrade \
150
 
            and getattr(format, 'upgrade_recommended', False):
151
 
            ui.ui_factory.recommend_upgrade(
152
 
                format.get_format_description(),
153
 
                basedir)
154
98
 
155
 
    def clone(self, url, revision_id=None, force_new_repo=False):
 
99
    def clone(self, url, revision_id=None, basis=None, force_new_repo=False):
156
100
        """Clone this bzrdir and its contents to url verbatim.
157
101
 
158
 
        If url's last component does not exist, it will be created.
159
 
 
160
 
        if revision_id is not None, then the clone operation may tune
161
 
            itself to download less data.
162
 
        :param force_new_repo: Do not use a shared repository for the target 
163
 
                               even if one is available.
164
 
        """
165
 
        return self.clone_on_transport(get_transport(url),
166
 
                                       revision_id=revision_id,
167
 
                                       force_new_repo=force_new_repo)
168
 
 
169
 
    def clone_on_transport(self, transport, revision_id=None,
170
 
                           force_new_repo=False):
171
 
        """Clone this bzrdir and its contents to transport verbatim.
172
 
 
173
 
        If the target directory does not exist, it will be created.
174
 
 
175
 
        if revision_id is not None, then the clone operation may tune
176
 
            itself to download less data.
177
 
        :param force_new_repo: Do not use a shared repository for the target 
178
 
                               even if one is available.
179
 
        """
180
 
        transport.ensure_base()
181
 
        result = self._format.initialize_on_transport(transport)
 
102
        If urls last component does not exist, it will be created.
 
103
 
 
104
        if revision_id is not None, then the clone operation may tune
 
105
            itself to download less data.
 
106
        :param force_new_repo: Do not use a shared repository for the target 
 
107
                               even if one is available.
 
108
        """
 
109
        self._make_tail(url)
 
110
        basis_repo, basis_branch, basis_tree = self._get_basis_components(basis)
 
111
        result = self._format.initialize(url)
182
112
        try:
183
113
            local_repo = self.find_repository()
184
114
        except errors.NoRepositoryPresent:
188
118
            if force_new_repo:
189
119
                result_repo = local_repo.clone(
190
120
                    result,
191
 
                    revision_id=revision_id)
 
121
                    revision_id=revision_id,
 
122
                    basis=basis_repo)
192
123
                result_repo.set_make_working_trees(local_repo.make_working_trees())
193
124
            else:
194
125
                try:
195
126
                    result_repo = result.find_repository()
196
127
                    # fetch content this dir needs.
 
128
                    if basis_repo:
 
129
                        # XXX FIXME RBC 20060214 need tests for this when the basis
 
130
                        # is incomplete
 
131
                        result_repo.fetch(basis_repo, revision_id=revision_id)
197
132
                    result_repo.fetch(local_repo, revision_id=revision_id)
198
133
                except errors.NoRepositoryPresent:
199
134
                    # needed to make one anyway.
200
135
                    result_repo = local_repo.clone(
201
136
                        result,
202
 
                        revision_id=revision_id)
 
137
                        revision_id=revision_id,
 
138
                        basis=basis_repo)
203
139
                    result_repo.set_make_working_trees(local_repo.make_working_trees())
204
140
        # 1 if there is a branch present
205
141
        #   make sure its content is available in the target repository
209
145
        except errors.NotBranchError:
210
146
            pass
211
147
        try:
212
 
            self.open_workingtree().clone(result)
 
148
            self.open_workingtree().clone(result, basis=basis_tree)
213
149
        except (errors.NoWorkingTree, errors.NotLocalUrl):
214
150
            pass
215
151
        return result
216
152
 
 
153
    def _get_basis_components(self, basis):
 
154
        """Retrieve the basis components that are available at basis."""
 
155
        if basis is None:
 
156
            return None, None, None
 
157
        try:
 
158
            basis_tree = basis.open_workingtree()
 
159
            basis_branch = basis_tree.branch
 
160
            basis_repo = basis_branch.repository
 
161
        except (errors.NoWorkingTree, errors.NotLocalUrl):
 
162
            basis_tree = None
 
163
            try:
 
164
                basis_branch = basis.open_branch()
 
165
                basis_repo = basis_branch.repository
 
166
            except errors.NotBranchError:
 
167
                basis_branch = None
 
168
                try:
 
169
                    basis_repo = basis.open_repository()
 
170
                except errors.NoRepositoryPresent:
 
171
                    basis_repo = None
 
172
        return basis_repo, basis_branch, basis_tree
 
173
 
217
174
    # TODO: This should be given a Transport, and should chdir up; otherwise
218
175
    # this will open a new connection.
219
176
    def _make_tail(self, url):
220
 
        t = get_transport(url)
221
 
        t.ensure_base()
 
177
        head, tail = urlutils.split(url)
 
178
        if tail and tail != '.':
 
179
            t = bzrlib.transport.get_transport(head)
 
180
            try:
 
181
                t.mkdir(tail)
 
182
            except errors.FileExists:
 
183
                pass
222
184
 
 
185
    # TODO: Should take a Transport
223
186
    @classmethod
224
 
    def create(cls, base, format=None, possible_transports=None):
 
187
    def create(cls, base):
225
188
        """Create a new BzrDir at the url 'base'.
226
189
        
227
 
        :param format: If supplied, the format of branch to create.  If not
228
 
            supplied, the default is used.
229
 
        :param possible_transports: If supplied, a list of transports that 
230
 
            can be reused to share a remote connection.
 
190
        This will call the current default formats initialize with base
 
191
        as the only parameter.
 
192
 
 
193
        If you need a specific format, consider creating an instance
 
194
        of that and calling initialize().
231
195
        """
232
196
        if cls is not BzrDir:
233
 
            raise AssertionError("BzrDir.create always creates the default"
234
 
                " format, not one of %r" % cls)
235
 
        t = get_transport(base, possible_transports)
236
 
        t.ensure_base()
237
 
        if format is None:
238
 
            format = BzrDirFormat.get_default_format()
239
 
        return format.initialize_on_transport(t)
 
197
            raise AssertionError("BzrDir.create always creates the default format, "
 
198
                    "not one of %r" % cls)
 
199
        head, tail = urlutils.split(base)
 
200
        if tail and tail != '.':
 
201
            t = bzrlib.transport.get_transport(head)
 
202
            try:
 
203
                t.mkdir(tail)
 
204
            except errors.FileExists:
 
205
                pass
 
206
        return BzrDirFormat.get_default_format().initialize(safe_unicode(base))
240
207
 
241
208
    def create_branch(self):
242
209
        """Create a branch in this BzrDir.
243
210
 
244
 
        The bzrdir's format will control what branch format is created.
 
211
        The bzrdirs format will control what branch format is created.
245
212
        For more control see BranchFormatXX.create(a_bzrdir).
246
213
        """
247
214
        raise NotImplementedError(self.create_branch)
248
215
 
249
 
    def destroy_branch(self):
250
 
        """Destroy the branch in this BzrDir"""
251
 
        raise NotImplementedError(self.destroy_branch)
252
 
 
253
216
    @staticmethod
254
 
    def create_branch_and_repo(base, force_new_repo=False, format=None):
 
217
    def create_branch_and_repo(base, force_new_repo=False):
255
218
        """Create a new BzrDir, Branch and Repository at the url 'base'.
256
219
 
257
 
        This will use the current default BzrDirFormat unless one is
258
 
        specified, and use whatever 
 
220
        This will use the current default BzrDirFormat, and use whatever 
259
221
        repository format that that uses via bzrdir.create_branch and
260
222
        create_repository. If a shared repository is available that is used
261
223
        preferentially.
264
226
 
265
227
        :param base: The URL to create the branch at.
266
228
        :param force_new_repo: If True a new repository is always created.
267
 
        :param format: If supplied, the format of branch to create.  If not
268
 
            supplied, the default is used.
269
229
        """
270
 
        bzrdir = BzrDir.create(base, format)
 
230
        bzrdir = BzrDir.create(base)
271
231
        bzrdir._find_or_create_repository(force_new_repo)
272
232
        return bzrdir.create_branch()
273
233
 
282
242
        
283
243
    @staticmethod
284
244
    def create_branch_convenience(base, force_new_repo=False,
285
 
                                  force_new_tree=None, format=None,
286
 
                                  possible_transports=None):
 
245
                                  force_new_tree=None, format=None):
287
246
        """Create a new BzrDir, Branch and Repository at the url 'base'.
288
247
 
289
248
        This is a convenience function - it will use an existing repository
290
249
        if possible, can be told explicitly whether to create a working tree or
291
250
        not.
292
251
 
293
 
        This will use the current default BzrDirFormat unless one is
294
 
        specified, and use whatever 
 
252
        This will use the current default BzrDirFormat, and use whatever 
295
253
        repository format that that uses via bzrdir.create_branch and
296
254
        create_repository. If a shared repository is available that is used
297
255
        preferentially. Whatever repository is used, its tree creation policy
306
264
        :param force_new_repo: If True a new repository is always created.
307
265
        :param force_new_tree: If True or False force creation of a tree or 
308
266
                               prevent such creation respectively.
309
 
        :param format: Override for the bzrdir format to create.
310
 
        :param possible_transports: An optional reusable transports list.
 
267
        :param format: Override for the for the bzrdir format to create
311
268
        """
312
269
        if force_new_tree:
313
270
            # check for non local urls
314
 
            t = get_transport(base, possible_transports)
 
271
            t = get_transport(safe_unicode(base))
315
272
            if not isinstance(t, LocalTransport):
316
273
                raise errors.NotLocalUrl(base)
317
 
        bzrdir = BzrDir.create(base, format, possible_transports)
 
274
        if format is None:
 
275
            bzrdir = BzrDir.create(base)
 
276
        else:
 
277
            bzrdir = format.initialize(base)
318
278
        repo = bzrdir._find_or_create_repository(force_new_repo)
319
279
        result = bzrdir.create_branch()
320
 
        if force_new_tree or (repo.make_working_trees() and
 
280
        if force_new_tree or (repo.make_working_trees() and 
321
281
                              force_new_tree is None):
322
282
            try:
323
283
                bzrdir.create_workingtree()
324
284
            except errors.NotLocalUrl:
325
285
                pass
326
286
        return result
327
 
 
 
287
        
328
288
    @staticmethod
329
 
    @deprecated_function(zero_ninetyone)
330
 
    def create_repository(base, shared=False, format=None):
 
289
    def create_repository(base, shared=False):
331
290
        """Create a new BzrDir and Repository at the url 'base'.
332
291
 
333
 
        If no format is supplied, this will default to the current default
334
 
        BzrDirFormat by default, and use whatever repository format that that
335
 
        uses for bzrdirformat.create_repository.
 
292
        This will use the current default BzrDirFormat, and use whatever 
 
293
        repository format that that uses for bzrdirformat.create_repository.
336
294
 
337
 
        :param shared: Create a shared repository rather than a standalone
 
295
        ;param shared: Create a shared repository rather than a standalone
338
296
                       repository.
339
297
        The Repository object is returned.
340
298
 
341
299
        This must be overridden as an instance method in child classes, where
342
300
        it should take no parameters and construct whatever repository format
343
301
        that child class desires.
344
 
 
345
 
        This method is deprecated, please call create_repository on a bzrdir
346
 
        instance instead.
347
302
        """
348
 
        bzrdir = BzrDir.create(base, format)
 
303
        bzrdir = BzrDir.create(base)
349
304
        return bzrdir.create_repository(shared)
350
305
 
351
306
    @staticmethod
352
 
    def create_standalone_workingtree(base, format=None):
 
307
    def create_standalone_workingtree(base):
353
308
        """Create a new BzrDir, WorkingTree, Branch and Repository at 'base'.
354
309
 
355
310
        'base' must be a local path or a file:// url.
356
311
 
357
 
        This will use the current default BzrDirFormat unless one is
358
 
        specified, and use whatever 
 
312
        This will use the current default BzrDirFormat, and use whatever 
359
313
        repository format that that uses for bzrdirformat.create_workingtree,
360
314
        create_branch and create_repository.
361
315
 
362
 
        :param format: Override for the bzrdir format to create.
363
 
        :return: The WorkingTree object.
 
316
        The WorkingTree object is returned.
364
317
        """
365
 
        t = get_transport(base)
 
318
        t = get_transport(safe_unicode(base))
366
319
        if not isinstance(t, LocalTransport):
367
320
            raise errors.NotLocalUrl(base)
368
 
        bzrdir = BzrDir.create_branch_and_repo(base,
369
 
                                               force_new_repo=True,
370
 
                                               format=format).bzrdir
 
321
        bzrdir = BzrDir.create_branch_and_repo(safe_unicode(base),
 
322
                                               force_new_repo=True).bzrdir
371
323
        return bzrdir.create_workingtree()
372
324
 
373
325
    def create_workingtree(self, revision_id=None):
377
329
        """
378
330
        raise NotImplementedError(self.create_workingtree)
379
331
 
380
 
    def retire_bzrdir(self, limit=10000):
381
 
        """Permanently disable the bzrdir.
382
 
 
383
 
        This is done by renaming it to give the user some ability to recover
384
 
        if there was a problem.
385
 
 
386
 
        This will have horrible consequences if anyone has anything locked or
387
 
        in use.
388
 
        :param limit: number of times to retry
389
 
        """
390
 
        i  = 0
391
 
        while True:
392
 
            try:
393
 
                to_path = '.bzr.retired.%d' % i
394
 
                self.root_transport.rename('.bzr', to_path)
395
 
                note("renamed %s to %s"
396
 
                    % (self.root_transport.abspath('.bzr'), to_path))
397
 
                return
398
 
            except (errors.TransportError, IOError, errors.PathError):
399
 
                i += 1
400
 
                if i > limit:
401
 
                    raise
402
 
                else:
403
 
                    pass
404
 
 
405
 
    def destroy_workingtree(self):
406
 
        """Destroy the working tree at this BzrDir.
407
 
 
408
 
        Formats that do not support this may raise UnsupportedOperation.
409
 
        """
410
 
        raise NotImplementedError(self.destroy_workingtree)
411
 
 
412
 
    def destroy_workingtree_metadata(self):
413
 
        """Destroy the control files for the working tree at this BzrDir.
414
 
 
415
 
        The contents of working tree files are not affected.
416
 
        Formats that do not support this may raise UnsupportedOperation.
417
 
        """
418
 
        raise NotImplementedError(self.destroy_workingtree_metadata)
419
 
 
420
332
    def find_repository(self):
421
 
        """Find the repository that should be used.
 
333
        """Find the repository that should be used for a_bzrdir.
422
334
 
423
335
        This does not require a branch as we use it to find the repo for
424
336
        new branches as well as to hook existing branches up to their
447
359
                    break
448
360
                else:
449
361
                    continue
450
 
            if ((found_bzrdir.root_transport.base ==
 
362
            if ((found_bzrdir.root_transport.base == 
451
363
                 self.root_transport.base) or repository.is_shared()):
452
364
                return repository
453
365
            else:
454
366
                raise errors.NoRepositoryPresent(self)
455
367
        raise errors.NoRepositoryPresent(self)
456
368
 
457
 
    def get_branch_reference(self):
458
 
        """Return the referenced URL for the branch in this bzrdir.
459
 
 
460
 
        :raises NotBranchError: If there is no Branch.
461
 
        :return: The URL the branch in this bzrdir references if it is a
462
 
            reference branch, or None for regular branches.
463
 
        """
464
 
        return None
465
 
 
466
369
    def get_branch_transport(self, branch_format):
467
370
        """Get the transport for use by branch format in this BzrDir.
468
371
 
471
374
        a format string, and vice versa.
472
375
 
473
376
        If branch_format is None, the transport is returned with no 
474
 
        checking. If it is not None, then the returned transport is
 
377
        checking. if it is not None, then the returned transport is
475
378
        guaranteed to point to an existing directory ready for use.
476
379
        """
477
380
        raise NotImplementedError(self.get_branch_transport)
484
387
        a format string, and vice versa.
485
388
 
486
389
        If repository_format is None, the transport is returned with no 
487
 
        checking. If it is not None, then the returned transport is
 
390
        checking. if it is not None, then the returned transport is
488
391
        guaranteed to point to an existing directory ready for use.
489
392
        """
490
393
        raise NotImplementedError(self.get_repository_transport)
493
396
        """Get the transport for use by workingtree format in this BzrDir.
494
397
 
495
398
        Note that bzr dirs that do not support format strings will raise
496
 
        IncompatibleFormat if the workingtree format they are given has a
497
 
        format string, and vice versa.
 
399
        IncompatibleFormat if the workingtree format they are given has
 
400
        a format string, and vice versa.
498
401
 
499
402
        If workingtree_format is None, the transport is returned with no 
500
 
        checking. If it is not None, then the returned transport is
 
403
        checking. if it is not None, then the returned transport is
501
404
        guaranteed to point to an existing directory ready for use.
502
405
        """
503
406
        raise NotImplementedError(self.get_workingtree_transport)
529
432
        # this might be better on the BzrDirFormat class because it refers to 
530
433
        # all the possible bzrdir disk formats. 
531
434
        # This method is tested via the workingtree is_control_filename tests- 
532
 
        # it was extracted from WorkingTree.is_control_filename. If the method's
533
 
        # contract is extended beyond the current trivial implementation, please
 
435
        # it was extracted from WorkingTree.is_control_filename. If the methods
 
436
        # contract is extended beyond the current trivial  implementation please
534
437
        # add new tests for it to the appropriate place.
535
438
        return filename == '.bzr' or filename.startswith('.bzr/')
536
439
 
551
454
        return BzrDir.open(base, _unsupported=True)
552
455
        
553
456
    @staticmethod
554
 
    def open(base, _unsupported=False, possible_transports=None):
555
 
        """Open an existing bzrdir, rooted at 'base' (url).
 
457
    def open(base, _unsupported=False):
 
458
        """Open an existing bzrdir, rooted at 'base' (url)
556
459
        
557
 
        :param _unsupported: a private parameter to the BzrDir class.
558
 
        """
559
 
        t = get_transport(base, possible_transports=possible_transports)
560
 
        return BzrDir.open_from_transport(t, _unsupported=_unsupported)
561
 
 
562
 
    @staticmethod
563
 
    def open_from_transport(transport, _unsupported=False,
564
 
                            _server_formats=True):
565
 
        """Open a bzrdir within a particular directory.
566
 
 
567
 
        :param transport: Transport containing the bzrdir.
568
 
        :param _unsupported: private.
569
 
        """
570
 
        base = transport.base
571
 
 
572
 
        def find_format(transport):
573
 
            return transport, BzrDirFormat.find_format(
574
 
                transport, _server_formats=_server_formats)
575
 
 
576
 
        def redirected(transport, e, redirection_notice):
577
 
            qualified_source = e.get_source_url()
578
 
            relpath = transport.relpath(qualified_source)
579
 
            if not e.target.endswith(relpath):
580
 
                # Not redirected to a branch-format, not a branch
581
 
                raise errors.NotBranchError(path=e.target)
582
 
            target = e.target[:-len(relpath)]
583
 
            note('%s is%s redirected to %s',
584
 
                 transport.base, e.permanently, target)
585
 
            # Let's try with a new transport
586
 
            # FIXME: If 'transport' has a qualifier, this should
587
 
            # be applied again to the new transport *iff* the
588
 
            # schemes used are the same. Uncomment this code
589
 
            # once the function (and tests) exist.
590
 
            # -- vila20070212
591
 
            #target = urlutils.copy_url_qualifiers(original, target)
592
 
            return get_transport(target)
593
 
 
594
 
        try:
595
 
            transport, format = do_catching_redirections(find_format,
596
 
                                                         transport,
597
 
                                                         redirected)
598
 
        except errors.TooManyRedirections:
599
 
            raise errors.NotBranchError(base)
600
 
 
 
460
        _unsupported is a private parameter to the BzrDir class.
 
461
        """
 
462
        t = get_transport(base)
 
463
        # mutter("trying to open %r with transport %r", base, t)
 
464
        format = BzrDirFormat.find_format(t)
601
465
        BzrDir._check_supported(format, _unsupported)
602
 
        return format.open(transport, _found=True)
 
466
        return format.open(t, _found=True)
603
467
 
604
468
    def open_branch(self, unsupported=False):
605
469
        """Open the branch object at this BzrDir if one is present.
612
476
        raise NotImplementedError(self.open_branch)
613
477
 
614
478
    @staticmethod
615
 
    def open_containing(url, possible_transports=None):
 
479
    def open_containing(url):
616
480
        """Open an existing branch which contains url.
617
481
        
618
482
        :param url: url to search from.
619
483
        See open_containing_from_transport for more detail.
620
484
        """
621
 
        transport = get_transport(url, possible_transports)
622
 
        return BzrDir.open_containing_from_transport(transport)
 
485
        return BzrDir.open_containing_from_transport(get_transport(url))
623
486
    
624
487
    @staticmethod
625
488
    def open_containing_from_transport(a_transport):
626
 
        """Open an existing branch which contains a_transport.base.
 
489
        """Open an existing branch which contains a_transport.base
627
490
 
628
491
        This probes for a branch at a_transport, and searches upwards from there.
629
492
 
640
503
        url = a_transport.base
641
504
        while True:
642
505
            try:
643
 
                result = BzrDir.open_from_transport(a_transport)
644
 
                return result, urlutils.unescape(a_transport.relpath(url))
 
506
                format = BzrDirFormat.find_format(a_transport)
 
507
                BzrDir._check_supported(format, False)
 
508
                return format.open(a_transport), urlutils.unescape(a_transport.relpath(url))
645
509
            except errors.NotBranchError, e:
 
510
                ## mutter('not a branch in: %r %s', a_transport.base, e)
646
511
                pass
647
 
            try:
648
 
                new_t = a_transport.clone('..')
649
 
            except errors.InvalidURLJoin:
650
 
                # reached the root, whatever that may be
651
 
                raise errors.NotBranchError(path=url)
 
512
            new_t = a_transport.clone('..')
652
513
            if new_t.base == a_transport.base:
653
514
                # reached the root, whatever that may be
654
515
                raise errors.NotBranchError(path=url)
655
516
            a_transport = new_t
656
517
 
657
 
    @classmethod
658
 
    def open_containing_tree_or_branch(klass, location):
659
 
        """Return the branch and working tree contained by a location.
660
 
 
661
 
        Returns (tree, branch, relpath).
662
 
        If there is no tree at containing the location, tree will be None.
663
 
        If there is no branch containing the location, an exception will be
664
 
        raised
665
 
        relpath is the portion of the path that is contained by the branch.
666
 
        """
667
 
        bzrdir, relpath = klass.open_containing(location)
668
 
        try:
669
 
            tree = bzrdir.open_workingtree()
670
 
        except (errors.NoWorkingTree, errors.NotLocalUrl):
671
 
            tree = None
672
 
            branch = bzrdir.open_branch()
673
 
        else:
674
 
            branch = tree.branch
675
 
        return tree, branch, relpath
676
 
 
677
518
    def open_repository(self, _unsupported=False):
678
519
        """Open the repository object at this BzrDir if one is present.
679
520
 
680
 
        This will not follow the Branch object pointer - it's strictly a direct
 
521
        This will not follow the Branch object pointer - its strictly a direct
681
522
        open facility. Most client code should use open_branch().repository to
682
523
        get at a repository.
683
524
 
684
 
        :param _unsupported: a private parameter, not part of the api.
 
525
        _unsupported is a private parameter, not part of the api.
685
526
        TODO: static convenience version of this?
686
527
        """
687
528
        raise NotImplementedError(self.open_repository)
688
529
 
689
 
    def open_workingtree(self, _unsupported=False,
690
 
            recommend_upgrade=True):
 
530
    def open_workingtree(self, _unsupported=False):
691
531
        """Open the workingtree object at this BzrDir if one is present.
692
 
 
693
 
        :param recommend_upgrade: Optional keyword parameter, when True (the
694
 
            default), emit through the ui module a recommendation that the user
695
 
            upgrade the working tree when the workingtree being opened is old
696
 
            (but still fully supported).
 
532
        
 
533
        TODO: static convenience version of this?
697
534
        """
698
535
        raise NotImplementedError(self.open_workingtree)
699
536
 
721
558
        workingtree and discards it, and that's somewhat expensive.) 
722
559
        """
723
560
        try:
724
 
            self.open_workingtree(recommend_upgrade=False)
 
561
            self.open_workingtree()
725
562
            return True
726
563
        except errors.NoWorkingTree:
727
564
            return False
728
565
 
729
 
    def _cloning_metadir(self):
730
 
        """Produce a metadir suitable for cloning with."""
731
 
        result_format = self._format.__class__()
732
 
        try:
733
 
            try:
734
 
                branch = self.open_branch()
735
 
                source_repository = branch.repository
736
 
            except errors.NotBranchError:
737
 
                source_branch = None
738
 
                source_repository = self.open_repository()
739
 
        except errors.NoRepositoryPresent:
740
 
            source_repository = None
741
 
        else:
742
 
            # XXX TODO: This isinstance is here because we have not implemented
743
 
            # the fix recommended in bug # 103195 - to delegate this choice the
744
 
            # repository itself.
745
 
            repo_format = source_repository._format
746
 
            if not isinstance(repo_format, remote.RemoteRepositoryFormat):
747
 
                result_format.repository_format = repo_format
748
 
        try:
749
 
            # TODO: Couldn't we just probe for the format in these cases,
750
 
            # rather than opening the whole tree?  It would be a little
751
 
            # faster. mbp 20070401
752
 
            tree = self.open_workingtree(recommend_upgrade=False)
753
 
        except (errors.NoWorkingTree, errors.NotLocalUrl):
754
 
            result_format.workingtree_format = None
755
 
        else:
756
 
            result_format.workingtree_format = tree._format.__class__()
757
 
        return result_format, source_repository
758
 
 
759
 
    def cloning_metadir(self):
760
 
        """Produce a metadir suitable for cloning or sprouting with.
761
 
 
762
 
        These operations may produce workingtrees (yes, even though they're
763
 
        "cloning" something that doesn't have a tree), so a viable workingtree
764
 
        format must be selected.
765
 
        """
766
 
        format, repository = self._cloning_metadir()
767
 
        if format._workingtree_format is None:
768
 
            if repository is None:
769
 
                return format
770
 
            tree_format = repository._format._matchingbzrdir.workingtree_format
771
 
            format.workingtree_format = tree_format.__class__()
772
 
        return format
773
 
 
774
 
    def checkout_metadir(self):
775
 
        return self.cloning_metadir()
776
 
 
777
 
    def sprout(self, url, revision_id=None, force_new_repo=False,
778
 
               recurse='down', possible_transports=None):
 
566
    def sprout(self, url, revision_id=None, basis=None, force_new_repo=False):
779
567
        """Create a copy of this bzrdir prepared for use as a new line of
780
568
        development.
781
569
 
782
 
        If url's last component does not exist, it will be created.
 
570
        If urls last component does not exist, it will be created.
783
571
 
784
572
        Attributes related to the identity of the source branch like
785
573
        branch nickname will be cleaned, a working tree is created
789
577
        if revision_id is not None, then the clone operation may tune
790
578
            itself to download less data.
791
579
        """
792
 
        target_transport = get_transport(url, possible_transports)
793
 
        target_transport.ensure_base()
794
 
        cloning_format = self.cloning_metadir()
795
 
        result = cloning_format.initialize_on_transport(target_transport)
 
580
        self._make_tail(url)
 
581
        result = self._format.initialize(url)
 
582
        basis_repo, basis_branch, basis_tree = self._get_basis_components(basis)
796
583
        try:
797
584
            source_branch = self.open_branch()
798
585
            source_repository = source_branch.repository
801
588
            try:
802
589
                source_repository = self.open_repository()
803
590
            except errors.NoRepositoryPresent:
804
 
                source_repository = None
 
591
                # copy the entire basis one if there is one
 
592
                # but there is no repository.
 
593
                source_repository = basis_repo
805
594
        if force_new_repo:
806
595
            result_repo = None
807
596
        else:
816
605
            result.create_repository()
817
606
        elif source_repository is not None and result_repo is None:
818
607
            # have source, and want to make a new target repo
819
 
            result_repo = source_repository.sprout(result,
820
 
                                                   revision_id=revision_id)
821
 
        else:
 
608
            # we don't clone the repo because that preserves attributes
 
609
            # like is_shared(), and we have not yet implemented a 
 
610
            # repository sprout().
 
611
            result_repo = result.create_repository()
 
612
        if result_repo is not None:
822
613
            # fetch needed content into target.
823
 
            if source_repository is not None:
824
 
                # would rather do 
825
 
                # source_repository.copy_content_into(result_repo,
826
 
                #                                     revision_id=revision_id)
827
 
                # so we can override the copy method
828
 
                result_repo.fetch(source_repository, revision_id=revision_id)
 
614
            if basis_repo:
 
615
                # XXX FIXME RBC 20060214 need tests for this when the basis
 
616
                # is incomplete
 
617
                result_repo.fetch(basis_repo, revision_id=revision_id)
 
618
            result_repo.fetch(source_repository, revision_id=revision_id)
829
619
        if source_branch is not None:
830
620
            source_branch.sprout(result, revision_id=revision_id)
831
621
        else:
832
622
            result.create_branch()
833
 
        if isinstance(target_transport, LocalTransport) and (
834
 
            result_repo is None or result_repo.make_working_trees()):
835
 
            wt = result.create_workingtree()
836
 
            wt.lock_write()
837
 
            try:
838
 
                if wt.path2id('') is None:
839
 
                    try:
840
 
                        wt.set_root_id(self.open_workingtree.get_root_id())
841
 
                    except errors.NoWorkingTree:
842
 
                        pass
843
 
            finally:
844
 
                wt.unlock()
845
 
        else:
846
 
            wt = None
847
 
        if recurse == 'down':
848
 
            if wt is not None:
849
 
                basis = wt.basis_tree()
850
 
                basis.lock_read()
851
 
                subtrees = basis.iter_references()
852
 
                recurse_branch = wt.branch
853
 
            elif source_branch is not None:
854
 
                basis = source_branch.basis_tree()
855
 
                basis.lock_read()
856
 
                subtrees = basis.iter_references()
857
 
                recurse_branch = source_branch
858
 
            else:
859
 
                subtrees = []
860
 
                basis = None
861
 
            try:
862
 
                for path, file_id in subtrees:
863
 
                    target = urlutils.join(url, urlutils.escape(path))
864
 
                    sublocation = source_branch.reference_parent(file_id, path)
865
 
                    sublocation.bzrdir.sprout(target,
866
 
                        basis.get_reference_revision(file_id, path),
867
 
                        force_new_repo=force_new_repo, recurse=recurse)
868
 
            finally:
869
 
                if basis is not None:
870
 
                    basis.unlock()
 
623
        # TODO: jam 20060426 we probably need a test in here in the
 
624
        #       case that the newly sprouted branch is a remote one
 
625
        if result_repo is None or result_repo.make_working_trees():
 
626
            result.create_workingtree()
871
627
        return result
872
628
 
873
629
 
877
633
    def __init__(self, _transport, _format):
878
634
        """See BzrDir.__init__."""
879
635
        super(BzrDirPreSplitOut, self).__init__(_transport, _format)
880
 
        assert self._format._lock_class == lockable_files.TransportLock
 
636
        assert self._format._lock_class == TransportLock
881
637
        assert self._format._lock_file_name == 'branch-lock'
882
 
        self._control_files = lockable_files.LockableFiles(
883
 
                                            self.get_branch_transport(None),
 
638
        self._control_files = LockableFiles(self.get_branch_transport(None),
884
639
                                            self._format._lock_file_name,
885
640
                                            self._format._lock_class)
886
641
 
888
643
        """Pre-splitout bzrdirs do not suffer from stale locks."""
889
644
        raise NotImplementedError(self.break_lock)
890
645
 
891
 
    def clone(self, url, revision_id=None, force_new_repo=False):
 
646
    def clone(self, url, revision_id=None, basis=None, force_new_repo=False):
892
647
        """See BzrDir.clone()."""
893
648
        from bzrlib.workingtree import WorkingTreeFormat2
894
649
        self._make_tail(url)
895
650
        result = self._format._initialize_for_clone(url)
896
 
        self.open_repository().clone(result, revision_id=revision_id)
 
651
        basis_repo, basis_branch, basis_tree = self._get_basis_components(basis)
 
652
        self.open_repository().clone(result, revision_id=revision_id, basis=basis_repo)
897
653
        from_branch = self.open_branch()
898
654
        from_branch.clone(result, revision_id=revision_id)
899
655
        try:
900
 
            self.open_workingtree().clone(result)
 
656
            self.open_workingtree().clone(result, basis=basis_tree)
901
657
        except errors.NotLocalUrl:
902
658
            # make a new one, this format always has to have one.
903
659
            try:
912
668
        """See BzrDir.create_branch."""
913
669
        return self.open_branch()
914
670
 
915
 
    def destroy_branch(self):
916
 
        """See BzrDir.destroy_branch."""
917
 
        raise errors.UnsupportedOperation(self.destroy_branch, self)
918
 
 
919
671
    def create_repository(self, shared=False):
920
672
        """See BzrDir.create_repository."""
921
673
        if shared:
925
677
    def create_workingtree(self, revision_id=None):
926
678
        """See BzrDir.create_workingtree."""
927
679
        # this looks buggy but is not -really-
928
 
        # because this format creates the workingtree when the bzrdir is
929
 
        # created
930
680
        # clone and sprout will have set the revision_id
931
681
        # and that will have set it for us, its only
932
682
        # specific uses of create_workingtree in isolation
933
683
        # that can do wonky stuff here, and that only
934
684
        # happens for creating checkouts, which cannot be 
935
685
        # done on this format anyway. So - acceptable wart.
936
 
        result = self.open_workingtree(recommend_upgrade=False)
 
686
        result = self.open_workingtree()
937
687
        if revision_id is not None:
938
 
            if revision_id == _mod_revision.NULL_REVISION:
939
 
                result.set_parent_ids([])
940
 
            else:
941
 
                result.set_parent_ids([revision_id])
 
688
            result.set_last_revision(revision_id)
942
689
        return result
943
690
 
944
 
    def destroy_workingtree(self):
945
 
        """See BzrDir.destroy_workingtree."""
946
 
        raise errors.UnsupportedOperation(self.destroy_workingtree, self)
947
 
 
948
 
    def destroy_workingtree_metadata(self):
949
 
        """See BzrDir.destroy_workingtree_metadata."""
950
 
        raise errors.UnsupportedOperation(self.destroy_workingtree_metadata, 
951
 
                                          self)
952
 
 
953
691
    def get_branch_transport(self, branch_format):
954
692
        """See BzrDir.get_branch_transport()."""
955
693
        if branch_format is None:
995
733
        self._check_supported(format, unsupported)
996
734
        return format.open(self, _found=True)
997
735
 
998
 
    def sprout(self, url, revision_id=None, force_new_repo=False,
999
 
               possible_transports=None):
 
736
    def sprout(self, url, revision_id=None, basis=None):
1000
737
        """See BzrDir.sprout()."""
1001
738
        from bzrlib.workingtree import WorkingTreeFormat2
1002
739
        self._make_tail(url)
1003
740
        result = self._format._initialize_for_clone(url)
 
741
        basis_repo, basis_branch, basis_tree = self._get_basis_components(basis)
1004
742
        try:
1005
 
            self.open_repository().clone(result, revision_id=revision_id)
 
743
            self.open_repository().clone(result, revision_id=revision_id, basis=basis_repo)
1006
744
        except errors.NoRepositoryPresent:
1007
745
            pass
1008
746
        try:
1030
768
 
1031
769
    def open_repository(self):
1032
770
        """See BzrDir.open_repository."""
1033
 
        from bzrlib.repofmt.weaverepo import RepositoryFormat4
 
771
        from bzrlib.repository import RepositoryFormat4
1034
772
        return RepositoryFormat4().open(self, _found=True)
1035
773
 
1036
774
 
1042
780
 
1043
781
    def open_repository(self):
1044
782
        """See BzrDir.open_repository."""
1045
 
        from bzrlib.repofmt.weaverepo import RepositoryFormat5
 
783
        from bzrlib.repository import RepositoryFormat5
1046
784
        return RepositoryFormat5().open(self, _found=True)
1047
785
 
1048
 
    def open_workingtree(self, _unsupported=False,
1049
 
            recommend_upgrade=True):
 
786
    def open_workingtree(self, _unsupported=False):
1050
787
        """See BzrDir.create_workingtree."""
1051
788
        from bzrlib.workingtree import WorkingTreeFormat2
1052
 
        wt_format = WorkingTreeFormat2()
1053
 
        # we don't warn here about upgrades; that ought to be handled for the
1054
 
        # bzrdir as a whole
1055
 
        return wt_format.open(self, _found=True)
 
789
        return WorkingTreeFormat2().open(self, _found=True)
1056
790
 
1057
791
 
1058
792
class BzrDir6(BzrDirPreSplitOut):
1063
797
 
1064
798
    def open_repository(self):
1065
799
        """See BzrDir.open_repository."""
1066
 
        from bzrlib.repofmt.weaverepo import RepositoryFormat6
 
800
        from bzrlib.repository import RepositoryFormat6
1067
801
        return RepositoryFormat6().open(self, _found=True)
1068
802
 
1069
 
    def open_workingtree(self, _unsupported=False,
1070
 
        recommend_upgrade=True):
 
803
    def open_workingtree(self, _unsupported=False):
1071
804
        """See BzrDir.create_workingtree."""
1072
 
        # we don't warn here about upgrades; that ought to be handled for the
1073
 
        # bzrdir as a whole
1074
805
        from bzrlib.workingtree import WorkingTreeFormat2
1075
806
        return WorkingTreeFormat2().open(self, _found=True)
1076
807
 
1090
821
 
1091
822
    def create_branch(self):
1092
823
        """See BzrDir.create_branch."""
1093
 
        return self._format.get_branch_format().initialize(self)
1094
 
 
1095
 
    def destroy_branch(self):
1096
 
        """See BzrDir.create_branch."""
1097
 
        self.transport.delete_tree('branch')
 
824
        from bzrlib.branch import BranchFormat
 
825
        return BranchFormat.get_default_format().initialize(self)
1098
826
 
1099
827
    def create_repository(self, shared=False):
1100
828
        """See BzrDir.create_repository."""
1103
831
    def create_workingtree(self, revision_id=None):
1104
832
        """See BzrDir.create_workingtree."""
1105
833
        from bzrlib.workingtree import WorkingTreeFormat
1106
 
        return self._format.workingtree_format.initialize(self, revision_id)
1107
 
 
1108
 
    def destroy_workingtree(self):
1109
 
        """See BzrDir.destroy_workingtree."""
1110
 
        wt = self.open_workingtree(recommend_upgrade=False)
1111
 
        repository = wt.branch.repository
1112
 
        empty = repository.revision_tree(_mod_revision.NULL_REVISION)
1113
 
        wt.revert(old_tree=empty)
1114
 
        self.destroy_workingtree_metadata()
1115
 
 
1116
 
    def destroy_workingtree_metadata(self):
1117
 
        self.transport.delete_tree('checkout')
1118
 
 
1119
 
    def find_branch_format(self):
1120
 
        """Find the branch 'format' for this bzrdir.
1121
 
 
1122
 
        This might be a synthetic object for e.g. RemoteBranch and SVN.
1123
 
        """
1124
 
        from bzrlib.branch import BranchFormat
1125
 
        return BranchFormat.find_format(self)
 
834
        return WorkingTreeFormat.get_default_format().initialize(self, revision_id)
1126
835
 
1127
836
    def _get_mkdir_mode(self):
1128
837
        """Figure out the mode to use when creating a bzrdir subdir."""
1129
 
        temp_control = lockable_files.LockableFiles(self.transport, '',
1130
 
                                     lockable_files.TransportLock)
 
838
        temp_control = LockableFiles(self.transport, '', TransportLock)
1131
839
        return temp_control._dir_mode
1132
840
 
1133
 
    def get_branch_reference(self):
1134
 
        """See BzrDir.get_branch_reference()."""
1135
 
        from bzrlib.branch import BranchFormat
1136
 
        format = BranchFormat.find_format(self)
1137
 
        return format.get_reference(self)
1138
 
 
1139
841
    def get_branch_transport(self, branch_format):
1140
842
        """See BzrDir.get_branch_transport()."""
1141
843
        if branch_format is None:
1193
895
                return True
1194
896
        except errors.NoRepositoryPresent:
1195
897
            pass
1196
 
        try:
1197
 
            if not isinstance(self.open_branch()._format,
1198
 
                              format.get_branch_format().__class__):
1199
 
                # the branch needs an upgrade.
1200
 
                return True
1201
 
        except errors.NotBranchError:
1202
 
            pass
1203
 
        try:
1204
 
            my_wt = self.open_workingtree(recommend_upgrade=False)
1205
 
            if not isinstance(my_wt._format,
1206
 
                              format.workingtree_format.__class__):
1207
 
                # the workingtree needs an upgrade.
1208
 
                return True
1209
 
        except (errors.NoWorkingTree, errors.NotLocalUrl):
1210
 
            pass
 
898
        # currently there are no other possible conversions for meta1 formats.
1211
899
        return False
1212
900
 
1213
901
    def open_branch(self, unsupported=False):
1214
902
        """See BzrDir.open_branch."""
1215
 
        format = self.find_branch_format()
 
903
        from bzrlib.branch import BranchFormat
 
904
        format = BranchFormat.find_format(self)
1216
905
        self._check_supported(format, unsupported)
1217
906
        return format.open(self, _found=True)
1218
907
 
1223
912
        self._check_supported(format, unsupported)
1224
913
        return format.open(self, _found=True)
1225
914
 
1226
 
    def open_workingtree(self, unsupported=False,
1227
 
            recommend_upgrade=True):
 
915
    def open_workingtree(self, unsupported=False):
1228
916
        """See BzrDir.open_workingtree."""
1229
917
        from bzrlib.workingtree import WorkingTreeFormat
1230
918
        format = WorkingTreeFormat.find_format(self)
1231
 
        self._check_supported(format, unsupported,
1232
 
            recommend_upgrade,
1233
 
            basedir=self.root_transport.base)
 
919
        self._check_supported(format, unsupported)
1234
920
        return format.open(self, _found=True)
1235
921
 
1236
922
 
1242
928
     * a format string,
1243
929
     * an open routine.
1244
930
 
1245
 
    Formats are placed in a dict by their format string for reference 
 
931
    Formats are placed in an dict by their format string for reference 
1246
932
    during bzrdir opening. These should be subclasses of BzrDirFormat
1247
933
    for consistency.
1248
934
 
1263
949
    This is a list of BzrDirFormat objects.
1264
950
    """
1265
951
 
1266
 
    _control_server_formats = []
1267
 
    """The registered control server formats, e.g. RemoteBzrDirs.
1268
 
 
1269
 
    This is a list of BzrDirFormat objects.
1270
 
    """
1271
 
 
1272
952
    _lock_file_name = 'branch-lock'
1273
953
 
1274
954
    # _lock_class must be set in subclasses to the lock type, typ.
1275
955
    # TransportLock or LockDir
1276
956
 
1277
957
    @classmethod
1278
 
    def find_format(klass, transport, _server_formats=True):
 
958
    def find_format(klass, transport):
1279
959
        """Return the format present at transport."""
1280
 
        if _server_formats:
1281
 
            formats = klass._control_server_formats + klass._control_formats
1282
 
        else:
1283
 
            formats = klass._control_formats
1284
 
        for format in formats:
 
960
        for format in klass._control_formats:
1285
961
            try:
1286
962
                return format.probe_transport(transport)
1287
963
            except errors.NotBranchError:
1291
967
 
1292
968
    @classmethod
1293
969
    def probe_transport(klass, transport):
1294
 
        """Return the .bzrdir style format present in a directory."""
 
970
        """Return the .bzrdir style transport present at URL."""
1295
971
        try:
1296
972
            format_string = transport.get(".bzr/branch-format").read()
1297
973
        except errors.NoSuchFile:
1329
1005
        """
1330
1006
        raise NotImplementedError(self.get_converter)
1331
1007
 
1332
 
    def initialize(self, url, possible_transports=None):
 
1008
    def initialize(self, url):
1333
1009
        """Create a bzr control dir at this url and return an opened copy.
1334
1010
        
1335
1011
        Subclasses should typically override initialize_on_transport
1336
1012
        instead of this method.
1337
1013
        """
1338
 
        return self.initialize_on_transport(get_transport(url,
1339
 
                                                          possible_transports))
 
1014
        return self.initialize_on_transport(get_transport(url))
1340
1015
 
1341
1016
    def initialize_on_transport(self, transport):
1342
1017
        """Initialize a new bzrdir in the base directory of a Transport."""
1343
1018
        # Since we don't have a .bzr directory, inherit the
1344
1019
        # mode from the root directory
1345
 
        temp_control = lockable_files.LockableFiles(transport,
1346
 
                            '', lockable_files.TransportLock)
 
1020
        temp_control = LockableFiles(transport, '', TransportLock)
1347
1021
        temp_control._transport.mkdir('.bzr',
1348
1022
                                      # FIXME: RBC 20060121 don't peek under
1349
1023
                                      # the covers
1358
1032
                      ('branch-format', self.get_format_string()),
1359
1033
                      ]
1360
1034
        # NB: no need to escape relative paths that are url safe.
1361
 
        control_files = lockable_files.LockableFiles(control,
1362
 
                            self._lock_file_name, self._lock_class)
 
1035
        control_files = LockableFiles(control, self._lock_file_name, 
 
1036
                                      self._lock_class)
1363
1037
        control_files.create_lock()
1364
1038
        control_files.lock_write()
1365
1039
        try:
1378
1052
        """
1379
1053
        return True
1380
1054
 
1381
 
    def same_model(self, target_format):
1382
 
        return (self.repository_format.rich_root_data == 
1383
 
            target_format.rich_root_data)
1384
 
 
1385
1055
    @classmethod
1386
1056
    def known_formats(klass):
1387
1057
        """Return all the known formats.
1407
1077
        _found is a private parameter, do not use it.
1408
1078
        """
1409
1079
        if not _found:
1410
 
            found_format = BzrDirFormat.find_format(transport)
1411
 
            if not isinstance(found_format, self.__class__):
1412
 
                raise AssertionError("%s was asked to open %s, but it seems to need "
1413
 
                        "format %s" 
1414
 
                        % (self, transport, found_format))
 
1080
            assert isinstance(BzrDirFormat.find_format(transport),
 
1081
                              self.__class__)
1415
1082
        return self._open(transport)
1416
1083
 
1417
1084
    def _open(self, transport):
1428
1095
 
1429
1096
    @classmethod
1430
1097
    def register_control_format(klass, format):
1431
 
        """Register a format that does not use '.bzr' for its control dir.
 
1098
        """Register a format that does not use '.bzrdir' for its control dir.
1432
1099
 
1433
1100
        TODO: This should be pulled up into a 'ControlDirFormat' base class
1434
1101
        which BzrDirFormat can inherit from, and renamed to register_format 
1438
1105
        klass._control_formats.append(format)
1439
1106
 
1440
1107
    @classmethod
1441
 
    def register_control_server_format(klass, format):
1442
 
        """Register a control format for client-server environments.
1443
 
 
1444
 
        These formats will be tried before ones registered with
1445
 
        register_control_format.  This gives implementations that decide to the
1446
 
        chance to grab it before anything looks at the contents of the format
1447
 
        file.
1448
 
        """
1449
 
        klass._control_server_formats.append(format)
1450
 
 
1451
 
    @classmethod
1452
 
    @symbol_versioning.deprecated_method(symbol_versioning.zero_fourteen)
1453
1108
    def set_default_format(klass, format):
1454
 
        klass._set_default_format(format)
1455
 
 
1456
 
    @classmethod
1457
 
    def _set_default_format(klass, format):
1458
 
        """Set default format (for testing behavior of defaults only)"""
1459
1109
        klass._default_format = format
1460
1110
 
1461
1111
    def __str__(self):
1462
 
        # Trim the newline
1463
 
        return self.get_format_string().rstrip()
 
1112
        return self.get_format_string()[:-1]
1464
1113
 
1465
1114
    @classmethod
1466
1115
    def unregister_format(klass, format):
1472
1121
        klass._control_formats.remove(format)
1473
1122
 
1474
1123
 
 
1124
# register BzrDirFormat as a control format
 
1125
BzrDirFormat.register_control_format(BzrDirFormat)
 
1126
 
 
1127
 
1475
1128
class BzrDirFormat4(BzrDirFormat):
1476
1129
    """Bzr dir format 4.
1477
1130
 
1485
1138
    removed in format 5; write support for this format has been removed.
1486
1139
    """
1487
1140
 
1488
 
    _lock_class = lockable_files.TransportLock
 
1141
    _lock_class = TransportLock
1489
1142
 
1490
1143
    def get_format_string(self):
1491
1144
        """See BzrDirFormat.get_format_string()."""
1519
1172
 
1520
1173
    def __return_repository_format(self):
1521
1174
        """Circular import protection."""
1522
 
        from bzrlib.repofmt.weaverepo import RepositoryFormat4
1523
 
        return RepositoryFormat4()
 
1175
        from bzrlib.repository import RepositoryFormat4
 
1176
        return RepositoryFormat4(self)
1524
1177
    repository_format = property(__return_repository_format)
1525
1178
 
1526
1179
 
1535
1188
       Unhashed stores in the repository.
1536
1189
    """
1537
1190
 
1538
 
    _lock_class = lockable_files.TransportLock
 
1191
    _lock_class = TransportLock
1539
1192
 
1540
1193
    def get_format_string(self):
1541
1194
        """See BzrDirFormat.get_format_string()."""
1559
1212
        Except when they are being cloned.
1560
1213
        """
1561
1214
        from bzrlib.branch import BzrBranchFormat4
1562
 
        from bzrlib.repofmt.weaverepo import RepositoryFormat5
 
1215
        from bzrlib.repository import RepositoryFormat5
1563
1216
        from bzrlib.workingtree import WorkingTreeFormat2
1564
1217
        result = (super(BzrDirFormat5, self).initialize_on_transport(transport))
1565
1218
        RepositoryFormat5().initialize(result, _internal=True)
1566
1219
        if not _cloning:
1567
 
            branch = BzrBranchFormat4().initialize(result)
1568
 
            try:
1569
 
                WorkingTreeFormat2().initialize(result)
1570
 
            except errors.NotLocalUrl:
1571
 
                # Even though we can't access the working tree, we need to
1572
 
                # create its control files.
1573
 
                WorkingTreeFormat2().stub_initialize_remote(branch.control_files)
 
1220
            BzrBranchFormat4().initialize(result)
 
1221
            WorkingTreeFormat2().initialize(result)
1574
1222
        return result
1575
1223
 
1576
1224
    def _open(self, transport):
1579
1227
 
1580
1228
    def __return_repository_format(self):
1581
1229
        """Circular import protection."""
1582
 
        from bzrlib.repofmt.weaverepo import RepositoryFormat5
1583
 
        return RepositoryFormat5()
 
1230
        from bzrlib.repository import RepositoryFormat5
 
1231
        return RepositoryFormat5(self)
1584
1232
    repository_format = property(__return_repository_format)
1585
1233
 
1586
1234
 
1594
1242
     - Format 6 repositories [always]
1595
1243
    """
1596
1244
 
1597
 
    _lock_class = lockable_files.TransportLock
 
1245
    _lock_class = TransportLock
1598
1246
 
1599
1247
    def get_format_string(self):
1600
1248
        """See BzrDirFormat.get_format_string()."""
1618
1266
        Except when they are being cloned.
1619
1267
        """
1620
1268
        from bzrlib.branch import BzrBranchFormat4
1621
 
        from bzrlib.repofmt.weaverepo import RepositoryFormat6
 
1269
        from bzrlib.repository import RepositoryFormat6
1622
1270
        from bzrlib.workingtree import WorkingTreeFormat2
1623
1271
        result = super(BzrDirFormat6, self).initialize_on_transport(transport)
1624
1272
        RepositoryFormat6().initialize(result, _internal=True)
1625
1273
        if not _cloning:
1626
 
            branch = BzrBranchFormat4().initialize(result)
 
1274
            BzrBranchFormat4().initialize(result)
1627
1275
            try:
1628
1276
                WorkingTreeFormat2().initialize(result)
1629
1277
            except errors.NotLocalUrl:
1630
 
                # Even though we can't access the working tree, we need to
1631
 
                # create its control files.
1632
 
                WorkingTreeFormat2().stub_initialize_remote(branch.control_files)
 
1278
                # emulate pre-check behaviour for working tree and silently 
 
1279
                # fail.
 
1280
                pass
1633
1281
        return result
1634
1282
 
1635
1283
    def _open(self, transport):
1638
1286
 
1639
1287
    def __return_repository_format(self):
1640
1288
        """Circular import protection."""
1641
 
        from bzrlib.repofmt.weaverepo import RepositoryFormat6
1642
 
        return RepositoryFormat6()
 
1289
        from bzrlib.repository import RepositoryFormat6
 
1290
        return RepositoryFormat6(self)
1643
1291
    repository_format = property(__return_repository_format)
1644
1292
 
1645
1293
 
1654
1302
     - Format 7 repositories [optional]
1655
1303
    """
1656
1304
 
1657
 
    _lock_class = lockdir.LockDir
1658
 
 
1659
 
    def __init__(self):
1660
 
        self._workingtree_format = None
1661
 
        self._branch_format = None
1662
 
 
1663
 
    def __eq__(self, other):
1664
 
        if other.__class__ is not self.__class__:
1665
 
            return False
1666
 
        if other.repository_format != self.repository_format:
1667
 
            return False
1668
 
        if other.workingtree_format != self.workingtree_format:
1669
 
            return False
1670
 
        return True
1671
 
 
1672
 
    def __ne__(self, other):
1673
 
        return not self == other
1674
 
 
1675
 
    def get_branch_format(self):
1676
 
        if self._branch_format is None:
1677
 
            from bzrlib.branch import BranchFormat
1678
 
            self._branch_format = BranchFormat.get_default_format()
1679
 
        return self._branch_format
1680
 
 
1681
 
    def set_branch_format(self, format):
1682
 
        self._branch_format = format
 
1305
    _lock_class = LockDir
1683
1306
 
1684
1307
    def get_converter(self, format=None):
1685
1308
        """See BzrDirFormat.get_converter()."""
1715
1338
 
1716
1339
    repository_format = property(__return_repository_format, __set_repository_format)
1717
1340
 
1718
 
    def __get_workingtree_format(self):
1719
 
        if self._workingtree_format is None:
1720
 
            from bzrlib.workingtree import WorkingTreeFormat
1721
 
            self._workingtree_format = WorkingTreeFormat.get_default_format()
1722
 
        return self._workingtree_format
1723
 
 
1724
 
    def __set_workingtree_format(self, wt_format):
1725
 
        self._workingtree_format = wt_format
1726
 
 
1727
 
    workingtree_format = property(__get_workingtree_format,
1728
 
                                  __set_workingtree_format)
1729
 
 
1730
 
 
1731
 
# Register bzr control format
1732
 
BzrDirFormat.register_control_format(BzrDirFormat)
1733
 
 
1734
 
# Register bzr formats
 
1341
 
1735
1342
BzrDirFormat.register_format(BzrDirFormat4())
1736
1343
BzrDirFormat.register_format(BzrDirFormat5())
1737
1344
BzrDirFormat.register_format(BzrDirFormat6())
1738
1345
__default_format = BzrDirMetaFormat1()
1739
1346
BzrDirFormat.register_format(__default_format)
1740
 
BzrDirFormat._default_format = __default_format
 
1347
BzrDirFormat.set_default_format(__default_format)
 
1348
 
 
1349
 
 
1350
class BzrDirTestProviderAdapter(object):
 
1351
    """A tool to generate a suite testing multiple bzrdir formats at once.
 
1352
 
 
1353
    This is done by copying the test once for each transport and injecting
 
1354
    the transport_server, transport_readonly_server, and bzrdir_format
 
1355
    classes into each copy. Each copy is also given a new id() to make it
 
1356
    easy to identify.
 
1357
    """
 
1358
 
 
1359
    def __init__(self, transport_server, transport_readonly_server, formats):
 
1360
        self._transport_server = transport_server
 
1361
        self._transport_readonly_server = transport_readonly_server
 
1362
        self._formats = formats
 
1363
    
 
1364
    def adapt(self, test):
 
1365
        result = TestSuite()
 
1366
        for format in self._formats:
 
1367
            new_test = deepcopy(test)
 
1368
            new_test.transport_server = self._transport_server
 
1369
            new_test.transport_readonly_server = self._transport_readonly_server
 
1370
            new_test.bzrdir_format = format
 
1371
            def make_new_test_id():
 
1372
                new_id = "%s(%s)" % (new_test.id(), format.__class__.__name__)
 
1373
                return lambda: new_id
 
1374
            new_test.id = make_new_test_id()
 
1375
            result.addTest(new_test)
 
1376
        return result
1741
1377
 
1742
1378
 
1743
1379
class Converter(object):
1830
1466
        self.bzrdir.transport.delete_tree('text-store')
1831
1467
 
1832
1468
    def _convert_working_inv(self):
1833
 
        inv = xml4.serializer_v4.read_inventory(
1834
 
                    self.branch.control_files.get('inventory'))
1835
 
        new_inv_xml = xml5.serializer_v5.write_inventory_to_string(inv, working=True)
 
1469
        inv = serializer_v4.read_inventory(self.branch.control_files.get('inventory'))
 
1470
        new_inv_xml = bzrlib.xml5.serializer_v5.write_inventory_to_string(inv)
1836
1471
        # FIXME inventory is a working tree change.
1837
 
        self.branch.control_files.put('inventory', StringIO(new_inv_xml))
 
1472
        self.branch.control_files.put('inventory', new_inv_xml)
1838
1473
 
1839
1474
    def _write_all_weaves(self):
1840
1475
        controlweaves = WeaveStore(self.bzrdir.transport, prefixed=False)
1864
1499
                                                      prefixed=False,
1865
1500
                                                      compressed=True))
1866
1501
        try:
1867
 
            transaction = WriteTransaction()
 
1502
            transaction = bzrlib.transactions.WriteTransaction()
1868
1503
            for i, rev_id in enumerate(self.converted_revs):
1869
1504
                self.pb.update('write revision', i, len(self.converted_revs))
1870
1505
                _revision_store.add_revision(self.revisions[rev_id], transaction)
1896
1531
    def _load_old_inventory(self, rev_id):
1897
1532
        assert rev_id not in self.converted_revs
1898
1533
        old_inv_xml = self.branch.repository.inventory_store.get(rev_id).read()
1899
 
        inv = xml4.serializer_v4.read_inventory_from_string(old_inv_xml)
1900
 
        inv.revision_id = rev_id
 
1534
        inv = serializer_v4.read_inventory_from_string(old_inv_xml)
1901
1535
        rev = self.revisions[rev_id]
1902
1536
        if rev.inventory_sha1:
1903
1537
            assert rev.inventory_sha1 == sha_string(old_inv_xml), \
1907
1541
    def _load_updated_inventory(self, rev_id):
1908
1542
        assert rev_id in self.converted_revs
1909
1543
        inv_xml = self.inv_weave.get_text(rev_id)
1910
 
        inv = xml5.serializer_v5.read_inventory_from_string(inv_xml)
 
1544
        inv = bzrlib.xml5.serializer_v5.read_inventory_from_string(inv_xml)
1911
1545
        return inv
1912
1546
 
1913
1547
    def _convert_one_rev(self, rev_id):
1917
1551
        present_parents = [p for p in rev.parent_ids
1918
1552
                           if p not in self.absent_revisions]
1919
1553
        self._convert_revision_contents(rev, inv, present_parents)
1920
 
        self._store_new_inv(rev, inv, present_parents)
 
1554
        self._store_new_weave(rev, inv, present_parents)
1921
1555
        self.converted_revs.add(rev_id)
1922
1556
 
1923
 
    def _store_new_inv(self, rev, inv, present_parents):
 
1557
    def _store_new_weave(self, rev, inv, present_parents):
1924
1558
        # the XML is now updated with text versions
1925
1559
        if __debug__:
1926
1560
            entries = inv.iter_entries()
1927
1561
            entries.next()
1928
1562
            for path, ie in entries:
1929
 
                assert getattr(ie, 'revision', None) is not None, \
 
1563
                assert hasattr(ie, 'revision'), \
1930
1564
                    'no revision on {%s} in {%s}' % \
1931
1565
                    (file_id, rev.revision_id)
1932
 
        new_inv_xml = xml5.serializer_v5.write_inventory_to_string(inv)
 
1566
        new_inv_xml = bzrlib.xml5.serializer_v5.write_inventory_to_string(inv)
1933
1567
        new_inv_sha1 = sha_string(new_inv_xml)
1934
 
        self.inv_weave.add_lines(rev.revision_id,
 
1568
        self.inv_weave.add_lines(rev.revision_id, 
1935
1569
                                 present_parents,
1936
1570
                                 new_inv_xml.splitlines(True))
1937
1571
        rev.inventory_sha1 = new_inv_sha1
1962
1596
            w = Weave(file_id)
1963
1597
            self.text_weaves[file_id] = w
1964
1598
        text_changed = False
1965
 
        parent_candiate_entries = ie.parent_candidates(parent_invs)
1966
 
        for old_revision in parent_candiate_entries.keys():
1967
 
            # if this fails, its a ghost ?
1968
 
            assert old_revision in self.converted_revs, \
1969
 
                "Revision {%s} not in converted_revs" % old_revision
1970
 
        heads = graph.Graph(self).heads(parent_candiate_entries.keys())
1971
 
        # XXX: Note that this is unordered - and this is tolerable because 
1972
 
        # the previous code was also unordered.
1973
 
        previous_entries = dict((head, parent_candiate_entries[head]) for head
1974
 
            in heads)
 
1599
        previous_entries = ie.find_previous_heads(parent_invs,
 
1600
                                                  None,
 
1601
                                                  None,
 
1602
                                                  entry_vf=w)
 
1603
        for old_revision in previous_entries:
 
1604
                # if this fails, its a ghost ?
 
1605
                assert old_revision in self.converted_revs 
1975
1606
        self.snapshot_ie(previous_entries, ie, w, rev_id)
1976
1607
        del ie.text_id
1977
1608
        assert getattr(ie, 'revision', None) is not None
1978
1609
 
1979
 
    def get_parents(self, revision_ids):
1980
 
        for revision_id in revision_ids:
1981
 
            yield self.revisions[revision_id].parent_ids
1982
 
 
1983
1610
    def snapshot_ie(self, previous_revisions, ie, w, rev_id):
1984
1611
        # TODO: convert this logic, which is ~= snapshot to
1985
1612
        # a call to:. This needs the path figured out. rather than a work_tree
1994
1621
                ie.revision = previous_ie.revision
1995
1622
                return
1996
1623
        if ie.has_text():
1997
 
            text = self.branch.repository.weave_store.get(ie.text_id)
 
1624
            text = self.branch.repository.text_store.get(ie.text_id)
1998
1625
            file_lines = text.readlines()
1999
1626
            assert sha_strings(file_lines) == ie.text_sha1
2000
1627
            assert sum(map(len, file_lines)) == ie.text_size
2068
1695
 
2069
1696
    def convert(self, to_convert, pb):
2070
1697
        """See Converter.convert()."""
2071
 
        from bzrlib.repofmt.weaverepo import RepositoryFormat7
2072
 
        from bzrlib.branch import BzrBranchFormat5
2073
1698
        self.bzrdir = to_convert
2074
1699
        self.pb = pb
2075
1700
        self.count = 0
2104
1729
        # we hard code the formats here because we are converting into
2105
1730
        # the meta format. The meta format upgrader can take this to a 
2106
1731
        # future format within each component.
2107
 
        self.put_format('repository', RepositoryFormat7())
 
1732
        self.put_format('repository', bzrlib.repository.RepositoryFormat7())
2108
1733
        for entry in repository_names:
2109
1734
            self.move_entry('repository', entry)
2110
1735
 
2111
1736
        self.step('Upgrading branch      ')
2112
1737
        self.bzrdir.transport.mkdir('branch', mode=self.dir_mode)
2113
1738
        self.make_lock('branch')
2114
 
        self.put_format('branch', BzrBranchFormat5())
 
1739
        self.put_format('branch', bzrlib.branch.BzrBranchFormat5())
2115
1740
        branch_files = [('revision-history', True),
2116
1741
                        ('branch-name', True),
2117
1742
                        ('parent', False)]
2118
1743
        for entry in branch_files:
2119
1744
            self.move_entry('branch', entry)
2120
1745
 
 
1746
        self.step('Upgrading working tree')
 
1747
        self.bzrdir.transport.mkdir('checkout', mode=self.dir_mode)
 
1748
        self.make_lock('checkout')
 
1749
        self.put_format('checkout', bzrlib.workingtree.WorkingTreeFormat3())
 
1750
        self.bzrdir.transport.delete_multi(self.garbage_inventories, self.pb)
2121
1751
        checkout_files = [('pending-merges', True),
2122
1752
                          ('inventory', True),
2123
1753
                          ('stat-cache', False)]
2124
 
        # If a mandatory checkout file is not present, the branch does not have
2125
 
        # a functional checkout. Do not create a checkout in the converted
2126
 
        # branch.
2127
 
        for name, mandatory in checkout_files:
2128
 
            if mandatory and name not in bzrcontents:
2129
 
                has_checkout = False
2130
 
                break
2131
 
        else:
2132
 
            has_checkout = True
2133
 
        if not has_checkout:
2134
 
            self.pb.note('No working tree.')
2135
 
            # If some checkout files are there, we may as well get rid of them.
2136
 
            for name, mandatory in checkout_files:
2137
 
                if name in bzrcontents:
2138
 
                    self.bzrdir.transport.delete(name)
2139
 
        else:
2140
 
            from bzrlib.workingtree import WorkingTreeFormat3
2141
 
            self.step('Upgrading working tree')
2142
 
            self.bzrdir.transport.mkdir('checkout', mode=self.dir_mode)
2143
 
            self.make_lock('checkout')
2144
 
            self.put_format(
2145
 
                'checkout', WorkingTreeFormat3())
2146
 
            self.bzrdir.transport.delete_multi(
2147
 
                self.garbage_inventories, self.pb)
2148
 
            for entry in checkout_files:
2149
 
                self.move_entry('checkout', entry)
2150
 
            if last_revision is not None:
2151
 
                self.bzrdir._control_files.put_utf8(
2152
 
                    'checkout/last-revision', last_revision)
2153
 
        self.bzrdir._control_files.put_utf8(
2154
 
            'branch-format', BzrDirMetaFormat1().get_format_string())
 
1754
        for entry in checkout_files:
 
1755
            self.move_entry('checkout', entry)
 
1756
        if last_revision is not None:
 
1757
            self.bzrdir._control_files.put_utf8('checkout/last-revision',
 
1758
                                                last_revision)
 
1759
        self.bzrdir._control_files.put_utf8('branch-format', BzrDirMetaFormat1().get_format_string())
2155
1760
        return BzrDir.open(self.bzrdir.root_transport.base)
2156
1761
 
2157
1762
    def make_lock(self, name):
2158
1763
        """Make a lock for the new control dir name."""
2159
1764
        self.step('Make %s lock' % name)
2160
 
        ld = lockdir.LockDir(self.bzrdir.transport,
2161
 
                             '%s/lock' % name,
2162
 
                             file_modebits=self.file_mode,
2163
 
                             dir_modebits=self.dir_mode)
 
1765
        ld = LockDir(self.bzrdir.transport, 
 
1766
                     '%s/lock' % name,
 
1767
                     file_modebits=self.file_mode,
 
1768
                     dir_modebits=self.dir_mode)
2164
1769
        ld.create()
2165
1770
 
2166
1771
    def move_entry(self, new_dir, entry):
2205
1810
                self.pb.note('starting repository conversion')
2206
1811
                converter = CopyConverter(self.target_format.repository_format)
2207
1812
                converter.convert(repo, pb)
2208
 
        try:
2209
 
            branch = self.bzrdir.open_branch()
2210
 
        except errors.NotBranchError:
2211
 
            pass
2212
 
        else:
2213
 
            # TODO: conversions of Branch and Tree should be done by
2214
 
            # InterXFormat lookups
2215
 
            # Avoid circular imports
2216
 
            from bzrlib import branch as _mod_branch
2217
 
            if (branch._format.__class__ is _mod_branch.BzrBranchFormat5 and
2218
 
                self.target_format.get_branch_format().__class__ is
2219
 
                _mod_branch.BzrBranchFormat6):
2220
 
                branch_converter = _mod_branch.Converter5to6()
2221
 
                branch_converter.convert(branch)
2222
 
        try:
2223
 
            tree = self.bzrdir.open_workingtree(recommend_upgrade=False)
2224
 
        except (errors.NoWorkingTree, errors.NotLocalUrl):
2225
 
            pass
2226
 
        else:
2227
 
            # TODO: conversions of Branch and Tree should be done by
2228
 
            # InterXFormat lookups
2229
 
            if (isinstance(tree, workingtree.WorkingTree3) and
2230
 
                not isinstance(tree, workingtree_4.WorkingTree4) and
2231
 
                isinstance(self.target_format.workingtree_format,
2232
 
                    workingtree_4.WorkingTreeFormat4)):
2233
 
                workingtree_4.Converter3to4().convert(tree)
2234
1813
        return to_convert
2235
 
 
2236
 
 
2237
 
# This is not in remote.py because it's small, and needs to be registered.
2238
 
# Putting it in remote.py creates a circular import problem.
2239
 
# we can make it a lazy object if the control formats is turned into something
2240
 
# like a registry.
2241
 
class RemoteBzrDirFormat(BzrDirMetaFormat1):
2242
 
    """Format representing bzrdirs accessed via a smart server"""
2243
 
 
2244
 
    def get_format_description(self):
2245
 
        return 'bzr remote bzrdir'
2246
 
    
2247
 
    @classmethod
2248
 
    def probe_transport(klass, transport):
2249
 
        """Return a RemoteBzrDirFormat object if it looks possible."""
2250
 
        try:
2251
 
            client = transport.get_smart_client()
2252
 
        except (NotImplementedError, AttributeError,
2253
 
                errors.TransportNotPossible):
2254
 
            # no smart server, so not a branch for this format type.
2255
 
            raise errors.NotBranchError(path=transport.base)
2256
 
        else:
2257
 
            # Send a 'hello' request in protocol version one, and decline to
2258
 
            # open it if the server doesn't support our required version (2) so
2259
 
            # that the VFS-based transport will do it.
2260
 
            request = client.get_request()
2261
 
            smart_protocol = protocol.SmartClientRequestProtocolOne(request)
2262
 
            server_version = smart_protocol.query_version()
2263
 
            if server_version != 2:
2264
 
                raise errors.NotBranchError(path=transport.base)
2265
 
            return klass()
2266
 
 
2267
 
    def initialize_on_transport(self, transport):
2268
 
        try:
2269
 
            # hand off the request to the smart server
2270
 
            shared_medium = transport.get_shared_medium()
2271
 
        except errors.NoSmartMedium:
2272
 
            # TODO: lookup the local format from a server hint.
2273
 
            local_dir_format = BzrDirMetaFormat1()
2274
 
            return local_dir_format.initialize_on_transport(transport)
2275
 
        client = _SmartClient(shared_medium)
2276
 
        path = client.remote_path_from_transport(transport)
2277
 
        response = _SmartClient(shared_medium).call('BzrDirFormat.initialize',
2278
 
                                                    path)
2279
 
        assert response[0] in ('ok', ), 'unexpected response code %s' % (response,)
2280
 
        return remote.RemoteBzrDir(transport)
2281
 
 
2282
 
    def _open(self, transport):
2283
 
        return remote.RemoteBzrDir(transport)
2284
 
 
2285
 
    def __eq__(self, other):
2286
 
        if not isinstance(other, RemoteBzrDirFormat):
2287
 
            return False
2288
 
        return self.get_format_description() == other.get_format_description()
2289
 
 
2290
 
 
2291
 
BzrDirFormat.register_control_server_format(RemoteBzrDirFormat)
2292
 
 
2293
 
 
2294
 
class BzrDirFormatInfo(object):
2295
 
 
2296
 
    def __init__(self, native, deprecated, hidden):
2297
 
        self.deprecated = deprecated
2298
 
        self.native = native
2299
 
        self.hidden = hidden
2300
 
 
2301
 
 
2302
 
class BzrDirFormatRegistry(registry.Registry):
2303
 
    """Registry of user-selectable BzrDir subformats.
2304
 
    
2305
 
    Differs from BzrDirFormat._control_formats in that it provides sub-formats,
2306
 
    e.g. BzrDirMeta1 with weave repository.  Also, it's more user-oriented.
2307
 
    """
2308
 
 
2309
 
    def register_metadir(self, key,
2310
 
             repository_format, help, native=True, deprecated=False,
2311
 
             branch_format=None,
2312
 
             tree_format=None,
2313
 
             hidden=False):
2314
 
        """Register a metadir subformat.
2315
 
 
2316
 
        These all use a BzrDirMetaFormat1 bzrdir, but can be parameterized
2317
 
        by the Repository format.
2318
 
 
2319
 
        :param repository_format: The fully-qualified repository format class
2320
 
            name as a string.
2321
 
        :param branch_format: Fully-qualified branch format class name as
2322
 
            a string.
2323
 
        :param tree_format: Fully-qualified tree format class name as
2324
 
            a string.
2325
 
        """
2326
 
        # This should be expanded to support setting WorkingTree and Branch
2327
 
        # formats, once BzrDirMetaFormat1 supports that.
2328
 
        def _load(full_name):
2329
 
            mod_name, factory_name = full_name.rsplit('.', 1)
2330
 
            try:
2331
 
                mod = __import__(mod_name, globals(), locals(),
2332
 
                        [factory_name])
2333
 
            except ImportError, e:
2334
 
                raise ImportError('failed to load %s: %s' % (full_name, e))
2335
 
            try:
2336
 
                factory = getattr(mod, factory_name)
2337
 
            except AttributeError:
2338
 
                raise AttributeError('no factory %s in module %r'
2339
 
                    % (full_name, mod))
2340
 
            return factory()
2341
 
 
2342
 
        def helper():
2343
 
            bd = BzrDirMetaFormat1()
2344
 
            if branch_format is not None:
2345
 
                bd.set_branch_format(_load(branch_format))
2346
 
            if tree_format is not None:
2347
 
                bd.workingtree_format = _load(tree_format)
2348
 
            if repository_format is not None:
2349
 
                bd.repository_format = _load(repository_format)
2350
 
            return bd
2351
 
        self.register(key, helper, help, native, deprecated, hidden)
2352
 
 
2353
 
    def register(self, key, factory, help, native=True, deprecated=False,
2354
 
                 hidden=False):
2355
 
        """Register a BzrDirFormat factory.
2356
 
        
2357
 
        The factory must be a callable that takes one parameter: the key.
2358
 
        It must produce an instance of the BzrDirFormat when called.
2359
 
 
2360
 
        This function mainly exists to prevent the info object from being
2361
 
        supplied directly.
2362
 
        """
2363
 
        registry.Registry.register(self, key, factory, help, 
2364
 
            BzrDirFormatInfo(native, deprecated, hidden))
2365
 
 
2366
 
    def register_lazy(self, key, module_name, member_name, help, native=True,
2367
 
                      deprecated=False, hidden=False):
2368
 
        registry.Registry.register_lazy(self, key, module_name, member_name, 
2369
 
            help, BzrDirFormatInfo(native, deprecated, hidden))
2370
 
 
2371
 
    def set_default(self, key):
2372
 
        """Set the 'default' key to be a clone of the supplied key.
2373
 
        
2374
 
        This method must be called once and only once.
2375
 
        """
2376
 
        registry.Registry.register(self, 'default', self.get(key), 
2377
 
            self.get_help(key), info=self.get_info(key))
2378
 
 
2379
 
    def set_default_repository(self, key):
2380
 
        """Set the FormatRegistry default and Repository default.
2381
 
        
2382
 
        This is a transitional method while Repository.set_default_format
2383
 
        is deprecated.
2384
 
        """
2385
 
        if 'default' in self:
2386
 
            self.remove('default')
2387
 
        self.set_default(key)
2388
 
        format = self.get('default')()
2389
 
        assert isinstance(format, BzrDirMetaFormat1)
2390
 
 
2391
 
    def make_bzrdir(self, key):
2392
 
        return self.get(key)()
2393
 
 
2394
 
    def help_topic(self, topic):
2395
 
        output = textwrap.dedent("""\
2396
 
            These formats can be used for creating branches, working trees, and
2397
 
            repositories.
2398
 
 
2399
 
            """)
2400
 
        default_realkey = None
2401
 
        default_help = self.get_help('default')
2402
 
        help_pairs = []
2403
 
        for key in self.keys():
2404
 
            if key == 'default':
2405
 
                continue
2406
 
            help = self.get_help(key)
2407
 
            if help == default_help:
2408
 
                default_realkey = key
2409
 
            else:
2410
 
                help_pairs.append((key, help))
2411
 
 
2412
 
        def wrapped(key, help, info):
2413
 
            if info.native:
2414
 
                help = '(native) ' + help
2415
 
            return ':%s:\n%s\n\n' % (key, 
2416
 
                    textwrap.fill(help, initial_indent='    ', 
2417
 
                    subsequent_indent='    '))
2418
 
        if default_realkey is not None:
2419
 
            output += wrapped(default_realkey, '(default) %s' % default_help,
2420
 
                              self.get_info('default'))
2421
 
        deprecated_pairs = []
2422
 
        for key, help in help_pairs:
2423
 
            info = self.get_info(key)
2424
 
            if info.hidden:
2425
 
                continue
2426
 
            elif info.deprecated:
2427
 
                deprecated_pairs.append((key, help))
2428
 
            else:
2429
 
                output += wrapped(key, help, info)
2430
 
        if len(deprecated_pairs) > 0:
2431
 
            output += "Deprecated formats are shown below.\n\n"
2432
 
            for key, help in deprecated_pairs:
2433
 
                info = self.get_info(key)
2434
 
                output += wrapped(key, help, info)
2435
 
 
2436
 
        return output
2437
 
 
2438
 
 
2439
 
format_registry = BzrDirFormatRegistry()
2440
 
format_registry.register('weave', BzrDirFormat6,
2441
 
    'Pre-0.8 format.  Slower than knit and does not'
2442
 
    ' support checkouts or shared repositories.',
2443
 
    deprecated=True)
2444
 
format_registry.register_metadir('knit',
2445
 
    'bzrlib.repofmt.knitrepo.RepositoryFormatKnit1',
2446
 
    'Format using knits.  Recommended for interoperation with bzr <= 0.14.',
2447
 
    branch_format='bzrlib.branch.BzrBranchFormat5',
2448
 
    tree_format='bzrlib.workingtree.WorkingTreeFormat3')
2449
 
format_registry.register_metadir('metaweave',
2450
 
    'bzrlib.repofmt.weaverepo.RepositoryFormat7',
2451
 
    'Transitional format in 0.8.  Slower than knit.',
2452
 
    branch_format='bzrlib.branch.BzrBranchFormat5',
2453
 
    tree_format='bzrlib.workingtree.WorkingTreeFormat3',
2454
 
    deprecated=True)
2455
 
format_registry.register_metadir('dirstate',
2456
 
    'bzrlib.repofmt.knitrepo.RepositoryFormatKnit1',
2457
 
    help='New in 0.15: Fast local operations. Compatible with bzr 0.8 and '
2458
 
        'above when accessed over the network.',
2459
 
    branch_format='bzrlib.branch.BzrBranchFormat5',
2460
 
    # this uses bzrlib.workingtree.WorkingTreeFormat4 because importing
2461
 
    # directly from workingtree_4 triggers a circular import.
2462
 
    tree_format='bzrlib.workingtree.WorkingTreeFormat4',
2463
 
    )
2464
 
format_registry.register_metadir('dirstate-tags',
2465
 
    'bzrlib.repofmt.knitrepo.RepositoryFormatKnit1',
2466
 
    help='New in 0.15: Fast local operations and improved scaling for '
2467
 
        'network operations. Additionally adds support for tags.'
2468
 
        ' Incompatible with bzr < 0.15.',
2469
 
    branch_format='bzrlib.branch.BzrBranchFormat6',
2470
 
    tree_format='bzrlib.workingtree.WorkingTreeFormat4',
2471
 
    )
2472
 
format_registry.register_metadir('dirstate-with-subtree',
2473
 
    'bzrlib.repofmt.knitrepo.RepositoryFormatKnit3',
2474
 
    help='New in 0.15: Fast local operations and improved scaling for '
2475
 
        'network operations. Additionally adds support for versioning nested '
2476
 
        'bzr branches. Incompatible with bzr < 0.15.',
2477
 
    branch_format='bzrlib.branch.BzrBranchFormat6',
2478
 
    tree_format='bzrlib.workingtree.WorkingTreeFormat4',
2479
 
    hidden=True,
2480
 
    )
2481
 
format_registry.register_metadir('experimental',
2482
 
    'bzrlib.repofmt.pack_repo.RepositoryFormatKnitPack1',
2483
 
    help='New in XXX: Experimental format with data compatible with dirstate '
2484
 
        'format repositories. Cannot be read except with bzr.dev. '
2485
 
        'WARNING: This format is unstable and data in it will not be upgradable'
2486
 
        ' to release formats of bzr.',
2487
 
    branch_format='bzrlib.branch.BzrBranchFormat6',
2488
 
    tree_format='bzrlib.workingtree.WorkingTreeFormat4',
2489
 
    hidden=True,
2490
 
    )
2491
 
format_registry.register_metadir('experimental-subtree',
2492
 
    'bzrlib.repofmt.pack_repo.RepositoryFormatKnitPack3',
2493
 
    help='New in XXX: Experimental format with data compatible with '
2494
 
        'dirstate-with-subtree format repositories. Cannot be read except with'
2495
 
        ' bzr.dev. WARNING: This format is unstable and data in it will not be'
2496
 
        ' upgradable to release formats of bzr.',
2497
 
    branch_format='bzrlib.branch.BzrBranchFormat6',
2498
 
    tree_format='bzrlib.workingtree.WorkingTreeFormat4',
2499
 
    hidden=True,
2500
 
    )
2501
 
format_registry.set_default('dirstate-tags')