~bzr-pqm/bzr/bzr.dev

« back to all changes in this revision

Viewing changes to bzrlib/bzrdir.py

  • Committer: Martin Pool
  • Date: 2010-02-25 06:17:27 UTC
  • mfrom: (5055 +trunk)
  • mto: This revision was merged to the branch mainline in revision 5057.
  • Revision ID: mbp@sourcefrog.net-20100225061727-4sd9lt0qmdc6087t
merge news

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
# TODO: Move old formats into a plugin to make this file smaller.
 
29
 
 
30
import os
28
31
import sys
 
32
import warnings
29
33
 
30
34
from bzrlib.lazy_import import lazy_import
31
35
lazy_import(globals(), """
 
36
from stat import S_ISDIR
 
37
import textwrap
 
38
 
32
39
import bzrlib
33
40
from bzrlib import (
34
 
    branch as _mod_branch,
35
 
    cleanup,
 
41
    branch,
 
42
    config,
36
43
    errors,
37
 
    fetch,
38
44
    graph,
39
45
    lockable_files,
40
46
    lockdir,
41
47
    osutils,
42
 
    pyutils,
43
48
    remote,
44
49
    repository,
45
50
    revision as _mod_revision,
46
 
    transport as _mod_transport,
47
51
    ui,
48
52
    urlutils,
 
53
    versionedfile,
49
54
    win32utils,
50
 
    workingtree_3,
 
55
    workingtree,
51
56
    workingtree_4,
52
 
    )
53
 
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
54
70
from bzrlib.transport import (
55
71
    do_catching_redirections,
 
72
    get_transport,
56
73
    local,
57
74
    )
58
 
from bzrlib.i18n import gettext
 
75
from bzrlib.weave import Weave
59
76
""")
60
77
 
61
78
from bzrlib.trace import (
62
79
    mutter,
63
80
    note,
 
81
    warning,
64
82
    )
65
83
 
66
84
from bzrlib import (
67
 
    config,
68
 
    controldir,
69
85
    hooks,
70
86
    registry,
71
 
    )
72
 
from bzrlib.symbol_versioning import (
73
 
    deprecated_in,
74
 
    deprecated_method,
75
 
    )
76
 
 
77
 
 
78
 
class BzrDir(controldir.ControlDir):
 
87
    symbol_versioning,
 
88
    )
 
89
 
 
90
 
 
91
class BzrDir(object):
79
92
    """A .bzr control diretory.
80
93
 
81
94
    BzrDir instances let you create or open any of the things that can be
112
125
                    return
113
126
        thing_to_unlock.break_lock()
114
127
 
 
128
    def can_convert_format(self):
 
129
        """Return true if this bzrdir is one whose format we can convert from."""
 
130
        return True
 
131
 
115
132
    def check_conversion_target(self, target_format):
116
133
        """Check that a bzrdir as a whole can be converted to a new format."""
117
134
        # The only current restriction is that the repository content can be 
124
141
            # No repo, no problem.
125
142
            pass
126
143
 
 
144
    @staticmethod
 
145
    def _check_supported(format, allow_unsupported,
 
146
        recommend_upgrade=True,
 
147
        basedir=None):
 
148
        """Give an error or warning on old formats.
 
149
 
 
150
        :param format: may be any kind of format - workingtree, branch,
 
151
        or repository.
 
152
 
 
153
        :param allow_unsupported: If true, allow opening
 
154
        formats that are strongly deprecated, and which may
 
155
        have limited functionality.
 
156
 
 
157
        :param recommend_upgrade: If true (default), warn
 
158
        the user through the ui object that they may wish
 
159
        to upgrade the object.
 
160
        """
 
161
        # TODO: perhaps move this into a base Format class; it's not BzrDir
 
162
        # specific. mbp 20070323
 
163
        if not allow_unsupported and not format.is_supported():
 
164
            # see open_downlevel to open legacy branches.
 
165
            raise errors.UnsupportedFormatError(format=format)
 
166
        if recommend_upgrade \
 
167
            and getattr(format, 'upgrade_recommended', False):
 
168
            ui.ui_factory.recommend_upgrade(
 
169
                format.get_format_description(),
 
170
                basedir)
 
171
 
 
172
    def clone(self, url, revision_id=None, force_new_repo=False,
 
173
              preserve_stacking=False):
 
174
        """Clone this bzrdir and its contents to url verbatim.
 
175
 
 
176
        :param url: The url create the clone at.  If url's last component does
 
177
            not exist, it will be created.
 
178
        :param revision_id: The tip revision-id to use for any branch or
 
179
            working tree.  If not None, then the clone operation may tune
 
180
            itself to download less data.
 
181
        :param force_new_repo: Do not use a shared repository for the target
 
182
                               even if one is available.
 
183
        :param preserve_stacking: When cloning a stacked branch, stack the
 
184
            new branch on top of the other branch's stacked-on branch.
 
185
        """
 
186
        return self.clone_on_transport(get_transport(url),
 
187
                                       revision_id=revision_id,
 
188
                                       force_new_repo=force_new_repo,
 
189
                                       preserve_stacking=preserve_stacking)
 
190
 
127
191
    def clone_on_transport(self, transport, revision_id=None,
128
192
        force_new_repo=False, preserve_stacking=False, stacked_on=None,
129
 
        create_prefix=False, use_existing_dir=True, no_tree=False):
 
193
        create_prefix=False, use_existing_dir=True):
130
194
        """Clone this bzrdir and its contents to transport verbatim.
131
195
 
132
196
        :param transport: The transport for the location to produce the clone
141
205
        :param create_prefix: Create any missing directories leading up to
142
206
            to_transport.
143
207
        :param use_existing_dir: Use an existing directory if one exists.
144
 
        :param no_tree: If set to true prevents creation of a working tree.
145
208
        """
146
209
        # Overview: put together a broad description of what we want to end up
147
210
        # with; then make as few api calls as possible to do it.
148
 
 
 
211
        
149
212
        # We may want to create a repo/branch/tree, if we do so what format
150
213
        # would we want for each:
151
214
        require_stacking = (stacked_on is not None)
152
215
        format = self.cloning_metadir(require_stacking)
153
 
 
 
216
        
154
217
        # Figure out what objects we want:
155
218
        try:
156
219
            local_repo = self.find_repository()
175
238
        # we should look up the policy needs first, or just use it as a hint,
176
239
        # or something.
177
240
        if local_repo:
178
 
            make_working_trees = local_repo.make_working_trees() and not no_tree
 
241
            make_working_trees = local_repo.make_working_trees()
179
242
            want_shared = local_repo.is_shared()
180
243
            repo_format_name = format.repository_format.network_name()
181
244
        else:
198
261
                # copied, and finally if we are copying up to a specific
199
262
                # revision_id then we can use the pending-ancestry-result which
200
263
                # does not require traversing all of history to describe it.
201
 
                if (result_repo.user_url == result.user_url
202
 
                    and not require_stacking and
 
264
                if (result_repo.bzrdir.root_transport.base ==
 
265
                    result.root_transport.base and not require_stacking and
203
266
                    revision_id is not None):
204
267
                    fetch_spec = graph.PendingAncestryResult(
205
268
                        [revision_id], local_repo)
230
293
    # TODO: This should be given a Transport, and should chdir up; otherwise
231
294
    # this will open a new connection.
232
295
    def _make_tail(self, url):
233
 
        t = _mod_transport.get_transport(url)
234
 
        t.ensure_base()
 
296
        t = get_transport(url)
 
297
        t.ensure_base()
 
298
 
 
299
    @classmethod
 
300
    def create(cls, base, format=None, possible_transports=None):
 
301
        """Create a new BzrDir at the url 'base'.
 
302
 
 
303
        :param format: If supplied, the format of branch to create.  If not
 
304
            supplied, the default is used.
 
305
        :param possible_transports: If supplied, a list of transports that
 
306
            can be reused to share a remote connection.
 
307
        """
 
308
        if cls is not BzrDir:
 
309
            raise AssertionError("BzrDir.create always creates the default"
 
310
                " format, not one of %r" % cls)
 
311
        t = get_transport(base, possible_transports)
 
312
        t.ensure_base()
 
313
        if format is None:
 
314
            format = BzrDirFormat.get_default_format()
 
315
        return format.initialize_on_transport(t)
235
316
 
236
317
    @staticmethod
237
318
    def find_bzrdirs(transport, evaluate=None, list_current=None):
240
321
        This is intended primarily as a building block for more sophisticated
241
322
        functionality, like finding trees under a directory, or finding
242
323
        branches that use a given repository.
243
 
 
244
324
        :param evaluate: An optional callable that yields recurse, value,
245
325
            where recurse controls whether this bzrdir is recursed into
246
326
            and value is the value to yield.  By default, all bzrdirs
262
342
            recurse = True
263
343
            try:
264
344
                bzrdir = BzrDir.open_from_transport(current_transport)
265
 
            except (errors.NotBranchError, errors.PermissionDenied):
 
345
            except errors.NotBranchError:
266
346
                pass
267
347
            else:
268
348
                recurse, value = evaluate(bzrdir)
269
349
                yield value
270
350
            try:
271
351
                subdirs = list_current(current_transport)
272
 
            except (errors.NoSuchFile, errors.PermissionDenied):
 
352
            except errors.NoSuchFile:
273
353
                continue
274
354
            if recurse:
275
355
                for subdir in sorted(subdirs, reverse=True):
276
356
                    pending.append(current_transport.clone(subdir))
277
357
 
 
358
    def list_branches(self):
 
359
        """Return a sequence of all branches local to this control directory.
 
360
 
 
361
        """
 
362
        try:
 
363
            return [self.open_branch()]
 
364
        except errors.NotBranchError:
 
365
            return []
 
366
 
278
367
    @staticmethod
279
368
    def find_branches(transport):
280
369
        """Find all branches under a transport.
303
392
                ret.extend(branches)
304
393
        return ret
305
394
 
 
395
    def destroy_repository(self):
 
396
        """Destroy the repository in this BzrDir"""
 
397
        raise NotImplementedError(self.destroy_repository)
 
398
 
 
399
    def create_branch(self):
 
400
        """Create a branch in this BzrDir.
 
401
 
 
402
        The bzrdir's format will control what branch format is created.
 
403
        For more control see BranchFormatXX.create(a_bzrdir).
 
404
        """
 
405
        raise NotImplementedError(self.create_branch)
 
406
 
 
407
    def destroy_branch(self):
 
408
        """Destroy the branch in this BzrDir"""
 
409
        raise NotImplementedError(self.destroy_branch)
 
410
 
306
411
    @staticmethod
307
412
    def create_branch_and_repo(base, force_new_repo=False, format=None):
308
413
        """Create a new BzrDir, Branch and Repository at the url 'base'.
346
451
            stop = False
347
452
            stack_on = config.get_default_stack_on()
348
453
            if stack_on is not None:
349
 
                stack_on_pwd = found_bzrdir.user_url
 
454
                stack_on_pwd = found_bzrdir.root_transport.base
350
455
                stop = True
351
456
            # does it have a repository ?
352
457
            try:
354
459
            except errors.NoRepositoryPresent:
355
460
                repository = None
356
461
            else:
357
 
                if (found_bzrdir.user_url != self.user_url 
358
 
                    and not repository.is_shared()):
 
462
                if ((found_bzrdir.root_transport.base !=
 
463
                     self.root_transport.base) and not repository.is_shared()):
359
464
                    # Don't look higher, can't use a higher shared repo.
360
465
                    repository = None
361
466
                    stop = True
390
495
        policy = self.determine_repository_policy(force_new_repo)
391
496
        return policy.acquire_repository()[0]
392
497
 
393
 
    def _find_source_repo(self, add_cleanup, source_branch):
394
 
        """Find the source branch and repo for a sprout operation.
395
 
        
396
 
        This is helper intended for use by _sprout.
397
 
 
398
 
        :returns: (source_branch, source_repository).  Either or both may be
399
 
            None.  If not None, they will be read-locked (and their unlock(s)
400
 
            scheduled via the add_cleanup param).
401
 
        """
402
 
        if source_branch is not None:
403
 
            add_cleanup(source_branch.lock_read().unlock)
404
 
            return source_branch, source_branch.repository
405
 
        try:
406
 
            source_branch = self.open_branch()
407
 
            source_repository = source_branch.repository
408
 
        except errors.NotBranchError:
409
 
            source_branch = None
410
 
            try:
411
 
                source_repository = self.open_repository()
412
 
            except errors.NoRepositoryPresent:
413
 
                source_repository = None
414
 
            else:
415
 
                add_cleanup(source_repository.lock_read().unlock)
416
 
        else:
417
 
            add_cleanup(source_branch.lock_read().unlock)
418
 
        return source_branch, source_repository
419
 
 
420
 
    def sprout(self, url, revision_id=None, force_new_repo=False,
421
 
               recurse='down', possible_transports=None,
422
 
               accelerator_tree=None, hardlink=False, stacked=False,
423
 
               source_branch=None, create_tree_if_local=True):
424
 
        """Create a copy of this controldir prepared for use as a new line of
425
 
        development.
426
 
 
427
 
        If url's last component does not exist, it will be created.
428
 
 
429
 
        Attributes related to the identity of the source branch like
430
 
        branch nickname will be cleaned, a working tree is created
431
 
        whether one existed before or not; and a local branch is always
432
 
        created.
433
 
 
434
 
        if revision_id is not None, then the clone operation may tune
435
 
            itself to download less data.
436
 
 
437
 
        :param accelerator_tree: A tree which can be used for retrieving file
438
 
            contents more quickly than the revision tree, i.e. a workingtree.
439
 
            The revision tree will be used for cases where accelerator_tree's
440
 
            content is different.
441
 
        :param hardlink: If true, hard-link files from accelerator_tree,
442
 
            where possible.
443
 
        :param stacked: If true, create a stacked branch referring to the
444
 
            location of this control directory.
445
 
        :param create_tree_if_local: If true, a working-tree will be created
446
 
            when working locally.
447
 
        """
448
 
        operation = cleanup.OperationWithCleanups(self._sprout)
449
 
        return operation.run(url, revision_id=revision_id,
450
 
            force_new_repo=force_new_repo, recurse=recurse,
451
 
            possible_transports=possible_transports,
452
 
            accelerator_tree=accelerator_tree, hardlink=hardlink,
453
 
            stacked=stacked, source_branch=source_branch,
454
 
            create_tree_if_local=create_tree_if_local)
455
 
 
456
 
    def _sprout(self, op, url, revision_id=None, force_new_repo=False,
457
 
               recurse='down', possible_transports=None,
458
 
               accelerator_tree=None, hardlink=False, stacked=False,
459
 
               source_branch=None, create_tree_if_local=True):
460
 
        add_cleanup = op.add_cleanup
461
 
        fetch_spec_factory = fetch.FetchSpecFactory()
462
 
        if revision_id is not None:
463
 
            fetch_spec_factory.add_revision_ids([revision_id])
464
 
            fetch_spec_factory.source_branch_stop_revision_id = revision_id
465
 
        target_transport = _mod_transport.get_transport(url,
466
 
            possible_transports)
467
 
        target_transport.ensure_base()
468
 
        cloning_format = self.cloning_metadir(stacked)
469
 
        # Create/update the result branch
470
 
        result = cloning_format.initialize_on_transport(target_transport)
471
 
        source_branch, source_repository = self._find_source_repo(
472
 
            add_cleanup, source_branch)
473
 
        fetch_spec_factory.source_branch = source_branch
474
 
        # if a stacked branch wasn't requested, we don't create one
475
 
        # even if the origin was stacked
476
 
        if stacked and source_branch is not None:
477
 
            stacked_branch_url = self.root_transport.base
478
 
        else:
479
 
            stacked_branch_url = None
480
 
        repository_policy = result.determine_repository_policy(
481
 
            force_new_repo, stacked_branch_url, require_stacking=stacked)
482
 
        result_repo, is_new_repo = repository_policy.acquire_repository()
483
 
        add_cleanup(result_repo.lock_write().unlock)
484
 
        fetch_spec_factory.source_repo = source_repository
485
 
        fetch_spec_factory.target_repo = result_repo
486
 
        if stacked or (len(result_repo._fallback_repositories) != 0):
487
 
            target_repo_kind = fetch.TargetRepoKinds.STACKED
488
 
        elif is_new_repo:
489
 
            target_repo_kind = fetch.TargetRepoKinds.EMPTY
490
 
        else:
491
 
            target_repo_kind = fetch.TargetRepoKinds.PREEXISTING
492
 
        fetch_spec_factory.target_repo_kind = target_repo_kind
493
 
        if source_repository is not None:
494
 
            fetch_spec = fetch_spec_factory.make_fetch_spec()
495
 
            result_repo.fetch(source_repository, fetch_spec=fetch_spec)
496
 
 
497
 
        if source_branch is None:
498
 
            # this is for sprouting a controldir without a branch; is that
499
 
            # actually useful?
500
 
            # Not especially, but it's part of the contract.
501
 
            result_branch = result.create_branch()
502
 
        else:
503
 
            result_branch = source_branch.sprout(result,
504
 
                revision_id=revision_id, repository_policy=repository_policy,
505
 
                repository=result_repo)
506
 
        mutter("created new branch %r" % (result_branch,))
507
 
 
508
 
        # Create/update the result working tree
509
 
        if (create_tree_if_local and
510
 
            isinstance(target_transport, local.LocalTransport) and
511
 
            (result_repo is None or result_repo.make_working_trees())):
512
 
            wt = result.create_workingtree(accelerator_tree=accelerator_tree,
513
 
                hardlink=hardlink, from_branch=result_branch)
514
 
            wt.lock_write()
515
 
            try:
516
 
                if wt.path2id('') is None:
517
 
                    try:
518
 
                        wt.set_root_id(self.open_workingtree.get_root_id())
519
 
                    except errors.NoWorkingTree:
520
 
                        pass
521
 
            finally:
522
 
                wt.unlock()
523
 
        else:
524
 
            wt = None
525
 
        if recurse == 'down':
526
 
            basis = None
527
 
            if wt is not None:
528
 
                basis = wt.basis_tree()
529
 
            elif result_branch is not None:
530
 
                basis = result_branch.basis_tree()
531
 
            elif source_branch is not None:
532
 
                basis = source_branch.basis_tree()
533
 
            if basis is not None:
534
 
                add_cleanup(basis.lock_read().unlock)
535
 
                subtrees = basis.iter_references()
536
 
            else:
537
 
                subtrees = []
538
 
            for path, file_id in subtrees:
539
 
                target = urlutils.join(url, urlutils.escape(path))
540
 
                sublocation = source_branch.reference_parent(file_id, path)
541
 
                sublocation.bzrdir.sprout(target,
542
 
                    basis.get_reference_revision(file_id, path),
543
 
                    force_new_repo=force_new_repo, recurse=recurse,
544
 
                    stacked=stacked)
545
 
        return result
546
 
 
547
498
    @staticmethod
548
499
    def create_branch_convenience(base, force_new_repo=False,
549
500
                                  force_new_tree=None, format=None,
575
526
        """
576
527
        if force_new_tree:
577
528
            # check for non local urls
578
 
            t = _mod_transport.get_transport(base, possible_transports)
 
529
            t = get_transport(base, possible_transports)
579
530
            if not isinstance(t, local.LocalTransport):
580
531
                raise errors.NotLocalUrl(base)
581
532
        bzrdir = BzrDir.create(base, format, possible_transports)
603
554
        :param format: Override for the bzrdir format to create.
604
555
        :return: The WorkingTree object.
605
556
        """
606
 
        t = _mod_transport.get_transport(base)
 
557
        t = get_transport(base)
607
558
        if not isinstance(t, local.LocalTransport):
608
559
            raise errors.NotLocalUrl(base)
609
560
        bzrdir = BzrDir.create_branch_and_repo(base,
611
562
                                               format=format).bzrdir
612
563
        return bzrdir.create_workingtree()
613
564
 
614
 
    @deprecated_method(deprecated_in((2, 3, 0)))
615
 
    def generate_backup_name(self, base):
616
 
        return self._available_backup_name(base)
617
 
 
618
 
    def _available_backup_name(self, base):
619
 
        """Find a non-existing backup file name based on base.
620
 
 
621
 
        See bzrlib.osutils.available_backup_name about race conditions.
 
565
    def create_workingtree(self, revision_id=None, from_branch=None,
 
566
        accelerator_tree=None, hardlink=False):
 
567
        """Create a working tree at this BzrDir.
 
568
 
 
569
        :param revision_id: create it as of this revision id.
 
570
        :param from_branch: override bzrdir branch (for lightweight checkouts)
 
571
        :param accelerator_tree: A tree which can be used for retrieving file
 
572
            contents more quickly than the revision tree, i.e. a workingtree.
 
573
            The revision tree will be used for cases where accelerator_tree's
 
574
            content is different.
622
575
        """
623
 
        return osutils.available_backup_name(base, self.root_transport.has)
 
576
        raise NotImplementedError(self.create_workingtree)
624
577
 
625
578
    def backup_bzrdir(self):
626
579
        """Backup this bzr control directory.
627
580
 
628
581
        :return: Tuple with old path name and new path name
629
582
        """
 
583
        def name_gen(base='backup.bzr'):
 
584
            counter = 1
 
585
            name = "%s.~%d~" % (base, counter)
 
586
            while self.root_transport.has(name):
 
587
                counter += 1
 
588
                name = "%s.~%d~" % (base, counter)
 
589
            return name
630
590
 
 
591
        backup_dir=name_gen()
631
592
        pb = ui.ui_factory.nested_progress_bar()
632
593
        try:
 
594
            # FIXME: bug 300001 -- the backup fails if the backup directory
 
595
            # already exists, but it should instead either remove it or make
 
596
            # a new backup directory.
 
597
            #
 
598
            # FIXME: bug 262450 -- the backup directory should have the same
 
599
            # permissions as the .bzr directory (probably a bug in copy_tree)
633
600
            old_path = self.root_transport.abspath('.bzr')
634
 
            backup_dir = self._available_backup_name('backup.bzr')
635
601
            new_path = self.root_transport.abspath(backup_dir)
636
 
            ui.ui_factory.note(gettext('making backup of {0}\n  to {1}').format(
637
 
                urlutils.unescape_for_display(old_path, 'utf-8'),
638
 
                urlutils.unescape_for_display(new_path, 'utf-8')))
 
602
            ui.ui_factory.note('making backup of %s\n  to %s' % (old_path, new_path,))
639
603
            self.root_transport.copy_tree('.bzr', backup_dir)
640
604
            return (old_path, new_path)
641
605
        finally:
656
620
            try:
657
621
                to_path = '.bzr.retired.%d' % i
658
622
                self.root_transport.rename('.bzr', to_path)
659
 
                note(gettext("renamed {0} to {1}").format(
660
 
                    self.root_transport.abspath('.bzr'), to_path))
 
623
                note("renamed %s to %s"
 
624
                    % (self.root_transport.abspath('.bzr'), to_path))
661
625
                return
662
626
            except (errors.TransportError, IOError, errors.PathError):
663
627
                i += 1
666
630
                else:
667
631
                    pass
668
632
 
 
633
    def destroy_workingtree(self):
 
634
        """Destroy the working tree at this BzrDir.
 
635
 
 
636
        Formats that do not support this may raise UnsupportedOperation.
 
637
        """
 
638
        raise NotImplementedError(self.destroy_workingtree)
 
639
 
 
640
    def destroy_workingtree_metadata(self):
 
641
        """Destroy the control files for the working tree at this BzrDir.
 
642
 
 
643
        The contents of working tree files are not affected.
 
644
        Formats that do not support this may raise UnsupportedOperation.
 
645
        """
 
646
        raise NotImplementedError(self.destroy_workingtree_metadata)
 
647
 
669
648
    def _find_containing(self, evaluate):
670
649
        """Find something in a containing control directory.
671
650
 
685
664
            if stop:
686
665
                return result
687
666
            next_transport = found_bzrdir.root_transport.clone('..')
688
 
            if (found_bzrdir.user_url == next_transport.base):
 
667
            if (found_bzrdir.root_transport.base == next_transport.base):
689
668
                # top of the file system
690
669
                return None
691
670
            # find the next containing bzrdir
708
687
                repository = found_bzrdir.open_repository()
709
688
            except errors.NoRepositoryPresent:
710
689
                return None, False
711
 
            if found_bzrdir.user_url == self.user_url:
 
690
            if found_bzrdir.root_transport.base == self.root_transport.base:
712
691
                return repository, True
713
692
            elif repository.is_shared():
714
693
                return repository, True
720
699
            raise errors.NoRepositoryPresent(self)
721
700
        return found_repo
722
701
 
 
702
    def get_branch_reference(self):
 
703
        """Return the referenced URL for the branch in this bzrdir.
 
704
 
 
705
        :raises NotBranchError: If there is no Branch.
 
706
        :return: The URL the branch in this bzrdir references if it is a
 
707
            reference branch, or None for regular branches.
 
708
        """
 
709
        return None
 
710
 
 
711
    def get_branch_transport(self, branch_format):
 
712
        """Get the transport for use by branch format in this BzrDir.
 
713
 
 
714
        Note that bzr dirs that do not support format strings will raise
 
715
        IncompatibleFormat if the branch format they are given has
 
716
        a format string, and vice versa.
 
717
 
 
718
        If branch_format is None, the transport is returned with no
 
719
        checking. If it is not None, then the returned transport is
 
720
        guaranteed to point to an existing directory ready for use.
 
721
        """
 
722
        raise NotImplementedError(self.get_branch_transport)
 
723
 
723
724
    def _find_creation_modes(self):
724
725
        """Determine the appropriate modes for files and directories.
725
726
 
764
765
            self._find_creation_modes()
765
766
        return self._dir_mode
766
767
 
 
768
    def get_repository_transport(self, repository_format):
 
769
        """Get the transport for use by repository format in this BzrDir.
 
770
 
 
771
        Note that bzr dirs that do not support format strings will raise
 
772
        IncompatibleFormat if the repository format they are given has
 
773
        a format string, and vice versa.
 
774
 
 
775
        If repository_format is None, the transport is returned with no
 
776
        checking. If it is not None, then the returned transport is
 
777
        guaranteed to point to an existing directory ready for use.
 
778
        """
 
779
        raise NotImplementedError(self.get_repository_transport)
 
780
 
 
781
    def get_workingtree_transport(self, tree_format):
 
782
        """Get the transport for use by workingtree format in this BzrDir.
 
783
 
 
784
        Note that bzr dirs that do not support format strings will raise
 
785
        IncompatibleFormat if the workingtree format they are given has a
 
786
        format string, and vice versa.
 
787
 
 
788
        If workingtree_format is None, the transport is returned with no
 
789
        checking. If it is not None, then the returned transport is
 
790
        guaranteed to point to an existing directory ready for use.
 
791
        """
 
792
        raise NotImplementedError(self.get_workingtree_transport)
 
793
 
767
794
    def get_config(self):
768
795
        """Get configuration for this BzrDir."""
769
796
        return config.BzrDirConfig(self)
782
809
        :param _transport: the transport this dir is based at.
783
810
        """
784
811
        self._format = _format
785
 
        # these are also under the more standard names of 
786
 
        # control_transport and user_transport
787
812
        self.transport = _transport.clone('.bzr')
788
813
        self.root_transport = _transport
789
814
        self._mode_check_done = False
790
815
 
791
 
    @property 
792
 
    def user_transport(self):
793
 
        return self.root_transport
794
 
 
795
 
    @property
796
 
    def control_transport(self):
797
 
        return self.transport
798
 
 
799
816
    def is_control_filename(self, filename):
800
817
        """True if filename is the name of a path which is reserved for bzrdir's.
801
818
 
803
820
 
804
821
        This is true IF and ONLY IF the filename is part of the namespace reserved
805
822
        for bzr control dirs. Currently this is the '.bzr' directory in the root
806
 
        of the root_transport. 
 
823
        of the root_transport. it is expected that plugins will need to extend
 
824
        this in the future - for instance to make bzr talk with svn working
 
825
        trees.
807
826
        """
808
827
        # this might be better on the BzrDirFormat class because it refers to
809
828
        # all the possible bzrdir disk formats.
813
832
        # add new tests for it to the appropriate place.
814
833
        return filename == '.bzr' or filename.startswith('.bzr/')
815
834
 
 
835
    def needs_format_conversion(self, format=None):
 
836
        """Return true if this bzrdir needs convert_format run on it.
 
837
 
 
838
        For instance, if the repository format is out of date but the
 
839
        branch and working tree are not, this should return True.
 
840
 
 
841
        :param format: Optional parameter indicating a specific desired
 
842
                       format we plan to arrive at.
 
843
        """
 
844
        raise NotImplementedError(self.needs_format_conversion)
 
845
 
816
846
    @staticmethod
817
847
    def open_unsupported(base):
818
848
        """Open a branch which is not supported."""
824
854
 
825
855
        :param _unsupported: a private parameter to the BzrDir class.
826
856
        """
827
 
        t = _mod_transport.get_transport(base, possible_transports)
 
857
        t = get_transport(base, possible_transports=possible_transports)
828
858
        return BzrDir.open_from_transport(t, _unsupported=_unsupported)
829
859
 
830
860
    @staticmethod
841
871
        # the redirections.
842
872
        base = transport.base
843
873
        def find_format(transport):
844
 
            return transport, controldir.ControlDirFormat.find_format(
 
874
            return transport, BzrDirFormat.find_format(
845
875
                transport, _server_formats=_server_formats)
846
876
 
847
877
        def redirected(transport, e, redirection_notice):
848
878
            redirected_transport = transport._redirected_to(e.source, e.target)
849
879
            if redirected_transport is None:
850
880
                raise errors.NotBranchError(base)
851
 
            note(gettext('{0} is{1} redirected to {2}').format(
852
 
                 transport.base, e.permanently, redirected_transport.base))
 
881
            note('%s is%s redirected to %s',
 
882
                 transport.base, e.permanently, redirected_transport.base)
853
883
            return redirected_transport
854
884
 
855
885
        try:
859
889
        except errors.TooManyRedirections:
860
890
            raise errors.NotBranchError(base)
861
891
 
862
 
        format.check_support_status(_unsupported)
 
892
        BzrDir._check_supported(format, _unsupported)
863
893
        return format.open(transport, _found=True)
864
894
 
 
895
    def open_branch(self, unsupported=False, ignore_fallbacks=False):
 
896
        """Open the branch object at this BzrDir if one is present.
 
897
 
 
898
        If unsupported is True, then no longer supported branch formats can
 
899
        still be opened.
 
900
 
 
901
        TODO: static convenience version of this?
 
902
        """
 
903
        raise NotImplementedError(self.open_branch)
 
904
 
865
905
    @staticmethod
866
906
    def open_containing(url, possible_transports=None):
867
907
        """Open an existing branch which contains url.
868
908
 
869
909
        :param url: url to search from.
870
 
 
871
910
        See open_containing_from_transport for more detail.
872
911
        """
873
 
        transport = _mod_transport.get_transport(url, possible_transports)
 
912
        transport = get_transport(url, possible_transports)
874
913
        return BzrDir.open_containing_from_transport(transport)
875
914
 
876
915
    @staticmethod
906
945
                raise errors.NotBranchError(path=url)
907
946
            a_transport = new_t
908
947
 
 
948
    def _get_tree_branch(self):
 
949
        """Return the branch and tree, if any, for this bzrdir.
 
950
 
 
951
        Return None for tree if not present or inaccessible.
 
952
        Raise NotBranchError if no branch is present.
 
953
        :return: (tree, branch)
 
954
        """
 
955
        try:
 
956
            tree = self.open_workingtree()
 
957
        except (errors.NoWorkingTree, errors.NotLocalUrl):
 
958
            tree = None
 
959
            branch = self.open_branch()
 
960
        else:
 
961
            branch = tree.branch
 
962
        return tree, branch
 
963
 
909
964
    @classmethod
910
965
    def open_tree_or_branch(klass, location):
911
966
        """Return the branch and working tree at a location.
957
1012
                raise errors.NotBranchError(location)
958
1013
        return tree, branch, branch.repository, relpath
959
1014
 
 
1015
    def open_repository(self, _unsupported=False):
 
1016
        """Open the repository object at this BzrDir if one is present.
 
1017
 
 
1018
        This will not follow the Branch object pointer - it's strictly a direct
 
1019
        open facility. Most client code should use open_branch().repository to
 
1020
        get at a repository.
 
1021
 
 
1022
        :param _unsupported: a private parameter, not part of the api.
 
1023
        TODO: static convenience version of this?
 
1024
        """
 
1025
        raise NotImplementedError(self.open_repository)
 
1026
 
 
1027
    def open_workingtree(self, _unsupported=False,
 
1028
                         recommend_upgrade=True, from_branch=None):
 
1029
        """Open the workingtree object at this BzrDir if one is present.
 
1030
 
 
1031
        :param recommend_upgrade: Optional keyword parameter, when True (the
 
1032
            default), emit through the ui module a recommendation that the user
 
1033
            upgrade the working tree when the workingtree being opened is old
 
1034
            (but still fully supported).
 
1035
        :param from_branch: override bzrdir branch (for lightweight checkouts)
 
1036
        """
 
1037
        raise NotImplementedError(self.open_workingtree)
 
1038
 
 
1039
    def has_branch(self):
 
1040
        """Tell if this bzrdir contains a branch.
 
1041
 
 
1042
        Note: if you're going to open the branch, you should just go ahead
 
1043
        and try, and not ask permission first.  (This method just opens the
 
1044
        branch and discards it, and that's somewhat expensive.)
 
1045
        """
 
1046
        try:
 
1047
            self.open_branch()
 
1048
            return True
 
1049
        except errors.NotBranchError:
 
1050
            return False
 
1051
 
 
1052
    def has_workingtree(self):
 
1053
        """Tell if this bzrdir contains a working tree.
 
1054
 
 
1055
        This will still raise an exception if the bzrdir has a workingtree that
 
1056
        is remote & inaccessible.
 
1057
 
 
1058
        Note: if you're going to open the working tree, you should just go ahead
 
1059
        and try, and not ask permission first.  (This method just opens the
 
1060
        workingtree and discards it, and that's somewhat expensive.)
 
1061
        """
 
1062
        try:
 
1063
            self.open_workingtree(recommend_upgrade=False)
 
1064
            return True
 
1065
        except errors.NoWorkingTree:
 
1066
            return False
 
1067
 
960
1068
    def _cloning_metadir(self):
961
1069
        """Produce a metadir suitable for cloning with.
962
1070
 
1020
1128
            format.require_stacking()
1021
1129
        return format
1022
1130
 
1023
 
    @classmethod
1024
 
    def create(cls, base, format=None, possible_transports=None):
1025
 
        """Create a new BzrDir at the url 'base'.
1026
 
 
1027
 
        :param format: If supplied, the format of branch to create.  If not
1028
 
            supplied, the default is used.
1029
 
        :param possible_transports: If supplied, a list of transports that
1030
 
            can be reused to share a remote connection.
1031
 
        """
1032
 
        if cls is not BzrDir:
1033
 
            raise AssertionError("BzrDir.create always creates the"
1034
 
                "default format, not one of %r" % cls)
1035
 
        t = _mod_transport.get_transport(base, possible_transports)
1036
 
        t.ensure_base()
1037
 
        if format is None:
1038
 
            format = controldir.ControlDirFormat.get_default_format()
1039
 
        return format.initialize_on_transport(t)
1040
 
 
1041
 
    def get_branch_transport(self, branch_format, name=None):
1042
 
        """Get the transport for use by branch format in this BzrDir.
1043
 
 
1044
 
        Note that bzr dirs that do not support format strings will raise
1045
 
        IncompatibleFormat if the branch format they are given has
1046
 
        a format string, and vice versa.
1047
 
 
1048
 
        If branch_format is None, the transport is returned with no
1049
 
        checking. If it is not None, then the returned transport is
1050
 
        guaranteed to point to an existing directory ready for use.
1051
 
        """
1052
 
        raise NotImplementedError(self.get_branch_transport)
1053
 
 
1054
 
    def get_repository_transport(self, repository_format):
1055
 
        """Get the transport for use by repository format in this BzrDir.
1056
 
 
1057
 
        Note that bzr dirs that do not support format strings will raise
1058
 
        IncompatibleFormat if the repository format they are given has
1059
 
        a format string, and vice versa.
1060
 
 
1061
 
        If repository_format is None, the transport is returned with no
1062
 
        checking. If it is not None, then the returned transport is
1063
 
        guaranteed to point to an existing directory ready for use.
1064
 
        """
1065
 
        raise NotImplementedError(self.get_repository_transport)
1066
 
 
1067
 
    def get_workingtree_transport(self, tree_format):
1068
 
        """Get the transport for use by workingtree format in this BzrDir.
1069
 
 
1070
 
        Note that bzr dirs that do not support format strings will raise
1071
 
        IncompatibleFormat if the workingtree format they are given has a
1072
 
        format string, and vice versa.
1073
 
 
1074
 
        If workingtree_format is None, the transport is returned with no
1075
 
        checking. If it is not None, then the returned transport is
1076
 
        guaranteed to point to an existing directory ready for use.
1077
 
        """
1078
 
        raise NotImplementedError(self.get_workingtree_transport)
 
1131
    def checkout_metadir(self):
 
1132
        return self.cloning_metadir()
 
1133
 
 
1134
    def sprout(self, url, revision_id=None, force_new_repo=False,
 
1135
               recurse='down', possible_transports=None,
 
1136
               accelerator_tree=None, hardlink=False, stacked=False,
 
1137
               source_branch=None, create_tree_if_local=True):
 
1138
        """Create a copy of this bzrdir prepared for use as a new line of
 
1139
        development.
 
1140
 
 
1141
        If url's last component does not exist, it will be created.
 
1142
 
 
1143
        Attributes related to the identity of the source branch like
 
1144
        branch nickname will be cleaned, a working tree is created
 
1145
        whether one existed before or not; and a local branch is always
 
1146
        created.
 
1147
 
 
1148
        if revision_id is not None, then the clone operation may tune
 
1149
            itself to download less data.
 
1150
        :param accelerator_tree: A tree which can be used for retrieving file
 
1151
            contents more quickly than the revision tree, i.e. a workingtree.
 
1152
            The revision tree will be used for cases where accelerator_tree's
 
1153
            content is different.
 
1154
        :param hardlink: If true, hard-link files from accelerator_tree,
 
1155
            where possible.
 
1156
        :param stacked: If true, create a stacked branch referring to the
 
1157
            location of this control directory.
 
1158
        :param create_tree_if_local: If true, a working-tree will be created
 
1159
            when working locally.
 
1160
        """
 
1161
        target_transport = get_transport(url, possible_transports)
 
1162
        target_transport.ensure_base()
 
1163
        cloning_format = self.cloning_metadir(stacked)
 
1164
        # Create/update the result branch
 
1165
        result = cloning_format.initialize_on_transport(target_transport)
 
1166
        # if a stacked branch wasn't requested, we don't create one
 
1167
        # even if the origin was stacked
 
1168
        stacked_branch_url = None
 
1169
        if source_branch is not None:
 
1170
            if stacked:
 
1171
                stacked_branch_url = self.root_transport.base
 
1172
            source_repository = source_branch.repository
 
1173
        else:
 
1174
            try:
 
1175
                source_branch = self.open_branch()
 
1176
                source_repository = source_branch.repository
 
1177
                if stacked:
 
1178
                    stacked_branch_url = self.root_transport.base
 
1179
            except errors.NotBranchError:
 
1180
                source_branch = None
 
1181
                try:
 
1182
                    source_repository = self.open_repository()
 
1183
                except errors.NoRepositoryPresent:
 
1184
                    source_repository = None
 
1185
        repository_policy = result.determine_repository_policy(
 
1186
            force_new_repo, stacked_branch_url, require_stacking=stacked)
 
1187
        result_repo, is_new_repo = repository_policy.acquire_repository()
 
1188
        if is_new_repo and revision_id is not None and not stacked:
 
1189
            fetch_spec = graph.PendingAncestryResult(
 
1190
                [revision_id], source_repository)
 
1191
        else:
 
1192
            fetch_spec = None
 
1193
        if source_repository is not None:
 
1194
            # Fetch while stacked to prevent unstacked fetch from
 
1195
            # Branch.sprout.
 
1196
            if fetch_spec is None:
 
1197
                result_repo.fetch(source_repository, revision_id=revision_id)
 
1198
            else:
 
1199
                result_repo.fetch(source_repository, fetch_spec=fetch_spec)
 
1200
 
 
1201
        if source_branch is None:
 
1202
            # this is for sprouting a bzrdir without a branch; is that
 
1203
            # actually useful?
 
1204
            # Not especially, but it's part of the contract.
 
1205
            result_branch = result.create_branch()
 
1206
        else:
 
1207
            result_branch = source_branch.sprout(result,
 
1208
                revision_id=revision_id, repository_policy=repository_policy)
 
1209
        mutter("created new branch %r" % (result_branch,))
 
1210
 
 
1211
        # Create/update the result working tree
 
1212
        if (create_tree_if_local and
 
1213
            isinstance(target_transport, local.LocalTransport) and
 
1214
            (result_repo is None or result_repo.make_working_trees())):
 
1215
            wt = result.create_workingtree(accelerator_tree=accelerator_tree,
 
1216
                hardlink=hardlink)
 
1217
            wt.lock_write()
 
1218
            try:
 
1219
                if wt.path2id('') is None:
 
1220
                    try:
 
1221
                        wt.set_root_id(self.open_workingtree.get_root_id())
 
1222
                    except errors.NoWorkingTree:
 
1223
                        pass
 
1224
            finally:
 
1225
                wt.unlock()
 
1226
        else:
 
1227
            wt = None
 
1228
        if recurse == 'down':
 
1229
            if wt is not None:
 
1230
                basis = wt.basis_tree()
 
1231
                basis.lock_read()
 
1232
                subtrees = basis.iter_references()
 
1233
            elif result_branch is not None:
 
1234
                basis = result_branch.basis_tree()
 
1235
                basis.lock_read()
 
1236
                subtrees = basis.iter_references()
 
1237
            elif source_branch is not None:
 
1238
                basis = source_branch.basis_tree()
 
1239
                basis.lock_read()
 
1240
                subtrees = basis.iter_references()
 
1241
            else:
 
1242
                subtrees = []
 
1243
                basis = None
 
1244
            try:
 
1245
                for path, file_id in subtrees:
 
1246
                    target = urlutils.join(url, urlutils.escape(path))
 
1247
                    sublocation = source_branch.reference_parent(file_id, path)
 
1248
                    sublocation.bzrdir.sprout(target,
 
1249
                        basis.get_reference_revision(file_id, path),
 
1250
                        force_new_repo=force_new_repo, recurse=recurse,
 
1251
                        stacked=stacked)
 
1252
            finally:
 
1253
                if basis is not None:
 
1254
                    basis.unlock()
 
1255
        return result
 
1256
 
 
1257
    def push_branch(self, source, revision_id=None, overwrite=False, 
 
1258
        remember=False, create_prefix=False):
 
1259
        """Push the source branch into this BzrDir."""
 
1260
        br_to = None
 
1261
        # If we can open a branch, use its direct repository, otherwise see
 
1262
        # if there is a repository without a branch.
 
1263
        try:
 
1264
            br_to = self.open_branch()
 
1265
        except errors.NotBranchError:
 
1266
            # Didn't find a branch, can we find a repository?
 
1267
            repository_to = self.find_repository()
 
1268
        else:
 
1269
            # Found a branch, so we must have found a repository
 
1270
            repository_to = br_to.repository
 
1271
 
 
1272
        push_result = PushResult()
 
1273
        push_result.source_branch = source
 
1274
        if br_to is None:
 
1275
            # We have a repository but no branch, copy the revisions, and then
 
1276
            # create a branch.
 
1277
            repository_to.fetch(source.repository, revision_id=revision_id)
 
1278
            br_to = source.clone(self, revision_id=revision_id)
 
1279
            if source.get_push_location() is None or remember:
 
1280
                source.set_push_location(br_to.base)
 
1281
            push_result.stacked_on = None
 
1282
            push_result.branch_push_result = None
 
1283
            push_result.old_revno = None
 
1284
            push_result.old_revid = _mod_revision.NULL_REVISION
 
1285
            push_result.target_branch = br_to
 
1286
            push_result.master_branch = None
 
1287
            push_result.workingtree_updated = False
 
1288
        else:
 
1289
            # We have successfully opened the branch, remember if necessary:
 
1290
            if source.get_push_location() is None or remember:
 
1291
                source.set_push_location(br_to.base)
 
1292
            try:
 
1293
                tree_to = self.open_workingtree()
 
1294
            except errors.NotLocalUrl:
 
1295
                push_result.branch_push_result = source.push(br_to, 
 
1296
                    overwrite, stop_revision=revision_id)
 
1297
                push_result.workingtree_updated = False
 
1298
            except errors.NoWorkingTree:
 
1299
                push_result.branch_push_result = source.push(br_to,
 
1300
                    overwrite, stop_revision=revision_id)
 
1301
                push_result.workingtree_updated = None # Not applicable
 
1302
            else:
 
1303
                tree_to.lock_write()
 
1304
                try:
 
1305
                    push_result.branch_push_result = source.push(
 
1306
                        tree_to.branch, overwrite, stop_revision=revision_id)
 
1307
                    tree_to.update()
 
1308
                finally:
 
1309
                    tree_to.unlock()
 
1310
                push_result.workingtree_updated = True
 
1311
            push_result.old_revno = push_result.branch_push_result.old_revno
 
1312
            push_result.old_revid = push_result.branch_push_result.old_revid
 
1313
            push_result.target_branch = \
 
1314
                push_result.branch_push_result.target_branch
 
1315
        return push_result
1079
1316
 
1080
1317
 
1081
1318
class BzrDirHooks(hooks.Hooks):
1083
1320
 
1084
1321
    def __init__(self):
1085
1322
        """Create the default hooks."""
1086
 
        hooks.Hooks.__init__(self, "bzrlib.bzrdir", "BzrDir.hooks")
1087
 
        self.add_hook('pre_open',
 
1323
        hooks.Hooks.__init__(self)
 
1324
        self.create_hook(hooks.HookPoint('pre_open',
1088
1325
            "Invoked before attempting to open a BzrDir with the transport "
1089
 
            "that the open will use.", (1, 14))
1090
 
        self.add_hook('post_repo_init',
1091
 
            "Invoked after a repository has been initialized. "
1092
 
            "post_repo_init is called with a "
1093
 
            "bzrlib.bzrdir.RepoInitHookParams.",
1094
 
            (2, 2))
 
1326
            "that the open will use.", (1, 14), None))
1095
1327
 
1096
1328
# install the default hooks
1097
1329
BzrDir.hooks = BzrDirHooks()
1098
1330
 
1099
1331
 
1100
 
class RepoInitHookParams(object):
1101
 
    """Object holding parameters passed to `*_repo_init` hooks.
1102
 
 
1103
 
    There are 4 fields that hooks may wish to access:
1104
 
 
1105
 
    :ivar repository: Repository created
1106
 
    :ivar format: Repository format
1107
 
    :ivar bzrdir: The bzrdir for the repository
1108
 
    :ivar shared: The repository is shared
1109
 
    """
1110
 
 
1111
 
    def __init__(self, repository, format, a_bzrdir, shared):
1112
 
        """Create a group of RepoInitHook parameters.
1113
 
 
1114
 
        :param repository: Repository created
1115
 
        :param format: Repository format
1116
 
        :param bzrdir: The bzrdir for the repository
1117
 
        :param shared: The repository is shared
 
1332
class BzrDirPreSplitOut(BzrDir):
 
1333
    """A common class for the all-in-one formats."""
 
1334
 
 
1335
    def __init__(self, _transport, _format):
 
1336
        """See BzrDir.__init__."""
 
1337
        super(BzrDirPreSplitOut, self).__init__(_transport, _format)
 
1338
        self._control_files = lockable_files.LockableFiles(
 
1339
                                            self.get_branch_transport(None),
 
1340
                                            self._format._lock_file_name,
 
1341
                                            self._format._lock_class)
 
1342
 
 
1343
    def break_lock(self):
 
1344
        """Pre-splitout bzrdirs do not suffer from stale locks."""
 
1345
        raise NotImplementedError(self.break_lock)
 
1346
 
 
1347
    def cloning_metadir(self, require_stacking=False):
 
1348
        """Produce a metadir suitable for cloning with."""
 
1349
        if require_stacking:
 
1350
            return format_registry.make_bzrdir('1.6')
 
1351
        return self._format.__class__()
 
1352
 
 
1353
    def clone(self, url, revision_id=None, force_new_repo=False,
 
1354
              preserve_stacking=False):
 
1355
        """See BzrDir.clone().
 
1356
 
 
1357
        force_new_repo has no effect, since this family of formats always
 
1358
        require a new repository.
 
1359
        preserve_stacking has no effect, since no source branch using this
 
1360
        family of formats can be stacked, so there is no stacking to preserve.
1118
1361
        """
1119
 
        self.repository = repository
1120
 
        self.format = format
1121
 
        self.bzrdir = a_bzrdir
1122
 
        self.shared = shared
1123
 
 
1124
 
    def __eq__(self, other):
1125
 
        return self.__dict__ == other.__dict__
1126
 
 
1127
 
    def __repr__(self):
1128
 
        if self.repository:
1129
 
            return "<%s for %s>" % (self.__class__.__name__,
1130
 
                self.repository)
 
1362
        self._make_tail(url)
 
1363
        result = self._format._initialize_for_clone(url)
 
1364
        self.open_repository().clone(result, revision_id=revision_id)
 
1365
        from_branch = self.open_branch()
 
1366
        from_branch.clone(result, revision_id=revision_id)
 
1367
        try:
 
1368
            tree = self.open_workingtree()
 
1369
        except errors.NotLocalUrl:
 
1370
            # make a new one, this format always has to have one.
 
1371
            result._init_workingtree()
1131
1372
        else:
1132
 
            return "<%s for %s>" % (self.__class__.__name__,
1133
 
                self.bzrdir)
 
1373
            tree.clone(result)
 
1374
        return result
 
1375
 
 
1376
    def create_branch(self):
 
1377
        """See BzrDir.create_branch."""
 
1378
        return self._format.get_branch_format().initialize(self)
 
1379
 
 
1380
    def destroy_branch(self):
 
1381
        """See BzrDir.destroy_branch."""
 
1382
        raise errors.UnsupportedOperation(self.destroy_branch, self)
 
1383
 
 
1384
    def create_repository(self, shared=False):
 
1385
        """See BzrDir.create_repository."""
 
1386
        if shared:
 
1387
            raise errors.IncompatibleFormat('shared repository', self._format)
 
1388
        return self.open_repository()
 
1389
 
 
1390
    def destroy_repository(self):
 
1391
        """See BzrDir.destroy_repository."""
 
1392
        raise errors.UnsupportedOperation(self.destroy_repository, self)
 
1393
 
 
1394
    def create_workingtree(self, revision_id=None, from_branch=None,
 
1395
                           accelerator_tree=None, hardlink=False):
 
1396
        """See BzrDir.create_workingtree."""
 
1397
        # The workingtree is sometimes created when the bzrdir is created,
 
1398
        # but not when cloning.
 
1399
 
 
1400
        # this looks buggy but is not -really-
 
1401
        # because this format creates the workingtree when the bzrdir is
 
1402
        # created
 
1403
        # clone and sprout will have set the revision_id
 
1404
        # and that will have set it for us, its only
 
1405
        # specific uses of create_workingtree in isolation
 
1406
        # that can do wonky stuff here, and that only
 
1407
        # happens for creating checkouts, which cannot be
 
1408
        # done on this format anyway. So - acceptable wart.
 
1409
        if hardlink:
 
1410
            warning("can't support hardlinked working trees in %r"
 
1411
                % (self,))
 
1412
        try:
 
1413
            result = self.open_workingtree(recommend_upgrade=False)
 
1414
        except errors.NoSuchFile:
 
1415
            result = self._init_workingtree()
 
1416
        if revision_id is not None:
 
1417
            if revision_id == _mod_revision.NULL_REVISION:
 
1418
                result.set_parent_ids([])
 
1419
            else:
 
1420
                result.set_parent_ids([revision_id])
 
1421
        return result
 
1422
 
 
1423
    def _init_workingtree(self):
 
1424
        from bzrlib.workingtree import WorkingTreeFormat2
 
1425
        try:
 
1426
            return WorkingTreeFormat2().initialize(self)
 
1427
        except errors.NotLocalUrl:
 
1428
            # Even though we can't access the working tree, we need to
 
1429
            # create its control files.
 
1430
            return WorkingTreeFormat2()._stub_initialize_on_transport(
 
1431
                self.transport, self._control_files._file_mode)
 
1432
 
 
1433
    def destroy_workingtree(self):
 
1434
        """See BzrDir.destroy_workingtree."""
 
1435
        raise errors.UnsupportedOperation(self.destroy_workingtree, self)
 
1436
 
 
1437
    def destroy_workingtree_metadata(self):
 
1438
        """See BzrDir.destroy_workingtree_metadata."""
 
1439
        raise errors.UnsupportedOperation(self.destroy_workingtree_metadata,
 
1440
                                          self)
 
1441
 
 
1442
    def get_branch_transport(self, branch_format):
 
1443
        """See BzrDir.get_branch_transport()."""
 
1444
        if branch_format is None:
 
1445
            return self.transport
 
1446
        try:
 
1447
            branch_format.get_format_string()
 
1448
        except NotImplementedError:
 
1449
            return self.transport
 
1450
        raise errors.IncompatibleFormat(branch_format, self._format)
 
1451
 
 
1452
    def get_repository_transport(self, repository_format):
 
1453
        """See BzrDir.get_repository_transport()."""
 
1454
        if repository_format is None:
 
1455
            return self.transport
 
1456
        try:
 
1457
            repository_format.get_format_string()
 
1458
        except NotImplementedError:
 
1459
            return self.transport
 
1460
        raise errors.IncompatibleFormat(repository_format, self._format)
 
1461
 
 
1462
    def get_workingtree_transport(self, workingtree_format):
 
1463
        """See BzrDir.get_workingtree_transport()."""
 
1464
        if workingtree_format is None:
 
1465
            return self.transport
 
1466
        try:
 
1467
            workingtree_format.get_format_string()
 
1468
        except NotImplementedError:
 
1469
            return self.transport
 
1470
        raise errors.IncompatibleFormat(workingtree_format, self._format)
 
1471
 
 
1472
    def needs_format_conversion(self, format=None):
 
1473
        """See BzrDir.needs_format_conversion()."""
 
1474
        # if the format is not the same as the system default,
 
1475
        # an upgrade is needed.
 
1476
        if format is None:
 
1477
            symbol_versioning.warn(symbol_versioning.deprecated_in((1, 13, 0))
 
1478
                % 'needs_format_conversion(format=None)')
 
1479
            format = BzrDirFormat.get_default_format()
 
1480
        return not isinstance(self._format, format.__class__)
 
1481
 
 
1482
    def open_branch(self, unsupported=False, ignore_fallbacks=False):
 
1483
        """See BzrDir.open_branch."""
 
1484
        from bzrlib.branch import BzrBranchFormat4
 
1485
        format = BzrBranchFormat4()
 
1486
        self._check_supported(format, unsupported)
 
1487
        return format.open(self, _found=True)
 
1488
 
 
1489
    def sprout(self, url, revision_id=None, force_new_repo=False,
 
1490
               possible_transports=None, accelerator_tree=None,
 
1491
               hardlink=False, stacked=False, create_tree_if_local=True,
 
1492
               source_branch=None):
 
1493
        """See BzrDir.sprout()."""
 
1494
        if source_branch is not None:
 
1495
            my_branch = self.open_branch()
 
1496
            if source_branch.base != my_branch.base:
 
1497
                raise AssertionError(
 
1498
                    "source branch %r is not within %r with branch %r" %
 
1499
                    (source_branch, self, my_branch))
 
1500
        if stacked:
 
1501
            raise errors.UnstackableBranchFormat(
 
1502
                self._format, self.root_transport.base)
 
1503
        if not create_tree_if_local:
 
1504
            raise errors.MustHaveWorkingTree(
 
1505
                self._format, self.root_transport.base)
 
1506
        from bzrlib.workingtree import WorkingTreeFormat2
 
1507
        self._make_tail(url)
 
1508
        result = self._format._initialize_for_clone(url)
 
1509
        try:
 
1510
            self.open_repository().clone(result, revision_id=revision_id)
 
1511
        except errors.NoRepositoryPresent:
 
1512
            pass
 
1513
        try:
 
1514
            self.open_branch().sprout(result, revision_id=revision_id)
 
1515
        except errors.NotBranchError:
 
1516
            pass
 
1517
 
 
1518
        # we always want a working tree
 
1519
        WorkingTreeFormat2().initialize(result,
 
1520
                                        accelerator_tree=accelerator_tree,
 
1521
                                        hardlink=hardlink)
 
1522
        return result
 
1523
 
 
1524
 
 
1525
class BzrDir4(BzrDirPreSplitOut):
 
1526
    """A .bzr version 4 control object.
 
1527
 
 
1528
    This is a deprecated format and may be removed after sept 2006.
 
1529
    """
 
1530
 
 
1531
    def create_repository(self, shared=False):
 
1532
        """See BzrDir.create_repository."""
 
1533
        return self._format.repository_format.initialize(self, shared)
 
1534
 
 
1535
    def needs_format_conversion(self, format=None):
 
1536
        """Format 4 dirs are always in need of conversion."""
 
1537
        if format is None:
 
1538
            symbol_versioning.warn(symbol_versioning.deprecated_in((1, 13, 0))
 
1539
                % 'needs_format_conversion(format=None)')
 
1540
        return True
 
1541
 
 
1542
    def open_repository(self):
 
1543
        """See BzrDir.open_repository."""
 
1544
        from bzrlib.repofmt.weaverepo import RepositoryFormat4
 
1545
        return RepositoryFormat4().open(self, _found=True)
 
1546
 
 
1547
 
 
1548
class BzrDir5(BzrDirPreSplitOut):
 
1549
    """A .bzr version 5 control object.
 
1550
 
 
1551
    This is a deprecated format and may be removed after sept 2006.
 
1552
    """
 
1553
 
 
1554
    def has_workingtree(self):
 
1555
        """See BzrDir.has_workingtree."""
 
1556
        return True
 
1557
    
 
1558
    def open_repository(self):
 
1559
        """See BzrDir.open_repository."""
 
1560
        from bzrlib.repofmt.weaverepo import RepositoryFormat5
 
1561
        return RepositoryFormat5().open(self, _found=True)
 
1562
 
 
1563
    def open_workingtree(self, _unsupported=False,
 
1564
            recommend_upgrade=True):
 
1565
        """See BzrDir.create_workingtree."""
 
1566
        from bzrlib.workingtree import WorkingTreeFormat2
 
1567
        wt_format = WorkingTreeFormat2()
 
1568
        # we don't warn here about upgrades; that ought to be handled for the
 
1569
        # bzrdir as a whole
 
1570
        return wt_format.open(self, _found=True)
 
1571
 
 
1572
 
 
1573
class BzrDir6(BzrDirPreSplitOut):
 
1574
    """A .bzr version 6 control object.
 
1575
 
 
1576
    This is a deprecated format and may be removed after sept 2006.
 
1577
    """
 
1578
 
 
1579
    def has_workingtree(self):
 
1580
        """See BzrDir.has_workingtree."""
 
1581
        return True
 
1582
    
 
1583
    def open_repository(self):
 
1584
        """See BzrDir.open_repository."""
 
1585
        from bzrlib.repofmt.weaverepo import RepositoryFormat6
 
1586
        return RepositoryFormat6().open(self, _found=True)
 
1587
 
 
1588
    def open_workingtree(self, _unsupported=False,
 
1589
        recommend_upgrade=True):
 
1590
        """See BzrDir.create_workingtree."""
 
1591
        # we don't warn here about upgrades; that ought to be handled for the
 
1592
        # bzrdir as a whole
 
1593
        from bzrlib.workingtree import WorkingTreeFormat2
 
1594
        return WorkingTreeFormat2().open(self, _found=True)
1134
1595
 
1135
1596
 
1136
1597
class BzrDirMeta1(BzrDir):
1146
1607
        """See BzrDir.can_convert_format()."""
1147
1608
        return True
1148
1609
 
1149
 
    def create_branch(self, name=None, repository=None,
1150
 
            append_revisions_only=None):
 
1610
    def create_branch(self):
1151
1611
        """See BzrDir.create_branch."""
1152
 
        return self._format.get_branch_format().initialize(self, name=name,
1153
 
                repository=repository,
1154
 
                append_revisions_only=append_revisions_only)
 
1612
        return self._format.get_branch_format().initialize(self)
1155
1613
 
1156
 
    def destroy_branch(self, name=None):
 
1614
    def destroy_branch(self):
1157
1615
        """See BzrDir.create_branch."""
1158
 
        if name is not None:
1159
 
            raise errors.NoColocatedBranchSupport(self)
1160
1616
        self.transport.delete_tree('branch')
1161
1617
 
1162
1618
    def create_repository(self, shared=False):
1179
1635
        wt = self.open_workingtree(recommend_upgrade=False)
1180
1636
        repository = wt.branch.repository
1181
1637
        empty = repository.revision_tree(_mod_revision.NULL_REVISION)
1182
 
        # We ignore the conflicts returned by wt.revert since we're about to
1183
 
        # delete the wt metadata anyway, all that should be left here are
1184
 
        # detritus. But see bug #634470 about subtree .bzr dirs.
1185
 
        conflicts = wt.revert(old_tree=empty)
 
1638
        wt.revert(old_tree=empty)
1186
1639
        self.destroy_workingtree_metadata()
1187
1640
 
1188
1641
    def destroy_workingtree_metadata(self):
1189
1642
        self.transport.delete_tree('checkout')
1190
1643
 
1191
 
    def find_branch_format(self, name=None):
 
1644
    def find_branch_format(self):
1192
1645
        """Find the branch 'format' for this bzrdir.
1193
1646
 
1194
1647
        This might be a synthetic object for e.g. RemoteBranch and SVN.
1195
1648
        """
1196
1649
        from bzrlib.branch import BranchFormat
1197
 
        return BranchFormat.find_format(self, name=name)
 
1650
        return BranchFormat.find_format(self)
1198
1651
 
1199
1652
    def _get_mkdir_mode(self):
1200
1653
        """Figure out the mode to use when creating a bzrdir subdir."""
1202
1655
                                     lockable_files.TransportLock)
1203
1656
        return temp_control._dir_mode
1204
1657
 
1205
 
    def get_branch_reference(self, name=None):
 
1658
    def get_branch_reference(self):
1206
1659
        """See BzrDir.get_branch_reference()."""
1207
1660
        from bzrlib.branch import BranchFormat
1208
 
        format = BranchFormat.find_format(self, name=name)
1209
 
        return format.get_reference(self, name=name)
 
1661
        format = BranchFormat.find_format(self)
 
1662
        return format.get_reference(self)
1210
1663
 
1211
 
    def get_branch_transport(self, branch_format, name=None):
 
1664
    def get_branch_transport(self, branch_format):
1212
1665
        """See BzrDir.get_branch_transport()."""
1213
 
        if name is not None:
1214
 
            raise errors.NoColocatedBranchSupport(self)
1215
1666
        # XXX: this shouldn't implicitly create the directory if it's just
1216
1667
        # promising to get a transport -- mbp 20090727
1217
1668
        if branch_format is None:
1257
1708
    def has_workingtree(self):
1258
1709
        """Tell if this bzrdir contains a working tree.
1259
1710
 
 
1711
        This will still raise an exception if the bzrdir has a workingtree that
 
1712
        is remote & inaccessible.
 
1713
 
1260
1714
        Note: if you're going to open the working tree, you should just go
1261
1715
        ahead and try, and not ask permission first.
1262
1716
        """
1263
1717
        from bzrlib.workingtree import WorkingTreeFormat
1264
1718
        try:
1265
 
            WorkingTreeFormat.find_format_string(self)
 
1719
            WorkingTreeFormat.find_format(self)
1266
1720
        except errors.NoWorkingTree:
1267
1721
            return False
1268
1722
        return True
1269
1723
 
1270
 
    def needs_format_conversion(self, format):
 
1724
    def needs_format_conversion(self, format=None):
1271
1725
        """See BzrDir.needs_format_conversion()."""
 
1726
        if format is None:
 
1727
            symbol_versioning.warn(symbol_versioning.deprecated_in((1, 13, 0))
 
1728
                % 'needs_format_conversion(format=None)')
 
1729
        if format is None:
 
1730
            format = BzrDirFormat.get_default_format()
1272
1731
        if not isinstance(self._format, format.__class__):
1273
1732
            # it is not a meta dir format, conversion is needed.
1274
1733
            return True
1280
1739
                return True
1281
1740
        except errors.NoRepositoryPresent:
1282
1741
            pass
1283
 
        for branch in self.list_branches():
1284
 
            if not isinstance(branch._format,
 
1742
        try:
 
1743
            if not isinstance(self.open_branch()._format,
1285
1744
                              format.get_branch_format().__class__):
1286
1745
                # the branch needs an upgrade.
1287
1746
                return True
 
1747
        except errors.NotBranchError:
 
1748
            pass
1288
1749
        try:
1289
1750
            my_wt = self.open_workingtree(recommend_upgrade=False)
1290
1751
            if not isinstance(my_wt._format,
1295
1756
            pass
1296
1757
        return False
1297
1758
 
1298
 
    def open_branch(self, name=None, unsupported=False,
1299
 
                    ignore_fallbacks=False):
 
1759
    def open_branch(self, unsupported=False, ignore_fallbacks=False):
1300
1760
        """See BzrDir.open_branch."""
1301
 
        format = self.find_branch_format(name=name)
1302
 
        format.check_support_status(unsupported)
1303
 
        return format.open(self, name=name,
1304
 
            _found=True, ignore_fallbacks=ignore_fallbacks)
 
1761
        format = self.find_branch_format()
 
1762
        self._check_supported(format, unsupported)
 
1763
        return format.open(self, _found=True, ignore_fallbacks=ignore_fallbacks)
1305
1764
 
1306
1765
    def open_repository(self, unsupported=False):
1307
1766
        """See BzrDir.open_repository."""
1308
1767
        from bzrlib.repository import RepositoryFormat
1309
1768
        format = RepositoryFormat.find_format(self)
1310
 
        format.check_support_status(unsupported)
 
1769
        self._check_supported(format, unsupported)
1311
1770
        return format.open(self, _found=True)
1312
1771
 
1313
1772
    def open_workingtree(self, unsupported=False,
1315
1774
        """See BzrDir.open_workingtree."""
1316
1775
        from bzrlib.workingtree import WorkingTreeFormat
1317
1776
        format = WorkingTreeFormat.find_format(self)
1318
 
        format.check_support_status(unsupported, recommend_upgrade,
 
1777
        self._check_supported(format, unsupported,
 
1778
            recommend_upgrade,
1319
1779
            basedir=self.root_transport.base)
1320
1780
        return format.open(self, _found=True)
1321
1781
 
1323
1783
        return config.TransportConfig(self.transport, 'control.conf')
1324
1784
 
1325
1785
 
1326
 
class BzrProber(controldir.Prober):
1327
 
    """Prober for formats that use a .bzr/ control directory."""
1328
 
 
1329
 
    formats = registry.FormatRegistry(controldir.network_format_registry)
1330
 
    """The known .bzr formats."""
1331
 
 
1332
 
    @classmethod
1333
 
    @deprecated_method(deprecated_in((2, 4, 0)))
1334
 
    def register_bzrdir_format(klass, format):
1335
 
        klass.formats.register(format.get_format_string(), format)
1336
 
 
1337
 
    @classmethod
1338
 
    @deprecated_method(deprecated_in((2, 4, 0)))
1339
 
    def unregister_bzrdir_format(klass, format):
1340
 
        klass.formats.remove(format.get_format_string())
1341
 
 
1342
 
    @classmethod
1343
 
    def probe_transport(klass, transport):
1344
 
        """Return the .bzrdir style format present in a directory."""
1345
 
        try:
1346
 
            format_string = transport.get_bytes(".bzr/branch-format")
1347
 
        except errors.NoSuchFile:
1348
 
            raise errors.NotBranchError(path=transport.base)
1349
 
        try:
1350
 
            return klass.formats.get(format_string)
1351
 
        except KeyError:
1352
 
            raise errors.UnknownFormatError(format=format_string, kind='bzrdir')
1353
 
 
1354
 
    @classmethod
1355
 
    def known_formats(cls):
1356
 
        result = set()
1357
 
        for name, format in cls.formats.iteritems():
1358
 
            if callable(format):
1359
 
                format = format()
1360
 
            result.add(format)
1361
 
        return result
1362
 
 
1363
 
 
1364
 
controldir.ControlDirFormat.register_prober(BzrProber)
1365
 
 
1366
 
 
1367
 
class RemoteBzrProber(controldir.Prober):
1368
 
    """Prober for remote servers that provide a Bazaar smart server."""
1369
 
 
1370
 
    @classmethod
1371
 
    def probe_transport(klass, transport):
1372
 
        """Return a RemoteBzrDirFormat object if it looks possible."""
1373
 
        try:
1374
 
            medium = transport.get_smart_medium()
1375
 
        except (NotImplementedError, AttributeError,
1376
 
                errors.TransportNotPossible, errors.NoSmartMedium,
1377
 
                errors.SmartProtocolError):
1378
 
            # no smart server, so not a branch for this format type.
1379
 
            raise errors.NotBranchError(path=transport.base)
1380
 
        else:
1381
 
            # Decline to open it if the server doesn't support our required
1382
 
            # version (3) so that the VFS-based transport will do it.
1383
 
            if medium.should_probe():
1384
 
                try:
1385
 
                    server_version = medium.protocol_version()
1386
 
                except errors.SmartProtocolError:
1387
 
                    # Apparently there's no usable smart server there, even though
1388
 
                    # the medium supports the smart protocol.
1389
 
                    raise errors.NotBranchError(path=transport.base)
1390
 
                if server_version != '2':
1391
 
                    raise errors.NotBranchError(path=transport.base)
1392
 
            from bzrlib.remote import RemoteBzrDirFormat
1393
 
            return RemoteBzrDirFormat()
1394
 
 
1395
 
    @classmethod
1396
 
    def known_formats(cls):
1397
 
        from bzrlib.remote import RemoteBzrDirFormat
1398
 
        return set([RemoteBzrDirFormat()])
1399
 
 
1400
 
 
1401
 
class BzrDirFormat(controldir.ControlDirFormat):
1402
 
    """ControlDirFormat base class for .bzr/ directories.
 
1786
class BzrDirFormat(object):
 
1787
    """An encapsulation of the initialization and open routines for a format.
 
1788
 
 
1789
    Formats provide three things:
 
1790
     * An initialization routine,
 
1791
     * a format string,
 
1792
     * an open routine.
1403
1793
 
1404
1794
    Formats are placed in a dict by their format string for reference
1405
1795
    during bzrdir opening. These should be subclasses of BzrDirFormat
1410
1800
    object will be created every system load.
1411
1801
    """
1412
1802
 
 
1803
    _default_format = None
 
1804
    """The default format used for new .bzr dirs."""
 
1805
 
 
1806
    _formats = {}
 
1807
    """The known formats."""
 
1808
 
 
1809
    _control_formats = []
 
1810
    """The registered control formats - .bzr, ....
 
1811
 
 
1812
    This is a list of BzrDirFormat objects.
 
1813
    """
 
1814
 
 
1815
    _control_server_formats = []
 
1816
    """The registered control server formats, e.g. RemoteBzrDirs.
 
1817
 
 
1818
    This is a list of BzrDirFormat objects.
 
1819
    """
 
1820
 
1413
1821
    _lock_file_name = 'branch-lock'
1414
1822
 
1415
1823
    # _lock_class must be set in subclasses to the lock type, typ.
1416
1824
    # TransportLock or LockDir
1417
1825
 
1418
1826
    @classmethod
1419
 
    def get_format_string(cls):
 
1827
    def find_format(klass, transport, _server_formats=True):
 
1828
        """Return the format present at transport."""
 
1829
        if _server_formats:
 
1830
            formats = klass._control_server_formats + klass._control_formats
 
1831
        else:
 
1832
            formats = klass._control_formats
 
1833
        for format in formats:
 
1834
            try:
 
1835
                return format.probe_transport(transport)
 
1836
            except errors.NotBranchError:
 
1837
                # this format does not find a control dir here.
 
1838
                pass
 
1839
        raise errors.NotBranchError(path=transport.base)
 
1840
 
 
1841
    @classmethod
 
1842
    def probe_transport(klass, transport):
 
1843
        """Return the .bzrdir style format present in a directory."""
 
1844
        try:
 
1845
            format_string = transport.get_bytes(".bzr/branch-format")
 
1846
        except errors.NoSuchFile:
 
1847
            raise errors.NotBranchError(path=transport.base)
 
1848
 
 
1849
        try:
 
1850
            return klass._formats[format_string]
 
1851
        except KeyError:
 
1852
            raise errors.UnknownFormatError(format=format_string, kind='bzrdir')
 
1853
 
 
1854
    @classmethod
 
1855
    def get_default_format(klass):
 
1856
        """Return the current default format."""
 
1857
        return klass._default_format
 
1858
 
 
1859
    def get_format_string(self):
1420
1860
        """Return the ASCII format string that identifies this format."""
1421
 
        raise NotImplementedError(cls.get_format_string)
 
1861
        raise NotImplementedError(self.get_format_string)
 
1862
 
 
1863
    def get_format_description(self):
 
1864
        """Return the short description for this format."""
 
1865
        raise NotImplementedError(self.get_format_description)
 
1866
 
 
1867
    def get_converter(self, format=None):
 
1868
        """Return the converter to use to convert bzrdirs needing converts.
 
1869
 
 
1870
        This returns a bzrlib.bzrdir.Converter object.
 
1871
 
 
1872
        This should return the best upgrader to step this format towards the
 
1873
        current default format. In the case of plugins we can/should provide
 
1874
        some means for them to extend the range of returnable converters.
 
1875
 
 
1876
        :param format: Optional format to override the default format of the
 
1877
                       library.
 
1878
        """
 
1879
        raise NotImplementedError(self.get_converter)
 
1880
 
 
1881
    def initialize(self, url, possible_transports=None):
 
1882
        """Create a bzr control dir at this url and return an opened copy.
 
1883
 
 
1884
        While not deprecated, this method is very specific and its use will
 
1885
        lead to many round trips to setup a working environment. See
 
1886
        initialize_on_transport_ex for a [nearly] all-in-one method.
 
1887
 
 
1888
        Subclasses should typically override initialize_on_transport
 
1889
        instead of this method.
 
1890
        """
 
1891
        return self.initialize_on_transport(get_transport(url,
 
1892
                                                          possible_transports))
1422
1893
 
1423
1894
    def initialize_on_transport(self, transport):
1424
1895
        """Initialize a new bzrdir in the base directory of a Transport."""
1434
1905
            # metadir1
1435
1906
            if type(self) != BzrDirMetaFormat1:
1436
1907
                return self._initialize_on_transport_vfs(transport)
1437
 
            from bzrlib.remote import RemoteBzrDirFormat
1438
1908
            remote_format = RemoteBzrDirFormat()
1439
1909
            self._supply_sub_formats_to(remote_format)
1440
1910
            return remote_format.initialize_on_transport(transport)
1478
1948
            except errors.NoSmartMedium:
1479
1949
                pass
1480
1950
            else:
1481
 
                from bzrlib.remote import RemoteBzrDirFormat
1482
1951
                # TODO: lookup the local format from a server hint.
1483
1952
                remote_dir_format = RemoteBzrDirFormat()
1484
1953
                remote_dir_format._network_name = self.network_name()
1559
2028
        utf8_files = [('README',
1560
2029
                       "This is a Bazaar control directory.\n"
1561
2030
                       "Do not change any files in this directory.\n"
1562
 
                       "See http://bazaar.canonical.com/ for more information about Bazaar.\n"),
 
2031
                       "See http://bazaar-vcs.org/ for more information about Bazaar.\n"),
1563
2032
                      ('branch-format', self.get_format_string()),
1564
2033
                      ]
1565
2034
        # NB: no need to escape relative paths that are url safe.
1575
2044
            control_files.unlock()
1576
2045
        return self.open(transport, _found=True)
1577
2046
 
 
2047
    def is_supported(self):
 
2048
        """Is this format supported?
 
2049
 
 
2050
        Supported formats must be initializable and openable.
 
2051
        Unsupported formats may not support initialization or committing or
 
2052
        some other features depending on the reason for not being supported.
 
2053
        """
 
2054
        return True
 
2055
 
 
2056
    def network_name(self):
 
2057
        """A simple byte string uniquely identifying this format for RPC calls.
 
2058
 
 
2059
        Bzr control formats use thir disk format string to identify the format
 
2060
        over the wire. Its possible that other control formats have more
 
2061
        complex detection requirements, so we permit them to use any unique and
 
2062
        immutable string they desire.
 
2063
        """
 
2064
        raise NotImplementedError(self.network_name)
 
2065
 
 
2066
    def same_model(self, target_format):
 
2067
        return (self.repository_format.rich_root_data ==
 
2068
            target_format.rich_root_data)
 
2069
 
 
2070
    @classmethod
 
2071
    def known_formats(klass):
 
2072
        """Return all the known formats.
 
2073
 
 
2074
        Concrete formats should override _known_formats.
 
2075
        """
 
2076
        # There is double indirection here to make sure that control
 
2077
        # formats used by more than one dir format will only be probed
 
2078
        # once. This can otherwise be quite expensive for remote connections.
 
2079
        result = set()
 
2080
        for format in klass._control_formats:
 
2081
            result.update(format._known_formats())
 
2082
        return result
 
2083
 
 
2084
    @classmethod
 
2085
    def _known_formats(klass):
 
2086
        """Return the known format instances for this control format."""
 
2087
        return set(klass._formats.values())
 
2088
 
1578
2089
    def open(self, transport, _found=False):
1579
2090
        """Return an instance of this format for the dir transport points at.
1580
2091
 
1581
2092
        _found is a private parameter, do not use it.
1582
2093
        """
1583
2094
        if not _found:
1584
 
            found_format = controldir.ControlDirFormat.find_format(transport)
 
2095
            found_format = BzrDirFormat.find_format(transport)
1585
2096
            if not isinstance(found_format, self.__class__):
1586
2097
                raise AssertionError("%s was asked to open %s, but it seems to need "
1587
2098
                        "format %s"
1599
2110
        """
1600
2111
        raise NotImplementedError(self._open)
1601
2112
 
 
2113
    @classmethod
 
2114
    def register_format(klass, format):
 
2115
        klass._formats[format.get_format_string()] = format
 
2116
        # bzr native formats have a network name of their format string.
 
2117
        network_format_registry.register(format.get_format_string(), format.__class__)
 
2118
 
 
2119
    @classmethod
 
2120
    def register_control_format(klass, format):
 
2121
        """Register a format that does not use '.bzr' for its control dir.
 
2122
 
 
2123
        TODO: This should be pulled up into a 'ControlDirFormat' base class
 
2124
        which BzrDirFormat can inherit from, and renamed to register_format
 
2125
        there. It has been done without that for now for simplicity of
 
2126
        implementation.
 
2127
        """
 
2128
        klass._control_formats.append(format)
 
2129
 
 
2130
    @classmethod
 
2131
    def register_control_server_format(klass, format):
 
2132
        """Register a control format for client-server environments.
 
2133
 
 
2134
        These formats will be tried before ones registered with
 
2135
        register_control_format.  This gives implementations that decide to the
 
2136
        chance to grab it before anything looks at the contents of the format
 
2137
        file.
 
2138
        """
 
2139
        klass._control_server_formats.append(format)
 
2140
 
 
2141
    @classmethod
 
2142
    def _set_default_format(klass, format):
 
2143
        """Set default format (for testing behavior of defaults only)"""
 
2144
        klass._default_format = format
 
2145
 
 
2146
    def __str__(self):
 
2147
        # Trim the newline
 
2148
        return self.get_format_description().rstrip()
 
2149
 
1602
2150
    def _supply_sub_formats_to(self, other_format):
1603
2151
        """Give other_format the same values for sub formats as this has.
1604
2152
 
1611
2159
        :return: None.
1612
2160
        """
1613
2161
 
 
2162
    @classmethod
 
2163
    def unregister_format(klass, format):
 
2164
        del klass._formats[format.get_format_string()]
 
2165
 
 
2166
    @classmethod
 
2167
    def unregister_control_format(klass, format):
 
2168
        klass._control_formats.remove(format)
 
2169
 
 
2170
 
 
2171
class BzrDirFormat4(BzrDirFormat):
 
2172
    """Bzr dir format 4.
 
2173
 
 
2174
    This format is a combined format for working tree, branch and repository.
 
2175
    It has:
 
2176
     - Format 1 working trees [always]
 
2177
     - Format 4 branches [always]
 
2178
     - Format 4 repositories [always]
 
2179
 
 
2180
    This format is deprecated: it indexes texts using a text it which is
 
2181
    removed in format 5; write support for this format has been removed.
 
2182
    """
 
2183
 
 
2184
    _lock_class = lockable_files.TransportLock
 
2185
 
 
2186
    def get_format_string(self):
 
2187
        """See BzrDirFormat.get_format_string()."""
 
2188
        return "Bazaar-NG branch, format 0.0.4\n"
 
2189
 
 
2190
    def get_format_description(self):
 
2191
        """See BzrDirFormat.get_format_description()."""
 
2192
        return "All-in-one format 4"
 
2193
 
 
2194
    def get_converter(self, format=None):
 
2195
        """See BzrDirFormat.get_converter()."""
 
2196
        # there is one and only one upgrade path here.
 
2197
        return ConvertBzrDir4To5()
 
2198
 
 
2199
    def initialize_on_transport(self, transport):
 
2200
        """Format 4 branches cannot be created."""
 
2201
        raise errors.UninitializableFormat(self)
 
2202
 
 
2203
    def is_supported(self):
 
2204
        """Format 4 is not supported.
 
2205
 
 
2206
        It is not supported because the model changed from 4 to 5 and the
 
2207
        conversion logic is expensive - so doing it on the fly was not
 
2208
        feasible.
 
2209
        """
 
2210
        return False
 
2211
 
 
2212
    def network_name(self):
 
2213
        return self.get_format_string()
 
2214
 
 
2215
    def _open(self, transport):
 
2216
        """See BzrDirFormat._open."""
 
2217
        return BzrDir4(transport, self)
 
2218
 
 
2219
    def __return_repository_format(self):
 
2220
        """Circular import protection."""
 
2221
        from bzrlib.repofmt.weaverepo import RepositoryFormat4
 
2222
        return RepositoryFormat4()
 
2223
    repository_format = property(__return_repository_format)
 
2224
 
 
2225
 
 
2226
class BzrDirFormatAllInOne(BzrDirFormat):
 
2227
    """Common class for formats before meta-dirs."""
 
2228
 
 
2229
    def initialize_on_transport_ex(self, transport, use_existing_dir=False,
 
2230
        create_prefix=False, force_new_repo=False, stacked_on=None,
 
2231
        stack_on_pwd=None, repo_format_name=None, make_working_trees=None,
 
2232
        shared_repo=False):
 
2233
        """See BzrDirFormat.initialize_on_transport_ex."""
 
2234
        require_stacking = (stacked_on is not None)
 
2235
        # Format 5 cannot stack, but we've been asked to - actually init
 
2236
        # a Meta1Dir
 
2237
        if require_stacking:
 
2238
            format = BzrDirMetaFormat1()
 
2239
            return format.initialize_on_transport_ex(transport,
 
2240
                use_existing_dir=use_existing_dir, create_prefix=create_prefix,
 
2241
                force_new_repo=force_new_repo, stacked_on=stacked_on,
 
2242
                stack_on_pwd=stack_on_pwd, repo_format_name=repo_format_name,
 
2243
                make_working_trees=make_working_trees, shared_repo=shared_repo)
 
2244
        return BzrDirFormat.initialize_on_transport_ex(self, transport,
 
2245
            use_existing_dir=use_existing_dir, create_prefix=create_prefix,
 
2246
            force_new_repo=force_new_repo, stacked_on=stacked_on,
 
2247
            stack_on_pwd=stack_on_pwd, repo_format_name=repo_format_name,
 
2248
            make_working_trees=make_working_trees, shared_repo=shared_repo)
 
2249
 
 
2250
 
 
2251
class BzrDirFormat5(BzrDirFormatAllInOne):
 
2252
    """Bzr control format 5.
 
2253
 
 
2254
    This format is a combined format for working tree, branch and repository.
 
2255
    It has:
 
2256
     - Format 2 working trees [always]
 
2257
     - Format 4 branches [always]
 
2258
     - Format 5 repositories [always]
 
2259
       Unhashed stores in the repository.
 
2260
    """
 
2261
 
 
2262
    _lock_class = lockable_files.TransportLock
 
2263
 
 
2264
    def get_format_string(self):
 
2265
        """See BzrDirFormat.get_format_string()."""
 
2266
        return "Bazaar-NG branch, format 5\n"
 
2267
 
 
2268
    def get_branch_format(self):
 
2269
        from bzrlib import branch
 
2270
        return branch.BzrBranchFormat4()
 
2271
 
 
2272
    def get_format_description(self):
 
2273
        """See BzrDirFormat.get_format_description()."""
 
2274
        return "All-in-one format 5"
 
2275
 
 
2276
    def get_converter(self, format=None):
 
2277
        """See BzrDirFormat.get_converter()."""
 
2278
        # there is one and only one upgrade path here.
 
2279
        return ConvertBzrDir5To6()
 
2280
 
 
2281
    def _initialize_for_clone(self, url):
 
2282
        return self.initialize_on_transport(get_transport(url), _cloning=True)
 
2283
 
 
2284
    def initialize_on_transport(self, transport, _cloning=False):
 
2285
        """Format 5 dirs always have working tree, branch and repository.
 
2286
 
 
2287
        Except when they are being cloned.
 
2288
        """
 
2289
        from bzrlib.branch import BzrBranchFormat4
 
2290
        from bzrlib.repofmt.weaverepo import RepositoryFormat5
 
2291
        result = (super(BzrDirFormat5, self).initialize_on_transport(transport))
 
2292
        RepositoryFormat5().initialize(result, _internal=True)
 
2293
        if not _cloning:
 
2294
            branch = BzrBranchFormat4().initialize(result)
 
2295
            result._init_workingtree()
 
2296
        return result
 
2297
 
 
2298
    def network_name(self):
 
2299
        return self.get_format_string()
 
2300
 
 
2301
    def _open(self, transport):
 
2302
        """See BzrDirFormat._open."""
 
2303
        return BzrDir5(transport, self)
 
2304
 
 
2305
    def __return_repository_format(self):
 
2306
        """Circular import protection."""
 
2307
        from bzrlib.repofmt.weaverepo import RepositoryFormat5
 
2308
        return RepositoryFormat5()
 
2309
    repository_format = property(__return_repository_format)
 
2310
 
 
2311
 
 
2312
class BzrDirFormat6(BzrDirFormatAllInOne):
 
2313
    """Bzr control format 6.
 
2314
 
 
2315
    This format is a combined format for working tree, branch and repository.
 
2316
    It has:
 
2317
     - Format 2 working trees [always]
 
2318
     - Format 4 branches [always]
 
2319
     - Format 6 repositories [always]
 
2320
    """
 
2321
 
 
2322
    _lock_class = lockable_files.TransportLock
 
2323
 
 
2324
    def get_format_string(self):
 
2325
        """See BzrDirFormat.get_format_string()."""
 
2326
        return "Bazaar-NG branch, format 6\n"
 
2327
 
 
2328
    def get_format_description(self):
 
2329
        """See BzrDirFormat.get_format_description()."""
 
2330
        return "All-in-one format 6"
 
2331
 
 
2332
    def get_branch_format(self):
 
2333
        from bzrlib import branch
 
2334
        return branch.BzrBranchFormat4()
 
2335
 
 
2336
    def get_converter(self, format=None):
 
2337
        """See BzrDirFormat.get_converter()."""
 
2338
        # there is one and only one upgrade path here.
 
2339
        return ConvertBzrDir6ToMeta()
 
2340
 
 
2341
    def _initialize_for_clone(self, url):
 
2342
        return self.initialize_on_transport(get_transport(url), _cloning=True)
 
2343
 
 
2344
    def initialize_on_transport(self, transport, _cloning=False):
 
2345
        """Format 6 dirs always have working tree, branch and repository.
 
2346
 
 
2347
        Except when they are being cloned.
 
2348
        """
 
2349
        from bzrlib.branch import BzrBranchFormat4
 
2350
        from bzrlib.repofmt.weaverepo import RepositoryFormat6
 
2351
        result = super(BzrDirFormat6, self).initialize_on_transport(transport)
 
2352
        RepositoryFormat6().initialize(result, _internal=True)
 
2353
        if not _cloning:
 
2354
            branch = BzrBranchFormat4().initialize(result)
 
2355
            result._init_workingtree()
 
2356
        return result
 
2357
 
 
2358
    def network_name(self):
 
2359
        return self.get_format_string()
 
2360
 
 
2361
    def _open(self, transport):
 
2362
        """See BzrDirFormat._open."""
 
2363
        return BzrDir6(transport, self)
 
2364
 
 
2365
    def __return_repository_format(self):
 
2366
        """Circular import protection."""
 
2367
        from bzrlib.repofmt.weaverepo import RepositoryFormat6
 
2368
        return RepositoryFormat6()
 
2369
    repository_format = property(__return_repository_format)
 
2370
 
1614
2371
 
1615
2372
class BzrDirMetaFormat1(BzrDirFormat):
1616
2373
    """Bzr meta control format 1
1617
2374
 
1618
2375
    This is the first format with split out working tree, branch and repository
1619
2376
    disk storage.
1620
 
 
1621
2377
    It has:
1622
 
 
1623
 
    - Format 3 working trees [optional]
1624
 
    - Format 5 branches [optional]
1625
 
    - Format 7 repositories [optional]
 
2378
     - Format 3 working trees [optional]
 
2379
     - Format 5 branches [optional]
 
2380
     - Format 7 repositories [optional]
1626
2381
    """
1627
2382
 
1628
2383
    _lock_class = lockdir.LockDir
1629
2384
 
1630
 
    fixed_components = False
1631
 
 
1632
2385
    def __init__(self):
1633
2386
        self._workingtree_format = None
1634
2387
        self._branch_format = None
1648
2401
 
1649
2402
    def get_branch_format(self):
1650
2403
        if self._branch_format is None:
1651
 
            from bzrlib.branch import format_registry as branch_format_registry
1652
 
            self._branch_format = branch_format_registry.get_default()
 
2404
            from bzrlib.branch import BranchFormat
 
2405
            self._branch_format = BranchFormat.get_default_format()
1653
2406
        return self._branch_format
1654
2407
 
1655
2408
    def set_branch_format(self, format):
1710
2463
                    # stack_on is inaccessible, JFDI.
1711
2464
                    # TODO: bad monkey, hard-coded formats...
1712
2465
                    if self.repository_format.rich_root_data:
1713
 
                        new_repo_format = knitpack_repo.RepositoryFormatKnitPack5RichRoot()
 
2466
                        new_repo_format = pack_repo.RepositoryFormatKnitPack5RichRoot()
1714
2467
                    else:
1715
 
                        new_repo_format = knitpack_repo.RepositoryFormatKnitPack5()
 
2468
                        new_repo_format = pack_repo.RepositoryFormatKnitPack5()
1716
2469
            else:
1717
2470
                # If the target already supports stacking, then we know the
1718
2471
                # project is already able to use stacking, so auto-upgrade
1724
2477
                    new_repo_format = None
1725
2478
            if new_repo_format is not None:
1726
2479
                self.repository_format = new_repo_format
1727
 
                note(gettext('Source repository format does not support stacking,'
1728
 
                     ' using format:\n  %s'),
 
2480
                note('Source repository format does not support stacking,'
 
2481
                     ' using format:\n  %s',
1729
2482
                     new_repo_format.get_format_description())
1730
2483
 
1731
2484
        if not self.get_branch_format().supports_stacking():
1735
2488
            if target_branch is None:
1736
2489
                if do_upgrade:
1737
2490
                    # TODO: bad monkey, hard-coded formats...
1738
 
                    from bzrlib.branch import BzrBranchFormat7
1739
 
                    new_branch_format = BzrBranchFormat7()
 
2491
                    new_branch_format = branch.BzrBranchFormat7()
1740
2492
            else:
1741
2493
                new_branch_format = target_branch._format
1742
2494
                if not new_branch_format.supports_stacking():
1744
2496
            if new_branch_format is not None:
1745
2497
                # Does support stacking, use its format.
1746
2498
                self.set_branch_format(new_branch_format)
1747
 
                note(gettext('Source branch format does not support stacking,'
1748
 
                     ' using format:\n  %s'),
 
2499
                note('Source branch format does not support stacking,'
 
2500
                     ' using format:\n  %s',
1749
2501
                     new_branch_format.get_format_description())
1750
2502
 
1751
2503
    def get_converter(self, format=None):
1757
2509
            raise NotImplementedError(self.get_converter)
1758
2510
        return ConvertMetaToMeta(format)
1759
2511
 
1760
 
    @classmethod
1761
 
    def get_format_string(cls):
 
2512
    def get_format_string(self):
1762
2513
        """See BzrDirFormat.get_format_string()."""
1763
2514
        return "Bazaar-NG meta directory, format 1\n"
1764
2515
 
1782
2533
        """Circular import protection."""
1783
2534
        if self._repository_format:
1784
2535
            return self._repository_format
1785
 
        from bzrlib.repository import format_registry
1786
 
        return format_registry.get_default()
 
2536
        from bzrlib.repository import RepositoryFormat
 
2537
        return RepositoryFormat.get_default_format()
1787
2538
 
1788
2539
    def _set_repository_format(self, value):
1789
2540
        """Allow changing the repository format for metadir formats."""
1812
2563
 
1813
2564
    def __get_workingtree_format(self):
1814
2565
        if self._workingtree_format is None:
1815
 
            from bzrlib.workingtree import (
1816
 
                format_registry as wt_format_registry,
1817
 
                )
1818
 
            self._workingtree_format = wt_format_registry.get_default()
 
2566
            from bzrlib.workingtree import WorkingTreeFormat
 
2567
            self._workingtree_format = WorkingTreeFormat.get_default_format()
1819
2568
        return self._workingtree_format
1820
2569
 
1821
2570
    def __set_workingtree_format(self, wt_format):
1825
2574
                                  __set_workingtree_format)
1826
2575
 
1827
2576
 
 
2577
network_format_registry = registry.FormatRegistry()
 
2578
"""Registry of formats indexed by their network name.
 
2579
 
 
2580
The network name for a BzrDirFormat is an identifier that can be used when
 
2581
referring to formats with smart server operations. See
 
2582
BzrDirFormat.network_name() for more detail.
 
2583
"""
 
2584
 
 
2585
 
 
2586
# Register bzr control format
 
2587
BzrDirFormat.register_control_format(BzrDirFormat)
 
2588
 
1828
2589
# Register bzr formats
1829
 
BzrProber.formats.register(BzrDirMetaFormat1.get_format_string(),
1830
 
    BzrDirMetaFormat1)
1831
 
controldir.ControlDirFormat._default_format = BzrDirMetaFormat1()
1832
 
 
1833
 
 
1834
 
class ConvertMetaToMeta(controldir.Converter):
 
2590
BzrDirFormat.register_format(BzrDirFormat4())
 
2591
BzrDirFormat.register_format(BzrDirFormat5())
 
2592
BzrDirFormat.register_format(BzrDirFormat6())
 
2593
__default_format = BzrDirMetaFormat1()
 
2594
BzrDirFormat.register_format(__default_format)
 
2595
BzrDirFormat._default_format = __default_format
 
2596
 
 
2597
 
 
2598
class Converter(object):
 
2599
    """Converts a disk format object from one format to another."""
 
2600
 
 
2601
    def convert(self, to_convert, pb):
 
2602
        """Perform the conversion of to_convert, giving feedback via pb.
 
2603
 
 
2604
        :param to_convert: The disk object to convert.
 
2605
        :param pb: a progress bar to use for progress information.
 
2606
        """
 
2607
 
 
2608
    def step(self, message):
 
2609
        """Update the pb by a step."""
 
2610
        self.count +=1
 
2611
        self.pb.update(message, self.count, self.total)
 
2612
 
 
2613
 
 
2614
class ConvertBzrDir4To5(Converter):
 
2615
    """Converts format 4 bzr dirs to format 5."""
 
2616
 
 
2617
    def __init__(self):
 
2618
        super(ConvertBzrDir4To5, self).__init__()
 
2619
        self.converted_revs = set()
 
2620
        self.absent_revisions = set()
 
2621
        self.text_count = 0
 
2622
        self.revisions = {}
 
2623
 
 
2624
    def convert(self, to_convert, pb):
 
2625
        """See Converter.convert()."""
 
2626
        self.bzrdir = to_convert
 
2627
        if pb is not None:
 
2628
            warnings.warn("pb parameter to convert() is deprecated")
 
2629
        self.pb = ui.ui_factory.nested_progress_bar()
 
2630
        try:
 
2631
            ui.ui_factory.note('starting upgrade from format 4 to 5')
 
2632
            if isinstance(self.bzrdir.transport, local.LocalTransport):
 
2633
                self.bzrdir.get_workingtree_transport(None).delete('stat-cache')
 
2634
            self._convert_to_weaves()
 
2635
            return BzrDir.open(self.bzrdir.root_transport.base)
 
2636
        finally:
 
2637
            self.pb.finished()
 
2638
 
 
2639
    def _convert_to_weaves(self):
 
2640
        ui.ui_factory.note('note: upgrade may be faster if all store files are ungzipped first')
 
2641
        try:
 
2642
            # TODO permissions
 
2643
            stat = self.bzrdir.transport.stat('weaves')
 
2644
            if not S_ISDIR(stat.st_mode):
 
2645
                self.bzrdir.transport.delete('weaves')
 
2646
                self.bzrdir.transport.mkdir('weaves')
 
2647
        except errors.NoSuchFile:
 
2648
            self.bzrdir.transport.mkdir('weaves')
 
2649
        # deliberately not a WeaveFile as we want to build it up slowly.
 
2650
        self.inv_weave = Weave('inventory')
 
2651
        # holds in-memory weaves for all files
 
2652
        self.text_weaves = {}
 
2653
        self.bzrdir.transport.delete('branch-format')
 
2654
        self.branch = self.bzrdir.open_branch()
 
2655
        self._convert_working_inv()
 
2656
        rev_history = self.branch.revision_history()
 
2657
        # to_read is a stack holding the revisions we still need to process;
 
2658
        # appending to it adds new highest-priority revisions
 
2659
        self.known_revisions = set(rev_history)
 
2660
        self.to_read = rev_history[-1:]
 
2661
        while self.to_read:
 
2662
            rev_id = self.to_read.pop()
 
2663
            if (rev_id not in self.revisions
 
2664
                and rev_id not in self.absent_revisions):
 
2665
                self._load_one_rev(rev_id)
 
2666
        self.pb.clear()
 
2667
        to_import = self._make_order()
 
2668
        for i, rev_id in enumerate(to_import):
 
2669
            self.pb.update('converting revision', i, len(to_import))
 
2670
            self._convert_one_rev(rev_id)
 
2671
        self.pb.clear()
 
2672
        self._write_all_weaves()
 
2673
        self._write_all_revs()
 
2674
        ui.ui_factory.note('upgraded to weaves:')
 
2675
        ui.ui_factory.note('  %6d revisions and inventories' % len(self.revisions))
 
2676
        ui.ui_factory.note('  %6d revisions not present' % len(self.absent_revisions))
 
2677
        ui.ui_factory.note('  %6d texts' % self.text_count)
 
2678
        self._cleanup_spare_files_after_format4()
 
2679
        self.branch._transport.put_bytes(
 
2680
            'branch-format',
 
2681
            BzrDirFormat5().get_format_string(),
 
2682
            mode=self.bzrdir._get_file_mode())
 
2683
 
 
2684
    def _cleanup_spare_files_after_format4(self):
 
2685
        # FIXME working tree upgrade foo.
 
2686
        for n in 'merged-patches', 'pending-merged-patches':
 
2687
            try:
 
2688
                ## assert os.path.getsize(p) == 0
 
2689
                self.bzrdir.transport.delete(n)
 
2690
            except errors.NoSuchFile:
 
2691
                pass
 
2692
        self.bzrdir.transport.delete_tree('inventory-store')
 
2693
        self.bzrdir.transport.delete_tree('text-store')
 
2694
 
 
2695
    def _convert_working_inv(self):
 
2696
        inv = xml4.serializer_v4.read_inventory(
 
2697
                self.branch._transport.get('inventory'))
 
2698
        new_inv_xml = xml5.serializer_v5.write_inventory_to_string(inv, working=True)
 
2699
        self.branch._transport.put_bytes('inventory', new_inv_xml,
 
2700
            mode=self.bzrdir._get_file_mode())
 
2701
 
 
2702
    def _write_all_weaves(self):
 
2703
        controlweaves = WeaveStore(self.bzrdir.transport, prefixed=False)
 
2704
        weave_transport = self.bzrdir.transport.clone('weaves')
 
2705
        weaves = WeaveStore(weave_transport, prefixed=False)
 
2706
        transaction = WriteTransaction()
 
2707
 
 
2708
        try:
 
2709
            i = 0
 
2710
            for file_id, file_weave in self.text_weaves.items():
 
2711
                self.pb.update('writing weave', i, len(self.text_weaves))
 
2712
                weaves._put_weave(file_id, file_weave, transaction)
 
2713
                i += 1
 
2714
            self.pb.update('inventory', 0, 1)
 
2715
            controlweaves._put_weave('inventory', self.inv_weave, transaction)
 
2716
            self.pb.update('inventory', 1, 1)
 
2717
        finally:
 
2718
            self.pb.clear()
 
2719
 
 
2720
    def _write_all_revs(self):
 
2721
        """Write all revisions out in new form."""
 
2722
        self.bzrdir.transport.delete_tree('revision-store')
 
2723
        self.bzrdir.transport.mkdir('revision-store')
 
2724
        revision_transport = self.bzrdir.transport.clone('revision-store')
 
2725
        # TODO permissions
 
2726
        from bzrlib.xml5 import serializer_v5
 
2727
        from bzrlib.repofmt.weaverepo import RevisionTextStore
 
2728
        revision_store = RevisionTextStore(revision_transport,
 
2729
            serializer_v5, False, versionedfile.PrefixMapper(),
 
2730
            lambda:True, lambda:True)
 
2731
        try:
 
2732
            for i, rev_id in enumerate(self.converted_revs):
 
2733
                self.pb.update('write revision', i, len(self.converted_revs))
 
2734
                text = serializer_v5.write_revision_to_string(
 
2735
                    self.revisions[rev_id])
 
2736
                key = (rev_id,)
 
2737
                revision_store.add_lines(key, None, osutils.split_lines(text))
 
2738
        finally:
 
2739
            self.pb.clear()
 
2740
 
 
2741
    def _load_one_rev(self, rev_id):
 
2742
        """Load a revision object into memory.
 
2743
 
 
2744
        Any parents not either loaded or abandoned get queued to be
 
2745
        loaded."""
 
2746
        self.pb.update('loading revision',
 
2747
                       len(self.revisions),
 
2748
                       len(self.known_revisions))
 
2749
        if not self.branch.repository.has_revision(rev_id):
 
2750
            self.pb.clear()
 
2751
            ui.ui_factory.note('revision {%s} not present in branch; '
 
2752
                         'will be converted as a ghost' %
 
2753
                         rev_id)
 
2754
            self.absent_revisions.add(rev_id)
 
2755
        else:
 
2756
            rev = self.branch.repository.get_revision(rev_id)
 
2757
            for parent_id in rev.parent_ids:
 
2758
                self.known_revisions.add(parent_id)
 
2759
                self.to_read.append(parent_id)
 
2760
            self.revisions[rev_id] = rev
 
2761
 
 
2762
    def _load_old_inventory(self, rev_id):
 
2763
        old_inv_xml = self.branch.repository.inventory_store.get(rev_id).read()
 
2764
        inv = xml4.serializer_v4.read_inventory_from_string(old_inv_xml)
 
2765
        inv.revision_id = rev_id
 
2766
        rev = self.revisions[rev_id]
 
2767
        return inv
 
2768
 
 
2769
    def _load_updated_inventory(self, rev_id):
 
2770
        inv_xml = self.inv_weave.get_text(rev_id)
 
2771
        inv = xml5.serializer_v5.read_inventory_from_string(inv_xml, rev_id)
 
2772
        return inv
 
2773
 
 
2774
    def _convert_one_rev(self, rev_id):
 
2775
        """Convert revision and all referenced objects to new format."""
 
2776
        rev = self.revisions[rev_id]
 
2777
        inv = self._load_old_inventory(rev_id)
 
2778
        present_parents = [p for p in rev.parent_ids
 
2779
                           if p not in self.absent_revisions]
 
2780
        self._convert_revision_contents(rev, inv, present_parents)
 
2781
        self._store_new_inv(rev, inv, present_parents)
 
2782
        self.converted_revs.add(rev_id)
 
2783
 
 
2784
    def _store_new_inv(self, rev, inv, present_parents):
 
2785
        new_inv_xml = xml5.serializer_v5.write_inventory_to_string(inv)
 
2786
        new_inv_sha1 = sha_string(new_inv_xml)
 
2787
        self.inv_weave.add_lines(rev.revision_id,
 
2788
                                 present_parents,
 
2789
                                 new_inv_xml.splitlines(True))
 
2790
        rev.inventory_sha1 = new_inv_sha1
 
2791
 
 
2792
    def _convert_revision_contents(self, rev, inv, present_parents):
 
2793
        """Convert all the files within a revision.
 
2794
 
 
2795
        Also upgrade the inventory to refer to the text revision ids."""
 
2796
        rev_id = rev.revision_id
 
2797
        mutter('converting texts of revision {%s}',
 
2798
               rev_id)
 
2799
        parent_invs = map(self._load_updated_inventory, present_parents)
 
2800
        entries = inv.iter_entries()
 
2801
        entries.next()
 
2802
        for path, ie in entries:
 
2803
            self._convert_file_version(rev, ie, parent_invs)
 
2804
 
 
2805
    def _convert_file_version(self, rev, ie, parent_invs):
 
2806
        """Convert one version of one file.
 
2807
 
 
2808
        The file needs to be added into the weave if it is a merge
 
2809
        of >=2 parents or if it's changed from its parent.
 
2810
        """
 
2811
        file_id = ie.file_id
 
2812
        rev_id = rev.revision_id
 
2813
        w = self.text_weaves.get(file_id)
 
2814
        if w is None:
 
2815
            w = Weave(file_id)
 
2816
            self.text_weaves[file_id] = w
 
2817
        text_changed = False
 
2818
        parent_candiate_entries = ie.parent_candidates(parent_invs)
 
2819
        heads = graph.Graph(self).heads(parent_candiate_entries.keys())
 
2820
        # XXX: Note that this is unordered - and this is tolerable because
 
2821
        # the previous code was also unordered.
 
2822
        previous_entries = dict((head, parent_candiate_entries[head]) for head
 
2823
            in heads)
 
2824
        self.snapshot_ie(previous_entries, ie, w, rev_id)
 
2825
        del ie.text_id
 
2826
 
 
2827
    def get_parent_map(self, revision_ids):
 
2828
        """See graph.StackedParentsProvider.get_parent_map"""
 
2829
        return dict((revision_id, self.revisions[revision_id])
 
2830
                    for revision_id in revision_ids
 
2831
                     if revision_id in self.revisions)
 
2832
 
 
2833
    def snapshot_ie(self, previous_revisions, ie, w, rev_id):
 
2834
        # TODO: convert this logic, which is ~= snapshot to
 
2835
        # a call to:. This needs the path figured out. rather than a work_tree
 
2836
        # a v4 revision_tree can be given, or something that looks enough like
 
2837
        # one to give the file content to the entry if it needs it.
 
2838
        # and we need something that looks like a weave store for snapshot to
 
2839
        # save against.
 
2840
        #ie.snapshot(rev, PATH, previous_revisions, REVISION_TREE, InMemoryWeaveStore(self.text_weaves))
 
2841
        if len(previous_revisions) == 1:
 
2842
            previous_ie = previous_revisions.values()[0]
 
2843
            if ie._unchanged(previous_ie):
 
2844
                ie.revision = previous_ie.revision
 
2845
                return
 
2846
        if ie.has_text():
 
2847
            text = self.branch.repository._text_store.get(ie.text_id)
 
2848
            file_lines = text.readlines()
 
2849
            w.add_lines(rev_id, previous_revisions, file_lines)
 
2850
            self.text_count += 1
 
2851
        else:
 
2852
            w.add_lines(rev_id, previous_revisions, [])
 
2853
        ie.revision = rev_id
 
2854
 
 
2855
    def _make_order(self):
 
2856
        """Return a suitable order for importing revisions.
 
2857
 
 
2858
        The order must be such that an revision is imported after all
 
2859
        its (present) parents.
 
2860
        """
 
2861
        todo = set(self.revisions.keys())
 
2862
        done = self.absent_revisions.copy()
 
2863
        order = []
 
2864
        while todo:
 
2865
            # scan through looking for a revision whose parents
 
2866
            # are all done
 
2867
            for rev_id in sorted(list(todo)):
 
2868
                rev = self.revisions[rev_id]
 
2869
                parent_ids = set(rev.parent_ids)
 
2870
                if parent_ids.issubset(done):
 
2871
                    # can take this one now
 
2872
                    order.append(rev_id)
 
2873
                    todo.remove(rev_id)
 
2874
                    done.add(rev_id)
 
2875
        return order
 
2876
 
 
2877
 
 
2878
class ConvertBzrDir5To6(Converter):
 
2879
    """Converts format 5 bzr dirs to format 6."""
 
2880
 
 
2881
    def convert(self, to_convert, pb):
 
2882
        """See Converter.convert()."""
 
2883
        self.bzrdir = to_convert
 
2884
        pb = ui.ui_factory.nested_progress_bar()
 
2885
        try:
 
2886
            ui.ui_factory.note('starting upgrade from format 5 to 6')
 
2887
            self._convert_to_prefixed()
 
2888
            return BzrDir.open(self.bzrdir.root_transport.base)
 
2889
        finally:
 
2890
            pb.finished()
 
2891
 
 
2892
    def _convert_to_prefixed(self):
 
2893
        from bzrlib.store import TransportStore
 
2894
        self.bzrdir.transport.delete('branch-format')
 
2895
        for store_name in ["weaves", "revision-store"]:
 
2896
            ui.ui_factory.note("adding prefixes to %s" % store_name)
 
2897
            store_transport = self.bzrdir.transport.clone(store_name)
 
2898
            store = TransportStore(store_transport, prefixed=True)
 
2899
            for urlfilename in store_transport.list_dir('.'):
 
2900
                filename = urlutils.unescape(urlfilename)
 
2901
                if (filename.endswith(".weave") or
 
2902
                    filename.endswith(".gz") or
 
2903
                    filename.endswith(".sig")):
 
2904
                    file_id, suffix = os.path.splitext(filename)
 
2905
                else:
 
2906
                    file_id = filename
 
2907
                    suffix = ''
 
2908
                new_name = store._mapper.map((file_id,)) + suffix
 
2909
                # FIXME keep track of the dirs made RBC 20060121
 
2910
                try:
 
2911
                    store_transport.move(filename, new_name)
 
2912
                except errors.NoSuchFile: # catches missing dirs strangely enough
 
2913
                    store_transport.mkdir(osutils.dirname(new_name))
 
2914
                    store_transport.move(filename, new_name)
 
2915
        self.bzrdir.transport.put_bytes(
 
2916
            'branch-format',
 
2917
            BzrDirFormat6().get_format_string(),
 
2918
            mode=self.bzrdir._get_file_mode())
 
2919
 
 
2920
 
 
2921
class ConvertBzrDir6ToMeta(Converter):
 
2922
    """Converts format 6 bzr dirs to metadirs."""
 
2923
 
 
2924
    def convert(self, to_convert, pb):
 
2925
        """See Converter.convert()."""
 
2926
        from bzrlib.repofmt.weaverepo import RepositoryFormat7
 
2927
        from bzrlib.branch import BzrBranchFormat5
 
2928
        self.bzrdir = to_convert
 
2929
        self.pb = ui.ui_factory.nested_progress_bar()
 
2930
        self.count = 0
 
2931
        self.total = 20 # the steps we know about
 
2932
        self.garbage_inventories = []
 
2933
        self.dir_mode = self.bzrdir._get_dir_mode()
 
2934
        self.file_mode = self.bzrdir._get_file_mode()
 
2935
 
 
2936
        ui.ui_factory.note('starting upgrade from format 6 to metadir')
 
2937
        self.bzrdir.transport.put_bytes(
 
2938
                'branch-format',
 
2939
                "Converting to format 6",
 
2940
                mode=self.file_mode)
 
2941
        # its faster to move specific files around than to open and use the apis...
 
2942
        # first off, nuke ancestry.weave, it was never used.
 
2943
        try:
 
2944
            self.step('Removing ancestry.weave')
 
2945
            self.bzrdir.transport.delete('ancestry.weave')
 
2946
        except errors.NoSuchFile:
 
2947
            pass
 
2948
        # find out whats there
 
2949
        self.step('Finding branch files')
 
2950
        last_revision = self.bzrdir.open_branch().last_revision()
 
2951
        bzrcontents = self.bzrdir.transport.list_dir('.')
 
2952
        for name in bzrcontents:
 
2953
            if name.startswith('basis-inventory.'):
 
2954
                self.garbage_inventories.append(name)
 
2955
        # create new directories for repository, working tree and branch
 
2956
        repository_names = [('inventory.weave', True),
 
2957
                            ('revision-store', True),
 
2958
                            ('weaves', True)]
 
2959
        self.step('Upgrading repository  ')
 
2960
        self.bzrdir.transport.mkdir('repository', mode=self.dir_mode)
 
2961
        self.make_lock('repository')
 
2962
        # we hard code the formats here because we are converting into
 
2963
        # the meta format. The meta format upgrader can take this to a
 
2964
        # future format within each component.
 
2965
        self.put_format('repository', RepositoryFormat7())
 
2966
        for entry in repository_names:
 
2967
            self.move_entry('repository', entry)
 
2968
 
 
2969
        self.step('Upgrading branch      ')
 
2970
        self.bzrdir.transport.mkdir('branch', mode=self.dir_mode)
 
2971
        self.make_lock('branch')
 
2972
        self.put_format('branch', BzrBranchFormat5())
 
2973
        branch_files = [('revision-history', True),
 
2974
                        ('branch-name', True),
 
2975
                        ('parent', False)]
 
2976
        for entry in branch_files:
 
2977
            self.move_entry('branch', entry)
 
2978
 
 
2979
        checkout_files = [('pending-merges', True),
 
2980
                          ('inventory', True),
 
2981
                          ('stat-cache', False)]
 
2982
        # If a mandatory checkout file is not present, the branch does not have
 
2983
        # a functional checkout. Do not create a checkout in the converted
 
2984
        # branch.
 
2985
        for name, mandatory in checkout_files:
 
2986
            if mandatory and name not in bzrcontents:
 
2987
                has_checkout = False
 
2988
                break
 
2989
        else:
 
2990
            has_checkout = True
 
2991
        if not has_checkout:
 
2992
            ui.ui_factory.note('No working tree.')
 
2993
            # If some checkout files are there, we may as well get rid of them.
 
2994
            for name, mandatory in checkout_files:
 
2995
                if name in bzrcontents:
 
2996
                    self.bzrdir.transport.delete(name)
 
2997
        else:
 
2998
            from bzrlib.workingtree import WorkingTreeFormat3
 
2999
            self.step('Upgrading working tree')
 
3000
            self.bzrdir.transport.mkdir('checkout', mode=self.dir_mode)
 
3001
            self.make_lock('checkout')
 
3002
            self.put_format(
 
3003
                'checkout', WorkingTreeFormat3())
 
3004
            self.bzrdir.transport.delete_multi(
 
3005
                self.garbage_inventories, self.pb)
 
3006
            for entry in checkout_files:
 
3007
                self.move_entry('checkout', entry)
 
3008
            if last_revision is not None:
 
3009
                self.bzrdir.transport.put_bytes(
 
3010
                    'checkout/last-revision', last_revision)
 
3011
        self.bzrdir.transport.put_bytes(
 
3012
            'branch-format',
 
3013
            BzrDirMetaFormat1().get_format_string(),
 
3014
            mode=self.file_mode)
 
3015
        self.pb.finished()
 
3016
        return BzrDir.open(self.bzrdir.root_transport.base)
 
3017
 
 
3018
    def make_lock(self, name):
 
3019
        """Make a lock for the new control dir name."""
 
3020
        self.step('Make %s lock' % name)
 
3021
        ld = lockdir.LockDir(self.bzrdir.transport,
 
3022
                             '%s/lock' % name,
 
3023
                             file_modebits=self.file_mode,
 
3024
                             dir_modebits=self.dir_mode)
 
3025
        ld.create()
 
3026
 
 
3027
    def move_entry(self, new_dir, entry):
 
3028
        """Move then entry name into new_dir."""
 
3029
        name = entry[0]
 
3030
        mandatory = entry[1]
 
3031
        self.step('Moving %s' % name)
 
3032
        try:
 
3033
            self.bzrdir.transport.move(name, '%s/%s' % (new_dir, name))
 
3034
        except errors.NoSuchFile:
 
3035
            if mandatory:
 
3036
                raise
 
3037
 
 
3038
    def put_format(self, dirname, format):
 
3039
        self.bzrdir.transport.put_bytes('%s/format' % dirname,
 
3040
            format.get_format_string(),
 
3041
            self.file_mode)
 
3042
 
 
3043
 
 
3044
class ConvertMetaToMeta(Converter):
1835
3045
    """Converts the components of metadirs."""
1836
3046
 
1837
3047
    def __init__(self, target_format):
1855
3065
        else:
1856
3066
            if not isinstance(repo._format, self.target_format.repository_format.__class__):
1857
3067
                from bzrlib.repository import CopyConverter
1858
 
                ui.ui_factory.note(gettext('starting repository conversion'))
 
3068
                ui.ui_factory.note('starting repository conversion')
1859
3069
                converter = CopyConverter(self.target_format.repository_format)
1860
3070
                converter.convert(repo, pb)
1861
3071
        for branch in self.bzrdir.list_branches():
1862
3072
            # TODO: conversions of Branch and Tree should be done by
1863
3073
            # InterXFormat lookups/some sort of registry.
1864
3074
            # Avoid circular imports
 
3075
            from bzrlib import branch as _mod_branch
1865
3076
            old = branch._format.__class__
1866
3077
            new = self.target_format.get_branch_format().__class__
1867
3078
            while old != new:
1890
3101
        else:
1891
3102
            # TODO: conversions of Branch and Tree should be done by
1892
3103
            # InterXFormat lookups
1893
 
            if (isinstance(tree, workingtree_3.WorkingTree3) and
 
3104
            if (isinstance(tree, workingtree.WorkingTree3) and
1894
3105
                not isinstance(tree, workingtree_4.DirStateWorkingTree) and
1895
3106
                isinstance(self.target_format.workingtree_format,
1896
3107
                    workingtree_4.DirStateWorkingTreeFormat)):
1909
3120
        return to_convert
1910
3121
 
1911
3122
 
1912
 
controldir.ControlDirFormat.register_server_prober(RemoteBzrProber)
 
3123
# This is not in remote.py because it's relatively small, and needs to be
 
3124
# registered. Putting it in remote.py creates a circular import problem.
 
3125
# we can make it a lazy object if the control formats is turned into something
 
3126
# like a registry.
 
3127
class RemoteBzrDirFormat(BzrDirMetaFormat1):
 
3128
    """Format representing bzrdirs accessed via a smart server"""
 
3129
 
 
3130
    def __init__(self):
 
3131
        BzrDirMetaFormat1.__init__(self)
 
3132
        # XXX: It's a bit ugly that the network name is here, because we'd
 
3133
        # like to believe that format objects are stateless or at least
 
3134
        # immutable,  However, we do at least avoid mutating the name after
 
3135
        # it's returned.  See <https://bugs.edge.launchpad.net/bzr/+bug/504102>
 
3136
        self._network_name = None
 
3137
 
 
3138
    def __repr__(self):
 
3139
        return "%s(_network_name=%r)" % (self.__class__.__name__,
 
3140
            self._network_name)
 
3141
 
 
3142
    def get_format_description(self):
 
3143
        if self._network_name:
 
3144
            real_format = network_format_registry.get(self._network_name)
 
3145
            return 'Remote: ' + real_format.get_format_description()
 
3146
        return 'bzr remote bzrdir'
 
3147
 
 
3148
    def get_format_string(self):
 
3149
        raise NotImplementedError(self.get_format_string)
 
3150
 
 
3151
    def network_name(self):
 
3152
        if self._network_name:
 
3153
            return self._network_name
 
3154
        else:
 
3155
            raise AssertionError("No network name set.")
 
3156
 
 
3157
    @classmethod
 
3158
    def probe_transport(klass, transport):
 
3159
        """Return a RemoteBzrDirFormat object if it looks possible."""
 
3160
        try:
 
3161
            medium = transport.get_smart_medium()
 
3162
        except (NotImplementedError, AttributeError,
 
3163
                errors.TransportNotPossible, errors.NoSmartMedium,
 
3164
                errors.SmartProtocolError):
 
3165
            # no smart server, so not a branch for this format type.
 
3166
            raise errors.NotBranchError(path=transport.base)
 
3167
        else:
 
3168
            # Decline to open it if the server doesn't support our required
 
3169
            # version (3) so that the VFS-based transport will do it.
 
3170
            if medium.should_probe():
 
3171
                try:
 
3172
                    server_version = medium.protocol_version()
 
3173
                except errors.SmartProtocolError:
 
3174
                    # Apparently there's no usable smart server there, even though
 
3175
                    # the medium supports the smart protocol.
 
3176
                    raise errors.NotBranchError(path=transport.base)
 
3177
                if server_version != '2':
 
3178
                    raise errors.NotBranchError(path=transport.base)
 
3179
            return klass()
 
3180
 
 
3181
    def initialize_on_transport(self, transport):
 
3182
        try:
 
3183
            # hand off the request to the smart server
 
3184
            client_medium = transport.get_smart_medium()
 
3185
        except errors.NoSmartMedium:
 
3186
            # TODO: lookup the local format from a server hint.
 
3187
            local_dir_format = BzrDirMetaFormat1()
 
3188
            return local_dir_format.initialize_on_transport(transport)
 
3189
        client = _SmartClient(client_medium)
 
3190
        path = client.remote_path_from_transport(transport)
 
3191
        try:
 
3192
            response = client.call('BzrDirFormat.initialize', path)
 
3193
        except errors.ErrorFromSmartServer, err:
 
3194
            remote._translate_error(err, path=path)
 
3195
        if response[0] != 'ok':
 
3196
            raise errors.SmartProtocolError('unexpected response code %s' % (response,))
 
3197
        format = RemoteBzrDirFormat()
 
3198
        self._supply_sub_formats_to(format)
 
3199
        return remote.RemoteBzrDir(transport, format)
 
3200
 
 
3201
    def parse_NoneTrueFalse(self, arg):
 
3202
        if not arg:
 
3203
            return None
 
3204
        if arg == 'False':
 
3205
            return False
 
3206
        if arg == 'True':
 
3207
            return True
 
3208
        raise AssertionError("invalid arg %r" % arg)
 
3209
 
 
3210
    def _serialize_NoneTrueFalse(self, arg):
 
3211
        if arg is False:
 
3212
            return 'False'
 
3213
        if arg:
 
3214
            return 'True'
 
3215
        return ''
 
3216
 
 
3217
    def _serialize_NoneString(self, arg):
 
3218
        return arg or ''
 
3219
 
 
3220
    def initialize_on_transport_ex(self, transport, use_existing_dir=False,
 
3221
        create_prefix=False, force_new_repo=False, stacked_on=None,
 
3222
        stack_on_pwd=None, repo_format_name=None, make_working_trees=None,
 
3223
        shared_repo=False):
 
3224
        try:
 
3225
            # hand off the request to the smart server
 
3226
            client_medium = transport.get_smart_medium()
 
3227
        except errors.NoSmartMedium:
 
3228
            do_vfs = True
 
3229
        else:
 
3230
            # Decline to open it if the server doesn't support our required
 
3231
            # version (3) so that the VFS-based transport will do it.
 
3232
            if client_medium.should_probe():
 
3233
                try:
 
3234
                    server_version = client_medium.protocol_version()
 
3235
                    if server_version != '2':
 
3236
                        do_vfs = True
 
3237
                    else:
 
3238
                        do_vfs = False
 
3239
                except errors.SmartProtocolError:
 
3240
                    # Apparently there's no usable smart server there, even though
 
3241
                    # the medium supports the smart protocol.
 
3242
                    do_vfs = True
 
3243
            else:
 
3244
                do_vfs = False
 
3245
        if not do_vfs:
 
3246
            client = _SmartClient(client_medium)
 
3247
            path = client.remote_path_from_transport(transport)
 
3248
            if client_medium._is_remote_before((1, 16)):
 
3249
                do_vfs = True
 
3250
        if do_vfs:
 
3251
            # TODO: lookup the local format from a server hint.
 
3252
            local_dir_format = BzrDirMetaFormat1()
 
3253
            self._supply_sub_formats_to(local_dir_format)
 
3254
            return local_dir_format.initialize_on_transport_ex(transport,
 
3255
                use_existing_dir=use_existing_dir, create_prefix=create_prefix,
 
3256
                force_new_repo=force_new_repo, stacked_on=stacked_on,
 
3257
                stack_on_pwd=stack_on_pwd, repo_format_name=repo_format_name,
 
3258
                make_working_trees=make_working_trees, shared_repo=shared_repo,
 
3259
                vfs_only=True)
 
3260
        return self._initialize_on_transport_ex_rpc(client, path, transport,
 
3261
            use_existing_dir, create_prefix, force_new_repo, stacked_on,
 
3262
            stack_on_pwd, repo_format_name, make_working_trees, shared_repo)
 
3263
 
 
3264
    def _initialize_on_transport_ex_rpc(self, client, path, transport,
 
3265
        use_existing_dir, create_prefix, force_new_repo, stacked_on,
 
3266
        stack_on_pwd, repo_format_name, make_working_trees, shared_repo):
 
3267
        args = []
 
3268
        args.append(self._serialize_NoneTrueFalse(use_existing_dir))
 
3269
        args.append(self._serialize_NoneTrueFalse(create_prefix))
 
3270
        args.append(self._serialize_NoneTrueFalse(force_new_repo))
 
3271
        args.append(self._serialize_NoneString(stacked_on))
 
3272
        # stack_on_pwd is often/usually our transport
 
3273
        if stack_on_pwd:
 
3274
            try:
 
3275
                stack_on_pwd = transport.relpath(stack_on_pwd)
 
3276
                if not stack_on_pwd:
 
3277
                    stack_on_pwd = '.'
 
3278
            except errors.PathNotChild:
 
3279
                pass
 
3280
        args.append(self._serialize_NoneString(stack_on_pwd))
 
3281
        args.append(self._serialize_NoneString(repo_format_name))
 
3282
        args.append(self._serialize_NoneTrueFalse(make_working_trees))
 
3283
        args.append(self._serialize_NoneTrueFalse(shared_repo))
 
3284
        request_network_name = self._network_name or \
 
3285
            BzrDirFormat.get_default_format().network_name()
 
3286
        try:
 
3287
            response = client.call('BzrDirFormat.initialize_ex_1.16',
 
3288
                request_network_name, path, *args)
 
3289
        except errors.UnknownSmartMethod:
 
3290
            client._medium._remember_remote_is_before((1,16))
 
3291
            local_dir_format = BzrDirMetaFormat1()
 
3292
            self._supply_sub_formats_to(local_dir_format)
 
3293
            return local_dir_format.initialize_on_transport_ex(transport,
 
3294
                use_existing_dir=use_existing_dir, create_prefix=create_prefix,
 
3295
                force_new_repo=force_new_repo, stacked_on=stacked_on,
 
3296
                stack_on_pwd=stack_on_pwd, repo_format_name=repo_format_name,
 
3297
                make_working_trees=make_working_trees, shared_repo=shared_repo,
 
3298
                vfs_only=True)
 
3299
        except errors.ErrorFromSmartServer, err:
 
3300
            remote._translate_error(err, path=path)
 
3301
        repo_path = response[0]
 
3302
        bzrdir_name = response[6]
 
3303
        require_stacking = response[7]
 
3304
        require_stacking = self.parse_NoneTrueFalse(require_stacking)
 
3305
        format = RemoteBzrDirFormat()
 
3306
        format._network_name = bzrdir_name
 
3307
        self._supply_sub_formats_to(format)
 
3308
        bzrdir = remote.RemoteBzrDir(transport, format, _client=client)
 
3309
        if repo_path:
 
3310
            repo_format = remote.response_tuple_to_repo_format(response[1:])
 
3311
            if repo_path == '.':
 
3312
                repo_path = ''
 
3313
            if repo_path:
 
3314
                repo_bzrdir_format = RemoteBzrDirFormat()
 
3315
                repo_bzrdir_format._network_name = response[5]
 
3316
                repo_bzr = remote.RemoteBzrDir(transport.clone(repo_path),
 
3317
                    repo_bzrdir_format)
 
3318
            else:
 
3319
                repo_bzr = bzrdir
 
3320
            final_stack = response[8] or None
 
3321
            final_stack_pwd = response[9] or None
 
3322
            if final_stack_pwd:
 
3323
                final_stack_pwd = urlutils.join(
 
3324
                    transport.base, final_stack_pwd)
 
3325
            remote_repo = remote.RemoteRepository(repo_bzr, repo_format)
 
3326
            if len(response) > 10:
 
3327
                # Updated server verb that locks remotely.
 
3328
                repo_lock_token = response[10] or None
 
3329
                remote_repo.lock_write(repo_lock_token, _skip_rpc=True)
 
3330
                if repo_lock_token:
 
3331
                    remote_repo.dont_leave_lock_in_place()
 
3332
            else:
 
3333
                remote_repo.lock_write()
 
3334
            policy = UseExistingRepository(remote_repo, final_stack,
 
3335
                final_stack_pwd, require_stacking)
 
3336
            policy.acquire_repository()
 
3337
        else:
 
3338
            remote_repo = None
 
3339
            policy = None
 
3340
        bzrdir._format.set_branch_format(self.get_branch_format())
 
3341
        if require_stacking:
 
3342
            # The repo has already been created, but we need to make sure that
 
3343
            # we'll make a stackable branch.
 
3344
            bzrdir._format.require_stacking(_skip_repo=True)
 
3345
        return remote_repo, bzrdir, require_stacking, policy
 
3346
 
 
3347
    def _open(self, transport):
 
3348
        return remote.RemoteBzrDir(transport, self)
 
3349
 
 
3350
    def __eq__(self, other):
 
3351
        if not isinstance(other, RemoteBzrDirFormat):
 
3352
            return False
 
3353
        return self.get_format_description() == other.get_format_description()
 
3354
 
 
3355
    def __return_repository_format(self):
 
3356
        # Always return a RemoteRepositoryFormat object, but if a specific bzr
 
3357
        # repository format has been asked for, tell the RemoteRepositoryFormat
 
3358
        # that it should use that for init() etc.
 
3359
        result = remote.RemoteRepositoryFormat()
 
3360
        custom_format = getattr(self, '_repository_format', None)
 
3361
        if custom_format:
 
3362
            if isinstance(custom_format, remote.RemoteRepositoryFormat):
 
3363
                return custom_format
 
3364
            else:
 
3365
                # We will use the custom format to create repositories over the
 
3366
                # wire; expose its details like rich_root_data for code to
 
3367
                # query
 
3368
                result._custom_format = custom_format
 
3369
        return result
 
3370
 
 
3371
    def get_branch_format(self):
 
3372
        result = BzrDirMetaFormat1.get_branch_format(self)
 
3373
        if not isinstance(result, remote.RemoteBranchFormat):
 
3374
            new_result = remote.RemoteBranchFormat()
 
3375
            new_result._custom_format = result
 
3376
            # cache the result
 
3377
            self.set_branch_format(new_result)
 
3378
            result = new_result
 
3379
        return result
 
3380
 
 
3381
    repository_format = property(__return_repository_format,
 
3382
        BzrDirMetaFormat1._set_repository_format) #.im_func)
 
3383
 
 
3384
 
 
3385
BzrDirFormat.register_control_server_format(RemoteBzrDirFormat)
 
3386
 
 
3387
 
 
3388
class BzrDirFormatInfo(object):
 
3389
 
 
3390
    def __init__(self, native, deprecated, hidden, experimental):
 
3391
        self.deprecated = deprecated
 
3392
        self.native = native
 
3393
        self.hidden = hidden
 
3394
        self.experimental = experimental
 
3395
 
 
3396
 
 
3397
class BzrDirFormatRegistry(registry.Registry):
 
3398
    """Registry of user-selectable BzrDir subformats.
 
3399
 
 
3400
    Differs from BzrDirFormat._control_formats in that it provides sub-formats,
 
3401
    e.g. BzrDirMeta1 with weave repository.  Also, it's more user-oriented.
 
3402
    """
 
3403
 
 
3404
    def __init__(self):
 
3405
        """Create a BzrDirFormatRegistry."""
 
3406
        self._aliases = set()
 
3407
        self._registration_order = list()
 
3408
        super(BzrDirFormatRegistry, self).__init__()
 
3409
 
 
3410
    def aliases(self):
 
3411
        """Return a set of the format names which are aliases."""
 
3412
        return frozenset(self._aliases)
 
3413
 
 
3414
    def register_metadir(self, key,
 
3415
             repository_format, help, native=True, deprecated=False,
 
3416
             branch_format=None,
 
3417
             tree_format=None,
 
3418
             hidden=False,
 
3419
             experimental=False,
 
3420
             alias=False):
 
3421
        """Register a metadir subformat.
 
3422
 
 
3423
        These all use a BzrDirMetaFormat1 bzrdir, but can be parameterized
 
3424
        by the Repository/Branch/WorkingTreeformats.
 
3425
 
 
3426
        :param repository_format: The fully-qualified repository format class
 
3427
            name as a string.
 
3428
        :param branch_format: Fully-qualified branch format class name as
 
3429
            a string.
 
3430
        :param tree_format: Fully-qualified tree format class name as
 
3431
            a string.
 
3432
        """
 
3433
        # This should be expanded to support setting WorkingTree and Branch
 
3434
        # formats, once BzrDirMetaFormat1 supports that.
 
3435
        def _load(full_name):
 
3436
            mod_name, factory_name = full_name.rsplit('.', 1)
 
3437
            try:
 
3438
                mod = __import__(mod_name, globals(), locals(),
 
3439
                        [factory_name])
 
3440
            except ImportError, e:
 
3441
                raise ImportError('failed to load %s: %s' % (full_name, e))
 
3442
            try:
 
3443
                factory = getattr(mod, factory_name)
 
3444
            except AttributeError:
 
3445
                raise AttributeError('no factory %s in module %r'
 
3446
                    % (full_name, mod))
 
3447
            return factory()
 
3448
 
 
3449
        def helper():
 
3450
            bd = BzrDirMetaFormat1()
 
3451
            if branch_format is not None:
 
3452
                bd.set_branch_format(_load(branch_format))
 
3453
            if tree_format is not None:
 
3454
                bd.workingtree_format = _load(tree_format)
 
3455
            if repository_format is not None:
 
3456
                bd.repository_format = _load(repository_format)
 
3457
            return bd
 
3458
        self.register(key, helper, help, native, deprecated, hidden,
 
3459
            experimental, alias)
 
3460
 
 
3461
    def register(self, key, factory, help, native=True, deprecated=False,
 
3462
                 hidden=False, experimental=False, alias=False):
 
3463
        """Register a BzrDirFormat factory.
 
3464
 
 
3465
        The factory must be a callable that takes one parameter: the key.
 
3466
        It must produce an instance of the BzrDirFormat when called.
 
3467
 
 
3468
        This function mainly exists to prevent the info object from being
 
3469
        supplied directly.
 
3470
        """
 
3471
        registry.Registry.register(self, key, factory, help,
 
3472
            BzrDirFormatInfo(native, deprecated, hidden, experimental))
 
3473
        if alias:
 
3474
            self._aliases.add(key)
 
3475
        self._registration_order.append(key)
 
3476
 
 
3477
    def register_lazy(self, key, module_name, member_name, help, native=True,
 
3478
        deprecated=False, hidden=False, experimental=False, alias=False):
 
3479
        registry.Registry.register_lazy(self, key, module_name, member_name,
 
3480
            help, BzrDirFormatInfo(native, deprecated, hidden, experimental))
 
3481
        if alias:
 
3482
            self._aliases.add(key)
 
3483
        self._registration_order.append(key)
 
3484
 
 
3485
    def set_default(self, key):
 
3486
        """Set the 'default' key to be a clone of the supplied key.
 
3487
 
 
3488
        This method must be called once and only once.
 
3489
        """
 
3490
        registry.Registry.register(self, 'default', self.get(key),
 
3491
            self.get_help(key), info=self.get_info(key))
 
3492
        self._aliases.add('default')
 
3493
 
 
3494
    def set_default_repository(self, key):
 
3495
        """Set the FormatRegistry default and Repository default.
 
3496
 
 
3497
        This is a transitional method while Repository.set_default_format
 
3498
        is deprecated.
 
3499
        """
 
3500
        if 'default' in self:
 
3501
            self.remove('default')
 
3502
        self.set_default(key)
 
3503
        format = self.get('default')()
 
3504
 
 
3505
    def make_bzrdir(self, key):
 
3506
        return self.get(key)()
 
3507
 
 
3508
    def help_topic(self, topic):
 
3509
        output = ""
 
3510
        default_realkey = None
 
3511
        default_help = self.get_help('default')
 
3512
        help_pairs = []
 
3513
        for key in self._registration_order:
 
3514
            if key == 'default':
 
3515
                continue
 
3516
            help = self.get_help(key)
 
3517
            if help == default_help:
 
3518
                default_realkey = key
 
3519
            else:
 
3520
                help_pairs.append((key, help))
 
3521
 
 
3522
        def wrapped(key, help, info):
 
3523
            if info.native:
 
3524
                help = '(native) ' + help
 
3525
            return ':%s:\n%s\n\n' % (key,
 
3526
                textwrap.fill(help, initial_indent='    ',
 
3527
                    subsequent_indent='    ',
 
3528
                    break_long_words=False))
 
3529
        if default_realkey is not None:
 
3530
            output += wrapped(default_realkey, '(default) %s' % default_help,
 
3531
                              self.get_info('default'))
 
3532
        deprecated_pairs = []
 
3533
        experimental_pairs = []
 
3534
        for key, help in help_pairs:
 
3535
            info = self.get_info(key)
 
3536
            if info.hidden:
 
3537
                continue
 
3538
            elif info.deprecated:
 
3539
                deprecated_pairs.append((key, help))
 
3540
            elif info.experimental:
 
3541
                experimental_pairs.append((key, help))
 
3542
            else:
 
3543
                output += wrapped(key, help, info)
 
3544
        output += "\nSee :doc:`formats-help` for more about storage formats."
 
3545
        other_output = ""
 
3546
        if len(experimental_pairs) > 0:
 
3547
            other_output += "Experimental formats are shown below.\n\n"
 
3548
            for key, help in experimental_pairs:
 
3549
                info = self.get_info(key)
 
3550
                other_output += wrapped(key, help, info)
 
3551
        else:
 
3552
            other_output += \
 
3553
                "No experimental formats are available.\n\n"
 
3554
        if len(deprecated_pairs) > 0:
 
3555
            other_output += "\nDeprecated formats are shown below.\n\n"
 
3556
            for key, help in deprecated_pairs:
 
3557
                info = self.get_info(key)
 
3558
                other_output += wrapped(key, help, info)
 
3559
        else:
 
3560
            other_output += \
 
3561
                "\nNo deprecated formats are available.\n\n"
 
3562
        other_output += \
 
3563
                "\nSee :doc:`formats-help` for more about storage formats."
 
3564
 
 
3565
        if topic == 'other-formats':
 
3566
            return other_output
 
3567
        else:
 
3568
            return output
1913
3569
 
1914
3570
 
1915
3571
class RepositoryAcquisitionPolicy(object):
1944
3600
            try:
1945
3601
                stack_on = urlutils.rebase_url(self._stack_on,
1946
3602
                    self._stack_on_pwd,
1947
 
                    branch.user_url)
 
3603
                    branch.bzrdir.root_transport.base)
1948
3604
            except errors.InvalidRebaseURLs:
1949
3605
                stack_on = self._get_full_stack_on()
1950
3606
        try:
1996
3652
 
1997
3653
        Implementations may create a new repository or use a pre-exising
1998
3654
        repository.
1999
 
 
2000
3655
        :param make_working_trees: If creating a repository, set
2001
3656
            make_working_trees to this value (if non-None)
2002
3657
        :param shared: If creating a repository, make it shared if True
2011
3666
 
2012
3667
    def __init__(self, bzrdir, stack_on=None, stack_on_pwd=None,
2013
3668
                 require_stacking=False):
2014
 
        """Constructor.
2015
 
 
 
3669
        """
 
3670
        Constructor.
2016
3671
        :param bzrdir: The bzrdir to create the repository on.
2017
3672
        :param stack_on: A location to stack on
2018
3673
        :param stack_on_pwd: If stack_on is relative, the location it is
2034
3689
                                    possible_transports=[self._bzrdir.root_transport])
2035
3690
            if not self._require_stacking:
2036
3691
                # We have picked up automatic stacking somewhere.
2037
 
                note(gettext('Using default stacking branch {0} at {1}').format(
2038
 
                    self._stack_on, self._stack_on_pwd))
 
3692
                note('Using default stacking branch %s at %s', self._stack_on,
 
3693
                    self._stack_on_pwd)
2039
3694
        repository = self._bzrdir.create_repository(shared=shared)
2040
3695
        self._add_fallback(repository,
2041
3696
                           possible_transports=[self._bzrdir.transport])
2070
3725
        return self._repository, False
2071
3726
 
2072
3727
 
2073
 
def register_metadir(registry, key,
2074
 
         repository_format, help, native=True, deprecated=False,
2075
 
         branch_format=None,
2076
 
         tree_format=None,
2077
 
         hidden=False,
2078
 
         experimental=False,
2079
 
         alias=False):
2080
 
    """Register a metadir subformat.
2081
 
 
2082
 
    These all use a BzrDirMetaFormat1 bzrdir, but can be parameterized
2083
 
    by the Repository/Branch/WorkingTreeformats.
2084
 
 
2085
 
    :param repository_format: The fully-qualified repository format class
2086
 
        name as a string.
2087
 
    :param branch_format: Fully-qualified branch format class name as
2088
 
        a string.
2089
 
    :param tree_format: Fully-qualified tree format class name as
2090
 
        a string.
2091
 
    """
2092
 
    # This should be expanded to support setting WorkingTree and Branch
2093
 
    # formats, once BzrDirMetaFormat1 supports that.
2094
 
    def _load(full_name):
2095
 
        mod_name, factory_name = full_name.rsplit('.', 1)
2096
 
        try:
2097
 
            factory = pyutils.get_named_object(mod_name, factory_name)
2098
 
        except ImportError, e:
2099
 
            raise ImportError('failed to load %s: %s' % (full_name, e))
2100
 
        except AttributeError:
2101
 
            raise AttributeError('no factory %s in module %r'
2102
 
                % (full_name, sys.modules[mod_name]))
2103
 
        return factory()
2104
 
 
2105
 
    def helper():
2106
 
        bd = BzrDirMetaFormat1()
2107
 
        if branch_format is not None:
2108
 
            bd.set_branch_format(_load(branch_format))
2109
 
        if tree_format is not None:
2110
 
            bd.workingtree_format = _load(tree_format)
2111
 
        if repository_format is not None:
2112
 
            bd.repository_format = _load(repository_format)
2113
 
        return bd
2114
 
    registry.register(key, helper, help, native, deprecated, hidden,
2115
 
        experimental, alias)
2116
 
 
2117
 
register_metadir(controldir.format_registry, 'knit',
 
3728
# Please register new formats after old formats so that formats
 
3729
# appear in chronological order and format descriptions can build
 
3730
# on previous ones.
 
3731
format_registry = BzrDirFormatRegistry()
 
3732
# The pre-0.8 formats have their repository format network name registered in
 
3733
# repository.py. MetaDir formats have their repository format network name
 
3734
# inferred from their disk format string.
 
3735
format_registry.register('weave', BzrDirFormat6,
 
3736
    'Pre-0.8 format.  Slower than knit and does not'
 
3737
    ' support checkouts or shared repositories.',
 
3738
    hidden=True,
 
3739
    deprecated=True)
 
3740
format_registry.register_metadir('metaweave',
 
3741
    'bzrlib.repofmt.weaverepo.RepositoryFormat7',
 
3742
    'Transitional format in 0.8.  Slower than knit.',
 
3743
    branch_format='bzrlib.branch.BzrBranchFormat5',
 
3744
    tree_format='bzrlib.workingtree.WorkingTreeFormat3',
 
3745
    hidden=True,
 
3746
    deprecated=True)
 
3747
format_registry.register_metadir('knit',
2118
3748
    'bzrlib.repofmt.knitrepo.RepositoryFormatKnit1',
2119
3749
    'Format using knits.  Recommended for interoperation with bzr <= 0.14.',
2120
3750
    branch_format='bzrlib.branch.BzrBranchFormat5',
2121
 
    tree_format='bzrlib.workingtree_3.WorkingTreeFormat3',
 
3751
    tree_format='bzrlib.workingtree.WorkingTreeFormat3',
2122
3752
    hidden=True,
2123
3753
    deprecated=True)
2124
 
register_metadir(controldir.format_registry, 'dirstate',
 
3754
format_registry.register_metadir('dirstate',
2125
3755
    'bzrlib.repofmt.knitrepo.RepositoryFormatKnit1',
2126
3756
    help='New in 0.15: Fast local operations. Compatible with bzr 0.8 and '
2127
3757
        'above when accessed over the network.',
2128
3758
    branch_format='bzrlib.branch.BzrBranchFormat5',
2129
 
    tree_format='bzrlib.workingtree_4.WorkingTreeFormat4',
 
3759
    # this uses bzrlib.workingtree.WorkingTreeFormat4 because importing
 
3760
    # directly from workingtree_4 triggers a circular import.
 
3761
    tree_format='bzrlib.workingtree.WorkingTreeFormat4',
2130
3762
    hidden=True,
2131
3763
    deprecated=True)
2132
 
register_metadir(controldir.format_registry, 'dirstate-tags',
 
3764
format_registry.register_metadir('dirstate-tags',
2133
3765
    'bzrlib.repofmt.knitrepo.RepositoryFormatKnit1',
2134
3766
    help='New in 0.15: Fast local operations and improved scaling for '
2135
3767
        'network operations. Additionally adds support for tags.'
2136
3768
        ' Incompatible with bzr < 0.15.',
2137
3769
    branch_format='bzrlib.branch.BzrBranchFormat6',
2138
 
    tree_format='bzrlib.workingtree_4.WorkingTreeFormat4',
 
3770
    tree_format='bzrlib.workingtree.WorkingTreeFormat4',
2139
3771
    hidden=True,
2140
3772
    deprecated=True)
2141
 
register_metadir(controldir.format_registry, 'rich-root',
 
3773
format_registry.register_metadir('rich-root',
2142
3774
    'bzrlib.repofmt.knitrepo.RepositoryFormatKnit4',
2143
3775
    help='New in 1.0.  Better handling of tree roots.  Incompatible with'
2144
3776
        ' bzr < 1.0.',
2145
3777
    branch_format='bzrlib.branch.BzrBranchFormat6',
2146
 
    tree_format='bzrlib.workingtree_4.WorkingTreeFormat4',
 
3778
    tree_format='bzrlib.workingtree.WorkingTreeFormat4',
2147
3779
    hidden=True,
2148
3780
    deprecated=True)
2149
 
register_metadir(controldir.format_registry, 'dirstate-with-subtree',
 
3781
format_registry.register_metadir('dirstate-with-subtree',
2150
3782
    'bzrlib.repofmt.knitrepo.RepositoryFormatKnit3',
2151
3783
    help='New in 0.15: Fast local operations and improved scaling for '
2152
3784
        'network operations. Additionally adds support for versioning nested '
2153
3785
        'bzr branches. Incompatible with bzr < 0.15.',
2154
3786
    branch_format='bzrlib.branch.BzrBranchFormat6',
2155
 
    tree_format='bzrlib.workingtree_4.WorkingTreeFormat4',
 
3787
    tree_format='bzrlib.workingtree.WorkingTreeFormat4',
2156
3788
    experimental=True,
2157
3789
    hidden=True,
2158
3790
    )
2159
 
register_metadir(controldir.format_registry, 'pack-0.92',
2160
 
    'bzrlib.repofmt.knitpack_repo.RepositoryFormatKnitPack1',
 
3791
format_registry.register_metadir('pack-0.92',
 
3792
    'bzrlib.repofmt.pack_repo.RepositoryFormatKnitPack1',
2161
3793
    help='New in 0.92: Pack-based format with data compatible with '
2162
3794
        'dirstate-tags format repositories. Interoperates with '
2163
3795
        'bzr repositories before 0.92 but cannot be read by bzr < 0.92. '
2164
3796
        ,
2165
3797
    branch_format='bzrlib.branch.BzrBranchFormat6',
2166
 
    tree_format='bzrlib.workingtree_4.WorkingTreeFormat4',
 
3798
    tree_format='bzrlib.workingtree.WorkingTreeFormat4',
2167
3799
    )
2168
 
register_metadir(controldir.format_registry, 'pack-0.92-subtree',
2169
 
    'bzrlib.repofmt.knitpack_repo.RepositoryFormatKnitPack3',
 
3800
format_registry.register_metadir('pack-0.92-subtree',
 
3801
    'bzrlib.repofmt.pack_repo.RepositoryFormatKnitPack3',
2170
3802
    help='New in 0.92: Pack-based format with data compatible with '
2171
3803
        'dirstate-with-subtree format repositories. Interoperates with '
2172
3804
        'bzr repositories before 0.92 but cannot be read by bzr < 0.92. '
2173
3805
        ,
2174
3806
    branch_format='bzrlib.branch.BzrBranchFormat6',
2175
 
    tree_format='bzrlib.workingtree_4.WorkingTreeFormat4',
 
3807
    tree_format='bzrlib.workingtree.WorkingTreeFormat4',
2176
3808
    hidden=True,
2177
3809
    experimental=True,
2178
3810
    )
2179
 
register_metadir(controldir.format_registry, 'rich-root-pack',
2180
 
    'bzrlib.repofmt.knitpack_repo.RepositoryFormatKnitPack4',
 
3811
format_registry.register_metadir('rich-root-pack',
 
3812
    'bzrlib.repofmt.pack_repo.RepositoryFormatKnitPack4',
2181
3813
    help='New in 1.0: A variant of pack-0.92 that supports rich-root data '
2182
3814
         '(needed for bzr-svn and bzr-git).',
2183
3815
    branch_format='bzrlib.branch.BzrBranchFormat6',
2184
 
    tree_format='bzrlib.workingtree_4.WorkingTreeFormat4',
 
3816
    tree_format='bzrlib.workingtree.WorkingTreeFormat4',
2185
3817
    hidden=True,
2186
3818
    )
2187
 
register_metadir(controldir.format_registry, '1.6',
2188
 
    'bzrlib.repofmt.knitpack_repo.RepositoryFormatKnitPack5',
 
3819
format_registry.register_metadir('1.6',
 
3820
    'bzrlib.repofmt.pack_repo.RepositoryFormatKnitPack5',
2189
3821
    help='A format that allows a branch to indicate that there is another '
2190
3822
         '(stacked) repository that should be used to access data that is '
2191
3823
         'not present locally.',
2192
3824
    branch_format='bzrlib.branch.BzrBranchFormat7',
2193
 
    tree_format='bzrlib.workingtree_4.WorkingTreeFormat4',
 
3825
    tree_format='bzrlib.workingtree.WorkingTreeFormat4',
2194
3826
    hidden=True,
2195
3827
    )
2196
 
register_metadir(controldir.format_registry, '1.6.1-rich-root',
2197
 
    'bzrlib.repofmt.knitpack_repo.RepositoryFormatKnitPack5RichRoot',
 
3828
format_registry.register_metadir('1.6.1-rich-root',
 
3829
    'bzrlib.repofmt.pack_repo.RepositoryFormatKnitPack5RichRoot',
2198
3830
    help='A variant of 1.6 that supports rich-root data '
2199
3831
         '(needed for bzr-svn and bzr-git).',
2200
3832
    branch_format='bzrlib.branch.BzrBranchFormat7',
2201
 
    tree_format='bzrlib.workingtree_4.WorkingTreeFormat4',
 
3833
    tree_format='bzrlib.workingtree.WorkingTreeFormat4',
2202
3834
    hidden=True,
2203
3835
    )
2204
 
register_metadir(controldir.format_registry, '1.9',
2205
 
    'bzrlib.repofmt.knitpack_repo.RepositoryFormatKnitPack6',
 
3836
format_registry.register_metadir('1.9',
 
3837
    'bzrlib.repofmt.pack_repo.RepositoryFormatKnitPack6',
2206
3838
    help='A repository format using B+tree indexes. These indexes '
2207
3839
         'are smaller in size, have smarter caching and provide faster '
2208
3840
         'performance for most operations.',
2209
3841
    branch_format='bzrlib.branch.BzrBranchFormat7',
2210
 
    tree_format='bzrlib.workingtree_4.WorkingTreeFormat4',
 
3842
    tree_format='bzrlib.workingtree.WorkingTreeFormat4',
2211
3843
    hidden=True,
2212
3844
    )
2213
 
register_metadir(controldir.format_registry, '1.9-rich-root',
2214
 
    'bzrlib.repofmt.knitpack_repo.RepositoryFormatKnitPack6RichRoot',
 
3845
format_registry.register_metadir('1.9-rich-root',
 
3846
    'bzrlib.repofmt.pack_repo.RepositoryFormatKnitPack6RichRoot',
2215
3847
    help='A variant of 1.9 that supports rich-root data '
2216
3848
         '(needed for bzr-svn and bzr-git).',
2217
3849
    branch_format='bzrlib.branch.BzrBranchFormat7',
2218
 
    tree_format='bzrlib.workingtree_4.WorkingTreeFormat4',
 
3850
    tree_format='bzrlib.workingtree.WorkingTreeFormat4',
2219
3851
    hidden=True,
2220
3852
    )
2221
 
register_metadir(controldir.format_registry, '1.14',
2222
 
    'bzrlib.repofmt.knitpack_repo.RepositoryFormatKnitPack6',
 
3853
format_registry.register_metadir('1.14',
 
3854
    'bzrlib.repofmt.pack_repo.RepositoryFormatKnitPack6',
2223
3855
    help='A working-tree format that supports content filtering.',
2224
3856
    branch_format='bzrlib.branch.BzrBranchFormat7',
2225
 
    tree_format='bzrlib.workingtree_4.WorkingTreeFormat5',
 
3857
    tree_format='bzrlib.workingtree.WorkingTreeFormat5',
2226
3858
    )
2227
 
register_metadir(controldir.format_registry, '1.14-rich-root',
2228
 
    'bzrlib.repofmt.knitpack_repo.RepositoryFormatKnitPack6RichRoot',
 
3859
format_registry.register_metadir('1.14-rich-root',
 
3860
    'bzrlib.repofmt.pack_repo.RepositoryFormatKnitPack6RichRoot',
2229
3861
    help='A variant of 1.14 that supports rich-root data '
2230
3862
         '(needed for bzr-svn and bzr-git).',
2231
3863
    branch_format='bzrlib.branch.BzrBranchFormat7',
2232
 
    tree_format='bzrlib.workingtree_4.WorkingTreeFormat5',
 
3864
    tree_format='bzrlib.workingtree.WorkingTreeFormat5',
2233
3865
    )
2234
3866
# The following un-numbered 'development' formats should always just be aliases.
2235
 
register_metadir(controldir.format_registry, 'development-subtree',
2236
 
    'bzrlib.repofmt.groupcompress_repo.RepositoryFormat2aSubtree',
 
3867
format_registry.register_metadir('development-rich-root',
 
3868
    'bzrlib.repofmt.groupcompress_repo.RepositoryFormatCHK1',
 
3869
    help='Current development format. Supports rich roots. Can convert data '
 
3870
        'to and from rich-root-pack (and anything compatible with '
 
3871
        'rich-root-pack) format repositories. Repositories and branches in '
 
3872
        'this format can only be read by bzr.dev. Please read '
 
3873
        'http://doc.bazaar.canonical.com/latest/developers/development-repo.html '
 
3874
        'before use.',
 
3875
    branch_format='bzrlib.branch.BzrBranchFormat7',
 
3876
    tree_format='bzrlib.workingtree.WorkingTreeFormat6',
 
3877
    experimental=True,
 
3878
    alias=True,
 
3879
    hidden=True,
 
3880
    )
 
3881
format_registry.register_metadir('development-subtree',
 
3882
    'bzrlib.repofmt.pack_repo.RepositoryFormatPackDevelopment2Subtree',
2237
3883
    help='Current development format, subtree variant. Can convert data to and '
2238
3884
        'from pack-0.92-subtree (and anything compatible with '
2239
3885
        'pack-0.92-subtree) format repositories. Repositories and branches in '
2241
3887
        'http://doc.bazaar.canonical.com/latest/developers/development-repo.html '
2242
3888
        'before use.',
2243
3889
    branch_format='bzrlib.branch.BzrBranchFormat7',
2244
 
    tree_format='bzrlib.workingtree_4.WorkingTreeFormat6',
 
3890
    tree_format='bzrlib.workingtree.WorkingTreeFormat6',
2245
3891
    experimental=True,
2246
3892
    hidden=True,
2247
3893
    alias=False, # Restore to being an alias when an actual development subtree format is added
2248
3894
                 # This current non-alias status is simply because we did not introduce a
2249
3895
                 # chk based subtree format.
2250
3896
    )
2251
 
register_metadir(controldir.format_registry, 'development5-subtree',
2252
 
    'bzrlib.repofmt.knitpack_repo.RepositoryFormatPackDevelopment2Subtree',
2253
 
    help='Development format, subtree variant. Can convert data to and '
2254
 
        'from pack-0.92-subtree (and anything compatible with '
2255
 
        'pack-0.92-subtree) format repositories. Repositories and branches in '
2256
 
        'this format can only be read by bzr.dev. Please read '
2257
 
        'http://doc.bazaar.canonical.com/latest/developers/development-repo.html '
2258
 
        'before use.',
2259
 
    branch_format='bzrlib.branch.BzrBranchFormat7',
2260
 
    tree_format='bzrlib.workingtree_4.WorkingTreeFormat6',
2261
 
    experimental=True,
2262
 
    hidden=True,
2263
 
    alias=False,
2264
 
    )
2265
3897
 
2266
3898
# And the development formats above will have aliased one of the following:
2267
 
 
2268
 
# Finally, the current format.
2269
 
register_metadir(controldir.format_registry, '2a',
 
3899
format_registry.register_metadir('development6-rich-root',
 
3900
    'bzrlib.repofmt.groupcompress_repo.RepositoryFormatCHK1',
 
3901
    help='pack-1.9 with 255-way hashed CHK inv, group compress, rich roots '
 
3902
        'Please read '
 
3903
        'http://doc.bazaar.canonical.com/latest/developers/development-repo.html '
 
3904
        'before use.',
 
3905
    branch_format='bzrlib.branch.BzrBranchFormat7',
 
3906
    tree_format='bzrlib.workingtree.WorkingTreeFormat6',
 
3907
    hidden=True,
 
3908
    experimental=True,
 
3909
    )
 
3910
 
 
3911
format_registry.register_metadir('development7-rich-root',
 
3912
    'bzrlib.repofmt.groupcompress_repo.RepositoryFormatCHK2',
 
3913
    help='pack-1.9 with 255-way hashed CHK inv, bencode revision, group compress, '
 
3914
        'rich roots. Please read '
 
3915
        'http://doc.bazaar.canonical.com/latest/developers/development-repo.html '
 
3916
        'before use.',
 
3917
    branch_format='bzrlib.branch.BzrBranchFormat7',
 
3918
    tree_format='bzrlib.workingtree.WorkingTreeFormat6',
 
3919
    hidden=True,
 
3920
    experimental=True,
 
3921
    )
 
3922
 
 
3923
format_registry.register_metadir('2a',
2270
3924
    'bzrlib.repofmt.groupcompress_repo.RepositoryFormat2a',
2271
3925
    help='First format for bzr 2.0 series.\n'
2272
3926
        'Uses group-compress storage.\n'
2274
3928
        # 'storage in packs, 255-way hashed CHK inventory, bencode revision, group compress, '
2275
3929
        # 'rich roots. Supported by bzr 1.16 and later.',
2276
3930
    branch_format='bzrlib.branch.BzrBranchFormat7',
2277
 
    tree_format='bzrlib.workingtree_4.WorkingTreeFormat6',
2278
 
    experimental=False,
 
3931
    tree_format='bzrlib.workingtree.WorkingTreeFormat6',
 
3932
    experimental=True,
2279
3933
    )
2280
3934
 
2281
3935
# The following format should be an alias for the rich root equivalent 
2282
3936
# of the default format
2283
 
register_metadir(controldir.format_registry, 'default-rich-root',
 
3937
format_registry.register_metadir('default-rich-root',
2284
3938
    'bzrlib.repofmt.groupcompress_repo.RepositoryFormat2a',
2285
3939
    branch_format='bzrlib.branch.BzrBranchFormat7',
2286
 
    tree_format='bzrlib.workingtree_4.WorkingTreeFormat6',
 
3940
    tree_format='bzrlib.workingtree.WorkingTreeFormat6',
2287
3941
    alias=True,
2288
3942
    hidden=True,
2289
3943
    help='Same as 2a.')
2290
3944
 
2291
3945
# The current format that is made on 'bzr init'.
2292
 
format_name = config.GlobalStack().get('default_format')
2293
 
controldir.format_registry.set_default(format_name)
2294
 
 
2295
 
# XXX 2010-08-20 JRV: There is still a lot of code relying on
2296
 
# bzrlib.bzrdir.format_registry existing. When BzrDir.create/BzrDir.open/etc
2297
 
# get changed to ControlDir.create/ControlDir.open/etc this should be removed.
2298
 
format_registry = controldir.format_registry
 
3946
format_registry.set_default('2a')