~bzr-pqm/bzr/bzr.dev

« back to all changes in this revision

Viewing changes to bzrlib/bzrdir.py

  • Committer: Patch Queue Manager
  • Date: 2013-10-07 17:04:34 UTC
  • mfrom: (6588.1.1 trunk)
  • Revision ID: pqm@pqm.ubuntu.com-20131007170434-mb0ahksmrzsnhi1i
(vila) Stricter checks on configuration option names (Vincent Ladeuil)

Show diffs side-by-side

added added

removed removed

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