~bzr-pqm/bzr/bzr.dev

« back to all changes in this revision

Viewing changes to bzrlib/bzrdir.py

MergeĀ lp:~gz/bzr/path_from_environ_832028

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