/brz/remove-bazaar

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

« back to all changes in this revision

Viewing changes to bzrlib/bzrdir.py

  • Committer: Aaron Bentley
  • Date: 2007-12-21 20:48:57 UTC
  • mto: This revision was merged to the branch mainline in revision 3143.
  • Revision ID: abentley@panoramicfeedback.com-20071221204857-r9pxxwx34iuyt46d
Update NEWS

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