~bzr-pqm/bzr/bzr.dev

« back to all changes in this revision

Viewing changes to bzrlib/bzrdir.py

  • Committer: Robert Collins
  • Date: 2007-03-01 05:02:47 UTC
  • mto: (2255.11.3 dirstate)
  • mto: This revision was merged to the branch mainline in revision 2322.
  • Revision ID: robertc@robertcollins.net-20070301050247-ufh99m2ze45d7mol
Whitespace fix.

Show diffs side-by-side

added added

removed removed

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