~bzr-pqm/bzr/bzr.dev

« back to all changes in this revision

Viewing changes to bzrlib/bzrdir.py

  • Committer: Jelmer Vernooij
  • Date: 2010-12-20 11:57:14 UTC
  • mto: This revision was merged to the branch mainline in revision 5577.
  • Revision ID: jelmer@samba.org-20101220115714-2ru3hfappjweeg7q
Don't use no-plugins.

Show diffs side-by-side

added added

removed removed

Lines of Context:
1
 
# Copyright (C) 2005, 2006, 2007 Canonical Ltd
 
1
# Copyright (C) 2006-2010 Canonical Ltd
2
2
#
3
3
# This program is free software; you can redistribute it and/or modify
4
4
# it under the terms of the GNU General Public License as published by
12
12
#
13
13
# You should have received a copy of the GNU General Public License
14
14
# along with this program; if not, write to the Free Software
15
 
# Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
 
15
# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
16
16
 
17
17
"""BzrDir logic. The BzrDir is the basic control directory used by bzr.
18
18
 
27
27
 
28
28
# TODO: Move old formats into a plugin to make this file smaller.
29
29
 
30
 
from cStringIO import StringIO
31
30
import os
 
31
import sys
 
32
import warnings
32
33
 
33
34
from bzrlib.lazy_import import lazy_import
34
35
lazy_import(globals(), """
35
36
from stat import S_ISDIR
36
 
import textwrap
37
 
from warnings import warn
38
37
 
39
38
import bzrlib
40
39
from bzrlib import (
 
40
    branch,
 
41
    config,
 
42
    controldir,
41
43
    errors,
42
44
    graph,
43
45
    lockable_files,
44
46
    lockdir,
45
 
    registry,
 
47
    osutils,
 
48
    pyutils,
46
49
    remote,
 
50
    repository,
47
51
    revision as _mod_revision,
48
 
    symbol_versioning,
49
52
    ui,
50
53
    urlutils,
 
54
    versionedfile,
 
55
    win32utils,
 
56
    workingtree,
 
57
    workingtree_4,
51
58
    xml4,
52
59
    xml5,
53
 
    workingtree,
54
 
    workingtree_4,
55
60
    )
56
61
from bzrlib.osutils import (
57
 
    sha_strings,
58
62
    sha_string,
59
63
    )
 
64
from bzrlib.push import (
 
65
    PushResult,
 
66
    )
 
67
from bzrlib.repofmt import pack_repo
60
68
from bzrlib.smart.client import _SmartClient
61
 
from bzrlib.smart import protocol
62
 
from bzrlib.store.revision.text import TextRevisionStore
63
 
from bzrlib.store.text import TextStore
64
69
from bzrlib.store.versioned import WeaveStore
65
70
from bzrlib.transactions import WriteTransaction
66
71
from bzrlib.transport import (
67
72
    do_catching_redirections,
68
73
    get_transport,
 
74
    local,
69
75
    )
70
76
from bzrlib.weave import Weave
71
77
""")
73
79
from bzrlib.trace import (
74
80
    mutter,
75
81
    note,
76
 
    )
77
 
from bzrlib.transport.local import LocalTransport
 
82
    warning,
 
83
    )
 
84
 
 
85
from bzrlib import (
 
86
    hooks,
 
87
    registry,
 
88
    symbol_versioning,
 
89
    )
78
90
from bzrlib.symbol_versioning import (
79
 
    deprecated_function,
 
91
    deprecated_in,
80
92
    deprecated_method,
81
 
    zero_ninetyone,
82
93
    )
83
94
 
84
95
 
85
 
class BzrDir(object):
 
96
class BzrDir(controldir.ControlDir):
86
97
    """A .bzr control diretory.
87
 
    
 
98
 
88
99
    BzrDir instances let you create or open any of the things that can be
89
100
    found within .bzr - checkouts, branches and repositories.
90
 
    
91
 
    transport
 
101
 
 
102
    :ivar transport:
92
103
        the transport which this bzr dir is rooted at (i.e. file:///.../.bzr/)
93
 
    root_transport
 
104
    :ivar root_transport:
94
105
        a transport connected to the directory this bzr was opened from
95
106
        (i.e. the parent directory holding the .bzr directory).
 
107
 
 
108
    Everything in the bzrdir should have the same file permissions.
 
109
 
 
110
    :cvar hooks: An instance of BzrDirHooks.
96
111
    """
97
112
 
98
113
    def break_lock(self):
115
130
                    return
116
131
        thing_to_unlock.break_lock()
117
132
 
118
 
    def can_convert_format(self):
119
 
        """Return true if this bzrdir is one whose format we can convert from."""
120
 
        return True
121
 
 
122
133
    def check_conversion_target(self, target_format):
 
134
        """Check that a bzrdir as a whole can be converted to a new format."""
 
135
        # The only current restriction is that the repository content can be 
 
136
        # fetched compatibly with the target.
123
137
        target_repo_format = target_format.repository_format
124
 
        source_repo_format = self._format.repository_format
125
 
        source_repo_format.check_conversion_target(target_repo_format)
 
138
        try:
 
139
            self.open_repository()._format.check_conversion_target(
 
140
                target_repo_format)
 
141
        except errors.NoRepositoryPresent:
 
142
            # No repo, no problem.
 
143
            pass
126
144
 
127
145
    @staticmethod
128
146
    def _check_supported(format, allow_unsupported,
130
148
        basedir=None):
131
149
        """Give an error or warning on old formats.
132
150
 
133
 
        :param format: may be any kind of format - workingtree, branch, 
 
151
        :param format: may be any kind of format - workingtree, branch,
134
152
        or repository.
135
153
 
136
 
        :param allow_unsupported: If true, allow opening 
137
 
        formats that are strongly deprecated, and which may 
 
154
        :param allow_unsupported: If true, allow opening
 
155
        formats that are strongly deprecated, and which may
138
156
        have limited functionality.
139
157
 
140
158
        :param recommend_upgrade: If true (default), warn
152
170
                format.get_format_description(),
153
171
                basedir)
154
172
 
155
 
    def clone(self, url, revision_id=None, force_new_repo=False):
156
 
        """Clone this bzrdir and its contents to url verbatim.
157
 
 
158
 
        If url's last component does not exist, it will be created.
159
 
 
160
 
        if revision_id is not None, then the clone operation may tune
161
 
            itself to download less data.
162
 
        :param force_new_repo: Do not use a shared repository for the target 
163
 
                               even if one is available.
164
 
        """
165
 
        return self.clone_on_transport(get_transport(url),
166
 
                                       revision_id=revision_id,
167
 
                                       force_new_repo=force_new_repo)
168
 
 
169
173
    def clone_on_transport(self, transport, revision_id=None,
170
 
                           force_new_repo=False):
 
174
        force_new_repo=False, preserve_stacking=False, stacked_on=None,
 
175
        create_prefix=False, use_existing_dir=True, no_tree=False):
171
176
        """Clone this bzrdir and its contents to transport verbatim.
172
177
 
173
 
        If the target directory does not exist, it will be created.
174
 
 
175
 
        if revision_id is not None, then the clone operation may tune
 
178
        :param transport: The transport for the location to produce the clone
 
179
            at.  If the target directory does not exist, it will be created.
 
180
        :param revision_id: The tip revision-id to use for any branch or
 
181
            working tree.  If not None, then the clone operation may tune
176
182
            itself to download less data.
177
 
        :param force_new_repo: Do not use a shared repository for the target 
 
183
        :param force_new_repo: Do not use a shared repository for the target,
178
184
                               even if one is available.
 
185
        :param preserve_stacking: When cloning a stacked branch, stack the
 
186
            new branch on top of the other branch's stacked-on branch.
 
187
        :param create_prefix: Create any missing directories leading up to
 
188
            to_transport.
 
189
        :param use_existing_dir: Use an existing directory if one exists.
179
190
        """
180
 
        transport.ensure_base()
181
 
        result = self._format.initialize_on_transport(transport)
 
191
        # Overview: put together a broad description of what we want to end up
 
192
        # with; then make as few api calls as possible to do it.
 
193
 
 
194
        # We may want to create a repo/branch/tree, if we do so what format
 
195
        # would we want for each:
 
196
        require_stacking = (stacked_on is not None)
 
197
        format = self.cloning_metadir(require_stacking)
 
198
 
 
199
        # Figure out what objects we want:
182
200
        try:
183
201
            local_repo = self.find_repository()
184
202
        except errors.NoRepositoryPresent:
185
203
            local_repo = None
 
204
        try:
 
205
            local_branch = self.open_branch()
 
206
        except errors.NotBranchError:
 
207
            local_branch = None
 
208
        else:
 
209
            # enable fallbacks when branch is not a branch reference
 
210
            if local_branch.repository.has_same_location(local_repo):
 
211
                local_repo = local_branch.repository
 
212
            if preserve_stacking:
 
213
                try:
 
214
                    stacked_on = local_branch.get_stacked_on_url()
 
215
                except (errors.UnstackableBranchFormat,
 
216
                        errors.UnstackableRepositoryFormat,
 
217
                        errors.NotStacked):
 
218
                    pass
 
219
        # Bug: We create a metadir without knowing if it can support stacking,
 
220
        # we should look up the policy needs first, or just use it as a hint,
 
221
        # or something.
186
222
        if local_repo:
187
 
            # may need to copy content in
188
 
            if force_new_repo:
189
 
                result_repo = local_repo.clone(
190
 
                    result,
191
 
                    revision_id=revision_id)
192
 
                result_repo.set_make_working_trees(local_repo.make_working_trees())
193
 
            else:
194
 
                try:
195
 
                    result_repo = result.find_repository()
196
 
                    # fetch content this dir needs.
 
223
            make_working_trees = local_repo.make_working_trees() and not no_tree
 
224
            want_shared = local_repo.is_shared()
 
225
            repo_format_name = format.repository_format.network_name()
 
226
        else:
 
227
            make_working_trees = False
 
228
            want_shared = False
 
229
            repo_format_name = None
 
230
 
 
231
        result_repo, result, require_stacking, repository_policy = \
 
232
            format.initialize_on_transport_ex(transport,
 
233
            use_existing_dir=use_existing_dir, create_prefix=create_prefix,
 
234
            force_new_repo=force_new_repo, stacked_on=stacked_on,
 
235
            stack_on_pwd=self.root_transport.base,
 
236
            repo_format_name=repo_format_name,
 
237
            make_working_trees=make_working_trees, shared_repo=want_shared)
 
238
        if repo_format_name:
 
239
            try:
 
240
                # If the result repository is in the same place as the
 
241
                # resulting bzr dir, it will have no content, further if the
 
242
                # result is not stacked then we know all content should be
 
243
                # copied, and finally if we are copying up to a specific
 
244
                # revision_id then we can use the pending-ancestry-result which
 
245
                # does not require traversing all of history to describe it.
 
246
                if (result_repo.user_url == result.user_url
 
247
                    and not require_stacking and
 
248
                    revision_id is not None):
 
249
                    fetch_spec = graph.PendingAncestryResult(
 
250
                        [revision_id], local_repo)
 
251
                    result_repo.fetch(local_repo, fetch_spec=fetch_spec)
 
252
                else:
197
253
                    result_repo.fetch(local_repo, revision_id=revision_id)
198
 
                except errors.NoRepositoryPresent:
199
 
                    # needed to make one anyway.
200
 
                    result_repo = local_repo.clone(
201
 
                        result,
202
 
                        revision_id=revision_id)
203
 
                    result_repo.set_make_working_trees(local_repo.make_working_trees())
 
254
            finally:
 
255
                result_repo.unlock()
 
256
        else:
 
257
            if result_repo is not None:
 
258
                raise AssertionError('result_repo not None(%r)' % result_repo)
204
259
        # 1 if there is a branch present
205
260
        #   make sure its content is available in the target repository
206
261
        #   clone it.
207
 
        try:
208
 
            self.open_branch().clone(result, revision_id=revision_id)
209
 
        except errors.NotBranchError:
210
 
            pass
211
 
        try:
212
 
            result_repo = result.find_repository()
213
 
        except errors.NoRepositoryPresent:
214
 
            result_repo = None
215
 
        if result_repo is None or result_repo.make_working_trees():
216
 
            try:
 
262
        if local_branch is not None:
 
263
            result_branch = local_branch.clone(result, revision_id=revision_id,
 
264
                repository_policy=repository_policy)
 
265
        try:
 
266
            # Cheaper to check if the target is not local, than to try making
 
267
            # the tree and fail.
 
268
            result.root_transport.local_abspath('.')
 
269
            if result_repo is None or result_repo.make_working_trees():
217
270
                self.open_workingtree().clone(result)
218
 
            except (errors.NoWorkingTree, errors.NotLocalUrl):
219
 
                pass
 
271
        except (errors.NoWorkingTree, errors.NotLocalUrl):
 
272
            pass
220
273
        return result
221
274
 
222
275
    # TODO: This should be given a Transport, and should chdir up; otherwise
225
278
        t = get_transport(url)
226
279
        t.ensure_base()
227
280
 
228
 
    @classmethod
229
 
    def create(cls, base, format=None, possible_transports=None):
230
 
        """Create a new BzrDir at the url 'base'.
231
 
        
232
 
        :param format: If supplied, the format of branch to create.  If not
233
 
            supplied, the default is used.
234
 
        :param possible_transports: If supplied, a list of transports that 
235
 
            can be reused to share a remote connection.
236
 
        """
237
 
        if cls is not BzrDir:
238
 
            raise AssertionError("BzrDir.create always creates the default"
239
 
                " format, not one of %r" % cls)
240
 
        t = get_transport(base, possible_transports)
241
 
        t.ensure_base()
242
 
        if format is None:
243
 
            format = BzrDirFormat.get_default_format()
244
 
        return format.initialize_on_transport(t)
245
 
 
246
 
    def create_branch(self):
247
 
        """Create a branch in this BzrDir.
248
 
 
249
 
        The bzrdir's format will control what branch format is created.
250
 
        For more control see BranchFormatXX.create(a_bzrdir).
251
 
        """
252
 
        raise NotImplementedError(self.create_branch)
253
 
 
254
 
    def destroy_branch(self):
255
 
        """Destroy the branch in this BzrDir"""
256
 
        raise NotImplementedError(self.destroy_branch)
 
281
    @staticmethod
 
282
    def find_bzrdirs(transport, evaluate=None, list_current=None):
 
283
        """Find bzrdirs recursively from current location.
 
284
 
 
285
        This is intended primarily as a building block for more sophisticated
 
286
        functionality, like finding trees under a directory, or finding
 
287
        branches that use a given repository.
 
288
        :param evaluate: An optional callable that yields recurse, value,
 
289
            where recurse controls whether this bzrdir is recursed into
 
290
            and value is the value to yield.  By default, all bzrdirs
 
291
            are recursed into, and the return value is the bzrdir.
 
292
        :param list_current: if supplied, use this function to list the current
 
293
            directory, instead of Transport.list_dir
 
294
        :return: a generator of found bzrdirs, or whatever evaluate returns.
 
295
        """
 
296
        if list_current is None:
 
297
            def list_current(transport):
 
298
                return transport.list_dir('')
 
299
        if evaluate is None:
 
300
            def evaluate(bzrdir):
 
301
                return True, bzrdir
 
302
 
 
303
        pending = [transport]
 
304
        while len(pending) > 0:
 
305
            current_transport = pending.pop()
 
306
            recurse = True
 
307
            try:
 
308
                bzrdir = BzrDir.open_from_transport(current_transport)
 
309
            except (errors.NotBranchError, errors.PermissionDenied):
 
310
                pass
 
311
            else:
 
312
                recurse, value = evaluate(bzrdir)
 
313
                yield value
 
314
            try:
 
315
                subdirs = list_current(current_transport)
 
316
            except (errors.NoSuchFile, errors.PermissionDenied):
 
317
                continue
 
318
            if recurse:
 
319
                for subdir in sorted(subdirs, reverse=True):
 
320
                    pending.append(current_transport.clone(subdir))
 
321
 
 
322
    @staticmethod
 
323
    def find_branches(transport):
 
324
        """Find all branches under a transport.
 
325
 
 
326
        This will find all branches below the transport, including branches
 
327
        inside other branches.  Where possible, it will use
 
328
        Repository.find_branches.
 
329
 
 
330
        To list all the branches that use a particular Repository, see
 
331
        Repository.find_branches
 
332
        """
 
333
        def evaluate(bzrdir):
 
334
            try:
 
335
                repository = bzrdir.open_repository()
 
336
            except errors.NoRepositoryPresent:
 
337
                pass
 
338
            else:
 
339
                return False, ([], repository)
 
340
            return True, (bzrdir.list_branches(), None)
 
341
        ret = []
 
342
        for branches, repo in BzrDir.find_bzrdirs(transport,
 
343
                                                  evaluate=evaluate):
 
344
            if repo is not None:
 
345
                ret.extend(repo.find_branches())
 
346
            if branches is not None:
 
347
                ret.extend(branches)
 
348
        return ret
257
349
 
258
350
    @staticmethod
259
351
    def create_branch_and_repo(base, force_new_repo=False, format=None):
260
352
        """Create a new BzrDir, Branch and Repository at the url 'base'.
261
353
 
262
354
        This will use the current default BzrDirFormat unless one is
263
 
        specified, and use whatever 
 
355
        specified, and use whatever
264
356
        repository format that that uses via bzrdir.create_branch and
265
357
        create_repository. If a shared repository is available that is used
266
358
        preferentially.
276
368
        bzrdir._find_or_create_repository(force_new_repo)
277
369
        return bzrdir.create_branch()
278
370
 
 
371
    def determine_repository_policy(self, force_new_repo=False, stack_on=None,
 
372
                                    stack_on_pwd=None, require_stacking=False):
 
373
        """Return an object representing a policy to use.
 
374
 
 
375
        This controls whether a new repository is created, and the format of
 
376
        that repository, or some existing shared repository used instead.
 
377
 
 
378
        If stack_on is supplied, will not seek a containing shared repo.
 
379
 
 
380
        :param force_new_repo: If True, require a new repository to be created.
 
381
        :param stack_on: If supplied, the location to stack on.  If not
 
382
            supplied, a default_stack_on location may be used.
 
383
        :param stack_on_pwd: If stack_on is relative, the location it is
 
384
            relative to.
 
385
        """
 
386
        def repository_policy(found_bzrdir):
 
387
            stack_on = None
 
388
            stack_on_pwd = None
 
389
            config = found_bzrdir.get_config()
 
390
            stop = False
 
391
            stack_on = config.get_default_stack_on()
 
392
            if stack_on is not None:
 
393
                stack_on_pwd = found_bzrdir.user_url
 
394
                stop = True
 
395
            # does it have a repository ?
 
396
            try:
 
397
                repository = found_bzrdir.open_repository()
 
398
            except errors.NoRepositoryPresent:
 
399
                repository = None
 
400
            else:
 
401
                if (found_bzrdir.user_url != self.user_url 
 
402
                    and not repository.is_shared()):
 
403
                    # Don't look higher, can't use a higher shared repo.
 
404
                    repository = None
 
405
                    stop = True
 
406
                else:
 
407
                    stop = True
 
408
            if not stop:
 
409
                return None, False
 
410
            if repository:
 
411
                return UseExistingRepository(repository, stack_on,
 
412
                    stack_on_pwd, require_stacking=require_stacking), True
 
413
            else:
 
414
                return CreateRepository(self, stack_on, stack_on_pwd,
 
415
                    require_stacking=require_stacking), True
 
416
 
 
417
        if not force_new_repo:
 
418
            if stack_on is None:
 
419
                policy = self._find_containing(repository_policy)
 
420
                if policy is not None:
 
421
                    return policy
 
422
            else:
 
423
                try:
 
424
                    return UseExistingRepository(self.open_repository(),
 
425
                        stack_on, stack_on_pwd,
 
426
                        require_stacking=require_stacking)
 
427
                except errors.NoRepositoryPresent:
 
428
                    pass
 
429
        return CreateRepository(self, stack_on, stack_on_pwd,
 
430
                                require_stacking=require_stacking)
 
431
 
279
432
    def _find_or_create_repository(self, force_new_repo):
280
433
        """Create a new repository if needed, returning the repository."""
281
 
        if force_new_repo:
282
 
            return self.create_repository()
283
 
        try:
284
 
            return self.find_repository()
285
 
        except errors.NoRepositoryPresent:
286
 
            return self.create_repository()
287
 
        
 
434
        policy = self.determine_repository_policy(force_new_repo)
 
435
        return policy.acquire_repository()[0]
 
436
 
288
437
    @staticmethod
289
438
    def create_branch_convenience(base, force_new_repo=False,
290
439
                                  force_new_tree=None, format=None,
296
445
        not.
297
446
 
298
447
        This will use the current default BzrDirFormat unless one is
299
 
        specified, and use whatever 
 
448
        specified, and use whatever
300
449
        repository format that that uses via bzrdir.create_branch and
301
450
        create_repository. If a shared repository is available that is used
302
451
        preferentially. Whatever repository is used, its tree creation policy
304
453
 
305
454
        The created Branch object is returned.
306
455
        If a working tree cannot be made due to base not being a file:// url,
307
 
        no error is raised unless force_new_tree is True, in which case no 
 
456
        no error is raised unless force_new_tree is True, in which case no
308
457
        data is created on disk and NotLocalUrl is raised.
309
458
 
310
459
        :param base: The URL to create the branch at.
311
460
        :param force_new_repo: If True a new repository is always created.
312
 
        :param force_new_tree: If True or False force creation of a tree or 
 
461
        :param force_new_tree: If True or False force creation of a tree or
313
462
                               prevent such creation respectively.
314
463
        :param format: Override for the bzrdir format to create.
315
464
        :param possible_transports: An optional reusable transports list.
317
466
        if force_new_tree:
318
467
            # check for non local urls
319
468
            t = get_transport(base, possible_transports)
320
 
            if not isinstance(t, LocalTransport):
 
469
            if not isinstance(t, local.LocalTransport):
321
470
                raise errors.NotLocalUrl(base)
322
471
        bzrdir = BzrDir.create(base, format, possible_transports)
323
472
        repo = bzrdir._find_or_create_repository(force_new_repo)
331
480
        return result
332
481
 
333
482
    @staticmethod
334
 
    @deprecated_function(zero_ninetyone)
335
 
    def create_repository(base, shared=False, format=None):
336
 
        """Create a new BzrDir and Repository at the url 'base'.
337
 
 
338
 
        If no format is supplied, this will default to the current default
339
 
        BzrDirFormat by default, and use whatever repository format that that
340
 
        uses for bzrdirformat.create_repository.
341
 
 
342
 
        :param shared: Create a shared repository rather than a standalone
343
 
                       repository.
344
 
        The Repository object is returned.
345
 
 
346
 
        This must be overridden as an instance method in child classes, where
347
 
        it should take no parameters and construct whatever repository format
348
 
        that child class desires.
349
 
 
350
 
        This method is deprecated, please call create_repository on a bzrdir
351
 
        instance instead.
352
 
        """
353
 
        bzrdir = BzrDir.create(base, format)
354
 
        return bzrdir.create_repository(shared)
355
 
 
356
 
    @staticmethod
357
483
    def create_standalone_workingtree(base, format=None):
358
484
        """Create a new BzrDir, WorkingTree, Branch and Repository at 'base'.
359
485
 
360
486
        'base' must be a local path or a file:// url.
361
487
 
362
488
        This will use the current default BzrDirFormat unless one is
363
 
        specified, and use whatever 
 
489
        specified, and use whatever
364
490
        repository format that that uses for bzrdirformat.create_workingtree,
365
491
        create_branch and create_repository.
366
492
 
368
494
        :return: The WorkingTree object.
369
495
        """
370
496
        t = get_transport(base)
371
 
        if not isinstance(t, LocalTransport):
 
497
        if not isinstance(t, local.LocalTransport):
372
498
            raise errors.NotLocalUrl(base)
373
499
        bzrdir = BzrDir.create_branch_and_repo(base,
374
500
                                               force_new_repo=True,
375
501
                                               format=format).bzrdir
376
502
        return bzrdir.create_workingtree()
377
503
 
378
 
    def create_workingtree(self, revision_id=None, from_branch=None):
379
 
        """Create a working tree at this BzrDir.
380
 
        
381
 
        :param revision_id: create it as of this revision id.
382
 
        :param from_branch: override bzrdir branch (for lightweight checkouts)
383
 
        """
384
 
        raise NotImplementedError(self.create_workingtree)
 
504
    @deprecated_method(deprecated_in((2, 3, 0)))
 
505
    def generate_backup_name(self, base):
 
506
        return self._available_backup_name(base)
 
507
 
 
508
    def _available_backup_name(self, base):
 
509
        """Find a non-existing backup file name based on base.
 
510
 
 
511
        See bzrlib.osutils.available_backup_name about race conditions.
 
512
        """
 
513
        return osutils.available_backup_name(base, self.root_transport.has)
 
514
 
 
515
    def backup_bzrdir(self):
 
516
        """Backup this bzr control directory.
 
517
 
 
518
        :return: Tuple with old path name and new path name
 
519
        """
 
520
 
 
521
        pb = ui.ui_factory.nested_progress_bar()
 
522
        try:
 
523
            old_path = self.root_transport.abspath('.bzr')
 
524
            backup_dir = self._available_backup_name('backup.bzr')
 
525
            new_path = self.root_transport.abspath(backup_dir)
 
526
            ui.ui_factory.note('making backup of %s\n  to %s'
 
527
                               % (old_path, new_path,))
 
528
            self.root_transport.copy_tree('.bzr', backup_dir)
 
529
            return (old_path, new_path)
 
530
        finally:
 
531
            pb.finished()
385
532
 
386
533
    def retire_bzrdir(self, limit=10000):
387
534
        """Permanently disable the bzrdir.
408
555
                else:
409
556
                    pass
410
557
 
411
 
    def destroy_workingtree(self):
412
 
        """Destroy the working tree at this BzrDir.
413
 
 
414
 
        Formats that do not support this may raise UnsupportedOperation.
415
 
        """
416
 
        raise NotImplementedError(self.destroy_workingtree)
417
 
 
418
 
    def destroy_workingtree_metadata(self):
419
 
        """Destroy the control files for the working tree at this BzrDir.
420
 
 
421
 
        The contents of working tree files are not affected.
422
 
        Formats that do not support this may raise UnsupportedOperation.
423
 
        """
424
 
        raise NotImplementedError(self.destroy_workingtree_metadata)
 
558
    def _find_containing(self, evaluate):
 
559
        """Find something in a containing control directory.
 
560
 
 
561
        This method will scan containing control dirs, until it finds what
 
562
        it is looking for, decides that it will never find it, or runs out
 
563
        of containing control directories to check.
 
564
 
 
565
        It is used to implement find_repository and
 
566
        determine_repository_policy.
 
567
 
 
568
        :param evaluate: A function returning (value, stop).  If stop is True,
 
569
            the value will be returned.
 
570
        """
 
571
        found_bzrdir = self
 
572
        while True:
 
573
            result, stop = evaluate(found_bzrdir)
 
574
            if stop:
 
575
                return result
 
576
            next_transport = found_bzrdir.root_transport.clone('..')
 
577
            if (found_bzrdir.user_url == next_transport.base):
 
578
                # top of the file system
 
579
                return None
 
580
            # find the next containing bzrdir
 
581
            try:
 
582
                found_bzrdir = BzrDir.open_containing_from_transport(
 
583
                    next_transport)[0]
 
584
            except errors.NotBranchError:
 
585
                return None
425
586
 
426
587
    def find_repository(self):
427
588
        """Find the repository that should be used.
430
591
        new branches as well as to hook existing branches up to their
431
592
        repository.
432
593
        """
433
 
        try:
434
 
            return self.open_repository()
435
 
        except errors.NoRepositoryPresent:
436
 
            pass
437
 
        next_transport = self.root_transport.clone('..')
438
 
        while True:
439
 
            # find the next containing bzrdir
440
 
            try:
441
 
                found_bzrdir = BzrDir.open_containing_from_transport(
442
 
                    next_transport)[0]
443
 
            except errors.NotBranchError:
444
 
                # none found
445
 
                raise errors.NoRepositoryPresent(self)
 
594
        def usable_repository(found_bzrdir):
446
595
            # does it have a repository ?
447
596
            try:
448
597
                repository = found_bzrdir.open_repository()
449
598
            except errors.NoRepositoryPresent:
450
 
                next_transport = found_bzrdir.root_transport.clone('..')
451
 
                if (found_bzrdir.root_transport.base == next_transport.base):
452
 
                    # top of the file system
453
 
                    break
454
 
                else:
455
 
                    continue
456
 
            if ((found_bzrdir.root_transport.base ==
457
 
                 self.root_transport.base) or repository.is_shared()):
458
 
                return repository
459
 
            else:
460
 
                raise errors.NoRepositoryPresent(self)
461
 
        raise errors.NoRepositoryPresent(self)
462
 
 
463
 
    def get_branch_reference(self):
464
 
        """Return the referenced URL for the branch in this bzrdir.
465
 
 
466
 
        :raises NotBranchError: If there is no Branch.
467
 
        :return: The URL the branch in this bzrdir references if it is a
468
 
            reference branch, or None for regular branches.
469
 
        """
 
599
                return None, False
 
600
            if found_bzrdir.user_url == self.user_url:
 
601
                return repository, True
 
602
            elif repository.is_shared():
 
603
                return repository, True
 
604
            else:
 
605
                return None, True
 
606
 
 
607
        found_repo = self._find_containing(usable_repository)
 
608
        if found_repo is None:
 
609
            raise errors.NoRepositoryPresent(self)
 
610
        return found_repo
 
611
 
 
612
    def _find_creation_modes(self):
 
613
        """Determine the appropriate modes for files and directories.
 
614
 
 
615
        They're always set to be consistent with the base directory,
 
616
        assuming that this transport allows setting modes.
 
617
        """
 
618
        # TODO: Do we need or want an option (maybe a config setting) to turn
 
619
        # this off or override it for particular locations? -- mbp 20080512
 
620
        if self._mode_check_done:
 
621
            return
 
622
        self._mode_check_done = True
 
623
        try:
 
624
            st = self.transport.stat('.')
 
625
        except errors.TransportNotPossible:
 
626
            self._dir_mode = None
 
627
            self._file_mode = None
 
628
        else:
 
629
            # Check the directory mode, but also make sure the created
 
630
            # directories and files are read-write for this user. This is
 
631
            # mostly a workaround for filesystems which lie about being able to
 
632
            # write to a directory (cygwin & win32)
 
633
            if (st.st_mode & 07777 == 00000):
 
634
                # FTP allows stat but does not return dir/file modes
 
635
                self._dir_mode = None
 
636
                self._file_mode = None
 
637
            else:
 
638
                self._dir_mode = (st.st_mode & 07777) | 00700
 
639
                # Remove the sticky and execute bits for files
 
640
                self._file_mode = self._dir_mode & ~07111
 
641
 
 
642
    def _get_file_mode(self):
 
643
        """Return Unix mode for newly created files, or None.
 
644
        """
 
645
        if not self._mode_check_done:
 
646
            self._find_creation_modes()
 
647
        return self._file_mode
 
648
 
 
649
    def _get_dir_mode(self):
 
650
        """Return Unix mode for newly created directories, or None.
 
651
        """
 
652
        if not self._mode_check_done:
 
653
            self._find_creation_modes()
 
654
        return self._dir_mode
 
655
 
 
656
    def get_config(self):
 
657
        """Get configuration for this BzrDir."""
 
658
        return config.BzrDirConfig(self)
 
659
 
 
660
    def _get_config(self):
 
661
        """By default, no configuration is available."""
470
662
        return None
471
663
 
472
 
    def get_branch_transport(self, branch_format):
473
 
        """Get the transport for use by branch format in this BzrDir.
474
 
 
475
 
        Note that bzr dirs that do not support format strings will raise
476
 
        IncompatibleFormat if the branch format they are given has
477
 
        a format string, and vice versa.
478
 
 
479
 
        If branch_format is None, the transport is returned with no 
480
 
        checking. If it is not None, then the returned transport is
481
 
        guaranteed to point to an existing directory ready for use.
482
 
        """
483
 
        raise NotImplementedError(self.get_branch_transport)
484
 
        
485
 
    def get_repository_transport(self, repository_format):
486
 
        """Get the transport for use by repository format in this BzrDir.
487
 
 
488
 
        Note that bzr dirs that do not support format strings will raise
489
 
        IncompatibleFormat if the repository format they are given has
490
 
        a format string, and vice versa.
491
 
 
492
 
        If repository_format is None, the transport is returned with no 
493
 
        checking. If it is not None, then the returned transport is
494
 
        guaranteed to point to an existing directory ready for use.
495
 
        """
496
 
        raise NotImplementedError(self.get_repository_transport)
497
 
        
498
 
    def get_workingtree_transport(self, tree_format):
499
 
        """Get the transport for use by workingtree format in this BzrDir.
500
 
 
501
 
        Note that bzr dirs that do not support format strings will raise
502
 
        IncompatibleFormat if the workingtree format they are given has a
503
 
        format string, and vice versa.
504
 
 
505
 
        If workingtree_format is None, the transport is returned with no 
506
 
        checking. If it is not None, then the returned transport is
507
 
        guaranteed to point to an existing directory ready for use.
508
 
        """
509
 
        raise NotImplementedError(self.get_workingtree_transport)
510
 
        
511
664
    def __init__(self, _transport, _format):
512
665
        """Initialize a Bzr control dir object.
513
 
        
 
666
 
514
667
        Only really common logic should reside here, concrete classes should be
515
668
        made with varying behaviours.
516
669
 
518
671
        :param _transport: the transport this dir is based at.
519
672
        """
520
673
        self._format = _format
 
674
        # these are also under the more standard names of 
 
675
        # control_transport and user_transport
521
676
        self.transport = _transport.clone('.bzr')
522
677
        self.root_transport = _transport
 
678
        self._mode_check_done = False
 
679
 
 
680
    @property 
 
681
    def user_transport(self):
 
682
        return self.root_transport
 
683
 
 
684
    @property
 
685
    def control_transport(self):
 
686
        return self.transport
523
687
 
524
688
    def is_control_filename(self, filename):
525
689
        """True if filename is the name of a path which is reserved for bzrdir's.
526
 
        
 
690
 
527
691
        :param filename: A filename within the root transport of this bzrdir.
528
692
 
529
693
        This is true IF and ONLY IF the filename is part of the namespace reserved
530
694
        for bzr control dirs. Currently this is the '.bzr' directory in the root
531
 
        of the root_transport. it is expected that plugins will need to extend
532
 
        this in the future - for instance to make bzr talk with svn working
533
 
        trees.
 
695
        of the root_transport. 
534
696
        """
535
 
        # this might be better on the BzrDirFormat class because it refers to 
536
 
        # all the possible bzrdir disk formats. 
537
 
        # This method is tested via the workingtree is_control_filename tests- 
 
697
        # this might be better on the BzrDirFormat class because it refers to
 
698
        # all the possible bzrdir disk formats.
 
699
        # This method is tested via the workingtree is_control_filename tests-
538
700
        # it was extracted from WorkingTree.is_control_filename. If the method's
539
701
        # contract is extended beyond the current trivial implementation, please
540
702
        # add new tests for it to the appropriate place.
541
703
        return filename == '.bzr' or filename.startswith('.bzr/')
542
704
 
543
 
    def needs_format_conversion(self, format=None):
544
 
        """Return true if this bzrdir needs convert_format run on it.
545
 
        
546
 
        For instance, if the repository format is out of date but the 
547
 
        branch and working tree are not, this should return True.
548
 
 
549
 
        :param format: Optional parameter indicating a specific desired
550
 
                       format we plan to arrive at.
551
 
        """
552
 
        raise NotImplementedError(self.needs_format_conversion)
553
 
 
554
705
    @staticmethod
555
706
    def open_unsupported(base):
556
707
        """Open a branch which is not supported."""
557
708
        return BzrDir.open(base, _unsupported=True)
558
 
        
 
709
 
559
710
    @staticmethod
560
711
    def open(base, _unsupported=False, possible_transports=None):
561
712
        """Open an existing bzrdir, rooted at 'base' (url).
562
 
        
 
713
 
563
714
        :param _unsupported: a private parameter to the BzrDir class.
564
715
        """
565
716
        t = get_transport(base, possible_transports=possible_transports)
573
724
        :param transport: Transport containing the bzrdir.
574
725
        :param _unsupported: private.
575
726
        """
 
727
        for hook in BzrDir.hooks['pre_open']:
 
728
            hook(transport)
 
729
        # Keep initial base since 'transport' may be modified while following
 
730
        # the redirections.
576
731
        base = transport.base
577
 
 
578
732
        def find_format(transport):
579
 
            return transport, BzrDirFormat.find_format(
 
733
            return transport, controldir.ControlDirFormat.find_format(
580
734
                transport, _server_formats=_server_formats)
581
735
 
582
736
        def redirected(transport, e, redirection_notice):
583
 
            qualified_source = e.get_source_url()
584
 
            relpath = transport.relpath(qualified_source)
585
 
            if not e.target.endswith(relpath):
586
 
                # Not redirected to a branch-format, not a branch
587
 
                raise errors.NotBranchError(path=e.target)
588
 
            target = e.target[:-len(relpath)]
 
737
            redirected_transport = transport._redirected_to(e.source, e.target)
 
738
            if redirected_transport is None:
 
739
                raise errors.NotBranchError(base)
589
740
            note('%s is%s redirected to %s',
590
 
                 transport.base, e.permanently, target)
591
 
            # Let's try with a new transport
592
 
            # FIXME: If 'transport' has a qualifier, this should
593
 
            # be applied again to the new transport *iff* the
594
 
            # schemes used are the same. Uncomment this code
595
 
            # once the function (and tests) exist.
596
 
            # -- vila20070212
597
 
            #target = urlutils.copy_url_qualifiers(original, target)
598
 
            return get_transport(target)
 
741
                 transport.base, e.permanently, redirected_transport.base)
 
742
            return redirected_transport
599
743
 
600
744
        try:
601
745
            transport, format = do_catching_redirections(find_format,
607
751
        BzrDir._check_supported(format, _unsupported)
608
752
        return format.open(transport, _found=True)
609
753
 
610
 
    def open_branch(self, unsupported=False):
611
 
        """Open the branch object at this BzrDir if one is present.
612
 
 
613
 
        If unsupported is True, then no longer supported branch formats can
614
 
        still be opened.
615
 
        
616
 
        TODO: static convenience version of this?
617
 
        """
618
 
        raise NotImplementedError(self.open_branch)
619
 
 
620
754
    @staticmethod
621
755
    def open_containing(url, possible_transports=None):
622
756
        """Open an existing branch which contains url.
623
 
        
 
757
 
624
758
        :param url: url to search from.
625
759
        See open_containing_from_transport for more detail.
626
760
        """
627
761
        transport = get_transport(url, possible_transports)
628
762
        return BzrDir.open_containing_from_transport(transport)
629
 
    
 
763
 
630
764
    @staticmethod
631
765
    def open_containing_from_transport(a_transport):
632
766
        """Open an existing branch which contains a_transport.base.
635
769
 
636
770
        Basically we keep looking up until we find the control directory or
637
771
        run into the root.  If there isn't one, raises NotBranchError.
638
 
        If there is one and it is either an unrecognised format or an unsupported 
 
772
        If there is one and it is either an unrecognised format or an unsupported
639
773
        format, UnknownFormatError or UnsupportedFormatError are raised.
640
774
        If there is one, it is returned, along with the unused portion of url.
641
775
 
642
 
        :return: The BzrDir that contains the path, and a Unicode path 
 
776
        :return: The BzrDir that contains the path, and a Unicode path
643
777
                for the rest of the URL.
644
778
        """
645
779
        # this gets the normalised url back. I.e. '.' -> the full path.
661
795
            a_transport = new_t
662
796
 
663
797
    @classmethod
 
798
    def open_tree_or_branch(klass, location):
 
799
        """Return the branch and working tree at a location.
 
800
 
 
801
        If there is no tree at the location, tree will be None.
 
802
        If there is no branch at the location, an exception will be
 
803
        raised
 
804
        :return: (tree, branch)
 
805
        """
 
806
        bzrdir = klass.open(location)
 
807
        return bzrdir._get_tree_branch()
 
808
 
 
809
    @classmethod
664
810
    def open_containing_tree_or_branch(klass, location):
665
811
        """Return the branch and working tree contained by a location.
666
812
 
671
817
        relpath is the portion of the path that is contained by the branch.
672
818
        """
673
819
        bzrdir, relpath = klass.open_containing(location)
674
 
        try:
675
 
            tree = bzrdir.open_workingtree()
676
 
        except (errors.NoWorkingTree, errors.NotLocalUrl):
677
 
            tree = None
678
 
            branch = bzrdir.open_branch()
679
 
        else:
680
 
            branch = tree.branch
 
820
        tree, branch = bzrdir._get_tree_branch()
681
821
        return tree, branch, relpath
682
822
 
683
 
    def open_repository(self, _unsupported=False):
684
 
        """Open the repository object at this BzrDir if one is present.
685
 
 
686
 
        This will not follow the Branch object pointer - it's strictly a direct
687
 
        open facility. Most client code should use open_branch().repository to
688
 
        get at a repository.
689
 
 
690
 
        :param _unsupported: a private parameter, not part of the api.
691
 
        TODO: static convenience version of this?
692
 
        """
693
 
        raise NotImplementedError(self.open_repository)
694
 
 
695
 
    def open_workingtree(self, _unsupported=False,
696
 
                         recommend_upgrade=True, from_branch=None):
697
 
        """Open the workingtree object at this BzrDir if one is present.
698
 
 
699
 
        :param recommend_upgrade: Optional keyword parameter, when True (the
700
 
            default), emit through the ui module a recommendation that the user
701
 
            upgrade the working tree when the workingtree being opened is old
702
 
            (but still fully supported).
703
 
        :param from_branch: override bzrdir branch (for lightweight checkouts)
704
 
        """
705
 
        raise NotImplementedError(self.open_workingtree)
706
 
 
707
 
    def has_branch(self):
708
 
        """Tell if this bzrdir contains a branch.
709
 
        
710
 
        Note: if you're going to open the branch, you should just go ahead
711
 
        and try, and not ask permission first.  (This method just opens the 
712
 
        branch and discards it, and that's somewhat expensive.) 
713
 
        """
 
823
    @classmethod
 
824
    def open_containing_tree_branch_or_repository(klass, location):
 
825
        """Return the working tree, branch and repo contained by a location.
 
826
 
 
827
        Returns (tree, branch, repository, relpath).
 
828
        If there is no tree containing the location, tree will be None.
 
829
        If there is no branch containing the location, branch will be None.
 
830
        If there is no repository containing the location, repository will be
 
831
        None.
 
832
        relpath is the portion of the path that is contained by the innermost
 
833
        BzrDir.
 
834
 
 
835
        If no tree, branch or repository is found, a NotBranchError is raised.
 
836
        """
 
837
        bzrdir, relpath = klass.open_containing(location)
714
838
        try:
715
 
            self.open_branch()
716
 
            return True
 
839
            tree, branch = bzrdir._get_tree_branch()
717
840
        except errors.NotBranchError:
718
 
            return False
719
 
 
720
 
    def has_workingtree(self):
721
 
        """Tell if this bzrdir contains a working tree.
722
 
 
723
 
        This will still raise an exception if the bzrdir has a workingtree that
724
 
        is remote & inaccessible.
725
 
        
726
 
        Note: if you're going to open the working tree, you should just go ahead
727
 
        and try, and not ask permission first.  (This method just opens the 
728
 
        workingtree and discards it, and that's somewhat expensive.) 
729
 
        """
730
 
        try:
731
 
            self.open_workingtree(recommend_upgrade=False)
732
 
            return True
733
 
        except errors.NoWorkingTree:
734
 
            return False
 
841
            try:
 
842
                repo = bzrdir.find_repository()
 
843
                return None, None, repo, relpath
 
844
            except (errors.NoRepositoryPresent):
 
845
                raise errors.NotBranchError(location)
 
846
        return tree, branch, branch.repository, relpath
735
847
 
736
848
    def _cloning_metadir(self):
737
 
        """Produce a metadir suitable for cloning with."""
 
849
        """Produce a metadir suitable for cloning with.
 
850
 
 
851
        :returns: (destination_bzrdir_format, source_repository)
 
852
        """
738
853
        result_format = self._format.__class__()
739
854
        try:
740
855
            try:
741
 
                branch = self.open_branch()
 
856
                branch = self.open_branch(ignore_fallbacks=True)
742
857
                source_repository = branch.repository
 
858
                result_format._branch_format = branch._format
743
859
            except errors.NotBranchError:
744
860
                source_branch = None
745
861
                source_repository = self.open_repository()
750
866
            # the fix recommended in bug # 103195 - to delegate this choice the
751
867
            # repository itself.
752
868
            repo_format = source_repository._format
753
 
            if not isinstance(repo_format, remote.RemoteRepositoryFormat):
754
 
                result_format.repository_format = repo_format
 
869
            if isinstance(repo_format, remote.RemoteRepositoryFormat):
 
870
                source_repository._ensure_real()
 
871
                repo_format = source_repository._real_repository._format
 
872
            result_format.repository_format = repo_format
755
873
        try:
756
874
            # TODO: Couldn't we just probe for the format in these cases,
757
875
            # rather than opening the whole tree?  It would be a little
763
881
            result_format.workingtree_format = tree._format.__class__()
764
882
        return result_format, source_repository
765
883
 
766
 
    def cloning_metadir(self):
 
884
    def cloning_metadir(self, require_stacking=False):
767
885
        """Produce a metadir suitable for cloning or sprouting with.
768
886
 
769
887
        These operations may produce workingtrees (yes, even though they're
770
888
        "cloning" something that doesn't have a tree), so a viable workingtree
771
889
        format must be selected.
 
890
 
 
891
        :require_stacking: If True, non-stackable formats will be upgraded
 
892
            to similar stackable formats.
 
893
        :returns: a BzrDirFormat with all component formats either set
 
894
            appropriately or set to None if that component should not be
 
895
            created.
772
896
        """
773
897
        format, repository = self._cloning_metadir()
774
898
        if format._workingtree_format is None:
 
899
            # No tree in self.
775
900
            if repository is None:
 
901
                # No repository either
776
902
                return format
 
903
            # We have a repository, so set a working tree? (Why? This seems to
 
904
            # contradict the stated return value in the docstring).
777
905
            tree_format = repository._format._matchingbzrdir.workingtree_format
778
906
            format.workingtree_format = tree_format.__class__()
 
907
        if require_stacking:
 
908
            format.require_stacking()
779
909
        return format
780
910
 
781
 
    def checkout_metadir(self):
782
 
        return self.cloning_metadir()
783
 
 
784
 
    def sprout(self, url, revision_id=None, force_new_repo=False,
785
 
               recurse='down', possible_transports=None):
786
 
        """Create a copy of this bzrdir prepared for use as a new line of
787
 
        development.
788
 
 
789
 
        If url's last component does not exist, it will be created.
790
 
 
791
 
        Attributes related to the identity of the source branch like
792
 
        branch nickname will be cleaned, a working tree is created
793
 
        whether one existed before or not; and a local branch is always
794
 
        created.
795
 
 
796
 
        if revision_id is not None, then the clone operation may tune
797
 
            itself to download less data.
798
 
        """
799
 
        target_transport = get_transport(url, possible_transports)
800
 
        target_transport.ensure_base()
801
 
        cloning_format = self.cloning_metadir()
802
 
        result = cloning_format.initialize_on_transport(target_transport)
803
 
        try:
804
 
            source_branch = self.open_branch()
805
 
            source_repository = source_branch.repository
806
 
        except errors.NotBranchError:
807
 
            source_branch = None
808
 
            try:
809
 
                source_repository = self.open_repository()
810
 
            except errors.NoRepositoryPresent:
811
 
                source_repository = None
812
 
        if force_new_repo:
813
 
            result_repo = None
814
 
        else:
815
 
            try:
816
 
                result_repo = result.find_repository()
817
 
            except errors.NoRepositoryPresent:
818
 
                result_repo = None
819
 
        if source_repository is None and result_repo is not None:
820
 
            pass
821
 
        elif source_repository is None and result_repo is None:
822
 
            # no repo available, make a new one
823
 
            result.create_repository()
824
 
        elif source_repository is not None and result_repo is None:
825
 
            # have source, and want to make a new target repo
826
 
            result_repo = source_repository.sprout(result,
827
 
                                                   revision_id=revision_id)
828
 
        else:
829
 
            # fetch needed content into target.
830
 
            if source_repository is not None:
831
 
                # would rather do 
832
 
                # source_repository.copy_content_into(result_repo,
833
 
                #                                     revision_id=revision_id)
834
 
                # so we can override the copy method
835
 
                result_repo.fetch(source_repository, revision_id=revision_id)
836
 
        if source_branch is not None:
837
 
            source_branch.sprout(result, revision_id=revision_id)
838
 
        else:
839
 
            result.create_branch()
840
 
        if isinstance(target_transport, LocalTransport) and (
841
 
            result_repo is None or result_repo.make_working_trees()):
842
 
            wt = result.create_workingtree()
843
 
            wt.lock_write()
844
 
            try:
845
 
                if wt.path2id('') is None:
846
 
                    try:
847
 
                        wt.set_root_id(self.open_workingtree.get_root_id())
848
 
                    except errors.NoWorkingTree:
849
 
                        pass
850
 
            finally:
851
 
                wt.unlock()
852
 
        else:
853
 
            wt = None
854
 
        if recurse == 'down':
855
 
            if wt is not None:
856
 
                basis = wt.basis_tree()
857
 
                basis.lock_read()
858
 
                subtrees = basis.iter_references()
859
 
                recurse_branch = wt.branch
860
 
            elif source_branch is not None:
861
 
                basis = source_branch.basis_tree()
862
 
                basis.lock_read()
863
 
                subtrees = basis.iter_references()
864
 
                recurse_branch = source_branch
865
 
            else:
866
 
                subtrees = []
867
 
                basis = None
868
 
            try:
869
 
                for path, file_id in subtrees:
870
 
                    target = urlutils.join(url, urlutils.escape(path))
871
 
                    sublocation = source_branch.reference_parent(file_id, path)
872
 
                    sublocation.bzrdir.sprout(target,
873
 
                        basis.get_reference_revision(file_id, path),
874
 
                        force_new_repo=force_new_repo, recurse=recurse)
875
 
            finally:
876
 
                if basis is not None:
877
 
                    basis.unlock()
878
 
        return result
 
911
    @classmethod
 
912
    def create(cls, base, format=None, possible_transports=None):
 
913
        """Create a new BzrDir at the url 'base'.
 
914
 
 
915
        :param format: If supplied, the format of branch to create.  If not
 
916
            supplied, the default is used.
 
917
        :param possible_transports: If supplied, a list of transports that
 
918
            can be reused to share a remote connection.
 
919
        """
 
920
        if cls is not BzrDir:
 
921
            raise AssertionError("BzrDir.create always creates the"
 
922
                "default format, not one of %r" % cls)
 
923
        t = get_transport(base, possible_transports)
 
924
        t.ensure_base()
 
925
        if format is None:
 
926
            format = controldir.ControlDirFormat.get_default_format()
 
927
        return format.initialize_on_transport(t)
 
928
 
 
929
 
 
930
 
 
931
class BzrDirHooks(hooks.Hooks):
 
932
    """Hooks for BzrDir operations."""
 
933
 
 
934
    def __init__(self):
 
935
        """Create the default hooks."""
 
936
        hooks.Hooks.__init__(self)
 
937
        self.create_hook(hooks.HookPoint('pre_open',
 
938
            "Invoked before attempting to open a BzrDir with the transport "
 
939
            "that the open will use.", (1, 14), None))
 
940
        self.create_hook(hooks.HookPoint('post_repo_init',
 
941
            "Invoked after a repository has been initialized. "
 
942
            "post_repo_init is called with a "
 
943
            "bzrlib.bzrdir.RepoInitHookParams.",
 
944
            (2, 2), None))
 
945
 
 
946
# install the default hooks
 
947
BzrDir.hooks = BzrDirHooks()
 
948
 
 
949
 
 
950
class RepoInitHookParams(object):
 
951
    """Object holding parameters passed to *_repo_init hooks.
 
952
 
 
953
    There are 4 fields that hooks may wish to access:
 
954
 
 
955
    :ivar repository: Repository created
 
956
    :ivar format: Repository format
 
957
    :ivar bzrdir: The bzrdir for the repository
 
958
    :ivar shared: The repository is shared
 
959
    """
 
960
 
 
961
    def __init__(self, repository, format, a_bzrdir, shared):
 
962
        """Create a group of RepoInitHook parameters.
 
963
 
 
964
        :param repository: Repository created
 
965
        :param format: Repository format
 
966
        :param bzrdir: The bzrdir for the repository
 
967
        :param shared: The repository is shared
 
968
        """
 
969
        self.repository = repository
 
970
        self.format = format
 
971
        self.bzrdir = a_bzrdir
 
972
        self.shared = shared
 
973
 
 
974
    def __eq__(self, other):
 
975
        return self.__dict__ == other.__dict__
 
976
 
 
977
    def __repr__(self):
 
978
        if self.repository:
 
979
            return "<%s for %s>" % (self.__class__.__name__,
 
980
                self.repository)
 
981
        else:
 
982
            return "<%s for %s>" % (self.__class__.__name__,
 
983
                self.bzrdir)
879
984
 
880
985
 
881
986
class BzrDirPreSplitOut(BzrDir):
884
989
    def __init__(self, _transport, _format):
885
990
        """See BzrDir.__init__."""
886
991
        super(BzrDirPreSplitOut, self).__init__(_transport, _format)
887
 
        assert self._format._lock_class == lockable_files.TransportLock
888
 
        assert self._format._lock_file_name == 'branch-lock'
889
992
        self._control_files = lockable_files.LockableFiles(
890
993
                                            self.get_branch_transport(None),
891
994
                                            self._format._lock_file_name,
895
998
        """Pre-splitout bzrdirs do not suffer from stale locks."""
896
999
        raise NotImplementedError(self.break_lock)
897
1000
 
898
 
    def clone(self, url, revision_id=None, force_new_repo=False):
899
 
        """See BzrDir.clone()."""
900
 
        from bzrlib.workingtree import WorkingTreeFormat2
 
1001
    def cloning_metadir(self, require_stacking=False):
 
1002
        """Produce a metadir suitable for cloning with."""
 
1003
        if require_stacking:
 
1004
            return controldir.format_registry.make_bzrdir('1.6')
 
1005
        return self._format.__class__()
 
1006
 
 
1007
    def clone(self, url, revision_id=None, force_new_repo=False,
 
1008
              preserve_stacking=False):
 
1009
        """See BzrDir.clone().
 
1010
 
 
1011
        force_new_repo has no effect, since this family of formats always
 
1012
        require a new repository.
 
1013
        preserve_stacking has no effect, since no source branch using this
 
1014
        family of formats can be stacked, so there is no stacking to preserve.
 
1015
        """
901
1016
        self._make_tail(url)
902
1017
        result = self._format._initialize_for_clone(url)
903
1018
        self.open_repository().clone(result, revision_id=revision_id)
904
1019
        from_branch = self.open_branch()
905
1020
        from_branch.clone(result, revision_id=revision_id)
906
1021
        try:
907
 
            self.open_workingtree().clone(result)
 
1022
            tree = self.open_workingtree()
908
1023
        except errors.NotLocalUrl:
909
1024
            # make a new one, this format always has to have one.
910
 
            try:
911
 
                WorkingTreeFormat2().initialize(result)
912
 
            except errors.NotLocalUrl:
913
 
                # but we cannot do it for remote trees.
914
 
                to_branch = result.open_branch()
915
 
                WorkingTreeFormat2().stub_initialize_remote(to_branch.control_files)
 
1025
            result._init_workingtree()
 
1026
        else:
 
1027
            tree.clone(result)
916
1028
        return result
917
1029
 
918
 
    def create_branch(self):
 
1030
    def create_branch(self, name=None, repository=None):
919
1031
        """See BzrDir.create_branch."""
920
 
        return self.open_branch()
 
1032
        if repository is not None:
 
1033
            raise NotImplementedError(
 
1034
                "create_branch(repository=<not None>) on %r" % (self,))
 
1035
        return self._format.get_branch_format().initialize(self, name=name)
921
1036
 
922
 
    def destroy_branch(self):
 
1037
    def destroy_branch(self, name=None):
923
1038
        """See BzrDir.destroy_branch."""
924
1039
        raise errors.UnsupportedOperation(self.destroy_branch, self)
925
1040
 
929
1044
            raise errors.IncompatibleFormat('shared repository', self._format)
930
1045
        return self.open_repository()
931
1046
 
932
 
    def create_workingtree(self, revision_id=None, from_branch=None):
 
1047
    def destroy_repository(self):
 
1048
        """See BzrDir.destroy_repository."""
 
1049
        raise errors.UnsupportedOperation(self.destroy_repository, self)
 
1050
 
 
1051
    def create_workingtree(self, revision_id=None, from_branch=None,
 
1052
                           accelerator_tree=None, hardlink=False):
933
1053
        """See BzrDir.create_workingtree."""
 
1054
        # The workingtree is sometimes created when the bzrdir is created,
 
1055
        # but not when cloning.
 
1056
 
934
1057
        # this looks buggy but is not -really-
935
1058
        # because this format creates the workingtree when the bzrdir is
936
1059
        # created
938
1061
        # and that will have set it for us, its only
939
1062
        # specific uses of create_workingtree in isolation
940
1063
        # that can do wonky stuff here, and that only
941
 
        # happens for creating checkouts, which cannot be 
 
1064
        # happens for creating checkouts, which cannot be
942
1065
        # done on this format anyway. So - acceptable wart.
943
 
        result = self.open_workingtree(recommend_upgrade=False)
 
1066
        if hardlink:
 
1067
            warning("can't support hardlinked working trees in %r"
 
1068
                % (self,))
 
1069
        try:
 
1070
            result = self.open_workingtree(recommend_upgrade=False)
 
1071
        except errors.NoSuchFile:
 
1072
            result = self._init_workingtree()
944
1073
        if revision_id is not None:
945
1074
            if revision_id == _mod_revision.NULL_REVISION:
946
1075
                result.set_parent_ids([])
948
1077
                result.set_parent_ids([revision_id])
949
1078
        return result
950
1079
 
 
1080
    def _init_workingtree(self):
 
1081
        from bzrlib.workingtree import WorkingTreeFormat2
 
1082
        try:
 
1083
            return WorkingTreeFormat2().initialize(self)
 
1084
        except errors.NotLocalUrl:
 
1085
            # Even though we can't access the working tree, we need to
 
1086
            # create its control files.
 
1087
            return WorkingTreeFormat2()._stub_initialize_on_transport(
 
1088
                self.transport, self._control_files._file_mode)
 
1089
 
951
1090
    def destroy_workingtree(self):
952
1091
        """See BzrDir.destroy_workingtree."""
953
1092
        raise errors.UnsupportedOperation(self.destroy_workingtree, self)
954
1093
 
955
1094
    def destroy_workingtree_metadata(self):
956
1095
        """See BzrDir.destroy_workingtree_metadata."""
957
 
        raise errors.UnsupportedOperation(self.destroy_workingtree_metadata, 
 
1096
        raise errors.UnsupportedOperation(self.destroy_workingtree_metadata,
958
1097
                                          self)
959
1098
 
960
 
    def get_branch_transport(self, branch_format):
 
1099
    def get_branch_transport(self, branch_format, name=None):
961
1100
        """See BzrDir.get_branch_transport()."""
 
1101
        if name is not None:
 
1102
            raise errors.NoColocatedBranchSupport(self)
962
1103
        if branch_format is None:
963
1104
            return self.transport
964
1105
        try:
992
1133
        # if the format is not the same as the system default,
993
1134
        # an upgrade is needed.
994
1135
        if format is None:
 
1136
            symbol_versioning.warn(symbol_versioning.deprecated_in((1, 13, 0))
 
1137
                % 'needs_format_conversion(format=None)')
995
1138
            format = BzrDirFormat.get_default_format()
996
1139
        return not isinstance(self._format, format.__class__)
997
1140
 
998
 
    def open_branch(self, unsupported=False):
 
1141
    def open_branch(self, name=None, unsupported=False,
 
1142
                    ignore_fallbacks=False):
999
1143
        """See BzrDir.open_branch."""
1000
1144
        from bzrlib.branch import BzrBranchFormat4
1001
1145
        format = BzrBranchFormat4()
1002
1146
        self._check_supported(format, unsupported)
1003
 
        return format.open(self, _found=True)
 
1147
        return format.open(self, name, _found=True)
1004
1148
 
1005
1149
    def sprout(self, url, revision_id=None, force_new_repo=False,
1006
 
               possible_transports=None):
 
1150
               possible_transports=None, accelerator_tree=None,
 
1151
               hardlink=False, stacked=False, create_tree_if_local=True,
 
1152
               source_branch=None):
1007
1153
        """See BzrDir.sprout()."""
 
1154
        if source_branch is not None:
 
1155
            my_branch = self.open_branch()
 
1156
            if source_branch.base != my_branch.base:
 
1157
                raise AssertionError(
 
1158
                    "source branch %r is not within %r with branch %r" %
 
1159
                    (source_branch, self, my_branch))
 
1160
        if stacked:
 
1161
            raise errors.UnstackableBranchFormat(
 
1162
                self._format, self.root_transport.base)
 
1163
        if not create_tree_if_local:
 
1164
            raise errors.MustHaveWorkingTree(
 
1165
                self._format, self.root_transport.base)
1008
1166
        from bzrlib.workingtree import WorkingTreeFormat2
1009
1167
        self._make_tail(url)
1010
1168
        result = self._format._initialize_for_clone(url)
1016
1174
            self.open_branch().sprout(result, revision_id=revision_id)
1017
1175
        except errors.NotBranchError:
1018
1176
            pass
 
1177
 
1019
1178
        # we always want a working tree
1020
 
        WorkingTreeFormat2().initialize(result)
 
1179
        WorkingTreeFormat2().initialize(result,
 
1180
                                        accelerator_tree=accelerator_tree,
 
1181
                                        hardlink=hardlink)
1021
1182
        return result
1022
1183
 
1023
1184
 
1024
1185
class BzrDir4(BzrDirPreSplitOut):
1025
1186
    """A .bzr version 4 control object.
1026
 
    
 
1187
 
1027
1188
    This is a deprecated format and may be removed after sept 2006.
1028
1189
    """
1029
1190
 
1033
1194
 
1034
1195
    def needs_format_conversion(self, format=None):
1035
1196
        """Format 4 dirs are always in need of conversion."""
 
1197
        if format is None:
 
1198
            symbol_versioning.warn(symbol_versioning.deprecated_in((1, 13, 0))
 
1199
                % 'needs_format_conversion(format=None)')
1036
1200
        return True
1037
1201
 
1038
1202
    def open_repository(self):
1047
1211
    This is a deprecated format and may be removed after sept 2006.
1048
1212
    """
1049
1213
 
 
1214
    def has_workingtree(self):
 
1215
        """See BzrDir.has_workingtree."""
 
1216
        return True
 
1217
    
1050
1218
    def open_repository(self):
1051
1219
        """See BzrDir.open_repository."""
1052
1220
        from bzrlib.repofmt.weaverepo import RepositoryFormat5
1068
1236
    This is a deprecated format and may be removed after sept 2006.
1069
1237
    """
1070
1238
 
 
1239
    def has_workingtree(self):
 
1240
        """See BzrDir.has_workingtree."""
 
1241
        return True
 
1242
    
1071
1243
    def open_repository(self):
1072
1244
        """See BzrDir.open_repository."""
1073
1245
        from bzrlib.repofmt.weaverepo import RepositoryFormat6
1084
1256
 
1085
1257
class BzrDirMeta1(BzrDir):
1086
1258
    """A .bzr meta version 1 control object.
1087
 
    
1088
 
    This is the first control object where the 
 
1259
 
 
1260
    This is the first control object where the
1089
1261
    individual aspects are really split out: there are separate repository,
1090
1262
    workingtree and branch subdirectories and any subset of the three can be
1091
1263
    present within a BzrDir.
1095
1267
        """See BzrDir.can_convert_format()."""
1096
1268
        return True
1097
1269
 
1098
 
    def create_branch(self):
 
1270
    def create_branch(self, name=None, repository=None):
1099
1271
        """See BzrDir.create_branch."""
1100
 
        return self._format.get_branch_format().initialize(self)
 
1272
        return self._format.get_branch_format().initialize(self, name=name,
 
1273
                repository=repository)
1101
1274
 
1102
 
    def destroy_branch(self):
 
1275
    def destroy_branch(self, name=None):
1103
1276
        """See BzrDir.create_branch."""
 
1277
        if name is not None:
 
1278
            raise errors.NoColocatedBranchSupport(self)
1104
1279
        self.transport.delete_tree('branch')
1105
1280
 
1106
1281
    def create_repository(self, shared=False):
1107
1282
        """See BzrDir.create_repository."""
1108
1283
        return self._format.repository_format.initialize(self, shared)
1109
1284
 
1110
 
    def create_workingtree(self, revision_id=None, from_branch=None):
 
1285
    def destroy_repository(self):
 
1286
        """See BzrDir.destroy_repository."""
 
1287
        self.transport.delete_tree('repository')
 
1288
 
 
1289
    def create_workingtree(self, revision_id=None, from_branch=None,
 
1290
                           accelerator_tree=None, hardlink=False):
1111
1291
        """See BzrDir.create_workingtree."""
1112
1292
        return self._format.workingtree_format.initialize(
1113
 
            self, revision_id, from_branch=from_branch)
 
1293
            self, revision_id, from_branch=from_branch,
 
1294
            accelerator_tree=accelerator_tree, hardlink=hardlink)
1114
1295
 
1115
1296
    def destroy_workingtree(self):
1116
1297
        """See BzrDir.destroy_workingtree."""
1117
1298
        wt = self.open_workingtree(recommend_upgrade=False)
1118
1299
        repository = wt.branch.repository
1119
1300
        empty = repository.revision_tree(_mod_revision.NULL_REVISION)
1120
 
        wt.revert(old_tree=empty)
 
1301
        # We ignore the conflicts returned by wt.revert since we're about to
 
1302
        # delete the wt metadata anyway, all that should be left here are
 
1303
        # detritus. But see bug #634470 about subtree .bzr dirs.
 
1304
        conflicts = wt.revert(old_tree=empty)
1121
1305
        self.destroy_workingtree_metadata()
1122
1306
 
1123
1307
    def destroy_workingtree_metadata(self):
1124
1308
        self.transport.delete_tree('checkout')
1125
1309
 
1126
 
    def find_branch_format(self):
 
1310
    def find_branch_format(self, name=None):
1127
1311
        """Find the branch 'format' for this bzrdir.
1128
1312
 
1129
1313
        This might be a synthetic object for e.g. RemoteBranch and SVN.
1130
1314
        """
1131
1315
        from bzrlib.branch import BranchFormat
1132
 
        return BranchFormat.find_format(self)
 
1316
        return BranchFormat.find_format(self, name=name)
1133
1317
 
1134
1318
    def _get_mkdir_mode(self):
1135
1319
        """Figure out the mode to use when creating a bzrdir subdir."""
1137
1321
                                     lockable_files.TransportLock)
1138
1322
        return temp_control._dir_mode
1139
1323
 
1140
 
    def get_branch_reference(self):
 
1324
    def get_branch_reference(self, name=None):
1141
1325
        """See BzrDir.get_branch_reference()."""
1142
1326
        from bzrlib.branch import BranchFormat
1143
 
        format = BranchFormat.find_format(self)
1144
 
        return format.get_reference(self)
 
1327
        format = BranchFormat.find_format(self, name=name)
 
1328
        return format.get_reference(self, name=name)
1145
1329
 
1146
 
    def get_branch_transport(self, branch_format):
 
1330
    def get_branch_transport(self, branch_format, name=None):
1147
1331
        """See BzrDir.get_branch_transport()."""
 
1332
        if name is not None:
 
1333
            raise errors.NoColocatedBranchSupport(self)
 
1334
        # XXX: this shouldn't implicitly create the directory if it's just
 
1335
        # promising to get a transport -- mbp 20090727
1148
1336
        if branch_format is None:
1149
1337
            return self.transport.clone('branch')
1150
1338
        try:
1185
1373
            pass
1186
1374
        return self.transport.clone('checkout')
1187
1375
 
 
1376
    def has_workingtree(self):
 
1377
        """Tell if this bzrdir contains a working tree.
 
1378
 
 
1379
        This will still raise an exception if the bzrdir has a workingtree that
 
1380
        is remote & inaccessible.
 
1381
 
 
1382
        Note: if you're going to open the working tree, you should just go
 
1383
        ahead and try, and not ask permission first.
 
1384
        """
 
1385
        from bzrlib.workingtree import WorkingTreeFormat
 
1386
        try:
 
1387
            WorkingTreeFormat.find_format(self)
 
1388
        except errors.NoWorkingTree:
 
1389
            return False
 
1390
        return True
 
1391
 
1188
1392
    def needs_format_conversion(self, format=None):
1189
1393
        """See BzrDir.needs_format_conversion()."""
1190
1394
        if format is None:
 
1395
            symbol_versioning.warn(symbol_versioning.deprecated_in((1, 13, 0))
 
1396
                % 'needs_format_conversion(format=None)')
 
1397
        if format is None:
1191
1398
            format = BzrDirFormat.get_default_format()
1192
1399
        if not isinstance(self._format, format.__class__):
1193
1400
            # it is not a meta dir format, conversion is needed.
1200
1407
                return True
1201
1408
        except errors.NoRepositoryPresent:
1202
1409
            pass
1203
 
        try:
1204
 
            if not isinstance(self.open_branch()._format,
 
1410
        for branch in self.list_branches():
 
1411
            if not isinstance(branch._format,
1205
1412
                              format.get_branch_format().__class__):
1206
1413
                # the branch needs an upgrade.
1207
1414
                return True
1208
 
        except errors.NotBranchError:
1209
 
            pass
1210
1415
        try:
1211
1416
            my_wt = self.open_workingtree(recommend_upgrade=False)
1212
1417
            if not isinstance(my_wt._format,
1217
1422
            pass
1218
1423
        return False
1219
1424
 
1220
 
    def open_branch(self, unsupported=False):
 
1425
    def open_branch(self, name=None, unsupported=False,
 
1426
                    ignore_fallbacks=False):
1221
1427
        """See BzrDir.open_branch."""
1222
 
        format = self.find_branch_format()
 
1428
        format = self.find_branch_format(name=name)
1223
1429
        self._check_supported(format, unsupported)
1224
 
        return format.open(self, _found=True)
 
1430
        return format.open(self, name=name,
 
1431
            _found=True, ignore_fallbacks=ignore_fallbacks)
1225
1432
 
1226
1433
    def open_repository(self, unsupported=False):
1227
1434
        """See BzrDir.open_repository."""
1240
1447
            basedir=self.root_transport.base)
1241
1448
        return format.open(self, _found=True)
1242
1449
 
1243
 
 
1244
 
class BzrDirFormat(object):
1245
 
    """An encapsulation of the initialization and open routines for a format.
1246
 
 
1247
 
    Formats provide three things:
1248
 
     * An initialization routine,
1249
 
     * a format string,
1250
 
     * an open routine.
1251
 
 
1252
 
    Formats are placed in a dict by their format string for reference 
 
1450
    def _get_config(self):
 
1451
        return config.TransportConfig(self.transport, 'control.conf')
 
1452
 
 
1453
 
 
1454
class BzrProber(controldir.Prober):
 
1455
    """Prober for formats that use a .bzr/ control directory."""
 
1456
 
 
1457
    _formats = {}
 
1458
    """The known .bzr formats."""
 
1459
 
 
1460
    @classmethod
 
1461
    def register_bzrdir_format(klass, format):
 
1462
        klass._formats[format.get_format_string()] = format
 
1463
 
 
1464
    @classmethod
 
1465
    def unregister_bzrdir_format(klass, format):
 
1466
        del klass._formats[format.get_format_string()]
 
1467
 
 
1468
    @classmethod
 
1469
    def probe_transport(klass, transport):
 
1470
        """Return the .bzrdir style format present in a directory."""
 
1471
        try:
 
1472
            format_string = transport.get_bytes(".bzr/branch-format")
 
1473
        except errors.NoSuchFile:
 
1474
            raise errors.NotBranchError(path=transport.base)
 
1475
        try:
 
1476
            return klass._formats[format_string]
 
1477
        except KeyError:
 
1478
            raise errors.UnknownFormatError(format=format_string, kind='bzrdir')
 
1479
 
 
1480
 
 
1481
controldir.ControlDirFormat.register_prober(BzrProber)
 
1482
 
 
1483
 
 
1484
class RemoteBzrProber(controldir.Prober):
 
1485
    """Prober for remote servers that provide a Bazaar smart server."""
 
1486
 
 
1487
    @classmethod
 
1488
    def probe_transport(klass, transport):
 
1489
        """Return a RemoteBzrDirFormat object if it looks possible."""
 
1490
        try:
 
1491
            medium = transport.get_smart_medium()
 
1492
        except (NotImplementedError, AttributeError,
 
1493
                errors.TransportNotPossible, errors.NoSmartMedium,
 
1494
                errors.SmartProtocolError):
 
1495
            # no smart server, so not a branch for this format type.
 
1496
            raise errors.NotBranchError(path=transport.base)
 
1497
        else:
 
1498
            # Decline to open it if the server doesn't support our required
 
1499
            # version (3) so that the VFS-based transport will do it.
 
1500
            if medium.should_probe():
 
1501
                try:
 
1502
                    server_version = medium.protocol_version()
 
1503
                except errors.SmartProtocolError:
 
1504
                    # Apparently there's no usable smart server there, even though
 
1505
                    # the medium supports the smart protocol.
 
1506
                    raise errors.NotBranchError(path=transport.base)
 
1507
                if server_version != '2':
 
1508
                    raise errors.NotBranchError(path=transport.base)
 
1509
            return RemoteBzrDirFormat()
 
1510
 
 
1511
 
 
1512
class BzrDirFormat(controldir.ControlDirFormat):
 
1513
    """ControlDirFormat base class for .bzr/ directories.
 
1514
 
 
1515
    Formats are placed in a dict by their format string for reference
1253
1516
    during bzrdir opening. These should be subclasses of BzrDirFormat
1254
1517
    for consistency.
1255
1518
 
1256
1519
    Once a format is deprecated, just deprecate the initialize and open
1257
 
    methods on the format class. Do not deprecate the object, as the 
 
1520
    methods on the format class. Do not deprecate the object, as the
1258
1521
    object will be created every system load.
1259
1522
    """
1260
1523
 
1261
 
    _default_format = None
1262
 
    """The default format used for new .bzr dirs."""
1263
 
 
1264
 
    _formats = {}
1265
 
    """The known formats."""
1266
 
 
1267
 
    _control_formats = []
1268
 
    """The registered control formats - .bzr, ....
1269
 
    
1270
 
    This is a list of BzrDirFormat objects.
1271
 
    """
1272
 
 
1273
 
    _control_server_formats = []
1274
 
    """The registered control server formats, e.g. RemoteBzrDirs.
1275
 
 
1276
 
    This is a list of BzrDirFormat objects.
1277
 
    """
1278
 
 
1279
1524
    _lock_file_name = 'branch-lock'
1280
1525
 
1281
1526
    # _lock_class must be set in subclasses to the lock type, typ.
1282
1527
    # TransportLock or LockDir
1283
1528
 
1284
 
    @classmethod
1285
 
    def find_format(klass, transport, _server_formats=True):
1286
 
        """Return the format present at transport."""
1287
 
        if _server_formats:
1288
 
            formats = klass._control_server_formats + klass._control_formats
1289
 
        else:
1290
 
            formats = klass._control_formats
1291
 
        for format in formats:
1292
 
            try:
1293
 
                return format.probe_transport(transport)
1294
 
            except errors.NotBranchError:
1295
 
                # this format does not find a control dir here.
1296
 
                pass
1297
 
        raise errors.NotBranchError(path=transport.base)
1298
 
 
1299
 
    @classmethod
1300
 
    def probe_transport(klass, transport):
1301
 
        """Return the .bzrdir style format present in a directory."""
1302
 
        try:
1303
 
            format_string = transport.get(".bzr/branch-format").read()
1304
 
        except errors.NoSuchFile:
1305
 
            raise errors.NotBranchError(path=transport.base)
1306
 
 
1307
 
        try:
1308
 
            return klass._formats[format_string]
1309
 
        except KeyError:
1310
 
            raise errors.UnknownFormatError(format=format_string)
1311
 
 
1312
 
    @classmethod
1313
 
    def get_default_format(klass):
1314
 
        """Return the current default format."""
1315
 
        return klass._default_format
1316
 
 
1317
1529
    def get_format_string(self):
1318
1530
        """Return the ASCII format string that identifies this format."""
1319
1531
        raise NotImplementedError(self.get_format_string)
1320
1532
 
1321
 
    def get_format_description(self):
1322
 
        """Return the short description for this format."""
1323
 
        raise NotImplementedError(self.get_format_description)
1324
 
 
1325
 
    def get_converter(self, format=None):
1326
 
        """Return the converter to use to convert bzrdirs needing converts.
1327
 
 
1328
 
        This returns a bzrlib.bzrdir.Converter object.
1329
 
 
1330
 
        This should return the best upgrader to step this format towards the
1331
 
        current default format. In the case of plugins we can/should provide
1332
 
        some means for them to extend the range of returnable converters.
1333
 
 
1334
 
        :param format: Optional format to override the default format of the 
1335
 
                       library.
1336
 
        """
1337
 
        raise NotImplementedError(self.get_converter)
1338
 
 
1339
 
    def initialize(self, url, possible_transports=None):
1340
 
        """Create a bzr control dir at this url and return an opened copy.
1341
 
        
1342
 
        Subclasses should typically override initialize_on_transport
1343
 
        instead of this method.
1344
 
        """
1345
 
        return self.initialize_on_transport(get_transport(url,
1346
 
                                                          possible_transports))
1347
 
 
1348
1533
    def initialize_on_transport(self, transport):
1349
1534
        """Initialize a new bzrdir in the base directory of a Transport."""
1350
 
        # Since we don't have a .bzr directory, inherit the
 
1535
        try:
 
1536
            # can we hand off the request to the smart server rather than using
 
1537
            # vfs calls?
 
1538
            client_medium = transport.get_smart_medium()
 
1539
        except errors.NoSmartMedium:
 
1540
            return self._initialize_on_transport_vfs(transport)
 
1541
        else:
 
1542
            # Current RPC's only know how to create bzr metadir1 instances, so
 
1543
            # we still delegate to vfs methods if the requested format is not a
 
1544
            # metadir1
 
1545
            if type(self) != BzrDirMetaFormat1:
 
1546
                return self._initialize_on_transport_vfs(transport)
 
1547
            remote_format = RemoteBzrDirFormat()
 
1548
            self._supply_sub_formats_to(remote_format)
 
1549
            return remote_format.initialize_on_transport(transport)
 
1550
 
 
1551
    def initialize_on_transport_ex(self, transport, use_existing_dir=False,
 
1552
        create_prefix=False, force_new_repo=False, stacked_on=None,
 
1553
        stack_on_pwd=None, repo_format_name=None, make_working_trees=None,
 
1554
        shared_repo=False, vfs_only=False):
 
1555
        """Create this format on transport.
 
1556
 
 
1557
        The directory to initialize will be created.
 
1558
 
 
1559
        :param force_new_repo: Do not use a shared repository for the target,
 
1560
                               even if one is available.
 
1561
        :param create_prefix: Create any missing directories leading up to
 
1562
            to_transport.
 
1563
        :param use_existing_dir: Use an existing directory if one exists.
 
1564
        :param stacked_on: A url to stack any created branch on, None to follow
 
1565
            any target stacking policy.
 
1566
        :param stack_on_pwd: If stack_on is relative, the location it is
 
1567
            relative to.
 
1568
        :param repo_format_name: If non-None, a repository will be
 
1569
            made-or-found. Should none be found, or if force_new_repo is True
 
1570
            the repo_format_name is used to select the format of repository to
 
1571
            create.
 
1572
        :param make_working_trees: Control the setting of make_working_trees
 
1573
            for a new shared repository when one is made. None to use whatever
 
1574
            default the format has.
 
1575
        :param shared_repo: Control whether made repositories are shared or
 
1576
            not.
 
1577
        :param vfs_only: If True do not attempt to use a smart server
 
1578
        :return: repo, bzrdir, require_stacking, repository_policy. repo is
 
1579
            None if none was created or found, bzrdir is always valid.
 
1580
            require_stacking is the result of examining the stacked_on
 
1581
            parameter and any stacking policy found for the target.
 
1582
        """
 
1583
        if not vfs_only:
 
1584
            # Try to hand off to a smart server 
 
1585
            try:
 
1586
                client_medium = transport.get_smart_medium()
 
1587
            except errors.NoSmartMedium:
 
1588
                pass
 
1589
            else:
 
1590
                # TODO: lookup the local format from a server hint.
 
1591
                remote_dir_format = RemoteBzrDirFormat()
 
1592
                remote_dir_format._network_name = self.network_name()
 
1593
                self._supply_sub_formats_to(remote_dir_format)
 
1594
                return remote_dir_format.initialize_on_transport_ex(transport,
 
1595
                    use_existing_dir=use_existing_dir, create_prefix=create_prefix,
 
1596
                    force_new_repo=force_new_repo, stacked_on=stacked_on,
 
1597
                    stack_on_pwd=stack_on_pwd, repo_format_name=repo_format_name,
 
1598
                    make_working_trees=make_working_trees, shared_repo=shared_repo)
 
1599
        # XXX: Refactor the create_prefix/no_create_prefix code into a
 
1600
        #      common helper function
 
1601
        # The destination may not exist - if so make it according to policy.
 
1602
        def make_directory(transport):
 
1603
            transport.mkdir('.')
 
1604
            return transport
 
1605
        def redirected(transport, e, redirection_notice):
 
1606
            note(redirection_notice)
 
1607
            return transport._redirected_to(e.source, e.target)
 
1608
        try:
 
1609
            transport = do_catching_redirections(make_directory, transport,
 
1610
                redirected)
 
1611
        except errors.FileExists:
 
1612
            if not use_existing_dir:
 
1613
                raise
 
1614
        except errors.NoSuchFile:
 
1615
            if not create_prefix:
 
1616
                raise
 
1617
            transport.create_prefix()
 
1618
 
 
1619
        require_stacking = (stacked_on is not None)
 
1620
        # Now the target directory exists, but doesn't have a .bzr
 
1621
        # directory. So we need to create it, along with any work to create
 
1622
        # all of the dependent branches, etc.
 
1623
 
 
1624
        result = self.initialize_on_transport(transport)
 
1625
        if repo_format_name:
 
1626
            try:
 
1627
                # use a custom format
 
1628
                result._format.repository_format = \
 
1629
                    repository.network_format_registry.get(repo_format_name)
 
1630
            except AttributeError:
 
1631
                # The format didn't permit it to be set.
 
1632
                pass
 
1633
            # A repository is desired, either in-place or shared.
 
1634
            repository_policy = result.determine_repository_policy(
 
1635
                force_new_repo, stacked_on, stack_on_pwd,
 
1636
                require_stacking=require_stacking)
 
1637
            result_repo, is_new_repo = repository_policy.acquire_repository(
 
1638
                make_working_trees, shared_repo)
 
1639
            if not require_stacking and repository_policy._require_stacking:
 
1640
                require_stacking = True
 
1641
                result._format.require_stacking()
 
1642
            result_repo.lock_write()
 
1643
        else:
 
1644
            result_repo = None
 
1645
            repository_policy = None
 
1646
        return result_repo, result, require_stacking, repository_policy
 
1647
 
 
1648
    def _initialize_on_transport_vfs(self, transport):
 
1649
        """Initialize a new bzrdir using VFS calls.
 
1650
 
 
1651
        :param transport: The transport to create the .bzr directory in.
 
1652
        :return: A
 
1653
        """
 
1654
        # Since we are creating a .bzr directory, inherit the
1351
1655
        # mode from the root directory
1352
1656
        temp_control = lockable_files.LockableFiles(transport,
1353
1657
                            '', lockable_files.TransportLock)
1355
1659
                                      # FIXME: RBC 20060121 don't peek under
1356
1660
                                      # the covers
1357
1661
                                      mode=temp_control._dir_mode)
 
1662
        if sys.platform == 'win32' and isinstance(transport, local.LocalTransport):
 
1663
            win32utils.set_file_attr_hidden(transport._abspath('.bzr'))
1358
1664
        file_mode = temp_control._file_mode
1359
1665
        del temp_control
1360
 
        mutter('created control directory in ' + transport.base)
1361
 
        control = transport.clone('.bzr')
1362
 
        utf8_files = [('README', 
1363
 
                       "This is a Bazaar-NG control directory.\n"
1364
 
                       "Do not change any files in this directory.\n"),
 
1666
        bzrdir_transport = transport.clone('.bzr')
 
1667
        utf8_files = [('README',
 
1668
                       "This is a Bazaar control directory.\n"
 
1669
                       "Do not change any files in this directory.\n"
 
1670
                       "See http://bazaar.canonical.com/ for more information about Bazaar.\n"),
1365
1671
                      ('branch-format', self.get_format_string()),
1366
1672
                      ]
1367
1673
        # NB: no need to escape relative paths that are url safe.
1368
 
        control_files = lockable_files.LockableFiles(control,
1369
 
                            self._lock_file_name, self._lock_class)
 
1674
        control_files = lockable_files.LockableFiles(bzrdir_transport,
 
1675
            self._lock_file_name, self._lock_class)
1370
1676
        control_files.create_lock()
1371
1677
        control_files.lock_write()
1372
1678
        try:
1373
 
            for file, content in utf8_files:
1374
 
                control_files.put_utf8(file, content)
 
1679
            for (filename, content) in utf8_files:
 
1680
                bzrdir_transport.put_bytes(filename, content,
 
1681
                    mode=file_mode)
1375
1682
        finally:
1376
1683
            control_files.unlock()
1377
1684
        return self.open(transport, _found=True)
1378
1685
 
1379
 
    def is_supported(self):
1380
 
        """Is this format supported?
1381
 
 
1382
 
        Supported formats must be initializable and openable.
1383
 
        Unsupported formats may not support initialization or committing or 
1384
 
        some other features depending on the reason for not being supported.
1385
 
        """
1386
 
        return True
1387
 
 
1388
 
    def same_model(self, target_format):
1389
 
        return (self.repository_format.rich_root_data == 
1390
 
            target_format.rich_root_data)
1391
 
 
1392
 
    @classmethod
1393
 
    def known_formats(klass):
1394
 
        """Return all the known formats.
1395
 
        
1396
 
        Concrete formats should override _known_formats.
1397
 
        """
1398
 
        # There is double indirection here to make sure that control 
1399
 
        # formats used by more than one dir format will only be probed 
1400
 
        # once. This can otherwise be quite expensive for remote connections.
1401
 
        result = set()
1402
 
        for format in klass._control_formats:
1403
 
            result.update(format._known_formats())
1404
 
        return result
1405
 
    
1406
 
    @classmethod
1407
 
    def _known_formats(klass):
1408
 
        """Return the known format instances for this control format."""
1409
 
        return set(klass._formats.values())
1410
 
 
1411
1686
    def open(self, transport, _found=False):
1412
1687
        """Return an instance of this format for the dir transport points at.
1413
 
        
 
1688
 
1414
1689
        _found is a private parameter, do not use it.
1415
1690
        """
1416
1691
        if not _found:
1417
 
            found_format = BzrDirFormat.find_format(transport)
 
1692
            found_format = controldir.ControlDirFormat.find_format(transport)
1418
1693
            if not isinstance(found_format, self.__class__):
1419
1694
                raise AssertionError("%s was asked to open %s, but it seems to need "
1420
 
                        "format %s" 
 
1695
                        "format %s"
1421
1696
                        % (self, transport, found_format))
 
1697
            # Allow subclasses - use the found format.
 
1698
            self._supply_sub_formats_to(found_format)
 
1699
            return found_format._open(transport)
1422
1700
        return self._open(transport)
1423
1701
 
1424
1702
    def _open(self, transport):
1431
1709
 
1432
1710
    @classmethod
1433
1711
    def register_format(klass, format):
1434
 
        klass._formats[format.get_format_string()] = format
1435
 
 
1436
 
    @classmethod
1437
 
    def register_control_format(klass, format):
1438
 
        """Register a format that does not use '.bzr' for its control dir.
1439
 
 
1440
 
        TODO: This should be pulled up into a 'ControlDirFormat' base class
1441
 
        which BzrDirFormat can inherit from, and renamed to register_format 
1442
 
        there. It has been done without that for now for simplicity of
1443
 
        implementation.
1444
 
        """
1445
 
        klass._control_formats.append(format)
1446
 
 
1447
 
    @classmethod
1448
 
    def register_control_server_format(klass, format):
1449
 
        """Register a control format for client-server environments.
1450
 
 
1451
 
        These formats will be tried before ones registered with
1452
 
        register_control_format.  This gives implementations that decide to the
1453
 
        chance to grab it before anything looks at the contents of the format
1454
 
        file.
1455
 
        """
1456
 
        klass._control_server_formats.append(format)
1457
 
 
1458
 
    @classmethod
1459
 
    @symbol_versioning.deprecated_method(symbol_versioning.zero_fourteen)
1460
 
    def set_default_format(klass, format):
1461
 
        klass._set_default_format(format)
1462
 
 
1463
 
    @classmethod
1464
 
    def _set_default_format(klass, format):
1465
 
        """Set default format (for testing behavior of defaults only)"""
1466
 
        klass._default_format = format
1467
 
 
1468
 
    def __str__(self):
1469
 
        # Trim the newline
1470
 
        return self.get_format_string().rstrip()
 
1712
        BzrProber.register_bzrdir_format(format)
 
1713
        # bzr native formats have a network name of their format string.
 
1714
        controldir.network_format_registry.register(format.get_format_string(), format.__class__)
 
1715
        controldir.ControlDirFormat.register_format(format)
 
1716
 
 
1717
    def _supply_sub_formats_to(self, other_format):
 
1718
        """Give other_format the same values for sub formats as this has.
 
1719
 
 
1720
        This method is expected to be used when parameterising a
 
1721
        RemoteBzrDirFormat instance with the parameters from a
 
1722
        BzrDirMetaFormat1 instance.
 
1723
 
 
1724
        :param other_format: other_format is a format which should be
 
1725
            compatible with whatever sub formats are supported by self.
 
1726
        :return: None.
 
1727
        """
1471
1728
 
1472
1729
    @classmethod
1473
1730
    def unregister_format(klass, format):
1474
 
        assert klass._formats[format.get_format_string()] is format
1475
 
        del klass._formats[format.get_format_string()]
1476
 
 
1477
 
    @classmethod
1478
 
    def unregister_control_format(klass, format):
1479
 
        klass._control_formats.remove(format)
 
1731
        BzrProber.unregister_bzrdir_format(format)
 
1732
        controldir.ControlDirFormat.unregister_format(format)
 
1733
        controldir.network_format_registry.remove(format.get_format_string())
1480
1734
 
1481
1735
 
1482
1736
class BzrDirFormat4(BzrDirFormat):
1506
1760
        """See BzrDirFormat.get_converter()."""
1507
1761
        # there is one and only one upgrade path here.
1508
1762
        return ConvertBzrDir4To5()
1509
 
        
 
1763
 
1510
1764
    def initialize_on_transport(self, transport):
1511
1765
        """Format 4 branches cannot be created."""
1512
1766
        raise errors.UninitializableFormat(self)
1515
1769
        """Format 4 is not supported.
1516
1770
 
1517
1771
        It is not supported because the model changed from 4 to 5 and the
1518
 
        conversion logic is expensive - so doing it on the fly was not 
 
1772
        conversion logic is expensive - so doing it on the fly was not
1519
1773
        feasible.
1520
1774
        """
1521
1775
        return False
1522
1776
 
 
1777
    def network_name(self):
 
1778
        return self.get_format_string()
 
1779
 
1523
1780
    def _open(self, transport):
1524
1781
        """See BzrDirFormat._open."""
1525
1782
        return BzrDir4(transport, self)
1531
1788
    repository_format = property(__return_repository_format)
1532
1789
 
1533
1790
 
1534
 
class BzrDirFormat5(BzrDirFormat):
 
1791
class BzrDirFormatAllInOne(BzrDirFormat):
 
1792
    """Common class for formats before meta-dirs."""
 
1793
 
 
1794
    def initialize_on_transport_ex(self, transport, use_existing_dir=False,
 
1795
        create_prefix=False, force_new_repo=False, stacked_on=None,
 
1796
        stack_on_pwd=None, repo_format_name=None, make_working_trees=None,
 
1797
        shared_repo=False):
 
1798
        """See BzrDirFormat.initialize_on_transport_ex."""
 
1799
        require_stacking = (stacked_on is not None)
 
1800
        # Format 5 cannot stack, but we've been asked to - actually init
 
1801
        # a Meta1Dir
 
1802
        if require_stacking:
 
1803
            format = BzrDirMetaFormat1()
 
1804
            return format.initialize_on_transport_ex(transport,
 
1805
                use_existing_dir=use_existing_dir, create_prefix=create_prefix,
 
1806
                force_new_repo=force_new_repo, stacked_on=stacked_on,
 
1807
                stack_on_pwd=stack_on_pwd, repo_format_name=repo_format_name,
 
1808
                make_working_trees=make_working_trees, shared_repo=shared_repo)
 
1809
        return BzrDirFormat.initialize_on_transport_ex(self, transport,
 
1810
            use_existing_dir=use_existing_dir, create_prefix=create_prefix,
 
1811
            force_new_repo=force_new_repo, stacked_on=stacked_on,
 
1812
            stack_on_pwd=stack_on_pwd, repo_format_name=repo_format_name,
 
1813
            make_working_trees=make_working_trees, shared_repo=shared_repo)
 
1814
 
 
1815
 
 
1816
class BzrDirFormat5(BzrDirFormatAllInOne):
1535
1817
    """Bzr control format 5.
1536
1818
 
1537
1819
    This format is a combined format for working tree, branch and repository.
1538
1820
    It has:
1539
 
     - Format 2 working trees [always] 
1540
 
     - Format 4 branches [always] 
 
1821
     - Format 2 working trees [always]
 
1822
     - Format 4 branches [always]
1541
1823
     - Format 5 repositories [always]
1542
1824
       Unhashed stores in the repository.
1543
1825
    """
1548
1830
        """See BzrDirFormat.get_format_string()."""
1549
1831
        return "Bazaar-NG branch, format 5\n"
1550
1832
 
 
1833
    def get_branch_format(self):
 
1834
        from bzrlib import branch
 
1835
        return branch.BzrBranchFormat4()
 
1836
 
1551
1837
    def get_format_description(self):
1552
1838
        """See BzrDirFormat.get_format_description()."""
1553
1839
        return "All-in-one format 5"
1559
1845
 
1560
1846
    def _initialize_for_clone(self, url):
1561
1847
        return self.initialize_on_transport(get_transport(url), _cloning=True)
1562
 
        
 
1848
 
1563
1849
    def initialize_on_transport(self, transport, _cloning=False):
1564
1850
        """Format 5 dirs always have working tree, branch and repository.
1565
 
        
 
1851
 
1566
1852
        Except when they are being cloned.
1567
1853
        """
1568
1854
        from bzrlib.branch import BzrBranchFormat4
1569
1855
        from bzrlib.repofmt.weaverepo import RepositoryFormat5
1570
 
        from bzrlib.workingtree import WorkingTreeFormat2
1571
1856
        result = (super(BzrDirFormat5, self).initialize_on_transport(transport))
1572
1857
        RepositoryFormat5().initialize(result, _internal=True)
1573
1858
        if not _cloning:
1574
1859
            branch = BzrBranchFormat4().initialize(result)
1575
 
            try:
1576
 
                WorkingTreeFormat2().initialize(result)
1577
 
            except errors.NotLocalUrl:
1578
 
                # Even though we can't access the working tree, we need to
1579
 
                # create its control files.
1580
 
                WorkingTreeFormat2().stub_initialize_remote(branch.control_files)
 
1860
            result._init_workingtree()
1581
1861
        return result
1582
1862
 
 
1863
    def network_name(self):
 
1864
        return self.get_format_string()
 
1865
 
1583
1866
    def _open(self, transport):
1584
1867
        """See BzrDirFormat._open."""
1585
1868
        return BzrDir5(transport, self)
1591
1874
    repository_format = property(__return_repository_format)
1592
1875
 
1593
1876
 
1594
 
class BzrDirFormat6(BzrDirFormat):
 
1877
class BzrDirFormat6(BzrDirFormatAllInOne):
1595
1878
    """Bzr control format 6.
1596
1879
 
1597
1880
    This format is a combined format for working tree, branch and repository.
1598
1881
    It has:
1599
 
     - Format 2 working trees [always] 
1600
 
     - Format 4 branches [always] 
 
1882
     - Format 2 working trees [always]
 
1883
     - Format 4 branches [always]
1601
1884
     - Format 6 repositories [always]
1602
1885
    """
1603
1886
 
1611
1894
        """See BzrDirFormat.get_format_description()."""
1612
1895
        return "All-in-one format 6"
1613
1896
 
 
1897
    def get_branch_format(self):
 
1898
        from bzrlib import branch
 
1899
        return branch.BzrBranchFormat4()
 
1900
 
1614
1901
    def get_converter(self, format=None):
1615
1902
        """See BzrDirFormat.get_converter()."""
1616
1903
        # there is one and only one upgrade path here.
1617
1904
        return ConvertBzrDir6ToMeta()
1618
 
        
 
1905
 
1619
1906
    def _initialize_for_clone(self, url):
1620
1907
        return self.initialize_on_transport(get_transport(url), _cloning=True)
1621
1908
 
1622
1909
    def initialize_on_transport(self, transport, _cloning=False):
1623
1910
        """Format 6 dirs always have working tree, branch and repository.
1624
 
        
 
1911
 
1625
1912
        Except when they are being cloned.
1626
1913
        """
1627
1914
        from bzrlib.branch import BzrBranchFormat4
1628
1915
        from bzrlib.repofmt.weaverepo import RepositoryFormat6
1629
 
        from bzrlib.workingtree import WorkingTreeFormat2
1630
1916
        result = super(BzrDirFormat6, self).initialize_on_transport(transport)
1631
1917
        RepositoryFormat6().initialize(result, _internal=True)
1632
1918
        if not _cloning:
1633
1919
            branch = BzrBranchFormat4().initialize(result)
1634
 
            try:
1635
 
                WorkingTreeFormat2().initialize(result)
1636
 
            except errors.NotLocalUrl:
1637
 
                # Even though we can't access the working tree, we need to
1638
 
                # create its control files.
1639
 
                WorkingTreeFormat2().stub_initialize_remote(branch.control_files)
 
1920
            result._init_workingtree()
1640
1921
        return result
1641
1922
 
 
1923
    def network_name(self):
 
1924
        return self.get_format_string()
 
1925
 
1642
1926
    def _open(self, transport):
1643
1927
        """See BzrDirFormat._open."""
1644
1928
        return BzrDir6(transport, self)
1666
1950
    def __init__(self):
1667
1951
        self._workingtree_format = None
1668
1952
        self._branch_format = None
 
1953
        self._repository_format = None
1669
1954
 
1670
1955
    def __eq__(self, other):
1671
1956
        if other.__class__ is not self.__class__:
1688
1973
    def set_branch_format(self, format):
1689
1974
        self._branch_format = format
1690
1975
 
 
1976
    def require_stacking(self, stack_on=None, possible_transports=None,
 
1977
            _skip_repo=False):
 
1978
        """We have a request to stack, try to ensure the formats support it.
 
1979
 
 
1980
        :param stack_on: If supplied, it is the URL to a branch that we want to
 
1981
            stack on. Check to see if that format supports stacking before
 
1982
            forcing an upgrade.
 
1983
        """
 
1984
        # Stacking is desired. requested by the target, but does the place it
 
1985
        # points at support stacking? If it doesn't then we should
 
1986
        # not implicitly upgrade. We check this here.
 
1987
        new_repo_format = None
 
1988
        new_branch_format = None
 
1989
 
 
1990
        # a bit of state for get_target_branch so that we don't try to open it
 
1991
        # 2 times, for both repo *and* branch
 
1992
        target = [None, False, None] # target_branch, checked, upgrade anyway
 
1993
        def get_target_branch():
 
1994
            if target[1]:
 
1995
                # We've checked, don't check again
 
1996
                return target
 
1997
            if stack_on is None:
 
1998
                # No target format, that means we want to force upgrading
 
1999
                target[:] = [None, True, True]
 
2000
                return target
 
2001
            try:
 
2002
                target_dir = BzrDir.open(stack_on,
 
2003
                    possible_transports=possible_transports)
 
2004
            except errors.NotBranchError:
 
2005
                # Nothing there, don't change formats
 
2006
                target[:] = [None, True, False]
 
2007
                return target
 
2008
            except errors.JailBreak:
 
2009
                # JailBreak, JFDI and upgrade anyway
 
2010
                target[:] = [None, True, True]
 
2011
                return target
 
2012
            try:
 
2013
                target_branch = target_dir.open_branch()
 
2014
            except errors.NotBranchError:
 
2015
                # No branch, don't upgrade formats
 
2016
                target[:] = [None, True, False]
 
2017
                return target
 
2018
            target[:] = [target_branch, True, False]
 
2019
            return target
 
2020
 
 
2021
        if (not _skip_repo and
 
2022
                 not self.repository_format.supports_external_lookups):
 
2023
            # We need to upgrade the Repository.
 
2024
            target_branch, _, do_upgrade = get_target_branch()
 
2025
            if target_branch is None:
 
2026
                # We don't have a target branch, should we upgrade anyway?
 
2027
                if do_upgrade:
 
2028
                    # stack_on is inaccessible, JFDI.
 
2029
                    # TODO: bad monkey, hard-coded formats...
 
2030
                    if self.repository_format.rich_root_data:
 
2031
                        new_repo_format = pack_repo.RepositoryFormatKnitPack5RichRoot()
 
2032
                    else:
 
2033
                        new_repo_format = pack_repo.RepositoryFormatKnitPack5()
 
2034
            else:
 
2035
                # If the target already supports stacking, then we know the
 
2036
                # project is already able to use stacking, so auto-upgrade
 
2037
                # for them
 
2038
                new_repo_format = target_branch.repository._format
 
2039
                if not new_repo_format.supports_external_lookups:
 
2040
                    # target doesn't, source doesn't, so don't auto upgrade
 
2041
                    # repo
 
2042
                    new_repo_format = None
 
2043
            if new_repo_format is not None:
 
2044
                self.repository_format = new_repo_format
 
2045
                note('Source repository format does not support stacking,'
 
2046
                     ' using format:\n  %s',
 
2047
                     new_repo_format.get_format_description())
 
2048
 
 
2049
        if not self.get_branch_format().supports_stacking():
 
2050
            # We just checked the repo, now lets check if we need to
 
2051
            # upgrade the branch format
 
2052
            target_branch, _, do_upgrade = get_target_branch()
 
2053
            if target_branch is None:
 
2054
                if do_upgrade:
 
2055
                    # TODO: bad monkey, hard-coded formats...
 
2056
                    new_branch_format = branch.BzrBranchFormat7()
 
2057
            else:
 
2058
                new_branch_format = target_branch._format
 
2059
                if not new_branch_format.supports_stacking():
 
2060
                    new_branch_format = None
 
2061
            if new_branch_format is not None:
 
2062
                # Does support stacking, use its format.
 
2063
                self.set_branch_format(new_branch_format)
 
2064
                note('Source branch format does not support stacking,'
 
2065
                     ' using format:\n  %s',
 
2066
                     new_branch_format.get_format_description())
 
2067
 
1691
2068
    def get_converter(self, format=None):
1692
2069
        """See BzrDirFormat.get_converter()."""
1693
2070
        if format is None:
1705
2082
        """See BzrDirFormat.get_format_description()."""
1706
2083
        return "Meta directory format 1"
1707
2084
 
 
2085
    def network_name(self):
 
2086
        return self.get_format_string()
 
2087
 
1708
2088
    def _open(self, transport):
1709
2089
        """See BzrDirFormat._open."""
1710
 
        return BzrDirMeta1(transport, self)
 
2090
        # Create a new format instance because otherwise initialisation of new
 
2091
        # metadirs share the global default format object leading to alias
 
2092
        # problems.
 
2093
        format = BzrDirMetaFormat1()
 
2094
        self._supply_sub_formats_to(format)
 
2095
        return BzrDirMeta1(transport, format)
1711
2096
 
1712
2097
    def __return_repository_format(self):
1713
2098
        """Circular import protection."""
1714
 
        if getattr(self, '_repository_format', None):
 
2099
        if self._repository_format:
1715
2100
            return self._repository_format
1716
2101
        from bzrlib.repository import RepositoryFormat
1717
2102
        return RepositoryFormat.get_default_format()
1718
2103
 
1719
 
    def __set_repository_format(self, value):
 
2104
    def _set_repository_format(self, value):
1720
2105
        """Allow changing the repository format for metadir formats."""
1721
2106
        self._repository_format = value
1722
2107
 
1723
 
    repository_format = property(__return_repository_format, __set_repository_format)
 
2108
    repository_format = property(__return_repository_format,
 
2109
        _set_repository_format)
 
2110
 
 
2111
    def _supply_sub_formats_to(self, other_format):
 
2112
        """Give other_format the same values for sub formats as this has.
 
2113
 
 
2114
        This method is expected to be used when parameterising a
 
2115
        RemoteBzrDirFormat instance with the parameters from a
 
2116
        BzrDirMetaFormat1 instance.
 
2117
 
 
2118
        :param other_format: other_format is a format which should be
 
2119
            compatible with whatever sub formats are supported by self.
 
2120
        :return: None.
 
2121
        """
 
2122
        if getattr(self, '_repository_format', None) is not None:
 
2123
            other_format.repository_format = self.repository_format
 
2124
        if self._branch_format is not None:
 
2125
            other_format._branch_format = self._branch_format
 
2126
        if self._workingtree_format is not None:
 
2127
            other_format.workingtree_format = self.workingtree_format
1724
2128
 
1725
2129
    def __get_workingtree_format(self):
1726
2130
        if self._workingtree_format is None:
1735
2139
                                  __set_workingtree_format)
1736
2140
 
1737
2141
 
1738
 
# Register bzr control format
1739
 
BzrDirFormat.register_control_format(BzrDirFormat)
1740
 
 
1741
2142
# Register bzr formats
1742
2143
BzrDirFormat.register_format(BzrDirFormat4())
1743
2144
BzrDirFormat.register_format(BzrDirFormat5())
1744
2145
BzrDirFormat.register_format(BzrDirFormat6())
1745
2146
__default_format = BzrDirMetaFormat1()
1746
2147
BzrDirFormat.register_format(__default_format)
1747
 
BzrDirFormat._default_format = __default_format
 
2148
controldir.ControlDirFormat._default_format = __default_format
1748
2149
 
1749
2150
 
1750
2151
class Converter(object):
1772
2173
        self.absent_revisions = set()
1773
2174
        self.text_count = 0
1774
2175
        self.revisions = {}
1775
 
        
 
2176
 
1776
2177
    def convert(self, to_convert, pb):
1777
2178
        """See Converter.convert()."""
1778
2179
        self.bzrdir = to_convert
1779
 
        self.pb = pb
1780
 
        self.pb.note('starting upgrade from format 4 to 5')
1781
 
        if isinstance(self.bzrdir.transport, LocalTransport):
1782
 
            self.bzrdir.get_workingtree_transport(None).delete('stat-cache')
1783
 
        self._convert_to_weaves()
1784
 
        return BzrDir.open(self.bzrdir.root_transport.base)
 
2180
        if pb is not None:
 
2181
            warnings.warn("pb parameter to convert() is deprecated")
 
2182
        self.pb = ui.ui_factory.nested_progress_bar()
 
2183
        try:
 
2184
            ui.ui_factory.note('starting upgrade from format 4 to 5')
 
2185
            if isinstance(self.bzrdir.transport, local.LocalTransport):
 
2186
                self.bzrdir.get_workingtree_transport(None).delete('stat-cache')
 
2187
            self._convert_to_weaves()
 
2188
            return BzrDir.open(self.bzrdir.user_url)
 
2189
        finally:
 
2190
            self.pb.finished()
1785
2191
 
1786
2192
    def _convert_to_weaves(self):
1787
 
        self.pb.note('note: upgrade may be faster if all store files are ungzipped first')
 
2193
        ui.ui_factory.note('note: upgrade may be faster if all store files are ungzipped first')
1788
2194
        try:
1789
2195
            # TODO permissions
1790
2196
            stat = self.bzrdir.transport.stat('weaves')
1818
2224
        self.pb.clear()
1819
2225
        self._write_all_weaves()
1820
2226
        self._write_all_revs()
1821
 
        self.pb.note('upgraded to weaves:')
1822
 
        self.pb.note('  %6d revisions and inventories', len(self.revisions))
1823
 
        self.pb.note('  %6d revisions not present', len(self.absent_revisions))
1824
 
        self.pb.note('  %6d texts', self.text_count)
 
2227
        ui.ui_factory.note('upgraded to weaves:')
 
2228
        ui.ui_factory.note('  %6d revisions and inventories' % len(self.revisions))
 
2229
        ui.ui_factory.note('  %6d revisions not present' % len(self.absent_revisions))
 
2230
        ui.ui_factory.note('  %6d texts' % self.text_count)
1825
2231
        self._cleanup_spare_files_after_format4()
1826
 
        self.branch.control_files.put_utf8('branch-format', BzrDirFormat5().get_format_string())
 
2232
        self.branch._transport.put_bytes(
 
2233
            'branch-format',
 
2234
            BzrDirFormat5().get_format_string(),
 
2235
            mode=self.bzrdir._get_file_mode())
1827
2236
 
1828
2237
    def _cleanup_spare_files_after_format4(self):
1829
2238
        # FIXME working tree upgrade foo.
1838
2247
 
1839
2248
    def _convert_working_inv(self):
1840
2249
        inv = xml4.serializer_v4.read_inventory(
1841
 
                    self.branch.control_files.get('inventory'))
 
2250
                self.branch._transport.get('inventory'))
1842
2251
        new_inv_xml = xml5.serializer_v5.write_inventory_to_string(inv, working=True)
1843
 
        # FIXME inventory is a working tree change.
1844
 
        self.branch.control_files.put('inventory', StringIO(new_inv_xml))
 
2252
        self.branch._transport.put_bytes('inventory', new_inv_xml,
 
2253
            mode=self.bzrdir._get_file_mode())
1845
2254
 
1846
2255
    def _write_all_weaves(self):
1847
2256
        controlweaves = WeaveStore(self.bzrdir.transport, prefixed=False)
1867
2276
        self.bzrdir.transport.mkdir('revision-store')
1868
2277
        revision_transport = self.bzrdir.transport.clone('revision-store')
1869
2278
        # TODO permissions
1870
 
        _revision_store = TextRevisionStore(TextStore(revision_transport,
1871
 
                                                      prefixed=False,
1872
 
                                                      compressed=True))
 
2279
        from bzrlib.xml5 import serializer_v5
 
2280
        from bzrlib.repofmt.weaverepo import RevisionTextStore
 
2281
        revision_store = RevisionTextStore(revision_transport,
 
2282
            serializer_v5, False, versionedfile.PrefixMapper(),
 
2283
            lambda:True, lambda:True)
1873
2284
        try:
1874
 
            transaction = WriteTransaction()
1875
2285
            for i, rev_id in enumerate(self.converted_revs):
1876
2286
                self.pb.update('write revision', i, len(self.converted_revs))
1877
 
                _revision_store.add_revision(self.revisions[rev_id], transaction)
 
2287
                text = serializer_v5.write_revision_to_string(
 
2288
                    self.revisions[rev_id])
 
2289
                key = (rev_id,)
 
2290
                revision_store.add_lines(key, None, osutils.split_lines(text))
1878
2291
        finally:
1879
2292
            self.pb.clear()
1880
 
            
 
2293
 
1881
2294
    def _load_one_rev(self, rev_id):
1882
2295
        """Load a revision object into memory.
1883
2296
 
1888
2301
                       len(self.known_revisions))
1889
2302
        if not self.branch.repository.has_revision(rev_id):
1890
2303
            self.pb.clear()
1891
 
            self.pb.note('revision {%s} not present in branch; '
1892
 
                         'will be converted as a ghost',
 
2304
            ui.ui_factory.note('revision {%s} not present in branch; '
 
2305
                         'will be converted as a ghost' %
1893
2306
                         rev_id)
1894
2307
            self.absent_revisions.add(rev_id)
1895
2308
        else:
1896
 
            rev = self.branch.repository._revision_store.get_revision(rev_id,
1897
 
                self.branch.repository.get_transaction())
 
2309
            rev = self.branch.repository.get_revision(rev_id)
1898
2310
            for parent_id in rev.parent_ids:
1899
2311
                self.known_revisions.add(parent_id)
1900
2312
                self.to_read.append(parent_id)
1901
2313
            self.revisions[rev_id] = rev
1902
2314
 
1903
2315
    def _load_old_inventory(self, rev_id):
1904
 
        assert rev_id not in self.converted_revs
1905
 
        old_inv_xml = self.branch.repository.inventory_store.get(rev_id).read()
 
2316
        f = self.branch.repository.inventory_store.get(rev_id)
 
2317
        try:
 
2318
            old_inv_xml = f.read()
 
2319
        finally:
 
2320
            f.close()
1906
2321
        inv = xml4.serializer_v4.read_inventory_from_string(old_inv_xml)
1907
2322
        inv.revision_id = rev_id
1908
2323
        rev = self.revisions[rev_id]
1909
 
        if rev.inventory_sha1:
1910
 
            assert rev.inventory_sha1 == sha_string(old_inv_xml), \
1911
 
                'inventory sha mismatch for {%s}' % rev_id
1912
2324
        return inv
1913
2325
 
1914
2326
    def _load_updated_inventory(self, rev_id):
1915
 
        assert rev_id in self.converted_revs
1916
2327
        inv_xml = self.inv_weave.get_text(rev_id)
1917
 
        inv = xml5.serializer_v5.read_inventory_from_string(inv_xml)
 
2328
        inv = xml5.serializer_v5.read_inventory_from_string(inv_xml, rev_id)
1918
2329
        return inv
1919
2330
 
1920
2331
    def _convert_one_rev(self, rev_id):
1928
2339
        self.converted_revs.add(rev_id)
1929
2340
 
1930
2341
    def _store_new_inv(self, rev, inv, present_parents):
1931
 
        # the XML is now updated with text versions
1932
 
        if __debug__:
1933
 
            entries = inv.iter_entries()
1934
 
            entries.next()
1935
 
            for path, ie in entries:
1936
 
                assert getattr(ie, 'revision', None) is not None, \
1937
 
                    'no revision on {%s} in {%s}' % \
1938
 
                    (file_id, rev.revision_id)
1939
2342
        new_inv_xml = xml5.serializer_v5.write_inventory_to_string(inv)
1940
2343
        new_inv_sha1 = sha_string(new_inv_xml)
1941
2344
        self.inv_weave.add_lines(rev.revision_id,
1970
2373
            self.text_weaves[file_id] = w
1971
2374
        text_changed = False
1972
2375
        parent_candiate_entries = ie.parent_candidates(parent_invs)
1973
 
        for old_revision in parent_candiate_entries.keys():
1974
 
            # if this fails, its a ghost ?
1975
 
            assert old_revision in self.converted_revs, \
1976
 
                "Revision {%s} not in converted_revs" % old_revision
1977
2376
        heads = graph.Graph(self).heads(parent_candiate_entries.keys())
1978
 
        # XXX: Note that this is unordered - and this is tolerable because 
 
2377
        # XXX: Note that this is unordered - and this is tolerable because
1979
2378
        # the previous code was also unordered.
1980
2379
        previous_entries = dict((head, parent_candiate_entries[head]) for head
1981
2380
            in heads)
1982
2381
        self.snapshot_ie(previous_entries, ie, w, rev_id)
1983
 
        del ie.text_id
1984
 
        assert getattr(ie, 'revision', None) is not None
1985
2382
 
1986
 
    def get_parents(self, revision_ids):
1987
 
        for revision_id in revision_ids:
1988
 
            yield self.revisions[revision_id].parent_ids
 
2383
    def get_parent_map(self, revision_ids):
 
2384
        """See graph.StackedParentsProvider.get_parent_map"""
 
2385
        return dict((revision_id, self.revisions[revision_id])
 
2386
                    for revision_id in revision_ids
 
2387
                     if revision_id in self.revisions)
1989
2388
 
1990
2389
    def snapshot_ie(self, previous_revisions, ie, w, rev_id):
1991
2390
        # TODO: convert this logic, which is ~= snapshot to
1992
2391
        # a call to:. This needs the path figured out. rather than a work_tree
1993
2392
        # a v4 revision_tree can be given, or something that looks enough like
1994
2393
        # one to give the file content to the entry if it needs it.
1995
 
        # and we need something that looks like a weave store for snapshot to 
 
2394
        # and we need something that looks like a weave store for snapshot to
1996
2395
        # save against.
1997
2396
        #ie.snapshot(rev, PATH, previous_revisions, REVISION_TREE, InMemoryWeaveStore(self.text_weaves))
1998
2397
        if len(previous_revisions) == 1:
2001
2400
                ie.revision = previous_ie.revision
2002
2401
                return
2003
2402
        if ie.has_text():
2004
 
            text = self.branch.repository.weave_store.get(ie.text_id)
2005
 
            file_lines = text.readlines()
2006
 
            assert sha_strings(file_lines) == ie.text_sha1
2007
 
            assert sum(map(len, file_lines)) == ie.text_size
 
2403
            f = self.branch.repository._text_store.get(ie.text_id)
 
2404
            try:
 
2405
                file_lines = f.readlines()
 
2406
            finally:
 
2407
                f.close()
2008
2408
            w.add_lines(rev_id, previous_revisions, file_lines)
2009
2409
            self.text_count += 1
2010
2410
        else:
2040
2440
    def convert(self, to_convert, pb):
2041
2441
        """See Converter.convert()."""
2042
2442
        self.bzrdir = to_convert
2043
 
        self.pb = pb
2044
 
        self.pb.note('starting upgrade from format 5 to 6')
2045
 
        self._convert_to_prefixed()
2046
 
        return BzrDir.open(self.bzrdir.root_transport.base)
 
2443
        pb = ui.ui_factory.nested_progress_bar()
 
2444
        try:
 
2445
            ui.ui_factory.note('starting upgrade from format 5 to 6')
 
2446
            self._convert_to_prefixed()
 
2447
            return BzrDir.open(self.bzrdir.user_url)
 
2448
        finally:
 
2449
            pb.finished()
2047
2450
 
2048
2451
    def _convert_to_prefixed(self):
2049
2452
        from bzrlib.store import TransportStore
2050
2453
        self.bzrdir.transport.delete('branch-format')
2051
2454
        for store_name in ["weaves", "revision-store"]:
2052
 
            self.pb.note("adding prefixes to %s" % store_name)
 
2455
            ui.ui_factory.note("adding prefixes to %s" % store_name)
2053
2456
            store_transport = self.bzrdir.transport.clone(store_name)
2054
2457
            store = TransportStore(store_transport, prefixed=True)
2055
2458
            for urlfilename in store_transport.list_dir('.'):
2057
2460
                if (filename.endswith(".weave") or
2058
2461
                    filename.endswith(".gz") or
2059
2462
                    filename.endswith(".sig")):
2060
 
                    file_id = os.path.splitext(filename)[0]
 
2463
                    file_id, suffix = os.path.splitext(filename)
2061
2464
                else:
2062
2465
                    file_id = filename
2063
 
                prefix_dir = store.hash_prefix(file_id)
 
2466
                    suffix = ''
 
2467
                new_name = store._mapper.map((file_id,)) + suffix
2064
2468
                # FIXME keep track of the dirs made RBC 20060121
2065
2469
                try:
2066
 
                    store_transport.move(filename, prefix_dir + '/' + filename)
 
2470
                    store_transport.move(filename, new_name)
2067
2471
                except errors.NoSuchFile: # catches missing dirs strangely enough
2068
 
                    store_transport.mkdir(prefix_dir)
2069
 
                    store_transport.move(filename, prefix_dir + '/' + filename)
2070
 
        self.bzrdir._control_files.put_utf8('branch-format', BzrDirFormat6().get_format_string())
 
2472
                    store_transport.mkdir(osutils.dirname(new_name))
 
2473
                    store_transport.move(filename, new_name)
 
2474
        self.bzrdir.transport.put_bytes(
 
2475
            'branch-format',
 
2476
            BzrDirFormat6().get_format_string(),
 
2477
            mode=self.bzrdir._get_file_mode())
2071
2478
 
2072
2479
 
2073
2480
class ConvertBzrDir6ToMeta(Converter):
2078
2485
        from bzrlib.repofmt.weaverepo import RepositoryFormat7
2079
2486
        from bzrlib.branch import BzrBranchFormat5
2080
2487
        self.bzrdir = to_convert
2081
 
        self.pb = pb
 
2488
        self.pb = ui.ui_factory.nested_progress_bar()
2082
2489
        self.count = 0
2083
2490
        self.total = 20 # the steps we know about
2084
2491
        self.garbage_inventories = []
 
2492
        self.dir_mode = self.bzrdir._get_dir_mode()
 
2493
        self.file_mode = self.bzrdir._get_file_mode()
2085
2494
 
2086
 
        self.pb.note('starting upgrade from format 6 to metadir')
2087
 
        self.bzrdir._control_files.put_utf8('branch-format', "Converting to format 6")
 
2495
        ui.ui_factory.note('starting upgrade from format 6 to metadir')
 
2496
        self.bzrdir.transport.put_bytes(
 
2497
                'branch-format',
 
2498
                "Converting to format 6",
 
2499
                mode=self.file_mode)
2088
2500
        # its faster to move specific files around than to open and use the apis...
2089
2501
        # first off, nuke ancestry.weave, it was never used.
2090
2502
        try:
2100
2512
            if name.startswith('basis-inventory.'):
2101
2513
                self.garbage_inventories.append(name)
2102
2514
        # create new directories for repository, working tree and branch
2103
 
        self.dir_mode = self.bzrdir._control_files._dir_mode
2104
 
        self.file_mode = self.bzrdir._control_files._file_mode
2105
2515
        repository_names = [('inventory.weave', True),
2106
2516
                            ('revision-store', True),
2107
2517
                            ('weaves', True)]
2109
2519
        self.bzrdir.transport.mkdir('repository', mode=self.dir_mode)
2110
2520
        self.make_lock('repository')
2111
2521
        # we hard code the formats here because we are converting into
2112
 
        # the meta format. The meta format upgrader can take this to a 
 
2522
        # the meta format. The meta format upgrader can take this to a
2113
2523
        # future format within each component.
2114
2524
        self.put_format('repository', RepositoryFormat7())
2115
2525
        for entry in repository_names:
2138
2548
        else:
2139
2549
            has_checkout = True
2140
2550
        if not has_checkout:
2141
 
            self.pb.note('No working tree.')
 
2551
            ui.ui_factory.note('No working tree.')
2142
2552
            # If some checkout files are there, we may as well get rid of them.
2143
2553
            for name, mandatory in checkout_files:
2144
2554
                if name in bzrcontents:
2155
2565
            for entry in checkout_files:
2156
2566
                self.move_entry('checkout', entry)
2157
2567
            if last_revision is not None:
2158
 
                self.bzrdir._control_files.put_utf8(
 
2568
                self.bzrdir.transport.put_bytes(
2159
2569
                    'checkout/last-revision', last_revision)
2160
 
        self.bzrdir._control_files.put_utf8(
2161
 
            'branch-format', BzrDirMetaFormat1().get_format_string())
2162
 
        return BzrDir.open(self.bzrdir.root_transport.base)
 
2570
        self.bzrdir.transport.put_bytes(
 
2571
            'branch-format',
 
2572
            BzrDirMetaFormat1().get_format_string(),
 
2573
            mode=self.file_mode)
 
2574
        self.pb.finished()
 
2575
        return BzrDir.open(self.bzrdir.user_url)
2163
2576
 
2164
2577
    def make_lock(self, name):
2165
2578
        """Make a lock for the new control dir name."""
2182
2595
                raise
2183
2596
 
2184
2597
    def put_format(self, dirname, format):
2185
 
        self.bzrdir._control_files.put_utf8('%s/format' % dirname, format.get_format_string())
 
2598
        self.bzrdir.transport.put_bytes('%s/format' % dirname,
 
2599
            format.get_format_string(),
 
2600
            self.file_mode)
2186
2601
 
2187
2602
 
2188
2603
class ConvertMetaToMeta(Converter):
2198
2613
    def convert(self, to_convert, pb):
2199
2614
        """See Converter.convert()."""
2200
2615
        self.bzrdir = to_convert
2201
 
        self.pb = pb
 
2616
        self.pb = ui.ui_factory.nested_progress_bar()
2202
2617
        self.count = 0
2203
2618
        self.total = 1
2204
2619
        self.step('checking repository format')
2209
2624
        else:
2210
2625
            if not isinstance(repo._format, self.target_format.repository_format.__class__):
2211
2626
                from bzrlib.repository import CopyConverter
2212
 
                self.pb.note('starting repository conversion')
 
2627
                ui.ui_factory.note('starting repository conversion')
2213
2628
                converter = CopyConverter(self.target_format.repository_format)
2214
2629
                converter.convert(repo, pb)
2215
 
        try:
2216
 
            branch = self.bzrdir.open_branch()
2217
 
        except errors.NotBranchError:
2218
 
            pass
2219
 
        else:
 
2630
        for branch in self.bzrdir.list_branches():
2220
2631
            # TODO: conversions of Branch and Tree should be done by
2221
 
            # InterXFormat lookups
 
2632
            # InterXFormat lookups/some sort of registry.
2222
2633
            # Avoid circular imports
2223
2634
            from bzrlib import branch as _mod_branch
2224
 
            if (branch._format.__class__ is _mod_branch.BzrBranchFormat5 and
2225
 
                self.target_format.get_branch_format().__class__ is
2226
 
                _mod_branch.BzrBranchFormat6):
2227
 
                branch_converter = _mod_branch.Converter5to6()
 
2635
            old = branch._format.__class__
 
2636
            new = self.target_format.get_branch_format().__class__
 
2637
            while old != new:
 
2638
                if (old == _mod_branch.BzrBranchFormat5 and
 
2639
                    new in (_mod_branch.BzrBranchFormat6,
 
2640
                        _mod_branch.BzrBranchFormat7,
 
2641
                        _mod_branch.BzrBranchFormat8)):
 
2642
                    branch_converter = _mod_branch.Converter5to6()
 
2643
                elif (old == _mod_branch.BzrBranchFormat6 and
 
2644
                    new in (_mod_branch.BzrBranchFormat7,
 
2645
                            _mod_branch.BzrBranchFormat8)):
 
2646
                    branch_converter = _mod_branch.Converter6to7()
 
2647
                elif (old == _mod_branch.BzrBranchFormat7 and
 
2648
                      new is _mod_branch.BzrBranchFormat8):
 
2649
                    branch_converter = _mod_branch.Converter7to8()
 
2650
                else:
 
2651
                    raise errors.BadConversionTarget("No converter", new,
 
2652
                        branch._format)
2228
2653
                branch_converter.convert(branch)
 
2654
                branch = self.bzrdir.open_branch()
 
2655
                old = branch._format.__class__
2229
2656
        try:
2230
2657
            tree = self.bzrdir.open_workingtree(recommend_upgrade=False)
2231
2658
        except (errors.NoWorkingTree, errors.NotLocalUrl):
2234
2661
            # TODO: conversions of Branch and Tree should be done by
2235
2662
            # InterXFormat lookups
2236
2663
            if (isinstance(tree, workingtree.WorkingTree3) and
2237
 
                not isinstance(tree, workingtree_4.WorkingTree4) and
 
2664
                not isinstance(tree, workingtree_4.DirStateWorkingTree) and
2238
2665
                isinstance(self.target_format.workingtree_format,
2239
 
                    workingtree_4.WorkingTreeFormat4)):
 
2666
                    workingtree_4.DirStateWorkingTreeFormat)):
2240
2667
                workingtree_4.Converter3to4().convert(tree)
 
2668
            if (isinstance(tree, workingtree_4.DirStateWorkingTree) and
 
2669
                not isinstance(tree, workingtree_4.WorkingTree5) and
 
2670
                isinstance(self.target_format.workingtree_format,
 
2671
                    workingtree_4.WorkingTreeFormat5)):
 
2672
                workingtree_4.Converter4to5().convert(tree)
 
2673
            if (isinstance(tree, workingtree_4.DirStateWorkingTree) and
 
2674
                not isinstance(tree, workingtree_4.WorkingTree6) and
 
2675
                isinstance(self.target_format.workingtree_format,
 
2676
                    workingtree_4.WorkingTreeFormat6)):
 
2677
                workingtree_4.Converter4or5to6().convert(tree)
 
2678
        self.pb.finished()
2241
2679
        return to_convert
2242
2680
 
2243
2681
 
2244
 
# This is not in remote.py because it's small, and needs to be registered.
2245
 
# Putting it in remote.py creates a circular import problem.
 
2682
# This is not in remote.py because it's relatively small, and needs to be
 
2683
# registered. Putting it in remote.py creates a circular import problem.
2246
2684
# we can make it a lazy object if the control formats is turned into something
2247
2685
# like a registry.
2248
2686
class RemoteBzrDirFormat(BzrDirMetaFormat1):
2249
2687
    """Format representing bzrdirs accessed via a smart server"""
2250
2688
 
 
2689
    supports_workingtrees = False
 
2690
 
 
2691
    def __init__(self):
 
2692
        BzrDirMetaFormat1.__init__(self)
 
2693
        # XXX: It's a bit ugly that the network name is here, because we'd
 
2694
        # like to believe that format objects are stateless or at least
 
2695
        # immutable,  However, we do at least avoid mutating the name after
 
2696
        # it's returned.  See <https://bugs.launchpad.net/bzr/+bug/504102>
 
2697
        self._network_name = None
 
2698
 
 
2699
    def __repr__(self):
 
2700
        return "%s(_network_name=%r)" % (self.__class__.__name__,
 
2701
            self._network_name)
 
2702
 
2251
2703
    def get_format_description(self):
 
2704
        if self._network_name:
 
2705
            real_format = controldir.network_format_registry.get(self._network_name)
 
2706
            return 'Remote: ' + real_format.get_format_description()
2252
2707
        return 'bzr remote bzrdir'
2253
 
    
2254
 
    @classmethod
2255
 
    def probe_transport(klass, transport):
2256
 
        """Return a RemoteBzrDirFormat object if it looks possible."""
2257
 
        try:
2258
 
            client = transport.get_smart_client()
2259
 
        except (NotImplementedError, AttributeError,
2260
 
                errors.TransportNotPossible):
2261
 
            # no smart server, so not a branch for this format type.
2262
 
            raise errors.NotBranchError(path=transport.base)
 
2708
 
 
2709
    def get_format_string(self):
 
2710
        raise NotImplementedError(self.get_format_string)
 
2711
 
 
2712
    def network_name(self):
 
2713
        if self._network_name:
 
2714
            return self._network_name
2263
2715
        else:
2264
 
            # Send a 'hello' request in protocol version one, and decline to
2265
 
            # open it if the server doesn't support our required version (2) so
2266
 
            # that the VFS-based transport will do it.
2267
 
            request = client.get_request()
2268
 
            smart_protocol = protocol.SmartClientRequestProtocolOne(request)
2269
 
            server_version = smart_protocol.query_version()
2270
 
            if server_version != 2:
2271
 
                raise errors.NotBranchError(path=transport.base)
2272
 
            return klass()
 
2716
            raise AssertionError("No network name set.")
2273
2717
 
2274
2718
    def initialize_on_transport(self, transport):
2275
2719
        try:
2276
2720
            # hand off the request to the smart server
2277
 
            shared_medium = transport.get_shared_medium()
 
2721
            client_medium = transport.get_smart_medium()
2278
2722
        except errors.NoSmartMedium:
2279
2723
            # TODO: lookup the local format from a server hint.
2280
2724
            local_dir_format = BzrDirMetaFormat1()
2281
2725
            return local_dir_format.initialize_on_transport(transport)
2282
 
        client = _SmartClient(shared_medium)
 
2726
        client = _SmartClient(client_medium)
2283
2727
        path = client.remote_path_from_transport(transport)
2284
 
        response = _SmartClient(shared_medium).call('BzrDirFormat.initialize',
2285
 
                                                    path)
2286
 
        assert response[0] in ('ok', ), 'unexpected response code %s' % (response,)
2287
 
        return remote.RemoteBzrDir(transport)
 
2728
        try:
 
2729
            response = client.call('BzrDirFormat.initialize', path)
 
2730
        except errors.ErrorFromSmartServer, err:
 
2731
            remote._translate_error(err, path=path)
 
2732
        if response[0] != 'ok':
 
2733
            raise errors.SmartProtocolError('unexpected response code %s' % (response,))
 
2734
        format = RemoteBzrDirFormat()
 
2735
        self._supply_sub_formats_to(format)
 
2736
        return remote.RemoteBzrDir(transport, format)
 
2737
 
 
2738
    def parse_NoneTrueFalse(self, arg):
 
2739
        if not arg:
 
2740
            return None
 
2741
        if arg == 'False':
 
2742
            return False
 
2743
        if arg == 'True':
 
2744
            return True
 
2745
        raise AssertionError("invalid arg %r" % arg)
 
2746
 
 
2747
    def _serialize_NoneTrueFalse(self, arg):
 
2748
        if arg is False:
 
2749
            return 'False'
 
2750
        if arg:
 
2751
            return 'True'
 
2752
        return ''
 
2753
 
 
2754
    def _serialize_NoneString(self, arg):
 
2755
        return arg or ''
 
2756
 
 
2757
    def initialize_on_transport_ex(self, transport, use_existing_dir=False,
 
2758
        create_prefix=False, force_new_repo=False, stacked_on=None,
 
2759
        stack_on_pwd=None, repo_format_name=None, make_working_trees=None,
 
2760
        shared_repo=False):
 
2761
        try:
 
2762
            # hand off the request to the smart server
 
2763
            client_medium = transport.get_smart_medium()
 
2764
        except errors.NoSmartMedium:
 
2765
            do_vfs = True
 
2766
        else:
 
2767
            # Decline to open it if the server doesn't support our required
 
2768
            # version (3) so that the VFS-based transport will do it.
 
2769
            if client_medium.should_probe():
 
2770
                try:
 
2771
                    server_version = client_medium.protocol_version()
 
2772
                    if server_version != '2':
 
2773
                        do_vfs = True
 
2774
                    else:
 
2775
                        do_vfs = False
 
2776
                except errors.SmartProtocolError:
 
2777
                    # Apparently there's no usable smart server there, even though
 
2778
                    # the medium supports the smart protocol.
 
2779
                    do_vfs = True
 
2780
            else:
 
2781
                do_vfs = False
 
2782
        if not do_vfs:
 
2783
            client = _SmartClient(client_medium)
 
2784
            path = client.remote_path_from_transport(transport)
 
2785
            if client_medium._is_remote_before((1, 16)):
 
2786
                do_vfs = True
 
2787
        if do_vfs:
 
2788
            # TODO: lookup the local format from a server hint.
 
2789
            local_dir_format = BzrDirMetaFormat1()
 
2790
            self._supply_sub_formats_to(local_dir_format)
 
2791
            return local_dir_format.initialize_on_transport_ex(transport,
 
2792
                use_existing_dir=use_existing_dir, create_prefix=create_prefix,
 
2793
                force_new_repo=force_new_repo, stacked_on=stacked_on,
 
2794
                stack_on_pwd=stack_on_pwd, repo_format_name=repo_format_name,
 
2795
                make_working_trees=make_working_trees, shared_repo=shared_repo,
 
2796
                vfs_only=True)
 
2797
        return self._initialize_on_transport_ex_rpc(client, path, transport,
 
2798
            use_existing_dir, create_prefix, force_new_repo, stacked_on,
 
2799
            stack_on_pwd, repo_format_name, make_working_trees, shared_repo)
 
2800
 
 
2801
    def _initialize_on_transport_ex_rpc(self, client, path, transport,
 
2802
        use_existing_dir, create_prefix, force_new_repo, stacked_on,
 
2803
        stack_on_pwd, repo_format_name, make_working_trees, shared_repo):
 
2804
        args = []
 
2805
        args.append(self._serialize_NoneTrueFalse(use_existing_dir))
 
2806
        args.append(self._serialize_NoneTrueFalse(create_prefix))
 
2807
        args.append(self._serialize_NoneTrueFalse(force_new_repo))
 
2808
        args.append(self._serialize_NoneString(stacked_on))
 
2809
        # stack_on_pwd is often/usually our transport
 
2810
        if stack_on_pwd:
 
2811
            try:
 
2812
                stack_on_pwd = transport.relpath(stack_on_pwd)
 
2813
                if not stack_on_pwd:
 
2814
                    stack_on_pwd = '.'
 
2815
            except errors.PathNotChild:
 
2816
                pass
 
2817
        args.append(self._serialize_NoneString(stack_on_pwd))
 
2818
        args.append(self._serialize_NoneString(repo_format_name))
 
2819
        args.append(self._serialize_NoneTrueFalse(make_working_trees))
 
2820
        args.append(self._serialize_NoneTrueFalse(shared_repo))
 
2821
        request_network_name = self._network_name or \
 
2822
            BzrDirFormat.get_default_format().network_name()
 
2823
        try:
 
2824
            response = client.call('BzrDirFormat.initialize_ex_1.16',
 
2825
                request_network_name, path, *args)
 
2826
        except errors.UnknownSmartMethod:
 
2827
            client._medium._remember_remote_is_before((1,16))
 
2828
            local_dir_format = BzrDirMetaFormat1()
 
2829
            self._supply_sub_formats_to(local_dir_format)
 
2830
            return local_dir_format.initialize_on_transport_ex(transport,
 
2831
                use_existing_dir=use_existing_dir, create_prefix=create_prefix,
 
2832
                force_new_repo=force_new_repo, stacked_on=stacked_on,
 
2833
                stack_on_pwd=stack_on_pwd, repo_format_name=repo_format_name,
 
2834
                make_working_trees=make_working_trees, shared_repo=shared_repo,
 
2835
                vfs_only=True)
 
2836
        except errors.ErrorFromSmartServer, err:
 
2837
            remote._translate_error(err, path=path)
 
2838
        repo_path = response[0]
 
2839
        bzrdir_name = response[6]
 
2840
        require_stacking = response[7]
 
2841
        require_stacking = self.parse_NoneTrueFalse(require_stacking)
 
2842
        format = RemoteBzrDirFormat()
 
2843
        format._network_name = bzrdir_name
 
2844
        self._supply_sub_formats_to(format)
 
2845
        bzrdir = remote.RemoteBzrDir(transport, format, _client=client)
 
2846
        if repo_path:
 
2847
            repo_format = remote.response_tuple_to_repo_format(response[1:])
 
2848
            if repo_path == '.':
 
2849
                repo_path = ''
 
2850
            if repo_path:
 
2851
                repo_bzrdir_format = RemoteBzrDirFormat()
 
2852
                repo_bzrdir_format._network_name = response[5]
 
2853
                repo_bzr = remote.RemoteBzrDir(transport.clone(repo_path),
 
2854
                    repo_bzrdir_format)
 
2855
            else:
 
2856
                repo_bzr = bzrdir
 
2857
            final_stack = response[8] or None
 
2858
            final_stack_pwd = response[9] or None
 
2859
            if final_stack_pwd:
 
2860
                final_stack_pwd = urlutils.join(
 
2861
                    transport.base, final_stack_pwd)
 
2862
            remote_repo = remote.RemoteRepository(repo_bzr, repo_format)
 
2863
            if len(response) > 10:
 
2864
                # Updated server verb that locks remotely.
 
2865
                repo_lock_token = response[10] or None
 
2866
                remote_repo.lock_write(repo_lock_token, _skip_rpc=True)
 
2867
                if repo_lock_token:
 
2868
                    remote_repo.dont_leave_lock_in_place()
 
2869
            else:
 
2870
                remote_repo.lock_write()
 
2871
            policy = UseExistingRepository(remote_repo, final_stack,
 
2872
                final_stack_pwd, require_stacking)
 
2873
            policy.acquire_repository()
 
2874
        else:
 
2875
            remote_repo = None
 
2876
            policy = None
 
2877
        bzrdir._format.set_branch_format(self.get_branch_format())
 
2878
        if require_stacking:
 
2879
            # The repo has already been created, but we need to make sure that
 
2880
            # we'll make a stackable branch.
 
2881
            bzrdir._format.require_stacking(_skip_repo=True)
 
2882
        return remote_repo, bzrdir, require_stacking, policy
2288
2883
 
2289
2884
    def _open(self, transport):
2290
 
        return remote.RemoteBzrDir(transport)
 
2885
        return remote.RemoteBzrDir(transport, self)
2291
2886
 
2292
2887
    def __eq__(self, other):
2293
2888
        if not isinstance(other, RemoteBzrDirFormat):
2294
2889
            return False
2295
2890
        return self.get_format_description() == other.get_format_description()
2296
2891
 
2297
 
 
2298
 
BzrDirFormat.register_control_server_format(RemoteBzrDirFormat)
2299
 
 
2300
 
 
2301
 
class BzrDirFormatInfo(object):
2302
 
 
2303
 
    def __init__(self, native, deprecated, hidden, experimental):
2304
 
        self.deprecated = deprecated
2305
 
        self.native = native
2306
 
        self.hidden = hidden
2307
 
        self.experimental = experimental
2308
 
 
2309
 
 
2310
 
class BzrDirFormatRegistry(registry.Registry):
2311
 
    """Registry of user-selectable BzrDir subformats.
2312
 
    
2313
 
    Differs from BzrDirFormat._control_formats in that it provides sub-formats,
2314
 
    e.g. BzrDirMeta1 with weave repository.  Also, it's more user-oriented.
2315
 
    """
2316
 
 
2317
 
    def register_metadir(self, key,
2318
 
             repository_format, help, native=True, deprecated=False,
2319
 
             branch_format=None,
2320
 
             tree_format=None,
2321
 
             hidden=False,
2322
 
             experimental=False):
2323
 
        """Register a metadir subformat.
2324
 
 
2325
 
        These all use a BzrDirMetaFormat1 bzrdir, but can be parameterized
2326
 
        by the Repository format.
2327
 
 
2328
 
        :param repository_format: The fully-qualified repository format class
2329
 
            name as a string.
2330
 
        :param branch_format: Fully-qualified branch format class name as
2331
 
            a string.
2332
 
        :param tree_format: Fully-qualified tree format class name as
2333
 
            a string.
2334
 
        """
2335
 
        # This should be expanded to support setting WorkingTree and Branch
2336
 
        # formats, once BzrDirMetaFormat1 supports that.
2337
 
        def _load(full_name):
2338
 
            mod_name, factory_name = full_name.rsplit('.', 1)
2339
 
            try:
2340
 
                mod = __import__(mod_name, globals(), locals(),
2341
 
                        [factory_name])
2342
 
            except ImportError, e:
2343
 
                raise ImportError('failed to load %s: %s' % (full_name, e))
2344
 
            try:
2345
 
                factory = getattr(mod, factory_name)
2346
 
            except AttributeError:
2347
 
                raise AttributeError('no factory %s in module %r'
2348
 
                    % (full_name, mod))
2349
 
            return factory()
2350
 
 
2351
 
        def helper():
2352
 
            bd = BzrDirMetaFormat1()
2353
 
            if branch_format is not None:
2354
 
                bd.set_branch_format(_load(branch_format))
2355
 
            if tree_format is not None:
2356
 
                bd.workingtree_format = _load(tree_format)
2357
 
            if repository_format is not None:
2358
 
                bd.repository_format = _load(repository_format)
2359
 
            return bd
2360
 
        self.register(key, helper, help, native, deprecated, hidden,
2361
 
            experimental)
2362
 
 
2363
 
    def register(self, key, factory, help, native=True, deprecated=False,
2364
 
                 hidden=False, experimental=False):
2365
 
        """Register a BzrDirFormat factory.
2366
 
        
2367
 
        The factory must be a callable that takes one parameter: the key.
2368
 
        It must produce an instance of the BzrDirFormat when called.
2369
 
 
2370
 
        This function mainly exists to prevent the info object from being
2371
 
        supplied directly.
2372
 
        """
2373
 
        registry.Registry.register(self, key, factory, help, 
2374
 
            BzrDirFormatInfo(native, deprecated, hidden, experimental))
2375
 
 
2376
 
    def register_lazy(self, key, module_name, member_name, help, native=True,
2377
 
                      deprecated=False, hidden=False, experimental=False):
2378
 
        registry.Registry.register_lazy(self, key, module_name, member_name, 
2379
 
            help, BzrDirFormatInfo(native, deprecated, hidden, experimental))
2380
 
 
2381
 
    def set_default(self, key):
2382
 
        """Set the 'default' key to be a clone of the supplied key.
2383
 
        
2384
 
        This method must be called once and only once.
2385
 
        """
2386
 
        registry.Registry.register(self, 'default', self.get(key), 
2387
 
            self.get_help(key), info=self.get_info(key))
2388
 
 
2389
 
    def set_default_repository(self, key):
2390
 
        """Set the FormatRegistry default and Repository default.
2391
 
        
2392
 
        This is a transitional method while Repository.set_default_format
2393
 
        is deprecated.
2394
 
        """
2395
 
        if 'default' in self:
2396
 
            self.remove('default')
2397
 
        self.set_default(key)
2398
 
        format = self.get('default')()
2399
 
        assert isinstance(format, BzrDirMetaFormat1)
2400
 
 
2401
 
    def make_bzrdir(self, key):
2402
 
        return self.get(key)()
2403
 
 
2404
 
    def help_topic(self, topic):
2405
 
        output = textwrap.dedent("""\
2406
 
            These formats can be used for creating branches, working trees, and
2407
 
            repositories.
2408
 
 
2409
 
            """)
2410
 
        default_realkey = None
2411
 
        default_help = self.get_help('default')
2412
 
        help_pairs = []
2413
 
        for key in self.keys():
2414
 
            if key == 'default':
2415
 
                continue
2416
 
            help = self.get_help(key)
2417
 
            if help == default_help:
2418
 
                default_realkey = key
2419
 
            else:
2420
 
                help_pairs.append((key, help))
2421
 
 
2422
 
        def wrapped(key, help, info):
2423
 
            if info.native:
2424
 
                help = '(native) ' + help
2425
 
            return ':%s:\n%s\n\n' % (key, 
2426
 
                    textwrap.fill(help, initial_indent='    ', 
2427
 
                    subsequent_indent='    '))
2428
 
        if default_realkey is not None:
2429
 
            output += wrapped(default_realkey, '(default) %s' % default_help,
2430
 
                              self.get_info('default'))
2431
 
        deprecated_pairs = []
2432
 
        experimental_pairs = []
2433
 
        for key, help in help_pairs:
2434
 
            info = self.get_info(key)
2435
 
            if info.hidden:
2436
 
                continue
2437
 
            elif info.deprecated:
2438
 
                deprecated_pairs.append((key, help))
2439
 
            elif info.experimental:
2440
 
                experimental_pairs.append((key, help))
2441
 
            else:
2442
 
                output += wrapped(key, help, info)
2443
 
        if len(experimental_pairs) > 0:
2444
 
            output += "Experimental formats are shown below.\n\n"
2445
 
            for key, help in experimental_pairs:
2446
 
                info = self.get_info(key)
2447
 
                output += wrapped(key, help, info)
2448
 
        if len(deprecated_pairs) > 0:
2449
 
            output += "Deprecated formats are shown below.\n\n"
2450
 
            for key, help in deprecated_pairs:
2451
 
                info = self.get_info(key)
2452
 
                output += wrapped(key, help, info)
2453
 
 
2454
 
        return output
2455
 
 
2456
 
 
2457
 
format_registry = BzrDirFormatRegistry()
2458
 
format_registry.register('weave', BzrDirFormat6,
 
2892
    def __return_repository_format(self):
 
2893
        # Always return a RemoteRepositoryFormat object, but if a specific bzr
 
2894
        # repository format has been asked for, tell the RemoteRepositoryFormat
 
2895
        # that it should use that for init() etc.
 
2896
        result = remote.RemoteRepositoryFormat()
 
2897
        custom_format = getattr(self, '_repository_format', None)
 
2898
        if custom_format:
 
2899
            if isinstance(custom_format, remote.RemoteRepositoryFormat):
 
2900
                return custom_format
 
2901
            else:
 
2902
                # We will use the custom format to create repositories over the
 
2903
                # wire; expose its details like rich_root_data for code to
 
2904
                # query
 
2905
                result._custom_format = custom_format
 
2906
        return result
 
2907
 
 
2908
    def get_branch_format(self):
 
2909
        result = BzrDirMetaFormat1.get_branch_format(self)
 
2910
        if not isinstance(result, remote.RemoteBranchFormat):
 
2911
            new_result = remote.RemoteBranchFormat()
 
2912
            new_result._custom_format = result
 
2913
            # cache the result
 
2914
            self.set_branch_format(new_result)
 
2915
            result = new_result
 
2916
        return result
 
2917
 
 
2918
    repository_format = property(__return_repository_format,
 
2919
        BzrDirMetaFormat1._set_repository_format) #.im_func)
 
2920
 
 
2921
 
 
2922
controldir.ControlDirFormat.register_server_prober(RemoteBzrProber)
 
2923
 
 
2924
 
 
2925
class RepositoryAcquisitionPolicy(object):
 
2926
    """Abstract base class for repository acquisition policies.
 
2927
 
 
2928
    A repository acquisition policy decides how a BzrDir acquires a repository
 
2929
    for a branch that is being created.  The most basic policy decision is
 
2930
    whether to create a new repository or use an existing one.
 
2931
    """
 
2932
    def __init__(self, stack_on, stack_on_pwd, require_stacking):
 
2933
        """Constructor.
 
2934
 
 
2935
        :param stack_on: A location to stack on
 
2936
        :param stack_on_pwd: If stack_on is relative, the location it is
 
2937
            relative to.
 
2938
        :param require_stacking: If True, it is a failure to not stack.
 
2939
        """
 
2940
        self._stack_on = stack_on
 
2941
        self._stack_on_pwd = stack_on_pwd
 
2942
        self._require_stacking = require_stacking
 
2943
 
 
2944
    def configure_branch(self, branch):
 
2945
        """Apply any configuration data from this policy to the branch.
 
2946
 
 
2947
        Default implementation sets repository stacking.
 
2948
        """
 
2949
        if self._stack_on is None:
 
2950
            return
 
2951
        if self._stack_on_pwd is None:
 
2952
            stack_on = self._stack_on
 
2953
        else:
 
2954
            try:
 
2955
                stack_on = urlutils.rebase_url(self._stack_on,
 
2956
                    self._stack_on_pwd,
 
2957
                    branch.user_url)
 
2958
            except errors.InvalidRebaseURLs:
 
2959
                stack_on = self._get_full_stack_on()
 
2960
        try:
 
2961
            branch.set_stacked_on_url(stack_on)
 
2962
        except (errors.UnstackableBranchFormat,
 
2963
                errors.UnstackableRepositoryFormat):
 
2964
            if self._require_stacking:
 
2965
                raise
 
2966
 
 
2967
    def requires_stacking(self):
 
2968
        """Return True if this policy requires stacking."""
 
2969
        return self._stack_on is not None and self._require_stacking
 
2970
 
 
2971
    def _get_full_stack_on(self):
 
2972
        """Get a fully-qualified URL for the stack_on location."""
 
2973
        if self._stack_on is None:
 
2974
            return None
 
2975
        if self._stack_on_pwd is None:
 
2976
            return self._stack_on
 
2977
        else:
 
2978
            return urlutils.join(self._stack_on_pwd, self._stack_on)
 
2979
 
 
2980
    def _add_fallback(self, repository, possible_transports=None):
 
2981
        """Add a fallback to the supplied repository, if stacking is set."""
 
2982
        stack_on = self._get_full_stack_on()
 
2983
        if stack_on is None:
 
2984
            return
 
2985
        try:
 
2986
            stacked_dir = BzrDir.open(stack_on,
 
2987
                                      possible_transports=possible_transports)
 
2988
        except errors.JailBreak:
 
2989
            # We keep the stacking details, but we are in the server code so
 
2990
            # actually stacking is not needed.
 
2991
            return
 
2992
        try:
 
2993
            stacked_repo = stacked_dir.open_branch().repository
 
2994
        except errors.NotBranchError:
 
2995
            stacked_repo = stacked_dir.open_repository()
 
2996
        try:
 
2997
            repository.add_fallback_repository(stacked_repo)
 
2998
        except errors.UnstackableRepositoryFormat:
 
2999
            if self._require_stacking:
 
3000
                raise
 
3001
        else:
 
3002
            self._require_stacking = True
 
3003
 
 
3004
    def acquire_repository(self, make_working_trees=None, shared=False):
 
3005
        """Acquire a repository for this bzrdir.
 
3006
 
 
3007
        Implementations may create a new repository or use a pre-exising
 
3008
        repository.
 
3009
        :param make_working_trees: If creating a repository, set
 
3010
            make_working_trees to this value (if non-None)
 
3011
        :param shared: If creating a repository, make it shared if True
 
3012
        :return: A repository, is_new_flag (True if the repository was
 
3013
            created).
 
3014
        """
 
3015
        raise NotImplemented(RepositoryAcquisitionPolicy.acquire_repository)
 
3016
 
 
3017
 
 
3018
class CreateRepository(RepositoryAcquisitionPolicy):
 
3019
    """A policy of creating a new repository"""
 
3020
 
 
3021
    def __init__(self, bzrdir, stack_on=None, stack_on_pwd=None,
 
3022
                 require_stacking=False):
 
3023
        """
 
3024
        Constructor.
 
3025
        :param bzrdir: The bzrdir to create the repository on.
 
3026
        :param stack_on: A location to stack on
 
3027
        :param stack_on_pwd: If stack_on is relative, the location it is
 
3028
            relative to.
 
3029
        """
 
3030
        RepositoryAcquisitionPolicy.__init__(self, stack_on, stack_on_pwd,
 
3031
                                             require_stacking)
 
3032
        self._bzrdir = bzrdir
 
3033
 
 
3034
    def acquire_repository(self, make_working_trees=None, shared=False):
 
3035
        """Implementation of RepositoryAcquisitionPolicy.acquire_repository
 
3036
 
 
3037
        Creates the desired repository in the bzrdir we already have.
 
3038
        """
 
3039
        stack_on = self._get_full_stack_on()
 
3040
        if stack_on:
 
3041
            format = self._bzrdir._format
 
3042
            format.require_stacking(stack_on=stack_on,
 
3043
                                    possible_transports=[self._bzrdir.root_transport])
 
3044
            if not self._require_stacking:
 
3045
                # We have picked up automatic stacking somewhere.
 
3046
                note('Using default stacking branch %s at %s', self._stack_on,
 
3047
                    self._stack_on_pwd)
 
3048
        repository = self._bzrdir.create_repository(shared=shared)
 
3049
        self._add_fallback(repository,
 
3050
                           possible_transports=[self._bzrdir.transport])
 
3051
        if make_working_trees is not None:
 
3052
            repository.set_make_working_trees(make_working_trees)
 
3053
        return repository, True
 
3054
 
 
3055
 
 
3056
class UseExistingRepository(RepositoryAcquisitionPolicy):
 
3057
    """A policy of reusing an existing repository"""
 
3058
 
 
3059
    def __init__(self, repository, stack_on=None, stack_on_pwd=None,
 
3060
                 require_stacking=False):
 
3061
        """Constructor.
 
3062
 
 
3063
        :param repository: The repository to use.
 
3064
        :param stack_on: A location to stack on
 
3065
        :param stack_on_pwd: If stack_on is relative, the location it is
 
3066
            relative to.
 
3067
        """
 
3068
        RepositoryAcquisitionPolicy.__init__(self, stack_on, stack_on_pwd,
 
3069
                                             require_stacking)
 
3070
        self._repository = repository
 
3071
 
 
3072
    def acquire_repository(self, make_working_trees=None, shared=False):
 
3073
        """Implementation of RepositoryAcquisitionPolicy.acquire_repository
 
3074
 
 
3075
        Returns an existing repository to use.
 
3076
        """
 
3077
        self._add_fallback(self._repository,
 
3078
                       possible_transports=[self._repository.bzrdir.transport])
 
3079
        return self._repository, False
 
3080
 
 
3081
 
 
3082
def register_metadir(registry, key,
 
3083
         repository_format, help, native=True, deprecated=False,
 
3084
         branch_format=None,
 
3085
         tree_format=None,
 
3086
         hidden=False,
 
3087
         experimental=False,
 
3088
         alias=False):
 
3089
    """Register a metadir subformat.
 
3090
 
 
3091
    These all use a BzrDirMetaFormat1 bzrdir, but can be parameterized
 
3092
    by the Repository/Branch/WorkingTreeformats.
 
3093
 
 
3094
    :param repository_format: The fully-qualified repository format class
 
3095
        name as a string.
 
3096
    :param branch_format: Fully-qualified branch format class name as
 
3097
        a string.
 
3098
    :param tree_format: Fully-qualified tree format class name as
 
3099
        a string.
 
3100
    """
 
3101
    # This should be expanded to support setting WorkingTree and Branch
 
3102
    # formats, once BzrDirMetaFormat1 supports that.
 
3103
    def _load(full_name):
 
3104
        mod_name, factory_name = full_name.rsplit('.', 1)
 
3105
        try:
 
3106
            factory = pyutils.get_named_object(mod_name, factory_name)
 
3107
        except ImportError, e:
 
3108
            raise ImportError('failed to load %s: %s' % (full_name, e))
 
3109
        except AttributeError:
 
3110
            raise AttributeError('no factory %s in module %r'
 
3111
                % (full_name, sys.modules[mod_name]))
 
3112
        return factory()
 
3113
 
 
3114
    def helper():
 
3115
        bd = BzrDirMetaFormat1()
 
3116
        if branch_format is not None:
 
3117
            bd.set_branch_format(_load(branch_format))
 
3118
        if tree_format is not None:
 
3119
            bd.workingtree_format = _load(tree_format)
 
3120
        if repository_format is not None:
 
3121
            bd.repository_format = _load(repository_format)
 
3122
        return bd
 
3123
    registry.register(key, helper, help, native, deprecated, hidden,
 
3124
        experimental, alias)
 
3125
 
 
3126
# The pre-0.8 formats have their repository format network name registered in
 
3127
# repository.py. MetaDir formats have their repository format network name
 
3128
# inferred from their disk format string.
 
3129
controldir.format_registry.register('weave', BzrDirFormat6,
2459
3130
    'Pre-0.8 format.  Slower than knit and does not'
2460
3131
    ' support checkouts or shared repositories.',
 
3132
    hidden=True,
2461
3133
    deprecated=True)
2462
 
format_registry.register_metadir('knit',
2463
 
    'bzrlib.repofmt.knitrepo.RepositoryFormatKnit1',
2464
 
    'Format using knits.  Recommended for interoperation with bzr <= 0.14.',
2465
 
    branch_format='bzrlib.branch.BzrBranchFormat5',
2466
 
    tree_format='bzrlib.workingtree.WorkingTreeFormat3')
2467
 
format_registry.register_metadir('metaweave',
 
3134
register_metadir(controldir.format_registry, 'metaweave',
2468
3135
    'bzrlib.repofmt.weaverepo.RepositoryFormat7',
2469
3136
    'Transitional format in 0.8.  Slower than knit.',
2470
3137
    branch_format='bzrlib.branch.BzrBranchFormat5',
2471
3138
    tree_format='bzrlib.workingtree.WorkingTreeFormat3',
2472
 
    deprecated=True)
2473
 
format_registry.register_metadir('dirstate',
 
3139
    hidden=True,
 
3140
    deprecated=True)
 
3141
register_metadir(controldir.format_registry, 'knit',
 
3142
    'bzrlib.repofmt.knitrepo.RepositoryFormatKnit1',
 
3143
    'Format using knits.  Recommended for interoperation with bzr <= 0.14.',
 
3144
    branch_format='bzrlib.branch.BzrBranchFormat5',
 
3145
    tree_format='bzrlib.workingtree.WorkingTreeFormat3',
 
3146
    hidden=True,
 
3147
    deprecated=True)
 
3148
register_metadir(controldir.format_registry, 'dirstate',
2474
3149
    'bzrlib.repofmt.knitrepo.RepositoryFormatKnit1',
2475
3150
    help='New in 0.15: Fast local operations. Compatible with bzr 0.8 and '
2476
3151
        'above when accessed over the network.',
2478
3153
    # this uses bzrlib.workingtree.WorkingTreeFormat4 because importing
2479
3154
    # directly from workingtree_4 triggers a circular import.
2480
3155
    tree_format='bzrlib.workingtree.WorkingTreeFormat4',
2481
 
    )
2482
 
format_registry.register_metadir('dirstate-tags',
 
3156
    hidden=True,
 
3157
    deprecated=True)
 
3158
register_metadir(controldir.format_registry, 'dirstate-tags',
2483
3159
    'bzrlib.repofmt.knitrepo.RepositoryFormatKnit1',
2484
3160
    help='New in 0.15: Fast local operations and improved scaling for '
2485
3161
        'network operations. Additionally adds support for tags.'
2486
3162
        ' Incompatible with bzr < 0.15.',
2487
3163
    branch_format='bzrlib.branch.BzrBranchFormat6',
2488
3164
    tree_format='bzrlib.workingtree.WorkingTreeFormat4',
2489
 
    )
2490
 
format_registry.register_metadir('rich-root',
 
3165
    hidden=True,
 
3166
    deprecated=True)
 
3167
register_metadir(controldir.format_registry, 'rich-root',
2491
3168
    'bzrlib.repofmt.knitrepo.RepositoryFormatKnit4',
2492
3169
    help='New in 1.0.  Better handling of tree roots.  Incompatible with'
2493
 
        ' bzr < 1.0',
 
3170
        ' bzr < 1.0.',
2494
3171
    branch_format='bzrlib.branch.BzrBranchFormat6',
2495
3172
    tree_format='bzrlib.workingtree.WorkingTreeFormat4',
2496
 
    hidden=False,
2497
 
    )
2498
 
format_registry.register_metadir('dirstate-with-subtree',
 
3173
    hidden=True,
 
3174
    deprecated=True)
 
3175
register_metadir(controldir.format_registry, 'dirstate-with-subtree',
2499
3176
    'bzrlib.repofmt.knitrepo.RepositoryFormatKnit3',
2500
3177
    help='New in 0.15: Fast local operations and improved scaling for '
2501
3178
        'network operations. Additionally adds support for versioning nested '
2502
3179
        'bzr branches. Incompatible with bzr < 0.15.',
2503
3180
    branch_format='bzrlib.branch.BzrBranchFormat6',
2504
3181
    tree_format='bzrlib.workingtree.WorkingTreeFormat4',
 
3182
    experimental=True,
2505
3183
    hidden=True,
2506
3184
    )
2507
 
format_registry.register_metadir('pack-0.92',
 
3185
register_metadir(controldir.format_registry, 'pack-0.92',
2508
3186
    'bzrlib.repofmt.pack_repo.RepositoryFormatKnitPack1',
2509
3187
    help='New in 0.92: Pack-based format with data compatible with '
2510
3188
        'dirstate-tags format repositories. Interoperates with '
2511
3189
        'bzr repositories before 0.92 but cannot be read by bzr < 0.92. '
2512
 
        'Previously called knitpack-experimental.  '
2513
 
        'For more information, see '
2514
 
        'http://doc.bazaar-vcs.org/latest/developers/packrepo.html.',
 
3190
        ,
2515
3191
    branch_format='bzrlib.branch.BzrBranchFormat6',
2516
3192
    tree_format='bzrlib.workingtree.WorkingTreeFormat4',
2517
 
    experimental=True,
2518
3193
    )
2519
 
format_registry.register_metadir('pack-0.92-subtree',
 
3194
register_metadir(controldir.format_registry, 'pack-0.92-subtree',
2520
3195
    'bzrlib.repofmt.pack_repo.RepositoryFormatKnitPack3',
2521
3196
    help='New in 0.92: Pack-based format with data compatible with '
2522
3197
        'dirstate-with-subtree format repositories. Interoperates with '
2523
3198
        'bzr repositories before 0.92 but cannot be read by bzr < 0.92. '
2524
 
        'Previously called knitpack-experimental.  '
2525
 
        'For more information, see '
2526
 
        'http://doc.bazaar-vcs.org/latest/developers/packrepo.html.',
 
3199
        ,
2527
3200
    branch_format='bzrlib.branch.BzrBranchFormat6',
2528
3201
    tree_format='bzrlib.workingtree.WorkingTreeFormat4',
2529
3202
    hidden=True,
2530
3203
    experimental=True,
2531
3204
    )
2532
 
format_registry.register_metadir('rich-root-pack',
 
3205
register_metadir(controldir.format_registry, 'rich-root-pack',
2533
3206
    'bzrlib.repofmt.pack_repo.RepositoryFormatKnitPack4',
2534
 
    help='New in 1.0: Pack-based format with data compatible with '
2535
 
        'rich-root format repositories. Interoperates with '
2536
 
        'bzr repositories before 0.92 but cannot be read by bzr < 1.0. '
2537
 
        'NOTE: This format is experimental. Before using it, please read '
2538
 
        'http://doc.bazaar-vcs.org/latest/developers/knitpack.html.',
 
3207
    help='New in 1.0: A variant of pack-0.92 that supports rich-root data '
 
3208
         '(needed for bzr-svn and bzr-git).',
2539
3209
    branch_format='bzrlib.branch.BzrBranchFormat6',
2540
3210
    tree_format='bzrlib.workingtree.WorkingTreeFormat4',
2541
 
    hidden=False,
2542
 
    experimental=True,
2543
 
    )
2544
 
format_registry.set_default('dirstate-tags')
 
3211
    hidden=True,
 
3212
    )
 
3213
register_metadir(controldir.format_registry, '1.6',
 
3214
    'bzrlib.repofmt.pack_repo.RepositoryFormatKnitPack5',
 
3215
    help='A format that allows a branch to indicate that there is another '
 
3216
         '(stacked) repository that should be used to access data that is '
 
3217
         'not present locally.',
 
3218
    branch_format='bzrlib.branch.BzrBranchFormat7',
 
3219
    tree_format='bzrlib.workingtree.WorkingTreeFormat4',
 
3220
    hidden=True,
 
3221
    )
 
3222
register_metadir(controldir.format_registry, '1.6.1-rich-root',
 
3223
    'bzrlib.repofmt.pack_repo.RepositoryFormatKnitPack5RichRoot',
 
3224
    help='A variant of 1.6 that supports rich-root data '
 
3225
         '(needed for bzr-svn and bzr-git).',
 
3226
    branch_format='bzrlib.branch.BzrBranchFormat7',
 
3227
    tree_format='bzrlib.workingtree.WorkingTreeFormat4',
 
3228
    hidden=True,
 
3229
    )
 
3230
register_metadir(controldir.format_registry, '1.9',
 
3231
    'bzrlib.repofmt.pack_repo.RepositoryFormatKnitPack6',
 
3232
    help='A repository format using B+tree indexes. These indexes '
 
3233
         'are smaller in size, have smarter caching and provide faster '
 
3234
         'performance for most operations.',
 
3235
    branch_format='bzrlib.branch.BzrBranchFormat7',
 
3236
    tree_format='bzrlib.workingtree.WorkingTreeFormat4',
 
3237
    hidden=True,
 
3238
    )
 
3239
register_metadir(controldir.format_registry, '1.9-rich-root',
 
3240
    'bzrlib.repofmt.pack_repo.RepositoryFormatKnitPack6RichRoot',
 
3241
    help='A variant of 1.9 that supports rich-root data '
 
3242
         '(needed for bzr-svn and bzr-git).',
 
3243
    branch_format='bzrlib.branch.BzrBranchFormat7',
 
3244
    tree_format='bzrlib.workingtree.WorkingTreeFormat4',
 
3245
    hidden=True,
 
3246
    )
 
3247
register_metadir(controldir.format_registry, '1.14',
 
3248
    'bzrlib.repofmt.pack_repo.RepositoryFormatKnitPack6',
 
3249
    help='A working-tree format that supports content filtering.',
 
3250
    branch_format='bzrlib.branch.BzrBranchFormat7',
 
3251
    tree_format='bzrlib.workingtree.WorkingTreeFormat5',
 
3252
    )
 
3253
register_metadir(controldir.format_registry, '1.14-rich-root',
 
3254
    'bzrlib.repofmt.pack_repo.RepositoryFormatKnitPack6RichRoot',
 
3255
    help='A variant of 1.14 that supports rich-root data '
 
3256
         '(needed for bzr-svn and bzr-git).',
 
3257
    branch_format='bzrlib.branch.BzrBranchFormat7',
 
3258
    tree_format='bzrlib.workingtree.WorkingTreeFormat5',
 
3259
    )
 
3260
# The following un-numbered 'development' formats should always just be aliases.
 
3261
register_metadir(controldir.format_registry, 'development-subtree',
 
3262
    'bzrlib.repofmt.groupcompress_repo.RepositoryFormat2aSubtree',
 
3263
    help='Current development format, subtree variant. Can convert data to and '
 
3264
        'from pack-0.92-subtree (and anything compatible with '
 
3265
        'pack-0.92-subtree) format repositories. Repositories and branches in '
 
3266
        'this format can only be read by bzr.dev. Please read '
 
3267
        'http://doc.bazaar.canonical.com/latest/developers/development-repo.html '
 
3268
        'before use.',
 
3269
    branch_format='bzrlib.branch.BzrBranchFormat7',
 
3270
    tree_format='bzrlib.workingtree.WorkingTreeFormat6',
 
3271
    experimental=True,
 
3272
    hidden=True,
 
3273
    alias=False, # Restore to being an alias when an actual development subtree format is added
 
3274
                 # This current non-alias status is simply because we did not introduce a
 
3275
                 # chk based subtree format.
 
3276
    )
 
3277
register_metadir(controldir.format_registry, 'development5-subtree',
 
3278
    'bzrlib.repofmt.pack_repo.RepositoryFormatPackDevelopment2Subtree',
 
3279
    help='Development format, subtree variant. Can convert data to and '
 
3280
        'from pack-0.92-subtree (and anything compatible with '
 
3281
        'pack-0.92-subtree) format repositories. Repositories and branches in '
 
3282
        'this format can only be read by bzr.dev. Please read '
 
3283
        'http://doc.bazaar.canonical.com/latest/developers/development-repo.html '
 
3284
        'before use.',
 
3285
    branch_format='bzrlib.branch.BzrBranchFormat7',
 
3286
    tree_format='bzrlib.workingtree.WorkingTreeFormat6',
 
3287
    experimental=True,
 
3288
    hidden=True,
 
3289
    alias=False,
 
3290
    )
 
3291
 
 
3292
# And the development formats above will have aliased one of the following:
 
3293
 
 
3294
# Finally, the current format.
 
3295
register_metadir(controldir.format_registry, '2a',
 
3296
    'bzrlib.repofmt.groupcompress_repo.RepositoryFormat2a',
 
3297
    help='First format for bzr 2.0 series.\n'
 
3298
        'Uses group-compress storage.\n'
 
3299
        'Provides rich roots which are a one-way transition.\n',
 
3300
        # 'storage in packs, 255-way hashed CHK inventory, bencode revision, group compress, '
 
3301
        # 'rich roots. Supported by bzr 1.16 and later.',
 
3302
    branch_format='bzrlib.branch.BzrBranchFormat7',
 
3303
    tree_format='bzrlib.workingtree.WorkingTreeFormat6',
 
3304
    experimental=False,
 
3305
    )
 
3306
 
 
3307
# The following format should be an alias for the rich root equivalent 
 
3308
# of the default format
 
3309
register_metadir(controldir.format_registry, 'default-rich-root',
 
3310
    'bzrlib.repofmt.groupcompress_repo.RepositoryFormat2a',
 
3311
    branch_format='bzrlib.branch.BzrBranchFormat7',
 
3312
    tree_format='bzrlib.workingtree.WorkingTreeFormat6',
 
3313
    alias=True,
 
3314
    hidden=True,
 
3315
    help='Same as 2a.')
 
3316
 
 
3317
# The current format that is made on 'bzr init'.
 
3318
format_name = config.GlobalConfig().get_user_option('default_format')
 
3319
if format_name is None:
 
3320
    controldir.format_registry.set_default('2a')
 
3321
else:
 
3322
    controldir.format_registry.set_default(format_name)
 
3323
 
 
3324
# XXX 2010-08-20 JRV: There is still a lot of code relying on
 
3325
# bzrlib.bzrdir.format_registry existing. When BzrDir.create/BzrDir.open/etc
 
3326
# get changed to ControlDir.create/ControlDir.open/etc this should be removed.
 
3327
format_registry = controldir.format_registry