~bzr-pqm/bzr/bzr.dev

« back to all changes in this revision

Viewing changes to bzrlib/bzrdir.py

  • Committer: Patch Queue Manager
  • Date: 2015-04-21 05:32:33 UTC
  • mfrom: (6602.1.1 bzr.dev)
  • Revision ID: pqm@pqm.ubuntu.com-20150421053233-x63rhby1q3612v2h
(richard-wilbur) (jelmer)Make bzr build reproducible for Debian. (Jelmer
 Vernooij)

Show diffs side-by-side

added added

removed removed

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