~bzr-pqm/bzr/bzr.dev

« back to all changes in this revision

Viewing changes to bzrlib/bzrdir.py

Merge bzr.dev, update to use new hooks.

Show diffs side-by-side

added added

removed removed

Lines of Context:
1
 
# Copyright (C) 2006-2010 Canonical Ltd
 
1
# Copyright (C) 2006-2011 Canonical Ltd
2
2
#
3
3
# This program is free software; you can redistribute it and/or modify
4
4
# it under the terms of the GNU General Public License as published by
25
25
objects returned.
26
26
"""
27
27
 
28
 
# TODO: Move old formats into a plugin to make this file smaller.
29
 
 
30
 
import os
31
28
import sys
32
 
import warnings
33
29
 
34
30
from bzrlib.lazy_import import lazy_import
35
31
lazy_import(globals(), """
36
 
from stat import S_ISDIR
37
 
 
38
32
import bzrlib
39
33
from bzrlib import (
40
 
    branch,
41
 
    config,
42
 
    controldir,
 
34
    branch as _mod_branch,
 
35
    cleanup,
43
36
    errors,
 
37
    fetch,
44
38
    graph,
45
39
    lockable_files,
46
40
    lockdir,
49
43
    remote,
50
44
    repository,
51
45
    revision as _mod_revision,
 
46
    transport as _mod_transport,
52
47
    ui,
53
48
    urlutils,
54
 
    versionedfile,
 
49
    vf_search,
55
50
    win32utils,
56
 
    workingtree,
 
51
    workingtree_3,
57
52
    workingtree_4,
58
 
    xml4,
59
 
    xml5,
60
 
    )
61
 
from bzrlib.osutils import (
62
 
    sha_string,
63
 
    )
64
 
from bzrlib.push import (
65
 
    PushResult,
66
 
    )
67
 
from bzrlib.repofmt import pack_repo
68
 
from bzrlib.smart.client import _SmartClient
69
 
from bzrlib.store.versioned import WeaveStore
70
 
from bzrlib.transactions import WriteTransaction
 
53
    )
 
54
from bzrlib.repofmt import knitpack_repo
71
55
from bzrlib.transport import (
72
56
    do_catching_redirections,
73
 
    get_transport,
74
57
    local,
75
58
    )
76
 
from bzrlib.weave import Weave
 
59
from bzrlib.i18n import gettext
77
60
""")
78
61
 
79
62
from bzrlib.trace import (
80
63
    mutter,
81
64
    note,
82
 
    warning,
83
65
    )
84
66
 
85
67
from bzrlib import (
86
 
    hooks,
 
68
    config,
 
69
    controldir,
87
70
    registry,
88
 
    symbol_versioning,
 
71
    )
 
72
from bzrlib.symbol_versioning import (
 
73
    deprecated_in,
 
74
    deprecated_method,
89
75
    )
90
76
 
91
77
 
138
124
            # No repo, no problem.
139
125
            pass
140
126
 
141
 
    @staticmethod
142
 
    def _check_supported(format, allow_unsupported,
143
 
        recommend_upgrade=True,
144
 
        basedir=None):
145
 
        """Give an error or warning on old formats.
146
 
 
147
 
        :param format: may be any kind of format - workingtree, branch,
148
 
        or repository.
149
 
 
150
 
        :param allow_unsupported: If true, allow opening
151
 
        formats that are strongly deprecated, and which may
152
 
        have limited functionality.
153
 
 
154
 
        :param recommend_upgrade: If true (default), warn
155
 
        the user through the ui object that they may wish
156
 
        to upgrade the object.
157
 
        """
158
 
        # TODO: perhaps move this into a base Format class; it's not BzrDir
159
 
        # specific. mbp 20070323
160
 
        if not allow_unsupported and not format.is_supported():
161
 
            # see open_downlevel to open legacy branches.
162
 
            raise errors.UnsupportedFormatError(format=format)
163
 
        if recommend_upgrade \
164
 
            and getattr(format, 'upgrade_recommended', False):
165
 
            ui.ui_factory.recommend_upgrade(
166
 
                format.get_format_description(),
167
 
                basedir)
168
 
 
169
127
    def clone_on_transport(self, transport, revision_id=None,
170
128
        force_new_repo=False, preserve_stacking=False, stacked_on=None,
171
 
        create_prefix=False, use_existing_dir=True):
 
129
        create_prefix=False, use_existing_dir=True, no_tree=False):
172
130
        """Clone this bzrdir and its contents to transport verbatim.
173
131
 
174
132
        :param transport: The transport for the location to produce the clone
183
141
        :param create_prefix: Create any missing directories leading up to
184
142
            to_transport.
185
143
        :param use_existing_dir: Use an existing directory if one exists.
 
144
        :param no_tree: If set to true prevents creation of a working tree.
186
145
        """
187
146
        # Overview: put together a broad description of what we want to end up
188
147
        # with; then make as few api calls as possible to do it.
216
175
        # we should look up the policy needs first, or just use it as a hint,
217
176
        # or something.
218
177
        if local_repo:
219
 
            make_working_trees = local_repo.make_working_trees()
 
178
            make_working_trees = local_repo.make_working_trees() and not no_tree
220
179
            want_shared = local_repo.is_shared()
221
180
            repo_format_name = format.repository_format.network_name()
222
181
        else:
242
201
                if (result_repo.user_url == result.user_url
243
202
                    and not require_stacking and
244
203
                    revision_id is not None):
245
 
                    fetch_spec = graph.PendingAncestryResult(
 
204
                    fetch_spec = vf_search.PendingAncestryResult(
246
205
                        [revision_id], local_repo)
247
206
                    result_repo.fetch(local_repo, fetch_spec=fetch_spec)
248
207
                else:
263
222
            # the tree and fail.
264
223
            result.root_transport.local_abspath('.')
265
224
            if result_repo is None or result_repo.make_working_trees():
266
 
                self.open_workingtree().clone(result)
 
225
                self.open_workingtree().clone(result, revision_id=revision_id)
267
226
        except (errors.NoWorkingTree, errors.NotLocalUrl):
268
227
            pass
269
228
        return result
271
230
    # TODO: This should be given a Transport, and should chdir up; otherwise
272
231
    # this will open a new connection.
273
232
    def _make_tail(self, url):
274
 
        t = get_transport(url)
 
233
        t = _mod_transport.get_transport(url)
275
234
        t.ensure_base()
276
235
 
277
 
    @staticmethod
278
 
    def find_bzrdirs(transport, evaluate=None, list_current=None):
279
 
        """Find bzrdirs recursively from current location.
280
 
 
281
 
        This is intended primarily as a building block for more sophisticated
282
 
        functionality, like finding trees under a directory, or finding
283
 
        branches that use a given repository.
284
 
        :param evaluate: An optional callable that yields recurse, value,
285
 
            where recurse controls whether this bzrdir is recursed into
286
 
            and value is the value to yield.  By default, all bzrdirs
287
 
            are recursed into, and the return value is the bzrdir.
288
 
        :param list_current: if supplied, use this function to list the current
289
 
            directory, instead of Transport.list_dir
290
 
        :return: a generator of found bzrdirs, or whatever evaluate returns.
291
 
        """
292
 
        if list_current is None:
293
 
            def list_current(transport):
294
 
                return transport.list_dir('')
295
 
        if evaluate is None:
296
 
            def evaluate(bzrdir):
297
 
                return True, bzrdir
298
 
 
299
 
        pending = [transport]
300
 
        while len(pending) > 0:
301
 
            current_transport = pending.pop()
302
 
            recurse = True
303
 
            try:
304
 
                bzrdir = BzrDir.open_from_transport(current_transport)
305
 
            except (errors.NotBranchError, errors.PermissionDenied):
306
 
                pass
307
 
            else:
308
 
                recurse, value = evaluate(bzrdir)
309
 
                yield value
310
 
            try:
311
 
                subdirs = list_current(current_transport)
312
 
            except (errors.NoSuchFile, errors.PermissionDenied):
313
 
                continue
314
 
            if recurse:
315
 
                for subdir in sorted(subdirs, reverse=True):
316
 
                    pending.append(current_transport.clone(subdir))
317
 
 
318
 
    @staticmethod
319
 
    def find_branches(transport):
320
 
        """Find all branches under a transport.
321
 
 
322
 
        This will find all branches below the transport, including branches
323
 
        inside other branches.  Where possible, it will use
324
 
        Repository.find_branches.
325
 
 
326
 
        To list all the branches that use a particular Repository, see
327
 
        Repository.find_branches
328
 
        """
329
 
        def evaluate(bzrdir):
330
 
            try:
331
 
                repository = bzrdir.open_repository()
332
 
            except errors.NoRepositoryPresent:
333
 
                pass
334
 
            else:
335
 
                return False, ([], repository)
336
 
            return True, (bzrdir.list_branches(), None)
337
 
        ret = []
338
 
        for branches, repo in BzrDir.find_bzrdirs(transport,
339
 
                                                  evaluate=evaluate):
340
 
            if repo is not None:
341
 
                ret.extend(repo.find_branches())
342
 
            if branches is not None:
343
 
                ret.extend(branches)
344
 
        return ret
345
 
 
346
 
    @staticmethod
347
 
    def create_branch_and_repo(base, force_new_repo=False, format=None):
348
 
        """Create a new BzrDir, Branch and Repository at the url 'base'.
349
 
 
350
 
        This will use the current default BzrDirFormat unless one is
351
 
        specified, and use whatever
352
 
        repository format that that uses via bzrdir.create_branch and
353
 
        create_repository. If a shared repository is available that is used
354
 
        preferentially.
355
 
 
356
 
        The created Branch object is returned.
357
 
 
358
 
        :param base: The URL to create the branch at.
359
 
        :param force_new_repo: If True a new repository is always created.
360
 
        :param format: If supplied, the format of branch to create.  If not
361
 
            supplied, the default is used.
362
 
        """
363
 
        bzrdir = BzrDir.create(base, format)
364
 
        bzrdir._find_or_create_repository(force_new_repo)
365
 
        return bzrdir.create_branch()
366
 
 
367
236
    def determine_repository_policy(self, force_new_repo=False, stack_on=None,
368
237
                                    stack_on_pwd=None, require_stacking=False):
369
238
        """Return an object representing a policy to use.
430
299
        policy = self.determine_repository_policy(force_new_repo)
431
300
        return policy.acquire_repository()[0]
432
301
 
433
 
    @staticmethod
434
 
    def create_branch_convenience(base, force_new_repo=False,
435
 
                                  force_new_tree=None, format=None,
436
 
                                  possible_transports=None):
437
 
        """Create a new BzrDir, Branch and Repository at the url 'base'.
438
 
 
439
 
        This is a convenience function - it will use an existing repository
440
 
        if possible, can be told explicitly whether to create a working tree or
441
 
        not.
442
 
 
443
 
        This will use the current default BzrDirFormat unless one is
444
 
        specified, and use whatever
445
 
        repository format that that uses via bzrdir.create_branch and
446
 
        create_repository. If a shared repository is available that is used
447
 
        preferentially. Whatever repository is used, its tree creation policy
448
 
        is followed.
449
 
 
450
 
        The created Branch object is returned.
451
 
        If a working tree cannot be made due to base not being a file:// url,
452
 
        no error is raised unless force_new_tree is True, in which case no
453
 
        data is created on disk and NotLocalUrl is raised.
454
 
 
455
 
        :param base: The URL to create the branch at.
456
 
        :param force_new_repo: If True a new repository is always created.
457
 
        :param force_new_tree: If True or False force creation of a tree or
458
 
                               prevent such creation respectively.
459
 
        :param format: Override for the bzrdir format to create.
460
 
        :param possible_transports: An optional reusable transports list.
461
 
        """
462
 
        if force_new_tree:
463
 
            # check for non local urls
464
 
            t = get_transport(base, possible_transports)
465
 
            if not isinstance(t, local.LocalTransport):
466
 
                raise errors.NotLocalUrl(base)
467
 
        bzrdir = BzrDir.create(base, format, possible_transports)
468
 
        repo = bzrdir._find_or_create_repository(force_new_repo)
469
 
        result = bzrdir.create_branch()
470
 
        if force_new_tree or (repo.make_working_trees() and
471
 
                              force_new_tree is None):
472
 
            try:
473
 
                bzrdir.create_workingtree()
474
 
            except errors.NotLocalUrl:
475
 
                pass
 
302
    def _find_source_repo(self, add_cleanup, source_branch):
 
303
        """Find the source branch and repo for a sprout operation.
 
304
        
 
305
        This is helper intended for use by _sprout.
 
306
 
 
307
        :returns: (source_branch, source_repository).  Either or both may be
 
308
            None.  If not None, they will be read-locked (and their unlock(s)
 
309
            scheduled via the add_cleanup param).
 
310
        """
 
311
        if source_branch is not None:
 
312
            add_cleanup(source_branch.lock_read().unlock)
 
313
            return source_branch, source_branch.repository
 
314
        try:
 
315
            source_branch = self.open_branch()
 
316
            source_repository = source_branch.repository
 
317
        except errors.NotBranchError:
 
318
            source_branch = None
 
319
            try:
 
320
                source_repository = self.open_repository()
 
321
            except errors.NoRepositoryPresent:
 
322
                source_repository = None
 
323
            else:
 
324
                add_cleanup(source_repository.lock_read().unlock)
 
325
        else:
 
326
            add_cleanup(source_branch.lock_read().unlock)
 
327
        return source_branch, source_repository
 
328
 
 
329
    def sprout(self, url, revision_id=None, force_new_repo=False,
 
330
               recurse='down', possible_transports=None,
 
331
               accelerator_tree=None, hardlink=False, stacked=False,
 
332
               source_branch=None, create_tree_if_local=True):
 
333
        """Create a copy of this controldir prepared for use as a new line of
 
334
        development.
 
335
 
 
336
        If url's last component does not exist, it will be created.
 
337
 
 
338
        Attributes related to the identity of the source branch like
 
339
        branch nickname will be cleaned, a working tree is created
 
340
        whether one existed before or not; and a local branch is always
 
341
        created.
 
342
 
 
343
        if revision_id is not None, then the clone operation may tune
 
344
            itself to download less data.
 
345
 
 
346
        :param accelerator_tree: A tree which can be used for retrieving file
 
347
            contents more quickly than the revision tree, i.e. a workingtree.
 
348
            The revision tree will be used for cases where accelerator_tree's
 
349
            content is different.
 
350
        :param hardlink: If true, hard-link files from accelerator_tree,
 
351
            where possible.
 
352
        :param stacked: If true, create a stacked branch referring to the
 
353
            location of this control directory.
 
354
        :param create_tree_if_local: If true, a working-tree will be created
 
355
            when working locally.
 
356
        """
 
357
        operation = cleanup.OperationWithCleanups(self._sprout)
 
358
        return operation.run(url, revision_id=revision_id,
 
359
            force_new_repo=force_new_repo, recurse=recurse,
 
360
            possible_transports=possible_transports,
 
361
            accelerator_tree=accelerator_tree, hardlink=hardlink,
 
362
            stacked=stacked, source_branch=source_branch,
 
363
            create_tree_if_local=create_tree_if_local)
 
364
 
 
365
    def _sprout(self, op, url, revision_id=None, force_new_repo=False,
 
366
               recurse='down', possible_transports=None,
 
367
               accelerator_tree=None, hardlink=False, stacked=False,
 
368
               source_branch=None, create_tree_if_local=True):
 
369
        add_cleanup = op.add_cleanup
 
370
        fetch_spec_factory = fetch.FetchSpecFactory()
 
371
        if revision_id is not None:
 
372
            fetch_spec_factory.add_revision_ids([revision_id])
 
373
            fetch_spec_factory.source_branch_stop_revision_id = revision_id
 
374
        if possible_transports is None:
 
375
            possible_transports = []
 
376
        else:
 
377
            possible_transports = list(possible_transports) + [
 
378
                self.root_transport]
 
379
        target_transport = _mod_transport.get_transport(url,
 
380
            possible_transports)
 
381
        target_transport.ensure_base()
 
382
        cloning_format = self.cloning_metadir(stacked)
 
383
        # Create/update the result branch
 
384
        try:
 
385
            result = controldir.ControlDir.open_from_transport(target_transport)
 
386
        except errors.NotBranchError:
 
387
            result = cloning_format.initialize_on_transport(target_transport)
 
388
        source_branch, source_repository = self._find_source_repo(
 
389
            add_cleanup, source_branch)
 
390
        fetch_spec_factory.source_branch = source_branch
 
391
        # if a stacked branch wasn't requested, we don't create one
 
392
        # even if the origin was stacked
 
393
        if stacked and source_branch is not None:
 
394
            stacked_branch_url = self.root_transport.base
 
395
        else:
 
396
            stacked_branch_url = None
 
397
        repository_policy = result.determine_repository_policy(
 
398
            force_new_repo, stacked_branch_url, require_stacking=stacked)
 
399
        result_repo, is_new_repo = repository_policy.acquire_repository(
 
400
            possible_transports=possible_transports)
 
401
        add_cleanup(result_repo.lock_write().unlock)
 
402
        fetch_spec_factory.source_repo = source_repository
 
403
        fetch_spec_factory.target_repo = result_repo
 
404
        if stacked or (len(result_repo._fallback_repositories) != 0):
 
405
            target_repo_kind = fetch.TargetRepoKinds.STACKED
 
406
        elif is_new_repo:
 
407
            target_repo_kind = fetch.TargetRepoKinds.EMPTY
 
408
        else:
 
409
            target_repo_kind = fetch.TargetRepoKinds.PREEXISTING
 
410
        fetch_spec_factory.target_repo_kind = target_repo_kind
 
411
        if source_repository is not None:
 
412
            fetch_spec = fetch_spec_factory.make_fetch_spec()
 
413
            result_repo.fetch(source_repository, fetch_spec=fetch_spec)
 
414
 
 
415
        if source_branch is None:
 
416
            # this is for sprouting a controldir without a branch; is that
 
417
            # actually useful?
 
418
            # Not especially, but it's part of the contract.
 
419
            result_branch = result.create_branch()
 
420
        else:
 
421
            result_branch = source_branch.sprout(result,
 
422
                revision_id=revision_id, repository_policy=repository_policy,
 
423
                repository=result_repo)
 
424
        mutter("created new branch %r" % (result_branch,))
 
425
 
 
426
        # Create/update the result working tree
 
427
        if (create_tree_if_local and not result.has_workingtree() and
 
428
            isinstance(target_transport, local.LocalTransport) and
 
429
            (result_repo is None or result_repo.make_working_trees())):
 
430
            wt = result.create_workingtree(accelerator_tree=accelerator_tree,
 
431
                hardlink=hardlink, from_branch=result_branch)
 
432
            wt.lock_write()
 
433
            try:
 
434
                if wt.path2id('') is None:
 
435
                    try:
 
436
                        wt.set_root_id(self.open_workingtree.get_root_id())
 
437
                    except errors.NoWorkingTree:
 
438
                        pass
 
439
            finally:
 
440
                wt.unlock()
 
441
        else:
 
442
            wt = None
 
443
        if recurse == 'down':
 
444
            basis = None
 
445
            if wt is not None:
 
446
                basis = wt.basis_tree()
 
447
            elif result_branch is not None:
 
448
                basis = result_branch.basis_tree()
 
449
            elif source_branch is not None:
 
450
                basis = source_branch.basis_tree()
 
451
            if basis is not None:
 
452
                add_cleanup(basis.lock_read().unlock)
 
453
                subtrees = basis.iter_references()
 
454
            else:
 
455
                subtrees = []
 
456
            for path, file_id in subtrees:
 
457
                target = urlutils.join(url, urlutils.escape(path))
 
458
                sublocation = source_branch.reference_parent(file_id, path)
 
459
                sublocation.bzrdir.sprout(target,
 
460
                    basis.get_reference_revision(file_id, path),
 
461
                    force_new_repo=force_new_repo, recurse=recurse,
 
462
                    stacked=stacked)
476
463
        return result
477
464
 
478
 
    @staticmethod
479
 
    def create_standalone_workingtree(base, format=None):
480
 
        """Create a new BzrDir, WorkingTree, Branch and Repository at 'base'.
481
 
 
482
 
        'base' must be a local path or a file:// url.
483
 
 
484
 
        This will use the current default BzrDirFormat unless one is
485
 
        specified, and use whatever
486
 
        repository format that that uses for bzrdirformat.create_workingtree,
487
 
        create_branch and create_repository.
488
 
 
489
 
        :param format: Override for the bzrdir format to create.
490
 
        :return: The WorkingTree object.
491
 
        """
492
 
        t = get_transport(base)
493
 
        if not isinstance(t, local.LocalTransport):
494
 
            raise errors.NotLocalUrl(base)
495
 
        bzrdir = BzrDir.create_branch_and_repo(base,
496
 
                                               force_new_repo=True,
497
 
                                               format=format).bzrdir
498
 
        return bzrdir.create_workingtree()
499
 
 
 
465
    @deprecated_method(deprecated_in((2, 3, 0)))
500
466
    def generate_backup_name(self, base):
501
 
        """Generate a non-existing backup file name based on base."""
502
 
        counter = 1
503
 
        name = "%s.~%d~" % (base, counter)
504
 
        while self.root_transport.has(name):
505
 
            counter += 1
506
 
            name = "%s.~%d~" % (base, counter)
507
 
        return name
 
467
        return self._available_backup_name(base)
 
468
 
 
469
    def _available_backup_name(self, base):
 
470
        """Find a non-existing backup file name based on base.
 
471
 
 
472
        See bzrlib.osutils.available_backup_name about race conditions.
 
473
        """
 
474
        return osutils.available_backup_name(base, self.root_transport.has)
508
475
 
509
476
    def backup_bzrdir(self):
510
477
        """Backup this bzr control directory.
512
479
        :return: Tuple with old path name and new path name
513
480
        """
514
481
 
515
 
        backup_dir=self.generate_backup_name('backup.bzr')
516
482
        pb = ui.ui_factory.nested_progress_bar()
517
483
        try:
518
 
            # FIXME: bug 300001 -- the backup fails if the backup directory
519
 
            # already exists, but it should instead either remove it or make
520
 
            # a new backup directory.
521
 
            #
522
484
            old_path = self.root_transport.abspath('.bzr')
 
485
            backup_dir = self._available_backup_name('backup.bzr')
523
486
            new_path = self.root_transport.abspath(backup_dir)
524
 
            ui.ui_factory.note('making backup of %s\n  to %s' % (old_path, new_path,))
 
487
            ui.ui_factory.note(gettext('making backup of {0}\n  to {1}').format(
 
488
                urlutils.unescape_for_display(old_path, 'utf-8'),
 
489
                urlutils.unescape_for_display(new_path, 'utf-8')))
525
490
            self.root_transport.copy_tree('.bzr', backup_dir)
526
491
            return (old_path, new_path)
527
492
        finally:
542
507
            try:
543
508
                to_path = '.bzr.retired.%d' % i
544
509
                self.root_transport.rename('.bzr', to_path)
545
 
                note("renamed %s to %s"
546
 
                    % (self.root_transport.abspath('.bzr'), to_path))
 
510
                note(gettext("renamed {0} to {1}").format(
 
511
                    self.root_transport.abspath('.bzr'), to_path))
547
512
                return
548
513
            except (errors.TransportError, IOError, errors.PathError):
549
514
                i += 1
576
541
                return None
577
542
            # find the next containing bzrdir
578
543
            try:
579
 
                found_bzrdir = BzrDir.open_containing_from_transport(
 
544
                found_bzrdir = self.open_containing_from_transport(
580
545
                    next_transport)[0]
581
546
            except errors.NotBranchError:
582
547
                return None
699
664
        # add new tests for it to the appropriate place.
700
665
        return filename == '.bzr' or filename.startswith('.bzr/')
701
666
 
702
 
    @staticmethod
703
 
    def open_unsupported(base):
704
 
        """Open a branch which is not supported."""
705
 
        return BzrDir.open(base, _unsupported=True)
706
 
 
707
 
    @staticmethod
708
 
    def open(base, _unsupported=False, possible_transports=None):
709
 
        """Open an existing bzrdir, rooted at 'base' (url).
710
 
 
711
 
        :param _unsupported: a private parameter to the BzrDir class.
712
 
        """
713
 
        t = get_transport(base, possible_transports=possible_transports)
714
 
        return BzrDir.open_from_transport(t, _unsupported=_unsupported)
715
 
 
716
 
    @staticmethod
717
 
    def open_from_transport(transport, _unsupported=False,
718
 
                            _server_formats=True):
719
 
        """Open a bzrdir within a particular directory.
720
 
 
721
 
        :param transport: Transport containing the bzrdir.
722
 
        :param _unsupported: private.
723
 
        """
724
 
        for hook in BzrDir.hooks['pre_open']:
725
 
            hook(transport)
726
 
        # Keep initial base since 'transport' may be modified while following
727
 
        # the redirections.
728
 
        base = transport.base
729
 
        def find_format(transport):
730
 
            return transport, controldir.ControlDirFormat.find_format(
731
 
                transport, _server_formats=_server_formats)
732
 
 
733
 
        def redirected(transport, e, redirection_notice):
734
 
            redirected_transport = transport._redirected_to(e.source, e.target)
735
 
            if redirected_transport is None:
736
 
                raise errors.NotBranchError(base)
737
 
            note('%s is%s redirected to %s',
738
 
                 transport.base, e.permanently, redirected_transport.base)
739
 
            return redirected_transport
740
 
 
741
 
        try:
742
 
            transport, format = do_catching_redirections(find_format,
743
 
                                                         transport,
744
 
                                                         redirected)
745
 
        except errors.TooManyRedirections:
746
 
            raise errors.NotBranchError(base)
747
 
 
748
 
        BzrDir._check_supported(format, _unsupported)
749
 
        return format.open(transport, _found=True)
750
 
 
751
 
    @staticmethod
752
 
    def open_containing(url, possible_transports=None):
753
 
        """Open an existing branch which contains url.
754
 
 
755
 
        :param url: url to search from.
756
 
        See open_containing_from_transport for more detail.
757
 
        """
758
 
        transport = get_transport(url, possible_transports)
759
 
        return BzrDir.open_containing_from_transport(transport)
760
 
 
761
 
    @staticmethod
762
 
    def open_containing_from_transport(a_transport):
763
 
        """Open an existing branch which contains a_transport.base.
764
 
 
765
 
        This probes for a branch at a_transport, and searches upwards from there.
766
 
 
767
 
        Basically we keep looking up until we find the control directory or
768
 
        run into the root.  If there isn't one, raises NotBranchError.
769
 
        If there is one and it is either an unrecognised format or an unsupported
770
 
        format, UnknownFormatError or UnsupportedFormatError are raised.
771
 
        If there is one, it is returned, along with the unused portion of url.
772
 
 
773
 
        :return: The BzrDir that contains the path, and a Unicode path
774
 
                for the rest of the URL.
775
 
        """
776
 
        # this gets the normalised url back. I.e. '.' -> the full path.
777
 
        url = a_transport.base
778
 
        while True:
779
 
            try:
780
 
                result = BzrDir.open_from_transport(a_transport)
781
 
                return result, urlutils.unescape(a_transport.relpath(url))
782
 
            except errors.NotBranchError, e:
783
 
                pass
784
 
            try:
785
 
                new_t = a_transport.clone('..')
786
 
            except errors.InvalidURLJoin:
787
 
                # reached the root, whatever that may be
788
 
                raise errors.NotBranchError(path=url)
789
 
            if new_t.base == a_transport.base:
790
 
                # reached the root, whatever that may be
791
 
                raise errors.NotBranchError(path=url)
792
 
            a_transport = new_t
793
 
 
794
 
    @classmethod
795
 
    def open_tree_or_branch(klass, location):
796
 
        """Return the branch and working tree at a location.
797
 
 
798
 
        If there is no tree at the location, tree will be None.
799
 
        If there is no branch at the location, an exception will be
800
 
        raised
801
 
        :return: (tree, branch)
802
 
        """
803
 
        bzrdir = klass.open(location)
804
 
        return bzrdir._get_tree_branch()
805
 
 
806
 
    @classmethod
807
 
    def open_containing_tree_or_branch(klass, location):
808
 
        """Return the branch and working tree contained by a location.
809
 
 
810
 
        Returns (tree, branch, relpath).
811
 
        If there is no tree at containing the location, tree will be None.
812
 
        If there is no branch containing the location, an exception will be
813
 
        raised
814
 
        relpath is the portion of the path that is contained by the branch.
815
 
        """
816
 
        bzrdir, relpath = klass.open_containing(location)
817
 
        tree, branch = bzrdir._get_tree_branch()
818
 
        return tree, branch, relpath
819
 
 
820
 
    @classmethod
821
 
    def open_containing_tree_branch_or_repository(klass, location):
822
 
        """Return the working tree, branch and repo contained by a location.
823
 
 
824
 
        Returns (tree, branch, repository, relpath).
825
 
        If there is no tree containing the location, tree will be None.
826
 
        If there is no branch containing the location, branch will be None.
827
 
        If there is no repository containing the location, repository will be
828
 
        None.
829
 
        relpath is the portion of the path that is contained by the innermost
830
 
        BzrDir.
831
 
 
832
 
        If no tree, branch or repository is found, a NotBranchError is raised.
833
 
        """
834
 
        bzrdir, relpath = klass.open_containing(location)
835
 
        try:
836
 
            tree, branch = bzrdir._get_tree_branch()
837
 
        except errors.NotBranchError:
838
 
            try:
839
 
                repo = bzrdir.find_repository()
840
 
                return None, None, repo, relpath
841
 
            except (errors.NoRepositoryPresent):
842
 
                raise errors.NotBranchError(location)
843
 
        return tree, branch, branch.repository, relpath
844
 
 
845
667
    def _cloning_metadir(self):
846
668
        """Produce a metadir suitable for cloning with.
847
669
 
887
709
 
888
710
        :require_stacking: If True, non-stackable formats will be upgraded
889
711
            to similar stackable formats.
890
 
        :returns: a BzrDirFormat with all component formats either set
 
712
        :returns: a ControlDirFormat with all component formats either set
891
713
            appropriately or set to None if that component should not be
892
714
            created.
893
715
        """
905
727
            format.require_stacking()
906
728
        return format
907
729
 
 
730
    def get_branch_transport(self, branch_format, name=None):
 
731
        """Get the transport for use by branch format in this BzrDir.
 
732
 
 
733
        Note that bzr dirs that do not support format strings will raise
 
734
        IncompatibleFormat if the branch format they are given has
 
735
        a format string, and vice versa.
 
736
 
 
737
        If branch_format is None, the transport is returned with no
 
738
        checking. If it is not None, then the returned transport is
 
739
        guaranteed to point to an existing directory ready for use.
 
740
        """
 
741
        raise NotImplementedError(self.get_branch_transport)
 
742
 
 
743
    def get_repository_transport(self, repository_format):
 
744
        """Get the transport for use by repository format in this BzrDir.
 
745
 
 
746
        Note that bzr dirs that do not support format strings will raise
 
747
        IncompatibleFormat if the repository format they are given has
 
748
        a format string, and vice versa.
 
749
 
 
750
        If repository_format is None, the transport is returned with no
 
751
        checking. If it is not None, then the returned transport is
 
752
        guaranteed to point to an existing directory ready for use.
 
753
        """
 
754
        raise NotImplementedError(self.get_repository_transport)
 
755
 
 
756
    def get_workingtree_transport(self, tree_format):
 
757
        """Get the transport for use by workingtree format in this BzrDir.
 
758
 
 
759
        Note that bzr dirs that do not support format strings will raise
 
760
        IncompatibleFormat if the workingtree format they are given has a
 
761
        format string, and vice versa.
 
762
 
 
763
        If workingtree_format is None, the transport is returned with no
 
764
        checking. If it is not None, then the returned transport is
 
765
        guaranteed to point to an existing directory ready for use.
 
766
        """
 
767
        raise NotImplementedError(self.get_workingtree_transport)
 
768
 
908
769
    @classmethod
909
770
    def create(cls, base, format=None, possible_transports=None):
910
771
        """Create a new BzrDir at the url 'base'.
915
776
            can be reused to share a remote connection.
916
777
        """
917
778
        if cls is not BzrDir:
918
 
            raise AssertionError("BzrDir.create always creates the"
 
779
            raise AssertionError("BzrDir.create always creates the "
919
780
                "default format, not one of %r" % cls)
920
 
        t = get_transport(base, possible_transports)
921
 
        t.ensure_base()
922
 
        if format is None:
923
 
            format = controldir.ControlDirFormat.get_default_format()
924
 
        return format.initialize_on_transport(t)
925
 
 
926
 
 
927
 
 
928
 
class BzrDirHooks(hooks.Hooks):
929
 
    """Hooks for BzrDir operations."""
930
 
 
931
 
    def __init__(self):
932
 
        """Create the default hooks."""
933
 
        hooks.Hooks.__init__(self)
934
 
        self.create_hook(hooks.HookPoint('pre_open',
935
 
            "Invoked before attempting to open a BzrDir with the transport "
936
 
            "that the open will use.", (1, 14), None))
937
 
        self.create_hook(hooks.HookPoint('post_repo_init',
938
 
            "Invoked after a repository has been initialized. "
939
 
            "post_repo_init is called with a "
940
 
            "bzrlib.bzrdir.RepoInitHookParams.",
941
 
            (2, 2), None))
942
 
 
943
 
# install the default hooks
944
 
BzrDir.hooks = BzrDirHooks()
945
 
 
946
 
 
947
 
class RepoInitHookParams(object):
948
 
    """Object holding parameters passed to *_repo_init hooks.
949
 
 
950
 
    There are 4 fields that hooks may wish to access:
951
 
 
952
 
    :ivar repository: Repository created
953
 
    :ivar format: Repository format
954
 
    :ivar bzrdir: The bzrdir for the repository
955
 
    :ivar shared: The repository is shared
956
 
    """
957
 
 
958
 
    def __init__(self, repository, format, a_bzrdir, shared):
959
 
        """Create a group of RepoInitHook parameters.
960
 
 
961
 
        :param repository: Repository created
962
 
        :param format: Repository format
963
 
        :param bzrdir: The bzrdir for the repository
964
 
        :param shared: The repository is shared
965
 
        """
966
 
        self.repository = repository
967
 
        self.format = format
968
 
        self.bzrdir = a_bzrdir
969
 
        self.shared = shared
970
 
 
971
 
    def __eq__(self, other):
972
 
        return self.__dict__ == other.__dict__
 
781
        return controldir.ControlDir.create(base, format=format,
 
782
                possible_transports=possible_transports)
973
783
 
974
784
    def __repr__(self):
975
 
        if self.repository:
976
 
            return "<%s for %s>" % (self.__class__.__name__,
977
 
                self.repository)
978
 
        else:
979
 
            return "<%s for %s>" % (self.__class__.__name__,
980
 
                self.bzrdir)
981
 
 
982
 
 
983
 
class BzrDirPreSplitOut(BzrDir):
984
 
    """A common class for the all-in-one formats."""
985
 
 
986
 
    def __init__(self, _transport, _format):
987
 
        """See BzrDir.__init__."""
988
 
        super(BzrDirPreSplitOut, self).__init__(_transport, _format)
989
 
        self._control_files = lockable_files.LockableFiles(
990
 
                                            self.get_branch_transport(None),
991
 
                                            self._format._lock_file_name,
992
 
                                            self._format._lock_class)
993
 
 
994
 
    def break_lock(self):
995
 
        """Pre-splitout bzrdirs do not suffer from stale locks."""
996
 
        raise NotImplementedError(self.break_lock)
997
 
 
998
 
    def cloning_metadir(self, require_stacking=False):
999
 
        """Produce a metadir suitable for cloning with."""
1000
 
        if require_stacking:
1001
 
            return controldir.format_registry.make_bzrdir('1.6')
1002
 
        return self._format.__class__()
1003
 
 
1004
 
    def clone(self, url, revision_id=None, force_new_repo=False,
1005
 
              preserve_stacking=False):
1006
 
        """See BzrDir.clone().
1007
 
 
1008
 
        force_new_repo has no effect, since this family of formats always
1009
 
        require a new repository.
1010
 
        preserve_stacking has no effect, since no source branch using this
1011
 
        family of formats can be stacked, so there is no stacking to preserve.
1012
 
        """
1013
 
        self._make_tail(url)
1014
 
        result = self._format._initialize_for_clone(url)
1015
 
        self.open_repository().clone(result, revision_id=revision_id)
1016
 
        from_branch = self.open_branch()
1017
 
        from_branch.clone(result, revision_id=revision_id)
1018
 
        try:
1019
 
            tree = self.open_workingtree()
1020
 
        except errors.NotLocalUrl:
1021
 
            # make a new one, this format always has to have one.
1022
 
            result._init_workingtree()
1023
 
        else:
1024
 
            tree.clone(result)
1025
 
        return result
1026
 
 
1027
 
    def create_branch(self, name=None):
1028
 
        """See BzrDir.create_branch."""
1029
 
        return self._format.get_branch_format().initialize(self, name=name)
1030
 
 
1031
 
    def destroy_branch(self, name=None):
1032
 
        """See BzrDir.destroy_branch."""
1033
 
        raise errors.UnsupportedOperation(self.destroy_branch, self)
1034
 
 
1035
 
    def create_repository(self, shared=False):
1036
 
        """See BzrDir.create_repository."""
1037
 
        if shared:
1038
 
            raise errors.IncompatibleFormat('shared repository', self._format)
1039
 
        return self.open_repository()
1040
 
 
1041
 
    def destroy_repository(self):
1042
 
        """See BzrDir.destroy_repository."""
1043
 
        raise errors.UnsupportedOperation(self.destroy_repository, self)
1044
 
 
1045
 
    def create_workingtree(self, revision_id=None, from_branch=None,
1046
 
                           accelerator_tree=None, hardlink=False):
1047
 
        """See BzrDir.create_workingtree."""
1048
 
        # The workingtree is sometimes created when the bzrdir is created,
1049
 
        # but not when cloning.
1050
 
 
1051
 
        # this looks buggy but is not -really-
1052
 
        # because this format creates the workingtree when the bzrdir is
1053
 
        # created
1054
 
        # clone and sprout will have set the revision_id
1055
 
        # and that will have set it for us, its only
1056
 
        # specific uses of create_workingtree in isolation
1057
 
        # that can do wonky stuff here, and that only
1058
 
        # happens for creating checkouts, which cannot be
1059
 
        # done on this format anyway. So - acceptable wart.
1060
 
        if hardlink:
1061
 
            warning("can't support hardlinked working trees in %r"
1062
 
                % (self,))
1063
 
        try:
1064
 
            result = self.open_workingtree(recommend_upgrade=False)
1065
 
        except errors.NoSuchFile:
1066
 
            result = self._init_workingtree()
1067
 
        if revision_id is not None:
1068
 
            if revision_id == _mod_revision.NULL_REVISION:
1069
 
                result.set_parent_ids([])
1070
 
            else:
1071
 
                result.set_parent_ids([revision_id])
1072
 
        return result
1073
 
 
1074
 
    def _init_workingtree(self):
1075
 
        from bzrlib.workingtree import WorkingTreeFormat2
1076
 
        try:
1077
 
            return WorkingTreeFormat2().initialize(self)
1078
 
        except errors.NotLocalUrl:
1079
 
            # Even though we can't access the working tree, we need to
1080
 
            # create its control files.
1081
 
            return WorkingTreeFormat2()._stub_initialize_on_transport(
1082
 
                self.transport, self._control_files._file_mode)
1083
 
 
1084
 
    def destroy_workingtree(self):
1085
 
        """See BzrDir.destroy_workingtree."""
1086
 
        raise errors.UnsupportedOperation(self.destroy_workingtree, self)
1087
 
 
1088
 
    def destroy_workingtree_metadata(self):
1089
 
        """See BzrDir.destroy_workingtree_metadata."""
1090
 
        raise errors.UnsupportedOperation(self.destroy_workingtree_metadata,
1091
 
                                          self)
1092
 
 
1093
 
    def get_branch_transport(self, branch_format, name=None):
1094
 
        """See BzrDir.get_branch_transport()."""
1095
 
        if name is not None:
1096
 
            raise errors.NoColocatedBranchSupport(self)
1097
 
        if branch_format is None:
1098
 
            return self.transport
1099
 
        try:
1100
 
            branch_format.get_format_string()
1101
 
        except NotImplementedError:
1102
 
            return self.transport
1103
 
        raise errors.IncompatibleFormat(branch_format, self._format)
1104
 
 
1105
 
    def get_repository_transport(self, repository_format):
1106
 
        """See BzrDir.get_repository_transport()."""
1107
 
        if repository_format is None:
1108
 
            return self.transport
1109
 
        try:
1110
 
            repository_format.get_format_string()
1111
 
        except NotImplementedError:
1112
 
            return self.transport
1113
 
        raise errors.IncompatibleFormat(repository_format, self._format)
1114
 
 
1115
 
    def get_workingtree_transport(self, workingtree_format):
1116
 
        """See BzrDir.get_workingtree_transport()."""
1117
 
        if workingtree_format is None:
1118
 
            return self.transport
1119
 
        try:
1120
 
            workingtree_format.get_format_string()
1121
 
        except NotImplementedError:
1122
 
            return self.transport
1123
 
        raise errors.IncompatibleFormat(workingtree_format, self._format)
1124
 
 
1125
 
    def needs_format_conversion(self, format=None):
1126
 
        """See BzrDir.needs_format_conversion()."""
1127
 
        # if the format is not the same as the system default,
1128
 
        # an upgrade is needed.
1129
 
        if format is None:
1130
 
            symbol_versioning.warn(symbol_versioning.deprecated_in((1, 13, 0))
1131
 
                % 'needs_format_conversion(format=None)')
1132
 
            format = BzrDirFormat.get_default_format()
1133
 
        return not isinstance(self._format, format.__class__)
1134
 
 
1135
 
    def open_branch(self, name=None, unsupported=False,
1136
 
                    ignore_fallbacks=False):
1137
 
        """See BzrDir.open_branch."""
1138
 
        from bzrlib.branch import BzrBranchFormat4
1139
 
        format = BzrBranchFormat4()
1140
 
        self._check_supported(format, unsupported)
1141
 
        return format.open(self, name, _found=True)
1142
 
 
1143
 
    def sprout(self, url, revision_id=None, force_new_repo=False,
1144
 
               possible_transports=None, accelerator_tree=None,
1145
 
               hardlink=False, stacked=False, create_tree_if_local=True,
1146
 
               source_branch=None):
1147
 
        """See BzrDir.sprout()."""
1148
 
        if source_branch is not None:
1149
 
            my_branch = self.open_branch()
1150
 
            if source_branch.base != my_branch.base:
1151
 
                raise AssertionError(
1152
 
                    "source branch %r is not within %r with branch %r" %
1153
 
                    (source_branch, self, my_branch))
1154
 
        if stacked:
1155
 
            raise errors.UnstackableBranchFormat(
1156
 
                self._format, self.root_transport.base)
1157
 
        if not create_tree_if_local:
1158
 
            raise errors.MustHaveWorkingTree(
1159
 
                self._format, self.root_transport.base)
1160
 
        from bzrlib.workingtree import WorkingTreeFormat2
1161
 
        self._make_tail(url)
1162
 
        result = self._format._initialize_for_clone(url)
1163
 
        try:
1164
 
            self.open_repository().clone(result, revision_id=revision_id)
1165
 
        except errors.NoRepositoryPresent:
1166
 
            pass
1167
 
        try:
1168
 
            self.open_branch().sprout(result, revision_id=revision_id)
1169
 
        except errors.NotBranchError:
1170
 
            pass
1171
 
 
1172
 
        # we always want a working tree
1173
 
        WorkingTreeFormat2().initialize(result,
1174
 
                                        accelerator_tree=accelerator_tree,
1175
 
                                        hardlink=hardlink)
1176
 
        return result
1177
 
 
1178
 
 
1179
 
class BzrDir4(BzrDirPreSplitOut):
1180
 
    """A .bzr version 4 control object.
1181
 
 
1182
 
    This is a deprecated format and may be removed after sept 2006.
1183
 
    """
1184
 
 
1185
 
    def create_repository(self, shared=False):
1186
 
        """See BzrDir.create_repository."""
1187
 
        return self._format.repository_format.initialize(self, shared)
1188
 
 
1189
 
    def needs_format_conversion(self, format=None):
1190
 
        """Format 4 dirs are always in need of conversion."""
1191
 
        if format is None:
1192
 
            symbol_versioning.warn(symbol_versioning.deprecated_in((1, 13, 0))
1193
 
                % 'needs_format_conversion(format=None)')
1194
 
        return True
1195
 
 
1196
 
    def open_repository(self):
1197
 
        """See BzrDir.open_repository."""
1198
 
        from bzrlib.repofmt.weaverepo import RepositoryFormat4
1199
 
        return RepositoryFormat4().open(self, _found=True)
1200
 
 
1201
 
 
1202
 
class BzrDir5(BzrDirPreSplitOut):
1203
 
    """A .bzr version 5 control object.
1204
 
 
1205
 
    This is a deprecated format and may be removed after sept 2006.
1206
 
    """
1207
 
 
1208
 
    def has_workingtree(self):
1209
 
        """See BzrDir.has_workingtree."""
1210
 
        return True
1211
 
    
1212
 
    def open_repository(self):
1213
 
        """See BzrDir.open_repository."""
1214
 
        from bzrlib.repofmt.weaverepo import RepositoryFormat5
1215
 
        return RepositoryFormat5().open(self, _found=True)
1216
 
 
1217
 
    def open_workingtree(self, _unsupported=False,
1218
 
            recommend_upgrade=True):
1219
 
        """See BzrDir.create_workingtree."""
1220
 
        from bzrlib.workingtree import WorkingTreeFormat2
1221
 
        wt_format = WorkingTreeFormat2()
1222
 
        # we don't warn here about upgrades; that ought to be handled for the
1223
 
        # bzrdir as a whole
1224
 
        return wt_format.open(self, _found=True)
1225
 
 
1226
 
 
1227
 
class BzrDir6(BzrDirPreSplitOut):
1228
 
    """A .bzr version 6 control object.
1229
 
 
1230
 
    This is a deprecated format and may be removed after sept 2006.
1231
 
    """
1232
 
 
1233
 
    def has_workingtree(self):
1234
 
        """See BzrDir.has_workingtree."""
1235
 
        return True
1236
 
    
1237
 
    def open_repository(self):
1238
 
        """See BzrDir.open_repository."""
1239
 
        from bzrlib.repofmt.weaverepo import RepositoryFormat6
1240
 
        return RepositoryFormat6().open(self, _found=True)
1241
 
 
1242
 
    def open_workingtree(self, _unsupported=False,
1243
 
        recommend_upgrade=True):
1244
 
        """See BzrDir.create_workingtree."""
1245
 
        # we don't warn here about upgrades; that ought to be handled for the
1246
 
        # bzrdir as a whole
1247
 
        from bzrlib.workingtree import WorkingTreeFormat2
1248
 
        return WorkingTreeFormat2().open(self, _found=True)
 
785
        return "<%s at %r>" % (self.__class__.__name__, self.user_url)
1249
786
 
1250
787
 
1251
788
class BzrDirMeta1(BzrDir):
1261
798
        """See BzrDir.can_convert_format()."""
1262
799
        return True
1263
800
 
1264
 
    def create_branch(self, name=None):
 
801
    def create_branch(self, name=None, repository=None,
 
802
            append_revisions_only=None):
1265
803
        """See BzrDir.create_branch."""
1266
 
        return self._format.get_branch_format().initialize(self, name=name)
 
804
        if name is None:
 
805
            name = self._get_selected_branch()
 
806
        return self._format.get_branch_format().initialize(self, name=name,
 
807
                repository=repository,
 
808
                append_revisions_only=append_revisions_only)
1267
809
 
1268
810
    def destroy_branch(self, name=None):
1269
811
        """See BzrDir.create_branch."""
1277
819
 
1278
820
    def destroy_repository(self):
1279
821
        """See BzrDir.destroy_repository."""
1280
 
        self.transport.delete_tree('repository')
 
822
        try:
 
823
            self.transport.delete_tree('repository')
 
824
        except errors.NoSuchFile:
 
825
            raise errors.NoRepositoryPresent(self)
1281
826
 
1282
827
    def create_workingtree(self, revision_id=None, from_branch=None,
1283
828
                           accelerator_tree=None, hardlink=False):
1291
836
        wt = self.open_workingtree(recommend_upgrade=False)
1292
837
        repository = wt.branch.repository
1293
838
        empty = repository.revision_tree(_mod_revision.NULL_REVISION)
1294
 
        wt.revert(old_tree=empty)
 
839
        # We ignore the conflicts returned by wt.revert since we're about to
 
840
        # delete the wt metadata anyway, all that should be left here are
 
841
        # detritus. But see bug #634470 about subtree .bzr dirs.
 
842
        conflicts = wt.revert(old_tree=empty)
1295
843
        self.destroy_workingtree_metadata()
1296
844
 
1297
845
    def destroy_workingtree_metadata(self):
1302
850
 
1303
851
        This might be a synthetic object for e.g. RemoteBranch and SVN.
1304
852
        """
1305
 
        from bzrlib.branch import BranchFormat
1306
 
        return BranchFormat.find_format(self, name=name)
 
853
        from bzrlib.branch import BranchFormatMetadir
 
854
        return BranchFormatMetadir.find_format(self, name=name)
1307
855
 
1308
856
    def _get_mkdir_mode(self):
1309
857
        """Figure out the mode to use when creating a bzrdir subdir."""
1313
861
 
1314
862
    def get_branch_reference(self, name=None):
1315
863
        """See BzrDir.get_branch_reference()."""
1316
 
        from bzrlib.branch import BranchFormat
1317
 
        format = BranchFormat.find_format(self, name=name)
 
864
        from bzrlib.branch import BranchFormatMetadir
 
865
        format = BranchFormatMetadir.find_format(self, name=name)
1318
866
        return format.get_reference(self, name=name)
1319
867
 
1320
868
    def get_branch_transport(self, branch_format, name=None):
1366
914
    def has_workingtree(self):
1367
915
        """Tell if this bzrdir contains a working tree.
1368
916
 
1369
 
        This will still raise an exception if the bzrdir has a workingtree that
1370
 
        is remote & inaccessible.
1371
 
 
1372
917
        Note: if you're going to open the working tree, you should just go
1373
918
        ahead and try, and not ask permission first.
1374
919
        """
1375
 
        from bzrlib.workingtree import WorkingTreeFormat
 
920
        from bzrlib.workingtree import WorkingTreeFormatMetaDir
1376
921
        try:
1377
 
            WorkingTreeFormat.find_format(self)
 
922
            WorkingTreeFormatMetaDir.find_format_string(self)
1378
923
        except errors.NoWorkingTree:
1379
924
            return False
1380
925
        return True
1381
926
 
1382
 
    def needs_format_conversion(self, format=None):
 
927
    def needs_format_conversion(self, format):
1383
928
        """See BzrDir.needs_format_conversion()."""
1384
 
        if format is None:
1385
 
            symbol_versioning.warn(symbol_versioning.deprecated_in((1, 13, 0))
1386
 
                % 'needs_format_conversion(format=None)')
1387
 
        if format is None:
1388
 
            format = BzrDirFormat.get_default_format()
1389
 
        if not isinstance(self._format, format.__class__):
 
929
        if (not isinstance(self._format, format.__class__) or
 
930
            self._format.get_format_string() != format.get_format_string()):
1390
931
            # it is not a meta dir format, conversion is needed.
1391
932
            return True
1392
933
        # we might want to push this down to the repository?
1413
954
        return False
1414
955
 
1415
956
    def open_branch(self, name=None, unsupported=False,
1416
 
                    ignore_fallbacks=False):
1417
 
        """See BzrDir.open_branch."""
 
957
                    ignore_fallbacks=False, possible_transports=None):
 
958
        """See ControlDir.open_branch."""
 
959
        if name is None:
 
960
            name = self._get_selected_branch()
1418
961
        format = self.find_branch_format(name=name)
1419
 
        self._check_supported(format, unsupported)
 
962
        format.check_support_status(unsupported)
1420
963
        return format.open(self, name=name,
1421
 
            _found=True, ignore_fallbacks=ignore_fallbacks)
 
964
            _found=True, ignore_fallbacks=ignore_fallbacks,
 
965
            possible_transports=possible_transports)
1422
966
 
1423
967
    def open_repository(self, unsupported=False):
1424
968
        """See BzrDir.open_repository."""
1425
 
        from bzrlib.repository import RepositoryFormat
1426
 
        format = RepositoryFormat.find_format(self)
1427
 
        self._check_supported(format, unsupported)
 
969
        from bzrlib.repository import RepositoryFormatMetaDir
 
970
        format = RepositoryFormatMetaDir.find_format(self)
 
971
        format.check_support_status(unsupported)
1428
972
        return format.open(self, _found=True)
1429
973
 
1430
974
    def open_workingtree(self, unsupported=False,
1431
975
            recommend_upgrade=True):
1432
976
        """See BzrDir.open_workingtree."""
1433
 
        from bzrlib.workingtree import WorkingTreeFormat
1434
 
        format = WorkingTreeFormat.find_format(self)
1435
 
        self._check_supported(format, unsupported,
1436
 
            recommend_upgrade,
 
977
        from bzrlib.workingtree import WorkingTreeFormatMetaDir
 
978
        format = WorkingTreeFormatMetaDir.find_format(self)
 
979
        format.check_support_status(unsupported, recommend_upgrade,
1437
980
            basedir=self.root_transport.base)
1438
981
        return format.open(self, _found=True)
1439
982
 
1441
984
        return config.TransportConfig(self.transport, 'control.conf')
1442
985
 
1443
986
 
 
987
class BzrDirMeta1Colo(BzrDirMeta1):
 
988
    """BzrDirMeta1 with support for colocated branches.
 
989
 
 
990
    This format is experimental, and will eventually be merged back into
 
991
    BzrDirMeta1.
 
992
    """
 
993
 
 
994
    def __init__(self, _transport, _format):
 
995
        super(BzrDirMeta1Colo, self).__init__(_transport, _format)
 
996
        self.control_files = lockable_files.LockableFiles(self.control_transport,
 
997
            self._format._lock_file_name, self._format._lock_class)
 
998
 
 
999
    def _get_branch_path(self, name):
 
1000
        """Obtain the branch path to use.
 
1001
 
 
1002
        This uses the API specified branch name first, and then falls back to
 
1003
        the branch name specified in the URL. If neither of those is specified,
 
1004
        it uses the default branch.
 
1005
 
 
1006
        :param name: Optional branch name to use
 
1007
        :return: Relative path to branch
 
1008
        """
 
1009
        if name is None:
 
1010
            return 'branch'
 
1011
        return urlutils.join('branches', name.encode("utf-8"))
 
1012
 
 
1013
    def _read_branch_list(self):
 
1014
        """Read the branch list.
 
1015
 
 
1016
        :return: List of utf-8 encoded branch names.
 
1017
        """
 
1018
        try:
 
1019
            f = self.control_transport.get('branch-list')
 
1020
        except errors.NoSuchFile:
 
1021
            return []
 
1022
 
 
1023
        ret = []
 
1024
        try:
 
1025
            for name in f:
 
1026
                ret.append(name.rstrip("\n"))
 
1027
        finally:
 
1028
            f.close()
 
1029
        return ret
 
1030
 
 
1031
    def _write_branch_list(self, branches):
 
1032
        """Write out the branch list.
 
1033
 
 
1034
        :param branches: List of utf-8 branch names to write
 
1035
        """
 
1036
        self.transport.put_bytes('branch-list',
 
1037
            "".join([name+"\n" for name in branches]))
 
1038
 
 
1039
    def destroy_branch(self, name=None):
 
1040
        """See BzrDir.create_branch."""
 
1041
        if name is None:
 
1042
            name = self._get_selected_branch()
 
1043
        path = self._get_branch_path(name)
 
1044
        if name is not None:
 
1045
            self.control_files.lock_write()
 
1046
            try:
 
1047
                branches = self._read_branch_list()
 
1048
                try:
 
1049
                    branches.remove(name.encode("utf-8"))
 
1050
                except ValueError:
 
1051
                    raise errors.NotBranchError(name)
 
1052
                self._write_branch_list(branches)
 
1053
            finally:
 
1054
                self.control_files.unlock()
 
1055
        self.transport.delete_tree(path)
 
1056
 
 
1057
    def get_branches(self):
 
1058
        """See ControlDir.get_branches."""
 
1059
        ret = {}
 
1060
        try:
 
1061
            ret[None] = self.open_branch()
 
1062
        except (errors.NotBranchError, errors.NoRepositoryPresent):
 
1063
            pass
 
1064
 
 
1065
        for name in self._read_branch_list():
 
1066
            ret[name] = self.open_branch(name.decode('utf-8'))
 
1067
 
 
1068
        return ret
 
1069
 
 
1070
    def get_branch_transport(self, branch_format, name=None):
 
1071
        """See BzrDir.get_branch_transport()."""
 
1072
        path = self._get_branch_path(name)
 
1073
        # XXX: this shouldn't implicitly create the directory if it's just
 
1074
        # promising to get a transport -- mbp 20090727
 
1075
        if branch_format is None:
 
1076
            return self.transport.clone(path)
 
1077
        try:
 
1078
            branch_format.get_format_string()
 
1079
        except NotImplementedError:
 
1080
            raise errors.IncompatibleFormat(branch_format, self._format)
 
1081
        if name is not None:
 
1082
            try:
 
1083
                self.transport.mkdir('branches', mode=self._get_mkdir_mode())
 
1084
            except errors.FileExists:
 
1085
                pass
 
1086
            branches = self._read_branch_list()
 
1087
            utf8_name = name.encode("utf-8")
 
1088
            if not utf8_name in branches:
 
1089
                self.control_files.lock_write()
 
1090
                try:
 
1091
                    branches = self._read_branch_list()
 
1092
                    branches.append(utf8_name)
 
1093
                    self._write_branch_list(branches)
 
1094
                finally:
 
1095
                    self.control_files.unlock()
 
1096
        try:
 
1097
            self.transport.mkdir(path, mode=self._get_mkdir_mode())
 
1098
        except errors.FileExists:
 
1099
            pass
 
1100
        return self.transport.clone(path)
 
1101
 
 
1102
 
 
1103
class BzrDirMetaComponentFormat(controldir.ControlComponentFormat):
 
1104
    """Base class for all formats of things living in metadirs.
 
1105
 
 
1106
    This class manages the format string that is stored in the 'format'
 
1107
    or 'branch-format' file.
 
1108
 
 
1109
    All classes for (branch-, repository-, workingtree-) formats that
 
1110
    live in meta directories and have their own 'format' file
 
1111
    (i.e. different from .bzr/branch-format) derive from this class,
 
1112
    as well as the relevant base class for their kind
 
1113
    (BranchFormat, WorkingTreeFormat, RepositoryFormat).
 
1114
    """
 
1115
 
 
1116
    @classmethod
 
1117
    def get_format_string(cls):
 
1118
        """Return the ASCII format string that identifies this format."""
 
1119
        raise NotImplementedError(cls.get_format_string)
 
1120
 
 
1121
    @classmethod
 
1122
    def from_string(cls, format_string):
 
1123
        if format_string != cls.get_format_string():
 
1124
            raise ValueError("Invalid format header %r" % format_string)
 
1125
        return cls()
 
1126
 
 
1127
    @classmethod
 
1128
    def _find_format(klass, registry, kind, format_string):
 
1129
        try:
 
1130
            cls = registry.get(format_string)
 
1131
        except KeyError:
 
1132
            raise errors.UnknownFormatError(format=format_string, kind=kind)
 
1133
        return cls
 
1134
 
 
1135
    def network_name(self):
 
1136
        """A simple byte string uniquely identifying this format for RPC calls.
 
1137
 
 
1138
        Metadir branch formats use their format string.
 
1139
        """
 
1140
        return self.get_format_string()
 
1141
 
 
1142
    def __eq__(self, other):
 
1143
        return (self.__class__ is other.__class__)
 
1144
 
 
1145
 
1444
1146
class BzrProber(controldir.Prober):
1445
1147
    """Prober for formats that use a .bzr/ control directory."""
1446
1148
 
1447
 
    _formats = {}
 
1149
    formats = registry.FormatRegistry(controldir.network_format_registry)
1448
1150
    """The known .bzr formats."""
1449
1151
 
1450
1152
    @classmethod
 
1153
    @deprecated_method(deprecated_in((2, 4, 0)))
1451
1154
    def register_bzrdir_format(klass, format):
1452
 
        klass._formats[format.get_format_string()] = format
 
1155
        klass.formats.register(format.get_format_string(), format)
1453
1156
 
1454
1157
    @classmethod
 
1158
    @deprecated_method(deprecated_in((2, 4, 0)))
1455
1159
    def unregister_bzrdir_format(klass, format):
1456
 
        del klass._formats[format.get_format_string()]
 
1160
        klass.formats.remove(format.get_format_string())
1457
1161
 
1458
1162
    @classmethod
1459
1163
    def probe_transport(klass, transport):
1463
1167
        except errors.NoSuchFile:
1464
1168
            raise errors.NotBranchError(path=transport.base)
1465
1169
        try:
1466
 
            return klass._formats[format_string]
 
1170
            cls = klass.formats.get(format_string)
1467
1171
        except KeyError:
1468
1172
            raise errors.UnknownFormatError(format=format_string, kind='bzrdir')
 
1173
        return cls.from_string(format_string)
 
1174
 
 
1175
    @classmethod
 
1176
    def known_formats(cls):
 
1177
        result = set()
 
1178
        for name, format in cls.formats.iteritems():
 
1179
            if callable(format):
 
1180
                format = format()
 
1181
            result.add(format)
 
1182
        return result
1469
1183
 
1470
1184
 
1471
1185
controldir.ControlDirFormat.register_prober(BzrProber)
1496
1210
                    raise errors.NotBranchError(path=transport.base)
1497
1211
                if server_version != '2':
1498
1212
                    raise errors.NotBranchError(path=transport.base)
 
1213
            from bzrlib.remote import RemoteBzrDirFormat
1499
1214
            return RemoteBzrDirFormat()
1500
1215
 
 
1216
    @classmethod
 
1217
    def known_formats(cls):
 
1218
        from bzrlib.remote import RemoteBzrDirFormat
 
1219
        return set([RemoteBzrDirFormat()])
 
1220
 
1501
1221
 
1502
1222
class BzrDirFormat(controldir.ControlDirFormat):
1503
1223
    """ControlDirFormat base class for .bzr/ directories.
1516
1236
    # _lock_class must be set in subclasses to the lock type, typ.
1517
1237
    # TransportLock or LockDir
1518
1238
 
1519
 
    def get_format_string(self):
 
1239
    @classmethod
 
1240
    def get_format_string(cls):
1520
1241
        """Return the ASCII format string that identifies this format."""
1521
 
        raise NotImplementedError(self.get_format_string)
 
1242
        raise NotImplementedError(cls.get_format_string)
1522
1243
 
1523
1244
    def initialize_on_transport(self, transport):
1524
1245
        """Initialize a new bzrdir in the base directory of a Transport."""
1534
1255
            # metadir1
1535
1256
            if type(self) != BzrDirMetaFormat1:
1536
1257
                return self._initialize_on_transport_vfs(transport)
 
1258
            from bzrlib.remote import RemoteBzrDirFormat
1537
1259
            remote_format = RemoteBzrDirFormat()
1538
1260
            self._supply_sub_formats_to(remote_format)
1539
1261
            return remote_format.initialize_on_transport(transport)
1577
1299
            except errors.NoSmartMedium:
1578
1300
                pass
1579
1301
            else:
 
1302
                from bzrlib.remote import RemoteBzrDirFormat
1580
1303
                # TODO: lookup the local format from a server hint.
1581
1304
                remote_dir_format = RemoteBzrDirFormat()
1582
1305
                remote_dir_format._network_name = self.network_name()
1657
1380
        utf8_files = [('README',
1658
1381
                       "This is a Bazaar control directory.\n"
1659
1382
                       "Do not change any files in this directory.\n"
1660
 
                       "See http://bazaar-vcs.org/ for more information about Bazaar.\n"),
 
1383
                       "See http://bazaar.canonical.com/ for more information about Bazaar.\n"),
1661
1384
                      ('branch-format', self.get_format_string()),
1662
1385
                      ]
1663
1386
        # NB: no need to escape relative paths that are url safe.
1697
1420
        """
1698
1421
        raise NotImplementedError(self._open)
1699
1422
 
1700
 
    @classmethod
1701
 
    def register_format(klass, format):
1702
 
        BzrProber.register_bzrdir_format(format)
1703
 
        # bzr native formats have a network name of their format string.
1704
 
        controldir.network_format_registry.register(format.get_format_string(), format.__class__)
1705
 
        controldir.ControlDirFormat.register_format(format)
1706
 
 
1707
1423
    def _supply_sub_formats_to(self, other_format):
1708
1424
        """Give other_format the same values for sub formats as this has.
1709
1425
 
1716
1432
        :return: None.
1717
1433
        """
1718
1434
 
1719
 
    @classmethod
1720
 
    def unregister_format(klass, format):
1721
 
        BzrProber.unregister_bzrdir_format(format)
1722
 
        controldir.ControlDirFormat.unregister_format(format)
1723
 
        controldir.network_format_registry.remove(format.get_format_string())
1724
 
 
1725
 
 
1726
 
class BzrDirFormat4(BzrDirFormat):
1727
 
    """Bzr dir format 4.
1728
 
 
1729
 
    This format is a combined format for working tree, branch and repository.
1730
 
    It has:
1731
 
     - Format 1 working trees [always]
1732
 
     - Format 4 branches [always]
1733
 
     - Format 4 repositories [always]
1734
 
 
1735
 
    This format is deprecated: it indexes texts using a text it which is
1736
 
    removed in format 5; write support for this format has been removed.
1737
 
    """
1738
 
 
1739
 
    _lock_class = lockable_files.TransportLock
1740
 
 
1741
 
    def get_format_string(self):
1742
 
        """See BzrDirFormat.get_format_string()."""
1743
 
        return "Bazaar-NG branch, format 0.0.4\n"
1744
 
 
1745
 
    def get_format_description(self):
1746
 
        """See BzrDirFormat.get_format_description()."""
1747
 
        return "All-in-one format 4"
1748
 
 
1749
 
    def get_converter(self, format=None):
1750
 
        """See BzrDirFormat.get_converter()."""
1751
 
        # there is one and only one upgrade path here.
1752
 
        return ConvertBzrDir4To5()
1753
 
 
1754
 
    def initialize_on_transport(self, transport):
1755
 
        """Format 4 branches cannot be created."""
1756
 
        raise errors.UninitializableFormat(self)
1757
 
 
1758
 
    def is_supported(self):
1759
 
        """Format 4 is not supported.
1760
 
 
1761
 
        It is not supported because the model changed from 4 to 5 and the
1762
 
        conversion logic is expensive - so doing it on the fly was not
1763
 
        feasible.
1764
 
        """
1765
 
        return False
1766
 
 
1767
 
    def network_name(self):
1768
 
        return self.get_format_string()
1769
 
 
1770
 
    def _open(self, transport):
1771
 
        """See BzrDirFormat._open."""
1772
 
        return BzrDir4(transport, self)
1773
 
 
1774
 
    def __return_repository_format(self):
1775
 
        """Circular import protection."""
1776
 
        from bzrlib.repofmt.weaverepo import RepositoryFormat4
1777
 
        return RepositoryFormat4()
1778
 
    repository_format = property(__return_repository_format)
1779
 
 
1780
 
 
1781
 
class BzrDirFormatAllInOne(BzrDirFormat):
1782
 
    """Common class for formats before meta-dirs."""
1783
 
 
1784
 
    def initialize_on_transport_ex(self, transport, use_existing_dir=False,
1785
 
        create_prefix=False, force_new_repo=False, stacked_on=None,
1786
 
        stack_on_pwd=None, repo_format_name=None, make_working_trees=None,
1787
 
        shared_repo=False):
1788
 
        """See BzrDirFormat.initialize_on_transport_ex."""
1789
 
        require_stacking = (stacked_on is not None)
1790
 
        # Format 5 cannot stack, but we've been asked to - actually init
1791
 
        # a Meta1Dir
1792
 
        if require_stacking:
1793
 
            format = BzrDirMetaFormat1()
1794
 
            return format.initialize_on_transport_ex(transport,
1795
 
                use_existing_dir=use_existing_dir, create_prefix=create_prefix,
1796
 
                force_new_repo=force_new_repo, stacked_on=stacked_on,
1797
 
                stack_on_pwd=stack_on_pwd, repo_format_name=repo_format_name,
1798
 
                make_working_trees=make_working_trees, shared_repo=shared_repo)
1799
 
        return BzrDirFormat.initialize_on_transport_ex(self, transport,
1800
 
            use_existing_dir=use_existing_dir, create_prefix=create_prefix,
1801
 
            force_new_repo=force_new_repo, stacked_on=stacked_on,
1802
 
            stack_on_pwd=stack_on_pwd, repo_format_name=repo_format_name,
1803
 
            make_working_trees=make_working_trees, shared_repo=shared_repo)
1804
 
 
1805
 
 
1806
 
class BzrDirFormat5(BzrDirFormatAllInOne):
1807
 
    """Bzr control format 5.
1808
 
 
1809
 
    This format is a combined format for working tree, branch and repository.
1810
 
    It has:
1811
 
     - Format 2 working trees [always]
1812
 
     - Format 4 branches [always]
1813
 
     - Format 5 repositories [always]
1814
 
       Unhashed stores in the repository.
1815
 
    """
1816
 
 
1817
 
    _lock_class = lockable_files.TransportLock
1818
 
 
1819
 
    def get_format_string(self):
1820
 
        """See BzrDirFormat.get_format_string()."""
1821
 
        return "Bazaar-NG branch, format 5\n"
1822
 
 
1823
 
    def get_branch_format(self):
1824
 
        from bzrlib import branch
1825
 
        return branch.BzrBranchFormat4()
1826
 
 
1827
 
    def get_format_description(self):
1828
 
        """See BzrDirFormat.get_format_description()."""
1829
 
        return "All-in-one format 5"
1830
 
 
1831
 
    def get_converter(self, format=None):
1832
 
        """See BzrDirFormat.get_converter()."""
1833
 
        # there is one and only one upgrade path here.
1834
 
        return ConvertBzrDir5To6()
1835
 
 
1836
 
    def _initialize_for_clone(self, url):
1837
 
        return self.initialize_on_transport(get_transport(url), _cloning=True)
1838
 
 
1839
 
    def initialize_on_transport(self, transport, _cloning=False):
1840
 
        """Format 5 dirs always have working tree, branch and repository.
1841
 
 
1842
 
        Except when they are being cloned.
1843
 
        """
1844
 
        from bzrlib.branch import BzrBranchFormat4
1845
 
        from bzrlib.repofmt.weaverepo import RepositoryFormat5
1846
 
        result = (super(BzrDirFormat5, self).initialize_on_transport(transport))
1847
 
        RepositoryFormat5().initialize(result, _internal=True)
1848
 
        if not _cloning:
1849
 
            branch = BzrBranchFormat4().initialize(result)
1850
 
            result._init_workingtree()
1851
 
        return result
1852
 
 
1853
 
    def network_name(self):
1854
 
        return self.get_format_string()
1855
 
 
1856
 
    def _open(self, transport):
1857
 
        """See BzrDirFormat._open."""
1858
 
        return BzrDir5(transport, self)
1859
 
 
1860
 
    def __return_repository_format(self):
1861
 
        """Circular import protection."""
1862
 
        from bzrlib.repofmt.weaverepo import RepositoryFormat5
1863
 
        return RepositoryFormat5()
1864
 
    repository_format = property(__return_repository_format)
1865
 
 
1866
 
 
1867
 
class BzrDirFormat6(BzrDirFormatAllInOne):
1868
 
    """Bzr control format 6.
1869
 
 
1870
 
    This format is a combined format for working tree, branch and repository.
1871
 
    It has:
1872
 
     - Format 2 working trees [always]
1873
 
     - Format 4 branches [always]
1874
 
     - Format 6 repositories [always]
1875
 
    """
1876
 
 
1877
 
    _lock_class = lockable_files.TransportLock
1878
 
 
1879
 
    def get_format_string(self):
1880
 
        """See BzrDirFormat.get_format_string()."""
1881
 
        return "Bazaar-NG branch, format 6\n"
1882
 
 
1883
 
    def get_format_description(self):
1884
 
        """See BzrDirFormat.get_format_description()."""
1885
 
        return "All-in-one format 6"
1886
 
 
1887
 
    def get_branch_format(self):
1888
 
        from bzrlib import branch
1889
 
        return branch.BzrBranchFormat4()
1890
 
 
1891
 
    def get_converter(self, format=None):
1892
 
        """See BzrDirFormat.get_converter()."""
1893
 
        # there is one and only one upgrade path here.
1894
 
        return ConvertBzrDir6ToMeta()
1895
 
 
1896
 
    def _initialize_for_clone(self, url):
1897
 
        return self.initialize_on_transport(get_transport(url), _cloning=True)
1898
 
 
1899
 
    def initialize_on_transport(self, transport, _cloning=False):
1900
 
        """Format 6 dirs always have working tree, branch and repository.
1901
 
 
1902
 
        Except when they are being cloned.
1903
 
        """
1904
 
        from bzrlib.branch import BzrBranchFormat4
1905
 
        from bzrlib.repofmt.weaverepo import RepositoryFormat6
1906
 
        result = super(BzrDirFormat6, self).initialize_on_transport(transport)
1907
 
        RepositoryFormat6().initialize(result, _internal=True)
1908
 
        if not _cloning:
1909
 
            branch = BzrBranchFormat4().initialize(result)
1910
 
            result._init_workingtree()
1911
 
        return result
1912
 
 
1913
 
    def network_name(self):
1914
 
        return self.get_format_string()
1915
 
 
1916
 
    def _open(self, transport):
1917
 
        """See BzrDirFormat._open."""
1918
 
        return BzrDir6(transport, self)
1919
 
 
1920
 
    def __return_repository_format(self):
1921
 
        """Circular import protection."""
1922
 
        from bzrlib.repofmt.weaverepo import RepositoryFormat6
1923
 
        return RepositoryFormat6()
1924
 
    repository_format = property(__return_repository_format)
 
1435
    def supports_transport(self, transport):
 
1436
        # bzr formats can be opened over all known transports
 
1437
        return True
1925
1438
 
1926
1439
 
1927
1440
class BzrDirMetaFormat1(BzrDirFormat):
1929
1442
 
1930
1443
    This is the first format with split out working tree, branch and repository
1931
1444
    disk storage.
 
1445
 
1932
1446
    It has:
1933
 
     - Format 3 working trees [optional]
1934
 
     - Format 5 branches [optional]
1935
 
     - Format 7 repositories [optional]
 
1447
 
 
1448
    - Format 3 working trees [optional]
 
1449
    - Format 5 branches [optional]
 
1450
    - Format 7 repositories [optional]
1936
1451
    """
1937
1452
 
1938
1453
    _lock_class = lockdir.LockDir
1939
1454
 
 
1455
    fixed_components = False
 
1456
 
 
1457
    colocated_branches = False
 
1458
 
1940
1459
    def __init__(self):
1941
1460
        self._workingtree_format = None
1942
1461
        self._branch_format = None
1956
1475
 
1957
1476
    def get_branch_format(self):
1958
1477
        if self._branch_format is None:
1959
 
            from bzrlib.branch import BranchFormat
1960
 
            self._branch_format = BranchFormat.get_default_format()
 
1478
            from bzrlib.branch import format_registry as branch_format_registry
 
1479
            self._branch_format = branch_format_registry.get_default()
1961
1480
        return self._branch_format
1962
1481
 
1963
1482
    def set_branch_format(self, format):
2018
1537
                    # stack_on is inaccessible, JFDI.
2019
1538
                    # TODO: bad monkey, hard-coded formats...
2020
1539
                    if self.repository_format.rich_root_data:
2021
 
                        new_repo_format = pack_repo.RepositoryFormatKnitPack5RichRoot()
 
1540
                        new_repo_format = knitpack_repo.RepositoryFormatKnitPack5RichRoot()
2022
1541
                    else:
2023
 
                        new_repo_format = pack_repo.RepositoryFormatKnitPack5()
 
1542
                        new_repo_format = knitpack_repo.RepositoryFormatKnitPack5()
2024
1543
            else:
2025
1544
                # If the target already supports stacking, then we know the
2026
1545
                # project is already able to use stacking, so auto-upgrade
2032
1551
                    new_repo_format = None
2033
1552
            if new_repo_format is not None:
2034
1553
                self.repository_format = new_repo_format
2035
 
                note('Source repository format does not support stacking,'
2036
 
                     ' using format:\n  %s',
 
1554
                note(gettext('Source repository format does not support stacking,'
 
1555
                     ' using format:\n  %s'),
2037
1556
                     new_repo_format.get_format_description())
2038
1557
 
2039
1558
        if not self.get_branch_format().supports_stacking():
2043
1562
            if target_branch is None:
2044
1563
                if do_upgrade:
2045
1564
                    # TODO: bad monkey, hard-coded formats...
2046
 
                    new_branch_format = branch.BzrBranchFormat7()
 
1565
                    from bzrlib.branch import BzrBranchFormat7
 
1566
                    new_branch_format = BzrBranchFormat7()
2047
1567
            else:
2048
1568
                new_branch_format = target_branch._format
2049
1569
                if not new_branch_format.supports_stacking():
2051
1571
            if new_branch_format is not None:
2052
1572
                # Does support stacking, use its format.
2053
1573
                self.set_branch_format(new_branch_format)
2054
 
                note('Source branch format does not support stacking,'
2055
 
                     ' using format:\n  %s',
 
1574
                note(gettext('Source branch format does not support stacking,'
 
1575
                     ' using format:\n  %s'),
2056
1576
                     new_branch_format.get_format_description())
2057
1577
 
2058
1578
    def get_converter(self, format=None):
2059
1579
        """See BzrDirFormat.get_converter()."""
2060
1580
        if format is None:
2061
1581
            format = BzrDirFormat.get_default_format()
 
1582
        if (type(self) is BzrDirMetaFormat1 and
 
1583
            type(format) is BzrDirMetaFormat1Colo):
 
1584
            return ConvertMetaToColo(format)
 
1585
        if (type(self) is BzrDirMetaFormat1Colo and
 
1586
            type(format) is BzrDirMetaFormat1):
 
1587
            return ConvertMetaRemoveColo(format)
2062
1588
        if not isinstance(self, format.__class__):
2063
1589
            # converting away from metadir is not implemented
2064
1590
            raise NotImplementedError(self.get_converter)
2065
1591
        return ConvertMetaToMeta(format)
2066
1592
 
2067
 
    def get_format_string(self):
 
1593
    @classmethod
 
1594
    def get_format_string(cls):
2068
1595
        """See BzrDirFormat.get_format_string()."""
2069
1596
        return "Bazaar-NG meta directory, format 1\n"
2070
1597
 
2072
1599
        """See BzrDirFormat.get_format_description()."""
2073
1600
        return "Meta directory format 1"
2074
1601
 
 
1602
    @classmethod
 
1603
    def from_string(cls, format_string):
 
1604
        if format_string != cls.get_format_string():
 
1605
            raise ValueError("Invalid format string %r" % format_string)
 
1606
        return cls()
 
1607
 
2075
1608
    def network_name(self):
2076
1609
        return self.get_format_string()
2077
1610
 
2088
1621
        """Circular import protection."""
2089
1622
        if self._repository_format:
2090
1623
            return self._repository_format
2091
 
        from bzrlib.repository import RepositoryFormat
2092
 
        return RepositoryFormat.get_default_format()
 
1624
        from bzrlib.repository import format_registry
 
1625
        return format_registry.get_default()
2093
1626
 
2094
1627
    def _set_repository_format(self, value):
2095
1628
        """Allow changing the repository format for metadir formats."""
2118
1651
 
2119
1652
    def __get_workingtree_format(self):
2120
1653
        if self._workingtree_format is None:
2121
 
            from bzrlib.workingtree import WorkingTreeFormat
2122
 
            self._workingtree_format = WorkingTreeFormat.get_default_format()
 
1654
            from bzrlib.workingtree import (
 
1655
                format_registry as wt_format_registry,
 
1656
                )
 
1657
            self._workingtree_format = wt_format_registry.get_default()
2123
1658
        return self._workingtree_format
2124
1659
 
2125
1660
    def __set_workingtree_format(self, wt_format):
2126
1661
        self._workingtree_format = wt_format
2127
1662
 
 
1663
    def __repr__(self):
 
1664
        return "<%r>" % (self.__class__.__name__,)
 
1665
 
2128
1666
    workingtree_format = property(__get_workingtree_format,
2129
1667
                                  __set_workingtree_format)
2130
1668
 
2131
1669
 
2132
1670
# Register bzr formats
2133
 
BzrDirFormat.register_format(BzrDirFormat4())
2134
 
BzrDirFormat.register_format(BzrDirFormat5())
2135
 
BzrDirFormat.register_format(BzrDirFormat6())
2136
 
__default_format = BzrDirMetaFormat1()
2137
 
BzrDirFormat.register_format(__default_format)
2138
 
controldir.ControlDirFormat._default_format = __default_format
2139
 
 
2140
 
 
2141
 
class Converter(object):
2142
 
    """Converts a disk format object from one format to another."""
2143
 
 
2144
 
    def convert(self, to_convert, pb):
2145
 
        """Perform the conversion of to_convert, giving feedback via pb.
2146
 
 
2147
 
        :param to_convert: The disk object to convert.
2148
 
        :param pb: a progress bar to use for progress information.
2149
 
        """
2150
 
 
2151
 
    def step(self, message):
2152
 
        """Update the pb by a step."""
2153
 
        self.count +=1
2154
 
        self.pb.update(message, self.count, self.total)
2155
 
 
2156
 
 
2157
 
class ConvertBzrDir4To5(Converter):
2158
 
    """Converts format 4 bzr dirs to format 5."""
2159
 
 
2160
 
    def __init__(self):
2161
 
        super(ConvertBzrDir4To5, self).__init__()
2162
 
        self.converted_revs = set()
2163
 
        self.absent_revisions = set()
2164
 
        self.text_count = 0
2165
 
        self.revisions = {}
2166
 
 
2167
 
    def convert(self, to_convert, pb):
2168
 
        """See Converter.convert()."""
2169
 
        self.bzrdir = to_convert
2170
 
        if pb is not None:
2171
 
            warnings.warn("pb parameter to convert() is deprecated")
2172
 
        self.pb = ui.ui_factory.nested_progress_bar()
2173
 
        try:
2174
 
            ui.ui_factory.note('starting upgrade from format 4 to 5')
2175
 
            if isinstance(self.bzrdir.transport, local.LocalTransport):
2176
 
                self.bzrdir.get_workingtree_transport(None).delete('stat-cache')
2177
 
            self._convert_to_weaves()
2178
 
            return BzrDir.open(self.bzrdir.user_url)
2179
 
        finally:
2180
 
            self.pb.finished()
2181
 
 
2182
 
    def _convert_to_weaves(self):
2183
 
        ui.ui_factory.note('note: upgrade may be faster if all store files are ungzipped first')
2184
 
        try:
2185
 
            # TODO permissions
2186
 
            stat = self.bzrdir.transport.stat('weaves')
2187
 
            if not S_ISDIR(stat.st_mode):
2188
 
                self.bzrdir.transport.delete('weaves')
2189
 
                self.bzrdir.transport.mkdir('weaves')
2190
 
        except errors.NoSuchFile:
2191
 
            self.bzrdir.transport.mkdir('weaves')
2192
 
        # deliberately not a WeaveFile as we want to build it up slowly.
2193
 
        self.inv_weave = Weave('inventory')
2194
 
        # holds in-memory weaves for all files
2195
 
        self.text_weaves = {}
2196
 
        self.bzrdir.transport.delete('branch-format')
2197
 
        self.branch = self.bzrdir.open_branch()
2198
 
        self._convert_working_inv()
2199
 
        rev_history = self.branch.revision_history()
2200
 
        # to_read is a stack holding the revisions we still need to process;
2201
 
        # appending to it adds new highest-priority revisions
2202
 
        self.known_revisions = set(rev_history)
2203
 
        self.to_read = rev_history[-1:]
2204
 
        while self.to_read:
2205
 
            rev_id = self.to_read.pop()
2206
 
            if (rev_id not in self.revisions
2207
 
                and rev_id not in self.absent_revisions):
2208
 
                self._load_one_rev(rev_id)
2209
 
        self.pb.clear()
2210
 
        to_import = self._make_order()
2211
 
        for i, rev_id in enumerate(to_import):
2212
 
            self.pb.update('converting revision', i, len(to_import))
2213
 
            self._convert_one_rev(rev_id)
2214
 
        self.pb.clear()
2215
 
        self._write_all_weaves()
2216
 
        self._write_all_revs()
2217
 
        ui.ui_factory.note('upgraded to weaves:')
2218
 
        ui.ui_factory.note('  %6d revisions and inventories' % len(self.revisions))
2219
 
        ui.ui_factory.note('  %6d revisions not present' % len(self.absent_revisions))
2220
 
        ui.ui_factory.note('  %6d texts' % self.text_count)
2221
 
        self._cleanup_spare_files_after_format4()
2222
 
        self.branch._transport.put_bytes(
2223
 
            'branch-format',
2224
 
            BzrDirFormat5().get_format_string(),
2225
 
            mode=self.bzrdir._get_file_mode())
2226
 
 
2227
 
    def _cleanup_spare_files_after_format4(self):
2228
 
        # FIXME working tree upgrade foo.
2229
 
        for n in 'merged-patches', 'pending-merged-patches':
2230
 
            try:
2231
 
                ## assert os.path.getsize(p) == 0
2232
 
                self.bzrdir.transport.delete(n)
2233
 
            except errors.NoSuchFile:
2234
 
                pass
2235
 
        self.bzrdir.transport.delete_tree('inventory-store')
2236
 
        self.bzrdir.transport.delete_tree('text-store')
2237
 
 
2238
 
    def _convert_working_inv(self):
2239
 
        inv = xml4.serializer_v4.read_inventory(
2240
 
                self.branch._transport.get('inventory'))
2241
 
        new_inv_xml = xml5.serializer_v5.write_inventory_to_string(inv, working=True)
2242
 
        self.branch._transport.put_bytes('inventory', new_inv_xml,
2243
 
            mode=self.bzrdir._get_file_mode())
2244
 
 
2245
 
    def _write_all_weaves(self):
2246
 
        controlweaves = WeaveStore(self.bzrdir.transport, prefixed=False)
2247
 
        weave_transport = self.bzrdir.transport.clone('weaves')
2248
 
        weaves = WeaveStore(weave_transport, prefixed=False)
2249
 
        transaction = WriteTransaction()
2250
 
 
2251
 
        try:
2252
 
            i = 0
2253
 
            for file_id, file_weave in self.text_weaves.items():
2254
 
                self.pb.update('writing weave', i, len(self.text_weaves))
2255
 
                weaves._put_weave(file_id, file_weave, transaction)
2256
 
                i += 1
2257
 
            self.pb.update('inventory', 0, 1)
2258
 
            controlweaves._put_weave('inventory', self.inv_weave, transaction)
2259
 
            self.pb.update('inventory', 1, 1)
2260
 
        finally:
2261
 
            self.pb.clear()
2262
 
 
2263
 
    def _write_all_revs(self):
2264
 
        """Write all revisions out in new form."""
2265
 
        self.bzrdir.transport.delete_tree('revision-store')
2266
 
        self.bzrdir.transport.mkdir('revision-store')
2267
 
        revision_transport = self.bzrdir.transport.clone('revision-store')
2268
 
        # TODO permissions
2269
 
        from bzrlib.xml5 import serializer_v5
2270
 
        from bzrlib.repofmt.weaverepo import RevisionTextStore
2271
 
        revision_store = RevisionTextStore(revision_transport,
2272
 
            serializer_v5, False, versionedfile.PrefixMapper(),
2273
 
            lambda:True, lambda:True)
2274
 
        try:
2275
 
            for i, rev_id in enumerate(self.converted_revs):
2276
 
                self.pb.update('write revision', i, len(self.converted_revs))
2277
 
                text = serializer_v5.write_revision_to_string(
2278
 
                    self.revisions[rev_id])
2279
 
                key = (rev_id,)
2280
 
                revision_store.add_lines(key, None, osutils.split_lines(text))
2281
 
        finally:
2282
 
            self.pb.clear()
2283
 
 
2284
 
    def _load_one_rev(self, rev_id):
2285
 
        """Load a revision object into memory.
2286
 
 
2287
 
        Any parents not either loaded or abandoned get queued to be
2288
 
        loaded."""
2289
 
        self.pb.update('loading revision',
2290
 
                       len(self.revisions),
2291
 
                       len(self.known_revisions))
2292
 
        if not self.branch.repository.has_revision(rev_id):
2293
 
            self.pb.clear()
2294
 
            ui.ui_factory.note('revision {%s} not present in branch; '
2295
 
                         'will be converted as a ghost' %
2296
 
                         rev_id)
2297
 
            self.absent_revisions.add(rev_id)
2298
 
        else:
2299
 
            rev = self.branch.repository.get_revision(rev_id)
2300
 
            for parent_id in rev.parent_ids:
2301
 
                self.known_revisions.add(parent_id)
2302
 
                self.to_read.append(parent_id)
2303
 
            self.revisions[rev_id] = rev
2304
 
 
2305
 
    def _load_old_inventory(self, rev_id):
2306
 
        f = self.branch.repository.inventory_store.get(rev_id)
2307
 
        try:
2308
 
            old_inv_xml = f.read()
2309
 
        finally:
2310
 
            f.close()
2311
 
        inv = xml4.serializer_v4.read_inventory_from_string(old_inv_xml)
2312
 
        inv.revision_id = rev_id
2313
 
        rev = self.revisions[rev_id]
2314
 
        return inv
2315
 
 
2316
 
    def _load_updated_inventory(self, rev_id):
2317
 
        inv_xml = self.inv_weave.get_text(rev_id)
2318
 
        inv = xml5.serializer_v5.read_inventory_from_string(inv_xml, rev_id)
2319
 
        return inv
2320
 
 
2321
 
    def _convert_one_rev(self, rev_id):
2322
 
        """Convert revision and all referenced objects to new format."""
2323
 
        rev = self.revisions[rev_id]
2324
 
        inv = self._load_old_inventory(rev_id)
2325
 
        present_parents = [p for p in rev.parent_ids
2326
 
                           if p not in self.absent_revisions]
2327
 
        self._convert_revision_contents(rev, inv, present_parents)
2328
 
        self._store_new_inv(rev, inv, present_parents)
2329
 
        self.converted_revs.add(rev_id)
2330
 
 
2331
 
    def _store_new_inv(self, rev, inv, present_parents):
2332
 
        new_inv_xml = xml5.serializer_v5.write_inventory_to_string(inv)
2333
 
        new_inv_sha1 = sha_string(new_inv_xml)
2334
 
        self.inv_weave.add_lines(rev.revision_id,
2335
 
                                 present_parents,
2336
 
                                 new_inv_xml.splitlines(True))
2337
 
        rev.inventory_sha1 = new_inv_sha1
2338
 
 
2339
 
    def _convert_revision_contents(self, rev, inv, present_parents):
2340
 
        """Convert all the files within a revision.
2341
 
 
2342
 
        Also upgrade the inventory to refer to the text revision ids."""
2343
 
        rev_id = rev.revision_id
2344
 
        mutter('converting texts of revision {%s}',
2345
 
               rev_id)
2346
 
        parent_invs = map(self._load_updated_inventory, present_parents)
2347
 
        entries = inv.iter_entries()
2348
 
        entries.next()
2349
 
        for path, ie in entries:
2350
 
            self._convert_file_version(rev, ie, parent_invs)
2351
 
 
2352
 
    def _convert_file_version(self, rev, ie, parent_invs):
2353
 
        """Convert one version of one file.
2354
 
 
2355
 
        The file needs to be added into the weave if it is a merge
2356
 
        of >=2 parents or if it's changed from its parent.
2357
 
        """
2358
 
        file_id = ie.file_id
2359
 
        rev_id = rev.revision_id
2360
 
        w = self.text_weaves.get(file_id)
2361
 
        if w is None:
2362
 
            w = Weave(file_id)
2363
 
            self.text_weaves[file_id] = w
2364
 
        text_changed = False
2365
 
        parent_candiate_entries = ie.parent_candidates(parent_invs)
2366
 
        heads = graph.Graph(self).heads(parent_candiate_entries.keys())
2367
 
        # XXX: Note that this is unordered - and this is tolerable because
2368
 
        # the previous code was also unordered.
2369
 
        previous_entries = dict((head, parent_candiate_entries[head]) for head
2370
 
            in heads)
2371
 
        self.snapshot_ie(previous_entries, ie, w, rev_id)
2372
 
 
2373
 
    def get_parent_map(self, revision_ids):
2374
 
        """See graph.StackedParentsProvider.get_parent_map"""
2375
 
        return dict((revision_id, self.revisions[revision_id])
2376
 
                    for revision_id in revision_ids
2377
 
                     if revision_id in self.revisions)
2378
 
 
2379
 
    def snapshot_ie(self, previous_revisions, ie, w, rev_id):
2380
 
        # TODO: convert this logic, which is ~= snapshot to
2381
 
        # a call to:. This needs the path figured out. rather than a work_tree
2382
 
        # a v4 revision_tree can be given, or something that looks enough like
2383
 
        # one to give the file content to the entry if it needs it.
2384
 
        # and we need something that looks like a weave store for snapshot to
2385
 
        # save against.
2386
 
        #ie.snapshot(rev, PATH, previous_revisions, REVISION_TREE, InMemoryWeaveStore(self.text_weaves))
2387
 
        if len(previous_revisions) == 1:
2388
 
            previous_ie = previous_revisions.values()[0]
2389
 
            if ie._unchanged(previous_ie):
2390
 
                ie.revision = previous_ie.revision
2391
 
                return
2392
 
        if ie.has_text():
2393
 
            f = self.branch.repository._text_store.get(ie.text_id)
2394
 
            try:
2395
 
                file_lines = f.readlines()
2396
 
            finally:
2397
 
                f.close()
2398
 
            w.add_lines(rev_id, previous_revisions, file_lines)
2399
 
            self.text_count += 1
2400
 
        else:
2401
 
            w.add_lines(rev_id, previous_revisions, [])
2402
 
        ie.revision = rev_id
2403
 
 
2404
 
    def _make_order(self):
2405
 
        """Return a suitable order for importing revisions.
2406
 
 
2407
 
        The order must be such that an revision is imported after all
2408
 
        its (present) parents.
2409
 
        """
2410
 
        todo = set(self.revisions.keys())
2411
 
        done = self.absent_revisions.copy()
2412
 
        order = []
2413
 
        while todo:
2414
 
            # scan through looking for a revision whose parents
2415
 
            # are all done
2416
 
            for rev_id in sorted(list(todo)):
2417
 
                rev = self.revisions[rev_id]
2418
 
                parent_ids = set(rev.parent_ids)
2419
 
                if parent_ids.issubset(done):
2420
 
                    # can take this one now
2421
 
                    order.append(rev_id)
2422
 
                    todo.remove(rev_id)
2423
 
                    done.add(rev_id)
2424
 
        return order
2425
 
 
2426
 
 
2427
 
class ConvertBzrDir5To6(Converter):
2428
 
    """Converts format 5 bzr dirs to format 6."""
2429
 
 
2430
 
    def convert(self, to_convert, pb):
2431
 
        """See Converter.convert()."""
2432
 
        self.bzrdir = to_convert
2433
 
        pb = ui.ui_factory.nested_progress_bar()
2434
 
        try:
2435
 
            ui.ui_factory.note('starting upgrade from format 5 to 6')
2436
 
            self._convert_to_prefixed()
2437
 
            return BzrDir.open(self.bzrdir.user_url)
2438
 
        finally:
2439
 
            pb.finished()
2440
 
 
2441
 
    def _convert_to_prefixed(self):
2442
 
        from bzrlib.store import TransportStore
2443
 
        self.bzrdir.transport.delete('branch-format')
2444
 
        for store_name in ["weaves", "revision-store"]:
2445
 
            ui.ui_factory.note("adding prefixes to %s" % store_name)
2446
 
            store_transport = self.bzrdir.transport.clone(store_name)
2447
 
            store = TransportStore(store_transport, prefixed=True)
2448
 
            for urlfilename in store_transport.list_dir('.'):
2449
 
                filename = urlutils.unescape(urlfilename)
2450
 
                if (filename.endswith(".weave") or
2451
 
                    filename.endswith(".gz") or
2452
 
                    filename.endswith(".sig")):
2453
 
                    file_id, suffix = os.path.splitext(filename)
2454
 
                else:
2455
 
                    file_id = filename
2456
 
                    suffix = ''
2457
 
                new_name = store._mapper.map((file_id,)) + suffix
2458
 
                # FIXME keep track of the dirs made RBC 20060121
2459
 
                try:
2460
 
                    store_transport.move(filename, new_name)
2461
 
                except errors.NoSuchFile: # catches missing dirs strangely enough
2462
 
                    store_transport.mkdir(osutils.dirname(new_name))
2463
 
                    store_transport.move(filename, new_name)
2464
 
        self.bzrdir.transport.put_bytes(
2465
 
            'branch-format',
2466
 
            BzrDirFormat6().get_format_string(),
2467
 
            mode=self.bzrdir._get_file_mode())
2468
 
 
2469
 
 
2470
 
class ConvertBzrDir6ToMeta(Converter):
2471
 
    """Converts format 6 bzr dirs to metadirs."""
2472
 
 
2473
 
    def convert(self, to_convert, pb):
2474
 
        """See Converter.convert()."""
2475
 
        from bzrlib.repofmt.weaverepo import RepositoryFormat7
2476
 
        from bzrlib.branch import BzrBranchFormat5
2477
 
        self.bzrdir = to_convert
2478
 
        self.pb = ui.ui_factory.nested_progress_bar()
2479
 
        self.count = 0
2480
 
        self.total = 20 # the steps we know about
2481
 
        self.garbage_inventories = []
2482
 
        self.dir_mode = self.bzrdir._get_dir_mode()
2483
 
        self.file_mode = self.bzrdir._get_file_mode()
2484
 
 
2485
 
        ui.ui_factory.note('starting upgrade from format 6 to metadir')
2486
 
        self.bzrdir.transport.put_bytes(
2487
 
                'branch-format',
2488
 
                "Converting to format 6",
2489
 
                mode=self.file_mode)
2490
 
        # its faster to move specific files around than to open and use the apis...
2491
 
        # first off, nuke ancestry.weave, it was never used.
2492
 
        try:
2493
 
            self.step('Removing ancestry.weave')
2494
 
            self.bzrdir.transport.delete('ancestry.weave')
2495
 
        except errors.NoSuchFile:
2496
 
            pass
2497
 
        # find out whats there
2498
 
        self.step('Finding branch files')
2499
 
        last_revision = self.bzrdir.open_branch().last_revision()
2500
 
        bzrcontents = self.bzrdir.transport.list_dir('.')
2501
 
        for name in bzrcontents:
2502
 
            if name.startswith('basis-inventory.'):
2503
 
                self.garbage_inventories.append(name)
2504
 
        # create new directories for repository, working tree and branch
2505
 
        repository_names = [('inventory.weave', True),
2506
 
                            ('revision-store', True),
2507
 
                            ('weaves', True)]
2508
 
        self.step('Upgrading repository  ')
2509
 
        self.bzrdir.transport.mkdir('repository', mode=self.dir_mode)
2510
 
        self.make_lock('repository')
2511
 
        # we hard code the formats here because we are converting into
2512
 
        # the meta format. The meta format upgrader can take this to a
2513
 
        # future format within each component.
2514
 
        self.put_format('repository', RepositoryFormat7())
2515
 
        for entry in repository_names:
2516
 
            self.move_entry('repository', entry)
2517
 
 
2518
 
        self.step('Upgrading branch      ')
2519
 
        self.bzrdir.transport.mkdir('branch', mode=self.dir_mode)
2520
 
        self.make_lock('branch')
2521
 
        self.put_format('branch', BzrBranchFormat5())
2522
 
        branch_files = [('revision-history', True),
2523
 
                        ('branch-name', True),
2524
 
                        ('parent', False)]
2525
 
        for entry in branch_files:
2526
 
            self.move_entry('branch', entry)
2527
 
 
2528
 
        checkout_files = [('pending-merges', True),
2529
 
                          ('inventory', True),
2530
 
                          ('stat-cache', False)]
2531
 
        # If a mandatory checkout file is not present, the branch does not have
2532
 
        # a functional checkout. Do not create a checkout in the converted
2533
 
        # branch.
2534
 
        for name, mandatory in checkout_files:
2535
 
            if mandatory and name not in bzrcontents:
2536
 
                has_checkout = False
2537
 
                break
2538
 
        else:
2539
 
            has_checkout = True
2540
 
        if not has_checkout:
2541
 
            ui.ui_factory.note('No working tree.')
2542
 
            # If some checkout files are there, we may as well get rid of them.
2543
 
            for name, mandatory in checkout_files:
2544
 
                if name in bzrcontents:
2545
 
                    self.bzrdir.transport.delete(name)
2546
 
        else:
2547
 
            from bzrlib.workingtree import WorkingTreeFormat3
2548
 
            self.step('Upgrading working tree')
2549
 
            self.bzrdir.transport.mkdir('checkout', mode=self.dir_mode)
2550
 
            self.make_lock('checkout')
2551
 
            self.put_format(
2552
 
                'checkout', WorkingTreeFormat3())
2553
 
            self.bzrdir.transport.delete_multi(
2554
 
                self.garbage_inventories, self.pb)
2555
 
            for entry in checkout_files:
2556
 
                self.move_entry('checkout', entry)
2557
 
            if last_revision is not None:
2558
 
                self.bzrdir.transport.put_bytes(
2559
 
                    'checkout/last-revision', last_revision)
2560
 
        self.bzrdir.transport.put_bytes(
2561
 
            'branch-format',
2562
 
            BzrDirMetaFormat1().get_format_string(),
2563
 
            mode=self.file_mode)
2564
 
        self.pb.finished()
2565
 
        return BzrDir.open(self.bzrdir.user_url)
2566
 
 
2567
 
    def make_lock(self, name):
2568
 
        """Make a lock for the new control dir name."""
2569
 
        self.step('Make %s lock' % name)
2570
 
        ld = lockdir.LockDir(self.bzrdir.transport,
2571
 
                             '%s/lock' % name,
2572
 
                             file_modebits=self.file_mode,
2573
 
                             dir_modebits=self.dir_mode)
2574
 
        ld.create()
2575
 
 
2576
 
    def move_entry(self, new_dir, entry):
2577
 
        """Move then entry name into new_dir."""
2578
 
        name = entry[0]
2579
 
        mandatory = entry[1]
2580
 
        self.step('Moving %s' % name)
2581
 
        try:
2582
 
            self.bzrdir.transport.move(name, '%s/%s' % (new_dir, name))
2583
 
        except errors.NoSuchFile:
2584
 
            if mandatory:
2585
 
                raise
2586
 
 
2587
 
    def put_format(self, dirname, format):
2588
 
        self.bzrdir.transport.put_bytes('%s/format' % dirname,
2589
 
            format.get_format_string(),
2590
 
            self.file_mode)
2591
 
 
2592
 
 
2593
 
class ConvertMetaToMeta(Converter):
 
1671
BzrProber.formats.register(BzrDirMetaFormat1.get_format_string(),
 
1672
    BzrDirMetaFormat1)
 
1673
controldir.ControlDirFormat._default_format = BzrDirMetaFormat1()
 
1674
 
 
1675
 
 
1676
class BzrDirMetaFormat1Colo(BzrDirMetaFormat1):
 
1677
    """BzrDirMeta1 format with support for colocated branches."""
 
1678
 
 
1679
    colocated_branches = True
 
1680
 
 
1681
    @classmethod
 
1682
    def get_format_string(cls):
 
1683
        """See BzrDirFormat.get_format_string()."""
 
1684
        return "Bazaar meta directory, format 1 (with colocated branches)\n"
 
1685
 
 
1686
    def get_format_description(self):
 
1687
        """See BzrDirFormat.get_format_description()."""
 
1688
        return "Meta directory format 1 with support for colocated branches"
 
1689
 
 
1690
    def _open(self, transport):
 
1691
        """See BzrDirFormat._open."""
 
1692
        # Create a new format instance because otherwise initialisation of new
 
1693
        # metadirs share the global default format object leading to alias
 
1694
        # problems.
 
1695
        format = BzrDirMetaFormat1Colo()
 
1696
        self._supply_sub_formats_to(format)
 
1697
        return BzrDirMeta1Colo(transport, format)
 
1698
 
 
1699
 
 
1700
BzrProber.formats.register(BzrDirMetaFormat1Colo.get_format_string(),
 
1701
    BzrDirMetaFormat1Colo)
 
1702
 
 
1703
 
 
1704
class ConvertMetaToMeta(controldir.Converter):
2594
1705
    """Converts the components of metadirs."""
2595
1706
 
2596
1707
    def __init__(self, target_format):
2614
1725
        else:
2615
1726
            if not isinstance(repo._format, self.target_format.repository_format.__class__):
2616
1727
                from bzrlib.repository import CopyConverter
2617
 
                ui.ui_factory.note('starting repository conversion')
 
1728
                ui.ui_factory.note(gettext('starting repository conversion'))
2618
1729
                converter = CopyConverter(self.target_format.repository_format)
2619
1730
                converter.convert(repo, pb)
2620
1731
        for branch in self.bzrdir.list_branches():
2621
1732
            # TODO: conversions of Branch and Tree should be done by
2622
1733
            # InterXFormat lookups/some sort of registry.
2623
1734
            # Avoid circular imports
2624
 
            from bzrlib import branch as _mod_branch
2625
1735
            old = branch._format.__class__
2626
1736
            new = self.target_format.get_branch_format().__class__
2627
1737
            while old != new:
2650
1760
        else:
2651
1761
            # TODO: conversions of Branch and Tree should be done by
2652
1762
            # InterXFormat lookups
2653
 
            if (isinstance(tree, workingtree.WorkingTree3) and
 
1763
            if (isinstance(tree, workingtree_3.WorkingTree3) and
2654
1764
                not isinstance(tree, workingtree_4.DirStateWorkingTree) and
2655
1765
                isinstance(self.target_format.workingtree_format,
2656
1766
                    workingtree_4.DirStateWorkingTreeFormat)):
2669
1779
        return to_convert
2670
1780
 
2671
1781
 
2672
 
# This is not in remote.py because it's relatively small, and needs to be
2673
 
# registered. Putting it in remote.py creates a circular import problem.
2674
 
# we can make it a lazy object if the control formats is turned into something
2675
 
# like a registry.
2676
 
class RemoteBzrDirFormat(BzrDirMetaFormat1):
2677
 
    """Format representing bzrdirs accessed via a smart server"""
2678
 
 
2679
 
    supports_workingtrees = False
2680
 
 
2681
 
    def __init__(self):
2682
 
        BzrDirMetaFormat1.__init__(self)
2683
 
        # XXX: It's a bit ugly that the network name is here, because we'd
2684
 
        # like to believe that format objects are stateless or at least
2685
 
        # immutable,  However, we do at least avoid mutating the name after
2686
 
        # it's returned.  See <https://bugs.launchpad.net/bzr/+bug/504102>
2687
 
        self._network_name = None
2688
 
 
2689
 
    def __repr__(self):
2690
 
        return "%s(_network_name=%r)" % (self.__class__.__name__,
2691
 
            self._network_name)
2692
 
 
2693
 
    def get_format_description(self):
2694
 
        if self._network_name:
2695
 
            real_format = controldir.network_format_registry.get(self._network_name)
2696
 
            return 'Remote: ' + real_format.get_format_description()
2697
 
        return 'bzr remote bzrdir'
2698
 
 
2699
 
    def get_format_string(self):
2700
 
        raise NotImplementedError(self.get_format_string)
2701
 
 
2702
 
    def network_name(self):
2703
 
        if self._network_name:
2704
 
            return self._network_name
2705
 
        else:
2706
 
            raise AssertionError("No network name set.")
2707
 
 
2708
 
    def initialize_on_transport(self, transport):
2709
 
        try:
2710
 
            # hand off the request to the smart server
2711
 
            client_medium = transport.get_smart_medium()
2712
 
        except errors.NoSmartMedium:
2713
 
            # TODO: lookup the local format from a server hint.
2714
 
            local_dir_format = BzrDirMetaFormat1()
2715
 
            return local_dir_format.initialize_on_transport(transport)
2716
 
        client = _SmartClient(client_medium)
2717
 
        path = client.remote_path_from_transport(transport)
2718
 
        try:
2719
 
            response = client.call('BzrDirFormat.initialize', path)
2720
 
        except errors.ErrorFromSmartServer, err:
2721
 
            remote._translate_error(err, path=path)
2722
 
        if response[0] != 'ok':
2723
 
            raise errors.SmartProtocolError('unexpected response code %s' % (response,))
2724
 
        format = RemoteBzrDirFormat()
2725
 
        self._supply_sub_formats_to(format)
2726
 
        return remote.RemoteBzrDir(transport, format)
2727
 
 
2728
 
    def parse_NoneTrueFalse(self, arg):
2729
 
        if not arg:
2730
 
            return None
2731
 
        if arg == 'False':
2732
 
            return False
2733
 
        if arg == 'True':
2734
 
            return True
2735
 
        raise AssertionError("invalid arg %r" % arg)
2736
 
 
2737
 
    def _serialize_NoneTrueFalse(self, arg):
2738
 
        if arg is False:
2739
 
            return 'False'
2740
 
        if arg:
2741
 
            return 'True'
2742
 
        return ''
2743
 
 
2744
 
    def _serialize_NoneString(self, arg):
2745
 
        return arg or ''
2746
 
 
2747
 
    def initialize_on_transport_ex(self, transport, use_existing_dir=False,
2748
 
        create_prefix=False, force_new_repo=False, stacked_on=None,
2749
 
        stack_on_pwd=None, repo_format_name=None, make_working_trees=None,
2750
 
        shared_repo=False):
2751
 
        try:
2752
 
            # hand off the request to the smart server
2753
 
            client_medium = transport.get_smart_medium()
2754
 
        except errors.NoSmartMedium:
2755
 
            do_vfs = True
2756
 
        else:
2757
 
            # Decline to open it if the server doesn't support our required
2758
 
            # version (3) so that the VFS-based transport will do it.
2759
 
            if client_medium.should_probe():
2760
 
                try:
2761
 
                    server_version = client_medium.protocol_version()
2762
 
                    if server_version != '2':
2763
 
                        do_vfs = True
2764
 
                    else:
2765
 
                        do_vfs = False
2766
 
                except errors.SmartProtocolError:
2767
 
                    # Apparently there's no usable smart server there, even though
2768
 
                    # the medium supports the smart protocol.
2769
 
                    do_vfs = True
2770
 
            else:
2771
 
                do_vfs = False
2772
 
        if not do_vfs:
2773
 
            client = _SmartClient(client_medium)
2774
 
            path = client.remote_path_from_transport(transport)
2775
 
            if client_medium._is_remote_before((1, 16)):
2776
 
                do_vfs = True
2777
 
        if do_vfs:
2778
 
            # TODO: lookup the local format from a server hint.
2779
 
            local_dir_format = BzrDirMetaFormat1()
2780
 
            self._supply_sub_formats_to(local_dir_format)
2781
 
            return local_dir_format.initialize_on_transport_ex(transport,
2782
 
                use_existing_dir=use_existing_dir, create_prefix=create_prefix,
2783
 
                force_new_repo=force_new_repo, stacked_on=stacked_on,
2784
 
                stack_on_pwd=stack_on_pwd, repo_format_name=repo_format_name,
2785
 
                make_working_trees=make_working_trees, shared_repo=shared_repo,
2786
 
                vfs_only=True)
2787
 
        return self._initialize_on_transport_ex_rpc(client, path, transport,
2788
 
            use_existing_dir, create_prefix, force_new_repo, stacked_on,
2789
 
            stack_on_pwd, repo_format_name, make_working_trees, shared_repo)
2790
 
 
2791
 
    def _initialize_on_transport_ex_rpc(self, client, path, transport,
2792
 
        use_existing_dir, create_prefix, force_new_repo, stacked_on,
2793
 
        stack_on_pwd, repo_format_name, make_working_trees, shared_repo):
2794
 
        args = []
2795
 
        args.append(self._serialize_NoneTrueFalse(use_existing_dir))
2796
 
        args.append(self._serialize_NoneTrueFalse(create_prefix))
2797
 
        args.append(self._serialize_NoneTrueFalse(force_new_repo))
2798
 
        args.append(self._serialize_NoneString(stacked_on))
2799
 
        # stack_on_pwd is often/usually our transport
2800
 
        if stack_on_pwd:
2801
 
            try:
2802
 
                stack_on_pwd = transport.relpath(stack_on_pwd)
2803
 
                if not stack_on_pwd:
2804
 
                    stack_on_pwd = '.'
2805
 
            except errors.PathNotChild:
2806
 
                pass
2807
 
        args.append(self._serialize_NoneString(stack_on_pwd))
2808
 
        args.append(self._serialize_NoneString(repo_format_name))
2809
 
        args.append(self._serialize_NoneTrueFalse(make_working_trees))
2810
 
        args.append(self._serialize_NoneTrueFalse(shared_repo))
2811
 
        request_network_name = self._network_name or \
2812
 
            BzrDirFormat.get_default_format().network_name()
2813
 
        try:
2814
 
            response = client.call('BzrDirFormat.initialize_ex_1.16',
2815
 
                request_network_name, path, *args)
2816
 
        except errors.UnknownSmartMethod:
2817
 
            client._medium._remember_remote_is_before((1,16))
2818
 
            local_dir_format = BzrDirMetaFormat1()
2819
 
            self._supply_sub_formats_to(local_dir_format)
2820
 
            return local_dir_format.initialize_on_transport_ex(transport,
2821
 
                use_existing_dir=use_existing_dir, create_prefix=create_prefix,
2822
 
                force_new_repo=force_new_repo, stacked_on=stacked_on,
2823
 
                stack_on_pwd=stack_on_pwd, repo_format_name=repo_format_name,
2824
 
                make_working_trees=make_working_trees, shared_repo=shared_repo,
2825
 
                vfs_only=True)
2826
 
        except errors.ErrorFromSmartServer, err:
2827
 
            remote._translate_error(err, path=path)
2828
 
        repo_path = response[0]
2829
 
        bzrdir_name = response[6]
2830
 
        require_stacking = response[7]
2831
 
        require_stacking = self.parse_NoneTrueFalse(require_stacking)
2832
 
        format = RemoteBzrDirFormat()
2833
 
        format._network_name = bzrdir_name
2834
 
        self._supply_sub_formats_to(format)
2835
 
        bzrdir = remote.RemoteBzrDir(transport, format, _client=client)
2836
 
        if repo_path:
2837
 
            repo_format = remote.response_tuple_to_repo_format(response[1:])
2838
 
            if repo_path == '.':
2839
 
                repo_path = ''
2840
 
            if repo_path:
2841
 
                repo_bzrdir_format = RemoteBzrDirFormat()
2842
 
                repo_bzrdir_format._network_name = response[5]
2843
 
                repo_bzr = remote.RemoteBzrDir(transport.clone(repo_path),
2844
 
                    repo_bzrdir_format)
2845
 
            else:
2846
 
                repo_bzr = bzrdir
2847
 
            final_stack = response[8] or None
2848
 
            final_stack_pwd = response[9] or None
2849
 
            if final_stack_pwd:
2850
 
                final_stack_pwd = urlutils.join(
2851
 
                    transport.base, final_stack_pwd)
2852
 
            remote_repo = remote.RemoteRepository(repo_bzr, repo_format)
2853
 
            if len(response) > 10:
2854
 
                # Updated server verb that locks remotely.
2855
 
                repo_lock_token = response[10] or None
2856
 
                remote_repo.lock_write(repo_lock_token, _skip_rpc=True)
2857
 
                if repo_lock_token:
2858
 
                    remote_repo.dont_leave_lock_in_place()
2859
 
            else:
2860
 
                remote_repo.lock_write()
2861
 
            policy = UseExistingRepository(remote_repo, final_stack,
2862
 
                final_stack_pwd, require_stacking)
2863
 
            policy.acquire_repository()
2864
 
        else:
2865
 
            remote_repo = None
2866
 
            policy = None
2867
 
        bzrdir._format.set_branch_format(self.get_branch_format())
2868
 
        if require_stacking:
2869
 
            # The repo has already been created, but we need to make sure that
2870
 
            # we'll make a stackable branch.
2871
 
            bzrdir._format.require_stacking(_skip_repo=True)
2872
 
        return remote_repo, bzrdir, require_stacking, policy
2873
 
 
2874
 
    def _open(self, transport):
2875
 
        return remote.RemoteBzrDir(transport, self)
2876
 
 
2877
 
    def __eq__(self, other):
2878
 
        if not isinstance(other, RemoteBzrDirFormat):
2879
 
            return False
2880
 
        return self.get_format_description() == other.get_format_description()
2881
 
 
2882
 
    def __return_repository_format(self):
2883
 
        # Always return a RemoteRepositoryFormat object, but if a specific bzr
2884
 
        # repository format has been asked for, tell the RemoteRepositoryFormat
2885
 
        # that it should use that for init() etc.
2886
 
        result = remote.RemoteRepositoryFormat()
2887
 
        custom_format = getattr(self, '_repository_format', None)
2888
 
        if custom_format:
2889
 
            if isinstance(custom_format, remote.RemoteRepositoryFormat):
2890
 
                return custom_format
2891
 
            else:
2892
 
                # We will use the custom format to create repositories over the
2893
 
                # wire; expose its details like rich_root_data for code to
2894
 
                # query
2895
 
                result._custom_format = custom_format
2896
 
        return result
2897
 
 
2898
 
    def get_branch_format(self):
2899
 
        result = BzrDirMetaFormat1.get_branch_format(self)
2900
 
        if not isinstance(result, remote.RemoteBranchFormat):
2901
 
            new_result = remote.RemoteBranchFormat()
2902
 
            new_result._custom_format = result
2903
 
            # cache the result
2904
 
            self.set_branch_format(new_result)
2905
 
            result = new_result
2906
 
        return result
2907
 
 
2908
 
    repository_format = property(__return_repository_format,
2909
 
        BzrDirMetaFormat1._set_repository_format) #.im_func)
 
1782
class ConvertMetaToColo(controldir.Converter):
 
1783
    """Add colocated branch support."""
 
1784
 
 
1785
    def __init__(self, target_format):
 
1786
        """Create a converter.that upgrades a metadir to the colo format.
 
1787
 
 
1788
        :param target_format: The final metadir format that is desired.
 
1789
        """
 
1790
        self.target_format = target_format
 
1791
 
 
1792
    def convert(self, to_convert, pb):
 
1793
        """See Converter.convert()."""
 
1794
        to_convert.transport.put_bytes('branch-format',
 
1795
            self.target_format.get_format_string())
 
1796
        return BzrDir.open_from_transport(to_convert.root_transport)
 
1797
 
 
1798
 
 
1799
class ConvertMetaRemoveColo(controldir.Converter):
 
1800
    """Remove colocated branch support from a bzrdir."""
 
1801
 
 
1802
    def __init__(self, target_format):
 
1803
        """Create a converter.that downgrades a colocated branch metadir
 
1804
        to a regular metadir.
 
1805
 
 
1806
        :param target_format: The final metadir format that is desired.
 
1807
        """
 
1808
        self.target_format = target_format
 
1809
 
 
1810
    def convert(self, to_convert, pb):
 
1811
        """See Converter.convert()."""
 
1812
        to_convert.control_files.lock_write()
 
1813
        try:
 
1814
            branches = to_convert.list_branches()
 
1815
            if len(branches) > 1:
 
1816
                raise errors.BzrError("remove all but a single "
 
1817
                    "colocated branch when downgrading")
 
1818
        finally:
 
1819
            to_convert.control_files.unlock()
 
1820
        to_convert.transport.put_bytes('branch-format',
 
1821
            self.target_format.get_format_string())
 
1822
        return BzrDir.open_from_transport(to_convert.root_transport)
2910
1823
 
2911
1824
 
2912
1825
controldir.ControlDirFormat.register_server_prober(RemoteBzrProber)
2991
1904
        else:
2992
1905
            self._require_stacking = True
2993
1906
 
2994
 
    def acquire_repository(self, make_working_trees=None, shared=False):
 
1907
    def acquire_repository(self, make_working_trees=None, shared=False,
 
1908
            possible_transports=None):
2995
1909
        """Acquire a repository for this bzrdir.
2996
1910
 
2997
1911
        Implementations may create a new repository or use a pre-exising
2998
1912
        repository.
 
1913
 
2999
1914
        :param make_working_trees: If creating a repository, set
3000
1915
            make_working_trees to this value (if non-None)
3001
1916
        :param shared: If creating a repository, make it shared if True
3010
1925
 
3011
1926
    def __init__(self, bzrdir, stack_on=None, stack_on_pwd=None,
3012
1927
                 require_stacking=False):
3013
 
        """
3014
 
        Constructor.
 
1928
        """Constructor.
 
1929
 
3015
1930
        :param bzrdir: The bzrdir to create the repository on.
3016
1931
        :param stack_on: A location to stack on
3017
1932
        :param stack_on_pwd: If stack_on is relative, the location it is
3021
1936
                                             require_stacking)
3022
1937
        self._bzrdir = bzrdir
3023
1938
 
3024
 
    def acquire_repository(self, make_working_trees=None, shared=False):
 
1939
    def acquire_repository(self, make_working_trees=None, shared=False,
 
1940
            possible_transports=None):
3025
1941
        """Implementation of RepositoryAcquisitionPolicy.acquire_repository
3026
1942
 
3027
1943
        Creates the desired repository in the bzrdir we already have.
3028
1944
        """
 
1945
        if possible_transports is None:
 
1946
            possible_transports = []
 
1947
        else:
 
1948
            possible_transports = list(possible_transports)
 
1949
        possible_transports.append(self._bzrdir.root_transport)
3029
1950
        stack_on = self._get_full_stack_on()
3030
1951
        if stack_on:
3031
1952
            format = self._bzrdir._format
3032
1953
            format.require_stacking(stack_on=stack_on,
3033
 
                                    possible_transports=[self._bzrdir.root_transport])
 
1954
                                    possible_transports=possible_transports)
3034
1955
            if not self._require_stacking:
3035
1956
                # We have picked up automatic stacking somewhere.
3036
 
                note('Using default stacking branch %s at %s', self._stack_on,
3037
 
                    self._stack_on_pwd)
 
1957
                note(gettext('Using default stacking branch {0} at {1}').format(
 
1958
                    self._stack_on, self._stack_on_pwd))
3038
1959
        repository = self._bzrdir.create_repository(shared=shared)
3039
1960
        self._add_fallback(repository,
3040
 
                           possible_transports=[self._bzrdir.transport])
 
1961
                           possible_transports=possible_transports)
3041
1962
        if make_working_trees is not None:
3042
1963
            repository.set_make_working_trees(make_working_trees)
3043
1964
        return repository, True
3059
1980
                                             require_stacking)
3060
1981
        self._repository = repository
3061
1982
 
3062
 
    def acquire_repository(self, make_working_trees=None, shared=False):
 
1983
    def acquire_repository(self, make_working_trees=None, shared=False,
 
1984
            possible_transports=None):
3063
1985
        """Implementation of RepositoryAcquisitionPolicy.acquire_repository
3064
1986
 
3065
1987
        Returns an existing repository to use.
3066
1988
        """
 
1989
        if possible_transports is None:
 
1990
            possible_transports = []
 
1991
        else:
 
1992
            possible_transports = list(possible_transports)
 
1993
        possible_transports.append(self._repository.bzrdir.transport)
3067
1994
        self._add_fallback(self._repository,
3068
 
                       possible_transports=[self._repository.bzrdir.transport])
 
1995
                       possible_transports=possible_transports)
3069
1996
        return self._repository, False
3070
1997
 
3071
1998
 
3075
2002
         tree_format=None,
3076
2003
         hidden=False,
3077
2004
         experimental=False,
3078
 
         alias=False):
 
2005
         alias=False, bzrdir_format=None):
3079
2006
    """Register a metadir subformat.
3080
2007
 
3081
 
    These all use a BzrDirMetaFormat1 bzrdir, but can be parameterized
3082
 
    by the Repository/Branch/WorkingTreeformats.
 
2008
    These all use a meta bzrdir, but can be parameterized by the
 
2009
    Repository/Branch/WorkingTreeformats.
3083
2010
 
3084
2011
    :param repository_format: The fully-qualified repository format class
3085
2012
        name as a string.
3088
2015
    :param tree_format: Fully-qualified tree format class name as
3089
2016
        a string.
3090
2017
    """
 
2018
    if bzrdir_format is None:
 
2019
        bzrdir_format = BzrDirMetaFormat1
3091
2020
    # This should be expanded to support setting WorkingTree and Branch
3092
 
    # formats, once BzrDirMetaFormat1 supports that.
 
2021
    # formats, once the API supports that.
3093
2022
    def _load(full_name):
3094
2023
        mod_name, factory_name = full_name.rsplit('.', 1)
3095
2024
        try:
3102
2031
        return factory()
3103
2032
 
3104
2033
    def helper():
3105
 
        bd = BzrDirMetaFormat1()
 
2034
        bd = bzrdir_format()
3106
2035
        if branch_format is not None:
3107
2036
            bd.set_branch_format(_load(branch_format))
3108
2037
        if tree_format is not None:
3113
2042
    registry.register(key, helper, help, native, deprecated, hidden,
3114
2043
        experimental, alias)
3115
2044
 
3116
 
# The pre-0.8 formats have their repository format network name registered in
3117
 
# repository.py. MetaDir formats have their repository format network name
3118
 
# inferred from their disk format string.
3119
 
controldir.format_registry.register('weave', BzrDirFormat6,
3120
 
    'Pre-0.8 format.  Slower than knit and does not'
3121
 
    ' support checkouts or shared repositories.',
3122
 
    hidden=True,
3123
 
    deprecated=True)
3124
 
register_metadir(controldir.format_registry, 'metaweave',
3125
 
    'bzrlib.repofmt.weaverepo.RepositoryFormat7',
3126
 
    'Transitional format in 0.8.  Slower than knit.',
3127
 
    branch_format='bzrlib.branch.BzrBranchFormat5',
3128
 
    tree_format='bzrlib.workingtree.WorkingTreeFormat3',
3129
 
    hidden=True,
3130
 
    deprecated=True)
3131
2045
register_metadir(controldir.format_registry, 'knit',
3132
2046
    'bzrlib.repofmt.knitrepo.RepositoryFormatKnit1',
3133
2047
    'Format using knits.  Recommended for interoperation with bzr <= 0.14.',
3134
2048
    branch_format='bzrlib.branch.BzrBranchFormat5',
3135
 
    tree_format='bzrlib.workingtree.WorkingTreeFormat3',
 
2049
    tree_format='bzrlib.workingtree_3.WorkingTreeFormat3',
3136
2050
    hidden=True,
3137
2051
    deprecated=True)
3138
2052
register_metadir(controldir.format_registry, 'dirstate',
3139
2053
    'bzrlib.repofmt.knitrepo.RepositoryFormatKnit1',
3140
 
    help='New in 0.15: Fast local operations. Compatible with bzr 0.8 and '
3141
 
        'above when accessed over the network.',
 
2054
    help='Format using dirstate for working trees. '
 
2055
        'Compatible with bzr 0.8 and '
 
2056
        'above when accessed over the network. Introduced in bzr 0.15.',
3142
2057
    branch_format='bzrlib.branch.BzrBranchFormat5',
3143
 
    # this uses bzrlib.workingtree.WorkingTreeFormat4 because importing
3144
 
    # directly from workingtree_4 triggers a circular import.
3145
 
    tree_format='bzrlib.workingtree.WorkingTreeFormat4',
 
2058
    tree_format='bzrlib.workingtree_4.WorkingTreeFormat4',
3146
2059
    hidden=True,
3147
2060
    deprecated=True)
3148
2061
register_metadir(controldir.format_registry, 'dirstate-tags',
3149
2062
    'bzrlib.repofmt.knitrepo.RepositoryFormatKnit1',
3150
 
    help='New in 0.15: Fast local operations and improved scaling for '
3151
 
        'network operations. Additionally adds support for tags.'
3152
 
        ' Incompatible with bzr < 0.15.',
 
2063
    help='Variant of dirstate with support for tags. '
 
2064
        'Introduced in bzr 0.15.',
3153
2065
    branch_format='bzrlib.branch.BzrBranchFormat6',
3154
 
    tree_format='bzrlib.workingtree.WorkingTreeFormat4',
 
2066
    tree_format='bzrlib.workingtree_4.WorkingTreeFormat4',
3155
2067
    hidden=True,
3156
2068
    deprecated=True)
3157
2069
register_metadir(controldir.format_registry, 'rich-root',
3158
2070
    'bzrlib.repofmt.knitrepo.RepositoryFormatKnit4',
3159
 
    help='New in 1.0.  Better handling of tree roots.  Incompatible with'
3160
 
        ' bzr < 1.0.',
 
2071
    help='Variant of dirstate with better handling of tree roots. '
 
2072
        'Introduced in bzr 1.0',
3161
2073
    branch_format='bzrlib.branch.BzrBranchFormat6',
3162
 
    tree_format='bzrlib.workingtree.WorkingTreeFormat4',
 
2074
    tree_format='bzrlib.workingtree_4.WorkingTreeFormat4',
3163
2075
    hidden=True,
3164
2076
    deprecated=True)
3165
2077
register_metadir(controldir.format_registry, 'dirstate-with-subtree',
3166
2078
    'bzrlib.repofmt.knitrepo.RepositoryFormatKnit3',
3167
 
    help='New in 0.15: Fast local operations and improved scaling for '
3168
 
        'network operations. Additionally adds support for versioning nested '
3169
 
        'bzr branches. Incompatible with bzr < 0.15.',
 
2079
    help='Variant of dirstate with support for nested trees. '
 
2080
         'Introduced in 0.15.',
3170
2081
    branch_format='bzrlib.branch.BzrBranchFormat6',
3171
 
    tree_format='bzrlib.workingtree.WorkingTreeFormat4',
 
2082
    tree_format='bzrlib.workingtree_4.WorkingTreeFormat4',
3172
2083
    experimental=True,
3173
2084
    hidden=True,
3174
2085
    )
3175
2086
register_metadir(controldir.format_registry, 'pack-0.92',
3176
 
    'bzrlib.repofmt.pack_repo.RepositoryFormatKnitPack1',
3177
 
    help='New in 0.92: Pack-based format with data compatible with '
3178
 
        'dirstate-tags format repositories. Interoperates with '
3179
 
        'bzr repositories before 0.92 but cannot be read by bzr < 0.92. '
 
2087
    'bzrlib.repofmt.knitpack_repo.RepositoryFormatKnitPack1',
 
2088
    help='Pack-based format used in 1.x series. Introduced in 0.92. '
 
2089
        'Interoperates with bzr repositories before 0.92 but cannot be '
 
2090
        'read by bzr < 0.92. '
3180
2091
        ,
3181
2092
    branch_format='bzrlib.branch.BzrBranchFormat6',
3182
 
    tree_format='bzrlib.workingtree.WorkingTreeFormat4',
 
2093
    tree_format='bzrlib.workingtree_4.WorkingTreeFormat4',
 
2094
    deprecated=True,
3183
2095
    )
3184
2096
register_metadir(controldir.format_registry, 'pack-0.92-subtree',
3185
 
    'bzrlib.repofmt.pack_repo.RepositoryFormatKnitPack3',
3186
 
    help='New in 0.92: Pack-based format with data compatible with '
3187
 
        'dirstate-with-subtree format repositories. Interoperates with '
 
2097
    'bzrlib.repofmt.knitpack_repo.RepositoryFormatKnitPack3',
 
2098
    help='Pack-based format used in 1.x series, with subtree support. '
 
2099
        'Introduced in 0.92. Interoperates with '
3188
2100
        'bzr repositories before 0.92 but cannot be read by bzr < 0.92. '
3189
2101
        ,
3190
2102
    branch_format='bzrlib.branch.BzrBranchFormat6',
3191
 
    tree_format='bzrlib.workingtree.WorkingTreeFormat4',
 
2103
    tree_format='bzrlib.workingtree_4.WorkingTreeFormat4',
3192
2104
    hidden=True,
 
2105
    deprecated=True,
3193
2106
    experimental=True,
3194
2107
    )
3195
2108
register_metadir(controldir.format_registry, 'rich-root-pack',
3196
 
    'bzrlib.repofmt.pack_repo.RepositoryFormatKnitPack4',
3197
 
    help='New in 1.0: A variant of pack-0.92 that supports rich-root data '
3198
 
         '(needed for bzr-svn and bzr-git).',
 
2109
    'bzrlib.repofmt.knitpack_repo.RepositoryFormatKnitPack4',
 
2110
    help='A variant of pack-0.92 that supports rich-root data '
 
2111
         '(needed for bzr-svn and bzr-git). Introduced in 1.0.',
3199
2112
    branch_format='bzrlib.branch.BzrBranchFormat6',
3200
 
    tree_format='bzrlib.workingtree.WorkingTreeFormat4',
 
2113
    tree_format='bzrlib.workingtree_4.WorkingTreeFormat4',
3201
2114
    hidden=True,
 
2115
    deprecated=True,
3202
2116
    )
3203
2117
register_metadir(controldir.format_registry, '1.6',
3204
 
    'bzrlib.repofmt.pack_repo.RepositoryFormatKnitPack5',
 
2118
    'bzrlib.repofmt.knitpack_repo.RepositoryFormatKnitPack5',
3205
2119
    help='A format that allows a branch to indicate that there is another '
3206
2120
         '(stacked) repository that should be used to access data that is '
3207
2121
         'not present locally.',
3208
2122
    branch_format='bzrlib.branch.BzrBranchFormat7',
3209
 
    tree_format='bzrlib.workingtree.WorkingTreeFormat4',
 
2123
    tree_format='bzrlib.workingtree_4.WorkingTreeFormat4',
3210
2124
    hidden=True,
 
2125
    deprecated=True,
3211
2126
    )
3212
2127
register_metadir(controldir.format_registry, '1.6.1-rich-root',
3213
 
    'bzrlib.repofmt.pack_repo.RepositoryFormatKnitPack5RichRoot',
 
2128
    'bzrlib.repofmt.knitpack_repo.RepositoryFormatKnitPack5RichRoot',
3214
2129
    help='A variant of 1.6 that supports rich-root data '
3215
2130
         '(needed for bzr-svn and bzr-git).',
3216
2131
    branch_format='bzrlib.branch.BzrBranchFormat7',
3217
 
    tree_format='bzrlib.workingtree.WorkingTreeFormat4',
 
2132
    tree_format='bzrlib.workingtree_4.WorkingTreeFormat4',
3218
2133
    hidden=True,
 
2134
    deprecated=True,
3219
2135
    )
3220
2136
register_metadir(controldir.format_registry, '1.9',
3221
 
    'bzrlib.repofmt.pack_repo.RepositoryFormatKnitPack6',
 
2137
    'bzrlib.repofmt.knitpack_repo.RepositoryFormatKnitPack6',
3222
2138
    help='A repository format using B+tree indexes. These indexes '
3223
2139
         'are smaller in size, have smarter caching and provide faster '
3224
2140
         'performance for most operations.',
3225
2141
    branch_format='bzrlib.branch.BzrBranchFormat7',
3226
 
    tree_format='bzrlib.workingtree.WorkingTreeFormat4',
 
2142
    tree_format='bzrlib.workingtree_4.WorkingTreeFormat4',
3227
2143
    hidden=True,
 
2144
    deprecated=True,
3228
2145
    )
3229
2146
register_metadir(controldir.format_registry, '1.9-rich-root',
3230
 
    'bzrlib.repofmt.pack_repo.RepositoryFormatKnitPack6RichRoot',
 
2147
    'bzrlib.repofmt.knitpack_repo.RepositoryFormatKnitPack6RichRoot',
3231
2148
    help='A variant of 1.9 that supports rich-root data '
3232
2149
         '(needed for bzr-svn and bzr-git).',
3233
2150
    branch_format='bzrlib.branch.BzrBranchFormat7',
3234
 
    tree_format='bzrlib.workingtree.WorkingTreeFormat4',
 
2151
    tree_format='bzrlib.workingtree_4.WorkingTreeFormat4',
3235
2152
    hidden=True,
 
2153
    deprecated=True,
3236
2154
    )
3237
2155
register_metadir(controldir.format_registry, '1.14',
3238
 
    'bzrlib.repofmt.pack_repo.RepositoryFormatKnitPack6',
 
2156
    'bzrlib.repofmt.knitpack_repo.RepositoryFormatKnitPack6',
3239
2157
    help='A working-tree format that supports content filtering.',
3240
2158
    branch_format='bzrlib.branch.BzrBranchFormat7',
3241
 
    tree_format='bzrlib.workingtree.WorkingTreeFormat5',
 
2159
    tree_format='bzrlib.workingtree_4.WorkingTreeFormat5',
 
2160
    hidden=True,
 
2161
    deprecated=True,
3242
2162
    )
3243
2163
register_metadir(controldir.format_registry, '1.14-rich-root',
3244
 
    'bzrlib.repofmt.pack_repo.RepositoryFormatKnitPack6RichRoot',
 
2164
    'bzrlib.repofmt.knitpack_repo.RepositoryFormatKnitPack6RichRoot',
3245
2165
    help='A variant of 1.14 that supports rich-root data '
3246
2166
         '(needed for bzr-svn and bzr-git).',
3247
2167
    branch_format='bzrlib.branch.BzrBranchFormat7',
3248
 
    tree_format='bzrlib.workingtree.WorkingTreeFormat5',
 
2168
    tree_format='bzrlib.workingtree_4.WorkingTreeFormat5',
 
2169
    hidden=True,
 
2170
    deprecated=True,
3249
2171
    )
3250
2172
# The following un-numbered 'development' formats should always just be aliases.
3251
 
register_metadir(controldir.format_registry, 'development-rich-root',
3252
 
    'bzrlib.repofmt.groupcompress_repo.RepositoryFormatCHK1',
3253
 
    help='Current development format. Supports rich roots. Can convert data '
3254
 
        'to and from rich-root-pack (and anything compatible with '
3255
 
        'rich-root-pack) format repositories. Repositories and branches in '
3256
 
        'this format can only be read by bzr.dev. Please read '
3257
 
        'http://doc.bazaar.canonical.com/latest/developers/development-repo.html '
3258
 
        'before use.',
3259
 
    branch_format='bzrlib.branch.BzrBranchFormat7',
3260
 
    tree_format='bzrlib.workingtree.WorkingTreeFormat6',
3261
 
    experimental=True,
3262
 
    alias=True,
3263
 
    hidden=True,
3264
 
    )
3265
 
register_metadir(controldir.format_registry, 'development5-subtree',
3266
 
    'bzrlib.repofmt.pack_repo.RepositoryFormatPackDevelopment2Subtree',
3267
 
    help='Development format, subtree variant. Can convert data to and '
3268
 
        'from pack-0.92-subtree (and anything compatible with '
3269
 
        'pack-0.92-subtree) format repositories. Repositories and branches in '
3270
 
        'this format can only be read by bzr.dev. Please read '
3271
 
        'http://doc.bazaar.canonical.com/latest/developers/development-repo.html '
3272
 
        'before use.',
3273
 
    branch_format='bzrlib.branch.BzrBranchFormat7',
3274
 
    tree_format='bzrlib.workingtree.WorkingTreeFormat6',
3275
 
    experimental=True,
3276
 
    hidden=True,
3277
 
    alias=False,
3278
 
    )
3279
 
 
3280
 
 
3281
2173
register_metadir(controldir.format_registry, 'development-subtree',
3282
2174
    'bzrlib.repofmt.groupcompress_repo.RepositoryFormat2aSubtree',
3283
2175
    help='Current development format, subtree variant. Can convert data to and '
3287
2179
        'http://doc.bazaar.canonical.com/latest/developers/development-repo.html '
3288
2180
        'before use.',
3289
2181
    branch_format='bzrlib.branch.BzrBranchFormat7',
3290
 
    tree_format='bzrlib.workingtree.WorkingTreeFormat6',
 
2182
    tree_format='bzrlib.workingtree_4.WorkingTreeFormat6',
3291
2183
    experimental=True,
3292
2184
    hidden=True,
3293
2185
    alias=False, # Restore to being an alias when an actual development subtree format is added
3294
2186
                 # This current non-alias status is simply because we did not introduce a
3295
2187
                 # chk based subtree format.
3296
2188
    )
 
2189
register_metadir(controldir.format_registry, 'development5-subtree',
 
2190
    'bzrlib.repofmt.knitpack_repo.RepositoryFormatPackDevelopment2Subtree',
 
2191
    help='Development format, subtree variant. Can convert data to and '
 
2192
        'from pack-0.92-subtree (and anything compatible with '
 
2193
        'pack-0.92-subtree) format repositories. Repositories and branches in '
 
2194
        'this format can only be read by bzr.dev. Please read '
 
2195
        'http://doc.bazaar.canonical.com/latest/developers/development-repo.html '
 
2196
        'before use.',
 
2197
    branch_format='bzrlib.branch.BzrBranchFormat7',
 
2198
    tree_format='bzrlib.workingtree_4.WorkingTreeFormat6',
 
2199
    experimental=True,
 
2200
    hidden=True,
 
2201
    alias=False,
 
2202
    )
 
2203
 
 
2204
register_metadir(controldir.format_registry, 'development-colo',
 
2205
    'bzrlib.repofmt.groupcompress_repo.RepositoryFormat2a',
 
2206
    help='The 2a format with experimental support for colocated branches.\n',
 
2207
    branch_format='bzrlib.branch.BzrBranchFormat7',
 
2208
    tree_format='bzrlib.workingtree_4.WorkingTreeFormat6',
 
2209
    experimental=True,
 
2210
    bzrdir_format=BzrDirMetaFormat1Colo,
 
2211
    )
 
2212
 
3297
2213
 
3298
2214
# And the development formats above will have aliased one of the following:
3299
 
register_metadir(controldir.format_registry, 'development6-rich-root',
3300
 
    'bzrlib.repofmt.groupcompress_repo.RepositoryFormatCHK1',
3301
 
    help='pack-1.9 with 255-way hashed CHK inv, group compress, rich roots '
3302
 
        'Please read '
3303
 
        'http://doc.bazaar.canonical.com/latest/developers/development-repo.html '
3304
 
        'before use.',
3305
 
    branch_format='bzrlib.branch.BzrBranchFormat7',
3306
 
    tree_format='bzrlib.workingtree.WorkingTreeFormat6',
3307
 
    hidden=True,
3308
 
    experimental=True,
3309
 
    )
3310
 
 
3311
 
register_metadir(controldir.format_registry, 'development7-rich-root',
3312
 
    'bzrlib.repofmt.groupcompress_repo.RepositoryFormatCHK2',
3313
 
    help='pack-1.9 with 255-way hashed CHK inv, bencode revision, group compress, '
3314
 
        'rich roots. Please read '
3315
 
        'http://doc.bazaar.canonical.com/latest/developers/development-repo.html '
3316
 
        'before use.',
3317
 
    branch_format='bzrlib.branch.BzrBranchFormat7',
3318
 
    tree_format='bzrlib.workingtree.WorkingTreeFormat6',
3319
 
    hidden=True,
3320
 
    experimental=True,
3321
 
    )
3322
 
 
 
2215
 
 
2216
# Finally, the current format.
3323
2217
register_metadir(controldir.format_registry, '2a',
3324
2218
    'bzrlib.repofmt.groupcompress_repo.RepositoryFormat2a',
3325
 
    help='First format for bzr 2.0 series.\n'
 
2219
    help='Format for the bzr 2.0 series.\n'
3326
2220
        'Uses group-compress storage.\n'
3327
2221
        'Provides rich roots which are a one-way transition.\n',
3328
2222
        # 'storage in packs, 255-way hashed CHK inventory, bencode revision, group compress, '
3329
2223
        # 'rich roots. Supported by bzr 1.16 and later.',
3330
2224
    branch_format='bzrlib.branch.BzrBranchFormat7',
3331
 
    tree_format='bzrlib.workingtree.WorkingTreeFormat6',
 
2225
    tree_format='bzrlib.workingtree_4.WorkingTreeFormat6',
3332
2226
    experimental=False,
3333
2227
    )
3334
2228
 
3337
2231
register_metadir(controldir.format_registry, 'default-rich-root',
3338
2232
    'bzrlib.repofmt.groupcompress_repo.RepositoryFormat2a',
3339
2233
    branch_format='bzrlib.branch.BzrBranchFormat7',
3340
 
    tree_format='bzrlib.workingtree.WorkingTreeFormat6',
 
2234
    tree_format='bzrlib.workingtree_4.WorkingTreeFormat6',
3341
2235
    alias=True,
3342
2236
    hidden=True,
3343
2237
    help='Same as 2a.')
3344
2238
 
3345
2239
# The current format that is made on 'bzr init'.
3346
 
controldir.format_registry.set_default('2a')
 
2240
format_name = config.GlobalStack().get('default_format')
 
2241
controldir.format_registry.set_default(format_name)
3347
2242
 
3348
2243
# XXX 2010-08-20 JRV: There is still a lot of code relying on
3349
2244
# bzrlib.bzrdir.format_registry existing. When BzrDir.create/BzrDir.open/etc