~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: 2007-09-20 02:40:52 UTC
  • mfrom: (2835.1.1 ianc-integration)
  • Revision ID: pqm@pqm.ubuntu.com-20070920024052-y2l7r5o00zrpnr73
No longer propagate index differences automatically (Robert Collins)

Show diffs side-by-side

added added

removed removed

Lines of Context:
1
 
# Copyright (C) 2005, 2006 Canonical Ltd
2
 
 
 
1
# Copyright (C) 2005, 2006, 2007 Canonical Ltd
 
2
#
3
3
# This program is free software; you can redistribute it and/or modify
4
4
# it under the terms of the GNU General Public License as published by
5
5
# the Free Software Foundation; either version 2 of the License, or
6
6
# (at your option) any later version.
7
 
 
 
7
#
8
8
# This program is distributed in the hope that it will be useful,
9
9
# but WITHOUT ANY WARRANTY; without even the implied warranty of
10
10
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
11
11
# GNU General Public License for more details.
12
 
 
 
12
#
13
13
# You should have received a copy of the GNU General Public License
14
14
# along with this program; if not, write to the Free Software
15
15
# Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
20
20
directories.
21
21
"""
22
22
 
23
 
from copy import deepcopy
 
23
# TODO: Can we move specific formats into separate modules to make this file
 
24
# smaller?
 
25
 
 
26
from cStringIO import StringIO
24
27
import os
25
 
from cStringIO import StringIO
26
 
from unittest import TestSuite
 
28
 
 
29
from bzrlib.lazy_import import lazy_import
 
30
lazy_import(globals(), """
 
31
from stat import S_ISDIR
 
32
import textwrap
 
33
from warnings import warn
27
34
 
28
35
import bzrlib
29
 
import bzrlib.errors as errors
30
 
from bzrlib.lockable_files import LockableFiles, TransportLock
31
 
from bzrlib.lockdir import LockDir
32
 
from bzrlib.osutils import safe_unicode
 
36
from bzrlib import (
 
37
    errors,
 
38
    graph,
 
39
    lockable_files,
 
40
    lockdir,
 
41
    registry,
 
42
    remote,
 
43
    revision as _mod_revision,
 
44
    symbol_versioning,
 
45
    ui,
 
46
    urlutils,
 
47
    xml4,
 
48
    xml5,
 
49
    workingtree,
 
50
    workingtree_4,
 
51
    )
33
52
from bzrlib.osutils import (
34
 
                            abspath,
35
 
                            pathjoin,
36
 
                            safe_unicode,
37
 
                            sha_strings,
38
 
                            sha_string,
39
 
                            )
 
53
    sha_strings,
 
54
    sha_string,
 
55
    )
 
56
from bzrlib.smart.client import _SmartClient
 
57
from bzrlib.smart import protocol
40
58
from bzrlib.store.revision.text import TextRevisionStore
41
59
from bzrlib.store.text import TextStore
42
60
from bzrlib.store.versioned import WeaveStore
43
 
from bzrlib.symbol_versioning import *
44
 
from bzrlib.trace import mutter
45
61
from bzrlib.transactions import WriteTransaction
46
 
from bzrlib.transport import get_transport, urlunescape
 
62
from bzrlib.transport import (
 
63
    do_catching_redirections,
 
64
    get_transport,
 
65
    )
 
66
from bzrlib.weave import Weave
 
67
""")
 
68
 
 
69
from bzrlib.trace import (
 
70
    mutter,
 
71
    note,
 
72
    )
47
73
from bzrlib.transport.local import LocalTransport
48
 
from bzrlib.weave import Weave
49
 
from bzrlib.xml4 import serializer_v4
50
 
from bzrlib.xml5 import serializer_v5
 
74
from bzrlib.symbol_versioning import (
 
75
    deprecated_function,
 
76
    deprecated_method,
 
77
    zero_ninetyone,
 
78
    )
51
79
 
52
80
 
53
81
class BzrDir(object):
68
96
        If there is a tree, the tree is opened and break_lock() called.
69
97
        Otherwise, branch is tried, and finally repository.
70
98
        """
 
99
        # XXX: This seems more like a UI function than something that really
 
100
        # belongs in this class.
71
101
        try:
72
102
            thing_to_unlock = self.open_workingtree()
73
103
        except (errors.NotLocalUrl, errors.NoWorkingTree):
84
114
        """Return true if this bzrdir is one whose format we can convert from."""
85
115
        return True
86
116
 
 
117
    def check_conversion_target(self, target_format):
 
118
        target_repo_format = target_format.repository_format
 
119
        source_repo_format = self._format.repository_format
 
120
        source_repo_format.check_conversion_target(target_repo_format)
 
121
 
87
122
    @staticmethod
88
 
    def _check_supported(format, allow_unsupported):
89
 
        """Check whether format is a supported format.
90
 
 
91
 
        If allow_unsupported is True, this is a no-op.
 
123
    def _check_supported(format, allow_unsupported,
 
124
        recommend_upgrade=True,
 
125
        basedir=None):
 
126
        """Give an error or warning on old formats.
 
127
 
 
128
        :param format: may be any kind of format - workingtree, branch, 
 
129
        or repository.
 
130
 
 
131
        :param allow_unsupported: If true, allow opening 
 
132
        formats that are strongly deprecated, and which may 
 
133
        have limited functionality.
 
134
 
 
135
        :param recommend_upgrade: If true (default), warn
 
136
        the user through the ui object that they may wish
 
137
        to upgrade the object.
92
138
        """
 
139
        # TODO: perhaps move this into a base Format class; it's not BzrDir
 
140
        # specific. mbp 20070323
93
141
        if not allow_unsupported and not format.is_supported():
94
142
            # see open_downlevel to open legacy branches.
95
 
            raise errors.UnsupportedFormatError(
96
 
                    'sorry, format %s not supported' % format,
97
 
                    ['use a different bzr version',
98
 
                     'or remove the .bzr directory'
99
 
                     ' and "bzr init" again'])
 
143
            raise errors.UnsupportedFormatError(format=format)
 
144
        if recommend_upgrade \
 
145
            and getattr(format, 'upgrade_recommended', False):
 
146
            ui.ui_factory.recommend_upgrade(
 
147
                format.get_format_description(),
 
148
                basedir)
100
149
 
101
 
    def clone(self, url, revision_id=None, basis=None, force_new_repo=False):
 
150
    def clone(self, url, revision_id=None, force_new_repo=False):
102
151
        """Clone this bzrdir and its contents to url verbatim.
103
152
 
104
153
        If urls last component does not exist, it will be created.
108
157
        :param force_new_repo: Do not use a shared repository for the target 
109
158
                               even if one is available.
110
159
        """
111
 
        self._make_tail(url)
112
 
        basis_repo, basis_branch, basis_tree = self._get_basis_components(basis)
113
 
        result = self._format.initialize(url)
 
160
        return self.clone_on_transport(get_transport(url),
 
161
                                       revision_id=revision_id,
 
162
                                       force_new_repo=force_new_repo)
 
163
 
 
164
    def clone_on_transport(self, transport, revision_id=None,
 
165
                           force_new_repo=False):
 
166
        """Clone this bzrdir and its contents to transport verbatim.
 
167
 
 
168
        If the target directory does not exist, it will be created.
 
169
 
 
170
        if revision_id is not None, then the clone operation may tune
 
171
            itself to download less data.
 
172
        :param force_new_repo: Do not use a shared repository for the target 
 
173
                               even if one is available.
 
174
        """
 
175
        transport.ensure_base()
 
176
        result = self._format.initialize_on_transport(transport)
114
177
        try:
115
178
            local_repo = self.find_repository()
116
179
        except errors.NoRepositoryPresent:
120
183
            if force_new_repo:
121
184
                result_repo = local_repo.clone(
122
185
                    result,
123
 
                    revision_id=revision_id,
124
 
                    basis=basis_repo)
 
186
                    revision_id=revision_id)
125
187
                result_repo.set_make_working_trees(local_repo.make_working_trees())
126
188
            else:
127
189
                try:
128
190
                    result_repo = result.find_repository()
129
191
                    # fetch content this dir needs.
130
 
                    if basis_repo:
131
 
                        # XXX FIXME RBC 20060214 need tests for this when the basis
132
 
                        # is incomplete
133
 
                        result_repo.fetch(basis_repo, revision_id=revision_id)
134
192
                    result_repo.fetch(local_repo, revision_id=revision_id)
135
193
                except errors.NoRepositoryPresent:
136
194
                    # needed to make one anyway.
137
195
                    result_repo = local_repo.clone(
138
196
                        result,
139
 
                        revision_id=revision_id,
140
 
                        basis=basis_repo)
 
197
                        revision_id=revision_id)
141
198
                    result_repo.set_make_working_trees(local_repo.make_working_trees())
142
199
        # 1 if there is a branch present
143
200
        #   make sure its content is available in the target repository
147
204
        except errors.NotBranchError:
148
205
            pass
149
206
        try:
150
 
            self.open_workingtree().clone(result, basis=basis_tree)
 
207
            self.open_workingtree().clone(result)
151
208
        except (errors.NoWorkingTree, errors.NotLocalUrl):
152
209
            pass
153
210
        return result
154
211
 
155
 
    def _get_basis_components(self, basis):
156
 
        """Retrieve the basis components that are available at basis."""
157
 
        if basis is None:
158
 
            return None, None, None
159
 
        try:
160
 
            basis_tree = basis.open_workingtree()
161
 
            basis_branch = basis_tree.branch
162
 
            basis_repo = basis_branch.repository
163
 
        except (errors.NoWorkingTree, errors.NotLocalUrl):
164
 
            basis_tree = None
165
 
            try:
166
 
                basis_branch = basis.open_branch()
167
 
                basis_repo = basis_branch.repository
168
 
            except errors.NotBranchError:
169
 
                basis_branch = None
170
 
                try:
171
 
                    basis_repo = basis.open_repository()
172
 
                except errors.NoRepositoryPresent:
173
 
                    basis_repo = None
174
 
        return basis_repo, basis_branch, basis_tree
175
 
 
 
212
    # TODO: This should be given a Transport, and should chdir up; otherwise
 
213
    # this will open a new connection.
176
214
    def _make_tail(self, url):
177
 
        segments = url.split('/')
178
 
        if segments and segments[-1] not in ('', '.'):
179
 
            parent = '/'.join(segments[:-1])
180
 
            t = bzrlib.transport.get_transport(parent)
181
 
            try:
182
 
                t.mkdir(segments[-1])
183
 
            except errors.FileExists:
184
 
                pass
 
215
        t = get_transport(url)
 
216
        t.ensure_base()
185
217
 
186
218
    @classmethod
187
 
    def create(cls, base):
 
219
    def create(cls, base, format=None, possible_transports=None):
188
220
        """Create a new BzrDir at the url 'base'.
189
221
        
190
222
        This will call the current default formats initialize with base
191
223
        as the only parameter.
192
224
 
193
 
        If you need a specific format, consider creating an instance
194
 
        of that and calling initialize().
 
225
        :param format: If supplied, the format of branch to create.  If not
 
226
            supplied, the default is used.
 
227
        :param possible_transports: If supplied, a list of transports that 
 
228
            can be reused to share a remote connection.
195
229
        """
196
230
        if cls is not BzrDir:
197
 
            raise AssertionError("BzrDir.create always creates the default format, "
198
 
                    "not one of %r" % cls)
199
 
        segments = base.split('/')
200
 
        if segments and segments[-1] not in ('', '.'):
201
 
            parent = '/'.join(segments[:-1])
202
 
            t = bzrlib.transport.get_transport(parent)
203
 
            try:
204
 
                t.mkdir(segments[-1])
205
 
            except errors.FileExists:
206
 
                pass
207
 
        return BzrDirFormat.get_default_format().initialize(safe_unicode(base))
 
231
            raise AssertionError("BzrDir.create always creates the default"
 
232
                " format, not one of %r" % cls)
 
233
        t = get_transport(base, possible_transports)
 
234
        t.ensure_base()
 
235
        if format is None:
 
236
            format = BzrDirFormat.get_default_format()
 
237
        return format.initialize(base, possible_transports)
208
238
 
209
239
    def create_branch(self):
210
240
        """Create a branch in this BzrDir.
214
244
        """
215
245
        raise NotImplementedError(self.create_branch)
216
246
 
 
247
    def destroy_branch(self):
 
248
        """Destroy the branch in this BzrDir"""
 
249
        raise NotImplementedError(self.destroy_branch)
 
250
 
217
251
    @staticmethod
218
 
    def create_branch_and_repo(base, force_new_repo=False):
 
252
    def create_branch_and_repo(base, force_new_repo=False, format=None):
219
253
        """Create a new BzrDir, Branch and Repository at the url 'base'.
220
254
 
221
255
        This will use the current default BzrDirFormat, and use whatever 
228
262
        :param base: The URL to create the branch at.
229
263
        :param force_new_repo: If True a new repository is always created.
230
264
        """
231
 
        bzrdir = BzrDir.create(base)
 
265
        bzrdir = BzrDir.create(base, format)
232
266
        bzrdir._find_or_create_repository(force_new_repo)
233
267
        return bzrdir.create_branch()
234
268
 
243
277
        
244
278
    @staticmethod
245
279
    def create_branch_convenience(base, force_new_repo=False,
246
 
                                  force_new_tree=None, format=None):
 
280
                                  force_new_tree=None, format=None,
 
281
                                  possible_transports=None):
247
282
        """Create a new BzrDir, Branch and Repository at the url 'base'.
248
283
 
249
284
        This is a convenience function - it will use an existing repository
265
300
        :param force_new_repo: If True a new repository is always created.
266
301
        :param force_new_tree: If True or False force creation of a tree or 
267
302
                               prevent such creation respectively.
268
 
        :param format: Override for the for the bzrdir format to create
 
303
        :param format: Override for the for the bzrdir format to create.
 
304
        :param possible_transports: An optional reusable transports list.
269
305
        """
270
306
        if force_new_tree:
271
307
            # check for non local urls
272
 
            t = get_transport(safe_unicode(base))
 
308
            t = get_transport(base, possible_transports)
273
309
            if not isinstance(t, LocalTransport):
274
310
                raise errors.NotLocalUrl(base)
275
 
        if format is None:
276
 
            bzrdir = BzrDir.create(base)
277
 
        else:
278
 
            bzrdir = format.initialize(base)
 
311
        bzrdir = BzrDir.create(base, format, possible_transports)
279
312
        repo = bzrdir._find_or_create_repository(force_new_repo)
280
313
        result = bzrdir.create_branch()
281
 
        if force_new_tree or (repo.make_working_trees() and 
 
314
        if force_new_tree or (repo.make_working_trees() and
282
315
                              force_new_tree is None):
283
316
            try:
284
317
                bzrdir.create_workingtree()
285
318
            except errors.NotLocalUrl:
286
319
                pass
287
320
        return result
288
 
        
 
321
 
289
322
    @staticmethod
290
 
    def create_repository(base, shared=False):
 
323
    @deprecated_function(zero_ninetyone)
 
324
    def create_repository(base, shared=False, format=None):
291
325
        """Create a new BzrDir and Repository at the url 'base'.
292
326
 
293
 
        This will use the current default BzrDirFormat, and use whatever 
294
 
        repository format that that uses for bzrdirformat.create_repository.
 
327
        If no format is supplied, this will default to the current default
 
328
        BzrDirFormat by default, and use whatever repository format that that
 
329
        uses for bzrdirformat.create_repository.
295
330
 
296
 
        ;param shared: Create a shared repository rather than a standalone
 
331
        :param shared: Create a shared repository rather than a standalone
297
332
                       repository.
298
333
        The Repository object is returned.
299
334
 
300
335
        This must be overridden as an instance method in child classes, where
301
336
        it should take no parameters and construct whatever repository format
302
337
        that child class desires.
 
338
 
 
339
        This method is deprecated, please call create_repository on a bzrdir
 
340
        instance instead.
303
341
        """
304
 
        bzrdir = BzrDir.create(base)
305
 
        return bzrdir.create_repository()
 
342
        bzrdir = BzrDir.create(base, format)
 
343
        return bzrdir.create_repository(shared)
306
344
 
307
345
    @staticmethod
308
 
    def create_standalone_workingtree(base):
 
346
    def create_standalone_workingtree(base, format=None):
309
347
        """Create a new BzrDir, WorkingTree, Branch and Repository at 'base'.
310
348
 
311
349
        'base' must be a local path or a file:// url.
314
352
        repository format that that uses for bzrdirformat.create_workingtree,
315
353
        create_branch and create_repository.
316
354
 
317
 
        The WorkingTree object is returned.
 
355
        :return: The WorkingTree object.
318
356
        """
319
 
        t = get_transport(safe_unicode(base))
 
357
        t = get_transport(base)
320
358
        if not isinstance(t, LocalTransport):
321
359
            raise errors.NotLocalUrl(base)
322
 
        bzrdir = BzrDir.create_branch_and_repo(safe_unicode(base),
323
 
                                               force_new_repo=True).bzrdir
 
360
        bzrdir = BzrDir.create_branch_and_repo(base,
 
361
                                               force_new_repo=True,
 
362
                                               format=format).bzrdir
324
363
        return bzrdir.create_workingtree()
325
364
 
326
365
    def create_workingtree(self, revision_id=None):
330
369
        """
331
370
        raise NotImplementedError(self.create_workingtree)
332
371
 
 
372
    def retire_bzrdir(self):
 
373
        """Permanently disable the bzrdir.
 
374
 
 
375
        This is done by renaming it to give the user some ability to recover
 
376
        if there was a problem.
 
377
 
 
378
        This will have horrible consequences if anyone has anything locked or
 
379
        in use.
 
380
        """
 
381
        for i in xrange(10000):
 
382
            try:
 
383
                to_path = '.bzr.retired.%d' % i
 
384
                self.root_transport.rename('.bzr', to_path)
 
385
                note("renamed %s to %s"
 
386
                    % (self.root_transport.abspath('.bzr'), to_path))
 
387
                break
 
388
            except (errors.TransportError, IOError, errors.PathError):
 
389
                pass
 
390
 
 
391
    def destroy_workingtree(self):
 
392
        """Destroy the working tree at this BzrDir.
 
393
 
 
394
        Formats that do not support this may raise UnsupportedOperation.
 
395
        """
 
396
        raise NotImplementedError(self.destroy_workingtree)
 
397
 
 
398
    def destroy_workingtree_metadata(self):
 
399
        """Destroy the control files for the working tree at this BzrDir.
 
400
 
 
401
        The contents of working tree files are not affected.
 
402
        Formats that do not support this may raise UnsupportedOperation.
 
403
        """
 
404
        raise NotImplementedError(self.destroy_workingtree_metadata)
 
405
 
333
406
    def find_repository(self):
334
407
        """Find the repository that should be used for a_bzrdir.
335
408
 
343
416
            pass
344
417
        next_transport = self.root_transport.clone('..')
345
418
        while True:
 
419
            # find the next containing bzrdir
346
420
            try:
347
421
                found_bzrdir = BzrDir.open_containing_from_transport(
348
422
                    next_transport)[0]
349
423
            except errors.NotBranchError:
 
424
                # none found
350
425
                raise errors.NoRepositoryPresent(self)
 
426
            # does it have a repository ?
351
427
            try:
352
428
                repository = found_bzrdir.open_repository()
353
429
            except errors.NoRepositoryPresent:
354
430
                next_transport = found_bzrdir.root_transport.clone('..')
355
 
                continue
356
 
            if ((found_bzrdir.root_transport.base == 
 
431
                if (found_bzrdir.root_transport.base == next_transport.base):
 
432
                    # top of the file system
 
433
                    break
 
434
                else:
 
435
                    continue
 
436
            if ((found_bzrdir.root_transport.base ==
357
437
                 self.root_transport.base) or repository.is_shared()):
358
438
                return repository
359
439
            else:
360
440
                raise errors.NoRepositoryPresent(self)
361
441
        raise errors.NoRepositoryPresent(self)
362
442
 
 
443
    def get_branch_reference(self):
 
444
        """Return the referenced URL for the branch in this bzrdir.
 
445
 
 
446
        :raises NotBranchError: If there is no Branch.
 
447
        :return: The URL the branch in this bzrdir references if it is a
 
448
            reference branch, or None for regular branches.
 
449
        """
 
450
        return None
 
451
 
363
452
    def get_branch_transport(self, branch_format):
364
453
        """Get the transport for use by branch format in this BzrDir.
365
454
 
366
455
        Note that bzr dirs that do not support format strings will raise
367
456
        IncompatibleFormat if the branch format they are given has
368
 
        a format string, and vice verca.
 
457
        a format string, and vice versa.
369
458
 
370
459
        If branch_format is None, the transport is returned with no 
371
460
        checking. if it is not None, then the returned transport is
378
467
 
379
468
        Note that bzr dirs that do not support format strings will raise
380
469
        IncompatibleFormat if the repository format they are given has
381
 
        a format string, and vice verca.
 
470
        a format string, and vice versa.
382
471
 
383
472
        If repository_format is None, the transport is returned with no 
384
473
        checking. if it is not None, then the returned transport is
390
479
        """Get the transport for use by workingtree format in this BzrDir.
391
480
 
392
481
        Note that bzr dirs that do not support format strings will raise
393
 
        IncompatibleFormat if the workingtree format they are given has
394
 
        a format string, and vice verca.
 
482
        IncompatibleFormat if the workingtree format they are given has a
 
483
        format string, and vice versa.
395
484
 
396
485
        If workingtree_format is None, the transport is returned with no 
397
486
        checking. if it is not None, then the returned transport is
426
515
        # this might be better on the BzrDirFormat class because it refers to 
427
516
        # all the possible bzrdir disk formats. 
428
517
        # This method is tested via the workingtree is_control_filename tests- 
429
 
        # it was extractd from WorkingTree.is_control_filename. If the methods
 
518
        # it was extracted from WorkingTree.is_control_filename. If the methods
430
519
        # contract is extended beyond the current trivial  implementation please
431
520
        # add new tests for it to the appropriate place.
432
521
        return filename == '.bzr' or filename.startswith('.bzr/')
448
537
        return BzrDir.open(base, _unsupported=True)
449
538
        
450
539
    @staticmethod
451
 
    def open(base, _unsupported=False):
 
540
    def open(base, _unsupported=False, possible_transports=None):
452
541
        """Open an existing bzrdir, rooted at 'base' (url)
453
542
        
454
543
        _unsupported is a private parameter to the BzrDir class.
455
544
        """
456
 
        t = get_transport(base)
457
 
        mutter("trying to open %r with transport %r", base, t)
458
 
        format = BzrDirFormat.find_format(t)
 
545
        t = get_transport(base, possible_transports=possible_transports)
 
546
        return BzrDir.open_from_transport(t, _unsupported=_unsupported)
 
547
 
 
548
    @staticmethod
 
549
    def open_from_transport(transport, _unsupported=False,
 
550
                            _server_formats=True):
 
551
        """Open a bzrdir within a particular directory.
 
552
 
 
553
        :param transport: Transport containing the bzrdir.
 
554
        :param _unsupported: private.
 
555
        """
 
556
        base = transport.base
 
557
 
 
558
        def find_format(transport):
 
559
            return transport, BzrDirFormat.find_format(
 
560
                transport, _server_formats=_server_formats)
 
561
 
 
562
        def redirected(transport, e, redirection_notice):
 
563
            qualified_source = e.get_source_url()
 
564
            relpath = transport.relpath(qualified_source)
 
565
            if not e.target.endswith(relpath):
 
566
                # Not redirected to a branch-format, not a branch
 
567
                raise errors.NotBranchError(path=e.target)
 
568
            target = e.target[:-len(relpath)]
 
569
            note('%s is%s redirected to %s',
 
570
                 transport.base, e.permanently, target)
 
571
            # Let's try with a new transport
 
572
            qualified_target = e.get_target_url()[:-len(relpath)]
 
573
            # FIXME: If 'transport' has a qualifier, this should
 
574
            # be applied again to the new transport *iff* the
 
575
            # schemes used are the same. It's a bit tricky to
 
576
            # verify, so I'll punt for now
 
577
            # -- vila20070212
 
578
            return get_transport(target)
 
579
 
 
580
        try:
 
581
            transport, format = do_catching_redirections(find_format,
 
582
                                                         transport,
 
583
                                                         redirected)
 
584
        except errors.TooManyRedirections:
 
585
            raise errors.NotBranchError(base)
 
586
 
459
587
        BzrDir._check_supported(format, _unsupported)
460
 
        return format.open(t, _found=True)
 
588
        return format.open(transport, _found=True)
461
589
 
462
590
    def open_branch(self, unsupported=False):
463
591
        """Open the branch object at this BzrDir if one is present.
470
598
        raise NotImplementedError(self.open_branch)
471
599
 
472
600
    @staticmethod
473
 
    def open_containing(url):
 
601
    def open_containing(url, possible_transports=None):
474
602
        """Open an existing branch which contains url.
475
603
        
476
604
        :param url: url to search from.
477
605
        See open_containing_from_transport for more detail.
478
606
        """
479
 
        return BzrDir.open_containing_from_transport(get_transport(url))
 
607
        transport = get_transport(url, possible_transports)
 
608
        return BzrDir.open_containing_from_transport(transport)
480
609
    
481
610
    @staticmethod
482
611
    def open_containing_from_transport(a_transport):
489
618
        If there is one and it is either an unrecognised format or an unsupported 
490
619
        format, UnknownFormatError or UnsupportedFormatError are raised.
491
620
        If there is one, it is returned, along with the unused portion of url.
 
621
 
 
622
        :return: The BzrDir that contains the path, and a Unicode path 
 
623
                for the rest of the URL.
492
624
        """
493
625
        # this gets the normalised url back. I.e. '.' -> the full path.
494
626
        url = a_transport.base
495
627
        while True:
496
628
            try:
497
 
                format = BzrDirFormat.find_format(a_transport)
498
 
                BzrDir._check_supported(format, False)
499
 
                return format.open(a_transport), a_transport.relpath(url)
 
629
                result = BzrDir.open_from_transport(a_transport)
 
630
                return result, urlutils.unescape(a_transport.relpath(url))
500
631
            except errors.NotBranchError, e:
501
 
                mutter('not a branch in: %r %s', a_transport.base, e)
502
 
            new_t = a_transport.clone('..')
 
632
                pass
 
633
            try:
 
634
                new_t = a_transport.clone('..')
 
635
            except errors.InvalidURLJoin:
 
636
                # reached the root, whatever that may be
 
637
                raise errors.NotBranchError(path=url)
503
638
            if new_t.base == a_transport.base:
504
639
                # reached the root, whatever that may be
505
640
                raise errors.NotBranchError(path=url)
506
641
            a_transport = new_t
507
642
 
 
643
    @classmethod
 
644
    def open_containing_tree_or_branch(klass, location):
 
645
        """Return the branch and working tree contained by a location.
 
646
 
 
647
        Returns (tree, branch, relpath).
 
648
        If there is no tree at containing the location, tree will be None.
 
649
        If there is no branch containing the location, an exception will be
 
650
        raised
 
651
        relpath is the portion of the path that is contained by the branch.
 
652
        """
 
653
        bzrdir, relpath = klass.open_containing(location)
 
654
        try:
 
655
            tree = bzrdir.open_workingtree()
 
656
        except (errors.NoWorkingTree, errors.NotLocalUrl):
 
657
            tree = None
 
658
            branch = bzrdir.open_branch()
 
659
        else:
 
660
            branch = tree.branch
 
661
        return tree, branch, relpath
 
662
 
508
663
    def open_repository(self, _unsupported=False):
509
664
        """Open the repository object at this BzrDir if one is present.
510
665
 
517
672
        """
518
673
        raise NotImplementedError(self.open_repository)
519
674
 
520
 
    def open_workingtree(self, _unsupported=False):
 
675
    def open_workingtree(self, _unsupported=False,
 
676
            recommend_upgrade=True):
521
677
        """Open the workingtree object at this BzrDir if one is present.
522
 
        
523
 
        TODO: static convenience version of this?
 
678
 
 
679
        :param recommend_upgrade: Optional keyword parameter, when True (the
 
680
            default), emit through the ui module a recommendation that the user
 
681
            upgrade the working tree when the workingtree being opened is old
 
682
            (but still fully supported).
524
683
        """
525
684
        raise NotImplementedError(self.open_workingtree)
526
685
 
548
707
        workingtree and discards it, and that's somewhat expensive.) 
549
708
        """
550
709
        try:
551
 
            self.open_workingtree()
 
710
            self.open_workingtree(recommend_upgrade=False)
552
711
            return True
553
712
        except errors.NoWorkingTree:
554
713
            return False
555
714
 
556
 
    def sprout(self, url, revision_id=None, basis=None, force_new_repo=False):
 
715
    def _cloning_metadir(self):
 
716
        """Produce a metadir suitable for cloning with"""
 
717
        result_format = self._format.__class__()
 
718
        try:
 
719
            try:
 
720
                branch = self.open_branch()
 
721
                source_repository = branch.repository
 
722
            except errors.NotBranchError:
 
723
                source_branch = None
 
724
                source_repository = self.open_repository()
 
725
        except errors.NoRepositoryPresent:
 
726
            source_repository = None
 
727
        else:
 
728
            # XXX TODO: This isinstance is here because we have not implemented
 
729
            # the fix recommended in bug # 103195 - to delegate this choice the
 
730
            # repository itself.
 
731
            repo_format = source_repository._format
 
732
            if not isinstance(repo_format, remote.RemoteRepositoryFormat):
 
733
                result_format.repository_format = repo_format
 
734
        try:
 
735
            # TODO: Couldn't we just probe for the format in these cases,
 
736
            # rather than opening the whole tree?  It would be a little
 
737
            # faster. mbp 20070401
 
738
            tree = self.open_workingtree(recommend_upgrade=False)
 
739
        except (errors.NoWorkingTree, errors.NotLocalUrl):
 
740
            result_format.workingtree_format = None
 
741
        else:
 
742
            result_format.workingtree_format = tree._format.__class__()
 
743
        return result_format, source_repository
 
744
 
 
745
    def cloning_metadir(self):
 
746
        """Produce a metadir suitable for cloning or sprouting with.
 
747
 
 
748
        These operations may produce workingtrees (yes, even though they're
 
749
        "cloning" something that doesn't have a tree, so a viable workingtree
 
750
        format must be selected.
 
751
        """
 
752
        format, repository = self._cloning_metadir()
 
753
        if format._workingtree_format is None:
 
754
            if repository is None:
 
755
                return format
 
756
            tree_format = repository._format._matchingbzrdir.workingtree_format
 
757
            format.workingtree_format = tree_format.__class__()
 
758
        return format
 
759
 
 
760
    def checkout_metadir(self):
 
761
        return self.cloning_metadir()
 
762
 
 
763
    def sprout(self, url, revision_id=None, force_new_repo=False,
 
764
               recurse='down', possible_transports=None):
557
765
        """Create a copy of this bzrdir prepared for use as a new line of
558
766
        development.
559
767
 
567
775
        if revision_id is not None, then the clone operation may tune
568
776
            itself to download less data.
569
777
        """
570
 
        self._make_tail(url)
571
 
        result = self._format.initialize(url)
572
 
        basis_repo, basis_branch, basis_tree = self._get_basis_components(basis)
 
778
        target_transport = get_transport(url, possible_transports)
 
779
        target_transport.ensure_base()
 
780
        cloning_format = self.cloning_metadir()
 
781
        result = cloning_format.initialize_on_transport(target_transport)
573
782
        try:
574
783
            source_branch = self.open_branch()
575
784
            source_repository = source_branch.repository
578
787
            try:
579
788
                source_repository = self.open_repository()
580
789
            except errors.NoRepositoryPresent:
581
 
                # copy the entire basis one if there is one
582
 
                # but there is no repository.
583
 
                source_repository = basis_repo
 
790
                source_repository = None
584
791
        if force_new_repo:
585
792
            result_repo = None
586
793
        else:
595
802
            result.create_repository()
596
803
        elif source_repository is not None and result_repo is None:
597
804
            # have source, and want to make a new target repo
598
 
            # we dont clone the repo because that preserves attributes
599
 
            # like is_shared(), and we have not yet implemented a 
600
 
            # repository sprout().
601
 
            result_repo = result.create_repository()
602
 
        if result_repo is not None:
 
805
            result_repo = source_repository.sprout(result,
 
806
                                                   revision_id=revision_id)
 
807
        else:
603
808
            # fetch needed content into target.
604
 
            if basis_repo:
605
 
                # XXX FIXME RBC 20060214 need tests for this when the basis
606
 
                # is incomplete
607
 
                result_repo.fetch(basis_repo, revision_id=revision_id)
608
 
            result_repo.fetch(source_repository, revision_id=revision_id)
 
809
            if source_repository is not None:
 
810
                # would rather do 
 
811
                # source_repository.copy_content_into(result_repo,
 
812
                #                                     revision_id=revision_id)
 
813
                # so we can override the copy method
 
814
                result_repo.fetch(source_repository, revision_id=revision_id)
609
815
        if source_branch is not None:
610
816
            source_branch.sprout(result, revision_id=revision_id)
611
817
        else:
612
818
            result.create_branch()
613
 
        if result_repo is None or result_repo.make_working_trees():
614
 
            result.create_workingtree()
 
819
        if isinstance(target_transport, LocalTransport) and (
 
820
            result_repo is None or result_repo.make_working_trees()):
 
821
            wt = result.create_workingtree()
 
822
            wt.lock_write()
 
823
            try:
 
824
                if wt.path2id('') is None:
 
825
                    try:
 
826
                        wt.set_root_id(self.open_workingtree.get_root_id())
 
827
                    except errors.NoWorkingTree:
 
828
                        pass
 
829
            finally:
 
830
                wt.unlock()
 
831
        else:
 
832
            wt = None
 
833
        if recurse == 'down':
 
834
            if wt is not None:
 
835
                basis = wt.basis_tree()
 
836
                basis.lock_read()
 
837
                subtrees = basis.iter_references()
 
838
                recurse_branch = wt.branch
 
839
            elif source_branch is not None:
 
840
                basis = source_branch.basis_tree()
 
841
                basis.lock_read()
 
842
                subtrees = basis.iter_references()
 
843
                recurse_branch = source_branch
 
844
            else:
 
845
                subtrees = []
 
846
                basis = None
 
847
            try:
 
848
                for path, file_id in subtrees:
 
849
                    target = urlutils.join(url, urlutils.escape(path))
 
850
                    sublocation = source_branch.reference_parent(file_id, path)
 
851
                    sublocation.bzrdir.sprout(target,
 
852
                        basis.get_reference_revision(file_id, path),
 
853
                        force_new_repo=force_new_repo, recurse=recurse)
 
854
            finally:
 
855
                if basis is not None:
 
856
                    basis.unlock()
615
857
        return result
616
858
 
617
859
 
621
863
    def __init__(self, _transport, _format):
622
864
        """See BzrDir.__init__."""
623
865
        super(BzrDirPreSplitOut, self).__init__(_transport, _format)
624
 
        assert self._format._lock_class == TransportLock
 
866
        assert self._format._lock_class == lockable_files.TransportLock
625
867
        assert self._format._lock_file_name == 'branch-lock'
626
 
        self._control_files = LockableFiles(self.get_branch_transport(None),
 
868
        self._control_files = lockable_files.LockableFiles(
 
869
                                            self.get_branch_transport(None),
627
870
                                            self._format._lock_file_name,
628
871
                                            self._format._lock_class)
629
872
 
631
874
        """Pre-splitout bzrdirs do not suffer from stale locks."""
632
875
        raise NotImplementedError(self.break_lock)
633
876
 
634
 
    def clone(self, url, revision_id=None, basis=None, force_new_repo=False):
 
877
    def clone(self, url, revision_id=None, force_new_repo=False):
635
878
        """See BzrDir.clone()."""
636
879
        from bzrlib.workingtree import WorkingTreeFormat2
637
880
        self._make_tail(url)
638
881
        result = self._format._initialize_for_clone(url)
639
 
        basis_repo, basis_branch, basis_tree = self._get_basis_components(basis)
640
 
        self.open_repository().clone(result, revision_id=revision_id, basis=basis_repo)
 
882
        self.open_repository().clone(result, revision_id=revision_id)
641
883
        from_branch = self.open_branch()
642
884
        from_branch.clone(result, revision_id=revision_id)
643
885
        try:
644
 
            self.open_workingtree().clone(result, basis=basis_tree)
 
886
            self.open_workingtree().clone(result)
645
887
        except errors.NotLocalUrl:
646
888
            # make a new one, this format always has to have one.
647
889
            try:
656
898
        """See BzrDir.create_branch."""
657
899
        return self.open_branch()
658
900
 
 
901
    def destroy_branch(self):
 
902
        """See BzrDir.destroy_branch."""
 
903
        raise errors.UnsupportedOperation(self.destroy_branch, self)
 
904
 
659
905
    def create_repository(self, shared=False):
660
906
        """See BzrDir.create_repository."""
661
907
        if shared:
665
911
    def create_workingtree(self, revision_id=None):
666
912
        """See BzrDir.create_workingtree."""
667
913
        # this looks buggy but is not -really-
 
914
        # because this format creates the workingtree when the bzrdir is
 
915
        # created
668
916
        # clone and sprout will have set the revision_id
669
917
        # and that will have set it for us, its only
670
918
        # specific uses of create_workingtree in isolation
671
919
        # that can do wonky stuff here, and that only
672
920
        # happens for creating checkouts, which cannot be 
673
921
        # done on this format anyway. So - acceptable wart.
674
 
        result = self.open_workingtree()
 
922
        result = self.open_workingtree(recommend_upgrade=False)
675
923
        if revision_id is not None:
676
 
            result.set_last_revision(revision_id)
 
924
            if revision_id == _mod_revision.NULL_REVISION:
 
925
                result.set_parent_ids([])
 
926
            else:
 
927
                result.set_parent_ids([revision_id])
677
928
        return result
678
929
 
 
930
    def destroy_workingtree(self):
 
931
        """See BzrDir.destroy_workingtree."""
 
932
        raise errors.UnsupportedOperation(self.destroy_workingtree, self)
 
933
 
 
934
    def destroy_workingtree_metadata(self):
 
935
        """See BzrDir.destroy_workingtree_metadata."""
 
936
        raise errors.UnsupportedOperation(self.destroy_workingtree_metadata, 
 
937
                                          self)
 
938
 
679
939
    def get_branch_transport(self, branch_format):
680
940
        """See BzrDir.get_branch_transport()."""
681
941
        if branch_format is None:
721
981
        self._check_supported(format, unsupported)
722
982
        return format.open(self, _found=True)
723
983
 
724
 
    def sprout(self, url, revision_id=None, basis=None):
 
984
    def sprout(self, url, revision_id=None, force_new_repo=False,
 
985
               possible_transports=None):
725
986
        """See BzrDir.sprout()."""
726
987
        from bzrlib.workingtree import WorkingTreeFormat2
727
988
        self._make_tail(url)
728
989
        result = self._format._initialize_for_clone(url)
729
 
        basis_repo, basis_branch, basis_tree = self._get_basis_components(basis)
730
990
        try:
731
 
            self.open_repository().clone(result, revision_id=revision_id, basis=basis_repo)
 
991
            self.open_repository().clone(result, revision_id=revision_id)
732
992
        except errors.NoRepositoryPresent:
733
993
            pass
734
994
        try:
756
1016
 
757
1017
    def open_repository(self):
758
1018
        """See BzrDir.open_repository."""
759
 
        from bzrlib.repository import RepositoryFormat4
 
1019
        from bzrlib.repofmt.weaverepo import RepositoryFormat4
760
1020
        return RepositoryFormat4().open(self, _found=True)
761
1021
 
762
1022
 
768
1028
 
769
1029
    def open_repository(self):
770
1030
        """See BzrDir.open_repository."""
771
 
        from bzrlib.repository import RepositoryFormat5
 
1031
        from bzrlib.repofmt.weaverepo import RepositoryFormat5
772
1032
        return RepositoryFormat5().open(self, _found=True)
773
1033
 
774
 
    def open_workingtree(self, _unsupported=False):
 
1034
    def open_workingtree(self, _unsupported=False,
 
1035
            recommend_upgrade=True):
775
1036
        """See BzrDir.create_workingtree."""
776
1037
        from bzrlib.workingtree import WorkingTreeFormat2
777
 
        return WorkingTreeFormat2().open(self, _found=True)
 
1038
        wt_format = WorkingTreeFormat2()
 
1039
        # we don't warn here about upgrades; that ought to be handled for the
 
1040
        # bzrdir as a whole
 
1041
        return wt_format.open(self, _found=True)
778
1042
 
779
1043
 
780
1044
class BzrDir6(BzrDirPreSplitOut):
785
1049
 
786
1050
    def open_repository(self):
787
1051
        """See BzrDir.open_repository."""
788
 
        from bzrlib.repository import RepositoryFormat6
 
1052
        from bzrlib.repofmt.weaverepo import RepositoryFormat6
789
1053
        return RepositoryFormat6().open(self, _found=True)
790
1054
 
791
 
    def open_workingtree(self, _unsupported=False):
 
1055
    def open_workingtree(self, _unsupported=False,
 
1056
        recommend_upgrade=True):
792
1057
        """See BzrDir.create_workingtree."""
 
1058
        # we don't warn here about upgrades; that ought to be handled for the
 
1059
        # bzrdir as a whole
793
1060
        from bzrlib.workingtree import WorkingTreeFormat2
794
1061
        return WorkingTreeFormat2().open(self, _found=True)
795
1062
 
809
1076
 
810
1077
    def create_branch(self):
811
1078
        """See BzrDir.create_branch."""
812
 
        from bzrlib.branch import BranchFormat
813
 
        return BranchFormat.get_default_format().initialize(self)
 
1079
        return self._format.get_branch_format().initialize(self)
 
1080
 
 
1081
    def destroy_branch(self):
 
1082
        """See BzrDir.create_branch."""
 
1083
        self.transport.delete_tree('branch')
814
1084
 
815
1085
    def create_repository(self, shared=False):
816
1086
        """See BzrDir.create_repository."""
819
1089
    def create_workingtree(self, revision_id=None):
820
1090
        """See BzrDir.create_workingtree."""
821
1091
        from bzrlib.workingtree import WorkingTreeFormat
822
 
        return WorkingTreeFormat.get_default_format().initialize(self, revision_id)
 
1092
        return self._format.workingtree_format.initialize(self, revision_id)
 
1093
 
 
1094
    def destroy_workingtree(self):
 
1095
        """See BzrDir.destroy_workingtree."""
 
1096
        wt = self.open_workingtree(recommend_upgrade=False)
 
1097
        repository = wt.branch.repository
 
1098
        empty = repository.revision_tree(_mod_revision.NULL_REVISION)
 
1099
        wt.revert(old_tree=empty)
 
1100
        self.destroy_workingtree_metadata()
 
1101
 
 
1102
    def destroy_workingtree_metadata(self):
 
1103
        self.transport.delete_tree('checkout')
 
1104
 
 
1105
    def find_branch_format(self):
 
1106
        """Find the branch 'format' for this bzrdir.
 
1107
 
 
1108
        This might be a synthetic object for e.g. RemoteBranch and SVN.
 
1109
        """
 
1110
        from bzrlib.branch import BranchFormat
 
1111
        return BranchFormat.find_format(self)
823
1112
 
824
1113
    def _get_mkdir_mode(self):
825
1114
        """Figure out the mode to use when creating a bzrdir subdir."""
826
 
        temp_control = LockableFiles(self.transport, '', TransportLock)
 
1115
        temp_control = lockable_files.LockableFiles(self.transport, '',
 
1116
                                     lockable_files.TransportLock)
827
1117
        return temp_control._dir_mode
828
1118
 
 
1119
    def get_branch_reference(self):
 
1120
        """See BzrDir.get_branch_reference()."""
 
1121
        from bzrlib.branch import BranchFormat
 
1122
        format = BranchFormat.find_format(self)
 
1123
        return format.get_reference(self)
 
1124
 
829
1125
    def get_branch_transport(self, branch_format):
830
1126
        """See BzrDir.get_branch_transport()."""
831
1127
        if branch_format is None:
883
1179
                return True
884
1180
        except errors.NoRepositoryPresent:
885
1181
            pass
886
 
        # currently there are no other possible conversions for meta1 formats.
 
1182
        try:
 
1183
            if not isinstance(self.open_branch()._format,
 
1184
                              format.get_branch_format().__class__):
 
1185
                # the branch needs an upgrade.
 
1186
                return True
 
1187
        except errors.NotBranchError:
 
1188
            pass
 
1189
        try:
 
1190
            my_wt = self.open_workingtree(recommend_upgrade=False)
 
1191
            if not isinstance(my_wt._format,
 
1192
                              format.workingtree_format.__class__):
 
1193
                # the workingtree needs an upgrade.
 
1194
                return True
 
1195
        except (errors.NoWorkingTree, errors.NotLocalUrl):
 
1196
            pass
887
1197
        return False
888
1198
 
889
1199
    def open_branch(self, unsupported=False):
890
1200
        """See BzrDir.open_branch."""
891
 
        from bzrlib.branch import BranchFormat
892
 
        format = BranchFormat.find_format(self)
 
1201
        format = self.find_branch_format()
893
1202
        self._check_supported(format, unsupported)
894
1203
        return format.open(self, _found=True)
895
1204
 
900
1209
        self._check_supported(format, unsupported)
901
1210
        return format.open(self, _found=True)
902
1211
 
903
 
    def open_workingtree(self, unsupported=False):
 
1212
    def open_workingtree(self, unsupported=False,
 
1213
            recommend_upgrade=True):
904
1214
        """See BzrDir.open_workingtree."""
905
1215
        from bzrlib.workingtree import WorkingTreeFormat
906
1216
        format = WorkingTreeFormat.find_format(self)
907
 
        self._check_supported(format, unsupported)
 
1217
        self._check_supported(format, unsupported,
 
1218
            recommend_upgrade,
 
1219
            basedir=self.root_transport.base)
908
1220
        return format.open(self, _found=True)
909
1221
 
910
1222
 
931
1243
    _formats = {}
932
1244
    """The known formats."""
933
1245
 
 
1246
    _control_formats = []
 
1247
    """The registered control formats - .bzr, ....
 
1248
    
 
1249
    This is a list of BzrDirFormat objects.
 
1250
    """
 
1251
 
 
1252
    _control_server_formats = []
 
1253
    """The registered control server formats, e.g. RemoteBzrDirs.
 
1254
 
 
1255
    This is a list of BzrDirFormat objects.
 
1256
    """
 
1257
 
934
1258
    _lock_file_name = 'branch-lock'
935
1259
 
936
1260
    # _lock_class must be set in subclasses to the lock type, typ.
937
1261
    # TransportLock or LockDir
938
1262
 
939
1263
    @classmethod
940
 
    def find_format(klass, transport):
941
 
        """Return the format registered for URL."""
 
1264
    def find_format(klass, transport, _server_formats=True):
 
1265
        """Return the format present at transport."""
 
1266
        if _server_formats:
 
1267
            formats = klass._control_server_formats + klass._control_formats
 
1268
        else:
 
1269
            formats = klass._control_formats
 
1270
        for format in formats:
 
1271
            try:
 
1272
                return format.probe_transport(transport)
 
1273
            except errors.NotBranchError:
 
1274
                # this format does not find a control dir here.
 
1275
                pass
 
1276
        raise errors.NotBranchError(path=transport.base)
 
1277
 
 
1278
    @classmethod
 
1279
    def probe_transport(klass, transport):
 
1280
        """Return the .bzrdir style format present in a directory."""
942
1281
        try:
943
1282
            format_string = transport.get(".bzr/branch-format").read()
 
1283
        except errors.NoSuchFile:
 
1284
            raise errors.NotBranchError(path=transport.base)
 
1285
 
 
1286
        try:
944
1287
            return klass._formats[format_string]
945
 
        except errors.NoSuchFile:
946
 
            raise errors.NotBranchError(path=transport.base)
947
1288
        except KeyError:
948
 
            raise errors.UnknownFormatError(format_string)
 
1289
            raise errors.UnknownFormatError(format=format_string)
949
1290
 
950
1291
    @classmethod
951
1292
    def get_default_format(klass):
966
1307
        This returns a bzrlib.bzrdir.Converter object.
967
1308
 
968
1309
        This should return the best upgrader to step this format towards the
969
 
        current default format. In the case of plugins we can/shouold provide
 
1310
        current default format. In the case of plugins we can/should provide
970
1311
        some means for them to extend the range of returnable converters.
971
1312
 
972
 
        :param format: Optional format to override the default foramt of the 
 
1313
        :param format: Optional format to override the default format of the 
973
1314
                       library.
974
1315
        """
975
1316
        raise NotImplementedError(self.get_converter)
976
1317
 
977
 
    def initialize(self, url):
 
1318
    def initialize(self, url, possible_transports=None):
978
1319
        """Create a bzr control dir at this url and return an opened copy.
979
1320
        
980
1321
        Subclasses should typically override initialize_on_transport
981
1322
        instead of this method.
982
1323
        """
983
 
        return self.initialize_on_transport(get_transport(url))
 
1324
        return self.initialize_on_transport(get_transport(url,
 
1325
                                                          possible_transports))
984
1326
 
985
1327
    def initialize_on_transport(self, transport):
986
1328
        """Initialize a new bzrdir in the base directory of a Transport."""
987
 
        # Since we don'transport have a .bzr directory, inherit the
 
1329
        # Since we don't have a .bzr directory, inherit the
988
1330
        # mode from the root directory
989
 
        temp_control = LockableFiles(transport, '', TransportLock)
 
1331
        temp_control = lockable_files.LockableFiles(transport,
 
1332
                            '', lockable_files.TransportLock)
990
1333
        temp_control._transport.mkdir('.bzr',
991
 
                                      # FIXME: RBC 20060121 dont peek under
 
1334
                                      # FIXME: RBC 20060121 don't peek under
992
1335
                                      # the covers
993
1336
                                      mode=temp_control._dir_mode)
994
1337
        file_mode = temp_control._file_mode
1001
1344
                      ('branch-format', self.get_format_string()),
1002
1345
                      ]
1003
1346
        # NB: no need to escape relative paths that are url safe.
1004
 
        control_files = LockableFiles(control, self._lock_file_name, 
1005
 
                                      self._lock_class)
 
1347
        control_files = lockable_files.LockableFiles(control,
 
1348
                            self._lock_file_name, self._lock_class)
1006
1349
        control_files.create_lock()
1007
1350
        control_files.lock_write()
1008
1351
        try:
1021
1364
        """
1022
1365
        return True
1023
1366
 
 
1367
    def same_model(self, target_format):
 
1368
        return (self.repository_format.rich_root_data == 
 
1369
            target_format.rich_root_data)
 
1370
 
 
1371
    @classmethod
 
1372
    def known_formats(klass):
 
1373
        """Return all the known formats.
 
1374
        
 
1375
        Concrete formats should override _known_formats.
 
1376
        """
 
1377
        # There is double indirection here to make sure that control 
 
1378
        # formats used by more than one dir format will only be probed 
 
1379
        # once. This can otherwise be quite expensive for remote connections.
 
1380
        result = set()
 
1381
        for format in klass._control_formats:
 
1382
            result.update(format._known_formats())
 
1383
        return result
 
1384
    
 
1385
    @classmethod
 
1386
    def _known_formats(klass):
 
1387
        """Return the known format instances for this control format."""
 
1388
        return set(klass._formats.values())
 
1389
 
1024
1390
    def open(self, transport, _found=False):
1025
1391
        """Return an instance of this format for the dir transport points at.
1026
1392
        
1027
1393
        _found is a private parameter, do not use it.
1028
1394
        """
1029
1395
        if not _found:
1030
 
            assert isinstance(BzrDirFormat.find_format(transport),
1031
 
                              self.__class__)
 
1396
            found_format = BzrDirFormat.find_format(transport)
 
1397
            if not isinstance(found_format, self.__class__):
 
1398
                raise AssertionError("%s was asked to open %s, but it seems to need "
 
1399
                        "format %s" 
 
1400
                        % (self, transport, found_format))
1032
1401
        return self._open(transport)
1033
1402
 
1034
1403
    def _open(self, transport):
1044
1413
        klass._formats[format.get_format_string()] = format
1045
1414
 
1046
1415
    @classmethod
 
1416
    def register_control_format(klass, format):
 
1417
        """Register a format that does not use '.bzr' for its control dir.
 
1418
 
 
1419
        TODO: This should be pulled up into a 'ControlDirFormat' base class
 
1420
        which BzrDirFormat can inherit from, and renamed to register_format 
 
1421
        there. It has been done without that for now for simplicity of
 
1422
        implementation.
 
1423
        """
 
1424
        klass._control_formats.append(format)
 
1425
 
 
1426
    @classmethod
 
1427
    def register_control_server_format(klass, format):
 
1428
        """Register a control format for client-server environments.
 
1429
 
 
1430
        These formats will be tried before ones registered with
 
1431
        register_control_format.  This gives implementations that decide to the
 
1432
        chance to grab it before anything looks at the contents of the format
 
1433
        file.
 
1434
        """
 
1435
        klass._control_server_formats.append(format)
 
1436
 
 
1437
    @classmethod
 
1438
    @symbol_versioning.deprecated_method(symbol_versioning.zero_fourteen)
1047
1439
    def set_default_format(klass, format):
 
1440
        klass._set_default_format(format)
 
1441
 
 
1442
    @classmethod
 
1443
    def _set_default_format(klass, format):
 
1444
        """Set default format (for testing behavior of defaults only)"""
1048
1445
        klass._default_format = format
1049
1446
 
1050
1447
    def __str__(self):
1055
1452
        assert klass._formats[format.get_format_string()] is format
1056
1453
        del klass._formats[format.get_format_string()]
1057
1454
 
 
1455
    @classmethod
 
1456
    def unregister_control_format(klass, format):
 
1457
        klass._control_formats.remove(format)
 
1458
 
1058
1459
 
1059
1460
class BzrDirFormat4(BzrDirFormat):
1060
1461
    """Bzr dir format 4.
1069
1470
    removed in format 5; write support for this format has been removed.
1070
1471
    """
1071
1472
 
1072
 
    _lock_class = TransportLock
 
1473
    _lock_class = lockable_files.TransportLock
1073
1474
 
1074
1475
    def get_format_string(self):
1075
1476
        """See BzrDirFormat.get_format_string()."""
1103
1504
 
1104
1505
    def __return_repository_format(self):
1105
1506
        """Circular import protection."""
1106
 
        from bzrlib.repository import RepositoryFormat4
1107
 
        return RepositoryFormat4(self)
 
1507
        from bzrlib.repofmt.weaverepo import RepositoryFormat4
 
1508
        return RepositoryFormat4()
1108
1509
    repository_format = property(__return_repository_format)
1109
1510
 
1110
1511
 
1119
1520
       Unhashed stores in the repository.
1120
1521
    """
1121
1522
 
1122
 
    _lock_class = TransportLock
 
1523
    _lock_class = lockable_files.TransportLock
1123
1524
 
1124
1525
    def get_format_string(self):
1125
1526
        """See BzrDirFormat.get_format_string()."""
1143
1544
        Except when they are being cloned.
1144
1545
        """
1145
1546
        from bzrlib.branch import BzrBranchFormat4
1146
 
        from bzrlib.repository import RepositoryFormat5
 
1547
        from bzrlib.repofmt.weaverepo import RepositoryFormat5
1147
1548
        from bzrlib.workingtree import WorkingTreeFormat2
1148
1549
        result = (super(BzrDirFormat5, self).initialize_on_transport(transport))
1149
1550
        RepositoryFormat5().initialize(result, _internal=True)
1150
1551
        if not _cloning:
1151
 
            BzrBranchFormat4().initialize(result)
1152
 
            WorkingTreeFormat2().initialize(result)
 
1552
            branch = BzrBranchFormat4().initialize(result)
 
1553
            try:
 
1554
                WorkingTreeFormat2().initialize(result)
 
1555
            except errors.NotLocalUrl:
 
1556
                # Even though we can't access the working tree, we need to
 
1557
                # create its control files.
 
1558
                WorkingTreeFormat2().stub_initialize_remote(branch.control_files)
1153
1559
        return result
1154
1560
 
1155
1561
    def _open(self, transport):
1158
1564
 
1159
1565
    def __return_repository_format(self):
1160
1566
        """Circular import protection."""
1161
 
        from bzrlib.repository import RepositoryFormat5
1162
 
        return RepositoryFormat5(self)
 
1567
        from bzrlib.repofmt.weaverepo import RepositoryFormat5
 
1568
        return RepositoryFormat5()
1163
1569
    repository_format = property(__return_repository_format)
1164
1570
 
1165
1571
 
1173
1579
     - Format 6 repositories [always]
1174
1580
    """
1175
1581
 
1176
 
    _lock_class = TransportLock
 
1582
    _lock_class = lockable_files.TransportLock
1177
1583
 
1178
1584
    def get_format_string(self):
1179
1585
        """See BzrDirFormat.get_format_string()."""
1197
1603
        Except when they are being cloned.
1198
1604
        """
1199
1605
        from bzrlib.branch import BzrBranchFormat4
1200
 
        from bzrlib.repository import RepositoryFormat6
 
1606
        from bzrlib.repofmt.weaverepo import RepositoryFormat6
1201
1607
        from bzrlib.workingtree import WorkingTreeFormat2
1202
1608
        result = super(BzrDirFormat6, self).initialize_on_transport(transport)
1203
1609
        RepositoryFormat6().initialize(result, _internal=True)
1204
1610
        if not _cloning:
1205
 
            BzrBranchFormat4().initialize(result)
 
1611
            branch = BzrBranchFormat4().initialize(result)
1206
1612
            try:
1207
1613
                WorkingTreeFormat2().initialize(result)
1208
1614
            except errors.NotLocalUrl:
1209
 
                # emulate pre-check behaviour for working tree and silently 
1210
 
                # fail.
1211
 
                pass
 
1615
                # Even though we can't access the working tree, we need to
 
1616
                # create its control files.
 
1617
                WorkingTreeFormat2().stub_initialize_remote(branch.control_files)
1212
1618
        return result
1213
1619
 
1214
1620
    def _open(self, transport):
1217
1623
 
1218
1624
    def __return_repository_format(self):
1219
1625
        """Circular import protection."""
1220
 
        from bzrlib.repository import RepositoryFormat6
1221
 
        return RepositoryFormat6(self)
 
1626
        from bzrlib.repofmt.weaverepo import RepositoryFormat6
 
1627
        return RepositoryFormat6()
1222
1628
    repository_format = property(__return_repository_format)
1223
1629
 
1224
1630
 
1233
1639
     - Format 7 repositories [optional]
1234
1640
    """
1235
1641
 
1236
 
    _lock_class = LockDir
 
1642
    _lock_class = lockdir.LockDir
 
1643
 
 
1644
    def __init__(self):
 
1645
        self._workingtree_format = None
 
1646
        self._branch_format = None
 
1647
 
 
1648
    def __eq__(self, other):
 
1649
        if other.__class__ is not self.__class__:
 
1650
            return False
 
1651
        if other.repository_format != self.repository_format:
 
1652
            return False
 
1653
        if other.workingtree_format != self.workingtree_format:
 
1654
            return False
 
1655
        return True
 
1656
 
 
1657
    def __ne__(self, other):
 
1658
        return not self == other
 
1659
 
 
1660
    def get_branch_format(self):
 
1661
        if self._branch_format is None:
 
1662
            from bzrlib.branch import BranchFormat
 
1663
            self._branch_format = BranchFormat.get_default_format()
 
1664
        return self._branch_format
 
1665
 
 
1666
    def set_branch_format(self, format):
 
1667
        self._branch_format = format
1237
1668
 
1238
1669
    def get_converter(self, format=None):
1239
1670
        """See BzrDirFormat.get_converter()."""
1269
1700
 
1270
1701
    repository_format = property(__return_repository_format, __set_repository_format)
1271
1702
 
1272
 
 
 
1703
    def __get_workingtree_format(self):
 
1704
        if self._workingtree_format is None:
 
1705
            from bzrlib.workingtree import WorkingTreeFormat
 
1706
            self._workingtree_format = WorkingTreeFormat.get_default_format()
 
1707
        return self._workingtree_format
 
1708
 
 
1709
    def __set_workingtree_format(self, wt_format):
 
1710
        self._workingtree_format = wt_format
 
1711
 
 
1712
    workingtree_format = property(__get_workingtree_format,
 
1713
                                  __set_workingtree_format)
 
1714
 
 
1715
 
 
1716
# Register bzr control format
 
1717
BzrDirFormat.register_control_format(BzrDirFormat)
 
1718
 
 
1719
# Register bzr formats
1273
1720
BzrDirFormat.register_format(BzrDirFormat4())
1274
1721
BzrDirFormat.register_format(BzrDirFormat5())
1275
1722
BzrDirFormat.register_format(BzrDirFormat6())
1276
1723
__default_format = BzrDirMetaFormat1()
1277
1724
BzrDirFormat.register_format(__default_format)
1278
 
BzrDirFormat.set_default_format(__default_format)
1279
 
 
1280
 
 
1281
 
class BzrDirTestProviderAdapter(object):
1282
 
    """A tool to generate a suite testing multiple bzrdir formats at once.
1283
 
 
1284
 
    This is done by copying the test once for each transport and injecting
1285
 
    the transport_server, transport_readonly_server, and bzrdir_format
1286
 
    classes into each copy. Each copy is also given a new id() to make it
1287
 
    easy to identify.
1288
 
    """
1289
 
 
1290
 
    def __init__(self, transport_server, transport_readonly_server, formats):
1291
 
        self._transport_server = transport_server
1292
 
        self._transport_readonly_server = transport_readonly_server
1293
 
        self._formats = formats
1294
 
    
1295
 
    def adapt(self, test):
1296
 
        result = TestSuite()
1297
 
        for format in self._formats:
1298
 
            new_test = deepcopy(test)
1299
 
            new_test.transport_server = self._transport_server
1300
 
            new_test.transport_readonly_server = self._transport_readonly_server
1301
 
            new_test.bzrdir_format = format
1302
 
            def make_new_test_id():
1303
 
                new_id = "%s(%s)" % (new_test.id(), format.__class__.__name__)
1304
 
                return lambda: new_id
1305
 
            new_test.id = make_new_test_id()
1306
 
            result.addTest(new_test)
1307
 
        return result
1308
 
 
1309
 
 
1310
 
class ScratchDir(BzrDir6):
1311
 
    """Special test class: a bzrdir that cleans up itself..
1312
 
 
1313
 
    >>> d = ScratchDir()
1314
 
    >>> base = d.transport.base
1315
 
    >>> isdir(base)
1316
 
    True
1317
 
    >>> b.transport.__del__()
1318
 
    >>> isdir(base)
1319
 
    False
1320
 
    """
1321
 
 
1322
 
    def __init__(self, files=[], dirs=[], transport=None):
1323
 
        """Make a test branch.
1324
 
 
1325
 
        This creates a temporary directory and runs init-tree in it.
1326
 
 
1327
 
        If any files are listed, they are created in the working copy.
1328
 
        """
1329
 
        if transport is None:
1330
 
            transport = bzrlib.transport.local.ScratchTransport()
1331
 
            # local import for scope restriction
1332
 
            BzrDirFormat6().initialize(transport.base)
1333
 
            super(ScratchDir, self).__init__(transport, BzrDirFormat6())
1334
 
            self.create_repository()
1335
 
            self.create_branch()
1336
 
            self.create_workingtree()
1337
 
        else:
1338
 
            super(ScratchDir, self).__init__(transport, BzrDirFormat6())
1339
 
 
1340
 
        # BzrBranch creates a clone to .bzr and then forgets about the
1341
 
        # original transport. A ScratchTransport() deletes itself and
1342
 
        # everything underneath it when it goes away, so we need to
1343
 
        # grab a local copy to prevent that from happening
1344
 
        self._transport = transport
1345
 
 
1346
 
        for d in dirs:
1347
 
            self._transport.mkdir(d)
1348
 
            
1349
 
        for f in files:
1350
 
            self._transport.put(f, 'content of %s' % f)
1351
 
 
1352
 
    def clone(self):
1353
 
        """
1354
 
        >>> orig = ScratchDir(files=["file1", "file2"])
1355
 
        >>> os.listdir(orig.base)
1356
 
        [u'.bzr', u'file1', u'file2']
1357
 
        >>> clone = orig.clone()
1358
 
        >>> if os.name != 'nt':
1359
 
        ...   os.path.samefile(orig.base, clone.base)
1360
 
        ... else:
1361
 
        ...   orig.base == clone.base
1362
 
        ...
1363
 
        False
1364
 
        >>> os.listdir(clone.base)
1365
 
        [u'.bzr', u'file1', u'file2']
1366
 
        """
1367
 
        from shutil import copytree
1368
 
        from bzrlib.osutils import mkdtemp
1369
 
        base = mkdtemp()
1370
 
        os.rmdir(base)
1371
 
        copytree(self.base, base, symlinks=True)
1372
 
        return ScratchDir(
1373
 
            transport=bzrlib.transport.local.ScratchTransport(base))
 
1725
BzrDirFormat._default_format = __default_format
1374
1726
 
1375
1727
 
1376
1728
class Converter(object):
1463
1815
        self.bzrdir.transport.delete_tree('text-store')
1464
1816
 
1465
1817
    def _convert_working_inv(self):
1466
 
        inv = serializer_v4.read_inventory(self.branch.control_files.get('inventory'))
1467
 
        new_inv_xml = serializer_v5.write_inventory_to_string(inv)
 
1818
        inv = xml4.serializer_v4.read_inventory(
 
1819
                    self.branch.control_files.get('inventory'))
 
1820
        new_inv_xml = xml5.serializer_v5.write_inventory_to_string(inv, working=True)
1468
1821
        # FIXME inventory is a working tree change.
1469
 
        self.branch.control_files.put('inventory', new_inv_xml)
 
1822
        self.branch.control_files.put('inventory', StringIO(new_inv_xml))
1470
1823
 
1471
1824
    def _write_all_weaves(self):
1472
1825
        controlweaves = WeaveStore(self.bzrdir.transport, prefixed=False)
1496
1849
                                                      prefixed=False,
1497
1850
                                                      compressed=True))
1498
1851
        try:
1499
 
            transaction = bzrlib.transactions.WriteTransaction()
 
1852
            transaction = WriteTransaction()
1500
1853
            for i, rev_id in enumerate(self.converted_revs):
1501
1854
                self.pb.update('write revision', i, len(self.converted_revs))
1502
1855
                _revision_store.add_revision(self.revisions[rev_id], transaction)
1528
1881
    def _load_old_inventory(self, rev_id):
1529
1882
        assert rev_id not in self.converted_revs
1530
1883
        old_inv_xml = self.branch.repository.inventory_store.get(rev_id).read()
1531
 
        inv = serializer_v4.read_inventory_from_string(old_inv_xml)
 
1884
        inv = xml4.serializer_v4.read_inventory_from_string(old_inv_xml)
 
1885
        inv.revision_id = rev_id
1532
1886
        rev = self.revisions[rev_id]
1533
1887
        if rev.inventory_sha1:
1534
1888
            assert rev.inventory_sha1 == sha_string(old_inv_xml), \
1538
1892
    def _load_updated_inventory(self, rev_id):
1539
1893
        assert rev_id in self.converted_revs
1540
1894
        inv_xml = self.inv_weave.get_text(rev_id)
1541
 
        inv = serializer_v5.read_inventory_from_string(inv_xml)
 
1895
        inv = xml5.serializer_v5.read_inventory_from_string(inv_xml)
1542
1896
        return inv
1543
1897
 
1544
1898
    def _convert_one_rev(self, rev_id):
1548
1902
        present_parents = [p for p in rev.parent_ids
1549
1903
                           if p not in self.absent_revisions]
1550
1904
        self._convert_revision_contents(rev, inv, present_parents)
1551
 
        self._store_new_weave(rev, inv, present_parents)
 
1905
        self._store_new_inv(rev, inv, present_parents)
1552
1906
        self.converted_revs.add(rev_id)
1553
1907
 
1554
 
    def _store_new_weave(self, rev, inv, present_parents):
 
1908
    def _store_new_inv(self, rev, inv, present_parents):
1555
1909
        # the XML is now updated with text versions
1556
1910
        if __debug__:
1557
 
            for file_id in inv:
1558
 
                ie = inv[file_id]
1559
 
                if ie.kind == 'root_directory':
1560
 
                    continue
1561
 
                assert hasattr(ie, 'revision'), \
 
1911
            entries = inv.iter_entries()
 
1912
            entries.next()
 
1913
            for path, ie in entries:
 
1914
                assert getattr(ie, 'revision', None) is not None, \
1562
1915
                    'no revision on {%s} in {%s}' % \
1563
1916
                    (file_id, rev.revision_id)
1564
 
        new_inv_xml = serializer_v5.write_inventory_to_string(inv)
 
1917
        new_inv_xml = xml5.serializer_v5.write_inventory_to_string(inv)
1565
1918
        new_inv_sha1 = sha_string(new_inv_xml)
1566
 
        self.inv_weave.add_lines(rev.revision_id, 
 
1919
        self.inv_weave.add_lines(rev.revision_id,
1567
1920
                                 present_parents,
1568
1921
                                 new_inv_xml.splitlines(True))
1569
1922
        rev.inventory_sha1 = new_inv_sha1
1576
1929
        mutter('converting texts of revision {%s}',
1577
1930
               rev_id)
1578
1931
        parent_invs = map(self._load_updated_inventory, present_parents)
1579
 
        for file_id in inv:
1580
 
            ie = inv[file_id]
 
1932
        entries = inv.iter_entries()
 
1933
        entries.next()
 
1934
        for path, ie in entries:
1581
1935
            self._convert_file_version(rev, ie, parent_invs)
1582
1936
 
1583
1937
    def _convert_file_version(self, rev, ie, parent_invs):
1586
1940
        The file needs to be added into the weave if it is a merge
1587
1941
        of >=2 parents or if it's changed from its parent.
1588
1942
        """
1589
 
        if ie.kind == 'root_directory':
1590
 
            return
1591
1943
        file_id = ie.file_id
1592
1944
        rev_id = rev.revision_id
1593
1945
        w = self.text_weaves.get(file_id)
1595
1947
            w = Weave(file_id)
1596
1948
            self.text_weaves[file_id] = w
1597
1949
        text_changed = False
1598
 
        previous_entries = ie.find_previous_heads(parent_invs,
1599
 
                                                  None,
1600
 
                                                  None,
1601
 
                                                  entry_vf=w)
1602
 
        for old_revision in previous_entries:
1603
 
                # if this fails, its a ghost ?
1604
 
                assert old_revision in self.converted_revs 
 
1950
        parent_candiate_entries = ie.parent_candidates(parent_invs)
 
1951
        for old_revision in parent_candiate_entries.keys():
 
1952
            # if this fails, its a ghost ?
 
1953
            assert old_revision in self.converted_revs, \
 
1954
                "Revision {%s} not in converted_revs" % old_revision
 
1955
        heads = graph.Graph(self).heads(parent_candiate_entries.keys())
 
1956
        # XXX: Note that this is unordered - and this is tolerable because 
 
1957
        # the previous code was also unordered.
 
1958
        previous_entries = dict((head, parent_candiate_entries[head]) for head
 
1959
            in heads)
1605
1960
        self.snapshot_ie(previous_entries, ie, w, rev_id)
1606
1961
        del ie.text_id
1607
1962
        assert getattr(ie, 'revision', None) is not None
1608
1963
 
 
1964
    def get_parents(self, revision_ids):
 
1965
        for revision_id in revision_ids:
 
1966
            yield self.revisions[revision_id].parent_ids
 
1967
 
1609
1968
    def snapshot_ie(self, previous_revisions, ie, w, rev_id):
1610
1969
        # TODO: convert this logic, which is ~= snapshot to
1611
1970
        # a call to:. This needs the path figured out. rather than a work_tree
1620
1979
                ie.revision = previous_ie.revision
1621
1980
                return
1622
1981
        if ie.has_text():
1623
 
            text = self.branch.repository.text_store.get(ie.text_id)
 
1982
            text = self.branch.repository.weave_store.get(ie.text_id)
1624
1983
            file_lines = text.readlines()
1625
1984
            assert sha_strings(file_lines) == ie.text_sha1
1626
1985
            assert sum(map(len, file_lines)) == ie.text_size
1672
2031
            store_transport = self.bzrdir.transport.clone(store_name)
1673
2032
            store = TransportStore(store_transport, prefixed=True)
1674
2033
            for urlfilename in store_transport.list_dir('.'):
1675
 
                filename = urlunescape(urlfilename)
 
2034
                filename = urlutils.unescape(urlfilename)
1676
2035
                if (filename.endswith(".weave") or
1677
2036
                    filename.endswith(".gz") or
1678
2037
                    filename.endswith(".sig")):
1694
2053
 
1695
2054
    def convert(self, to_convert, pb):
1696
2055
        """See Converter.convert()."""
 
2056
        from bzrlib.repofmt.weaverepo import RepositoryFormat7
 
2057
        from bzrlib.branch import BzrBranchFormat5
1697
2058
        self.bzrdir = to_convert
1698
2059
        self.pb = pb
1699
2060
        self.count = 0
1728
2089
        # we hard code the formats here because we are converting into
1729
2090
        # the meta format. The meta format upgrader can take this to a 
1730
2091
        # future format within each component.
1731
 
        self.put_format('repository', bzrlib.repository.RepositoryFormat7())
 
2092
        self.put_format('repository', RepositoryFormat7())
1732
2093
        for entry in repository_names:
1733
2094
            self.move_entry('repository', entry)
1734
2095
 
1735
2096
        self.step('Upgrading branch      ')
1736
2097
        self.bzrdir.transport.mkdir('branch', mode=self.dir_mode)
1737
2098
        self.make_lock('branch')
1738
 
        self.put_format('branch', bzrlib.branch.BzrBranchFormat5())
 
2099
        self.put_format('branch', BzrBranchFormat5())
1739
2100
        branch_files = [('revision-history', True),
1740
2101
                        ('branch-name', True),
1741
2102
                        ('parent', False)]
1742
2103
        for entry in branch_files:
1743
2104
            self.move_entry('branch', entry)
1744
2105
 
1745
 
        self.step('Upgrading working tree')
1746
 
        self.bzrdir.transport.mkdir('checkout', mode=self.dir_mode)
1747
 
        self.make_lock('checkout')
1748
 
        self.put_format('checkout', bzrlib.workingtree.WorkingTreeFormat3())
1749
 
        self.bzrdir.transport.delete_multi(self.garbage_inventories, self.pb)
1750
2106
        checkout_files = [('pending-merges', True),
1751
2107
                          ('inventory', True),
1752
2108
                          ('stat-cache', False)]
1753
 
        for entry in checkout_files:
1754
 
            self.move_entry('checkout', entry)
1755
 
        if last_revision is not None:
1756
 
            self.bzrdir._control_files.put_utf8('checkout/last-revision',
1757
 
                                                last_revision)
1758
 
        self.bzrdir._control_files.put_utf8('branch-format', BzrDirMetaFormat1().get_format_string())
 
2109
        # If a mandatory checkout file is not present, the branch does not have
 
2110
        # a functional checkout. Do not create a checkout in the converted
 
2111
        # branch.
 
2112
        for name, mandatory in checkout_files:
 
2113
            if mandatory and name not in bzrcontents:
 
2114
                has_checkout = False
 
2115
                break
 
2116
        else:
 
2117
            has_checkout = True
 
2118
        if not has_checkout:
 
2119
            self.pb.note('No working tree.')
 
2120
            # If some checkout files are there, we may as well get rid of them.
 
2121
            for name, mandatory in checkout_files:
 
2122
                if name in bzrcontents:
 
2123
                    self.bzrdir.transport.delete(name)
 
2124
        else:
 
2125
            from bzrlib.workingtree import WorkingTreeFormat3
 
2126
            self.step('Upgrading working tree')
 
2127
            self.bzrdir.transport.mkdir('checkout', mode=self.dir_mode)
 
2128
            self.make_lock('checkout')
 
2129
            self.put_format(
 
2130
                'checkout', WorkingTreeFormat3())
 
2131
            self.bzrdir.transport.delete_multi(
 
2132
                self.garbage_inventories, self.pb)
 
2133
            for entry in checkout_files:
 
2134
                self.move_entry('checkout', entry)
 
2135
            if last_revision is not None:
 
2136
                self.bzrdir._control_files.put_utf8(
 
2137
                    'checkout/last-revision', last_revision)
 
2138
        self.bzrdir._control_files.put_utf8(
 
2139
            'branch-format', BzrDirMetaFormat1().get_format_string())
1759
2140
        return BzrDir.open(self.bzrdir.root_transport.base)
1760
2141
 
1761
2142
    def make_lock(self, name):
1762
2143
        """Make a lock for the new control dir name."""
1763
2144
        self.step('Make %s lock' % name)
1764
 
        ld = LockDir(self.bzrdir.transport, 
1765
 
                     '%s/lock' % name,
1766
 
                     file_modebits=self.file_mode,
1767
 
                     dir_modebits=self.dir_mode)
 
2145
        ld = lockdir.LockDir(self.bzrdir.transport,
 
2146
                             '%s/lock' % name,
 
2147
                             file_modebits=self.file_mode,
 
2148
                             dir_modebits=self.dir_mode)
1768
2149
        ld.create()
1769
2150
 
1770
2151
    def move_entry(self, new_dir, entry):
1809
2190
                self.pb.note('starting repository conversion')
1810
2191
                converter = CopyConverter(self.target_format.repository_format)
1811
2192
                converter.convert(repo, pb)
 
2193
        try:
 
2194
            branch = self.bzrdir.open_branch()
 
2195
        except errors.NotBranchError:
 
2196
            pass
 
2197
        else:
 
2198
            # TODO: conversions of Branch and Tree should be done by
 
2199
            # InterXFormat lookups
 
2200
            # Avoid circular imports
 
2201
            from bzrlib import branch as _mod_branch
 
2202
            if (branch._format.__class__ is _mod_branch.BzrBranchFormat5 and
 
2203
                self.target_format.get_branch_format().__class__ is
 
2204
                _mod_branch.BzrBranchFormat6):
 
2205
                branch_converter = _mod_branch.Converter5to6()
 
2206
                branch_converter.convert(branch)
 
2207
        try:
 
2208
            tree = self.bzrdir.open_workingtree(recommend_upgrade=False)
 
2209
        except (errors.NoWorkingTree, errors.NotLocalUrl):
 
2210
            pass
 
2211
        else:
 
2212
            # TODO: conversions of Branch and Tree should be done by
 
2213
            # InterXFormat lookups
 
2214
            if (isinstance(tree, workingtree.WorkingTree3) and
 
2215
                not isinstance(tree, workingtree_4.WorkingTree4) and
 
2216
                isinstance(self.target_format.workingtree_format,
 
2217
                    workingtree_4.WorkingTreeFormat4)):
 
2218
                workingtree_4.Converter3to4().convert(tree)
1812
2219
        return to_convert
 
2220
 
 
2221
 
 
2222
# This is not in remote.py because it's small, and needs to be registered.
 
2223
# Putting it in remote.py creates a circular import problem.
 
2224
# we can make it a lazy object if the control formats is turned into something
 
2225
# like a registry.
 
2226
class RemoteBzrDirFormat(BzrDirMetaFormat1):
 
2227
    """Format representing bzrdirs accessed via a smart server"""
 
2228
 
 
2229
    def get_format_description(self):
 
2230
        return 'bzr remote bzrdir'
 
2231
    
 
2232
    @classmethod
 
2233
    def probe_transport(klass, transport):
 
2234
        """Return a RemoteBzrDirFormat object if it looks possible."""
 
2235
        try:
 
2236
            client = transport.get_smart_client()
 
2237
        except (NotImplementedError, AttributeError,
 
2238
                errors.TransportNotPossible):
 
2239
            # no smart server, so not a branch for this format type.
 
2240
            raise errors.NotBranchError(path=transport.base)
 
2241
        else:
 
2242
            # Send a 'hello' request in protocol version one, and decline to
 
2243
            # open it if the server doesn't support our required version (2) so
 
2244
            # that the VFS-based transport will do it.
 
2245
            request = client.get_request()
 
2246
            smart_protocol = protocol.SmartClientRequestProtocolOne(request)
 
2247
            server_version = smart_protocol.query_version()
 
2248
            if server_version != 2:
 
2249
                raise errors.NotBranchError(path=transport.base)
 
2250
            return klass()
 
2251
 
 
2252
    def initialize_on_transport(self, transport):
 
2253
        try:
 
2254
            # hand off the request to the smart server
 
2255
            shared_medium = transport.get_shared_medium()
 
2256
        except errors.NoSmartMedium:
 
2257
            # TODO: lookup the local format from a server hint.
 
2258
            local_dir_format = BzrDirMetaFormat1()
 
2259
            return local_dir_format.initialize_on_transport(transport)
 
2260
        client = _SmartClient(shared_medium)
 
2261
        path = client.remote_path_from_transport(transport)
 
2262
        response = _SmartClient(shared_medium).call('BzrDirFormat.initialize',
 
2263
                                                    path)
 
2264
        assert response[0] in ('ok', ), 'unexpected response code %s' % (response,)
 
2265
        return remote.RemoteBzrDir(transport)
 
2266
 
 
2267
    def _open(self, transport):
 
2268
        return remote.RemoteBzrDir(transport)
 
2269
 
 
2270
    def __eq__(self, other):
 
2271
        if not isinstance(other, RemoteBzrDirFormat):
 
2272
            return False
 
2273
        return self.get_format_description() == other.get_format_description()
 
2274
 
 
2275
 
 
2276
BzrDirFormat.register_control_server_format(RemoteBzrDirFormat)
 
2277
 
 
2278
 
 
2279
class BzrDirFormatInfo(object):
 
2280
 
 
2281
    def __init__(self, native, deprecated, hidden):
 
2282
        self.deprecated = deprecated
 
2283
        self.native = native
 
2284
        self.hidden = hidden
 
2285
 
 
2286
 
 
2287
class BzrDirFormatRegistry(registry.Registry):
 
2288
    """Registry of user-selectable BzrDir subformats.
 
2289
    
 
2290
    Differs from BzrDirFormat._control_formats in that it provides sub-formats,
 
2291
    e.g. BzrDirMeta1 with weave repository.  Also, it's more user-oriented.
 
2292
    """
 
2293
 
 
2294
    def register_metadir(self, key,
 
2295
             repository_format, help, native=True, deprecated=False,
 
2296
             branch_format=None,
 
2297
             tree_format=None,
 
2298
             hidden=False):
 
2299
        """Register a metadir subformat.
 
2300
 
 
2301
        These all use a BzrDirMetaFormat1 bzrdir, but can be parameterized
 
2302
        by the Repository format.
 
2303
 
 
2304
        :param repository_format: The fully-qualified repository format class
 
2305
            name as a string.
 
2306
        :param branch_format: Fully-qualified branch format class name as
 
2307
            a string.
 
2308
        :param tree_format: Fully-qualified tree format class name as
 
2309
            a string.
 
2310
        """
 
2311
        # This should be expanded to support setting WorkingTree and Branch
 
2312
        # formats, once BzrDirMetaFormat1 supports that.
 
2313
        def _load(full_name):
 
2314
            mod_name, factory_name = full_name.rsplit('.', 1)
 
2315
            try:
 
2316
                mod = __import__(mod_name, globals(), locals(),
 
2317
                        [factory_name])
 
2318
            except ImportError, e:
 
2319
                raise ImportError('failed to load %s: %s' % (full_name, e))
 
2320
            try:
 
2321
                factory = getattr(mod, factory_name)
 
2322
            except AttributeError:
 
2323
                raise AttributeError('no factory %s in module %r'
 
2324
                    % (full_name, mod))
 
2325
            return factory()
 
2326
 
 
2327
        def helper():
 
2328
            bd = BzrDirMetaFormat1()
 
2329
            if branch_format is not None:
 
2330
                bd.set_branch_format(_load(branch_format))
 
2331
            if tree_format is not None:
 
2332
                bd.workingtree_format = _load(tree_format)
 
2333
            if repository_format is not None:
 
2334
                bd.repository_format = _load(repository_format)
 
2335
            return bd
 
2336
        self.register(key, helper, help, native, deprecated, hidden)
 
2337
 
 
2338
    def register(self, key, factory, help, native=True, deprecated=False,
 
2339
                 hidden=False):
 
2340
        """Register a BzrDirFormat factory.
 
2341
        
 
2342
        The factory must be a callable that takes one parameter: the key.
 
2343
        It must produce an instance of the BzrDirFormat when called.
 
2344
 
 
2345
        This function mainly exists to prevent the info object from being
 
2346
        supplied directly.
 
2347
        """
 
2348
        registry.Registry.register(self, key, factory, help, 
 
2349
            BzrDirFormatInfo(native, deprecated, hidden))
 
2350
 
 
2351
    def register_lazy(self, key, module_name, member_name, help, native=True,
 
2352
                      deprecated=False, hidden=False):
 
2353
        registry.Registry.register_lazy(self, key, module_name, member_name, 
 
2354
            help, BzrDirFormatInfo(native, deprecated, hidden))
 
2355
 
 
2356
    def set_default(self, key):
 
2357
        """Set the 'default' key to be a clone of the supplied key.
 
2358
        
 
2359
        This method must be called once and only once.
 
2360
        """
 
2361
        registry.Registry.register(self, 'default', self.get(key), 
 
2362
            self.get_help(key), info=self.get_info(key))
 
2363
 
 
2364
    def set_default_repository(self, key):
 
2365
        """Set the FormatRegistry default and Repository default.
 
2366
        
 
2367
        This is a transitional method while Repository.set_default_format
 
2368
        is deprecated.
 
2369
        """
 
2370
        if 'default' in self:
 
2371
            self.remove('default')
 
2372
        self.set_default(key)
 
2373
        format = self.get('default')()
 
2374
        assert isinstance(format, BzrDirMetaFormat1)
 
2375
 
 
2376
    def make_bzrdir(self, key):
 
2377
        return self.get(key)()
 
2378
 
 
2379
    def help_topic(self, topic):
 
2380
        output = textwrap.dedent("""\
 
2381
            These formats can be used for creating branches, working trees, and
 
2382
            repositories.
 
2383
 
 
2384
            """)
 
2385
        default_realkey = None
 
2386
        default_help = self.get_help('default')
 
2387
        help_pairs = []
 
2388
        for key in self.keys():
 
2389
            if key == 'default':
 
2390
                continue
 
2391
            help = self.get_help(key)
 
2392
            if help == default_help:
 
2393
                default_realkey = key
 
2394
            else:
 
2395
                help_pairs.append((key, help))
 
2396
 
 
2397
        def wrapped(key, help, info):
 
2398
            if info.native:
 
2399
                help = '(native) ' + help
 
2400
            return ':%s:\n%s\n\n' % (key, 
 
2401
                    textwrap.fill(help, initial_indent='    ', 
 
2402
                    subsequent_indent='    '))
 
2403
        if default_realkey is not None:
 
2404
            output += wrapped(default_realkey, '(default) %s' % default_help,
 
2405
                              self.get_info('default'))
 
2406
        deprecated_pairs = []
 
2407
        for key, help in help_pairs:
 
2408
            info = self.get_info(key)
 
2409
            if info.hidden:
 
2410
                continue
 
2411
            elif info.deprecated:
 
2412
                deprecated_pairs.append((key, help))
 
2413
            else:
 
2414
                output += wrapped(key, help, info)
 
2415
        if len(deprecated_pairs) > 0:
 
2416
            output += "Deprecated formats are shown below.\n\n"
 
2417
            for key, help in deprecated_pairs:
 
2418
                info = self.get_info(key)
 
2419
                output += wrapped(key, help, info)
 
2420
 
 
2421
        return output
 
2422
 
 
2423
 
 
2424
format_registry = BzrDirFormatRegistry()
 
2425
format_registry.register('weave', BzrDirFormat6,
 
2426
    'Pre-0.8 format.  Slower than knit and does not'
 
2427
    ' support checkouts or shared repositories.',
 
2428
    deprecated=True)
 
2429
format_registry.register_metadir('knit',
 
2430
    'bzrlib.repofmt.knitrepo.RepositoryFormatKnit1',
 
2431
    'Format using knits.  Recommended for interoperation with bzr <= 0.14.',
 
2432
    branch_format='bzrlib.branch.BzrBranchFormat5',
 
2433
    tree_format='bzrlib.workingtree.WorkingTreeFormat3')
 
2434
format_registry.register_metadir('metaweave',
 
2435
    'bzrlib.repofmt.weaverepo.RepositoryFormat7',
 
2436
    'Transitional format in 0.8.  Slower than knit.',
 
2437
    branch_format='bzrlib.branch.BzrBranchFormat5',
 
2438
    tree_format='bzrlib.workingtree.WorkingTreeFormat3',
 
2439
    deprecated=True)
 
2440
format_registry.register_metadir('dirstate',
 
2441
    'bzrlib.repofmt.knitrepo.RepositoryFormatKnit1',
 
2442
    help='New in 0.15: Fast local operations. Compatible with bzr 0.8 and '
 
2443
        'above when accessed over the network.',
 
2444
    branch_format='bzrlib.branch.BzrBranchFormat5',
 
2445
    # this uses bzrlib.workingtree.WorkingTreeFormat4 because importing
 
2446
    # directly from workingtree_4 triggers a circular import.
 
2447
    tree_format='bzrlib.workingtree.WorkingTreeFormat4',
 
2448
    )
 
2449
format_registry.register_metadir('dirstate-tags',
 
2450
    'bzrlib.repofmt.knitrepo.RepositoryFormatKnit1',
 
2451
    help='New in 0.15: Fast local operations and improved scaling for '
 
2452
        'network operations. Additionally adds support for tags.'
 
2453
        ' Incompatible with bzr < 0.15.',
 
2454
    branch_format='bzrlib.branch.BzrBranchFormat6',
 
2455
    tree_format='bzrlib.workingtree.WorkingTreeFormat4',
 
2456
    )
 
2457
format_registry.register_metadir('dirstate-with-subtree',
 
2458
    'bzrlib.repofmt.knitrepo.RepositoryFormatKnit3',
 
2459
    help='New in 0.15: Fast local operations and improved scaling for '
 
2460
        'network operations. Additionally adds support for versioning nested '
 
2461
        'bzr branches. Incompatible with bzr < 0.15.',
 
2462
    branch_format='bzrlib.branch.BzrBranchFormat6',
 
2463
    tree_format='bzrlib.workingtree.WorkingTreeFormat4',
 
2464
    hidden=True,
 
2465
    )
 
2466
format_registry.set_default('dirstate-tags')