~bzr-pqm/bzr/bzr.dev

« back to all changes in this revision

Viewing changes to bzrlib/bzrdir.py

  • Committer: Jelmer Vernooij
  • Date: 2009-04-10 15:58:09 UTC
  • mto: This revision was merged to the branch mainline in revision 4284.
  • Revision ID: jelmer@samba.org-20090410155809-kdibzcjvp7pdb83f
Fix missing import.

Show diffs side-by-side

added added

removed removed

Lines of Context:
1
 
# Copyright (C) 2006-2011 Canonical Ltd
 
1
# Copyright (C) 2005, 2006, 2007, 2008, 2009 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
29
32
 
30
33
from bzrlib.lazy_import import lazy_import
31
34
lazy_import(globals(), """
 
35
from stat import S_ISDIR
 
36
import textwrap
 
37
 
32
38
import bzrlib
33
39
from bzrlib import (
34
 
    branch as _mod_branch,
35
 
    cleanup,
 
40
    config,
36
41
    errors,
37
 
    fetch,
38
42
    graph,
39
43
    lockable_files,
40
44
    lockdir,
41
45
    osutils,
42
 
    pyutils,
43
46
    remote,
44
 
    repository,
45
47
    revision as _mod_revision,
46
 
    transport as _mod_transport,
47
48
    ui,
48
49
    urlutils,
 
50
    versionedfile,
49
51
    win32utils,
50
 
    workingtree_3,
 
52
    workingtree,
51
53
    workingtree_4,
52
 
    )
53
 
from bzrlib.repofmt import knitpack_repo
 
54
    xml4,
 
55
    xml5,
 
56
    )
 
57
from bzrlib.osutils import (
 
58
    sha_string,
 
59
    )
 
60
from bzrlib.push import (
 
61
    PushResult,
 
62
    )
 
63
from bzrlib.smart.client import _SmartClient
 
64
from bzrlib.store.versioned import WeaveStore
 
65
from bzrlib.transactions import WriteTransaction
54
66
from bzrlib.transport import (
55
67
    do_catching_redirections,
 
68
    get_transport,
56
69
    local,
 
70
    remote as remote_transport,
57
71
    )
 
72
from bzrlib.weave import Weave
58
73
""")
59
74
 
60
75
from bzrlib.trace import (
63
78
    )
64
79
 
65
80
from bzrlib import (
66
 
    config,
67
 
    controldir,
68
81
    hooks,
69
82
    registry,
70
 
    )
71
 
from bzrlib.symbol_versioning import (
72
 
    deprecated_in,
73
 
    deprecated_method,
74
 
    )
75
 
 
76
 
 
77
 
class BzrDir(controldir.ControlDir):
 
83
    symbol_versioning,
 
84
    )
 
85
 
 
86
 
 
87
class BzrDir(object):
78
88
    """A .bzr control diretory.
79
89
 
80
90
    BzrDir instances let you create or open any of the things that can be
111
121
                    return
112
122
        thing_to_unlock.break_lock()
113
123
 
 
124
    def can_convert_format(self):
 
125
        """Return true if this bzrdir is one whose format we can convert from."""
 
126
        return True
 
127
 
114
128
    def check_conversion_target(self, target_format):
115
 
        """Check that a bzrdir as a whole can be converted to a new format."""
116
 
        # The only current restriction is that the repository content can be 
117
 
        # fetched compatibly with the target.
118
129
        target_repo_format = target_format.repository_format
119
 
        try:
120
 
            self.open_repository()._format.check_conversion_target(
121
 
                target_repo_format)
122
 
        except errors.NoRepositoryPresent:
123
 
            # No repo, no problem.
124
 
            pass
 
130
        source_repo_format = self._format.repository_format
 
131
        source_repo_format.check_conversion_target(target_repo_format)
 
132
 
 
133
    @staticmethod
 
134
    def _check_supported(format, allow_unsupported,
 
135
        recommend_upgrade=True,
 
136
        basedir=None):
 
137
        """Give an error or warning on old formats.
 
138
 
 
139
        :param format: may be any kind of format - workingtree, branch,
 
140
        or repository.
 
141
 
 
142
        :param allow_unsupported: If true, allow opening
 
143
        formats that are strongly deprecated, and which may
 
144
        have limited functionality.
 
145
 
 
146
        :param recommend_upgrade: If true (default), warn
 
147
        the user through the ui object that they may wish
 
148
        to upgrade the object.
 
149
        """
 
150
        # TODO: perhaps move this into a base Format class; it's not BzrDir
 
151
        # specific. mbp 20070323
 
152
        if not allow_unsupported and not format.is_supported():
 
153
            # see open_downlevel to open legacy branches.
 
154
            raise errors.UnsupportedFormatError(format=format)
 
155
        if recommend_upgrade \
 
156
            and getattr(format, 'upgrade_recommended', False):
 
157
            ui.ui_factory.recommend_upgrade(
 
158
                format.get_format_description(),
 
159
                basedir)
 
160
 
 
161
    def clone(self, url, revision_id=None, force_new_repo=False,
 
162
              preserve_stacking=False):
 
163
        """Clone this bzrdir and its contents to url verbatim.
 
164
 
 
165
        :param url: The url create the clone at.  If url's last component does
 
166
            not exist, it will be created.
 
167
        :param revision_id: The tip revision-id to use for any branch or
 
168
            working tree.  If not None, then the clone operation may tune
 
169
            itself to download less data.
 
170
        :param force_new_repo: Do not use a shared repository for the target
 
171
                               even if one is available.
 
172
        :param preserve_stacking: When cloning a stacked branch, stack the
 
173
            new branch on top of the other branch's stacked-on branch.
 
174
        """
 
175
        return self.clone_on_transport(get_transport(url),
 
176
                                       revision_id=revision_id,
 
177
                                       force_new_repo=force_new_repo,
 
178
                                       preserve_stacking=preserve_stacking)
125
179
 
126
180
    def clone_on_transport(self, transport, revision_id=None,
127
 
        force_new_repo=False, preserve_stacking=False, stacked_on=None,
128
 
        create_prefix=False, use_existing_dir=True, no_tree=False):
 
181
                           force_new_repo=False, preserve_stacking=False,
 
182
                           stacked_on=None):
129
183
        """Clone this bzrdir and its contents to transport verbatim.
130
184
 
131
185
        :param transport: The transport for the location to produce the clone
137
191
                               even if one is available.
138
192
        :param preserve_stacking: When cloning a stacked branch, stack the
139
193
            new branch on top of the other branch's stacked-on branch.
140
 
        :param create_prefix: Create any missing directories leading up to
141
 
            to_transport.
142
 
        :param use_existing_dir: Use an existing directory if one exists.
143
 
        :param no_tree: If set to true prevents creation of a working tree.
144
194
        """
145
 
        # Overview: put together a broad description of what we want to end up
146
 
        # with; then make as few api calls as possible to do it.
147
 
 
148
 
        # We may want to create a repo/branch/tree, if we do so what format
149
 
        # would we want for each:
 
195
        transport.ensure_base()
150
196
        require_stacking = (stacked_on is not None)
151
197
        format = self.cloning_metadir(require_stacking)
152
 
 
153
 
        # Figure out what objects we want:
 
198
        # Bug: We create a metadir without knowing if it can support stacking,
 
199
        # we should look up the policy needs first.
 
200
        result = format.initialize_on_transport(transport)
 
201
        repository_policy = None
154
202
        try:
155
203
            local_repo = self.find_repository()
156
204
        except errors.NoRepositoryPresent:
170
218
                        errors.UnstackableRepositoryFormat,
171
219
                        errors.NotStacked):
172
220
                    pass
173
 
        # Bug: We create a metadir without knowing if it can support stacking,
174
 
        # we should look up the policy needs first, or just use it as a hint,
175
 
        # or something.
 
221
 
176
222
        if local_repo:
177
 
            make_working_trees = local_repo.make_working_trees() and not no_tree
178
 
            want_shared = local_repo.is_shared()
179
 
            repo_format_name = format.repository_format.network_name()
180
 
        else:
181
 
            make_working_trees = False
182
 
            want_shared = False
183
 
            repo_format_name = None
184
 
 
185
 
        result_repo, result, require_stacking, repository_policy = \
186
 
            format.initialize_on_transport_ex(transport,
187
 
            use_existing_dir=use_existing_dir, create_prefix=create_prefix,
188
 
            force_new_repo=force_new_repo, stacked_on=stacked_on,
189
 
            stack_on_pwd=self.root_transport.base,
190
 
            repo_format_name=repo_format_name,
191
 
            make_working_trees=make_working_trees, shared_repo=want_shared)
192
 
        if repo_format_name:
193
 
            try:
194
 
                # If the result repository is in the same place as the
195
 
                # resulting bzr dir, it will have no content, further if the
196
 
                # result is not stacked then we know all content should be
197
 
                # copied, and finally if we are copying up to a specific
198
 
                # revision_id then we can use the pending-ancestry-result which
199
 
                # does not require traversing all of history to describe it.
200
 
                if (result_repo.user_url == result.user_url
201
 
                    and not require_stacking and
202
 
                    revision_id is not None):
203
 
                    fetch_spec = graph.PendingAncestryResult(
204
 
                        [revision_id], local_repo)
205
 
                    result_repo.fetch(local_repo, fetch_spec=fetch_spec)
206
 
                else:
207
 
                    result_repo.fetch(local_repo, revision_id=revision_id)
208
 
            finally:
209
 
                result_repo.unlock()
210
 
        else:
211
 
            if result_repo is not None:
212
 
                raise AssertionError('result_repo not None(%r)' % result_repo)
 
223
            # may need to copy content in
 
224
            repository_policy = result.determine_repository_policy(
 
225
                force_new_repo, stacked_on, self.root_transport.base,
 
226
                require_stacking=require_stacking)
 
227
            make_working_trees = local_repo.make_working_trees()
 
228
            result_repo, is_new_repo = repository_policy.acquire_repository(
 
229
                make_working_trees, local_repo.is_shared())
 
230
            if not require_stacking and repository_policy._require_stacking:
 
231
                require_stacking = True
 
232
                result._format.require_stacking()
 
233
            if is_new_repo and not require_stacking and revision_id is not None:
 
234
                fetch_spec = graph.PendingAncestryResult(
 
235
                    [revision_id], local_repo)
 
236
                result_repo.fetch(local_repo, fetch_spec=fetch_spec)
 
237
            else:
 
238
                result_repo.fetch(local_repo, revision_id=revision_id)
 
239
        else:
 
240
            result_repo = None
213
241
        # 1 if there is a branch present
214
242
        #   make sure its content is available in the target repository
215
243
        #   clone it.
229
257
    # TODO: This should be given a Transport, and should chdir up; otherwise
230
258
    # this will open a new connection.
231
259
    def _make_tail(self, url):
232
 
        t = _mod_transport.get_transport(url)
233
 
        t.ensure_base()
 
260
        t = get_transport(url)
 
261
        t.ensure_base()
 
262
 
 
263
    @classmethod
 
264
    def create(cls, base, format=None, possible_transports=None):
 
265
        """Create a new BzrDir at the url 'base'.
 
266
 
 
267
        :param format: If supplied, the format of branch to create.  If not
 
268
            supplied, the default is used.
 
269
        :param possible_transports: If supplied, a list of transports that
 
270
            can be reused to share a remote connection.
 
271
        """
 
272
        if cls is not BzrDir:
 
273
            raise AssertionError("BzrDir.create always creates the default"
 
274
                " format, not one of %r" % cls)
 
275
        t = get_transport(base, possible_transports)
 
276
        t.ensure_base()
 
277
        if format is None:
 
278
            format = BzrDirFormat.get_default_format()
 
279
        return format.initialize_on_transport(t)
234
280
 
235
281
    @staticmethod
236
282
    def find_bzrdirs(transport, evaluate=None, list_current=None):
239
285
        This is intended primarily as a building block for more sophisticated
240
286
        functionality, like finding trees under a directory, or finding
241
287
        branches that use a given repository.
242
 
 
243
288
        :param evaluate: An optional callable that yields recurse, value,
244
289
            where recurse controls whether this bzrdir is recursed into
245
290
            and value is the value to yield.  By default, all bzrdirs
261
306
            recurse = True
262
307
            try:
263
308
                bzrdir = BzrDir.open_from_transport(current_transport)
264
 
            except (errors.NotBranchError, errors.PermissionDenied):
 
309
            except errors.NotBranchError:
265
310
                pass
266
311
            else:
267
312
                recurse, value = evaluate(bzrdir)
268
313
                yield value
269
314
            try:
270
315
                subdirs = list_current(current_transport)
271
 
            except (errors.NoSuchFile, errors.PermissionDenied):
 
316
            except errors.NoSuchFile:
272
317
                continue
273
318
            if recurse:
274
319
                for subdir in sorted(subdirs, reverse=True):
291
336
            except errors.NoRepositoryPresent:
292
337
                pass
293
338
            else:
294
 
                return False, ([], repository)
295
 
            return True, (bzrdir.list_branches(), None)
296
 
        ret = []
297
 
        for branches, repo in BzrDir.find_bzrdirs(transport,
298
 
                                                  evaluate=evaluate):
 
339
                return False, (None, repository)
 
340
            try:
 
341
                branch = bzrdir.open_branch()
 
342
            except errors.NotBranchError:
 
343
                return True, (None, None)
 
344
            else:
 
345
                return True, (branch, None)
 
346
        branches = []
 
347
        for branch, repo in BzrDir.find_bzrdirs(transport, evaluate=evaluate):
299
348
            if repo is not None:
300
 
                ret.extend(repo.find_branches())
301
 
            if branches is not None:
302
 
                ret.extend(branches)
303
 
        return ret
 
349
                branches.extend(repo.find_branches())
 
350
            if branch is not None:
 
351
                branches.append(branch)
 
352
        return branches
 
353
 
 
354
    def destroy_repository(self):
 
355
        """Destroy the repository in this BzrDir"""
 
356
        raise NotImplementedError(self.destroy_repository)
 
357
 
 
358
    def create_branch(self):
 
359
        """Create a branch in this BzrDir.
 
360
 
 
361
        The bzrdir's format will control what branch format is created.
 
362
        For more control see BranchFormatXX.create(a_bzrdir).
 
363
        """
 
364
        raise NotImplementedError(self.create_branch)
 
365
 
 
366
    def destroy_branch(self):
 
367
        """Destroy the branch in this BzrDir"""
 
368
        raise NotImplementedError(self.destroy_branch)
304
369
 
305
370
    @staticmethod
306
371
    def create_branch_and_repo(base, force_new_repo=False, format=None):
343
408
            stack_on_pwd = None
344
409
            config = found_bzrdir.get_config()
345
410
            stop = False
346
 
            stack_on = config.get_default_stack_on()
347
 
            if stack_on is not None:
348
 
                stack_on_pwd = found_bzrdir.user_url
349
 
                stop = True
 
411
            if config is not None:
 
412
                stack_on = config.get_default_stack_on()
 
413
                if stack_on is not None:
 
414
                    stack_on_pwd = found_bzrdir.root_transport.base
 
415
                    stop = True
350
416
            # does it have a repository ?
351
417
            try:
352
418
                repository = found_bzrdir.open_repository()
353
419
            except errors.NoRepositoryPresent:
354
420
                repository = None
355
421
            else:
356
 
                if (found_bzrdir.user_url != self.user_url 
357
 
                    and not repository.is_shared()):
 
422
                if ((found_bzrdir.root_transport.base !=
 
423
                     self.root_transport.base) and not repository.is_shared()):
358
424
                    # Don't look higher, can't use a higher shared repo.
359
425
                    repository = None
360
426
                    stop = True
389
455
        policy = self.determine_repository_policy(force_new_repo)
390
456
        return policy.acquire_repository()[0]
391
457
 
392
 
    def _find_source_repo(self, add_cleanup, source_branch):
393
 
        """Find the source branch and repo for a sprout operation.
394
 
        
395
 
        This is helper intended for use by _sprout.
396
 
 
397
 
        :returns: (source_branch, source_repository).  Either or both may be
398
 
            None.  If not None, they will be read-locked (and their unlock(s)
399
 
            scheduled via the add_cleanup param).
400
 
        """
401
 
        if source_branch is not None:
402
 
            add_cleanup(source_branch.lock_read().unlock)
403
 
            return source_branch, source_branch.repository
404
 
        try:
405
 
            source_branch = self.open_branch()
406
 
            source_repository = source_branch.repository
407
 
        except errors.NotBranchError:
408
 
            source_branch = None
409
 
            try:
410
 
                source_repository = self.open_repository()
411
 
            except errors.NoRepositoryPresent:
412
 
                source_repository = None
413
 
            else:
414
 
                add_cleanup(source_repository.lock_read().unlock)
415
 
        else:
416
 
            add_cleanup(source_branch.lock_read().unlock)
417
 
        return source_branch, source_repository
418
 
 
419
 
    def sprout(self, url, revision_id=None, force_new_repo=False,
420
 
               recurse='down', possible_transports=None,
421
 
               accelerator_tree=None, hardlink=False, stacked=False,
422
 
               source_branch=None, create_tree_if_local=True):
423
 
        """Create a copy of this controldir prepared for use as a new line of
424
 
        development.
425
 
 
426
 
        If url's last component does not exist, it will be created.
427
 
 
428
 
        Attributes related to the identity of the source branch like
429
 
        branch nickname will be cleaned, a working tree is created
430
 
        whether one existed before or not; and a local branch is always
431
 
        created.
432
 
 
433
 
        if revision_id is not None, then the clone operation may tune
434
 
            itself to download less data.
435
 
 
436
 
        :param accelerator_tree: A tree which can be used for retrieving file
437
 
            contents more quickly than the revision tree, i.e. a workingtree.
438
 
            The revision tree will be used for cases where accelerator_tree's
439
 
            content is different.
440
 
        :param hardlink: If true, hard-link files from accelerator_tree,
441
 
            where possible.
442
 
        :param stacked: If true, create a stacked branch referring to the
443
 
            location of this control directory.
444
 
        :param create_tree_if_local: If true, a working-tree will be created
445
 
            when working locally.
446
 
        """
447
 
        operation = cleanup.OperationWithCleanups(self._sprout)
448
 
        return operation.run(url, revision_id=revision_id,
449
 
            force_new_repo=force_new_repo, recurse=recurse,
450
 
            possible_transports=possible_transports,
451
 
            accelerator_tree=accelerator_tree, hardlink=hardlink,
452
 
            stacked=stacked, source_branch=source_branch,
453
 
            create_tree_if_local=create_tree_if_local)
454
 
 
455
 
    def _sprout(self, op, url, revision_id=None, force_new_repo=False,
456
 
               recurse='down', possible_transports=None,
457
 
               accelerator_tree=None, hardlink=False, stacked=False,
458
 
               source_branch=None, create_tree_if_local=True):
459
 
        add_cleanup = op.add_cleanup
460
 
        fetch_spec_factory = fetch.FetchSpecFactory()
461
 
        if revision_id is not None:
462
 
            fetch_spec_factory.add_revision_ids([revision_id])
463
 
            fetch_spec_factory.source_branch_stop_revision_id = revision_id
464
 
        target_transport = _mod_transport.get_transport(url,
465
 
            possible_transports)
466
 
        target_transport.ensure_base()
467
 
        cloning_format = self.cloning_metadir(stacked)
468
 
        # Create/update the result branch
469
 
        result = cloning_format.initialize_on_transport(target_transport)
470
 
        source_branch, source_repository = self._find_source_repo(
471
 
            add_cleanup, source_branch)
472
 
        fetch_spec_factory.source_branch = source_branch
473
 
        # if a stacked branch wasn't requested, we don't create one
474
 
        # even if the origin was stacked
475
 
        if stacked and source_branch is not None:
476
 
            stacked_branch_url = self.root_transport.base
477
 
        else:
478
 
            stacked_branch_url = None
479
 
        repository_policy = result.determine_repository_policy(
480
 
            force_new_repo, stacked_branch_url, require_stacking=stacked)
481
 
        result_repo, is_new_repo = repository_policy.acquire_repository()
482
 
        add_cleanup(result_repo.lock_write().unlock)
483
 
        fetch_spec_factory.source_repo = source_repository
484
 
        fetch_spec_factory.target_repo = result_repo
485
 
        if stacked or (len(result_repo._fallback_repositories) != 0):
486
 
            target_repo_kind = fetch.TargetRepoKinds.STACKED
487
 
        elif is_new_repo:
488
 
            target_repo_kind = fetch.TargetRepoKinds.EMPTY
489
 
        else:
490
 
            target_repo_kind = fetch.TargetRepoKinds.PREEXISTING
491
 
        fetch_spec_factory.target_repo_kind = target_repo_kind
492
 
        if source_repository is not None:
493
 
            fetch_spec = fetch_spec_factory.make_fetch_spec()
494
 
            result_repo.fetch(source_repository, fetch_spec=fetch_spec)
495
 
 
496
 
        if source_branch is None:
497
 
            # this is for sprouting a controldir without a branch; is that
498
 
            # actually useful?
499
 
            # Not especially, but it's part of the contract.
500
 
            result_branch = result.create_branch()
501
 
        else:
502
 
            result_branch = source_branch.sprout(result,
503
 
                revision_id=revision_id, repository_policy=repository_policy,
504
 
                repository=result_repo)
505
 
        mutter("created new branch %r" % (result_branch,))
506
 
 
507
 
        # Create/update the result working tree
508
 
        if (create_tree_if_local and
509
 
            isinstance(target_transport, local.LocalTransport) and
510
 
            (result_repo is None or result_repo.make_working_trees())):
511
 
            wt = result.create_workingtree(accelerator_tree=accelerator_tree,
512
 
                hardlink=hardlink, from_branch=result_branch)
513
 
            wt.lock_write()
514
 
            try:
515
 
                if wt.path2id('') is None:
516
 
                    try:
517
 
                        wt.set_root_id(self.open_workingtree.get_root_id())
518
 
                    except errors.NoWorkingTree:
519
 
                        pass
520
 
            finally:
521
 
                wt.unlock()
522
 
        else:
523
 
            wt = None
524
 
        if recurse == 'down':
525
 
            basis = None
526
 
            if wt is not None:
527
 
                basis = wt.basis_tree()
528
 
            elif result_branch is not None:
529
 
                basis = result_branch.basis_tree()
530
 
            elif source_branch is not None:
531
 
                basis = source_branch.basis_tree()
532
 
            if basis is not None:
533
 
                add_cleanup(basis.lock_read().unlock)
534
 
                subtrees = basis.iter_references()
535
 
            else:
536
 
                subtrees = []
537
 
            for path, file_id in subtrees:
538
 
                target = urlutils.join(url, urlutils.escape(path))
539
 
                sublocation = source_branch.reference_parent(file_id, path)
540
 
                sublocation.bzrdir.sprout(target,
541
 
                    basis.get_reference_revision(file_id, path),
542
 
                    force_new_repo=force_new_repo, recurse=recurse,
543
 
                    stacked=stacked)
544
 
        return result
545
 
 
546
 
 
547
 
 
548
458
    @staticmethod
549
459
    def create_branch_convenience(base, force_new_repo=False,
550
460
                                  force_new_tree=None, format=None,
576
486
        """
577
487
        if force_new_tree:
578
488
            # check for non local urls
579
 
            t = _mod_transport.get_transport(base, possible_transports)
 
489
            t = get_transport(base, possible_transports)
580
490
            if not isinstance(t, local.LocalTransport):
581
491
                raise errors.NotLocalUrl(base)
582
492
        bzrdir = BzrDir.create(base, format, possible_transports)
604
514
        :param format: Override for the bzrdir format to create.
605
515
        :return: The WorkingTree object.
606
516
        """
607
 
        t = _mod_transport.get_transport(base)
 
517
        t = get_transport(base)
608
518
        if not isinstance(t, local.LocalTransport):
609
519
            raise errors.NotLocalUrl(base)
610
520
        bzrdir = BzrDir.create_branch_and_repo(base,
612
522
                                               format=format).bzrdir
613
523
        return bzrdir.create_workingtree()
614
524
 
615
 
    @deprecated_method(deprecated_in((2, 3, 0)))
616
 
    def generate_backup_name(self, base):
617
 
        return self._available_backup_name(base)
618
 
 
619
 
    def _available_backup_name(self, base):
620
 
        """Find a non-existing backup file name based on base.
621
 
 
622
 
        See bzrlib.osutils.available_backup_name about race conditions.
 
525
    def create_workingtree(self, revision_id=None, from_branch=None,
 
526
        accelerator_tree=None, hardlink=False):
 
527
        """Create a working tree at this BzrDir.
 
528
 
 
529
        :param revision_id: create it as of this revision id.
 
530
        :param from_branch: override bzrdir branch (for lightweight checkouts)
 
531
        :param accelerator_tree: A tree which can be used for retrieving file
 
532
            contents more quickly than the revision tree, i.e. a workingtree.
 
533
            The revision tree will be used for cases where accelerator_tree's
 
534
            content is different.
623
535
        """
624
 
        return osutils.available_backup_name(base, self.root_transport.has)
 
536
        raise NotImplementedError(self.create_workingtree)
625
537
 
626
538
    def backup_bzrdir(self):
627
539
        """Backup this bzr control directory.
628
540
 
629
541
        :return: Tuple with old path name and new path name
630
542
        """
631
 
 
632
543
        pb = ui.ui_factory.nested_progress_bar()
633
544
        try:
 
545
            # FIXME: bug 300001 -- the backup fails if the backup directory
 
546
            # already exists, but it should instead either remove it or make
 
547
            # a new backup directory.
 
548
            #
 
549
            # FIXME: bug 262450 -- the backup directory should have the same
 
550
            # permissions as the .bzr directory (probably a bug in copy_tree)
634
551
            old_path = self.root_transport.abspath('.bzr')
635
 
            backup_dir = self._available_backup_name('backup.bzr')
636
 
            new_path = self.root_transport.abspath(backup_dir)
637
 
            ui.ui_factory.note('making backup of %s\n  to %s'
638
 
                               % (old_path, new_path,))
639
 
            self.root_transport.copy_tree('.bzr', backup_dir)
 
552
            new_path = self.root_transport.abspath('backup.bzr')
 
553
            pb.note('making backup of %s' % (old_path,))
 
554
            pb.note('  to %s' % (new_path,))
 
555
            self.root_transport.copy_tree('.bzr', 'backup.bzr')
640
556
            return (old_path, new_path)
641
557
        finally:
642
558
            pb.finished()
666
582
                else:
667
583
                    pass
668
584
 
 
585
    def destroy_workingtree(self):
 
586
        """Destroy the working tree at this BzrDir.
 
587
 
 
588
        Formats that do not support this may raise UnsupportedOperation.
 
589
        """
 
590
        raise NotImplementedError(self.destroy_workingtree)
 
591
 
 
592
    def destroy_workingtree_metadata(self):
 
593
        """Destroy the control files for the working tree at this BzrDir.
 
594
 
 
595
        The contents of working tree files are not affected.
 
596
        Formats that do not support this may raise UnsupportedOperation.
 
597
        """
 
598
        raise NotImplementedError(self.destroy_workingtree_metadata)
 
599
 
669
600
    def _find_containing(self, evaluate):
670
601
        """Find something in a containing control directory.
671
602
 
685
616
            if stop:
686
617
                return result
687
618
            next_transport = found_bzrdir.root_transport.clone('..')
688
 
            if (found_bzrdir.user_url == next_transport.base):
 
619
            if (found_bzrdir.root_transport.base == next_transport.base):
689
620
                # top of the file system
690
621
                return None
691
622
            # find the next containing bzrdir
708
639
                repository = found_bzrdir.open_repository()
709
640
            except errors.NoRepositoryPresent:
710
641
                return None, False
711
 
            if found_bzrdir.user_url == self.user_url:
 
642
            if found_bzrdir.root_transport.base == self.root_transport.base:
712
643
                return repository, True
713
644
            elif repository.is_shared():
714
645
                return repository, True
720
651
            raise errors.NoRepositoryPresent(self)
721
652
        return found_repo
722
653
 
 
654
    def get_branch_reference(self):
 
655
        """Return the referenced URL for the branch in this bzrdir.
 
656
 
 
657
        :raises NotBranchError: If there is no Branch.
 
658
        :return: The URL the branch in this bzrdir references if it is a
 
659
            reference branch, or None for regular branches.
 
660
        """
 
661
        return None
 
662
 
 
663
    def get_branch_transport(self, branch_format):
 
664
        """Get the transport for use by branch format in this BzrDir.
 
665
 
 
666
        Note that bzr dirs that do not support format strings will raise
 
667
        IncompatibleFormat if the branch format they are given has
 
668
        a format string, and vice versa.
 
669
 
 
670
        If branch_format is None, the transport is returned with no
 
671
        checking. If it is not None, then the returned transport is
 
672
        guaranteed to point to an existing directory ready for use.
 
673
        """
 
674
        raise NotImplementedError(self.get_branch_transport)
 
675
 
723
676
    def _find_creation_modes(self):
724
677
        """Determine the appropriate modes for files and directories.
725
678
 
764
717
            self._find_creation_modes()
765
718
        return self._dir_mode
766
719
 
 
720
    def get_repository_transport(self, repository_format):
 
721
        """Get the transport for use by repository format in this BzrDir.
 
722
 
 
723
        Note that bzr dirs that do not support format strings will raise
 
724
        IncompatibleFormat if the repository format they are given has
 
725
        a format string, and vice versa.
 
726
 
 
727
        If repository_format is None, the transport is returned with no
 
728
        checking. If it is not None, then the returned transport is
 
729
        guaranteed to point to an existing directory ready for use.
 
730
        """
 
731
        raise NotImplementedError(self.get_repository_transport)
 
732
 
 
733
    def get_workingtree_transport(self, tree_format):
 
734
        """Get the transport for use by workingtree format in this BzrDir.
 
735
 
 
736
        Note that bzr dirs that do not support format strings will raise
 
737
        IncompatibleFormat if the workingtree format they are given has a
 
738
        format string, and vice versa.
 
739
 
 
740
        If workingtree_format is None, the transport is returned with no
 
741
        checking. If it is not None, then the returned transport is
 
742
        guaranteed to point to an existing directory ready for use.
 
743
        """
 
744
        raise NotImplementedError(self.get_workingtree_transport)
 
745
 
767
746
    def get_config(self):
768
 
        """Get configuration for this BzrDir."""
769
 
        return config.BzrDirConfig(self)
770
 
 
771
 
    def _get_config(self):
772
 
        """By default, no configuration is available."""
773
 
        return None
 
747
        if getattr(self, '_get_config', None) is None:
 
748
            return None
 
749
        return self._get_config()
774
750
 
775
751
    def __init__(self, _transport, _format):
776
752
        """Initialize a Bzr control dir object.
782
758
        :param _transport: the transport this dir is based at.
783
759
        """
784
760
        self._format = _format
785
 
        # these are also under the more standard names of 
786
 
        # control_transport and user_transport
787
761
        self.transport = _transport.clone('.bzr')
788
762
        self.root_transport = _transport
789
763
        self._mode_check_done = False
790
764
 
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
765
    def is_control_filename(self, filename):
800
766
        """True if filename is the name of a path which is reserved for bzrdir's.
801
767
 
803
769
 
804
770
        This is true IF and ONLY IF the filename is part of the namespace reserved
805
771
        for bzr control dirs. Currently this is the '.bzr' directory in the root
806
 
        of the root_transport. 
 
772
        of the root_transport. it is expected that plugins will need to extend
 
773
        this in the future - for instance to make bzr talk with svn working
 
774
        trees.
807
775
        """
808
776
        # this might be better on the BzrDirFormat class because it refers to
809
777
        # all the possible bzrdir disk formats.
813
781
        # add new tests for it to the appropriate place.
814
782
        return filename == '.bzr' or filename.startswith('.bzr/')
815
783
 
 
784
    def needs_format_conversion(self, format=None):
 
785
        """Return true if this bzrdir needs convert_format run on it.
 
786
 
 
787
        For instance, if the repository format is out of date but the
 
788
        branch and working tree are not, this should return True.
 
789
 
 
790
        :param format: Optional parameter indicating a specific desired
 
791
                       format we plan to arrive at.
 
792
        """
 
793
        raise NotImplementedError(self.needs_format_conversion)
 
794
 
816
795
    @staticmethod
817
796
    def open_unsupported(base):
818
797
        """Open a branch which is not supported."""
824
803
 
825
804
        :param _unsupported: a private parameter to the BzrDir class.
826
805
        """
827
 
        t = _mod_transport.get_transport(base, possible_transports)
 
806
        t = get_transport(base, possible_transports=possible_transports)
828
807
        return BzrDir.open_from_transport(t, _unsupported=_unsupported)
829
808
 
830
809
    @staticmethod
841
820
        # the redirections.
842
821
        base = transport.base
843
822
        def find_format(transport):
844
 
            return transport, controldir.ControlDirFormat.find_format(
 
823
            return transport, BzrDirFormat.find_format(
845
824
                transport, _server_formats=_server_formats)
846
825
 
847
826
        def redirected(transport, e, redirection_notice):
859
838
        except errors.TooManyRedirections:
860
839
            raise errors.NotBranchError(base)
861
840
 
862
 
        format.check_support_status(_unsupported)
 
841
        BzrDir._check_supported(format, _unsupported)
863
842
        return format.open(transport, _found=True)
864
843
 
 
844
    def open_branch(self, unsupported=False, ignore_fallbacks=False):
 
845
        """Open the branch object at this BzrDir if one is present.
 
846
 
 
847
        If unsupported is True, then no longer supported branch formats can
 
848
        still be opened.
 
849
 
 
850
        TODO: static convenience version of this?
 
851
        """
 
852
        raise NotImplementedError(self.open_branch)
 
853
 
865
854
    @staticmethod
866
855
    def open_containing(url, possible_transports=None):
867
856
        """Open an existing branch which contains url.
868
857
 
869
858
        :param url: url to search from.
870
 
 
871
859
        See open_containing_from_transport for more detail.
872
860
        """
873
 
        transport = _mod_transport.get_transport(url, possible_transports)
 
861
        transport = get_transport(url, possible_transports)
874
862
        return BzrDir.open_containing_from_transport(transport)
875
863
 
876
864
    @staticmethod
906
894
                raise errors.NotBranchError(path=url)
907
895
            a_transport = new_t
908
896
 
 
897
    def _get_tree_branch(self):
 
898
        """Return the branch and tree, if any, for this bzrdir.
 
899
 
 
900
        Return None for tree if not present or inaccessible.
 
901
        Raise NotBranchError if no branch is present.
 
902
        :return: (tree, branch)
 
903
        """
 
904
        try:
 
905
            tree = self.open_workingtree()
 
906
        except (errors.NoWorkingTree, errors.NotLocalUrl):
 
907
            tree = None
 
908
            branch = self.open_branch()
 
909
        else:
 
910
            branch = tree.branch
 
911
        return tree, branch
 
912
 
909
913
    @classmethod
910
914
    def open_tree_or_branch(klass, location):
911
915
        """Return the branch and working tree at a location.
957
961
                raise errors.NotBranchError(location)
958
962
        return tree, branch, branch.repository, relpath
959
963
 
 
964
    def open_repository(self, _unsupported=False):
 
965
        """Open the repository object at this BzrDir if one is present.
 
966
 
 
967
        This will not follow the Branch object pointer - it's strictly a direct
 
968
        open facility. Most client code should use open_branch().repository to
 
969
        get at a repository.
 
970
 
 
971
        :param _unsupported: a private parameter, not part of the api.
 
972
        TODO: static convenience version of this?
 
973
        """
 
974
        raise NotImplementedError(self.open_repository)
 
975
 
 
976
    def open_workingtree(self, _unsupported=False,
 
977
                         recommend_upgrade=True, from_branch=None):
 
978
        """Open the workingtree object at this BzrDir if one is present.
 
979
 
 
980
        :param recommend_upgrade: Optional keyword parameter, when True (the
 
981
            default), emit through the ui module a recommendation that the user
 
982
            upgrade the working tree when the workingtree being opened is old
 
983
            (but still fully supported).
 
984
        :param from_branch: override bzrdir branch (for lightweight checkouts)
 
985
        """
 
986
        raise NotImplementedError(self.open_workingtree)
 
987
 
 
988
    def has_branch(self):
 
989
        """Tell if this bzrdir contains a branch.
 
990
 
 
991
        Note: if you're going to open the branch, you should just go ahead
 
992
        and try, and not ask permission first.  (This method just opens the
 
993
        branch and discards it, and that's somewhat expensive.)
 
994
        """
 
995
        try:
 
996
            self.open_branch()
 
997
            return True
 
998
        except errors.NotBranchError:
 
999
            return False
 
1000
 
 
1001
    def has_workingtree(self):
 
1002
        """Tell if this bzrdir contains a working tree.
 
1003
 
 
1004
        This will still raise an exception if the bzrdir has a workingtree that
 
1005
        is remote & inaccessible.
 
1006
 
 
1007
        Note: if you're going to open the working tree, you should just go ahead
 
1008
        and try, and not ask permission first.  (This method just opens the
 
1009
        workingtree and discards it, and that's somewhat expensive.)
 
1010
        """
 
1011
        try:
 
1012
            self.open_workingtree(recommend_upgrade=False)
 
1013
            return True
 
1014
        except errors.NoWorkingTree:
 
1015
            return False
 
1016
 
960
1017
    def _cloning_metadir(self):
961
1018
        """Produce a metadir suitable for cloning with.
962
1019
 
1008
1065
        """
1009
1066
        format, repository = self._cloning_metadir()
1010
1067
        if format._workingtree_format is None:
1011
 
            # No tree in self.
1012
1068
            if repository is None:
1013
 
                # No repository either
1014
1069
                return format
1015
 
            # We have a repository, so set a working tree? (Why? This seems to
1016
 
            # contradict the stated return value in the docstring).
1017
1070
            tree_format = repository._format._matchingbzrdir.workingtree_format
1018
1071
            format.workingtree_format = tree_format.__class__()
1019
1072
        if require_stacking:
1020
1073
            format.require_stacking()
1021
1074
        return format
1022
1075
 
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)
 
1076
    def checkout_metadir(self):
 
1077
        return self.cloning_metadir()
 
1078
 
 
1079
    def sprout(self, url, revision_id=None, force_new_repo=False,
 
1080
               recurse='down', possible_transports=None,
 
1081
               accelerator_tree=None, hardlink=False, stacked=False,
 
1082
               source_branch=None, create_tree_if_local=True):
 
1083
        """Create a copy of this bzrdir prepared for use as a new line of
 
1084
        development.
 
1085
 
 
1086
        If url's last component does not exist, it will be created.
 
1087
 
 
1088
        Attributes related to the identity of the source branch like
 
1089
        branch nickname will be cleaned, a working tree is created
 
1090
        whether one existed before or not; and a local branch is always
 
1091
        created.
 
1092
 
 
1093
        if revision_id is not None, then the clone operation may tune
 
1094
            itself to download less data.
 
1095
        :param accelerator_tree: A tree which can be used for retrieving file
 
1096
            contents more quickly than the revision tree, i.e. a workingtree.
 
1097
            The revision tree will be used for cases where accelerator_tree's
 
1098
            content is different.
 
1099
        :param hardlink: If true, hard-link files from accelerator_tree,
 
1100
            where possible.
 
1101
        :param stacked: If true, create a stacked branch referring to the
 
1102
            location of this control directory.
 
1103
        :param create_tree_if_local: If true, a working-tree will be created
 
1104
            when working locally.
 
1105
        """
 
1106
        target_transport = get_transport(url, possible_transports)
 
1107
        target_transport.ensure_base()
 
1108
        cloning_format = self.cloning_metadir(stacked)
 
1109
        # Create/update the result branch
 
1110
        result = cloning_format.initialize_on_transport(target_transport)
 
1111
        # if a stacked branch wasn't requested, we don't create one
 
1112
        # even if the origin was stacked
 
1113
        stacked_branch_url = None
 
1114
        if source_branch is not None:
 
1115
            if stacked:
 
1116
                stacked_branch_url = self.root_transport.base
 
1117
            source_repository = source_branch.repository
 
1118
        else:
 
1119
            try:
 
1120
                source_branch = self.open_branch()
 
1121
                source_repository = source_branch.repository
 
1122
                if stacked:
 
1123
                    stacked_branch_url = self.root_transport.base
 
1124
            except errors.NotBranchError:
 
1125
                source_branch = None
 
1126
                try:
 
1127
                    source_repository = self.open_repository()
 
1128
                except errors.NoRepositoryPresent:
 
1129
                    source_repository = None
 
1130
        repository_policy = result.determine_repository_policy(
 
1131
            force_new_repo, stacked_branch_url, require_stacking=stacked)
 
1132
        result_repo, is_new_repo = repository_policy.acquire_repository()
 
1133
        if is_new_repo and revision_id is not None and not stacked:
 
1134
            fetch_spec = graph.PendingAncestryResult(
 
1135
                [revision_id], source_repository)
 
1136
        else:
 
1137
            fetch_spec = None
 
1138
        if source_repository is not None:
 
1139
            # Fetch while stacked to prevent unstacked fetch from
 
1140
            # Branch.sprout.
 
1141
            if fetch_spec is None:
 
1142
                result_repo.fetch(source_repository, revision_id=revision_id)
 
1143
            else:
 
1144
                result_repo.fetch(source_repository, fetch_spec=fetch_spec)
 
1145
 
 
1146
        if source_branch is None:
 
1147
            # this is for sprouting a bzrdir without a branch; is that
 
1148
            # actually useful?
 
1149
            # Not especially, but it's part of the contract.
 
1150
            result_branch = result.create_branch()
 
1151
        else:
 
1152
            result_branch = source_branch.sprout(result,
 
1153
                revision_id=revision_id, repository_policy=repository_policy)
 
1154
        mutter("created new branch %r" % (result_branch,))
 
1155
 
 
1156
        # Create/update the result working tree
 
1157
        if (create_tree_if_local and
 
1158
            isinstance(target_transport, local.LocalTransport) and
 
1159
            (result_repo is None or result_repo.make_working_trees())):
 
1160
            wt = result.create_workingtree(accelerator_tree=accelerator_tree,
 
1161
                hardlink=hardlink)
 
1162
            wt.lock_write()
 
1163
            try:
 
1164
                if wt.path2id('') is None:
 
1165
                    try:
 
1166
                        wt.set_root_id(self.open_workingtree.get_root_id())
 
1167
                    except errors.NoWorkingTree:
 
1168
                        pass
 
1169
            finally:
 
1170
                wt.unlock()
 
1171
        else:
 
1172
            wt = None
 
1173
        if recurse == 'down':
 
1174
            if wt is not None:
 
1175
                basis = wt.basis_tree()
 
1176
                basis.lock_read()
 
1177
                subtrees = basis.iter_references()
 
1178
            elif result_branch is not None:
 
1179
                basis = result_branch.basis_tree()
 
1180
                basis.lock_read()
 
1181
                subtrees = basis.iter_references()
 
1182
            elif source_branch is not None:
 
1183
                basis = source_branch.basis_tree()
 
1184
                basis.lock_read()
 
1185
                subtrees = basis.iter_references()
 
1186
            else:
 
1187
                subtrees = []
 
1188
                basis = None
 
1189
            try:
 
1190
                for path, file_id in subtrees:
 
1191
                    target = urlutils.join(url, urlutils.escape(path))
 
1192
                    sublocation = source_branch.reference_parent(file_id, path)
 
1193
                    sublocation.bzrdir.sprout(target,
 
1194
                        basis.get_reference_revision(file_id, path),
 
1195
                        force_new_repo=force_new_repo, recurse=recurse,
 
1196
                        stacked=stacked)
 
1197
            finally:
 
1198
                if basis is not None:
 
1199
                    basis.unlock()
 
1200
        return result
 
1201
 
 
1202
    def push_branch(self, source, revision_id=None, overwrite=False, 
 
1203
        remember=False):
 
1204
        """Push the source branch into this BzrDir."""
 
1205
        br_to = None
 
1206
        # If we can open a branch, use its direct repository, otherwise see
 
1207
        # if there is a repository without a branch.
 
1208
        try:
 
1209
            br_to = self.open_branch()
 
1210
        except errors.NotBranchError:
 
1211
            # Didn't find a branch, can we find a repository?
 
1212
            repository_to = self.find_repository()
 
1213
        else:
 
1214
            # Found a branch, so we must have found a repository
 
1215
            repository_to = br_to.repository
 
1216
 
 
1217
        push_result = PushResult()
 
1218
        push_result.source_branch = source
 
1219
        if br_to is None:
 
1220
            # We have a repository but no branch, copy the revisions, and then
 
1221
            # create a branch.
 
1222
            repository_to.fetch(source.repository, revision_id=revision_id)
 
1223
            br_to = source.clone(self, revision_id=revision_id)
 
1224
            if source.get_push_location() is None or remember:
 
1225
                source.set_push_location(br_to.base)
 
1226
            push_result.stacked_on = None
 
1227
            push_result.branch_push_result = None
 
1228
            push_result.old_revno = None
 
1229
            push_result.old_revid = _mod_revision.NULL_REVISION
 
1230
            push_result.target_branch = br_to
 
1231
            push_result.master_branch = None
 
1232
            push_result.workingtree_updated = False
 
1233
        else:
 
1234
            # We have successfully opened the branch, remember if necessary:
 
1235
            if source.get_push_location() is None or remember:
 
1236
                source.set_push_location(br_to.base)
 
1237
            try:
 
1238
                tree_to = self.open_workingtree()
 
1239
            except errors.NotLocalUrl:
 
1240
                push_result.branch_push_result = source.push(br_to, 
 
1241
                    overwrite, stop_revision=revision_id)
 
1242
                push_result.workingtree_updated = False
 
1243
            except errors.NoWorkingTree:
 
1244
                push_result.branch_push_result = source.push(br_to,
 
1245
                    overwrite, stop_revision=revision_id)
 
1246
                push_result.workingtree_updated = None # Not applicable
 
1247
            else:
 
1248
                tree_to.lock_write()
 
1249
                try:
 
1250
                    push_result.branch_push_result = source.push(
 
1251
                        tree_to.branch, overwrite, stop_revision=revision_id)
 
1252
                    tree_to.update()
 
1253
                finally:
 
1254
                    tree_to.unlock()
 
1255
                push_result.workingtree_updated = True
 
1256
            push_result.old_revno = push_result.branch_push_result.old_revno
 
1257
            push_result.old_revid = push_result.branch_push_result.old_revid
 
1258
            push_result.target_branch = \
 
1259
                push_result.branch_push_result.target_branch
 
1260
        return push_result
1079
1261
 
1080
1262
 
1081
1263
class BzrDirHooks(hooks.Hooks):
1083
1265
 
1084
1266
    def __init__(self):
1085
1267
        """Create the default hooks."""
1086
 
        hooks.Hooks.__init__(self, "bzrlib.bzrdir", "BzrDir.hooks")
1087
 
        self.add_hook('pre_open',
 
1268
        hooks.Hooks.__init__(self)
 
1269
        self.create_hook(hooks.HookPoint('pre_open',
1088
1270
            "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))
 
1271
            "that the open will use.", (1, 14), None))
1095
1272
 
1096
1273
# install the default hooks
1097
1274
BzrDir.hooks = BzrDirHooks()
1098
1275
 
1099
1276
 
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
 
1277
class BzrDirPreSplitOut(BzrDir):
 
1278
    """A common class for the all-in-one formats."""
 
1279
 
 
1280
    def __init__(self, _transport, _format):
 
1281
        """See BzrDir.__init__."""
 
1282
        super(BzrDirPreSplitOut, self).__init__(_transport, _format)
 
1283
        self._control_files = lockable_files.LockableFiles(
 
1284
                                            self.get_branch_transport(None),
 
1285
                                            self._format._lock_file_name,
 
1286
                                            self._format._lock_class)
 
1287
 
 
1288
    def break_lock(self):
 
1289
        """Pre-splitout bzrdirs do not suffer from stale locks."""
 
1290
        raise NotImplementedError(self.break_lock)
 
1291
 
 
1292
    def cloning_metadir(self, require_stacking=False):
 
1293
        """Produce a metadir suitable for cloning with."""
 
1294
        if require_stacking:
 
1295
            return format_registry.make_bzrdir('1.6')
 
1296
        return self._format.__class__()
 
1297
 
 
1298
    def clone(self, url, revision_id=None, force_new_repo=False,
 
1299
              preserve_stacking=False):
 
1300
        """See BzrDir.clone().
 
1301
 
 
1302
        force_new_repo has no effect, since this family of formats always
 
1303
        require a new repository.
 
1304
        preserve_stacking has no effect, since no source branch using this
 
1305
        family of formats can be stacked, so there is no stacking to preserve.
1118
1306
        """
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)
 
1307
        self._make_tail(url)
 
1308
        result = self._format._initialize_for_clone(url)
 
1309
        self.open_repository().clone(result, revision_id=revision_id)
 
1310
        from_branch = self.open_branch()
 
1311
        from_branch.clone(result, revision_id=revision_id)
 
1312
        try:
 
1313
            tree = self.open_workingtree()
 
1314
        except errors.NotLocalUrl:
 
1315
            # make a new one, this format always has to have one.
 
1316
            result._init_workingtree()
1131
1317
        else:
1132
 
            return "<%s for %s>" % (self.__class__.__name__,
1133
 
                self.bzrdir)
 
1318
            tree.clone(result)
 
1319
        return result
 
1320
 
 
1321
    def create_branch(self):
 
1322
        """See BzrDir.create_branch."""
 
1323
        return self._format.get_branch_format().initialize(self)
 
1324
 
 
1325
    def destroy_branch(self):
 
1326
        """See BzrDir.destroy_branch."""
 
1327
        raise errors.UnsupportedOperation(self.destroy_branch, self)
 
1328
 
 
1329
    def create_repository(self, shared=False):
 
1330
        """See BzrDir.create_repository."""
 
1331
        if shared:
 
1332
            raise errors.IncompatibleFormat('shared repository', self._format)
 
1333
        return self.open_repository()
 
1334
 
 
1335
    def destroy_repository(self):
 
1336
        """See BzrDir.destroy_repository."""
 
1337
        raise errors.UnsupportedOperation(self.destroy_repository, self)
 
1338
 
 
1339
    def create_workingtree(self, revision_id=None, from_branch=None,
 
1340
                           accelerator_tree=None, hardlink=False):
 
1341
        """See BzrDir.create_workingtree."""
 
1342
        # The workingtree is sometimes created when the bzrdir is created,
 
1343
        # but not when cloning.
 
1344
 
 
1345
        # this looks buggy but is not -really-
 
1346
        # because this format creates the workingtree when the bzrdir is
 
1347
        # created
 
1348
        # clone and sprout will have set the revision_id
 
1349
        # and that will have set it for us, its only
 
1350
        # specific uses of create_workingtree in isolation
 
1351
        # that can do wonky stuff here, and that only
 
1352
        # happens for creating checkouts, which cannot be
 
1353
        # done on this format anyway. So - acceptable wart.
 
1354
        try:
 
1355
            result = self.open_workingtree(recommend_upgrade=False)
 
1356
        except errors.NoSuchFile:
 
1357
            result = self._init_workingtree()
 
1358
        if revision_id is not None:
 
1359
            if revision_id == _mod_revision.NULL_REVISION:
 
1360
                result.set_parent_ids([])
 
1361
            else:
 
1362
                result.set_parent_ids([revision_id])
 
1363
        return result
 
1364
 
 
1365
    def _init_workingtree(self):
 
1366
        from bzrlib.workingtree import WorkingTreeFormat2
 
1367
        try:
 
1368
            return WorkingTreeFormat2().initialize(self)
 
1369
        except errors.NotLocalUrl:
 
1370
            # Even though we can't access the working tree, we need to
 
1371
            # create its control files.
 
1372
            return WorkingTreeFormat2()._stub_initialize_on_transport(
 
1373
                self.transport, self._control_files._file_mode)
 
1374
 
 
1375
    def destroy_workingtree(self):
 
1376
        """See BzrDir.destroy_workingtree."""
 
1377
        raise errors.UnsupportedOperation(self.destroy_workingtree, self)
 
1378
 
 
1379
    def destroy_workingtree_metadata(self):
 
1380
        """See BzrDir.destroy_workingtree_metadata."""
 
1381
        raise errors.UnsupportedOperation(self.destroy_workingtree_metadata,
 
1382
                                          self)
 
1383
 
 
1384
    def get_branch_transport(self, branch_format):
 
1385
        """See BzrDir.get_branch_transport()."""
 
1386
        if branch_format is None:
 
1387
            return self.transport
 
1388
        try:
 
1389
            branch_format.get_format_string()
 
1390
        except NotImplementedError:
 
1391
            return self.transport
 
1392
        raise errors.IncompatibleFormat(branch_format, self._format)
 
1393
 
 
1394
    def get_repository_transport(self, repository_format):
 
1395
        """See BzrDir.get_repository_transport()."""
 
1396
        if repository_format is None:
 
1397
            return self.transport
 
1398
        try:
 
1399
            repository_format.get_format_string()
 
1400
        except NotImplementedError:
 
1401
            return self.transport
 
1402
        raise errors.IncompatibleFormat(repository_format, self._format)
 
1403
 
 
1404
    def get_workingtree_transport(self, workingtree_format):
 
1405
        """See BzrDir.get_workingtree_transport()."""
 
1406
        if workingtree_format is None:
 
1407
            return self.transport
 
1408
        try:
 
1409
            workingtree_format.get_format_string()
 
1410
        except NotImplementedError:
 
1411
            return self.transport
 
1412
        raise errors.IncompatibleFormat(workingtree_format, self._format)
 
1413
 
 
1414
    def needs_format_conversion(self, format=None):
 
1415
        """See BzrDir.needs_format_conversion()."""
 
1416
        # if the format is not the same as the system default,
 
1417
        # an upgrade is needed.
 
1418
        if format is None:
 
1419
            symbol_versioning.warn(symbol_versioning.deprecated_in((1, 13, 0))
 
1420
                % 'needs_format_conversion(format=None)')
 
1421
            format = BzrDirFormat.get_default_format()
 
1422
        return not isinstance(self._format, format.__class__)
 
1423
 
 
1424
    def open_branch(self, unsupported=False, ignore_fallbacks=False):
 
1425
        """See BzrDir.open_branch."""
 
1426
        from bzrlib.branch import BzrBranchFormat4
 
1427
        format = BzrBranchFormat4()
 
1428
        self._check_supported(format, unsupported)
 
1429
        return format.open(self, _found=True)
 
1430
 
 
1431
    def sprout(self, url, revision_id=None, force_new_repo=False,
 
1432
               possible_transports=None, accelerator_tree=None,
 
1433
               hardlink=False, stacked=False, create_tree_if_local=True,
 
1434
               source_branch=None):
 
1435
        """See BzrDir.sprout()."""
 
1436
        if source_branch is not None:
 
1437
            my_branch = self.open_branch()
 
1438
            if source_branch.base != my_branch.base:
 
1439
                raise AssertionError(
 
1440
                    "source branch %r is not within %r with branch %r" %
 
1441
                    (source_branch, self, my_branch))
 
1442
        if stacked:
 
1443
            raise errors.UnstackableBranchFormat(
 
1444
                self._format, self.root_transport.base)
 
1445
        if not create_tree_if_local:
 
1446
            raise errors.MustHaveWorkingTree(
 
1447
                self._format, self.root_transport.base)
 
1448
        from bzrlib.workingtree import WorkingTreeFormat2
 
1449
        self._make_tail(url)
 
1450
        result = self._format._initialize_for_clone(url)
 
1451
        try:
 
1452
            self.open_repository().clone(result, revision_id=revision_id)
 
1453
        except errors.NoRepositoryPresent:
 
1454
            pass
 
1455
        try:
 
1456
            self.open_branch().sprout(result, revision_id=revision_id)
 
1457
        except errors.NotBranchError:
 
1458
            pass
 
1459
 
 
1460
        # we always want a working tree
 
1461
        WorkingTreeFormat2().initialize(result,
 
1462
                                        accelerator_tree=accelerator_tree,
 
1463
                                        hardlink=hardlink)
 
1464
        return result
 
1465
 
 
1466
 
 
1467
class BzrDir4(BzrDirPreSplitOut):
 
1468
    """A .bzr version 4 control object.
 
1469
 
 
1470
    This is a deprecated format and may be removed after sept 2006.
 
1471
    """
 
1472
 
 
1473
    def create_repository(self, shared=False):
 
1474
        """See BzrDir.create_repository."""
 
1475
        return self._format.repository_format.initialize(self, shared)
 
1476
 
 
1477
    def needs_format_conversion(self, format=None):
 
1478
        """Format 4 dirs are always in need of conversion."""
 
1479
        if format is None:
 
1480
            symbol_versioning.warn(symbol_versioning.deprecated_in((1, 13, 0))
 
1481
                % 'needs_format_conversion(format=None)')
 
1482
        return True
 
1483
 
 
1484
    def open_repository(self):
 
1485
        """See BzrDir.open_repository."""
 
1486
        from bzrlib.repofmt.weaverepo import RepositoryFormat4
 
1487
        return RepositoryFormat4().open(self, _found=True)
 
1488
 
 
1489
 
 
1490
class BzrDir5(BzrDirPreSplitOut):
 
1491
    """A .bzr version 5 control object.
 
1492
 
 
1493
    This is a deprecated format and may be removed after sept 2006.
 
1494
    """
 
1495
 
 
1496
    def open_repository(self):
 
1497
        """See BzrDir.open_repository."""
 
1498
        from bzrlib.repofmt.weaverepo import RepositoryFormat5
 
1499
        return RepositoryFormat5().open(self, _found=True)
 
1500
 
 
1501
    def open_workingtree(self, _unsupported=False,
 
1502
            recommend_upgrade=True):
 
1503
        """See BzrDir.create_workingtree."""
 
1504
        from bzrlib.workingtree import WorkingTreeFormat2
 
1505
        wt_format = WorkingTreeFormat2()
 
1506
        # we don't warn here about upgrades; that ought to be handled for the
 
1507
        # bzrdir as a whole
 
1508
        return wt_format.open(self, _found=True)
 
1509
 
 
1510
 
 
1511
class BzrDir6(BzrDirPreSplitOut):
 
1512
    """A .bzr version 6 control object.
 
1513
 
 
1514
    This is a deprecated format and may be removed after sept 2006.
 
1515
    """
 
1516
 
 
1517
    def open_repository(self):
 
1518
        """See BzrDir.open_repository."""
 
1519
        from bzrlib.repofmt.weaverepo import RepositoryFormat6
 
1520
        return RepositoryFormat6().open(self, _found=True)
 
1521
 
 
1522
    def open_workingtree(self, _unsupported=False,
 
1523
        recommend_upgrade=True):
 
1524
        """See BzrDir.create_workingtree."""
 
1525
        # we don't warn here about upgrades; that ought to be handled for the
 
1526
        # bzrdir as a whole
 
1527
        from bzrlib.workingtree import WorkingTreeFormat2
 
1528
        return WorkingTreeFormat2().open(self, _found=True)
1134
1529
 
1135
1530
 
1136
1531
class BzrDirMeta1(BzrDir):
1146
1541
        """See BzrDir.can_convert_format()."""
1147
1542
        return True
1148
1543
 
1149
 
    def create_branch(self, name=None, repository=None):
 
1544
    def create_branch(self):
1150
1545
        """See BzrDir.create_branch."""
1151
 
        return self._format.get_branch_format().initialize(self, name=name,
1152
 
                repository=repository)
 
1546
        return self._format.get_branch_format().initialize(self)
1153
1547
 
1154
 
    def destroy_branch(self, name=None):
 
1548
    def destroy_branch(self):
1155
1549
        """See BzrDir.create_branch."""
1156
 
        if name is not None:
1157
 
            raise errors.NoColocatedBranchSupport(self)
1158
1550
        self.transport.delete_tree('branch')
1159
1551
 
1160
1552
    def create_repository(self, shared=False):
1177
1569
        wt = self.open_workingtree(recommend_upgrade=False)
1178
1570
        repository = wt.branch.repository
1179
1571
        empty = repository.revision_tree(_mod_revision.NULL_REVISION)
1180
 
        # We ignore the conflicts returned by wt.revert since we're about to
1181
 
        # delete the wt metadata anyway, all that should be left here are
1182
 
        # detritus. But see bug #634470 about subtree .bzr dirs.
1183
 
        conflicts = wt.revert(old_tree=empty)
 
1572
        wt.revert(old_tree=empty)
1184
1573
        self.destroy_workingtree_metadata()
1185
1574
 
1186
1575
    def destroy_workingtree_metadata(self):
1187
1576
        self.transport.delete_tree('checkout')
1188
1577
 
1189
 
    def find_branch_format(self, name=None):
 
1578
    def find_branch_format(self):
1190
1579
        """Find the branch 'format' for this bzrdir.
1191
1580
 
1192
1581
        This might be a synthetic object for e.g. RemoteBranch and SVN.
1193
1582
        """
1194
1583
        from bzrlib.branch import BranchFormat
1195
 
        return BranchFormat.find_format(self, name=name)
 
1584
        return BranchFormat.find_format(self)
1196
1585
 
1197
1586
    def _get_mkdir_mode(self):
1198
1587
        """Figure out the mode to use when creating a bzrdir subdir."""
1200
1589
                                     lockable_files.TransportLock)
1201
1590
        return temp_control._dir_mode
1202
1591
 
1203
 
    def get_branch_reference(self, name=None):
 
1592
    def get_branch_reference(self):
1204
1593
        """See BzrDir.get_branch_reference()."""
1205
1594
        from bzrlib.branch import BranchFormat
1206
 
        format = BranchFormat.find_format(self, name=name)
1207
 
        return format.get_reference(self, name=name)
 
1595
        format = BranchFormat.find_format(self)
 
1596
        return format.get_reference(self)
1208
1597
 
1209
 
    def get_branch_transport(self, branch_format, name=None):
 
1598
    def get_branch_transport(self, branch_format):
1210
1599
        """See BzrDir.get_branch_transport()."""
1211
 
        if name is not None:
1212
 
            raise errors.NoColocatedBranchSupport(self)
1213
 
        # XXX: this shouldn't implicitly create the directory if it's just
1214
 
        # promising to get a transport -- mbp 20090727
1215
1600
        if branch_format is None:
1216
1601
            return self.transport.clone('branch')
1217
1602
        try:
1252
1637
            pass
1253
1638
        return self.transport.clone('checkout')
1254
1639
 
1255
 
    def has_workingtree(self):
1256
 
        """Tell if this bzrdir contains a working tree.
1257
 
 
1258
 
        Note: if you're going to open the working tree, you should just go
1259
 
        ahead and try, and not ask permission first.
1260
 
        """
1261
 
        from bzrlib.workingtree import WorkingTreeFormat
1262
 
        try:
1263
 
            WorkingTreeFormat.find_format_string(self)
1264
 
        except errors.NoWorkingTree:
1265
 
            return False
1266
 
        return True
1267
 
 
1268
 
    def needs_format_conversion(self, format):
 
1640
    def needs_format_conversion(self, format=None):
1269
1641
        """See BzrDir.needs_format_conversion()."""
 
1642
        if format is None:
 
1643
            symbol_versioning.warn(symbol_versioning.deprecated_in((1, 13, 0))
 
1644
                % 'needs_format_conversion(format=None)')
 
1645
        if format is None:
 
1646
            format = BzrDirFormat.get_default_format()
1270
1647
        if not isinstance(self._format, format.__class__):
1271
1648
            # it is not a meta dir format, conversion is needed.
1272
1649
            return True
1278
1655
                return True
1279
1656
        except errors.NoRepositoryPresent:
1280
1657
            pass
1281
 
        for branch in self.list_branches():
1282
 
            if not isinstance(branch._format,
 
1658
        try:
 
1659
            if not isinstance(self.open_branch()._format,
1283
1660
                              format.get_branch_format().__class__):
1284
1661
                # the branch needs an upgrade.
1285
1662
                return True
 
1663
        except errors.NotBranchError:
 
1664
            pass
1286
1665
        try:
1287
1666
            my_wt = self.open_workingtree(recommend_upgrade=False)
1288
1667
            if not isinstance(my_wt._format,
1293
1672
            pass
1294
1673
        return False
1295
1674
 
1296
 
    def open_branch(self, name=None, unsupported=False,
1297
 
                    ignore_fallbacks=False):
 
1675
    def open_branch(self, unsupported=False, ignore_fallbacks=False):
1298
1676
        """See BzrDir.open_branch."""
1299
 
        format = self.find_branch_format(name=name)
1300
 
        format.check_support_status(unsupported)
1301
 
        return format.open(self, name=name,
1302
 
            _found=True, ignore_fallbacks=ignore_fallbacks)
 
1677
        format = self.find_branch_format()
 
1678
        self._check_supported(format, unsupported)
 
1679
        return format.open(self, _found=True, ignore_fallbacks=ignore_fallbacks)
1303
1680
 
1304
1681
    def open_repository(self, unsupported=False):
1305
1682
        """See BzrDir.open_repository."""
1306
1683
        from bzrlib.repository import RepositoryFormat
1307
1684
        format = RepositoryFormat.find_format(self)
1308
 
        format.check_support_status(unsupported)
 
1685
        self._check_supported(format, unsupported)
1309
1686
        return format.open(self, _found=True)
1310
1687
 
1311
1688
    def open_workingtree(self, unsupported=False,
1313
1690
        """See BzrDir.open_workingtree."""
1314
1691
        from bzrlib.workingtree import WorkingTreeFormat
1315
1692
        format = WorkingTreeFormat.find_format(self)
1316
 
        format.check_support_status(unsupported, recommend_upgrade,
 
1693
        self._check_supported(format, unsupported,
 
1694
            recommend_upgrade,
1317
1695
            basedir=self.root_transport.base)
1318
1696
        return format.open(self, _found=True)
1319
1697
 
1320
1698
    def _get_config(self):
1321
 
        return config.TransportConfig(self.transport, 'control.conf')
1322
 
 
1323
 
 
1324
 
class BzrProber(controldir.Prober):
1325
 
    """Prober for formats that use a .bzr/ control directory."""
1326
 
 
1327
 
    formats = registry.FormatRegistry(controldir.network_format_registry)
1328
 
    """The known .bzr formats."""
1329
 
 
1330
 
    @classmethod
1331
 
    @deprecated_method(deprecated_in((2, 4, 0)))
1332
 
    def register_bzrdir_format(klass, format):
1333
 
        klass.formats.register(format.get_format_string(), format)
1334
 
 
1335
 
    @classmethod
1336
 
    @deprecated_method(deprecated_in((2, 4, 0)))
1337
 
    def unregister_bzrdir_format(klass, format):
1338
 
        klass.formats.remove(format.get_format_string())
1339
 
 
1340
 
    @classmethod
1341
 
    def probe_transport(klass, transport):
1342
 
        """Return the .bzrdir style format present in a directory."""
1343
 
        try:
1344
 
            format_string = transport.get_bytes(".bzr/branch-format")
1345
 
        except errors.NoSuchFile:
1346
 
            raise errors.NotBranchError(path=transport.base)
1347
 
        try:
1348
 
            return klass.formats.get(format_string)
1349
 
        except KeyError:
1350
 
            raise errors.UnknownFormatError(format=format_string, kind='bzrdir')
1351
 
 
1352
 
    @classmethod
1353
 
    def known_formats(cls):
1354
 
        result = set()
1355
 
        for name, format in cls.formats.iteritems():
1356
 
            if callable(format):
1357
 
                format = format()
1358
 
            result.add(format)
1359
 
        return result
1360
 
 
1361
 
 
1362
 
controldir.ControlDirFormat.register_prober(BzrProber)
1363
 
 
1364
 
 
1365
 
class RemoteBzrProber(controldir.Prober):
1366
 
    """Prober for remote servers that provide a Bazaar smart server."""
1367
 
 
1368
 
    @classmethod
1369
 
    def probe_transport(klass, transport):
1370
 
        """Return a RemoteBzrDirFormat object if it looks possible."""
1371
 
        try:
1372
 
            medium = transport.get_smart_medium()
1373
 
        except (NotImplementedError, AttributeError,
1374
 
                errors.TransportNotPossible, errors.NoSmartMedium,
1375
 
                errors.SmartProtocolError):
1376
 
            # no smart server, so not a branch for this format type.
1377
 
            raise errors.NotBranchError(path=transport.base)
1378
 
        else:
1379
 
            # Decline to open it if the server doesn't support our required
1380
 
            # version (3) so that the VFS-based transport will do it.
1381
 
            if medium.should_probe():
1382
 
                try:
1383
 
                    server_version = medium.protocol_version()
1384
 
                except errors.SmartProtocolError:
1385
 
                    # Apparently there's no usable smart server there, even though
1386
 
                    # the medium supports the smart protocol.
1387
 
                    raise errors.NotBranchError(path=transport.base)
1388
 
                if server_version != '2':
1389
 
                    raise errors.NotBranchError(path=transport.base)
1390
 
            from bzrlib.remote import RemoteBzrDirFormat
1391
 
            return RemoteBzrDirFormat()
1392
 
 
1393
 
    @classmethod
1394
 
    def known_formats(cls):
1395
 
        from bzrlib.remote import RemoteBzrDirFormat
1396
 
        return set([RemoteBzrDirFormat()])
1397
 
 
1398
 
 
1399
 
class BzrDirFormat(controldir.ControlDirFormat):
1400
 
    """ControlDirFormat base class for .bzr/ directories.
 
1699
        return config.BzrDirConfig(self.transport)
 
1700
 
 
1701
 
 
1702
class BzrDirFormat(object):
 
1703
    """An encapsulation of the initialization and open routines for a format.
 
1704
 
 
1705
    Formats provide three things:
 
1706
     * An initialization routine,
 
1707
     * a format string,
 
1708
     * an open routine.
1401
1709
 
1402
1710
    Formats are placed in a dict by their format string for reference
1403
1711
    during bzrdir opening. These should be subclasses of BzrDirFormat
1408
1716
    object will be created every system load.
1409
1717
    """
1410
1718
 
 
1719
    _default_format = None
 
1720
    """The default format used for new .bzr dirs."""
 
1721
 
 
1722
    _formats = {}
 
1723
    """The known formats."""
 
1724
 
 
1725
    _control_formats = []
 
1726
    """The registered control formats - .bzr, ....
 
1727
 
 
1728
    This is a list of BzrDirFormat objects.
 
1729
    """
 
1730
 
 
1731
    _control_server_formats = []
 
1732
    """The registered control server formats, e.g. RemoteBzrDirs.
 
1733
 
 
1734
    This is a list of BzrDirFormat objects.
 
1735
    """
 
1736
 
1411
1737
    _lock_file_name = 'branch-lock'
1412
1738
 
1413
1739
    # _lock_class must be set in subclasses to the lock type, typ.
1414
1740
    # TransportLock or LockDir
1415
1741
 
1416
1742
    @classmethod
1417
 
    def get_format_string(cls):
 
1743
    def find_format(klass, transport, _server_formats=True):
 
1744
        """Return the format present at transport."""
 
1745
        if _server_formats:
 
1746
            formats = klass._control_server_formats + klass._control_formats
 
1747
        else:
 
1748
            formats = klass._control_formats
 
1749
        for format in formats:
 
1750
            try:
 
1751
                return format.probe_transport(transport)
 
1752
            except errors.NotBranchError:
 
1753
                # this format does not find a control dir here.
 
1754
                pass
 
1755
        raise errors.NotBranchError(path=transport.base)
 
1756
 
 
1757
    @classmethod
 
1758
    def probe_transport(klass, transport):
 
1759
        """Return the .bzrdir style format present in a directory."""
 
1760
        try:
 
1761
            format_string = transport.get(".bzr/branch-format").read()
 
1762
        except errors.NoSuchFile:
 
1763
            raise errors.NotBranchError(path=transport.base)
 
1764
 
 
1765
        try:
 
1766
            return klass._formats[format_string]
 
1767
        except KeyError:
 
1768
            raise errors.UnknownFormatError(format=format_string, kind='bzrdir')
 
1769
 
 
1770
    @classmethod
 
1771
    def get_default_format(klass):
 
1772
        """Return the current default format."""
 
1773
        return klass._default_format
 
1774
 
 
1775
    def get_format_string(self):
1418
1776
        """Return the ASCII format string that identifies this format."""
1419
 
        raise NotImplementedError(cls.get_format_string)
 
1777
        raise NotImplementedError(self.get_format_string)
 
1778
 
 
1779
    def get_format_description(self):
 
1780
        """Return the short description for this format."""
 
1781
        raise NotImplementedError(self.get_format_description)
 
1782
 
 
1783
    def get_converter(self, format=None):
 
1784
        """Return the converter to use to convert bzrdirs needing converts.
 
1785
 
 
1786
        This returns a bzrlib.bzrdir.Converter object.
 
1787
 
 
1788
        This should return the best upgrader to step this format towards the
 
1789
        current default format. In the case of plugins we can/should provide
 
1790
        some means for them to extend the range of returnable converters.
 
1791
 
 
1792
        :param format: Optional format to override the default format of the
 
1793
                       library.
 
1794
        """
 
1795
        raise NotImplementedError(self.get_converter)
 
1796
 
 
1797
    def initialize(self, url, possible_transports=None):
 
1798
        """Create a bzr control dir at this url and return an opened copy.
 
1799
 
 
1800
        Subclasses should typically override initialize_on_transport
 
1801
        instead of this method.
 
1802
        """
 
1803
        return self.initialize_on_transport(get_transport(url,
 
1804
                                                          possible_transports))
1420
1805
 
1421
1806
    def initialize_on_transport(self, transport):
1422
1807
        """Initialize a new bzrdir in the base directory of a Transport."""
1432
1817
            # metadir1
1433
1818
            if type(self) != BzrDirMetaFormat1:
1434
1819
                return self._initialize_on_transport_vfs(transport)
1435
 
            from bzrlib.remote import RemoteBzrDirFormat
1436
1820
            remote_format = RemoteBzrDirFormat()
1437
1821
            self._supply_sub_formats_to(remote_format)
1438
1822
            return remote_format.initialize_on_transport(transport)
1439
1823
 
1440
 
    def initialize_on_transport_ex(self, transport, use_existing_dir=False,
1441
 
        create_prefix=False, force_new_repo=False, stacked_on=None,
1442
 
        stack_on_pwd=None, repo_format_name=None, make_working_trees=None,
1443
 
        shared_repo=False, vfs_only=False):
1444
 
        """Create this format on transport.
1445
 
 
1446
 
        The directory to initialize will be created.
1447
 
 
1448
 
        :param force_new_repo: Do not use a shared repository for the target,
1449
 
                               even if one is available.
1450
 
        :param create_prefix: Create any missing directories leading up to
1451
 
            to_transport.
1452
 
        :param use_existing_dir: Use an existing directory if one exists.
1453
 
        :param stacked_on: A url to stack any created branch on, None to follow
1454
 
            any target stacking policy.
1455
 
        :param stack_on_pwd: If stack_on is relative, the location it is
1456
 
            relative to.
1457
 
        :param repo_format_name: If non-None, a repository will be
1458
 
            made-or-found. Should none be found, or if force_new_repo is True
1459
 
            the repo_format_name is used to select the format of repository to
1460
 
            create.
1461
 
        :param make_working_trees: Control the setting of make_working_trees
1462
 
            for a new shared repository when one is made. None to use whatever
1463
 
            default the format has.
1464
 
        :param shared_repo: Control whether made repositories are shared or
1465
 
            not.
1466
 
        :param vfs_only: If True do not attempt to use a smart server
1467
 
        :return: repo, bzrdir, require_stacking, repository_policy. repo is
1468
 
            None if none was created or found, bzrdir is always valid.
1469
 
            require_stacking is the result of examining the stacked_on
1470
 
            parameter and any stacking policy found for the target.
1471
 
        """
1472
 
        if not vfs_only:
1473
 
            # Try to hand off to a smart server 
1474
 
            try:
1475
 
                client_medium = transport.get_smart_medium()
1476
 
            except errors.NoSmartMedium:
1477
 
                pass
1478
 
            else:
1479
 
                from bzrlib.remote import RemoteBzrDirFormat
1480
 
                # TODO: lookup the local format from a server hint.
1481
 
                remote_dir_format = RemoteBzrDirFormat()
1482
 
                remote_dir_format._network_name = self.network_name()
1483
 
                self._supply_sub_formats_to(remote_dir_format)
1484
 
                return remote_dir_format.initialize_on_transport_ex(transport,
1485
 
                    use_existing_dir=use_existing_dir, create_prefix=create_prefix,
1486
 
                    force_new_repo=force_new_repo, stacked_on=stacked_on,
1487
 
                    stack_on_pwd=stack_on_pwd, repo_format_name=repo_format_name,
1488
 
                    make_working_trees=make_working_trees, shared_repo=shared_repo)
1489
 
        # XXX: Refactor the create_prefix/no_create_prefix code into a
1490
 
        #      common helper function
1491
 
        # The destination may not exist - if so make it according to policy.
1492
 
        def make_directory(transport):
1493
 
            transport.mkdir('.')
1494
 
            return transport
1495
 
        def redirected(transport, e, redirection_notice):
1496
 
            note(redirection_notice)
1497
 
            return transport._redirected_to(e.source, e.target)
1498
 
        try:
1499
 
            transport = do_catching_redirections(make_directory, transport,
1500
 
                redirected)
1501
 
        except errors.FileExists:
1502
 
            if not use_existing_dir:
1503
 
                raise
1504
 
        except errors.NoSuchFile:
1505
 
            if not create_prefix:
1506
 
                raise
1507
 
            transport.create_prefix()
1508
 
 
1509
 
        require_stacking = (stacked_on is not None)
1510
 
        # Now the target directory exists, but doesn't have a .bzr
1511
 
        # directory. So we need to create it, along with any work to create
1512
 
        # all of the dependent branches, etc.
1513
 
 
1514
 
        result = self.initialize_on_transport(transport)
1515
 
        if repo_format_name:
1516
 
            try:
1517
 
                # use a custom format
1518
 
                result._format.repository_format = \
1519
 
                    repository.network_format_registry.get(repo_format_name)
1520
 
            except AttributeError:
1521
 
                # The format didn't permit it to be set.
1522
 
                pass
1523
 
            # A repository is desired, either in-place or shared.
1524
 
            repository_policy = result.determine_repository_policy(
1525
 
                force_new_repo, stacked_on, stack_on_pwd,
1526
 
                require_stacking=require_stacking)
1527
 
            result_repo, is_new_repo = repository_policy.acquire_repository(
1528
 
                make_working_trees, shared_repo)
1529
 
            if not require_stacking and repository_policy._require_stacking:
1530
 
                require_stacking = True
1531
 
                result._format.require_stacking()
1532
 
            result_repo.lock_write()
1533
 
        else:
1534
 
            result_repo = None
1535
 
            repository_policy = None
1536
 
        return result_repo, result, require_stacking, repository_policy
1537
 
 
1538
1824
    def _initialize_on_transport_vfs(self, transport):
1539
1825
        """Initialize a new bzrdir using VFS calls.
1540
1826
 
1557
1843
        utf8_files = [('README',
1558
1844
                       "This is a Bazaar control directory.\n"
1559
1845
                       "Do not change any files in this directory.\n"
1560
 
                       "See http://bazaar.canonical.com/ for more information about Bazaar.\n"),
 
1846
                       "See http://bazaar-vcs.org/ for more information about Bazaar.\n"),
1561
1847
                      ('branch-format', self.get_format_string()),
1562
1848
                      ]
1563
1849
        # NB: no need to escape relative paths that are url safe.
1573
1859
            control_files.unlock()
1574
1860
        return self.open(transport, _found=True)
1575
1861
 
 
1862
    def is_supported(self):
 
1863
        """Is this format supported?
 
1864
 
 
1865
        Supported formats must be initializable and openable.
 
1866
        Unsupported formats may not support initialization or committing or
 
1867
        some other features depending on the reason for not being supported.
 
1868
        """
 
1869
        return True
 
1870
 
 
1871
    def network_name(self):
 
1872
        """A simple byte string uniquely identifying this format for RPC calls.
 
1873
 
 
1874
        Bzr control formats use thir disk format string to identify the format
 
1875
        over the wire. Its possible that other control formats have more
 
1876
        complex detection requirements, so we permit them to use any unique and
 
1877
        immutable string they desire.
 
1878
        """
 
1879
        raise NotImplementedError(self.network_name)
 
1880
 
 
1881
    def same_model(self, target_format):
 
1882
        return (self.repository_format.rich_root_data ==
 
1883
            target_format.rich_root_data)
 
1884
 
 
1885
    @classmethod
 
1886
    def known_formats(klass):
 
1887
        """Return all the known formats.
 
1888
 
 
1889
        Concrete formats should override _known_formats.
 
1890
        """
 
1891
        # There is double indirection here to make sure that control
 
1892
        # formats used by more than one dir format will only be probed
 
1893
        # once. This can otherwise be quite expensive for remote connections.
 
1894
        result = set()
 
1895
        for format in klass._control_formats:
 
1896
            result.update(format._known_formats())
 
1897
        return result
 
1898
 
 
1899
    @classmethod
 
1900
    def _known_formats(klass):
 
1901
        """Return the known format instances for this control format."""
 
1902
        return set(klass._formats.values())
 
1903
 
1576
1904
    def open(self, transport, _found=False):
1577
1905
        """Return an instance of this format for the dir transport points at.
1578
1906
 
1579
1907
        _found is a private parameter, do not use it.
1580
1908
        """
1581
1909
        if not _found:
1582
 
            found_format = controldir.ControlDirFormat.find_format(transport)
 
1910
            found_format = BzrDirFormat.find_format(transport)
1583
1911
            if not isinstance(found_format, self.__class__):
1584
1912
                raise AssertionError("%s was asked to open %s, but it seems to need "
1585
1913
                        "format %s"
1597
1925
        """
1598
1926
        raise NotImplementedError(self._open)
1599
1927
 
 
1928
    @classmethod
 
1929
    def register_format(klass, format):
 
1930
        klass._formats[format.get_format_string()] = format
 
1931
        # bzr native formats have a network name of their format string.
 
1932
        network_format_registry.register(format.get_format_string(), format.__class__)
 
1933
 
 
1934
    @classmethod
 
1935
    def register_control_format(klass, format):
 
1936
        """Register a format that does not use '.bzr' for its control dir.
 
1937
 
 
1938
        TODO: This should be pulled up into a 'ControlDirFormat' base class
 
1939
        which BzrDirFormat can inherit from, and renamed to register_format
 
1940
        there. It has been done without that for now for simplicity of
 
1941
        implementation.
 
1942
        """
 
1943
        klass._control_formats.append(format)
 
1944
 
 
1945
    @classmethod
 
1946
    def register_control_server_format(klass, format):
 
1947
        """Register a control format for client-server environments.
 
1948
 
 
1949
        These formats will be tried before ones registered with
 
1950
        register_control_format.  This gives implementations that decide to the
 
1951
        chance to grab it before anything looks at the contents of the format
 
1952
        file.
 
1953
        """
 
1954
        klass._control_server_formats.append(format)
 
1955
 
 
1956
    @classmethod
 
1957
    def _set_default_format(klass, format):
 
1958
        """Set default format (for testing behavior of defaults only)"""
 
1959
        klass._default_format = format
 
1960
 
 
1961
    def __str__(self):
 
1962
        # Trim the newline
 
1963
        return self.get_format_description().rstrip()
 
1964
 
1600
1965
    def _supply_sub_formats_to(self, other_format):
1601
1966
        """Give other_format the same values for sub formats as this has.
1602
1967
 
1609
1974
        :return: None.
1610
1975
        """
1611
1976
 
 
1977
    @classmethod
 
1978
    def unregister_format(klass, format):
 
1979
        del klass._formats[format.get_format_string()]
 
1980
 
 
1981
    @classmethod
 
1982
    def unregister_control_format(klass, format):
 
1983
        klass._control_formats.remove(format)
 
1984
 
 
1985
 
 
1986
class BzrDirFormat4(BzrDirFormat):
 
1987
    """Bzr dir format 4.
 
1988
 
 
1989
    This format is a combined format for working tree, branch and repository.
 
1990
    It has:
 
1991
     - Format 1 working trees [always]
 
1992
     - Format 4 branches [always]
 
1993
     - Format 4 repositories [always]
 
1994
 
 
1995
    This format is deprecated: it indexes texts using a text it which is
 
1996
    removed in format 5; write support for this format has been removed.
 
1997
    """
 
1998
 
 
1999
    _lock_class = lockable_files.TransportLock
 
2000
 
 
2001
    def get_format_string(self):
 
2002
        """See BzrDirFormat.get_format_string()."""
 
2003
        return "Bazaar-NG branch, format 0.0.4\n"
 
2004
 
 
2005
    def get_format_description(self):
 
2006
        """See BzrDirFormat.get_format_description()."""
 
2007
        return "All-in-one format 4"
 
2008
 
 
2009
    def get_converter(self, format=None):
 
2010
        """See BzrDirFormat.get_converter()."""
 
2011
        # there is one and only one upgrade path here.
 
2012
        return ConvertBzrDir4To5()
 
2013
 
 
2014
    def initialize_on_transport(self, transport):
 
2015
        """Format 4 branches cannot be created."""
 
2016
        raise errors.UninitializableFormat(self)
 
2017
 
 
2018
    def is_supported(self):
 
2019
        """Format 4 is not supported.
 
2020
 
 
2021
        It is not supported because the model changed from 4 to 5 and the
 
2022
        conversion logic is expensive - so doing it on the fly was not
 
2023
        feasible.
 
2024
        """
 
2025
        return False
 
2026
 
 
2027
    def network_name(self):
 
2028
        return self.get_format_string()
 
2029
 
 
2030
    def _open(self, transport):
 
2031
        """See BzrDirFormat._open."""
 
2032
        return BzrDir4(transport, self)
 
2033
 
 
2034
    def __return_repository_format(self):
 
2035
        """Circular import protection."""
 
2036
        from bzrlib.repofmt.weaverepo import RepositoryFormat4
 
2037
        return RepositoryFormat4()
 
2038
    repository_format = property(__return_repository_format)
 
2039
 
 
2040
 
 
2041
class BzrDirFormat5(BzrDirFormat):
 
2042
    """Bzr control format 5.
 
2043
 
 
2044
    This format is a combined format for working tree, branch and repository.
 
2045
    It has:
 
2046
     - Format 2 working trees [always]
 
2047
     - Format 4 branches [always]
 
2048
     - Format 5 repositories [always]
 
2049
       Unhashed stores in the repository.
 
2050
    """
 
2051
 
 
2052
    _lock_class = lockable_files.TransportLock
 
2053
 
 
2054
    def get_format_string(self):
 
2055
        """See BzrDirFormat.get_format_string()."""
 
2056
        return "Bazaar-NG branch, format 5\n"
 
2057
 
 
2058
    def get_branch_format(self):
 
2059
        from bzrlib import branch
 
2060
        return branch.BzrBranchFormat4()
 
2061
 
 
2062
    def get_format_description(self):
 
2063
        """See BzrDirFormat.get_format_description()."""
 
2064
        return "All-in-one format 5"
 
2065
 
 
2066
    def get_converter(self, format=None):
 
2067
        """See BzrDirFormat.get_converter()."""
 
2068
        # there is one and only one upgrade path here.
 
2069
        return ConvertBzrDir5To6()
 
2070
 
 
2071
    def _initialize_for_clone(self, url):
 
2072
        return self.initialize_on_transport(get_transport(url), _cloning=True)
 
2073
 
 
2074
    def initialize_on_transport(self, transport, _cloning=False):
 
2075
        """Format 5 dirs always have working tree, branch and repository.
 
2076
 
 
2077
        Except when they are being cloned.
 
2078
        """
 
2079
        from bzrlib.branch import BzrBranchFormat4
 
2080
        from bzrlib.repofmt.weaverepo import RepositoryFormat5
 
2081
        result = (super(BzrDirFormat5, self).initialize_on_transport(transport))
 
2082
        RepositoryFormat5().initialize(result, _internal=True)
 
2083
        if not _cloning:
 
2084
            branch = BzrBranchFormat4().initialize(result)
 
2085
            result._init_workingtree()
 
2086
        return result
 
2087
 
 
2088
    def network_name(self):
 
2089
        return self.get_format_string()
 
2090
 
 
2091
    def _open(self, transport):
 
2092
        """See BzrDirFormat._open."""
 
2093
        return BzrDir5(transport, self)
 
2094
 
 
2095
    def __return_repository_format(self):
 
2096
        """Circular import protection."""
 
2097
        from bzrlib.repofmt.weaverepo import RepositoryFormat5
 
2098
        return RepositoryFormat5()
 
2099
    repository_format = property(__return_repository_format)
 
2100
 
 
2101
 
 
2102
class BzrDirFormat6(BzrDirFormat):
 
2103
    """Bzr control format 6.
 
2104
 
 
2105
    This format is a combined format for working tree, branch and repository.
 
2106
    It has:
 
2107
     - Format 2 working trees [always]
 
2108
     - Format 4 branches [always]
 
2109
     - Format 6 repositories [always]
 
2110
    """
 
2111
 
 
2112
    _lock_class = lockable_files.TransportLock
 
2113
 
 
2114
    def get_format_string(self):
 
2115
        """See BzrDirFormat.get_format_string()."""
 
2116
        return "Bazaar-NG branch, format 6\n"
 
2117
 
 
2118
    def get_format_description(self):
 
2119
        """See BzrDirFormat.get_format_description()."""
 
2120
        return "All-in-one format 6"
 
2121
 
 
2122
    def get_branch_format(self):
 
2123
        from bzrlib import branch
 
2124
        return branch.BzrBranchFormat4()
 
2125
 
 
2126
    def get_converter(self, format=None):
 
2127
        """See BzrDirFormat.get_converter()."""
 
2128
        # there is one and only one upgrade path here.
 
2129
        return ConvertBzrDir6ToMeta()
 
2130
 
 
2131
    def _initialize_for_clone(self, url):
 
2132
        return self.initialize_on_transport(get_transport(url), _cloning=True)
 
2133
 
 
2134
    def initialize_on_transport(self, transport, _cloning=False):
 
2135
        """Format 6 dirs always have working tree, branch and repository.
 
2136
 
 
2137
        Except when they are being cloned.
 
2138
        """
 
2139
        from bzrlib.branch import BzrBranchFormat4
 
2140
        from bzrlib.repofmt.weaverepo import RepositoryFormat6
 
2141
        result = super(BzrDirFormat6, self).initialize_on_transport(transport)
 
2142
        RepositoryFormat6().initialize(result, _internal=True)
 
2143
        if not _cloning:
 
2144
            branch = BzrBranchFormat4().initialize(result)
 
2145
            result._init_workingtree()
 
2146
        return result
 
2147
 
 
2148
    def network_name(self):
 
2149
        return self.get_format_string()
 
2150
 
 
2151
    def _open(self, transport):
 
2152
        """See BzrDirFormat._open."""
 
2153
        return BzrDir6(transport, self)
 
2154
 
 
2155
    def __return_repository_format(self):
 
2156
        """Circular import protection."""
 
2157
        from bzrlib.repofmt.weaverepo import RepositoryFormat6
 
2158
        return RepositoryFormat6()
 
2159
    repository_format = property(__return_repository_format)
 
2160
 
1612
2161
 
1613
2162
class BzrDirMetaFormat1(BzrDirFormat):
1614
2163
    """Bzr meta control format 1
1615
2164
 
1616
2165
    This is the first format with split out working tree, branch and repository
1617
2166
    disk storage.
1618
 
 
1619
2167
    It has:
1620
 
 
1621
 
    - Format 3 working trees [optional]
1622
 
    - Format 5 branches [optional]
1623
 
    - Format 7 repositories [optional]
 
2168
     - Format 3 working trees [optional]
 
2169
     - Format 5 branches [optional]
 
2170
     - Format 7 repositories [optional]
1624
2171
    """
1625
2172
 
1626
2173
    _lock_class = lockdir.LockDir
1627
2174
 
1628
 
    fixed_components = False
1629
 
 
1630
2175
    def __init__(self):
1631
2176
        self._workingtree_format = None
1632
2177
        self._branch_format = None
1646
2191
 
1647
2192
    def get_branch_format(self):
1648
2193
        if self._branch_format is None:
1649
 
            from bzrlib.branch import format_registry as branch_format_registry
1650
 
            self._branch_format = branch_format_registry.get_default()
 
2194
            from bzrlib.branch import BranchFormat
 
2195
            self._branch_format = BranchFormat.get_default_format()
1651
2196
        return self._branch_format
1652
2197
 
1653
2198
    def set_branch_format(self, format):
1654
2199
        self._branch_format = format
1655
2200
 
1656
 
    def require_stacking(self, stack_on=None, possible_transports=None,
1657
 
            _skip_repo=False):
1658
 
        """We have a request to stack, try to ensure the formats support it.
1659
 
 
1660
 
        :param stack_on: If supplied, it is the URL to a branch that we want to
1661
 
            stack on. Check to see if that format supports stacking before
1662
 
            forcing an upgrade.
1663
 
        """
1664
 
        # Stacking is desired. requested by the target, but does the place it
1665
 
        # points at support stacking? If it doesn't then we should
1666
 
        # not implicitly upgrade. We check this here.
1667
 
        new_repo_format = None
1668
 
        new_branch_format = None
1669
 
 
1670
 
        # a bit of state for get_target_branch so that we don't try to open it
1671
 
        # 2 times, for both repo *and* branch
1672
 
        target = [None, False, None] # target_branch, checked, upgrade anyway
1673
 
        def get_target_branch():
1674
 
            if target[1]:
1675
 
                # We've checked, don't check again
1676
 
                return target
1677
 
            if stack_on is None:
1678
 
                # No target format, that means we want to force upgrading
1679
 
                target[:] = [None, True, True]
1680
 
                return target
1681
 
            try:
1682
 
                target_dir = BzrDir.open(stack_on,
1683
 
                    possible_transports=possible_transports)
1684
 
            except errors.NotBranchError:
1685
 
                # Nothing there, don't change formats
1686
 
                target[:] = [None, True, False]
1687
 
                return target
1688
 
            except errors.JailBreak:
1689
 
                # JailBreak, JFDI and upgrade anyway
1690
 
                target[:] = [None, True, True]
1691
 
                return target
1692
 
            try:
1693
 
                target_branch = target_dir.open_branch()
1694
 
            except errors.NotBranchError:
1695
 
                # No branch, don't upgrade formats
1696
 
                target[:] = [None, True, False]
1697
 
                return target
1698
 
            target[:] = [target_branch, True, False]
1699
 
            return target
1700
 
 
1701
 
        if (not _skip_repo and
1702
 
                 not self.repository_format.supports_external_lookups):
1703
 
            # We need to upgrade the Repository.
1704
 
            target_branch, _, do_upgrade = get_target_branch()
1705
 
            if target_branch is None:
1706
 
                # We don't have a target branch, should we upgrade anyway?
1707
 
                if do_upgrade:
1708
 
                    # stack_on is inaccessible, JFDI.
1709
 
                    # TODO: bad monkey, hard-coded formats...
1710
 
                    if self.repository_format.rich_root_data:
1711
 
                        new_repo_format = knitpack_repo.RepositoryFormatKnitPack5RichRoot()
1712
 
                    else:
1713
 
                        new_repo_format = knitpack_repo.RepositoryFormatKnitPack5()
1714
 
            else:
1715
 
                # If the target already supports stacking, then we know the
1716
 
                # project is already able to use stacking, so auto-upgrade
1717
 
                # for them
1718
 
                new_repo_format = target_branch.repository._format
1719
 
                if not new_repo_format.supports_external_lookups:
1720
 
                    # target doesn't, source doesn't, so don't auto upgrade
1721
 
                    # repo
1722
 
                    new_repo_format = None
1723
 
            if new_repo_format is not None:
1724
 
                self.repository_format = new_repo_format
1725
 
                note('Source repository format does not support stacking,'
1726
 
                     ' using format:\n  %s',
1727
 
                     new_repo_format.get_format_description())
1728
 
 
 
2201
    def require_stacking(self):
1729
2202
        if not self.get_branch_format().supports_stacking():
1730
 
            # We just checked the repo, now lets check if we need to
1731
 
            # upgrade the branch format
1732
 
            target_branch, _, do_upgrade = get_target_branch()
1733
 
            if target_branch is None:
1734
 
                if do_upgrade:
1735
 
                    # TODO: bad monkey, hard-coded formats...
1736
 
                    from bzrlib.branch import BzrBranchFormat7
1737
 
                    new_branch_format = BzrBranchFormat7()
 
2203
            # We need to make a stacked branch, but the default format for the
 
2204
            # target doesn't support stacking.  So force a branch that *can*
 
2205
            # support stacking.
 
2206
            from bzrlib.branch import BzrBranchFormat7
 
2207
            branch_format = BzrBranchFormat7()
 
2208
            self.set_branch_format(branch_format)
 
2209
            mutter("using %r for stacking" % (branch_format,))
 
2210
            from bzrlib.repofmt import pack_repo
 
2211
            if self.repository_format.rich_root_data:
 
2212
                bzrdir_format_name = '1.6.1-rich-root'
 
2213
                repo_format = pack_repo.RepositoryFormatKnitPack5RichRoot()
1738
2214
            else:
1739
 
                new_branch_format = target_branch._format
1740
 
                if not new_branch_format.supports_stacking():
1741
 
                    new_branch_format = None
1742
 
            if new_branch_format is not None:
1743
 
                # Does support stacking, use its format.
1744
 
                self.set_branch_format(new_branch_format)
1745
 
                note('Source branch format does not support stacking,'
1746
 
                     ' using format:\n  %s',
1747
 
                     new_branch_format.get_format_description())
 
2215
                bzrdir_format_name = '1.6'
 
2216
                repo_format = pack_repo.RepositoryFormatKnitPack5()
 
2217
            note('Source format does not support stacking, using format:'
 
2218
                 ' \'%s\'\n  %s\n',
 
2219
                 bzrdir_format_name, repo_format.get_format_description())
 
2220
            self.repository_format = repo_format
1748
2221
 
1749
2222
    def get_converter(self, format=None):
1750
2223
        """See BzrDirFormat.get_converter()."""
1755
2228
            raise NotImplementedError(self.get_converter)
1756
2229
        return ConvertMetaToMeta(format)
1757
2230
 
1758
 
    @classmethod
1759
 
    def get_format_string(cls):
 
2231
    def get_format_string(self):
1760
2232
        """See BzrDirFormat.get_format_string()."""
1761
2233
        return "Bazaar-NG meta directory, format 1\n"
1762
2234
 
1769
2241
 
1770
2242
    def _open(self, transport):
1771
2243
        """See BzrDirFormat._open."""
1772
 
        # Create a new format instance because otherwise initialisation of new
1773
 
        # metadirs share the global default format object leading to alias
1774
 
        # problems.
1775
 
        format = BzrDirMetaFormat1()
1776
 
        self._supply_sub_formats_to(format)
1777
 
        return BzrDirMeta1(transport, format)
 
2244
        return BzrDirMeta1(transport, self)
1778
2245
 
1779
2246
    def __return_repository_format(self):
1780
2247
        """Circular import protection."""
1781
2248
        if self._repository_format:
1782
2249
            return self._repository_format
1783
 
        from bzrlib.repository import format_registry
1784
 
        return format_registry.get_default()
 
2250
        from bzrlib.repository import RepositoryFormat
 
2251
        return RepositoryFormat.get_default_format()
1785
2252
 
1786
2253
    def _set_repository_format(self, value):
1787
2254
        """Allow changing the repository format for metadir formats."""
1810
2277
 
1811
2278
    def __get_workingtree_format(self):
1812
2279
        if self._workingtree_format is None:
1813
 
            from bzrlib.workingtree import (
1814
 
                format_registry as wt_format_registry,
1815
 
                )
1816
 
            self._workingtree_format = wt_format_registry.get_default()
 
2280
            from bzrlib.workingtree import WorkingTreeFormat
 
2281
            self._workingtree_format = WorkingTreeFormat.get_default_format()
1817
2282
        return self._workingtree_format
1818
2283
 
1819
2284
    def __set_workingtree_format(self, wt_format):
1823
2288
                                  __set_workingtree_format)
1824
2289
 
1825
2290
 
 
2291
network_format_registry = registry.FormatRegistry()
 
2292
"""Registry of formats indexed by their network name.
 
2293
 
 
2294
The network name for a BzrDirFormat is an identifier that can be used when
 
2295
referring to formats with smart server operations. See
 
2296
BzrDirFormat.network_name() for more detail.
 
2297
"""
 
2298
 
 
2299
 
 
2300
# Register bzr control format
 
2301
BzrDirFormat.register_control_format(BzrDirFormat)
 
2302
 
1826
2303
# Register bzr formats
1827
 
BzrProber.formats.register(BzrDirMetaFormat1.get_format_string(),
1828
 
    BzrDirMetaFormat1)
1829
 
controldir.ControlDirFormat._default_format = BzrDirMetaFormat1()
1830
 
 
1831
 
 
1832
 
class ConvertMetaToMeta(controldir.Converter):
 
2304
BzrDirFormat.register_format(BzrDirFormat4())
 
2305
BzrDirFormat.register_format(BzrDirFormat5())
 
2306
BzrDirFormat.register_format(BzrDirFormat6())
 
2307
__default_format = BzrDirMetaFormat1()
 
2308
BzrDirFormat.register_format(__default_format)
 
2309
BzrDirFormat._default_format = __default_format
 
2310
 
 
2311
 
 
2312
class Converter(object):
 
2313
    """Converts a disk format object from one format to another."""
 
2314
 
 
2315
    def convert(self, to_convert, pb):
 
2316
        """Perform the conversion of to_convert, giving feedback via pb.
 
2317
 
 
2318
        :param to_convert: The disk object to convert.
 
2319
        :param pb: a progress bar to use for progress information.
 
2320
        """
 
2321
 
 
2322
    def step(self, message):
 
2323
        """Update the pb by a step."""
 
2324
        self.count +=1
 
2325
        self.pb.update(message, self.count, self.total)
 
2326
 
 
2327
 
 
2328
class ConvertBzrDir4To5(Converter):
 
2329
    """Converts format 4 bzr dirs to format 5."""
 
2330
 
 
2331
    def __init__(self):
 
2332
        super(ConvertBzrDir4To5, self).__init__()
 
2333
        self.converted_revs = set()
 
2334
        self.absent_revisions = set()
 
2335
        self.text_count = 0
 
2336
        self.revisions = {}
 
2337
 
 
2338
    def convert(self, to_convert, pb):
 
2339
        """See Converter.convert()."""
 
2340
        self.bzrdir = to_convert
 
2341
        self.pb = pb
 
2342
        self.pb.note('starting upgrade from format 4 to 5')
 
2343
        if isinstance(self.bzrdir.transport, local.LocalTransport):
 
2344
            self.bzrdir.get_workingtree_transport(None).delete('stat-cache')
 
2345
        self._convert_to_weaves()
 
2346
        return BzrDir.open(self.bzrdir.root_transport.base)
 
2347
 
 
2348
    def _convert_to_weaves(self):
 
2349
        self.pb.note('note: upgrade may be faster if all store files are ungzipped first')
 
2350
        try:
 
2351
            # TODO permissions
 
2352
            stat = self.bzrdir.transport.stat('weaves')
 
2353
            if not S_ISDIR(stat.st_mode):
 
2354
                self.bzrdir.transport.delete('weaves')
 
2355
                self.bzrdir.transport.mkdir('weaves')
 
2356
        except errors.NoSuchFile:
 
2357
            self.bzrdir.transport.mkdir('weaves')
 
2358
        # deliberately not a WeaveFile as we want to build it up slowly.
 
2359
        self.inv_weave = Weave('inventory')
 
2360
        # holds in-memory weaves for all files
 
2361
        self.text_weaves = {}
 
2362
        self.bzrdir.transport.delete('branch-format')
 
2363
        self.branch = self.bzrdir.open_branch()
 
2364
        self._convert_working_inv()
 
2365
        rev_history = self.branch.revision_history()
 
2366
        # to_read is a stack holding the revisions we still need to process;
 
2367
        # appending to it adds new highest-priority revisions
 
2368
        self.known_revisions = set(rev_history)
 
2369
        self.to_read = rev_history[-1:]
 
2370
        while self.to_read:
 
2371
            rev_id = self.to_read.pop()
 
2372
            if (rev_id not in self.revisions
 
2373
                and rev_id not in self.absent_revisions):
 
2374
                self._load_one_rev(rev_id)
 
2375
        self.pb.clear()
 
2376
        to_import = self._make_order()
 
2377
        for i, rev_id in enumerate(to_import):
 
2378
            self.pb.update('converting revision', i, len(to_import))
 
2379
            self._convert_one_rev(rev_id)
 
2380
        self.pb.clear()
 
2381
        self._write_all_weaves()
 
2382
        self._write_all_revs()
 
2383
        self.pb.note('upgraded to weaves:')
 
2384
        self.pb.note('  %6d revisions and inventories', len(self.revisions))
 
2385
        self.pb.note('  %6d revisions not present', len(self.absent_revisions))
 
2386
        self.pb.note('  %6d texts', self.text_count)
 
2387
        self._cleanup_spare_files_after_format4()
 
2388
        self.branch._transport.put_bytes(
 
2389
            'branch-format',
 
2390
            BzrDirFormat5().get_format_string(),
 
2391
            mode=self.bzrdir._get_file_mode())
 
2392
 
 
2393
    def _cleanup_spare_files_after_format4(self):
 
2394
        # FIXME working tree upgrade foo.
 
2395
        for n in 'merged-patches', 'pending-merged-patches':
 
2396
            try:
 
2397
                ## assert os.path.getsize(p) == 0
 
2398
                self.bzrdir.transport.delete(n)
 
2399
            except errors.NoSuchFile:
 
2400
                pass
 
2401
        self.bzrdir.transport.delete_tree('inventory-store')
 
2402
        self.bzrdir.transport.delete_tree('text-store')
 
2403
 
 
2404
    def _convert_working_inv(self):
 
2405
        inv = xml4.serializer_v4.read_inventory(
 
2406
                self.branch._transport.get('inventory'))
 
2407
        new_inv_xml = xml5.serializer_v5.write_inventory_to_string(inv, working=True)
 
2408
        self.branch._transport.put_bytes('inventory', new_inv_xml,
 
2409
            mode=self.bzrdir._get_file_mode())
 
2410
 
 
2411
    def _write_all_weaves(self):
 
2412
        controlweaves = WeaveStore(self.bzrdir.transport, prefixed=False)
 
2413
        weave_transport = self.bzrdir.transport.clone('weaves')
 
2414
        weaves = WeaveStore(weave_transport, prefixed=False)
 
2415
        transaction = WriteTransaction()
 
2416
 
 
2417
        try:
 
2418
            i = 0
 
2419
            for file_id, file_weave in self.text_weaves.items():
 
2420
                self.pb.update('writing weave', i, len(self.text_weaves))
 
2421
                weaves._put_weave(file_id, file_weave, transaction)
 
2422
                i += 1
 
2423
            self.pb.update('inventory', 0, 1)
 
2424
            controlweaves._put_weave('inventory', self.inv_weave, transaction)
 
2425
            self.pb.update('inventory', 1, 1)
 
2426
        finally:
 
2427
            self.pb.clear()
 
2428
 
 
2429
    def _write_all_revs(self):
 
2430
        """Write all revisions out in new form."""
 
2431
        self.bzrdir.transport.delete_tree('revision-store')
 
2432
        self.bzrdir.transport.mkdir('revision-store')
 
2433
        revision_transport = self.bzrdir.transport.clone('revision-store')
 
2434
        # TODO permissions
 
2435
        from bzrlib.xml5 import serializer_v5
 
2436
        from bzrlib.repofmt.weaverepo import RevisionTextStore
 
2437
        revision_store = RevisionTextStore(revision_transport,
 
2438
            serializer_v5, False, versionedfile.PrefixMapper(),
 
2439
            lambda:True, lambda:True)
 
2440
        try:
 
2441
            for i, rev_id in enumerate(self.converted_revs):
 
2442
                self.pb.update('write revision', i, len(self.converted_revs))
 
2443
                text = serializer_v5.write_revision_to_string(
 
2444
                    self.revisions[rev_id])
 
2445
                key = (rev_id,)
 
2446
                revision_store.add_lines(key, None, osutils.split_lines(text))
 
2447
        finally:
 
2448
            self.pb.clear()
 
2449
 
 
2450
    def _load_one_rev(self, rev_id):
 
2451
        """Load a revision object into memory.
 
2452
 
 
2453
        Any parents not either loaded or abandoned get queued to be
 
2454
        loaded."""
 
2455
        self.pb.update('loading revision',
 
2456
                       len(self.revisions),
 
2457
                       len(self.known_revisions))
 
2458
        if not self.branch.repository.has_revision(rev_id):
 
2459
            self.pb.clear()
 
2460
            self.pb.note('revision {%s} not present in branch; '
 
2461
                         'will be converted as a ghost',
 
2462
                         rev_id)
 
2463
            self.absent_revisions.add(rev_id)
 
2464
        else:
 
2465
            rev = self.branch.repository.get_revision(rev_id)
 
2466
            for parent_id in rev.parent_ids:
 
2467
                self.known_revisions.add(parent_id)
 
2468
                self.to_read.append(parent_id)
 
2469
            self.revisions[rev_id] = rev
 
2470
 
 
2471
    def _load_old_inventory(self, rev_id):
 
2472
        old_inv_xml = self.branch.repository.inventory_store.get(rev_id).read()
 
2473
        inv = xml4.serializer_v4.read_inventory_from_string(old_inv_xml)
 
2474
        inv.revision_id = rev_id
 
2475
        rev = self.revisions[rev_id]
 
2476
        return inv
 
2477
 
 
2478
    def _load_updated_inventory(self, rev_id):
 
2479
        inv_xml = self.inv_weave.get_text(rev_id)
 
2480
        inv = xml5.serializer_v5.read_inventory_from_string(inv_xml, rev_id)
 
2481
        return inv
 
2482
 
 
2483
    def _convert_one_rev(self, rev_id):
 
2484
        """Convert revision and all referenced objects to new format."""
 
2485
        rev = self.revisions[rev_id]
 
2486
        inv = self._load_old_inventory(rev_id)
 
2487
        present_parents = [p for p in rev.parent_ids
 
2488
                           if p not in self.absent_revisions]
 
2489
        self._convert_revision_contents(rev, inv, present_parents)
 
2490
        self._store_new_inv(rev, inv, present_parents)
 
2491
        self.converted_revs.add(rev_id)
 
2492
 
 
2493
    def _store_new_inv(self, rev, inv, present_parents):
 
2494
        new_inv_xml = xml5.serializer_v5.write_inventory_to_string(inv)
 
2495
        new_inv_sha1 = sha_string(new_inv_xml)
 
2496
        self.inv_weave.add_lines(rev.revision_id,
 
2497
                                 present_parents,
 
2498
                                 new_inv_xml.splitlines(True))
 
2499
        rev.inventory_sha1 = new_inv_sha1
 
2500
 
 
2501
    def _convert_revision_contents(self, rev, inv, present_parents):
 
2502
        """Convert all the files within a revision.
 
2503
 
 
2504
        Also upgrade the inventory to refer to the text revision ids."""
 
2505
        rev_id = rev.revision_id
 
2506
        mutter('converting texts of revision {%s}',
 
2507
               rev_id)
 
2508
        parent_invs = map(self._load_updated_inventory, present_parents)
 
2509
        entries = inv.iter_entries()
 
2510
        entries.next()
 
2511
        for path, ie in entries:
 
2512
            self._convert_file_version(rev, ie, parent_invs)
 
2513
 
 
2514
    def _convert_file_version(self, rev, ie, parent_invs):
 
2515
        """Convert one version of one file.
 
2516
 
 
2517
        The file needs to be added into the weave if it is a merge
 
2518
        of >=2 parents or if it's changed from its parent.
 
2519
        """
 
2520
        file_id = ie.file_id
 
2521
        rev_id = rev.revision_id
 
2522
        w = self.text_weaves.get(file_id)
 
2523
        if w is None:
 
2524
            w = Weave(file_id)
 
2525
            self.text_weaves[file_id] = w
 
2526
        text_changed = False
 
2527
        parent_candiate_entries = ie.parent_candidates(parent_invs)
 
2528
        heads = graph.Graph(self).heads(parent_candiate_entries.keys())
 
2529
        # XXX: Note that this is unordered - and this is tolerable because
 
2530
        # the previous code was also unordered.
 
2531
        previous_entries = dict((head, parent_candiate_entries[head]) for head
 
2532
            in heads)
 
2533
        self.snapshot_ie(previous_entries, ie, w, rev_id)
 
2534
        del ie.text_id
 
2535
 
 
2536
    def get_parent_map(self, revision_ids):
 
2537
        """See graph._StackedParentsProvider.get_parent_map"""
 
2538
        return dict((revision_id, self.revisions[revision_id])
 
2539
                    for revision_id in revision_ids
 
2540
                     if revision_id in self.revisions)
 
2541
 
 
2542
    def snapshot_ie(self, previous_revisions, ie, w, rev_id):
 
2543
        # TODO: convert this logic, which is ~= snapshot to
 
2544
        # a call to:. This needs the path figured out. rather than a work_tree
 
2545
        # a v4 revision_tree can be given, or something that looks enough like
 
2546
        # one to give the file content to the entry if it needs it.
 
2547
        # and we need something that looks like a weave store for snapshot to
 
2548
        # save against.
 
2549
        #ie.snapshot(rev, PATH, previous_revisions, REVISION_TREE, InMemoryWeaveStore(self.text_weaves))
 
2550
        if len(previous_revisions) == 1:
 
2551
            previous_ie = previous_revisions.values()[0]
 
2552
            if ie._unchanged(previous_ie):
 
2553
                ie.revision = previous_ie.revision
 
2554
                return
 
2555
        if ie.has_text():
 
2556
            text = self.branch.repository._text_store.get(ie.text_id)
 
2557
            file_lines = text.readlines()
 
2558
            w.add_lines(rev_id, previous_revisions, file_lines)
 
2559
            self.text_count += 1
 
2560
        else:
 
2561
            w.add_lines(rev_id, previous_revisions, [])
 
2562
        ie.revision = rev_id
 
2563
 
 
2564
    def _make_order(self):
 
2565
        """Return a suitable order for importing revisions.
 
2566
 
 
2567
        The order must be such that an revision is imported after all
 
2568
        its (present) parents.
 
2569
        """
 
2570
        todo = set(self.revisions.keys())
 
2571
        done = self.absent_revisions.copy()
 
2572
        order = []
 
2573
        while todo:
 
2574
            # scan through looking for a revision whose parents
 
2575
            # are all done
 
2576
            for rev_id in sorted(list(todo)):
 
2577
                rev = self.revisions[rev_id]
 
2578
                parent_ids = set(rev.parent_ids)
 
2579
                if parent_ids.issubset(done):
 
2580
                    # can take this one now
 
2581
                    order.append(rev_id)
 
2582
                    todo.remove(rev_id)
 
2583
                    done.add(rev_id)
 
2584
        return order
 
2585
 
 
2586
 
 
2587
class ConvertBzrDir5To6(Converter):
 
2588
    """Converts format 5 bzr dirs to format 6."""
 
2589
 
 
2590
    def convert(self, to_convert, pb):
 
2591
        """See Converter.convert()."""
 
2592
        self.bzrdir = to_convert
 
2593
        self.pb = pb
 
2594
        self.pb.note('starting upgrade from format 5 to 6')
 
2595
        self._convert_to_prefixed()
 
2596
        return BzrDir.open(self.bzrdir.root_transport.base)
 
2597
 
 
2598
    def _convert_to_prefixed(self):
 
2599
        from bzrlib.store import TransportStore
 
2600
        self.bzrdir.transport.delete('branch-format')
 
2601
        for store_name in ["weaves", "revision-store"]:
 
2602
            self.pb.note("adding prefixes to %s" % store_name)
 
2603
            store_transport = self.bzrdir.transport.clone(store_name)
 
2604
            store = TransportStore(store_transport, prefixed=True)
 
2605
            for urlfilename in store_transport.list_dir('.'):
 
2606
                filename = urlutils.unescape(urlfilename)
 
2607
                if (filename.endswith(".weave") or
 
2608
                    filename.endswith(".gz") or
 
2609
                    filename.endswith(".sig")):
 
2610
                    file_id, suffix = os.path.splitext(filename)
 
2611
                else:
 
2612
                    file_id = filename
 
2613
                    suffix = ''
 
2614
                new_name = store._mapper.map((file_id,)) + suffix
 
2615
                # FIXME keep track of the dirs made RBC 20060121
 
2616
                try:
 
2617
                    store_transport.move(filename, new_name)
 
2618
                except errors.NoSuchFile: # catches missing dirs strangely enough
 
2619
                    store_transport.mkdir(osutils.dirname(new_name))
 
2620
                    store_transport.move(filename, new_name)
 
2621
        self.bzrdir.transport.put_bytes(
 
2622
            'branch-format',
 
2623
            BzrDirFormat6().get_format_string(),
 
2624
            mode=self.bzrdir._get_file_mode())
 
2625
 
 
2626
 
 
2627
class ConvertBzrDir6ToMeta(Converter):
 
2628
    """Converts format 6 bzr dirs to metadirs."""
 
2629
 
 
2630
    def convert(self, to_convert, pb):
 
2631
        """See Converter.convert()."""
 
2632
        from bzrlib.repofmt.weaverepo import RepositoryFormat7
 
2633
        from bzrlib.branch import BzrBranchFormat5
 
2634
        self.bzrdir = to_convert
 
2635
        self.pb = pb
 
2636
        self.count = 0
 
2637
        self.total = 20 # the steps we know about
 
2638
        self.garbage_inventories = []
 
2639
        self.dir_mode = self.bzrdir._get_dir_mode()
 
2640
        self.file_mode = self.bzrdir._get_file_mode()
 
2641
 
 
2642
        self.pb.note('starting upgrade from format 6 to metadir')
 
2643
        self.bzrdir.transport.put_bytes(
 
2644
                'branch-format',
 
2645
                "Converting to format 6",
 
2646
                mode=self.file_mode)
 
2647
        # its faster to move specific files around than to open and use the apis...
 
2648
        # first off, nuke ancestry.weave, it was never used.
 
2649
        try:
 
2650
            self.step('Removing ancestry.weave')
 
2651
            self.bzrdir.transport.delete('ancestry.weave')
 
2652
        except errors.NoSuchFile:
 
2653
            pass
 
2654
        # find out whats there
 
2655
        self.step('Finding branch files')
 
2656
        last_revision = self.bzrdir.open_branch().last_revision()
 
2657
        bzrcontents = self.bzrdir.transport.list_dir('.')
 
2658
        for name in bzrcontents:
 
2659
            if name.startswith('basis-inventory.'):
 
2660
                self.garbage_inventories.append(name)
 
2661
        # create new directories for repository, working tree and branch
 
2662
        repository_names = [('inventory.weave', True),
 
2663
                            ('revision-store', True),
 
2664
                            ('weaves', True)]
 
2665
        self.step('Upgrading repository  ')
 
2666
        self.bzrdir.transport.mkdir('repository', mode=self.dir_mode)
 
2667
        self.make_lock('repository')
 
2668
        # we hard code the formats here because we are converting into
 
2669
        # the meta format. The meta format upgrader can take this to a
 
2670
        # future format within each component.
 
2671
        self.put_format('repository', RepositoryFormat7())
 
2672
        for entry in repository_names:
 
2673
            self.move_entry('repository', entry)
 
2674
 
 
2675
        self.step('Upgrading branch      ')
 
2676
        self.bzrdir.transport.mkdir('branch', mode=self.dir_mode)
 
2677
        self.make_lock('branch')
 
2678
        self.put_format('branch', BzrBranchFormat5())
 
2679
        branch_files = [('revision-history', True),
 
2680
                        ('branch-name', True),
 
2681
                        ('parent', False)]
 
2682
        for entry in branch_files:
 
2683
            self.move_entry('branch', entry)
 
2684
 
 
2685
        checkout_files = [('pending-merges', True),
 
2686
                          ('inventory', True),
 
2687
                          ('stat-cache', False)]
 
2688
        # If a mandatory checkout file is not present, the branch does not have
 
2689
        # a functional checkout. Do not create a checkout in the converted
 
2690
        # branch.
 
2691
        for name, mandatory in checkout_files:
 
2692
            if mandatory and name not in bzrcontents:
 
2693
                has_checkout = False
 
2694
                break
 
2695
        else:
 
2696
            has_checkout = True
 
2697
        if not has_checkout:
 
2698
            self.pb.note('No working tree.')
 
2699
            # If some checkout files are there, we may as well get rid of them.
 
2700
            for name, mandatory in checkout_files:
 
2701
                if name in bzrcontents:
 
2702
                    self.bzrdir.transport.delete(name)
 
2703
        else:
 
2704
            from bzrlib.workingtree import WorkingTreeFormat3
 
2705
            self.step('Upgrading working tree')
 
2706
            self.bzrdir.transport.mkdir('checkout', mode=self.dir_mode)
 
2707
            self.make_lock('checkout')
 
2708
            self.put_format(
 
2709
                'checkout', WorkingTreeFormat3())
 
2710
            self.bzrdir.transport.delete_multi(
 
2711
                self.garbage_inventories, self.pb)
 
2712
            for entry in checkout_files:
 
2713
                self.move_entry('checkout', entry)
 
2714
            if last_revision is not None:
 
2715
                self.bzrdir.transport.put_bytes(
 
2716
                    'checkout/last-revision', last_revision)
 
2717
        self.bzrdir.transport.put_bytes(
 
2718
            'branch-format',
 
2719
            BzrDirMetaFormat1().get_format_string(),
 
2720
            mode=self.file_mode)
 
2721
        return BzrDir.open(self.bzrdir.root_transport.base)
 
2722
 
 
2723
    def make_lock(self, name):
 
2724
        """Make a lock for the new control dir name."""
 
2725
        self.step('Make %s lock' % name)
 
2726
        ld = lockdir.LockDir(self.bzrdir.transport,
 
2727
                             '%s/lock' % name,
 
2728
                             file_modebits=self.file_mode,
 
2729
                             dir_modebits=self.dir_mode)
 
2730
        ld.create()
 
2731
 
 
2732
    def move_entry(self, new_dir, entry):
 
2733
        """Move then entry name into new_dir."""
 
2734
        name = entry[0]
 
2735
        mandatory = entry[1]
 
2736
        self.step('Moving %s' % name)
 
2737
        try:
 
2738
            self.bzrdir.transport.move(name, '%s/%s' % (new_dir, name))
 
2739
        except errors.NoSuchFile:
 
2740
            if mandatory:
 
2741
                raise
 
2742
 
 
2743
    def put_format(self, dirname, format):
 
2744
        self.bzrdir.transport.put_bytes('%s/format' % dirname,
 
2745
            format.get_format_string(),
 
2746
            self.file_mode)
 
2747
 
 
2748
 
 
2749
class ConvertMetaToMeta(Converter):
1833
2750
    """Converts the components of metadirs."""
1834
2751
 
1835
2752
    def __init__(self, target_format):
1842
2759
    def convert(self, to_convert, pb):
1843
2760
        """See Converter.convert()."""
1844
2761
        self.bzrdir = to_convert
1845
 
        self.pb = ui.ui_factory.nested_progress_bar()
 
2762
        self.pb = pb
1846
2763
        self.count = 0
1847
2764
        self.total = 1
1848
2765
        self.step('checking repository format')
1853
2770
        else:
1854
2771
            if not isinstance(repo._format, self.target_format.repository_format.__class__):
1855
2772
                from bzrlib.repository import CopyConverter
1856
 
                ui.ui_factory.note('starting repository conversion')
 
2773
                self.pb.note('starting repository conversion')
1857
2774
                converter = CopyConverter(self.target_format.repository_format)
1858
2775
                converter.convert(repo, pb)
1859
 
        for branch in self.bzrdir.list_branches():
 
2776
        try:
 
2777
            branch = self.bzrdir.open_branch()
 
2778
        except errors.NotBranchError:
 
2779
            pass
 
2780
        else:
1860
2781
            # TODO: conversions of Branch and Tree should be done by
1861
2782
            # InterXFormat lookups/some sort of registry.
1862
2783
            # Avoid circular imports
 
2784
            from bzrlib import branch as _mod_branch
1863
2785
            old = branch._format.__class__
1864
2786
            new = self.target_format.get_branch_format().__class__
1865
2787
            while old != new:
1866
2788
                if (old == _mod_branch.BzrBranchFormat5 and
1867
2789
                    new in (_mod_branch.BzrBranchFormat6,
1868
 
                        _mod_branch.BzrBranchFormat7,
1869
 
                        _mod_branch.BzrBranchFormat8)):
 
2790
                        _mod_branch.BzrBranchFormat7)):
1870
2791
                    branch_converter = _mod_branch.Converter5to6()
1871
2792
                elif (old == _mod_branch.BzrBranchFormat6 and
1872
 
                    new in (_mod_branch.BzrBranchFormat7,
1873
 
                            _mod_branch.BzrBranchFormat8)):
 
2793
                    new == _mod_branch.BzrBranchFormat7):
1874
2794
                    branch_converter = _mod_branch.Converter6to7()
1875
 
                elif (old == _mod_branch.BzrBranchFormat7 and
1876
 
                      new is _mod_branch.BzrBranchFormat8):
1877
 
                    branch_converter = _mod_branch.Converter7to8()
1878
2795
                else:
1879
 
                    raise errors.BadConversionTarget("No converter", new,
1880
 
                        branch._format)
 
2796
                    raise errors.BadConversionTarget("No converter", new)
1881
2797
                branch_converter.convert(branch)
1882
2798
                branch = self.bzrdir.open_branch()
1883
2799
                old = branch._format.__class__
1888
2804
        else:
1889
2805
            # TODO: conversions of Branch and Tree should be done by
1890
2806
            # InterXFormat lookups
1891
 
            if (isinstance(tree, workingtree_3.WorkingTree3) and
 
2807
            if (isinstance(tree, workingtree.WorkingTree3) and
1892
2808
                not isinstance(tree, workingtree_4.DirStateWorkingTree) and
1893
2809
                isinstance(self.target_format.workingtree_format,
1894
2810
                    workingtree_4.DirStateWorkingTreeFormat)):
1903
2819
                isinstance(self.target_format.workingtree_format,
1904
2820
                    workingtree_4.WorkingTreeFormat6)):
1905
2821
                workingtree_4.Converter4or5to6().convert(tree)
1906
 
        self.pb.finished()
1907
2822
        return to_convert
1908
2823
 
1909
2824
 
1910
 
controldir.ControlDirFormat.register_server_prober(RemoteBzrProber)
 
2825
# This is not in remote.py because it's small, and needs to be registered.
 
2826
# Putting it in remote.py creates a circular import problem.
 
2827
# we can make it a lazy object if the control formats is turned into something
 
2828
# like a registry.
 
2829
class RemoteBzrDirFormat(BzrDirMetaFormat1):
 
2830
    """Format representing bzrdirs accessed via a smart server"""
 
2831
 
 
2832
    def __init__(self):
 
2833
        BzrDirMetaFormat1.__init__(self)
 
2834
        self._network_name = None
 
2835
 
 
2836
    def get_format_description(self):
 
2837
        return 'bzr remote bzrdir'
 
2838
 
 
2839
    def get_format_string(self):
 
2840
        raise NotImplementedError(self.get_format_string)
 
2841
 
 
2842
    def network_name(self):
 
2843
        if self._network_name:
 
2844
            return self._network_name
 
2845
        else:
 
2846
            raise AssertionError("No network name set.")
 
2847
 
 
2848
    @classmethod
 
2849
    def probe_transport(klass, transport):
 
2850
        """Return a RemoteBzrDirFormat object if it looks possible."""
 
2851
        try:
 
2852
            medium = transport.get_smart_medium()
 
2853
        except (NotImplementedError, AttributeError,
 
2854
                errors.TransportNotPossible, errors.NoSmartMedium,
 
2855
                errors.SmartProtocolError):
 
2856
            # no smart server, so not a branch for this format type.
 
2857
            raise errors.NotBranchError(path=transport.base)
 
2858
        else:
 
2859
            # Decline to open it if the server doesn't support our required
 
2860
            # version (3) so that the VFS-based transport will do it.
 
2861
            if medium.should_probe():
 
2862
                try:
 
2863
                    server_version = medium.protocol_version()
 
2864
                except errors.SmartProtocolError:
 
2865
                    # Apparently there's no usable smart server there, even though
 
2866
                    # the medium supports the smart protocol.
 
2867
                    raise errors.NotBranchError(path=transport.base)
 
2868
                if server_version != '2':
 
2869
                    raise errors.NotBranchError(path=transport.base)
 
2870
            return klass()
 
2871
 
 
2872
    def initialize_on_transport(self, transport):
 
2873
        try:
 
2874
            # hand off the request to the smart server
 
2875
            client_medium = transport.get_smart_medium()
 
2876
        except errors.NoSmartMedium:
 
2877
            # TODO: lookup the local format from a server hint.
 
2878
            local_dir_format = BzrDirMetaFormat1()
 
2879
            return local_dir_format.initialize_on_transport(transport)
 
2880
        client = _SmartClient(client_medium)
 
2881
        path = client.remote_path_from_transport(transport)
 
2882
        response = client.call('BzrDirFormat.initialize', path)
 
2883
        if response[0] != 'ok':
 
2884
            raise errors.SmartProtocolError('unexpected response code %s' % (response,))
 
2885
        format = RemoteBzrDirFormat()
 
2886
        self._supply_sub_formats_to(format)
 
2887
        return remote.RemoteBzrDir(transport, format)
 
2888
 
 
2889
    def _open(self, transport):
 
2890
        return remote.RemoteBzrDir(transport, self)
 
2891
 
 
2892
    def __eq__(self, other):
 
2893
        if not isinstance(other, RemoteBzrDirFormat):
 
2894
            return False
 
2895
        return self.get_format_description() == other.get_format_description()
 
2896
 
 
2897
    def __return_repository_format(self):
 
2898
        # Always return a RemoteRepositoryFormat object, but if a specific bzr
 
2899
        # repository format has been asked for, tell the RemoteRepositoryFormat
 
2900
        # that it should use that for init() etc.
 
2901
        result = remote.RemoteRepositoryFormat()
 
2902
        custom_format = getattr(self, '_repository_format', None)
 
2903
        if custom_format:
 
2904
            if isinstance(custom_format, remote.RemoteRepositoryFormat):
 
2905
                return custom_format
 
2906
            else:
 
2907
                # We will use the custom format to create repositories over the
 
2908
                # wire; expose its details like rich_root_data for code to
 
2909
                # query
 
2910
                result._custom_format = custom_format
 
2911
        return result
 
2912
 
 
2913
    def get_branch_format(self):
 
2914
        result = BzrDirMetaFormat1.get_branch_format(self)
 
2915
        if not isinstance(result, remote.RemoteBranchFormat):
 
2916
            new_result = remote.RemoteBranchFormat()
 
2917
            new_result._custom_format = result
 
2918
            # cache the result
 
2919
            self.set_branch_format(new_result)
 
2920
            result = new_result
 
2921
        return result
 
2922
 
 
2923
    repository_format = property(__return_repository_format,
 
2924
        BzrDirMetaFormat1._set_repository_format) #.im_func)
 
2925
 
 
2926
 
 
2927
BzrDirFormat.register_control_server_format(RemoteBzrDirFormat)
 
2928
 
 
2929
 
 
2930
class BzrDirFormatInfo(object):
 
2931
 
 
2932
    def __init__(self, native, deprecated, hidden, experimental):
 
2933
        self.deprecated = deprecated
 
2934
        self.native = native
 
2935
        self.hidden = hidden
 
2936
        self.experimental = experimental
 
2937
 
 
2938
 
 
2939
class BzrDirFormatRegistry(registry.Registry):
 
2940
    """Registry of user-selectable BzrDir subformats.
 
2941
 
 
2942
    Differs from BzrDirFormat._control_formats in that it provides sub-formats,
 
2943
    e.g. BzrDirMeta1 with weave repository.  Also, it's more user-oriented.
 
2944
    """
 
2945
 
 
2946
    def __init__(self):
 
2947
        """Create a BzrDirFormatRegistry."""
 
2948
        self._aliases = set()
 
2949
        self._registration_order = list()
 
2950
        super(BzrDirFormatRegistry, self).__init__()
 
2951
 
 
2952
    def aliases(self):
 
2953
        """Return a set of the format names which are aliases."""
 
2954
        return frozenset(self._aliases)
 
2955
 
 
2956
    def register_metadir(self, key,
 
2957
             repository_format, help, native=True, deprecated=False,
 
2958
             branch_format=None,
 
2959
             tree_format=None,
 
2960
             hidden=False,
 
2961
             experimental=False,
 
2962
             alias=False):
 
2963
        """Register a metadir subformat.
 
2964
 
 
2965
        These all use a BzrDirMetaFormat1 bzrdir, but can be parameterized
 
2966
        by the Repository/Branch/WorkingTreeformats.
 
2967
 
 
2968
        :param repository_format: The fully-qualified repository format class
 
2969
            name as a string.
 
2970
        :param branch_format: Fully-qualified branch format class name as
 
2971
            a string.
 
2972
        :param tree_format: Fully-qualified tree format class name as
 
2973
            a string.
 
2974
        """
 
2975
        # This should be expanded to support setting WorkingTree and Branch
 
2976
        # formats, once BzrDirMetaFormat1 supports that.
 
2977
        def _load(full_name):
 
2978
            mod_name, factory_name = full_name.rsplit('.', 1)
 
2979
            try:
 
2980
                mod = __import__(mod_name, globals(), locals(),
 
2981
                        [factory_name])
 
2982
            except ImportError, e:
 
2983
                raise ImportError('failed to load %s: %s' % (full_name, e))
 
2984
            try:
 
2985
                factory = getattr(mod, factory_name)
 
2986
            except AttributeError:
 
2987
                raise AttributeError('no factory %s in module %r'
 
2988
                    % (full_name, mod))
 
2989
            return factory()
 
2990
 
 
2991
        def helper():
 
2992
            bd = BzrDirMetaFormat1()
 
2993
            if branch_format is not None:
 
2994
                bd.set_branch_format(_load(branch_format))
 
2995
            if tree_format is not None:
 
2996
                bd.workingtree_format = _load(tree_format)
 
2997
            if repository_format is not None:
 
2998
                bd.repository_format = _load(repository_format)
 
2999
            return bd
 
3000
        self.register(key, helper, help, native, deprecated, hidden,
 
3001
            experimental, alias)
 
3002
 
 
3003
    def register(self, key, factory, help, native=True, deprecated=False,
 
3004
                 hidden=False, experimental=False, alias=False):
 
3005
        """Register a BzrDirFormat factory.
 
3006
 
 
3007
        The factory must be a callable that takes one parameter: the key.
 
3008
        It must produce an instance of the BzrDirFormat when called.
 
3009
 
 
3010
        This function mainly exists to prevent the info object from being
 
3011
        supplied directly.
 
3012
        """
 
3013
        registry.Registry.register(self, key, factory, help,
 
3014
            BzrDirFormatInfo(native, deprecated, hidden, experimental))
 
3015
        if alias:
 
3016
            self._aliases.add(key)
 
3017
        self._registration_order.append(key)
 
3018
 
 
3019
    def register_lazy(self, key, module_name, member_name, help, native=True,
 
3020
        deprecated=False, hidden=False, experimental=False, alias=False):
 
3021
        registry.Registry.register_lazy(self, key, module_name, member_name,
 
3022
            help, BzrDirFormatInfo(native, deprecated, hidden, experimental))
 
3023
        if alias:
 
3024
            self._aliases.add(key)
 
3025
        self._registration_order.append(key)
 
3026
 
 
3027
    def set_default(self, key):
 
3028
        """Set the 'default' key to be a clone of the supplied key.
 
3029
 
 
3030
        This method must be called once and only once.
 
3031
        """
 
3032
        registry.Registry.register(self, 'default', self.get(key),
 
3033
            self.get_help(key), info=self.get_info(key))
 
3034
        self._aliases.add('default')
 
3035
 
 
3036
    def set_default_repository(self, key):
 
3037
        """Set the FormatRegistry default and Repository default.
 
3038
 
 
3039
        This is a transitional method while Repository.set_default_format
 
3040
        is deprecated.
 
3041
        """
 
3042
        if 'default' in self:
 
3043
            self.remove('default')
 
3044
        self.set_default(key)
 
3045
        format = self.get('default')()
 
3046
 
 
3047
    def make_bzrdir(self, key):
 
3048
        return self.get(key)()
 
3049
 
 
3050
    def help_topic(self, topic):
 
3051
        output = ""
 
3052
        default_realkey = None
 
3053
        default_help = self.get_help('default')
 
3054
        help_pairs = []
 
3055
        for key in self._registration_order:
 
3056
            if key == 'default':
 
3057
                continue
 
3058
            help = self.get_help(key)
 
3059
            if help == default_help:
 
3060
                default_realkey = key
 
3061
            else:
 
3062
                help_pairs.append((key, help))
 
3063
 
 
3064
        def wrapped(key, help, info):
 
3065
            if info.native:
 
3066
                help = '(native) ' + help
 
3067
            return ':%s:\n%s\n\n' % (key,
 
3068
                    textwrap.fill(help, initial_indent='    ',
 
3069
                    subsequent_indent='    '))
 
3070
        if default_realkey is not None:
 
3071
            output += wrapped(default_realkey, '(default) %s' % default_help,
 
3072
                              self.get_info('default'))
 
3073
        deprecated_pairs = []
 
3074
        experimental_pairs = []
 
3075
        for key, help in help_pairs:
 
3076
            info = self.get_info(key)
 
3077
            if info.hidden:
 
3078
                continue
 
3079
            elif info.deprecated:
 
3080
                deprecated_pairs.append((key, help))
 
3081
            elif info.experimental:
 
3082
                experimental_pairs.append((key, help))
 
3083
            else:
 
3084
                output += wrapped(key, help, info)
 
3085
        output += "\nSee ``bzr help formats`` for more about storage formats."
 
3086
        other_output = ""
 
3087
        if len(experimental_pairs) > 0:
 
3088
            other_output += "Experimental formats are shown below.\n\n"
 
3089
            for key, help in experimental_pairs:
 
3090
                info = self.get_info(key)
 
3091
                other_output += wrapped(key, help, info)
 
3092
        else:
 
3093
            other_output += \
 
3094
                "No experimental formats are available.\n\n"
 
3095
        if len(deprecated_pairs) > 0:
 
3096
            other_output += "\nDeprecated formats are shown below.\n\n"
 
3097
            for key, help in deprecated_pairs:
 
3098
                info = self.get_info(key)
 
3099
                other_output += wrapped(key, help, info)
 
3100
        else:
 
3101
            other_output += \
 
3102
                "\nNo deprecated formats are available.\n\n"
 
3103
        other_output += \
 
3104
            "\nSee ``bzr help formats`` for more about storage formats."
 
3105
 
 
3106
        if topic == 'other-formats':
 
3107
            return other_output
 
3108
        else:
 
3109
            return output
1911
3110
 
1912
3111
 
1913
3112
class RepositoryAcquisitionPolicy(object):
1942
3141
            try:
1943
3142
                stack_on = urlutils.rebase_url(self._stack_on,
1944
3143
                    self._stack_on_pwd,
1945
 
                    branch.user_url)
 
3144
                    branch.bzrdir.root_transport.base)
1946
3145
            except errors.InvalidRebaseURLs:
1947
3146
                stack_on = self._get_full_stack_on()
1948
3147
        try:
1952
3151
            if self._require_stacking:
1953
3152
                raise
1954
3153
 
1955
 
    def requires_stacking(self):
1956
 
        """Return True if this policy requires stacking."""
1957
 
        return self._stack_on is not None and self._require_stacking
1958
 
 
1959
3154
    def _get_full_stack_on(self):
1960
3155
        """Get a fully-qualified URL for the stack_on location."""
1961
3156
        if self._stack_on is None:
1970
3165
        stack_on = self._get_full_stack_on()
1971
3166
        if stack_on is None:
1972
3167
            return
1973
 
        try:
1974
 
            stacked_dir = BzrDir.open(stack_on,
1975
 
                                      possible_transports=possible_transports)
1976
 
        except errors.JailBreak:
1977
 
            # We keep the stacking details, but we are in the server code so
1978
 
            # actually stacking is not needed.
1979
 
            return
 
3168
        stacked_dir = BzrDir.open(stack_on,
 
3169
                                  possible_transports=possible_transports)
1980
3170
        try:
1981
3171
            stacked_repo = stacked_dir.open_branch().repository
1982
3172
        except errors.NotBranchError:
1994
3184
 
1995
3185
        Implementations may create a new repository or use a pre-exising
1996
3186
        repository.
1997
 
 
1998
3187
        :param make_working_trees: If creating a repository, set
1999
3188
            make_working_trees to this value (if non-None)
2000
3189
        :param shared: If creating a repository, make it shared if True
2009
3198
 
2010
3199
    def __init__(self, bzrdir, stack_on=None, stack_on_pwd=None,
2011
3200
                 require_stacking=False):
2012
 
        """Constructor.
2013
 
 
 
3201
        """
 
3202
        Constructor.
2014
3203
        :param bzrdir: The bzrdir to create the repository on.
2015
3204
        :param stack_on: A location to stack on
2016
3205
        :param stack_on_pwd: If stack_on is relative, the location it is
2027
3216
        """
2028
3217
        stack_on = self._get_full_stack_on()
2029
3218
        if stack_on:
 
3219
            # Stacking is desired. requested by the target, but does the place it
 
3220
            # points at support stacking? If it doesn't then we should
 
3221
            # not implicitly upgrade. We check this here.
2030
3222
            format = self._bzrdir._format
2031
 
            format.require_stacking(stack_on=stack_on,
2032
 
                                    possible_transports=[self._bzrdir.root_transport])
 
3223
            if not (format.repository_format.supports_external_lookups
 
3224
                and format.get_branch_format().supports_stacking()):
 
3225
                # May need to upgrade - but only do if the target also
 
3226
                # supports stacking. Note that this currently wastes
 
3227
                # network round trips to check - but we only do this
 
3228
                # when the source can't stack so it will fade away
 
3229
                # as people do upgrade.
 
3230
                try:
 
3231
                    target_dir = BzrDir.open(stack_on,
 
3232
                        possible_transports=[self._bzrdir.root_transport])
 
3233
                except errors.NotBranchError:
 
3234
                    # Nothing there, don't change formats
 
3235
                    pass
 
3236
                else:
 
3237
                    try:
 
3238
                        target_branch = target_dir.open_branch()
 
3239
                    except errors.NotBranchError:
 
3240
                        # No branch, don't change formats
 
3241
                        pass
 
3242
                    else:
 
3243
                        branch_format = target_branch._format
 
3244
                        repo_format = target_branch.repository._format
 
3245
                        if not (branch_format.supports_stacking()
 
3246
                            and repo_format.supports_external_lookups):
 
3247
                            # Doesn't stack itself, don't force an upgrade
 
3248
                            pass
 
3249
                        else:
 
3250
                            # Does support stacking, use its format.
 
3251
                            format.repository_format = repo_format
 
3252
                            format.set_branch_format(branch_format)
 
3253
                            note('Source format does not support stacking, '
 
3254
                                'using format: \'%s\'\n  %s\n',
 
3255
                                branch_format.get_format_description(),
 
3256
                                repo_format.get_format_description())
2033
3257
            if not self._require_stacking:
2034
3258
                # We have picked up automatic stacking somewhere.
2035
3259
                note('Using default stacking branch %s at %s', self._stack_on,
2068
3292
        return self._repository, False
2069
3293
 
2070
3294
 
2071
 
def register_metadir(registry, key,
2072
 
         repository_format, help, native=True, deprecated=False,
2073
 
         branch_format=None,
2074
 
         tree_format=None,
2075
 
         hidden=False,
2076
 
         experimental=False,
2077
 
         alias=False):
2078
 
    """Register a metadir subformat.
2079
 
 
2080
 
    These all use a BzrDirMetaFormat1 bzrdir, but can be parameterized
2081
 
    by the Repository/Branch/WorkingTreeformats.
2082
 
 
2083
 
    :param repository_format: The fully-qualified repository format class
2084
 
        name as a string.
2085
 
    :param branch_format: Fully-qualified branch format class name as
2086
 
        a string.
2087
 
    :param tree_format: Fully-qualified tree format class name as
2088
 
        a string.
2089
 
    """
2090
 
    # This should be expanded to support setting WorkingTree and Branch
2091
 
    # formats, once BzrDirMetaFormat1 supports that.
2092
 
    def _load(full_name):
2093
 
        mod_name, factory_name = full_name.rsplit('.', 1)
2094
 
        try:
2095
 
            factory = pyutils.get_named_object(mod_name, factory_name)
2096
 
        except ImportError, e:
2097
 
            raise ImportError('failed to load %s: %s' % (full_name, e))
2098
 
        except AttributeError:
2099
 
            raise AttributeError('no factory %s in module %r'
2100
 
                % (full_name, sys.modules[mod_name]))
2101
 
        return factory()
2102
 
 
2103
 
    def helper():
2104
 
        bd = BzrDirMetaFormat1()
2105
 
        if branch_format is not None:
2106
 
            bd.set_branch_format(_load(branch_format))
2107
 
        if tree_format is not None:
2108
 
            bd.workingtree_format = _load(tree_format)
2109
 
        if repository_format is not None:
2110
 
            bd.repository_format = _load(repository_format)
2111
 
        return bd
2112
 
    registry.register(key, helper, help, native, deprecated, hidden,
2113
 
        experimental, alias)
2114
 
 
2115
 
register_metadir(controldir.format_registry, 'knit',
 
3295
# Please register new formats after old formats so that formats
 
3296
# appear in chronological order and format descriptions can build
 
3297
# on previous ones.
 
3298
format_registry = BzrDirFormatRegistry()
 
3299
# The pre-0.8 formats have their repository format network name registered in
 
3300
# repository.py. MetaDir formats have their repository format network name
 
3301
# inferred from their disk format string.
 
3302
format_registry.register('weave', BzrDirFormat6,
 
3303
    'Pre-0.8 format.  Slower than knit and does not'
 
3304
    ' support checkouts or shared repositories.',
 
3305
    deprecated=True)
 
3306
format_registry.register_metadir('metaweave',
 
3307
    'bzrlib.repofmt.weaverepo.RepositoryFormat7',
 
3308
    'Transitional format in 0.8.  Slower than knit.',
 
3309
    branch_format='bzrlib.branch.BzrBranchFormat5',
 
3310
    tree_format='bzrlib.workingtree.WorkingTreeFormat3',
 
3311
    deprecated=True)
 
3312
format_registry.register_metadir('knit',
2116
3313
    'bzrlib.repofmt.knitrepo.RepositoryFormatKnit1',
2117
3314
    'Format using knits.  Recommended for interoperation with bzr <= 0.14.',
2118
3315
    branch_format='bzrlib.branch.BzrBranchFormat5',
2119
 
    tree_format='bzrlib.workingtree_3.WorkingTreeFormat3',
2120
 
    hidden=True,
 
3316
    tree_format='bzrlib.workingtree.WorkingTreeFormat3',
2121
3317
    deprecated=True)
2122
 
register_metadir(controldir.format_registry, 'dirstate',
 
3318
format_registry.register_metadir('dirstate',
2123
3319
    'bzrlib.repofmt.knitrepo.RepositoryFormatKnit1',
2124
3320
    help='New in 0.15: Fast local operations. Compatible with bzr 0.8 and '
2125
3321
        'above when accessed over the network.',
2126
3322
    branch_format='bzrlib.branch.BzrBranchFormat5',
2127
 
    tree_format='bzrlib.workingtree_4.WorkingTreeFormat4',
2128
 
    hidden=True,
 
3323
    # this uses bzrlib.workingtree.WorkingTreeFormat4 because importing
 
3324
    # directly from workingtree_4 triggers a circular import.
 
3325
    tree_format='bzrlib.workingtree.WorkingTreeFormat4',
2129
3326
    deprecated=True)
2130
 
register_metadir(controldir.format_registry, 'dirstate-tags',
 
3327
format_registry.register_metadir('dirstate-tags',
2131
3328
    'bzrlib.repofmt.knitrepo.RepositoryFormatKnit1',
2132
3329
    help='New in 0.15: Fast local operations and improved scaling for '
2133
3330
        'network operations. Additionally adds support for tags.'
2134
3331
        ' Incompatible with bzr < 0.15.',
2135
3332
    branch_format='bzrlib.branch.BzrBranchFormat6',
2136
 
    tree_format='bzrlib.workingtree_4.WorkingTreeFormat4',
2137
 
    hidden=True,
 
3333
    tree_format='bzrlib.workingtree.WorkingTreeFormat4',
2138
3334
    deprecated=True)
2139
 
register_metadir(controldir.format_registry, 'rich-root',
 
3335
format_registry.register_metadir('rich-root',
2140
3336
    'bzrlib.repofmt.knitrepo.RepositoryFormatKnit4',
2141
3337
    help='New in 1.0.  Better handling of tree roots.  Incompatible with'
2142
3338
        ' bzr < 1.0.',
2143
3339
    branch_format='bzrlib.branch.BzrBranchFormat6',
2144
 
    tree_format='bzrlib.workingtree_4.WorkingTreeFormat4',
2145
 
    hidden=True,
 
3340
    tree_format='bzrlib.workingtree.WorkingTreeFormat4',
2146
3341
    deprecated=True)
2147
 
register_metadir(controldir.format_registry, 'dirstate-with-subtree',
 
3342
format_registry.register_metadir('dirstate-with-subtree',
2148
3343
    'bzrlib.repofmt.knitrepo.RepositoryFormatKnit3',
2149
3344
    help='New in 0.15: Fast local operations and improved scaling for '
2150
3345
        'network operations. Additionally adds support for versioning nested '
2151
3346
        'bzr branches. Incompatible with bzr < 0.15.',
2152
3347
    branch_format='bzrlib.branch.BzrBranchFormat6',
2153
 
    tree_format='bzrlib.workingtree_4.WorkingTreeFormat4',
 
3348
    tree_format='bzrlib.workingtree.WorkingTreeFormat4',
2154
3349
    experimental=True,
2155
3350
    hidden=True,
2156
3351
    )
2157
 
register_metadir(controldir.format_registry, 'pack-0.92',
2158
 
    'bzrlib.repofmt.knitpack_repo.RepositoryFormatKnitPack1',
 
3352
format_registry.register_metadir('pack-0.92',
 
3353
    'bzrlib.repofmt.pack_repo.RepositoryFormatKnitPack1',
2159
3354
    help='New in 0.92: Pack-based format with data compatible with '
2160
3355
        'dirstate-tags format repositories. Interoperates with '
2161
3356
        'bzr repositories before 0.92 but cannot be read by bzr < 0.92. '
2162
 
        ,
 
3357
        'Previously called knitpack-experimental.  '
 
3358
        'For more information, see '
 
3359
        'http://doc.bazaar-vcs.org/latest/developers/packrepo.html.',
2163
3360
    branch_format='bzrlib.branch.BzrBranchFormat6',
2164
 
    tree_format='bzrlib.workingtree_4.WorkingTreeFormat4',
 
3361
    tree_format='bzrlib.workingtree.WorkingTreeFormat4',
2165
3362
    )
2166
 
register_metadir(controldir.format_registry, 'pack-0.92-subtree',
2167
 
    'bzrlib.repofmt.knitpack_repo.RepositoryFormatKnitPack3',
 
3363
format_registry.register_metadir('pack-0.92-subtree',
 
3364
    'bzrlib.repofmt.pack_repo.RepositoryFormatKnitPack3',
2168
3365
    help='New in 0.92: Pack-based format with data compatible with '
2169
3366
        'dirstate-with-subtree format repositories. Interoperates with '
2170
3367
        'bzr repositories before 0.92 but cannot be read by bzr < 0.92. '
2171
 
        ,
 
3368
        'Previously called knitpack-experimental.  '
 
3369
        'For more information, see '
 
3370
        'http://doc.bazaar-vcs.org/latest/developers/packrepo.html.',
2172
3371
    branch_format='bzrlib.branch.BzrBranchFormat6',
2173
 
    tree_format='bzrlib.workingtree_4.WorkingTreeFormat4',
 
3372
    tree_format='bzrlib.workingtree.WorkingTreeFormat4',
2174
3373
    hidden=True,
2175
3374
    experimental=True,
2176
3375
    )
2177
 
register_metadir(controldir.format_registry, 'rich-root-pack',
2178
 
    'bzrlib.repofmt.knitpack_repo.RepositoryFormatKnitPack4',
 
3376
format_registry.register_metadir('rich-root-pack',
 
3377
    'bzrlib.repofmt.pack_repo.RepositoryFormatKnitPack4',
2179
3378
    help='New in 1.0: A variant of pack-0.92 that supports rich-root data '
2180
3379
         '(needed for bzr-svn and bzr-git).',
2181
3380
    branch_format='bzrlib.branch.BzrBranchFormat6',
2182
 
    tree_format='bzrlib.workingtree_4.WorkingTreeFormat4',
2183
 
    hidden=True,
 
3381
    tree_format='bzrlib.workingtree.WorkingTreeFormat4',
2184
3382
    )
2185
 
register_metadir(controldir.format_registry, '1.6',
2186
 
    'bzrlib.repofmt.knitpack_repo.RepositoryFormatKnitPack5',
 
3383
format_registry.register_metadir('1.6',
 
3384
    'bzrlib.repofmt.pack_repo.RepositoryFormatKnitPack5',
2187
3385
    help='A format that allows a branch to indicate that there is another '
2188
3386
         '(stacked) repository that should be used to access data that is '
2189
3387
         'not present locally.',
2190
3388
    branch_format='bzrlib.branch.BzrBranchFormat7',
2191
 
    tree_format='bzrlib.workingtree_4.WorkingTreeFormat4',
2192
 
    hidden=True,
 
3389
    tree_format='bzrlib.workingtree.WorkingTreeFormat4',
2193
3390
    )
2194
 
register_metadir(controldir.format_registry, '1.6.1-rich-root',
2195
 
    'bzrlib.repofmt.knitpack_repo.RepositoryFormatKnitPack5RichRoot',
 
3391
format_registry.register_metadir('1.6.1-rich-root',
 
3392
    'bzrlib.repofmt.pack_repo.RepositoryFormatKnitPack5RichRoot',
2196
3393
    help='A variant of 1.6 that supports rich-root data '
2197
3394
         '(needed for bzr-svn and bzr-git).',
2198
3395
    branch_format='bzrlib.branch.BzrBranchFormat7',
2199
 
    tree_format='bzrlib.workingtree_4.WorkingTreeFormat4',
2200
 
    hidden=True,
 
3396
    tree_format='bzrlib.workingtree.WorkingTreeFormat4',
2201
3397
    )
2202
 
register_metadir(controldir.format_registry, '1.9',
2203
 
    'bzrlib.repofmt.knitpack_repo.RepositoryFormatKnitPack6',
 
3398
format_registry.register_metadir('1.9',
 
3399
    'bzrlib.repofmt.pack_repo.RepositoryFormatKnitPack6',
2204
3400
    help='A repository format using B+tree indexes. These indexes '
2205
3401
         'are smaller in size, have smarter caching and provide faster '
2206
3402
         'performance for most operations.',
2207
3403
    branch_format='bzrlib.branch.BzrBranchFormat7',
2208
 
    tree_format='bzrlib.workingtree_4.WorkingTreeFormat4',
2209
 
    hidden=True,
 
3404
    tree_format='bzrlib.workingtree.WorkingTreeFormat4',
2210
3405
    )
2211
 
register_metadir(controldir.format_registry, '1.9-rich-root',
2212
 
    'bzrlib.repofmt.knitpack_repo.RepositoryFormatKnitPack6RichRoot',
 
3406
format_registry.register_metadir('1.9-rich-root',
 
3407
    'bzrlib.repofmt.pack_repo.RepositoryFormatKnitPack6RichRoot',
2213
3408
    help='A variant of 1.9 that supports rich-root data '
2214
3409
         '(needed for bzr-svn and bzr-git).',
2215
3410
    branch_format='bzrlib.branch.BzrBranchFormat7',
2216
 
    tree_format='bzrlib.workingtree_4.WorkingTreeFormat4',
2217
 
    hidden=True,
 
3411
    tree_format='bzrlib.workingtree.WorkingTreeFormat4',
2218
3412
    )
2219
 
register_metadir(controldir.format_registry, '1.14',
2220
 
    'bzrlib.repofmt.knitpack_repo.RepositoryFormatKnitPack6',
 
3413
format_registry.register_metadir('1.14',
 
3414
    'bzrlib.repofmt.pack_repo.RepositoryFormatKnitPack6',
2221
3415
    help='A working-tree format that supports content filtering.',
2222
3416
    branch_format='bzrlib.branch.BzrBranchFormat7',
2223
 
    tree_format='bzrlib.workingtree_4.WorkingTreeFormat5',
 
3417
    tree_format='bzrlib.workingtree.WorkingTreeFormat5',
2224
3418
    )
2225
 
register_metadir(controldir.format_registry, '1.14-rich-root',
2226
 
    'bzrlib.repofmt.knitpack_repo.RepositoryFormatKnitPack6RichRoot',
 
3419
format_registry.register_metadir('1.14-rich-root',
 
3420
    'bzrlib.repofmt.pack_repo.RepositoryFormatKnitPack6RichRoot',
2227
3421
    help='A variant of 1.14 that supports rich-root data '
2228
3422
         '(needed for bzr-svn and bzr-git).',
2229
3423
    branch_format='bzrlib.branch.BzrBranchFormat7',
2230
 
    tree_format='bzrlib.workingtree_4.WorkingTreeFormat5',
2231
 
    )
2232
 
# The following un-numbered 'development' formats should always just be aliases.
2233
 
register_metadir(controldir.format_registry, 'development-subtree',
2234
 
    'bzrlib.repofmt.groupcompress_repo.RepositoryFormat2aSubtree',
 
3424
    tree_format='bzrlib.workingtree.WorkingTreeFormat5',
 
3425
    )
 
3426
# The following two formats should always just be aliases.
 
3427
format_registry.register_metadir('development',
 
3428
    'bzrlib.repofmt.pack_repo.RepositoryFormatPackDevelopment2',
 
3429
    help='Current development format. Can convert data to and from pack-0.92 '
 
3430
        '(and anything compatible with pack-0.92) format repositories. '
 
3431
        'Repositories and branches in this format can only be read by bzr.dev. '
 
3432
        'Please read '
 
3433
        'http://doc.bazaar-vcs.org/latest/developers/development-repo.html '
 
3434
        'before use.',
 
3435
    branch_format='bzrlib.branch.BzrBranchFormat7',
 
3436
    tree_format='bzrlib.workingtree.WorkingTreeFormat4',
 
3437
    experimental=True,
 
3438
    alias=True,
 
3439
    )
 
3440
format_registry.register_metadir('development-subtree',
 
3441
    'bzrlib.repofmt.pack_repo.RepositoryFormatPackDevelopment2Subtree',
2235
3442
    help='Current development format, subtree variant. Can convert data to and '
2236
3443
        'from pack-0.92-subtree (and anything compatible with '
2237
3444
        'pack-0.92-subtree) format repositories. Repositories and branches in '
2238
3445
        'this format can only be read by bzr.dev. Please read '
2239
 
        'http://doc.bazaar.canonical.com/latest/developers/development-repo.html '
2240
 
        'before use.',
2241
 
    branch_format='bzrlib.branch.BzrBranchFormat7',
2242
 
    tree_format='bzrlib.workingtree_4.WorkingTreeFormat6',
2243
 
    experimental=True,
2244
 
    hidden=True,
2245
 
    alias=False, # Restore to being an alias when an actual development subtree format is added
2246
 
                 # This current non-alias status is simply because we did not introduce a
2247
 
                 # chk based subtree format.
2248
 
    )
2249
 
register_metadir(controldir.format_registry, 'development5-subtree',
2250
 
    'bzrlib.repofmt.knitpack_repo.RepositoryFormatPackDevelopment2Subtree',
2251
 
    help='Development format, subtree variant. Can convert data to and '
2252
 
        'from pack-0.92-subtree (and anything compatible with '
2253
 
        'pack-0.92-subtree) format repositories. Repositories and branches in '
2254
 
        'this format can only be read by bzr.dev. Please read '
2255
 
        'http://doc.bazaar.canonical.com/latest/developers/development-repo.html '
2256
 
        'before use.',
2257
 
    branch_format='bzrlib.branch.BzrBranchFormat7',
2258
 
    tree_format='bzrlib.workingtree_4.WorkingTreeFormat6',
2259
 
    experimental=True,
2260
 
    hidden=True,
2261
 
    alias=False,
2262
 
    )
2263
 
 
 
3446
        'http://doc.bazaar-vcs.org/latest/developers/development-repo.html '
 
3447
        'before use.',
 
3448
    branch_format='bzrlib.branch.BzrBranchFormat7',
 
3449
    tree_format='bzrlib.workingtree.WorkingTreeFormat4',
 
3450
    experimental=True,
 
3451
    alias=True,
 
3452
    )
2264
3453
# And the development formats above will have aliased one of the following:
2265
 
 
2266
 
# Finally, the current format.
2267
 
register_metadir(controldir.format_registry, '2a',
2268
 
    'bzrlib.repofmt.groupcompress_repo.RepositoryFormat2a',
2269
 
    help='First format for bzr 2.0 series.\n'
2270
 
        'Uses group-compress storage.\n'
2271
 
        'Provides rich roots which are a one-way transition.\n',
2272
 
        # 'storage in packs, 255-way hashed CHK inventory, bencode revision, group compress, '
2273
 
        # 'rich roots. Supported by bzr 1.16 and later.',
2274
 
    branch_format='bzrlib.branch.BzrBranchFormat7',
2275
 
    tree_format='bzrlib.workingtree_4.WorkingTreeFormat6',
2276
 
    experimental=False,
2277
 
    )
2278
 
 
 
3454
format_registry.register_metadir('development2',
 
3455
    'bzrlib.repofmt.pack_repo.RepositoryFormatPackDevelopment2',
 
3456
    help='1.6.1 with B+Tree based index. '
 
3457
        'Please read '
 
3458
        'http://doc.bazaar-vcs.org/latest/developers/development-repo.html '
 
3459
        'before use.',
 
3460
    branch_format='bzrlib.branch.BzrBranchFormat7',
 
3461
    tree_format='bzrlib.workingtree.WorkingTreeFormat4',
 
3462
    hidden=True,
 
3463
    experimental=True,
 
3464
    )
 
3465
format_registry.register_metadir('development2-subtree',
 
3466
    'bzrlib.repofmt.pack_repo.RepositoryFormatPackDevelopment2Subtree',
 
3467
    help='1.6.1-subtree with B+Tree based index. '
 
3468
        'Please read '
 
3469
        'http://doc.bazaar-vcs.org/latest/developers/development-repo.html '
 
3470
        'before use.',
 
3471
    branch_format='bzrlib.branch.BzrBranchFormat7',
 
3472
    tree_format='bzrlib.workingtree.WorkingTreeFormat4',
 
3473
    hidden=True,
 
3474
    experimental=True,
 
3475
    )
 
3476
# These next two formats should be removed when the gc formats are
 
3477
# updated to use WorkingTreeFormat6 and are merged into bzr.dev
 
3478
format_registry.register_metadir('development-wt6',
 
3479
    'bzrlib.repofmt.pack_repo.RepositoryFormatKnitPack6',
 
3480
    help='1.14 with filtered views. '
 
3481
        'Please read '
 
3482
        'http://doc.bazaar-vcs.org/latest/developers/development-repo.html '
 
3483
        'before use.',
 
3484
    branch_format='bzrlib.branch.BzrBranchFormat7',
 
3485
    tree_format='bzrlib.workingtree.WorkingTreeFormat6',
 
3486
    hidden=True,
 
3487
    experimental=True,
 
3488
    )
 
3489
format_registry.register_metadir('development-wt6-rich-root',
 
3490
    'bzrlib.repofmt.pack_repo.RepositoryFormatKnitPack6RichRoot',
 
3491
    help='A variant of development-wt6 that supports rich-root data '
 
3492
         '(needed for bzr-svn and bzr-git).',
 
3493
    branch_format='bzrlib.branch.BzrBranchFormat7',
 
3494
    tree_format='bzrlib.workingtree.WorkingTreeFormat6',
 
3495
    hidden=True,
 
3496
    experimental=True,
 
3497
    )
2279
3498
# The following format should be an alias for the rich root equivalent 
2280
3499
# of the default format
2281
 
register_metadir(controldir.format_registry, 'default-rich-root',
2282
 
    'bzrlib.repofmt.groupcompress_repo.RepositoryFormat2a',
2283
 
    branch_format='bzrlib.branch.BzrBranchFormat7',
2284
 
    tree_format='bzrlib.workingtree_4.WorkingTreeFormat6',
 
3500
format_registry.register_metadir('default-rich-root',
 
3501
    'bzrlib.repofmt.pack_repo.RepositoryFormatKnitPack4',
 
3502
    help='Default format, rich root variant. (needed for bzr-svn and bzr-git).',
 
3503
    branch_format='bzrlib.branch.BzrBranchFormat6',
 
3504
    tree_format='bzrlib.workingtree.WorkingTreeFormat4',
2285
3505
    alias=True,
2286
 
    hidden=True,
2287
 
    help='Same as 2a.')
2288
 
 
 
3506
    )
2289
3507
# The current format that is made on 'bzr init'.
2290
 
format_name = config.GlobalConfig().get_user_option('default_format')
2291
 
if format_name is None:
2292
 
    controldir.format_registry.set_default('2a')
2293
 
else:
2294
 
    controldir.format_registry.set_default(format_name)
2295
 
 
2296
 
# XXX 2010-08-20 JRV: There is still a lot of code relying on
2297
 
# bzrlib.bzrdir.format_registry existing. When BzrDir.create/BzrDir.open/etc
2298
 
# get changed to ControlDir.create/ControlDir.open/etc this should be removed.
2299
 
format_registry = controldir.format_registry
 
3508
format_registry.set_default('pack-0.92')