~bzr-pqm/bzr/bzr.dev

« back to all changes in this revision

Viewing changes to bzrlib/bzrdir.py

  • Committer: Canonical.com Patch Queue Manager
  • Date: 2010-09-01 08:02:42 UTC
  • mfrom: (5390.3.3 faster-revert-593560)
  • Revision ID: pqm@pqm.ubuntu.com-20100901080242-esg62ody4frwmy66
(spiv) Avoid repeatedly calling self.target.all_file_ids() in
 InterTree.iter_changes. (Andrew Bennetts)

Show diffs side-by-side

added added

removed removed

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