/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

Implement RemoteRepository.lock_write/unlock to expect and send tokens over the
smart protocol as appropriate, so that locking operations on RemoteRepositories
work correctly.

Show diffs side-by-side

added added

removed removed

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