/brz/remove-bazaar

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

« back to all changes in this revision

Viewing changes to bzrlib/bzrdir.py

  • Committer: John Arbash Meinel
  • Date: 2007-05-02 14:36:55 UTC
  • mto: (2476.3.1 111702)
  • mto: This revision was merged to the branch mainline in revision 2479.
  • Revision ID: john@arbash-meinel.com-20070502143655-id25373m3lgue8ke
Add Transport.ensure_base()

Show diffs side-by-side

added added

removed removed

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