1
# Copyright (C) 2005, 2006, 2007 Canonical Ltd
 
 
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.
 
 
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.
 
 
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
 
 
17
"""BzrDir logic. The BzrDir is the basic control directory used by bzr.
 
 
19
At format 7 this was split out into Branch, Repository and Checkout control
 
 
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
 
 
28
# TODO: Move old formats into a plugin to make this file smaller.
 
 
30
from cStringIO import StringIO
 
 
34
from bzrlib.lazy_import import lazy_import
 
 
35
lazy_import(globals(), """
 
 
36
from stat import S_ISDIR
 
 
38
from warnings import warn
 
 
48
    revision as _mod_revision,
 
 
58
from bzrlib.osutils import (
 
 
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,
 
 
72
from bzrlib.weave import Weave
 
 
75
from bzrlib.trace import (
 
 
79
from bzrlib.transport.local import LocalTransport
 
 
80
from bzrlib.symbol_versioning import (
 
 
88
    """A .bzr control diretory.
 
 
90
    BzrDir instances let you create or open any of the things that can be
 
 
91
    found within .bzr - checkouts, branches and repositories.
 
 
94
        the transport which this bzr dir is rooted at (i.e. file:///.../.bzr/)
 
 
96
        a transport connected to the directory this bzr was opened from
 
 
97
        (i.e. the parent directory holding the .bzr directory).
 
 
100
    def break_lock(self):
 
 
101
        """Invoke break_lock on the first object in the bzrdir.
 
 
103
        If there is a tree, the tree is opened and break_lock() called.
 
 
104
        Otherwise, branch is tried, and finally repository.
 
 
106
        # XXX: This seems more like a UI function than something that really
 
 
107
        # belongs in this class.
 
 
109
            thing_to_unlock = self.open_workingtree()
 
 
110
        except (errors.NotLocalUrl, errors.NoWorkingTree):
 
 
112
                thing_to_unlock = self.open_branch()
 
 
113
            except errors.NotBranchError:
 
 
115
                    thing_to_unlock = self.open_repository()
 
 
116
                except errors.NoRepositoryPresent:
 
 
118
        thing_to_unlock.break_lock()
 
 
120
    def can_convert_format(self):
 
 
121
        """Return true if this bzrdir is one whose format we can convert from."""
 
 
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)
 
 
130
    def _check_supported(format, allow_unsupported,
 
 
131
        recommend_upgrade=True,
 
 
133
        """Give an error or warning on old formats.
 
 
135
        :param format: may be any kind of format - workingtree, branch, 
 
 
138
        :param allow_unsupported: If true, allow opening 
 
 
139
        formats that are strongly deprecated, and which may 
 
 
140
        have limited functionality.
 
 
142
        :param recommend_upgrade: If true (default), warn
 
 
143
        the user through the ui object that they may wish
 
 
144
        to upgrade the object.
 
 
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(),
 
 
157
    def clone(self, url, revision_id=None, force_new_repo=False):
 
 
158
        """Clone this bzrdir and its contents to url verbatim.
 
 
160
        If url's last component does not exist, it will be created.
 
 
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.
 
 
167
        return self.clone_on_transport(get_transport(url),
 
 
168
                                       revision_id=revision_id,
 
 
169
                                       force_new_repo=force_new_repo)
 
 
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.
 
 
175
        If the target directory does not exist, it will be created.
 
 
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.
 
 
182
        transport.ensure_base()
 
 
183
        result = self.cloning_metadir().initialize_on_transport(transport)
 
 
184
        repository_policy = None
 
 
186
            local_repo = self.find_repository()
 
 
187
        except errors.NoRepositoryPresent:
 
 
190
            # may need to copy content in
 
 
191
            repository_policy = result.determine_repository_policy(
 
 
193
            make_working_trees = local_repo.make_working_trees()
 
 
194
            result_repo = repository_policy.acquire_repository(
 
 
195
                make_working_trees, local_repo.is_shared())
 
 
196
            result_repo.fetch(local_repo, revision_id=revision_id)
 
 
197
        # 1 if there is a branch present
 
 
198
        #   make sure its content is available in the target repository
 
 
201
            local_branch = self.open_branch()
 
 
202
        except errors.NotBranchError:
 
 
205
            result_branch = local_branch.clone(result, revision_id=revision_id)
 
 
206
            if repository_policy is not None:
 
 
207
                repository_policy.configure_branch(result_branch)
 
 
209
            result_repo = result.find_repository()
 
 
210
        except errors.NoRepositoryPresent:
 
 
212
        if result_repo is None or result_repo.make_working_trees():
 
 
214
                self.open_workingtree().clone(result)
 
 
215
            except (errors.NoWorkingTree, errors.NotLocalUrl):
 
 
219
    # TODO: This should be given a Transport, and should chdir up; otherwise
 
 
220
    # this will open a new connection.
 
 
221
    def _make_tail(self, url):
 
 
222
        t = get_transport(url)
 
 
226
    def create(cls, base, format=None, possible_transports=None):
 
 
227
        """Create a new BzrDir at the url 'base'.
 
 
229
        :param format: If supplied, the format of branch to create.  If not
 
 
230
            supplied, the default is used.
 
 
231
        :param possible_transports: If supplied, a list of transports that 
 
 
232
            can be reused to share a remote connection.
 
 
234
        if cls is not BzrDir:
 
 
235
            raise AssertionError("BzrDir.create always creates the default"
 
 
236
                " format, not one of %r" % cls)
 
 
237
        t = get_transport(base, possible_transports)
 
 
240
            format = BzrDirFormat.get_default_format()
 
 
241
        return format.initialize_on_transport(t)
 
 
244
    def find_bzrdirs(transport, evaluate=None, list_current=None):
 
 
245
        """Find bzrdirs recursively from current location.
 
 
247
        This is intended primarily as a building block for more sophisticated
 
 
248
        functionality, like finding trees under a directory, or finding
 
 
249
        branches that use a given repository.
 
 
250
        :param evaluate: An optional callable that yields recurse, value,
 
 
251
            where recurse controls whether this bzrdir is recursed into
 
 
252
            and value is the value to yield.  By default, all bzrdirs
 
 
253
            are recursed into, and the return value is the bzrdir.
 
 
254
        :param list_current: if supplied, use this function to list the current
 
 
255
            directory, instead of Transport.list_dir
 
 
256
        :return: a generator of found bzrdirs, or whatever evaluate returns.
 
 
258
        if list_current is None:
 
 
259
            def list_current(transport):
 
 
260
                return transport.list_dir('')
 
 
262
            def evaluate(bzrdir):
 
 
265
        pending = [transport]
 
 
266
        while len(pending) > 0:
 
 
267
            current_transport = pending.pop()
 
 
270
                bzrdir = BzrDir.open_from_transport(current_transport)
 
 
271
            except errors.NotBranchError:
 
 
274
                recurse, value = evaluate(bzrdir)
 
 
277
                subdirs = list_current(current_transport)
 
 
278
            except errors.NoSuchFile:
 
 
281
                for subdir in sorted(subdirs, reverse=True):
 
 
282
                    pending.append(current_transport.clone(subdir))
 
 
285
    def find_branches(transport):
 
 
286
        """Find all branches under a transport.
 
 
288
        This will find all branches below the transport, including branches
 
 
289
        inside other branches.  Where possible, it will use
 
 
290
        Repository.find_branches.
 
 
292
        To list all the branches that use a particular Repository, see
 
 
293
        Repository.find_branches
 
 
295
        def evaluate(bzrdir):
 
 
297
                repository = bzrdir.open_repository()
 
 
298
            except errors.NoRepositoryPresent:
 
 
301
                return False, (None, repository)
 
 
303
                branch = bzrdir.open_branch()
 
 
304
            except errors.NotBranchError:
 
 
305
                return True, (None, None)
 
 
307
                return True, (branch, None)
 
 
309
        for branch, repo in BzrDir.find_bzrdirs(transport, evaluate=evaluate):
 
 
311
                branches.extend(repo.find_branches())
 
 
312
            if branch is not None:
 
 
313
                branches.append(branch)
 
 
317
    def destroy_repository(self):
 
 
318
        """Destroy the repository in this BzrDir"""
 
 
319
        raise NotImplementedError(self.destroy_repository)
 
 
321
    def create_branch(self):
 
 
322
        """Create a branch in this BzrDir.
 
 
324
        The bzrdir's format will control what branch format is created.
 
 
325
        For more control see BranchFormatXX.create(a_bzrdir).
 
 
327
        raise NotImplementedError(self.create_branch)
 
 
329
    def destroy_branch(self):
 
 
330
        """Destroy the branch in this BzrDir"""
 
 
331
        raise NotImplementedError(self.destroy_branch)
 
 
334
    def create_branch_and_repo(base, force_new_repo=False, format=None):
 
 
335
        """Create a new BzrDir, Branch and Repository at the url 'base'.
 
 
337
        This will use the current default BzrDirFormat unless one is
 
 
338
        specified, and use whatever 
 
 
339
        repository format that that uses via bzrdir.create_branch and
 
 
340
        create_repository. If a shared repository is available that is used
 
 
343
        The created Branch object is returned.
 
 
345
        :param base: The URL to create the branch at.
 
 
346
        :param force_new_repo: If True a new repository is always created.
 
 
347
        :param format: If supplied, the format of branch to create.  If not
 
 
348
            supplied, the default is used.
 
 
350
        bzrdir = BzrDir.create(base, format)
 
 
351
        bzrdir._find_or_create_repository(force_new_repo)
 
 
352
        return bzrdir.create_branch()
 
 
354
    def determine_repository_policy(self, force_new_repo=False):
 
 
355
        """Return an object representing a policy to use.
 
 
357
        This controls whether a new repository is created, or a shared
 
 
358
        repository used instead.
 
 
360
        def repository_policy(found_bzrdir):
 
 
362
            # does it have a repository ?
 
 
364
                repository = found_bzrdir.open_repository()
 
 
365
            except errors.NoRepositoryPresent:
 
 
368
                if ((found_bzrdir.root_transport.base !=
 
 
369
                     self.root_transport.base) and not repository.is_shared()):
 
 
376
                return UseExistingRepository(repository), True
 
 
378
                return CreateRepository(self), True
 
 
380
        if not force_new_repo:
 
 
381
            policy = self._find_containing(repository_policy)
 
 
382
            if policy is not None:
 
 
384
        return CreateRepository(self)
 
 
386
    def _find_or_create_repository(self, force_new_repo):
 
 
387
        """Create a new repository if needed, returning the repository."""
 
 
388
        policy = self.determine_repository_policy(force_new_repo)
 
 
389
        return policy.acquire_repository()
 
 
392
    def create_branch_convenience(base, force_new_repo=False,
 
 
393
                                  force_new_tree=None, format=None,
 
 
394
                                  possible_transports=None):
 
 
395
        """Create a new BzrDir, Branch and Repository at the url 'base'.
 
 
397
        This is a convenience function - it will use an existing repository
 
 
398
        if possible, can be told explicitly whether to create a working tree or
 
 
401
        This will use the current default BzrDirFormat unless one is
 
 
402
        specified, and use whatever 
 
 
403
        repository format that that uses via bzrdir.create_branch and
 
 
404
        create_repository. If a shared repository is available that is used
 
 
405
        preferentially. Whatever repository is used, its tree creation policy
 
 
408
        The created Branch object is returned.
 
 
409
        If a working tree cannot be made due to base not being a file:// url,
 
 
410
        no error is raised unless force_new_tree is True, in which case no 
 
 
411
        data is created on disk and NotLocalUrl is raised.
 
 
413
        :param base: The URL to create the branch at.
 
 
414
        :param force_new_repo: If True a new repository is always created.
 
 
415
        :param force_new_tree: If True or False force creation of a tree or 
 
 
416
                               prevent such creation respectively.
 
 
417
        :param format: Override for the bzrdir format to create.
 
 
418
        :param possible_transports: An optional reusable transports list.
 
 
421
            # check for non local urls
 
 
422
            t = get_transport(base, possible_transports)
 
 
423
            if not isinstance(t, LocalTransport):
 
 
424
                raise errors.NotLocalUrl(base)
 
 
425
        bzrdir = BzrDir.create(base, format, possible_transports)
 
 
426
        repo = bzrdir._find_or_create_repository(force_new_repo)
 
 
427
        result = bzrdir.create_branch()
 
 
428
        if force_new_tree or (repo.make_working_trees() and
 
 
429
                              force_new_tree is None):
 
 
431
                bzrdir.create_workingtree()
 
 
432
            except errors.NotLocalUrl:
 
 
437
    @deprecated_function(zero_ninetyone)
 
 
438
    def create_repository(base, shared=False, format=None):
 
 
439
        """Create a new BzrDir and Repository at the url 'base'.
 
 
441
        If no format is supplied, this will default to the current default
 
 
442
        BzrDirFormat by default, and use whatever repository format that that
 
 
443
        uses for bzrdirformat.create_repository.
 
 
445
        :param shared: Create a shared repository rather than a standalone
 
 
447
        The Repository object is returned.
 
 
449
        This must be overridden as an instance method in child classes, where
 
 
450
        it should take no parameters and construct whatever repository format
 
 
451
        that child class desires.
 
 
453
        This method is deprecated, please call create_repository on a bzrdir
 
 
456
        bzrdir = BzrDir.create(base, format)
 
 
457
        return bzrdir.create_repository(shared)
 
 
460
    def create_standalone_workingtree(base, format=None):
 
 
461
        """Create a new BzrDir, WorkingTree, Branch and Repository at 'base'.
 
 
463
        'base' must be a local path or a file:// url.
 
 
465
        This will use the current default BzrDirFormat unless one is
 
 
466
        specified, and use whatever 
 
 
467
        repository format that that uses for bzrdirformat.create_workingtree,
 
 
468
        create_branch and create_repository.
 
 
470
        :param format: Override for the bzrdir format to create.
 
 
471
        :return: The WorkingTree object.
 
 
473
        t = get_transport(base)
 
 
474
        if not isinstance(t, LocalTransport):
 
 
475
            raise errors.NotLocalUrl(base)
 
 
476
        bzrdir = BzrDir.create_branch_and_repo(base,
 
 
478
                                               format=format).bzrdir
 
 
479
        return bzrdir.create_workingtree()
 
 
481
    def create_workingtree(self, revision_id=None, from_branch=None,
 
 
482
        accelerator_tree=None, hardlink=False):
 
 
483
        """Create a working tree at this BzrDir.
 
 
485
        :param revision_id: create it as of this revision id.
 
 
486
        :param from_branch: override bzrdir branch (for lightweight checkouts)
 
 
487
        :param accelerator_tree: A tree which can be used for retrieving file
 
 
488
            contents more quickly than the revision tree, i.e. a workingtree.
 
 
489
            The revision tree will be used for cases where accelerator_tree's
 
 
490
            content is different.
 
 
492
        raise NotImplementedError(self.create_workingtree)
 
 
494
    def retire_bzrdir(self, limit=10000):
 
 
495
        """Permanently disable the bzrdir.
 
 
497
        This is done by renaming it to give the user some ability to recover
 
 
498
        if there was a problem.
 
 
500
        This will have horrible consequences if anyone has anything locked or
 
 
502
        :param limit: number of times to retry
 
 
507
                to_path = '.bzr.retired.%d' % i
 
 
508
                self.root_transport.rename('.bzr', to_path)
 
 
509
                note("renamed %s to %s"
 
 
510
                    % (self.root_transport.abspath('.bzr'), to_path))
 
 
512
            except (errors.TransportError, IOError, errors.PathError):
 
 
519
    def destroy_workingtree(self):
 
 
520
        """Destroy the working tree at this BzrDir.
 
 
522
        Formats that do not support this may raise UnsupportedOperation.
 
 
524
        raise NotImplementedError(self.destroy_workingtree)
 
 
526
    def destroy_workingtree_metadata(self):
 
 
527
        """Destroy the control files for the working tree at this BzrDir.
 
 
529
        The contents of working tree files are not affected.
 
 
530
        Formats that do not support this may raise UnsupportedOperation.
 
 
532
        raise NotImplementedError(self.destroy_workingtree_metadata)
 
 
534
    def _find_containing(self, evaluate):
 
 
535
        """Find something in a containing control directory.
 
 
537
        This method will scan containing control dirs, until it finds what
 
 
538
        it is looking for, decides that it will never find it, or runs out
 
 
539
        of containing control directories to check.
 
 
541
        It is used to implement find_repository and
 
 
542
        determine_repository_policy.
 
 
544
        :param evaluate: A function returning (value, stop).  If stop is True,
 
 
545
            the value will be returned.
 
 
549
            result, stop = evaluate(found_bzrdir)
 
 
552
            next_transport = found_bzrdir.root_transport.clone('..')
 
 
553
            if (found_bzrdir.root_transport.base == next_transport.base):
 
 
554
                # top of the file system
 
 
556
            # find the next containing bzrdir
 
 
558
                found_bzrdir = BzrDir.open_containing_from_transport(
 
 
560
            except errors.NotBranchError:
 
 
563
    def find_repository(self):
 
 
564
        """Find the repository that should be used.
 
 
566
        This does not require a branch as we use it to find the repo for
 
 
567
        new branches as well as to hook existing branches up to their
 
 
570
        def usable_repository(found_bzrdir):
 
 
571
            # does it have a repository ?
 
 
573
                repository = found_bzrdir.open_repository()
 
 
574
            except errors.NoRepositoryPresent:
 
 
576
            if found_bzrdir.root_transport.base == self.root_transport.base:
 
 
577
                return repository, True
 
 
578
            elif repository.is_shared():
 
 
579
                return repository, True
 
 
583
        found_repo = self._find_containing(usable_repository)
 
 
584
        if found_repo is None:
 
 
585
            raise errors.NoRepositoryPresent(self)
 
 
588
    def get_branch_reference(self):
 
 
589
        """Return the referenced URL for the branch in this bzrdir.
 
 
591
        :raises NotBranchError: If there is no Branch.
 
 
592
        :return: The URL the branch in this bzrdir references if it is a
 
 
593
            reference branch, or None for regular branches.
 
 
597
    def get_branch_transport(self, branch_format):
 
 
598
        """Get the transport for use by branch format in this BzrDir.
 
 
600
        Note that bzr dirs that do not support format strings will raise
 
 
601
        IncompatibleFormat if the branch format they are given has
 
 
602
        a format string, and vice versa.
 
 
604
        If branch_format is None, the transport is returned with no 
 
 
605
        checking. If it is not None, then the returned transport is
 
 
606
        guaranteed to point to an existing directory ready for use.
 
 
608
        raise NotImplementedError(self.get_branch_transport)
 
 
610
    def get_repository_transport(self, repository_format):
 
 
611
        """Get the transport for use by repository format in this BzrDir.
 
 
613
        Note that bzr dirs that do not support format strings will raise
 
 
614
        IncompatibleFormat if the repository format they are given has
 
 
615
        a format string, and vice versa.
 
 
617
        If repository_format is None, the transport is returned with no 
 
 
618
        checking. If it is not None, then the returned transport is
 
 
619
        guaranteed to point to an existing directory ready for use.
 
 
621
        raise NotImplementedError(self.get_repository_transport)
 
 
623
    def get_workingtree_transport(self, tree_format):
 
 
624
        """Get the transport for use by workingtree format in this BzrDir.
 
 
626
        Note that bzr dirs that do not support format strings will raise
 
 
627
        IncompatibleFormat if the workingtree format they are given has a
 
 
628
        format string, and vice versa.
 
 
630
        If workingtree_format is None, the transport is returned with no 
 
 
631
        checking. If it is not None, then the returned transport is
 
 
632
        guaranteed to point to an existing directory ready for use.
 
 
634
        raise NotImplementedError(self.get_workingtree_transport)
 
 
636
    def __init__(self, _transport, _format):
 
 
637
        """Initialize a Bzr control dir object.
 
 
639
        Only really common logic should reside here, concrete classes should be
 
 
640
        made with varying behaviours.
 
 
642
        :param _format: the format that is creating this BzrDir instance.
 
 
643
        :param _transport: the transport this dir is based at.
 
 
645
        self._format = _format
 
 
646
        self.transport = _transport.clone('.bzr')
 
 
647
        self.root_transport = _transport
 
 
649
    def is_control_filename(self, filename):
 
 
650
        """True if filename is the name of a path which is reserved for bzrdir's.
 
 
652
        :param filename: A filename within the root transport of this bzrdir.
 
 
654
        This is true IF and ONLY IF the filename is part of the namespace reserved
 
 
655
        for bzr control dirs. Currently this is the '.bzr' directory in the root
 
 
656
        of the root_transport. it is expected that plugins will need to extend
 
 
657
        this in the future - for instance to make bzr talk with svn working
 
 
660
        # this might be better on the BzrDirFormat class because it refers to 
 
 
661
        # all the possible bzrdir disk formats. 
 
 
662
        # This method is tested via the workingtree is_control_filename tests- 
 
 
663
        # it was extracted from WorkingTree.is_control_filename. If the method's
 
 
664
        # contract is extended beyond the current trivial implementation, please
 
 
665
        # add new tests for it to the appropriate place.
 
 
666
        return filename == '.bzr' or filename.startswith('.bzr/')
 
 
668
    def needs_format_conversion(self, format=None):
 
 
669
        """Return true if this bzrdir needs convert_format run on it.
 
 
671
        For instance, if the repository format is out of date but the 
 
 
672
        branch and working tree are not, this should return True.
 
 
674
        :param format: Optional parameter indicating a specific desired
 
 
675
                       format we plan to arrive at.
 
 
677
        raise NotImplementedError(self.needs_format_conversion)
 
 
680
    def open_unsupported(base):
 
 
681
        """Open a branch which is not supported."""
 
 
682
        return BzrDir.open(base, _unsupported=True)
 
 
685
    def open(base, _unsupported=False, possible_transports=None):
 
 
686
        """Open an existing bzrdir, rooted at 'base' (url).
 
 
688
        :param _unsupported: a private parameter to the BzrDir class.
 
 
690
        t = get_transport(base, possible_transports=possible_transports)
 
 
691
        return BzrDir.open_from_transport(t, _unsupported=_unsupported)
 
 
694
    def open_from_transport(transport, _unsupported=False,
 
 
695
                            _server_formats=True):
 
 
696
        """Open a bzrdir within a particular directory.
 
 
698
        :param transport: Transport containing the bzrdir.
 
 
699
        :param _unsupported: private.
 
 
701
        base = transport.base
 
 
703
        def find_format(transport):
 
 
704
            return transport, BzrDirFormat.find_format(
 
 
705
                transport, _server_formats=_server_formats)
 
 
707
        def redirected(transport, e, redirection_notice):
 
 
708
            qualified_source = e.get_source_url()
 
 
709
            relpath = transport.relpath(qualified_source)
 
 
710
            if not e.target.endswith(relpath):
 
 
711
                # Not redirected to a branch-format, not a branch
 
 
712
                raise errors.NotBranchError(path=e.target)
 
 
713
            target = e.target[:-len(relpath)]
 
 
714
            note('%s is%s redirected to %s',
 
 
715
                 transport.base, e.permanently, target)
 
 
716
            # Let's try with a new transport
 
 
717
            # FIXME: If 'transport' has a qualifier, this should
 
 
718
            # be applied again to the new transport *iff* the
 
 
719
            # schemes used are the same. Uncomment this code
 
 
720
            # once the function (and tests) exist.
 
 
722
            #target = urlutils.copy_url_qualifiers(original, target)
 
 
723
            return get_transport(target)
 
 
726
            transport, format = do_catching_redirections(find_format,
 
 
729
        except errors.TooManyRedirections:
 
 
730
            raise errors.NotBranchError(base)
 
 
732
        BzrDir._check_supported(format, _unsupported)
 
 
733
        return format.open(transport, _found=True)
 
 
735
    def open_branch(self, unsupported=False):
 
 
736
        """Open the branch object at this BzrDir if one is present.
 
 
738
        If unsupported is True, then no longer supported branch formats can
 
 
741
        TODO: static convenience version of this?
 
 
743
        raise NotImplementedError(self.open_branch)
 
 
746
    def open_containing(url, possible_transports=None):
 
 
747
        """Open an existing branch which contains url.
 
 
749
        :param url: url to search from.
 
 
750
        See open_containing_from_transport for more detail.
 
 
752
        transport = get_transport(url, possible_transports)
 
 
753
        return BzrDir.open_containing_from_transport(transport)
 
 
756
    def open_containing_from_transport(a_transport):
 
 
757
        """Open an existing branch which contains a_transport.base.
 
 
759
        This probes for a branch at a_transport, and searches upwards from there.
 
 
761
        Basically we keep looking up until we find the control directory or
 
 
762
        run into the root.  If there isn't one, raises NotBranchError.
 
 
763
        If there is one and it is either an unrecognised format or an unsupported 
 
 
764
        format, UnknownFormatError or UnsupportedFormatError are raised.
 
 
765
        If there is one, it is returned, along with the unused portion of url.
 
 
767
        :return: The BzrDir that contains the path, and a Unicode path 
 
 
768
                for the rest of the URL.
 
 
770
        # this gets the normalised url back. I.e. '.' -> the full path.
 
 
771
        url = a_transport.base
 
 
774
                result = BzrDir.open_from_transport(a_transport)
 
 
775
                return result, urlutils.unescape(a_transport.relpath(url))
 
 
776
            except errors.NotBranchError, e:
 
 
779
                new_t = a_transport.clone('..')
 
 
780
            except errors.InvalidURLJoin:
 
 
781
                # reached the root, whatever that may be
 
 
782
                raise errors.NotBranchError(path=url)
 
 
783
            if new_t.base == a_transport.base:
 
 
784
                # reached the root, whatever that may be
 
 
785
                raise errors.NotBranchError(path=url)
 
 
788
    def _get_tree_branch(self):
 
 
789
        """Return the branch and tree, if any, for this bzrdir.
 
 
791
        Return None for tree if not present or inaccessible.
 
 
792
        Raise NotBranchError if no branch is present.
 
 
793
        :return: (tree, branch)
 
 
796
            tree = self.open_workingtree()
 
 
797
        except (errors.NoWorkingTree, errors.NotLocalUrl):
 
 
799
            branch = self.open_branch()
 
 
805
    def open_tree_or_branch(klass, location):
 
 
806
        """Return the branch and working tree at a location.
 
 
808
        If there is no tree at the location, tree will be None.
 
 
809
        If there is no branch at the location, an exception will be
 
 
811
        :return: (tree, branch)
 
 
813
        bzrdir = klass.open(location)
 
 
814
        return bzrdir._get_tree_branch()
 
 
817
    def open_containing_tree_or_branch(klass, location):
 
 
818
        """Return the branch and working tree contained by a location.
 
 
820
        Returns (tree, branch, relpath).
 
 
821
        If there is no tree at containing the location, tree will be None.
 
 
822
        If there is no branch containing the location, an exception will be
 
 
824
        relpath is the portion of the path that is contained by the branch.
 
 
826
        bzrdir, relpath = klass.open_containing(location)
 
 
827
        tree, branch = bzrdir._get_tree_branch()
 
 
828
        return tree, branch, relpath
 
 
830
    def open_repository(self, _unsupported=False):
 
 
831
        """Open the repository object at this BzrDir if one is present.
 
 
833
        This will not follow the Branch object pointer - it's strictly a direct
 
 
834
        open facility. Most client code should use open_branch().repository to
 
 
837
        :param _unsupported: a private parameter, not part of the api.
 
 
838
        TODO: static convenience version of this?
 
 
840
        raise NotImplementedError(self.open_repository)
 
 
842
    def open_workingtree(self, _unsupported=False,
 
 
843
                         recommend_upgrade=True, from_branch=None):
 
 
844
        """Open the workingtree object at this BzrDir if one is present.
 
 
846
        :param recommend_upgrade: Optional keyword parameter, when True (the
 
 
847
            default), emit through the ui module a recommendation that the user
 
 
848
            upgrade the working tree when the workingtree being opened is old
 
 
849
            (but still fully supported).
 
 
850
        :param from_branch: override bzrdir branch (for lightweight checkouts)
 
 
852
        raise NotImplementedError(self.open_workingtree)
 
 
854
    def has_branch(self):
 
 
855
        """Tell if this bzrdir contains a branch.
 
 
857
        Note: if you're going to open the branch, you should just go ahead
 
 
858
        and try, and not ask permission first.  (This method just opens the 
 
 
859
        branch and discards it, and that's somewhat expensive.) 
 
 
864
        except errors.NotBranchError:
 
 
867
    def has_workingtree(self):
 
 
868
        """Tell if this bzrdir contains a working tree.
 
 
870
        This will still raise an exception if the bzrdir has a workingtree that
 
 
871
        is remote & inaccessible.
 
 
873
        Note: if you're going to open the working tree, you should just go ahead
 
 
874
        and try, and not ask permission first.  (This method just opens the 
 
 
875
        workingtree and discards it, and that's somewhat expensive.) 
 
 
878
            self.open_workingtree(recommend_upgrade=False)
 
 
880
        except errors.NoWorkingTree:
 
 
883
    def _cloning_metadir(self):
 
 
884
        """Produce a metadir suitable for cloning with."""
 
 
885
        result_format = self._format.__class__()
 
 
888
                branch = self.open_branch()
 
 
889
                source_repository = branch.repository
 
 
890
            except errors.NotBranchError:
 
 
892
                source_repository = self.open_repository()
 
 
893
        except errors.NoRepositoryPresent:
 
 
894
            source_repository = None
 
 
896
            # XXX TODO: This isinstance is here because we have not implemented
 
 
897
            # the fix recommended in bug # 103195 - to delegate this choice the
 
 
899
            repo_format = source_repository._format
 
 
900
            if not isinstance(repo_format, remote.RemoteRepositoryFormat):
 
 
901
                result_format.repository_format = repo_format
 
 
903
            # TODO: Couldn't we just probe for the format in these cases,
 
 
904
            # rather than opening the whole tree?  It would be a little
 
 
905
            # faster. mbp 20070401
 
 
906
            tree = self.open_workingtree(recommend_upgrade=False)
 
 
907
        except (errors.NoWorkingTree, errors.NotLocalUrl):
 
 
908
            result_format.workingtree_format = None
 
 
910
            result_format.workingtree_format = tree._format.__class__()
 
 
911
        return result_format, source_repository
 
 
913
    def cloning_metadir(self):
 
 
914
        """Produce a metadir suitable for cloning or sprouting with.
 
 
916
        These operations may produce workingtrees (yes, even though they're
 
 
917
        "cloning" something that doesn't have a tree), so a viable workingtree
 
 
918
        format must be selected.
 
 
920
        format, repository = self._cloning_metadir()
 
 
921
        if format._workingtree_format is None:
 
 
922
            if repository is None:
 
 
924
            tree_format = repository._format._matchingbzrdir.workingtree_format
 
 
925
            format.workingtree_format = tree_format.__class__()
 
 
928
    def checkout_metadir(self):
 
 
929
        return self.cloning_metadir()
 
 
931
    def sprout(self, url, revision_id=None, force_new_repo=False,
 
 
932
               recurse='down', possible_transports=None,
 
 
933
               accelerator_tree=None, hardlink=False):
 
 
934
        """Create a copy of this bzrdir prepared for use as a new line of
 
 
937
        If url's last component does not exist, it will be created.
 
 
939
        Attributes related to the identity of the source branch like
 
 
940
        branch nickname will be cleaned, a working tree is created
 
 
941
        whether one existed before or not; and a local branch is always
 
 
944
        if revision_id is not None, then the clone operation may tune
 
 
945
            itself to download less data.
 
 
946
        :param accelerator_tree: A tree which can be used for retrieving file
 
 
947
            contents more quickly than the revision tree, i.e. a workingtree.
 
 
948
            The revision tree will be used for cases where accelerator_tree's
 
 
949
            content is different.
 
 
950
        :param hardlink: If true, hard-link files from accelerator_tree,
 
 
953
        target_transport = get_transport(url, possible_transports)
 
 
954
        target_transport.ensure_base()
 
 
955
        cloning_format = self.cloning_metadir()
 
 
956
        result = cloning_format.initialize_on_transport(target_transport)
 
 
958
            source_branch = self.open_branch()
 
 
959
            source_repository = source_branch.repository
 
 
960
        except errors.NotBranchError:
 
 
963
                source_repository = self.open_repository()
 
 
964
            except errors.NoRepositoryPresent:
 
 
965
                source_repository = None
 
 
970
                result_repo = result.find_repository()
 
 
971
            except errors.NoRepositoryPresent:
 
 
973
        if source_repository is None and result_repo is not None:
 
 
975
        elif source_repository is None and result_repo is None:
 
 
976
            # no repo available, make a new one
 
 
977
            result.create_repository()
 
 
978
        elif source_repository is not None and result_repo is None:
 
 
979
            # have source, and want to make a new target repo
 
 
980
            result_repo = source_repository.sprout(result,
 
 
981
                                                   revision_id=revision_id)
 
 
983
            # fetch needed content into target.
 
 
984
            if source_repository is not None:
 
 
986
                # source_repository.copy_content_into(result_repo,
 
 
987
                #                                     revision_id=revision_id)
 
 
988
                # so we can override the copy method
 
 
989
                result_repo.fetch(source_repository, revision_id=revision_id)
 
 
990
        if source_branch is not None:
 
 
991
            source_branch.sprout(result, revision_id=revision_id)
 
 
993
            result.create_branch()
 
 
994
        if isinstance(target_transport, LocalTransport) and (
 
 
995
            result_repo is None or result_repo.make_working_trees()):
 
 
996
            wt = result.create_workingtree(accelerator_tree=accelerator_tree,
 
 
1000
                if wt.path2id('') is None:
 
 
1002
                        wt.set_root_id(self.open_workingtree.get_root_id())
 
 
1003
                    except errors.NoWorkingTree:
 
 
1009
        if recurse == 'down':
 
 
1011
                basis = wt.basis_tree()
 
 
1013
                subtrees = basis.iter_references()
 
 
1014
                recurse_branch = wt.branch
 
 
1015
            elif source_branch is not None:
 
 
1016
                basis = source_branch.basis_tree()
 
 
1018
                subtrees = basis.iter_references()
 
 
1019
                recurse_branch = source_branch
 
 
1024
                for path, file_id in subtrees:
 
 
1025
                    target = urlutils.join(url, urlutils.escape(path))
 
 
1026
                    sublocation = source_branch.reference_parent(file_id, path)
 
 
1027
                    sublocation.bzrdir.sprout(target,
 
 
1028
                        basis.get_reference_revision(file_id, path),
 
 
1029
                        force_new_repo=force_new_repo, recurse=recurse)
 
 
1031
                if basis is not None:
 
 
1036
class BzrDirPreSplitOut(BzrDir):
 
 
1037
    """A common class for the all-in-one formats."""
 
 
1039
    def __init__(self, _transport, _format):
 
 
1040
        """See BzrDir.__init__."""
 
 
1041
        super(BzrDirPreSplitOut, self).__init__(_transport, _format)
 
 
1042
        self._control_files = lockable_files.LockableFiles(
 
 
1043
                                            self.get_branch_transport(None),
 
 
1044
                                            self._format._lock_file_name,
 
 
1045
                                            self._format._lock_class)
 
 
1047
    def break_lock(self):
 
 
1048
        """Pre-splitout bzrdirs do not suffer from stale locks."""
 
 
1049
        raise NotImplementedError(self.break_lock)
 
 
1051
    def cloning_metadir(self):
 
 
1052
        """Produce a metadir suitable for cloning with."""
 
 
1053
        return self._format.__class__()
 
 
1055
    def clone(self, url, revision_id=None, force_new_repo=False):
 
 
1056
        """See BzrDir.clone()."""
 
 
1057
        from bzrlib.workingtree import WorkingTreeFormat2
 
 
1058
        self._make_tail(url)
 
 
1059
        result = self._format._initialize_for_clone(url)
 
 
1060
        self.open_repository().clone(result, revision_id=revision_id)
 
 
1061
        from_branch = self.open_branch()
 
 
1062
        from_branch.clone(result, revision_id=revision_id)
 
 
1064
            self.open_workingtree().clone(result)
 
 
1065
        except errors.NotLocalUrl:
 
 
1066
            # make a new one, this format always has to have one.
 
 
1068
                WorkingTreeFormat2().initialize(result)
 
 
1069
            except errors.NotLocalUrl:
 
 
1070
                # but we cannot do it for remote trees.
 
 
1071
                to_branch = result.open_branch()
 
 
1072
                WorkingTreeFormat2().stub_initialize_remote(to_branch.control_files)
 
 
1075
    def create_branch(self):
 
 
1076
        """See BzrDir.create_branch."""
 
 
1077
        return self.open_branch()
 
 
1079
    def destroy_branch(self):
 
 
1080
        """See BzrDir.destroy_branch."""
 
 
1081
        raise errors.UnsupportedOperation(self.destroy_branch, self)
 
 
1083
    def create_repository(self, shared=False):
 
 
1084
        """See BzrDir.create_repository."""
 
 
1086
            raise errors.IncompatibleFormat('shared repository', self._format)
 
 
1087
        return self.open_repository()
 
 
1089
    def destroy_repository(self):
 
 
1090
        """See BzrDir.destroy_repository."""
 
 
1091
        raise errors.UnsupportedOperation(self.destroy_repository, self)
 
 
1093
    def create_workingtree(self, revision_id=None, from_branch=None,
 
 
1094
                           accelerator_tree=None, hardlink=False):
 
 
1095
        """See BzrDir.create_workingtree."""
 
 
1096
        # this looks buggy but is not -really-
 
 
1097
        # because this format creates the workingtree when the bzrdir is
 
 
1099
        # clone and sprout will have set the revision_id
 
 
1100
        # and that will have set it for us, its only
 
 
1101
        # specific uses of create_workingtree in isolation
 
 
1102
        # that can do wonky stuff here, and that only
 
 
1103
        # happens for creating checkouts, which cannot be 
 
 
1104
        # done on this format anyway. So - acceptable wart.
 
 
1105
        result = self.open_workingtree(recommend_upgrade=False)
 
 
1106
        if revision_id is not None:
 
 
1107
            if revision_id == _mod_revision.NULL_REVISION:
 
 
1108
                result.set_parent_ids([])
 
 
1110
                result.set_parent_ids([revision_id])
 
 
1113
    def destroy_workingtree(self):
 
 
1114
        """See BzrDir.destroy_workingtree."""
 
 
1115
        raise errors.UnsupportedOperation(self.destroy_workingtree, self)
 
 
1117
    def destroy_workingtree_metadata(self):
 
 
1118
        """See BzrDir.destroy_workingtree_metadata."""
 
 
1119
        raise errors.UnsupportedOperation(self.destroy_workingtree_metadata, 
 
 
1122
    def get_branch_transport(self, branch_format):
 
 
1123
        """See BzrDir.get_branch_transport()."""
 
 
1124
        if branch_format is None:
 
 
1125
            return self.transport
 
 
1127
            branch_format.get_format_string()
 
 
1128
        except NotImplementedError:
 
 
1129
            return self.transport
 
 
1130
        raise errors.IncompatibleFormat(branch_format, self._format)
 
 
1132
    def get_repository_transport(self, repository_format):
 
 
1133
        """See BzrDir.get_repository_transport()."""
 
 
1134
        if repository_format is None:
 
 
1135
            return self.transport
 
 
1137
            repository_format.get_format_string()
 
 
1138
        except NotImplementedError:
 
 
1139
            return self.transport
 
 
1140
        raise errors.IncompatibleFormat(repository_format, self._format)
 
 
1142
    def get_workingtree_transport(self, workingtree_format):
 
 
1143
        """See BzrDir.get_workingtree_transport()."""
 
 
1144
        if workingtree_format is None:
 
 
1145
            return self.transport
 
 
1147
            workingtree_format.get_format_string()
 
 
1148
        except NotImplementedError:
 
 
1149
            return self.transport
 
 
1150
        raise errors.IncompatibleFormat(workingtree_format, self._format)
 
 
1152
    def needs_format_conversion(self, format=None):
 
 
1153
        """See BzrDir.needs_format_conversion()."""
 
 
1154
        # if the format is not the same as the system default,
 
 
1155
        # an upgrade is needed.
 
 
1157
            format = BzrDirFormat.get_default_format()
 
 
1158
        return not isinstance(self._format, format.__class__)
 
 
1160
    def open_branch(self, unsupported=False):
 
 
1161
        """See BzrDir.open_branch."""
 
 
1162
        from bzrlib.branch import BzrBranchFormat4
 
 
1163
        format = BzrBranchFormat4()
 
 
1164
        self._check_supported(format, unsupported)
 
 
1165
        return format.open(self, _found=True)
 
 
1167
    def sprout(self, url, revision_id=None, force_new_repo=False,
 
 
1168
               possible_transports=None, accelerator_tree=None,
 
 
1170
        """See BzrDir.sprout()."""
 
 
1171
        from bzrlib.workingtree import WorkingTreeFormat2
 
 
1172
        self._make_tail(url)
 
 
1173
        result = self._format._initialize_for_clone(url)
 
 
1175
            self.open_repository().clone(result, revision_id=revision_id)
 
 
1176
        except errors.NoRepositoryPresent:
 
 
1179
            self.open_branch().sprout(result, revision_id=revision_id)
 
 
1180
        except errors.NotBranchError:
 
 
1182
        # we always want a working tree
 
 
1183
        WorkingTreeFormat2().initialize(result,
 
 
1184
                                        accelerator_tree=accelerator_tree,
 
 
1189
class BzrDir4(BzrDirPreSplitOut):
 
 
1190
    """A .bzr version 4 control object.
 
 
1192
    This is a deprecated format and may be removed after sept 2006.
 
 
1195
    def create_repository(self, shared=False):
 
 
1196
        """See BzrDir.create_repository."""
 
 
1197
        return self._format.repository_format.initialize(self, shared)
 
 
1199
    def needs_format_conversion(self, format=None):
 
 
1200
        """Format 4 dirs are always in need of conversion."""
 
 
1203
    def open_repository(self):
 
 
1204
        """See BzrDir.open_repository."""
 
 
1205
        from bzrlib.repofmt.weaverepo import RepositoryFormat4
 
 
1206
        return RepositoryFormat4().open(self, _found=True)
 
 
1209
class BzrDir5(BzrDirPreSplitOut):
 
 
1210
    """A .bzr version 5 control object.
 
 
1212
    This is a deprecated format and may be removed after sept 2006.
 
 
1215
    def open_repository(self):
 
 
1216
        """See BzrDir.open_repository."""
 
 
1217
        from bzrlib.repofmt.weaverepo import RepositoryFormat5
 
 
1218
        return RepositoryFormat5().open(self, _found=True)
 
 
1220
    def open_workingtree(self, _unsupported=False,
 
 
1221
            recommend_upgrade=True):
 
 
1222
        """See BzrDir.create_workingtree."""
 
 
1223
        from bzrlib.workingtree import WorkingTreeFormat2
 
 
1224
        wt_format = WorkingTreeFormat2()
 
 
1225
        # we don't warn here about upgrades; that ought to be handled for the
 
 
1227
        return wt_format.open(self, _found=True)
 
 
1230
class BzrDir6(BzrDirPreSplitOut):
 
 
1231
    """A .bzr version 6 control object.
 
 
1233
    This is a deprecated format and may be removed after sept 2006.
 
 
1236
    def open_repository(self):
 
 
1237
        """See BzrDir.open_repository."""
 
 
1238
        from bzrlib.repofmt.weaverepo import RepositoryFormat6
 
 
1239
        return RepositoryFormat6().open(self, _found=True)
 
 
1241
    def open_workingtree(self, _unsupported=False,
 
 
1242
        recommend_upgrade=True):
 
 
1243
        """See BzrDir.create_workingtree."""
 
 
1244
        # we don't warn here about upgrades; that ought to be handled for the
 
 
1246
        from bzrlib.workingtree import WorkingTreeFormat2
 
 
1247
        return WorkingTreeFormat2().open(self, _found=True)
 
 
1250
class BzrDirMeta1(BzrDir):
 
 
1251
    """A .bzr meta version 1 control object.
 
 
1253
    This is the first control object where the 
 
 
1254
    individual aspects are really split out: there are separate repository,
 
 
1255
    workingtree and branch subdirectories and any subset of the three can be
 
 
1256
    present within a BzrDir.
 
 
1259
    def can_convert_format(self):
 
 
1260
        """See BzrDir.can_convert_format()."""
 
 
1263
    def create_branch(self):
 
 
1264
        """See BzrDir.create_branch."""
 
 
1265
        return self._format.get_branch_format().initialize(self)
 
 
1267
    def destroy_branch(self):
 
 
1268
        """See BzrDir.create_branch."""
 
 
1269
        self.transport.delete_tree('branch')
 
 
1271
    def create_repository(self, shared=False):
 
 
1272
        """See BzrDir.create_repository."""
 
 
1273
        return self._format.repository_format.initialize(self, shared)
 
 
1275
    def destroy_repository(self):
 
 
1276
        """See BzrDir.destroy_repository."""
 
 
1277
        self.transport.delete_tree('repository')
 
 
1279
    def create_workingtree(self, revision_id=None, from_branch=None,
 
 
1280
                           accelerator_tree=None, hardlink=False):
 
 
1281
        """See BzrDir.create_workingtree."""
 
 
1282
        return self._format.workingtree_format.initialize(
 
 
1283
            self, revision_id, from_branch=from_branch,
 
 
1284
            accelerator_tree=accelerator_tree, hardlink=hardlink)
 
 
1286
    def destroy_workingtree(self):
 
 
1287
        """See BzrDir.destroy_workingtree."""
 
 
1288
        wt = self.open_workingtree(recommend_upgrade=False)
 
 
1289
        repository = wt.branch.repository
 
 
1290
        empty = repository.revision_tree(_mod_revision.NULL_REVISION)
 
 
1291
        wt.revert(old_tree=empty)
 
 
1292
        self.destroy_workingtree_metadata()
 
 
1294
    def destroy_workingtree_metadata(self):
 
 
1295
        self.transport.delete_tree('checkout')
 
 
1297
    def find_branch_format(self):
 
 
1298
        """Find the branch 'format' for this bzrdir.
 
 
1300
        This might be a synthetic object for e.g. RemoteBranch and SVN.
 
 
1302
        from bzrlib.branch import BranchFormat
 
 
1303
        return BranchFormat.find_format(self)
 
 
1305
    def _get_mkdir_mode(self):
 
 
1306
        """Figure out the mode to use when creating a bzrdir subdir."""
 
 
1307
        temp_control = lockable_files.LockableFiles(self.transport, '',
 
 
1308
                                     lockable_files.TransportLock)
 
 
1309
        return temp_control._dir_mode
 
 
1311
    def get_branch_reference(self):
 
 
1312
        """See BzrDir.get_branch_reference()."""
 
 
1313
        from bzrlib.branch import BranchFormat
 
 
1314
        format = BranchFormat.find_format(self)
 
 
1315
        return format.get_reference(self)
 
 
1317
    def get_branch_transport(self, branch_format):
 
 
1318
        """See BzrDir.get_branch_transport()."""
 
 
1319
        if branch_format is None:
 
 
1320
            return self.transport.clone('branch')
 
 
1322
            branch_format.get_format_string()
 
 
1323
        except NotImplementedError:
 
 
1324
            raise errors.IncompatibleFormat(branch_format, self._format)
 
 
1326
            self.transport.mkdir('branch', mode=self._get_mkdir_mode())
 
 
1327
        except errors.FileExists:
 
 
1329
        return self.transport.clone('branch')
 
 
1331
    def get_repository_transport(self, repository_format):
 
 
1332
        """See BzrDir.get_repository_transport()."""
 
 
1333
        if repository_format is None:
 
 
1334
            return self.transport.clone('repository')
 
 
1336
            repository_format.get_format_string()
 
 
1337
        except NotImplementedError:
 
 
1338
            raise errors.IncompatibleFormat(repository_format, self._format)
 
 
1340
            self.transport.mkdir('repository', mode=self._get_mkdir_mode())
 
 
1341
        except errors.FileExists:
 
 
1343
        return self.transport.clone('repository')
 
 
1345
    def get_workingtree_transport(self, workingtree_format):
 
 
1346
        """See BzrDir.get_workingtree_transport()."""
 
 
1347
        if workingtree_format is None:
 
 
1348
            return self.transport.clone('checkout')
 
 
1350
            workingtree_format.get_format_string()
 
 
1351
        except NotImplementedError:
 
 
1352
            raise errors.IncompatibleFormat(workingtree_format, self._format)
 
 
1354
            self.transport.mkdir('checkout', mode=self._get_mkdir_mode())
 
 
1355
        except errors.FileExists:
 
 
1357
        return self.transport.clone('checkout')
 
 
1359
    def needs_format_conversion(self, format=None):
 
 
1360
        """See BzrDir.needs_format_conversion()."""
 
 
1362
            format = BzrDirFormat.get_default_format()
 
 
1363
        if not isinstance(self._format, format.__class__):
 
 
1364
            # it is not a meta dir format, conversion is needed.
 
 
1366
        # we might want to push this down to the repository?
 
 
1368
            if not isinstance(self.open_repository()._format,
 
 
1369
                              format.repository_format.__class__):
 
 
1370
                # the repository needs an upgrade.
 
 
1372
        except errors.NoRepositoryPresent:
 
 
1375
            if not isinstance(self.open_branch()._format,
 
 
1376
                              format.get_branch_format().__class__):
 
 
1377
                # the branch needs an upgrade.
 
 
1379
        except errors.NotBranchError:
 
 
1382
            my_wt = self.open_workingtree(recommend_upgrade=False)
 
 
1383
            if not isinstance(my_wt._format,
 
 
1384
                              format.workingtree_format.__class__):
 
 
1385
                # the workingtree needs an upgrade.
 
 
1387
        except (errors.NoWorkingTree, errors.NotLocalUrl):
 
 
1391
    def open_branch(self, unsupported=False):
 
 
1392
        """See BzrDir.open_branch."""
 
 
1393
        format = self.find_branch_format()
 
 
1394
        self._check_supported(format, unsupported)
 
 
1395
        return format.open(self, _found=True)
 
 
1397
    def open_repository(self, unsupported=False):
 
 
1398
        """See BzrDir.open_repository."""
 
 
1399
        from bzrlib.repository import RepositoryFormat
 
 
1400
        format = RepositoryFormat.find_format(self)
 
 
1401
        self._check_supported(format, unsupported)
 
 
1402
        return format.open(self, _found=True)
 
 
1404
    def open_workingtree(self, unsupported=False,
 
 
1405
            recommend_upgrade=True):
 
 
1406
        """See BzrDir.open_workingtree."""
 
 
1407
        from bzrlib.workingtree import WorkingTreeFormat
 
 
1408
        format = WorkingTreeFormat.find_format(self)
 
 
1409
        self._check_supported(format, unsupported,
 
 
1411
            basedir=self.root_transport.base)
 
 
1412
        return format.open(self, _found=True)
 
 
1415
class BzrDirFormat(object):
 
 
1416
    """An encapsulation of the initialization and open routines for a format.
 
 
1418
    Formats provide three things:
 
 
1419
     * An initialization routine,
 
 
1423
    Formats are placed in a dict by their format string for reference 
 
 
1424
    during bzrdir opening. These should be subclasses of BzrDirFormat
 
 
1427
    Once a format is deprecated, just deprecate the initialize and open
 
 
1428
    methods on the format class. Do not deprecate the object, as the 
 
 
1429
    object will be created every system load.
 
 
1432
    _default_format = None
 
 
1433
    """The default format used for new .bzr dirs."""
 
 
1436
    """The known formats."""
 
 
1438
    _control_formats = []
 
 
1439
    """The registered control formats - .bzr, ....
 
 
1441
    This is a list of BzrDirFormat objects.
 
 
1444
    _control_server_formats = []
 
 
1445
    """The registered control server formats, e.g. RemoteBzrDirs.
 
 
1447
    This is a list of BzrDirFormat objects.
 
 
1450
    _lock_file_name = 'branch-lock'
 
 
1452
    # _lock_class must be set in subclasses to the lock type, typ.
 
 
1453
    # TransportLock or LockDir
 
 
1456
    def find_format(klass, transport, _server_formats=True):
 
 
1457
        """Return the format present at transport."""
 
 
1459
            formats = klass._control_server_formats + klass._control_formats
 
 
1461
            formats = klass._control_formats
 
 
1462
        for format in formats:
 
 
1464
                return format.probe_transport(transport)
 
 
1465
            except errors.NotBranchError:
 
 
1466
                # this format does not find a control dir here.
 
 
1468
        raise errors.NotBranchError(path=transport.base)
 
 
1471
    def probe_transport(klass, transport):
 
 
1472
        """Return the .bzrdir style format present in a directory."""
 
 
1474
            format_string = transport.get(".bzr/branch-format").read()
 
 
1475
        except errors.NoSuchFile:
 
 
1476
            raise errors.NotBranchError(path=transport.base)
 
 
1479
            return klass._formats[format_string]
 
 
1481
            raise errors.UnknownFormatError(format=format_string, kind='bzrdir')
 
 
1484
    def get_default_format(klass):
 
 
1485
        """Return the current default format."""
 
 
1486
        return klass._default_format
 
 
1488
    def get_format_string(self):
 
 
1489
        """Return the ASCII format string that identifies this format."""
 
 
1490
        raise NotImplementedError(self.get_format_string)
 
 
1492
    def get_format_description(self):
 
 
1493
        """Return the short description for this format."""
 
 
1494
        raise NotImplementedError(self.get_format_description)
 
 
1496
    def get_converter(self, format=None):
 
 
1497
        """Return the converter to use to convert bzrdirs needing converts.
 
 
1499
        This returns a bzrlib.bzrdir.Converter object.
 
 
1501
        This should return the best upgrader to step this format towards the
 
 
1502
        current default format. In the case of plugins we can/should provide
 
 
1503
        some means for them to extend the range of returnable converters.
 
 
1505
        :param format: Optional format to override the default format of the 
 
 
1508
        raise NotImplementedError(self.get_converter)
 
 
1510
    def initialize(self, url, possible_transports=None):
 
 
1511
        """Create a bzr control dir at this url and return an opened copy.
 
 
1513
        Subclasses should typically override initialize_on_transport
 
 
1514
        instead of this method.
 
 
1516
        return self.initialize_on_transport(get_transport(url,
 
 
1517
                                                          possible_transports))
 
 
1519
    def initialize_on_transport(self, transport):
 
 
1520
        """Initialize a new bzrdir in the base directory of a Transport."""
 
 
1521
        # Since we don't have a .bzr directory, inherit the
 
 
1522
        # mode from the root directory
 
 
1523
        temp_control = lockable_files.LockableFiles(transport,
 
 
1524
                            '', lockable_files.TransportLock)
 
 
1525
        temp_control._transport.mkdir('.bzr',
 
 
1526
                                      # FIXME: RBC 20060121 don't peek under
 
 
1528
                                      mode=temp_control._dir_mode)
 
 
1529
        if sys.platform == 'win32' and isinstance(transport, LocalTransport):
 
 
1530
            win32utils.set_file_attr_hidden(transport._abspath('.bzr'))
 
 
1531
        file_mode = temp_control._file_mode
 
 
1533
        mutter('created control directory in ' + transport.base)
 
 
1534
        control = transport.clone('.bzr')
 
 
1535
        utf8_files = [('README', 
 
 
1536
                       "This is a Bazaar control directory.\n"
 
 
1537
                       "Do not change any files in this directory.\n"
 
 
1538
                       "See http://bazaar-vcs.org/ for more information about Bazaar.\n"),
 
 
1539
                      ('branch-format', self.get_format_string()),
 
 
1541
        # NB: no need to escape relative paths that are url safe.
 
 
1542
        control_files = lockable_files.LockableFiles(control,
 
 
1543
                            self._lock_file_name, self._lock_class)
 
 
1544
        control_files.create_lock()
 
 
1545
        control_files.lock_write()
 
 
1547
            for file, content in utf8_files:
 
 
1548
                control_files.put_utf8(file, content)
 
 
1550
            control_files.unlock()
 
 
1551
        return self.open(transport, _found=True)
 
 
1553
    def is_supported(self):
 
 
1554
        """Is this format supported?
 
 
1556
        Supported formats must be initializable and openable.
 
 
1557
        Unsupported formats may not support initialization or committing or 
 
 
1558
        some other features depending on the reason for not being supported.
 
 
1562
    def same_model(self, target_format):
 
 
1563
        return (self.repository_format.rich_root_data == 
 
 
1564
            target_format.rich_root_data)
 
 
1567
    def known_formats(klass):
 
 
1568
        """Return all the known formats.
 
 
1570
        Concrete formats should override _known_formats.
 
 
1572
        # There is double indirection here to make sure that control 
 
 
1573
        # formats used by more than one dir format will only be probed 
 
 
1574
        # once. This can otherwise be quite expensive for remote connections.
 
 
1576
        for format in klass._control_formats:
 
 
1577
            result.update(format._known_formats())
 
 
1581
    def _known_formats(klass):
 
 
1582
        """Return the known format instances for this control format."""
 
 
1583
        return set(klass._formats.values())
 
 
1585
    def open(self, transport, _found=False):
 
 
1586
        """Return an instance of this format for the dir transport points at.
 
 
1588
        _found is a private parameter, do not use it.
 
 
1591
            found_format = BzrDirFormat.find_format(transport)
 
 
1592
            if not isinstance(found_format, self.__class__):
 
 
1593
                raise AssertionError("%s was asked to open %s, but it seems to need "
 
 
1595
                        % (self, transport, found_format))
 
 
1596
        return self._open(transport)
 
 
1598
    def _open(self, transport):
 
 
1599
        """Template method helper for opening BzrDirectories.
 
 
1601
        This performs the actual open and any additional logic or parameter
 
 
1604
        raise NotImplementedError(self._open)
 
 
1607
    def register_format(klass, format):
 
 
1608
        klass._formats[format.get_format_string()] = format
 
 
1611
    def register_control_format(klass, format):
 
 
1612
        """Register a format that does not use '.bzr' for its control dir.
 
 
1614
        TODO: This should be pulled up into a 'ControlDirFormat' base class
 
 
1615
        which BzrDirFormat can inherit from, and renamed to register_format 
 
 
1616
        there. It has been done without that for now for simplicity of
 
 
1619
        klass._control_formats.append(format)
 
 
1622
    def register_control_server_format(klass, format):
 
 
1623
        """Register a control format for client-server environments.
 
 
1625
        These formats will be tried before ones registered with
 
 
1626
        register_control_format.  This gives implementations that decide to the
 
 
1627
        chance to grab it before anything looks at the contents of the format
 
 
1630
        klass._control_server_formats.append(format)
 
 
1633
    @symbol_versioning.deprecated_method(symbol_versioning.zero_fourteen)
 
 
1634
    def set_default_format(klass, format):
 
 
1635
        klass._set_default_format(format)
 
 
1638
    def _set_default_format(klass, format):
 
 
1639
        """Set default format (for testing behavior of defaults only)"""
 
 
1640
        klass._default_format = format
 
 
1644
        return self.get_format_string().rstrip()
 
 
1647
    def unregister_format(klass, format):
 
 
1648
        del klass._formats[format.get_format_string()]
 
 
1651
    def unregister_control_format(klass, format):
 
 
1652
        klass._control_formats.remove(format)
 
 
1655
class BzrDirFormat4(BzrDirFormat):
 
 
1656
    """Bzr dir format 4.
 
 
1658
    This format is a combined format for working tree, branch and repository.
 
 
1660
     - Format 1 working trees [always]
 
 
1661
     - Format 4 branches [always]
 
 
1662
     - Format 4 repositories [always]
 
 
1664
    This format is deprecated: it indexes texts using a text it which is
 
 
1665
    removed in format 5; write support for this format has been removed.
 
 
1668
    _lock_class = lockable_files.TransportLock
 
 
1670
    def get_format_string(self):
 
 
1671
        """See BzrDirFormat.get_format_string()."""
 
 
1672
        return "Bazaar-NG branch, format 0.0.4\n"
 
 
1674
    def get_format_description(self):
 
 
1675
        """See BzrDirFormat.get_format_description()."""
 
 
1676
        return "All-in-one format 4"
 
 
1678
    def get_converter(self, format=None):
 
 
1679
        """See BzrDirFormat.get_converter()."""
 
 
1680
        # there is one and only one upgrade path here.
 
 
1681
        return ConvertBzrDir4To5()
 
 
1683
    def initialize_on_transport(self, transport):
 
 
1684
        """Format 4 branches cannot be created."""
 
 
1685
        raise errors.UninitializableFormat(self)
 
 
1687
    def is_supported(self):
 
 
1688
        """Format 4 is not supported.
 
 
1690
        It is not supported because the model changed from 4 to 5 and the
 
 
1691
        conversion logic is expensive - so doing it on the fly was not 
 
 
1696
    def _open(self, transport):
 
 
1697
        """See BzrDirFormat._open."""
 
 
1698
        return BzrDir4(transport, self)
 
 
1700
    def __return_repository_format(self):
 
 
1701
        """Circular import protection."""
 
 
1702
        from bzrlib.repofmt.weaverepo import RepositoryFormat4
 
 
1703
        return RepositoryFormat4()
 
 
1704
    repository_format = property(__return_repository_format)
 
 
1707
class BzrDirFormat5(BzrDirFormat):
 
 
1708
    """Bzr control format 5.
 
 
1710
    This format is a combined format for working tree, branch and repository.
 
 
1712
     - Format 2 working trees [always] 
 
 
1713
     - Format 4 branches [always] 
 
 
1714
     - Format 5 repositories [always]
 
 
1715
       Unhashed stores in the repository.
 
 
1718
    _lock_class = lockable_files.TransportLock
 
 
1720
    def get_format_string(self):
 
 
1721
        """See BzrDirFormat.get_format_string()."""
 
 
1722
        return "Bazaar-NG branch, format 5\n"
 
 
1724
    def get_format_description(self):
 
 
1725
        """See BzrDirFormat.get_format_description()."""
 
 
1726
        return "All-in-one format 5"
 
 
1728
    def get_converter(self, format=None):
 
 
1729
        """See BzrDirFormat.get_converter()."""
 
 
1730
        # there is one and only one upgrade path here.
 
 
1731
        return ConvertBzrDir5To6()
 
 
1733
    def _initialize_for_clone(self, url):
 
 
1734
        return self.initialize_on_transport(get_transport(url), _cloning=True)
 
 
1736
    def initialize_on_transport(self, transport, _cloning=False):
 
 
1737
        """Format 5 dirs always have working tree, branch and repository.
 
 
1739
        Except when they are being cloned.
 
 
1741
        from bzrlib.branch import BzrBranchFormat4
 
 
1742
        from bzrlib.repofmt.weaverepo import RepositoryFormat5
 
 
1743
        from bzrlib.workingtree import WorkingTreeFormat2
 
 
1744
        result = (super(BzrDirFormat5, self).initialize_on_transport(transport))
 
 
1745
        RepositoryFormat5().initialize(result, _internal=True)
 
 
1747
            branch = BzrBranchFormat4().initialize(result)
 
 
1749
                WorkingTreeFormat2().initialize(result)
 
 
1750
            except errors.NotLocalUrl:
 
 
1751
                # Even though we can't access the working tree, we need to
 
 
1752
                # create its control files.
 
 
1753
                WorkingTreeFormat2().stub_initialize_remote(branch.control_files)
 
 
1756
    def _open(self, transport):
 
 
1757
        """See BzrDirFormat._open."""
 
 
1758
        return BzrDir5(transport, self)
 
 
1760
    def __return_repository_format(self):
 
 
1761
        """Circular import protection."""
 
 
1762
        from bzrlib.repofmt.weaverepo import RepositoryFormat5
 
 
1763
        return RepositoryFormat5()
 
 
1764
    repository_format = property(__return_repository_format)
 
 
1767
class BzrDirFormat6(BzrDirFormat):
 
 
1768
    """Bzr control format 6.
 
 
1770
    This format is a combined format for working tree, branch and repository.
 
 
1772
     - Format 2 working trees [always] 
 
 
1773
     - Format 4 branches [always] 
 
 
1774
     - Format 6 repositories [always]
 
 
1777
    _lock_class = lockable_files.TransportLock
 
 
1779
    def get_format_string(self):
 
 
1780
        """See BzrDirFormat.get_format_string()."""
 
 
1781
        return "Bazaar-NG branch, format 6\n"
 
 
1783
    def get_format_description(self):
 
 
1784
        """See BzrDirFormat.get_format_description()."""
 
 
1785
        return "All-in-one format 6"
 
 
1787
    def get_converter(self, format=None):
 
 
1788
        """See BzrDirFormat.get_converter()."""
 
 
1789
        # there is one and only one upgrade path here.
 
 
1790
        return ConvertBzrDir6ToMeta()
 
 
1792
    def _initialize_for_clone(self, url):
 
 
1793
        return self.initialize_on_transport(get_transport(url), _cloning=True)
 
 
1795
    def initialize_on_transport(self, transport, _cloning=False):
 
 
1796
        """Format 6 dirs always have working tree, branch and repository.
 
 
1798
        Except when they are being cloned.
 
 
1800
        from bzrlib.branch import BzrBranchFormat4
 
 
1801
        from bzrlib.repofmt.weaverepo import RepositoryFormat6
 
 
1802
        from bzrlib.workingtree import WorkingTreeFormat2
 
 
1803
        result = super(BzrDirFormat6, self).initialize_on_transport(transport)
 
 
1804
        RepositoryFormat6().initialize(result, _internal=True)
 
 
1806
            branch = BzrBranchFormat4().initialize(result)
 
 
1808
                WorkingTreeFormat2().initialize(result)
 
 
1809
            except errors.NotLocalUrl:
 
 
1810
                # Even though we can't access the working tree, we need to
 
 
1811
                # create its control files.
 
 
1812
                WorkingTreeFormat2().stub_initialize_remote(branch.control_files)
 
 
1815
    def _open(self, transport):
 
 
1816
        """See BzrDirFormat._open."""
 
 
1817
        return BzrDir6(transport, self)
 
 
1819
    def __return_repository_format(self):
 
 
1820
        """Circular import protection."""
 
 
1821
        from bzrlib.repofmt.weaverepo import RepositoryFormat6
 
 
1822
        return RepositoryFormat6()
 
 
1823
    repository_format = property(__return_repository_format)
 
 
1826
class BzrDirMetaFormat1(BzrDirFormat):
 
 
1827
    """Bzr meta control format 1
 
 
1829
    This is the first format with split out working tree, branch and repository
 
 
1832
     - Format 3 working trees [optional]
 
 
1833
     - Format 5 branches [optional]
 
 
1834
     - Format 7 repositories [optional]
 
 
1837
    _lock_class = lockdir.LockDir
 
 
1840
        self._workingtree_format = None
 
 
1841
        self._branch_format = None
 
 
1843
    def __eq__(self, other):
 
 
1844
        if other.__class__ is not self.__class__:
 
 
1846
        if other.repository_format != self.repository_format:
 
 
1848
        if other.workingtree_format != self.workingtree_format:
 
 
1852
    def __ne__(self, other):
 
 
1853
        return not self == other
 
 
1855
    def get_branch_format(self):
 
 
1856
        if self._branch_format is None:
 
 
1857
            from bzrlib.branch import BranchFormat
 
 
1858
            self._branch_format = BranchFormat.get_default_format()
 
 
1859
        return self._branch_format
 
 
1861
    def set_branch_format(self, format):
 
 
1862
        self._branch_format = format
 
 
1864
    def get_converter(self, format=None):
 
 
1865
        """See BzrDirFormat.get_converter()."""
 
 
1867
            format = BzrDirFormat.get_default_format()
 
 
1868
        if not isinstance(self, format.__class__):
 
 
1869
            # converting away from metadir is not implemented
 
 
1870
            raise NotImplementedError(self.get_converter)
 
 
1871
        return ConvertMetaToMeta(format)
 
 
1873
    def get_format_string(self):
 
 
1874
        """See BzrDirFormat.get_format_string()."""
 
 
1875
        return "Bazaar-NG meta directory, format 1\n"
 
 
1877
    def get_format_description(self):
 
 
1878
        """See BzrDirFormat.get_format_description()."""
 
 
1879
        return "Meta directory format 1"
 
 
1881
    def _open(self, transport):
 
 
1882
        """See BzrDirFormat._open."""
 
 
1883
        return BzrDirMeta1(transport, self)
 
 
1885
    def __return_repository_format(self):
 
 
1886
        """Circular import protection."""
 
 
1887
        if getattr(self, '_repository_format', None):
 
 
1888
            return self._repository_format
 
 
1889
        from bzrlib.repository import RepositoryFormat
 
 
1890
        return RepositoryFormat.get_default_format()
 
 
1892
    def __set_repository_format(self, value):
 
 
1893
        """Allow changing the repository format for metadir formats."""
 
 
1894
        self._repository_format = value
 
 
1896
    repository_format = property(__return_repository_format, __set_repository_format)
 
 
1898
    def __get_workingtree_format(self):
 
 
1899
        if self._workingtree_format is None:
 
 
1900
            from bzrlib.workingtree import WorkingTreeFormat
 
 
1901
            self._workingtree_format = WorkingTreeFormat.get_default_format()
 
 
1902
        return self._workingtree_format
 
 
1904
    def __set_workingtree_format(self, wt_format):
 
 
1905
        self._workingtree_format = wt_format
 
 
1907
    workingtree_format = property(__get_workingtree_format,
 
 
1908
                                  __set_workingtree_format)
 
 
1911
# Register bzr control format
 
 
1912
BzrDirFormat.register_control_format(BzrDirFormat)
 
 
1914
# Register bzr formats
 
 
1915
BzrDirFormat.register_format(BzrDirFormat4())
 
 
1916
BzrDirFormat.register_format(BzrDirFormat5())
 
 
1917
BzrDirFormat.register_format(BzrDirFormat6())
 
 
1918
__default_format = BzrDirMetaFormat1()
 
 
1919
BzrDirFormat.register_format(__default_format)
 
 
1920
BzrDirFormat._default_format = __default_format
 
 
1923
class Converter(object):
 
 
1924
    """Converts a disk format object from one format to another."""
 
 
1926
    def convert(self, to_convert, pb):
 
 
1927
        """Perform the conversion of to_convert, giving feedback via pb.
 
 
1929
        :param to_convert: The disk object to convert.
 
 
1930
        :param pb: a progress bar to use for progress information.
 
 
1933
    def step(self, message):
 
 
1934
        """Update the pb by a step."""
 
 
1936
        self.pb.update(message, self.count, self.total)
 
 
1939
class ConvertBzrDir4To5(Converter):
 
 
1940
    """Converts format 4 bzr dirs to format 5."""
 
 
1943
        super(ConvertBzrDir4To5, self).__init__()
 
 
1944
        self.converted_revs = set()
 
 
1945
        self.absent_revisions = set()
 
 
1949
    def convert(self, to_convert, pb):
 
 
1950
        """See Converter.convert()."""
 
 
1951
        self.bzrdir = to_convert
 
 
1953
        self.pb.note('starting upgrade from format 4 to 5')
 
 
1954
        if isinstance(self.bzrdir.transport, LocalTransport):
 
 
1955
            self.bzrdir.get_workingtree_transport(None).delete('stat-cache')
 
 
1956
        self._convert_to_weaves()
 
 
1957
        return BzrDir.open(self.bzrdir.root_transport.base)
 
 
1959
    def _convert_to_weaves(self):
 
 
1960
        self.pb.note('note: upgrade may be faster if all store files are ungzipped first')
 
 
1963
            stat = self.bzrdir.transport.stat('weaves')
 
 
1964
            if not S_ISDIR(stat.st_mode):
 
 
1965
                self.bzrdir.transport.delete('weaves')
 
 
1966
                self.bzrdir.transport.mkdir('weaves')
 
 
1967
        except errors.NoSuchFile:
 
 
1968
            self.bzrdir.transport.mkdir('weaves')
 
 
1969
        # deliberately not a WeaveFile as we want to build it up slowly.
 
 
1970
        self.inv_weave = Weave('inventory')
 
 
1971
        # holds in-memory weaves for all files
 
 
1972
        self.text_weaves = {}
 
 
1973
        self.bzrdir.transport.delete('branch-format')
 
 
1974
        self.branch = self.bzrdir.open_branch()
 
 
1975
        self._convert_working_inv()
 
 
1976
        rev_history = self.branch.revision_history()
 
 
1977
        # to_read is a stack holding the revisions we still need to process;
 
 
1978
        # appending to it adds new highest-priority revisions
 
 
1979
        self.known_revisions = set(rev_history)
 
 
1980
        self.to_read = rev_history[-1:]
 
 
1982
            rev_id = self.to_read.pop()
 
 
1983
            if (rev_id not in self.revisions
 
 
1984
                and rev_id not in self.absent_revisions):
 
 
1985
                self._load_one_rev(rev_id)
 
 
1987
        to_import = self._make_order()
 
 
1988
        for i, rev_id in enumerate(to_import):
 
 
1989
            self.pb.update('converting revision', i, len(to_import))
 
 
1990
            self._convert_one_rev(rev_id)
 
 
1992
        self._write_all_weaves()
 
 
1993
        self._write_all_revs()
 
 
1994
        self.pb.note('upgraded to weaves:')
 
 
1995
        self.pb.note('  %6d revisions and inventories', len(self.revisions))
 
 
1996
        self.pb.note('  %6d revisions not present', len(self.absent_revisions))
 
 
1997
        self.pb.note('  %6d texts', self.text_count)
 
 
1998
        self._cleanup_spare_files_after_format4()
 
 
1999
        self.branch.control_files.put_utf8('branch-format', BzrDirFormat5().get_format_string())
 
 
2001
    def _cleanup_spare_files_after_format4(self):
 
 
2002
        # FIXME working tree upgrade foo.
 
 
2003
        for n in 'merged-patches', 'pending-merged-patches':
 
 
2005
                ## assert os.path.getsize(p) == 0
 
 
2006
                self.bzrdir.transport.delete(n)
 
 
2007
            except errors.NoSuchFile:
 
 
2009
        self.bzrdir.transport.delete_tree('inventory-store')
 
 
2010
        self.bzrdir.transport.delete_tree('text-store')
 
 
2012
    def _convert_working_inv(self):
 
 
2013
        inv = xml4.serializer_v4.read_inventory(
 
 
2014
                    self.branch.control_files.get('inventory'))
 
 
2015
        new_inv_xml = xml5.serializer_v5.write_inventory_to_string(inv, working=True)
 
 
2016
        # FIXME inventory is a working tree change.
 
 
2017
        self.branch.control_files.put('inventory', StringIO(new_inv_xml))
 
 
2019
    def _write_all_weaves(self):
 
 
2020
        controlweaves = WeaveStore(self.bzrdir.transport, prefixed=False)
 
 
2021
        weave_transport = self.bzrdir.transport.clone('weaves')
 
 
2022
        weaves = WeaveStore(weave_transport, prefixed=False)
 
 
2023
        transaction = WriteTransaction()
 
 
2027
            for file_id, file_weave in self.text_weaves.items():
 
 
2028
                self.pb.update('writing weave', i, len(self.text_weaves))
 
 
2029
                weaves._put_weave(file_id, file_weave, transaction)
 
 
2031
            self.pb.update('inventory', 0, 1)
 
 
2032
            controlweaves._put_weave('inventory', self.inv_weave, transaction)
 
 
2033
            self.pb.update('inventory', 1, 1)
 
 
2037
    def _write_all_revs(self):
 
 
2038
        """Write all revisions out in new form."""
 
 
2039
        self.bzrdir.transport.delete_tree('revision-store')
 
 
2040
        self.bzrdir.transport.mkdir('revision-store')
 
 
2041
        revision_transport = self.bzrdir.transport.clone('revision-store')
 
 
2043
        _revision_store = TextRevisionStore(TextStore(revision_transport,
 
 
2047
            transaction = WriteTransaction()
 
 
2048
            for i, rev_id in enumerate(self.converted_revs):
 
 
2049
                self.pb.update('write revision', i, len(self.converted_revs))
 
 
2050
                _revision_store.add_revision(self.revisions[rev_id], transaction)
 
 
2054
    def _load_one_rev(self, rev_id):
 
 
2055
        """Load a revision object into memory.
 
 
2057
        Any parents not either loaded or abandoned get queued to be
 
 
2059
        self.pb.update('loading revision',
 
 
2060
                       len(self.revisions),
 
 
2061
                       len(self.known_revisions))
 
 
2062
        if not self.branch.repository.has_revision(rev_id):
 
 
2064
            self.pb.note('revision {%s} not present in branch; '
 
 
2065
                         'will be converted as a ghost',
 
 
2067
            self.absent_revisions.add(rev_id)
 
 
2069
            rev = self.branch.repository._revision_store.get_revision(rev_id,
 
 
2070
                self.branch.repository.get_transaction())
 
 
2071
            for parent_id in rev.parent_ids:
 
 
2072
                self.known_revisions.add(parent_id)
 
 
2073
                self.to_read.append(parent_id)
 
 
2074
            self.revisions[rev_id] = rev
 
 
2076
    def _load_old_inventory(self, rev_id):
 
 
2077
        old_inv_xml = self.branch.repository.inventory_store.get(rev_id).read()
 
 
2078
        inv = xml4.serializer_v4.read_inventory_from_string(old_inv_xml)
 
 
2079
        inv.revision_id = rev_id
 
 
2080
        rev = self.revisions[rev_id]
 
 
2083
    def _load_updated_inventory(self, rev_id):
 
 
2084
        inv_xml = self.inv_weave.get_text(rev_id)
 
 
2085
        inv = xml5.serializer_v5.read_inventory_from_string(inv_xml, rev_id)
 
 
2088
    def _convert_one_rev(self, rev_id):
 
 
2089
        """Convert revision and all referenced objects to new format."""
 
 
2090
        rev = self.revisions[rev_id]
 
 
2091
        inv = self._load_old_inventory(rev_id)
 
 
2092
        present_parents = [p for p in rev.parent_ids
 
 
2093
                           if p not in self.absent_revisions]
 
 
2094
        self._convert_revision_contents(rev, inv, present_parents)
 
 
2095
        self._store_new_inv(rev, inv, present_parents)
 
 
2096
        self.converted_revs.add(rev_id)
 
 
2098
    def _store_new_inv(self, rev, inv, present_parents):
 
 
2099
        new_inv_xml = xml5.serializer_v5.write_inventory_to_string(inv)
 
 
2100
        new_inv_sha1 = sha_string(new_inv_xml)
 
 
2101
        self.inv_weave.add_lines(rev.revision_id,
 
 
2103
                                 new_inv_xml.splitlines(True))
 
 
2104
        rev.inventory_sha1 = new_inv_sha1
 
 
2106
    def _convert_revision_contents(self, rev, inv, present_parents):
 
 
2107
        """Convert all the files within a revision.
 
 
2109
        Also upgrade the inventory to refer to the text revision ids."""
 
 
2110
        rev_id = rev.revision_id
 
 
2111
        mutter('converting texts of revision {%s}',
 
 
2113
        parent_invs = map(self._load_updated_inventory, present_parents)
 
 
2114
        entries = inv.iter_entries()
 
 
2116
        for path, ie in entries:
 
 
2117
            self._convert_file_version(rev, ie, parent_invs)
 
 
2119
    def _convert_file_version(self, rev, ie, parent_invs):
 
 
2120
        """Convert one version of one file.
 
 
2122
        The file needs to be added into the weave if it is a merge
 
 
2123
        of >=2 parents or if it's changed from its parent.
 
 
2125
        file_id = ie.file_id
 
 
2126
        rev_id = rev.revision_id
 
 
2127
        w = self.text_weaves.get(file_id)
 
 
2130
            self.text_weaves[file_id] = w
 
 
2131
        text_changed = False
 
 
2132
        parent_candiate_entries = ie.parent_candidates(parent_invs)
 
 
2133
        heads = graph.Graph(self).heads(parent_candiate_entries.keys())
 
 
2134
        # XXX: Note that this is unordered - and this is tolerable because 
 
 
2135
        # the previous code was also unordered.
 
 
2136
        previous_entries = dict((head, parent_candiate_entries[head]) for head
 
 
2138
        self.snapshot_ie(previous_entries, ie, w, rev_id)
 
 
2141
    @symbol_versioning.deprecated_method(symbol_versioning.one_one)
 
 
2142
    def get_parents(self, revision_ids):
 
 
2143
        for revision_id in revision_ids:
 
 
2144
            yield self.revisions[revision_id].parent_ids
 
 
2146
    def get_parent_map(self, revision_ids):
 
 
2147
        """See graph._StackedParentsProvider.get_parent_map"""
 
 
2148
        return dict((revision_id, self.revisions[revision_id])
 
 
2149
                    for revision_id in revision_ids
 
 
2150
                     if revision_id in self.revisions)
 
 
2152
    def snapshot_ie(self, previous_revisions, ie, w, rev_id):
 
 
2153
        # TODO: convert this logic, which is ~= snapshot to
 
 
2154
        # a call to:. This needs the path figured out. rather than a work_tree
 
 
2155
        # a v4 revision_tree can be given, or something that looks enough like
 
 
2156
        # one to give the file content to the entry if it needs it.
 
 
2157
        # and we need something that looks like a weave store for snapshot to 
 
 
2159
        #ie.snapshot(rev, PATH, previous_revisions, REVISION_TREE, InMemoryWeaveStore(self.text_weaves))
 
 
2160
        if len(previous_revisions) == 1:
 
 
2161
            previous_ie = previous_revisions.values()[0]
 
 
2162
            if ie._unchanged(previous_ie):
 
 
2163
                ie.revision = previous_ie.revision
 
 
2166
            text = self.branch.repository.weave_store.get(ie.text_id)
 
 
2167
            file_lines = text.readlines()
 
 
2168
            w.add_lines(rev_id, previous_revisions, file_lines)
 
 
2169
            self.text_count += 1
 
 
2171
            w.add_lines(rev_id, previous_revisions, [])
 
 
2172
        ie.revision = rev_id
 
 
2174
    def _make_order(self):
 
 
2175
        """Return a suitable order for importing revisions.
 
 
2177
        The order must be such that an revision is imported after all
 
 
2178
        its (present) parents.
 
 
2180
        todo = set(self.revisions.keys())
 
 
2181
        done = self.absent_revisions.copy()
 
 
2184
            # scan through looking for a revision whose parents
 
 
2186
            for rev_id in sorted(list(todo)):
 
 
2187
                rev = self.revisions[rev_id]
 
 
2188
                parent_ids = set(rev.parent_ids)
 
 
2189
                if parent_ids.issubset(done):
 
 
2190
                    # can take this one now
 
 
2191
                    order.append(rev_id)
 
 
2197
class ConvertBzrDir5To6(Converter):
 
 
2198
    """Converts format 5 bzr dirs to format 6."""
 
 
2200
    def convert(self, to_convert, pb):
 
 
2201
        """See Converter.convert()."""
 
 
2202
        self.bzrdir = to_convert
 
 
2204
        self.pb.note('starting upgrade from format 5 to 6')
 
 
2205
        self._convert_to_prefixed()
 
 
2206
        return BzrDir.open(self.bzrdir.root_transport.base)
 
 
2208
    def _convert_to_prefixed(self):
 
 
2209
        from bzrlib.store import TransportStore
 
 
2210
        self.bzrdir.transport.delete('branch-format')
 
 
2211
        for store_name in ["weaves", "revision-store"]:
 
 
2212
            self.pb.note("adding prefixes to %s" % store_name)
 
 
2213
            store_transport = self.bzrdir.transport.clone(store_name)
 
 
2214
            store = TransportStore(store_transport, prefixed=True)
 
 
2215
            for urlfilename in store_transport.list_dir('.'):
 
 
2216
                filename = urlutils.unescape(urlfilename)
 
 
2217
                if (filename.endswith(".weave") or
 
 
2218
                    filename.endswith(".gz") or
 
 
2219
                    filename.endswith(".sig")):
 
 
2220
                    file_id = os.path.splitext(filename)[0]
 
 
2223
                prefix_dir = store.hash_prefix(file_id)
 
 
2224
                # FIXME keep track of the dirs made RBC 20060121
 
 
2226
                    store_transport.move(filename, prefix_dir + '/' + filename)
 
 
2227
                except errors.NoSuchFile: # catches missing dirs strangely enough
 
 
2228
                    store_transport.mkdir(prefix_dir)
 
 
2229
                    store_transport.move(filename, prefix_dir + '/' + filename)
 
 
2230
        self.bzrdir._control_files.put_utf8('branch-format', BzrDirFormat6().get_format_string())
 
 
2233
class ConvertBzrDir6ToMeta(Converter):
 
 
2234
    """Converts format 6 bzr dirs to metadirs."""
 
 
2236
    def convert(self, to_convert, pb):
 
 
2237
        """See Converter.convert()."""
 
 
2238
        from bzrlib.repofmt.weaverepo import RepositoryFormat7
 
 
2239
        from bzrlib.branch import BzrBranchFormat5
 
 
2240
        self.bzrdir = to_convert
 
 
2243
        self.total = 20 # the steps we know about
 
 
2244
        self.garbage_inventories = []
 
 
2246
        self.pb.note('starting upgrade from format 6 to metadir')
 
 
2247
        self.bzrdir._control_files.put_utf8('branch-format', "Converting to format 6")
 
 
2248
        # its faster to move specific files around than to open and use the apis...
 
 
2249
        # first off, nuke ancestry.weave, it was never used.
 
 
2251
            self.step('Removing ancestry.weave')
 
 
2252
            self.bzrdir.transport.delete('ancestry.weave')
 
 
2253
        except errors.NoSuchFile:
 
 
2255
        # find out whats there
 
 
2256
        self.step('Finding branch files')
 
 
2257
        last_revision = self.bzrdir.open_branch().last_revision()
 
 
2258
        bzrcontents = self.bzrdir.transport.list_dir('.')
 
 
2259
        for name in bzrcontents:
 
 
2260
            if name.startswith('basis-inventory.'):
 
 
2261
                self.garbage_inventories.append(name)
 
 
2262
        # create new directories for repository, working tree and branch
 
 
2263
        self.dir_mode = self.bzrdir._control_files._dir_mode
 
 
2264
        self.file_mode = self.bzrdir._control_files._file_mode
 
 
2265
        repository_names = [('inventory.weave', True),
 
 
2266
                            ('revision-store', True),
 
 
2268
        self.step('Upgrading repository  ')
 
 
2269
        self.bzrdir.transport.mkdir('repository', mode=self.dir_mode)
 
 
2270
        self.make_lock('repository')
 
 
2271
        # we hard code the formats here because we are converting into
 
 
2272
        # the meta format. The meta format upgrader can take this to a 
 
 
2273
        # future format within each component.
 
 
2274
        self.put_format('repository', RepositoryFormat7())
 
 
2275
        for entry in repository_names:
 
 
2276
            self.move_entry('repository', entry)
 
 
2278
        self.step('Upgrading branch      ')
 
 
2279
        self.bzrdir.transport.mkdir('branch', mode=self.dir_mode)
 
 
2280
        self.make_lock('branch')
 
 
2281
        self.put_format('branch', BzrBranchFormat5())
 
 
2282
        branch_files = [('revision-history', True),
 
 
2283
                        ('branch-name', True),
 
 
2285
        for entry in branch_files:
 
 
2286
            self.move_entry('branch', entry)
 
 
2288
        checkout_files = [('pending-merges', True),
 
 
2289
                          ('inventory', True),
 
 
2290
                          ('stat-cache', False)]
 
 
2291
        # If a mandatory checkout file is not present, the branch does not have
 
 
2292
        # a functional checkout. Do not create a checkout in the converted
 
 
2294
        for name, mandatory in checkout_files:
 
 
2295
            if mandatory and name not in bzrcontents:
 
 
2296
                has_checkout = False
 
 
2300
        if not has_checkout:
 
 
2301
            self.pb.note('No working tree.')
 
 
2302
            # If some checkout files are there, we may as well get rid of them.
 
 
2303
            for name, mandatory in checkout_files:
 
 
2304
                if name in bzrcontents:
 
 
2305
                    self.bzrdir.transport.delete(name)
 
 
2307
            from bzrlib.workingtree import WorkingTreeFormat3
 
 
2308
            self.step('Upgrading working tree')
 
 
2309
            self.bzrdir.transport.mkdir('checkout', mode=self.dir_mode)
 
 
2310
            self.make_lock('checkout')
 
 
2312
                'checkout', WorkingTreeFormat3())
 
 
2313
            self.bzrdir.transport.delete_multi(
 
 
2314
                self.garbage_inventories, self.pb)
 
 
2315
            for entry in checkout_files:
 
 
2316
                self.move_entry('checkout', entry)
 
 
2317
            if last_revision is not None:
 
 
2318
                self.bzrdir._control_files.put_utf8(
 
 
2319
                    'checkout/last-revision', last_revision)
 
 
2320
        self.bzrdir._control_files.put_utf8(
 
 
2321
            'branch-format', BzrDirMetaFormat1().get_format_string())
 
 
2322
        return BzrDir.open(self.bzrdir.root_transport.base)
 
 
2324
    def make_lock(self, name):
 
 
2325
        """Make a lock for the new control dir name."""
 
 
2326
        self.step('Make %s lock' % name)
 
 
2327
        ld = lockdir.LockDir(self.bzrdir.transport,
 
 
2329
                             file_modebits=self.file_mode,
 
 
2330
                             dir_modebits=self.dir_mode)
 
 
2333
    def move_entry(self, new_dir, entry):
 
 
2334
        """Move then entry name into new_dir."""
 
 
2336
        mandatory = entry[1]
 
 
2337
        self.step('Moving %s' % name)
 
 
2339
            self.bzrdir.transport.move(name, '%s/%s' % (new_dir, name))
 
 
2340
        except errors.NoSuchFile:
 
 
2344
    def put_format(self, dirname, format):
 
 
2345
        self.bzrdir._control_files.put_utf8('%s/format' % dirname, format.get_format_string())
 
 
2348
class ConvertMetaToMeta(Converter):
 
 
2349
    """Converts the components of metadirs."""
 
 
2351
    def __init__(self, target_format):
 
 
2352
        """Create a metadir to metadir converter.
 
 
2354
        :param target_format: The final metadir format that is desired.
 
 
2356
        self.target_format = target_format
 
 
2358
    def convert(self, to_convert, pb):
 
 
2359
        """See Converter.convert()."""
 
 
2360
        self.bzrdir = to_convert
 
 
2364
        self.step('checking repository format')
 
 
2366
            repo = self.bzrdir.open_repository()
 
 
2367
        except errors.NoRepositoryPresent:
 
 
2370
            if not isinstance(repo._format, self.target_format.repository_format.__class__):
 
 
2371
                from bzrlib.repository import CopyConverter
 
 
2372
                self.pb.note('starting repository conversion')
 
 
2373
                converter = CopyConverter(self.target_format.repository_format)
 
 
2374
                converter.convert(repo, pb)
 
 
2376
            branch = self.bzrdir.open_branch()
 
 
2377
        except errors.NotBranchError:
 
 
2380
            # TODO: conversions of Branch and Tree should be done by
 
 
2381
            # InterXFormat lookups
 
 
2382
            # Avoid circular imports
 
 
2383
            from bzrlib import branch as _mod_branch
 
 
2384
            if (branch._format.__class__ is _mod_branch.BzrBranchFormat5 and
 
 
2385
                self.target_format.get_branch_format().__class__ is
 
 
2386
                _mod_branch.BzrBranchFormat6):
 
 
2387
                branch_converter = _mod_branch.Converter5to6()
 
 
2388
                branch_converter.convert(branch)
 
 
2390
            tree = self.bzrdir.open_workingtree(recommend_upgrade=False)
 
 
2391
        except (errors.NoWorkingTree, errors.NotLocalUrl):
 
 
2394
            # TODO: conversions of Branch and Tree should be done by
 
 
2395
            # InterXFormat lookups
 
 
2396
            if (isinstance(tree, workingtree.WorkingTree3) and
 
 
2397
                not isinstance(tree, workingtree_4.WorkingTree4) and
 
 
2398
                isinstance(self.target_format.workingtree_format,
 
 
2399
                    workingtree_4.WorkingTreeFormat4)):
 
 
2400
                workingtree_4.Converter3to4().convert(tree)
 
 
2404
# This is not in remote.py because it's small, and needs to be registered.
 
 
2405
# Putting it in remote.py creates a circular import problem.
 
 
2406
# we can make it a lazy object if the control formats is turned into something
 
 
2408
class RemoteBzrDirFormat(BzrDirMetaFormat1):
 
 
2409
    """Format representing bzrdirs accessed via a smart server"""
 
 
2411
    def get_format_description(self):
 
 
2412
        return 'bzr remote bzrdir'
 
 
2415
    def probe_transport(klass, transport):
 
 
2416
        """Return a RemoteBzrDirFormat object if it looks possible."""
 
 
2418
            medium = transport.get_smart_medium()
 
 
2419
        except (NotImplementedError, AttributeError,
 
 
2420
                errors.TransportNotPossible, errors.NoSmartMedium):
 
 
2421
            # no smart server, so not a branch for this format type.
 
 
2422
            raise errors.NotBranchError(path=transport.base)
 
 
2424
            # Decline to open it if the server doesn't support our required
 
 
2425
            # version (2) so that the VFS-based transport will do it.
 
 
2427
                server_version = medium.protocol_version()
 
 
2428
            except errors.SmartProtocolError:
 
 
2429
                # Apparently there's no usable smart server there, even though
 
 
2430
                # the medium supports the smart protocol.
 
 
2431
                raise errors.NotBranchError(path=transport.base)
 
 
2432
            if server_version != 2:
 
 
2433
                raise errors.NotBranchError(path=transport.base)
 
 
2436
    def initialize_on_transport(self, transport):
 
 
2438
            # hand off the request to the smart server
 
 
2439
            client_medium = transport.get_smart_medium()
 
 
2440
        except errors.NoSmartMedium:
 
 
2441
            # TODO: lookup the local format from a server hint.
 
 
2442
            local_dir_format = BzrDirMetaFormat1()
 
 
2443
            return local_dir_format.initialize_on_transport(transport)
 
 
2444
        client = _SmartClient(client_medium, transport.base)
 
 
2445
        path = client.remote_path_from_transport(transport)
 
 
2446
        response = client.call('BzrDirFormat.initialize', path)
 
 
2447
        if response[0] != 'ok':
 
 
2448
            raise errors.SmartProtocolError('unexpected response code %s' % (response,))
 
 
2449
        return remote.RemoteBzrDir(transport)
 
 
2451
    def _open(self, transport):
 
 
2452
        return remote.RemoteBzrDir(transport)
 
 
2454
    def __eq__(self, other):
 
 
2455
        if not isinstance(other, RemoteBzrDirFormat):
 
 
2457
        return self.get_format_description() == other.get_format_description()
 
 
2460
BzrDirFormat.register_control_server_format(RemoteBzrDirFormat)
 
 
2463
class BzrDirFormatInfo(object):
 
 
2465
    def __init__(self, native, deprecated, hidden, experimental):
 
 
2466
        self.deprecated = deprecated
 
 
2467
        self.native = native
 
 
2468
        self.hidden = hidden
 
 
2469
        self.experimental = experimental
 
 
2472
class BzrDirFormatRegistry(registry.Registry):
 
 
2473
    """Registry of user-selectable BzrDir subformats.
 
 
2475
    Differs from BzrDirFormat._control_formats in that it provides sub-formats,
 
 
2476
    e.g. BzrDirMeta1 with weave repository.  Also, it's more user-oriented.
 
 
2480
        """Create a BzrDirFormatRegistry."""
 
 
2481
        self._aliases = set()
 
 
2482
        super(BzrDirFormatRegistry, self).__init__()
 
 
2485
        """Return a set of the format names which are aliases."""
 
 
2486
        return frozenset(self._aliases)
 
 
2488
    def register_metadir(self, key,
 
 
2489
             repository_format, help, native=True, deprecated=False,
 
 
2495
        """Register a metadir subformat.
 
 
2497
        These all use a BzrDirMetaFormat1 bzrdir, but can be parameterized
 
 
2498
        by the Repository format.
 
 
2500
        :param repository_format: The fully-qualified repository format class
 
 
2502
        :param branch_format: Fully-qualified branch format class name as
 
 
2504
        :param tree_format: Fully-qualified tree format class name as
 
 
2507
        # This should be expanded to support setting WorkingTree and Branch
 
 
2508
        # formats, once BzrDirMetaFormat1 supports that.
 
 
2509
        def _load(full_name):
 
 
2510
            mod_name, factory_name = full_name.rsplit('.', 1)
 
 
2512
                mod = __import__(mod_name, globals(), locals(),
 
 
2514
            except ImportError, e:
 
 
2515
                raise ImportError('failed to load %s: %s' % (full_name, e))
 
 
2517
                factory = getattr(mod, factory_name)
 
 
2518
            except AttributeError:
 
 
2519
                raise AttributeError('no factory %s in module %r'
 
 
2524
            bd = BzrDirMetaFormat1()
 
 
2525
            if branch_format is not None:
 
 
2526
                bd.set_branch_format(_load(branch_format))
 
 
2527
            if tree_format is not None:
 
 
2528
                bd.workingtree_format = _load(tree_format)
 
 
2529
            if repository_format is not None:
 
 
2530
                bd.repository_format = _load(repository_format)
 
 
2532
        self.register(key, helper, help, native, deprecated, hidden,
 
 
2533
            experimental, alias)
 
 
2535
    def register(self, key, factory, help, native=True, deprecated=False,
 
 
2536
                 hidden=False, experimental=False, alias=False):
 
 
2537
        """Register a BzrDirFormat factory.
 
 
2539
        The factory must be a callable that takes one parameter: the key.
 
 
2540
        It must produce an instance of the BzrDirFormat when called.
 
 
2542
        This function mainly exists to prevent the info object from being
 
 
2545
        registry.Registry.register(self, key, factory, help,
 
 
2546
            BzrDirFormatInfo(native, deprecated, hidden, experimental))
 
 
2548
            self._aliases.add(key)
 
 
2550
    def register_lazy(self, key, module_name, member_name, help, native=True,
 
 
2551
        deprecated=False, hidden=False, experimental=False, alias=False):
 
 
2552
        registry.Registry.register_lazy(self, key, module_name, member_name,
 
 
2553
            help, BzrDirFormatInfo(native, deprecated, hidden, experimental))
 
 
2555
            self._aliases.add(key)
 
 
2557
    def set_default(self, key):
 
 
2558
        """Set the 'default' key to be a clone of the supplied key.
 
 
2560
        This method must be called once and only once.
 
 
2562
        registry.Registry.register(self, 'default', self.get(key),
 
 
2563
            self.get_help(key), info=self.get_info(key))
 
 
2564
        self._aliases.add('default')
 
 
2566
    def set_default_repository(self, key):
 
 
2567
        """Set the FormatRegistry default and Repository default.
 
 
2569
        This is a transitional method while Repository.set_default_format
 
 
2572
        if 'default' in self:
 
 
2573
            self.remove('default')
 
 
2574
        self.set_default(key)
 
 
2575
        format = self.get('default')()
 
 
2577
    def make_bzrdir(self, key):
 
 
2578
        return self.get(key)()
 
 
2580
    def help_topic(self, topic):
 
 
2581
        output = textwrap.dedent("""\
 
 
2582
            These formats can be used for creating branches, working trees, and
 
 
2586
        default_realkey = None
 
 
2587
        default_help = self.get_help('default')
 
 
2589
        for key in self.keys():
 
 
2590
            if key == 'default':
 
 
2592
            help = self.get_help(key)
 
 
2593
            if help == default_help:
 
 
2594
                default_realkey = key
 
 
2596
                help_pairs.append((key, help))
 
 
2598
        def wrapped(key, help, info):
 
 
2600
                help = '(native) ' + help
 
 
2601
            return ':%s:\n%s\n\n' % (key, 
 
 
2602
                    textwrap.fill(help, initial_indent='    ', 
 
 
2603
                    subsequent_indent='    '))
 
 
2604
        if default_realkey is not None:
 
 
2605
            output += wrapped(default_realkey, '(default) %s' % default_help,
 
 
2606
                              self.get_info('default'))
 
 
2607
        deprecated_pairs = []
 
 
2608
        experimental_pairs = []
 
 
2609
        for key, help in help_pairs:
 
 
2610
            info = self.get_info(key)
 
 
2613
            elif info.deprecated:
 
 
2614
                deprecated_pairs.append((key, help))
 
 
2615
            elif info.experimental:
 
 
2616
                experimental_pairs.append((key, help))
 
 
2618
                output += wrapped(key, help, info)
 
 
2619
        if len(experimental_pairs) > 0:
 
 
2620
            output += "Experimental formats are shown below.\n\n"
 
 
2621
            for key, help in experimental_pairs:
 
 
2622
                info = self.get_info(key)
 
 
2623
                output += wrapped(key, help, info)
 
 
2624
        if len(deprecated_pairs) > 0:
 
 
2625
            output += "Deprecated formats are shown below.\n\n"
 
 
2626
            for key, help in deprecated_pairs:
 
 
2627
                info = self.get_info(key)
 
 
2628
                output += wrapped(key, help, info)
 
 
2633
class RepositoryAcquisitionPolicy(object):
 
 
2634
    """Abstract base class for repository acquisition policies.
 
 
2636
    A repository acquisition policy decides how a BzrDir acquires a repository
 
 
2637
    for a branch that is being created.  The most basic policy decision is
 
 
2638
    whether to create a new repository or use an existing one.
 
 
2641
    def configure_branch(self, branch):
 
 
2642
        """Apply any configuration data from this policy to the branch.
 
 
2644
        Default implementation does nothing.
 
 
2648
    def acquire_repository(self, make_working_trees=None, shared=False):
 
 
2649
        """Acquire a repository for this bzrdir.
 
 
2651
        Implementations may create a new repository or use a pre-exising
 
 
2653
        :param make_working_trees: If creating a repository, set
 
 
2654
            make_working_trees to this value (if non-None)
 
 
2655
        :param shared: If creating a repository, make it shared if True
 
 
2656
        :return: A repository
 
 
2658
        raise NotImplemented(RepositoryAcquisitionPolicy.acquire_repository)
 
 
2661
class CreateRepository(RepositoryAcquisitionPolicy):
 
 
2662
    """A policy of creating a new repository"""
 
 
2664
    def __init__(self, bzrdir):
 
 
2665
        RepositoryAcquisitionPolicy.__init__(self)
 
 
2666
        self._bzrdir = bzrdir
 
 
2668
    def acquire_repository(self, make_working_trees=None, shared=False):
 
 
2669
        """Implementation of RepositoryAcquisitionPolicy.acquire_repository
 
 
2671
        Creates the desired repository in the bzrdir we already have.
 
 
2673
        repository = self._bzrdir.create_repository(shared=shared)
 
 
2674
        if make_working_trees is not None:
 
 
2675
            repository.set_make_working_trees(make_working_trees)
 
 
2679
class UseExistingRepository(RepositoryAcquisitionPolicy):
 
 
2680
    """A policy of reusing an existing repository"""
 
 
2682
    def __init__(self, repository):
 
 
2683
        RepositoryAcquisitionPolicy.__init__(self)
 
 
2684
        self._repository = repository
 
 
2686
    def acquire_repository(self, make_working_trees=None, shared=False):
 
 
2687
        """Implementation of RepositoryAcquisitionPolicy.acquire_repository
 
 
2689
        Returns an existing repository to use
 
 
2691
        return self._repository
 
 
2694
format_registry = BzrDirFormatRegistry()
 
 
2695
format_registry.register('weave', BzrDirFormat6,
 
 
2696
    'Pre-0.8 format.  Slower than knit and does not'
 
 
2697
    ' support checkouts or shared repositories.',
 
 
2699
format_registry.register_metadir('knit',
 
 
2700
    'bzrlib.repofmt.knitrepo.RepositoryFormatKnit1',
 
 
2701
    'Format using knits.  Recommended for interoperation with bzr <= 0.14.',
 
 
2702
    branch_format='bzrlib.branch.BzrBranchFormat5',
 
 
2703
    tree_format='bzrlib.workingtree.WorkingTreeFormat3')
 
 
2704
format_registry.register_metadir('metaweave',
 
 
2705
    'bzrlib.repofmt.weaverepo.RepositoryFormat7',
 
 
2706
    'Transitional format in 0.8.  Slower than knit.',
 
 
2707
    branch_format='bzrlib.branch.BzrBranchFormat5',
 
 
2708
    tree_format='bzrlib.workingtree.WorkingTreeFormat3',
 
 
2710
format_registry.register_metadir('dirstate',
 
 
2711
    'bzrlib.repofmt.knitrepo.RepositoryFormatKnit1',
 
 
2712
    help='New in 0.15: Fast local operations. Compatible with bzr 0.8 and '
 
 
2713
        'above when accessed over the network.',
 
 
2714
    branch_format='bzrlib.branch.BzrBranchFormat5',
 
 
2715
    # this uses bzrlib.workingtree.WorkingTreeFormat4 because importing
 
 
2716
    # directly from workingtree_4 triggers a circular import.
 
 
2717
    tree_format='bzrlib.workingtree.WorkingTreeFormat4',
 
 
2719
format_registry.register_metadir('dirstate-tags',
 
 
2720
    'bzrlib.repofmt.knitrepo.RepositoryFormatKnit1',
 
 
2721
    help='New in 0.15: Fast local operations and improved scaling for '
 
 
2722
        'network operations. Additionally adds support for tags.'
 
 
2723
        ' Incompatible with bzr < 0.15.',
 
 
2724
    branch_format='bzrlib.branch.BzrBranchFormat6',
 
 
2725
    tree_format='bzrlib.workingtree.WorkingTreeFormat4',
 
 
2727
format_registry.register_metadir('rich-root',
 
 
2728
    'bzrlib.repofmt.knitrepo.RepositoryFormatKnit4',
 
 
2729
    help='New in 1.0.  Better handling of tree roots.  Incompatible with'
 
 
2731
    branch_format='bzrlib.branch.BzrBranchFormat6',
 
 
2732
    tree_format='bzrlib.workingtree.WorkingTreeFormat4',
 
 
2734
format_registry.register_metadir('dirstate-with-subtree',
 
 
2735
    'bzrlib.repofmt.knitrepo.RepositoryFormatKnit3',
 
 
2736
    help='New in 0.15: Fast local operations and improved scaling for '
 
 
2737
        'network operations. Additionally adds support for versioning nested '
 
 
2738
        'bzr branches. Incompatible with bzr < 0.15.',
 
 
2739
    branch_format='bzrlib.branch.BzrBranchFormat6',
 
 
2740
    tree_format='bzrlib.workingtree.WorkingTreeFormat4',
 
 
2744
format_registry.register_metadir('pack-0.92',
 
 
2745
    'bzrlib.repofmt.pack_repo.RepositoryFormatKnitPack1',
 
 
2746
    help='New in 0.92: Pack-based format with data compatible with '
 
 
2747
        'dirstate-tags format repositories. Interoperates with '
 
 
2748
        'bzr repositories before 0.92 but cannot be read by bzr < 0.92. '
 
 
2749
        'Previously called knitpack-experimental.  '
 
 
2750
        'For more information, see '
 
 
2751
        'http://doc.bazaar-vcs.org/latest/developers/packrepo.html.',
 
 
2752
    branch_format='bzrlib.branch.BzrBranchFormat6',
 
 
2753
    tree_format='bzrlib.workingtree.WorkingTreeFormat4',
 
 
2755
format_registry.register_metadir('pack-0.92-subtree',
 
 
2756
    'bzrlib.repofmt.pack_repo.RepositoryFormatKnitPack3',
 
 
2757
    help='New in 0.92: Pack-based format with data compatible with '
 
 
2758
        'dirstate-with-subtree format repositories. Interoperates with '
 
 
2759
        'bzr repositories before 0.92 but cannot be read by bzr < 0.92. '
 
 
2760
        'Previously called knitpack-experimental.  '
 
 
2761
        'For more information, see '
 
 
2762
        'http://doc.bazaar-vcs.org/latest/developers/packrepo.html.',
 
 
2763
    branch_format='bzrlib.branch.BzrBranchFormat6',
 
 
2764
    tree_format='bzrlib.workingtree.WorkingTreeFormat4',
 
 
2768
format_registry.register_metadir('rich-root-pack',
 
 
2769
    'bzrlib.repofmt.pack_repo.RepositoryFormatKnitPack4',
 
 
2770
    help='New in 1.0: Pack-based format with data compatible with '
 
 
2771
        'rich-root format repositories. Incompatible with'
 
 
2773
    branch_format='bzrlib.branch.BzrBranchFormat6',
 
 
2774
    tree_format='bzrlib.workingtree.WorkingTreeFormat4',
 
 
2776
# The following two formats should always just be aliases.
 
 
2777
format_registry.register_metadir('development',
 
 
2778
    'bzrlib.repofmt.pack_repo.RepositoryFormatPackDevelopment0',
 
 
2779
    help='Current development format. Can convert data to and from pack-0.92 '
 
 
2780
        '(and anything compatible with pack-0.92) format repositories. '
 
 
2781
        'Repositories in this format can only be read by bzr.dev. '
 
 
2783
        'http://doc.bazaar-vcs.org/latest/developers/development-repo.html '
 
 
2785
    branch_format='bzrlib.branch.BzrBranchFormat6',
 
 
2786
    tree_format='bzrlib.workingtree.WorkingTreeFormat4',
 
 
2790
format_registry.register_metadir('development-subtree',
 
 
2791
    'bzrlib.repofmt.pack_repo.RepositoryFormatPackDevelopment0Subtree',
 
 
2792
    help='Current development format, subtree variant. Can convert data to and '
 
 
2793
        'from pack-0.92 (and anything compatible with pack-0.92) format '
 
 
2794
        'repositories. Repositories in this format can only be read by '
 
 
2795
        'bzr.dev. Please read '
 
 
2796
        'http://doc.bazaar-vcs.org/latest/developers/development-repo.html '
 
 
2798
    branch_format='bzrlib.branch.BzrBranchFormat6',
 
 
2799
    tree_format='bzrlib.workingtree.WorkingTreeFormat4',
 
 
2803
# And the development formats which the will have aliased one of follow:
 
 
2804
format_registry.register_metadir('development0',
 
 
2805
    'bzrlib.repofmt.pack_repo.RepositoryFormatPackDevelopment0',
 
 
2806
    help='Trivial rename of pack-0.92 to provide a development format. '
 
 
2808
        'http://doc.bazaar-vcs.org/latest/developers/development-repo.html '
 
 
2810
    branch_format='bzrlib.branch.BzrBranchFormat6',
 
 
2811
    tree_format='bzrlib.workingtree.WorkingTreeFormat4',
 
 
2815
format_registry.register_metadir('development0-subtree',
 
 
2816
    'bzrlib.repofmt.pack_repo.RepositoryFormatPackDevelopment0Subtree',
 
 
2817
    help='Trivial rename of pack-0.92-subtree to provide a development format. '
 
 
2819
        'http://doc.bazaar-vcs.org/latest/developers/development-repo.html '
 
 
2821
    branch_format='bzrlib.branch.BzrBranchFormat6',
 
 
2822
    tree_format='bzrlib.workingtree.WorkingTreeFormat4',
 
 
2826
format_registry.set_default('pack-0.92')