/brz/remove-bazaar

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

« back to all changes in this revision

Viewing changes to bzrlib/bzrdir.py

  • Committer: Andrew Bennetts
  • Date: 2006-11-21 08:16:46 UTC
  • mfrom: (2145 +trunk)
  • mto: (2018.8.1 split smart)
  • mto: This revision was merged to the branch mainline in revision 2435.
  • Revision ID: andrew.bennetts@canonical.com-20061121081646-ef6a49ad44bf2f9b
Merge from bzr.dev.

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