~bzr-pqm/bzr/bzr.dev

« back to all changes in this revision

Viewing changes to bzrlib/bzrdir.py

  • Committer: Canonical.com Patch Queue Manager
  • Date: 2009-04-09 20:23:07 UTC
  • mfrom: (4265.1.4 bbc-merge)
  • Revision ID: pqm@pqm.ubuntu.com-20090409202307-n0depb16qepoe21o
(jam) Change _fetch_uses_deltas = False for CHK repos until we can
        write a better fix.

Show diffs side-by-side

added added

removed removed

Lines of Context:
1
 
# Copyright (C) 2005, 2006, 2007 Canonical Ltd
 
1
# Copyright (C) 2005, 2006, 2007, 2008, 2009 Canonical Ltd
2
2
#
3
3
# This program is free software; you can redistribute it and/or modify
4
4
# it under the terms of the GNU General Public License as published by
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
 
19
19
At format 7 this was split out into Branch, Repository and Checkout control
20
20
directories.
 
21
 
 
22
Note: This module has a lot of ``open`` functions/methods that return
 
23
references to in-memory objects. As a rule, there are no matching ``close``
 
24
methods. To free any associated resources, simply stop referencing the
 
25
objects returned.
21
26
"""
22
27
 
23
 
# TODO: remove unittest dependency; put that stuff inside the test suite
24
 
 
25
 
# TODO: The Format probe_transport seems a bit redundant with just trying to
26
 
# open the bzrdir. -- mbp
27
 
#
28
 
# TODO: Can we move specific formats into separate modules to make this file
29
 
# smaller?
30
 
 
31
 
from cStringIO import StringIO
 
28
# TODO: Move old formats into a plugin to make this file smaller.
 
29
 
32
30
import os
33
 
import textwrap
 
31
import sys
34
32
 
35
33
from bzrlib.lazy_import import lazy_import
36
34
lazy_import(globals(), """
37
 
from copy import deepcopy
38
35
from stat import S_ISDIR
39
 
import unittest
 
36
import textwrap
40
37
 
41
38
import bzrlib
42
39
from bzrlib import (
 
40
    config,
43
41
    errors,
 
42
    graph,
44
43
    lockable_files,
45
44
    lockdir,
46
 
    registry,
 
45
    osutils,
 
46
    remote,
47
47
    revision as _mod_revision,
48
 
    symbol_versioning,
49
48
    ui,
50
49
    urlutils,
 
50
    versionedfile,
 
51
    win32utils,
 
52
    workingtree,
 
53
    workingtree_4,
51
54
    xml4,
52
55
    xml5,
53
 
    workingtree,
54
 
    workingtree_4,
55
56
    )
56
57
from bzrlib.osutils import (
57
 
    safe_unicode,
58
 
    sha_strings,
59
58
    sha_string,
60
59
    )
61
 
from bzrlib.store.revision.text import TextRevisionStore
62
 
from bzrlib.store.text import TextStore
 
60
from bzrlib.push import (
 
61
    PushResult,
 
62
    )
 
63
from bzrlib.smart.client import _SmartClient
63
64
from bzrlib.store.versioned import WeaveStore
64
65
from bzrlib.transactions import WriteTransaction
65
66
from bzrlib.transport import (
66
67
    do_catching_redirections,
67
68
    get_transport,
 
69
    local,
 
70
    remote as remote_transport,
68
71
    )
69
72
from bzrlib.weave import Weave
70
73
""")
73
76
    mutter,
74
77
    note,
75
78
    )
76
 
from bzrlib.transport.local import LocalTransport
 
79
 
 
80
from bzrlib import (
 
81
    hooks,
 
82
    registry,
 
83
    symbol_versioning,
 
84
    )
77
85
 
78
86
 
79
87
class BzrDir(object):
80
88
    """A .bzr control diretory.
81
 
    
 
89
 
82
90
    BzrDir instances let you create or open any of the things that can be
83
91
    found within .bzr - checkouts, branches and repositories.
84
 
    
85
 
    transport
 
92
 
 
93
    :ivar transport:
86
94
        the transport which this bzr dir is rooted at (i.e. file:///.../.bzr/)
87
 
    root_transport
88
 
        a transport connected to the directory this bzr was opened from.
 
95
    :ivar root_transport:
 
96
        a transport connected to the directory this bzr was opened from
 
97
        (i.e. the parent directory holding the .bzr directory).
 
98
 
 
99
    Everything in the bzrdir should have the same file permissions.
 
100
 
 
101
    :cvar hooks: An instance of BzrDirHooks.
89
102
    """
90
103
 
91
104
    def break_lock(self):
94
107
        If there is a tree, the tree is opened and break_lock() called.
95
108
        Otherwise, branch is tried, and finally repository.
96
109
        """
 
110
        # XXX: This seems more like a UI function than something that really
 
111
        # belongs in this class.
97
112
        try:
98
113
            thing_to_unlock = self.open_workingtree()
99
114
        except (errors.NotLocalUrl, errors.NoWorkingTree):
121
136
        basedir=None):
122
137
        """Give an error or warning on old formats.
123
138
 
124
 
        :param format: may be any kind of format - workingtree, branch, 
 
139
        :param format: may be any kind of format - workingtree, branch,
125
140
        or repository.
126
141
 
127
 
        :param allow_unsupported: If true, allow opening 
128
 
        formats that are strongly deprecated, and which may 
 
142
        :param allow_unsupported: If true, allow opening
 
143
        formats that are strongly deprecated, and which may
129
144
        have limited functionality.
130
145
 
131
146
        :param recommend_upgrade: If true (default), warn
143
158
                format.get_format_description(),
144
159
                basedir)
145
160
 
146
 
    def clone(self, url, revision_id=None, force_new_repo=False):
 
161
    def clone(self, url, revision_id=None, force_new_repo=False,
 
162
              preserve_stacking=False):
147
163
        """Clone this bzrdir and its contents to url verbatim.
148
164
 
149
 
        If urls last component does not exist, it will be created.
150
 
 
151
 
        if revision_id is not None, then the clone operation may tune
152
 
            itself to download less data.
153
 
        :param force_new_repo: Do not use a shared repository for the target 
154
 
                               even if one is available.
155
 
        """
156
 
        self._make_tail(url)
157
 
        result = self._format.initialize(url)
 
165
        :param url: The url create the clone at.  If url's last component does
 
166
            not exist, it will be created.
 
167
        :param revision_id: The tip revision-id to use for any branch or
 
168
            working tree.  If not None, then the clone operation may tune
 
169
            itself to download less data.
 
170
        :param force_new_repo: Do not use a shared repository for the target
 
171
                               even if one is available.
 
172
        :param preserve_stacking: When cloning a stacked branch, stack the
 
173
            new branch on top of the other branch's stacked-on branch.
 
174
        """
 
175
        return self.clone_on_transport(get_transport(url),
 
176
                                       revision_id=revision_id,
 
177
                                       force_new_repo=force_new_repo,
 
178
                                       preserve_stacking=preserve_stacking)
 
179
 
 
180
    def clone_on_transport(self, transport, revision_id=None,
 
181
                           force_new_repo=False, preserve_stacking=False,
 
182
                           stacked_on=None):
 
183
        """Clone this bzrdir and its contents to transport verbatim.
 
184
 
 
185
        :param transport: The transport for the location to produce the clone
 
186
            at.  If the target directory does not exist, it will be created.
 
187
        :param revision_id: The tip revision-id to use for any branch or
 
188
            working tree.  If not None, then the clone operation may tune
 
189
            itself to download less data.
 
190
        :param force_new_repo: Do not use a shared repository for the target,
 
191
                               even if one is available.
 
192
        :param preserve_stacking: When cloning a stacked branch, stack the
 
193
            new branch on top of the other branch's stacked-on branch.
 
194
        """
 
195
        transport.ensure_base()
 
196
        require_stacking = (stacked_on is not None)
 
197
        format = self.cloning_metadir(require_stacking)
 
198
        # Bug: We create a metadir without knowing if it can support stacking,
 
199
        # we should look up the policy needs first.
 
200
        result = format.initialize_on_transport(transport)
 
201
        repository_policy = None
158
202
        try:
159
203
            local_repo = self.find_repository()
160
204
        except errors.NoRepositoryPresent:
161
205
            local_repo = None
 
206
        try:
 
207
            local_branch = self.open_branch()
 
208
        except errors.NotBranchError:
 
209
            local_branch = None
 
210
        else:
 
211
            # enable fallbacks when branch is not a branch reference
 
212
            if local_branch.repository.has_same_location(local_repo):
 
213
                local_repo = local_branch.repository
 
214
            if preserve_stacking:
 
215
                try:
 
216
                    stacked_on = local_branch.get_stacked_on_url()
 
217
                except (errors.UnstackableBranchFormat,
 
218
                        errors.UnstackableRepositoryFormat,
 
219
                        errors.NotStacked):
 
220
                    pass
 
221
 
162
222
        if local_repo:
163
223
            # may need to copy content in
164
 
            if force_new_repo:
165
 
                result_repo = local_repo.clone(
166
 
                    result,
167
 
                    revision_id=revision_id)
168
 
                result_repo.set_make_working_trees(local_repo.make_working_trees())
 
224
            repository_policy = result.determine_repository_policy(
 
225
                force_new_repo, stacked_on, self.root_transport.base,
 
226
                require_stacking=require_stacking)
 
227
            make_working_trees = local_repo.make_working_trees()
 
228
            result_repo, is_new_repo = repository_policy.acquire_repository(
 
229
                make_working_trees, local_repo.is_shared())
 
230
            if not require_stacking and repository_policy._require_stacking:
 
231
                require_stacking = True
 
232
                result._format.require_stacking()
 
233
            if is_new_repo and not require_stacking and revision_id is not None:
 
234
                fetch_spec = graph.PendingAncestryResult(
 
235
                    [revision_id], local_repo)
 
236
                result_repo.fetch(local_repo, fetch_spec=fetch_spec)
169
237
            else:
170
 
                try:
171
 
                    result_repo = result.find_repository()
172
 
                    # fetch content this dir needs.
173
 
                    result_repo.fetch(local_repo, revision_id=revision_id)
174
 
                except errors.NoRepositoryPresent:
175
 
                    # needed to make one anyway.
176
 
                    result_repo = local_repo.clone(
177
 
                        result,
178
 
                        revision_id=revision_id)
179
 
                    result_repo.set_make_working_trees(local_repo.make_working_trees())
 
238
                result_repo.fetch(local_repo, revision_id=revision_id)
 
239
        else:
 
240
            result_repo = None
180
241
        # 1 if there is a branch present
181
242
        #   make sure its content is available in the target repository
182
243
        #   clone it.
183
 
        try:
184
 
            self.open_branch().clone(result, revision_id=revision_id)
185
 
        except errors.NotBranchError:
186
 
            pass
187
 
        try:
188
 
            self.open_workingtree().clone(result)
 
244
        if local_branch is not None:
 
245
            result_branch = local_branch.clone(result, revision_id=revision_id,
 
246
                repository_policy=repository_policy)
 
247
        try:
 
248
            # Cheaper to check if the target is not local, than to try making
 
249
            # the tree and fail.
 
250
            result.root_transport.local_abspath('.')
 
251
            if result_repo is None or result_repo.make_working_trees():
 
252
                self.open_workingtree().clone(result)
189
253
        except (errors.NoWorkingTree, errors.NotLocalUrl):
190
254
            pass
191
255
        return result
193
257
    # TODO: This should be given a Transport, and should chdir up; otherwise
194
258
    # this will open a new connection.
195
259
    def _make_tail(self, url):
196
 
        head, tail = urlutils.split(url)
197
 
        if tail and tail != '.':
198
 
            t = get_transport(head)
199
 
            try:
200
 
                t.mkdir(tail)
201
 
            except errors.FileExists:
202
 
                pass
 
260
        t = get_transport(url)
 
261
        t.ensure_base()
203
262
 
204
 
    # TODO: Should take a Transport
205
263
    @classmethod
206
 
    def create(cls, base, format=None):
 
264
    def create(cls, base, format=None, possible_transports=None):
207
265
        """Create a new BzrDir at the url 'base'.
208
 
        
209
 
        This will call the current default formats initialize with base
210
 
        as the only parameter.
211
266
 
212
267
        :param format: If supplied, the format of branch to create.  If not
213
268
            supplied, the default is used.
 
269
        :param possible_transports: If supplied, a list of transports that
 
270
            can be reused to share a remote connection.
214
271
        """
215
272
        if cls is not BzrDir:
216
273
            raise AssertionError("BzrDir.create always creates the default"
217
274
                " format, not one of %r" % cls)
218
 
        head, tail = urlutils.split(base)
219
 
        if tail and tail != '.':
220
 
            t = get_transport(head)
221
 
            try:
222
 
                t.mkdir(tail)
223
 
            except errors.FileExists:
224
 
                pass
 
275
        t = get_transport(base, possible_transports)
 
276
        t.ensure_base()
225
277
        if format is None:
226
278
            format = BzrDirFormat.get_default_format()
227
 
        return format.initialize(safe_unicode(base))
 
279
        return format.initialize_on_transport(t)
 
280
 
 
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:
 
310
                pass
 
311
            else:
 
312
                recurse, value = evaluate(bzrdir)
 
313
                yield value
 
314
            try:
 
315
                subdirs = list_current(current_transport)
 
316
            except errors.NoSuchFile:
 
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, (None, repository)
 
340
            try:
 
341
                branch = bzrdir.open_branch()
 
342
            except errors.NotBranchError:
 
343
                return True, (None, None)
 
344
            else:
 
345
                return True, (branch, None)
 
346
        branches = []
 
347
        for branch, repo in BzrDir.find_bzrdirs(transport, evaluate=evaluate):
 
348
            if repo is not None:
 
349
                branches.extend(repo.find_branches())
 
350
            if branch is not None:
 
351
                branches.append(branch)
 
352
        return branches
 
353
 
 
354
    def destroy_repository(self):
 
355
        """Destroy the repository in this BzrDir"""
 
356
        raise NotImplementedError(self.destroy_repository)
228
357
 
229
358
    def create_branch(self):
230
359
        """Create a branch in this BzrDir.
231
360
 
232
 
        The bzrdirs format will control what branch format is created.
 
361
        The bzrdir's format will control what branch format is created.
233
362
        For more control see BranchFormatXX.create(a_bzrdir).
234
363
        """
235
364
        raise NotImplementedError(self.create_branch)
236
365
 
 
366
    def destroy_branch(self):
 
367
        """Destroy the branch in this BzrDir"""
 
368
        raise NotImplementedError(self.destroy_branch)
 
369
 
237
370
    @staticmethod
238
371
    def create_branch_and_repo(base, force_new_repo=False, format=None):
239
372
        """Create a new BzrDir, Branch and Repository at the url 'base'.
240
373
 
241
 
        This will use the current default BzrDirFormat, and use whatever 
 
374
        This will use the current default BzrDirFormat unless one is
 
375
        specified, and use whatever
242
376
        repository format that that uses via bzrdir.create_branch and
243
377
        create_repository. If a shared repository is available that is used
244
378
        preferentially.
247
381
 
248
382
        :param base: The URL to create the branch at.
249
383
        :param force_new_repo: If True a new repository is always created.
 
384
        :param format: If supplied, the format of branch to create.  If not
 
385
            supplied, the default is used.
250
386
        """
251
387
        bzrdir = BzrDir.create(base, format)
252
388
        bzrdir._find_or_create_repository(force_new_repo)
253
389
        return bzrdir.create_branch()
254
390
 
 
391
    def determine_repository_policy(self, force_new_repo=False, stack_on=None,
 
392
                                    stack_on_pwd=None, require_stacking=False):
 
393
        """Return an object representing a policy to use.
 
394
 
 
395
        This controls whether a new repository is created, and the format of
 
396
        that repository, or some existing shared repository used instead.
 
397
 
 
398
        If stack_on is supplied, will not seek a containing shared repo.
 
399
 
 
400
        :param force_new_repo: If True, require a new repository to be created.
 
401
        :param stack_on: If supplied, the location to stack on.  If not
 
402
            supplied, a default_stack_on location may be used.
 
403
        :param stack_on_pwd: If stack_on is relative, the location it is
 
404
            relative to.
 
405
        """
 
406
        def repository_policy(found_bzrdir):
 
407
            stack_on = None
 
408
            stack_on_pwd = None
 
409
            config = found_bzrdir.get_config()
 
410
            stop = False
 
411
            if config is not None:
 
412
                stack_on = config.get_default_stack_on()
 
413
                if stack_on is not None:
 
414
                    stack_on_pwd = found_bzrdir.root_transport.base
 
415
                    stop = True
 
416
            # does it have a repository ?
 
417
            try:
 
418
                repository = found_bzrdir.open_repository()
 
419
            except errors.NoRepositoryPresent:
 
420
                repository = None
 
421
            else:
 
422
                if ((found_bzrdir.root_transport.base !=
 
423
                     self.root_transport.base) and not repository.is_shared()):
 
424
                    # Don't look higher, can't use a higher shared repo.
 
425
                    repository = None
 
426
                    stop = True
 
427
                else:
 
428
                    stop = True
 
429
            if not stop:
 
430
                return None, False
 
431
            if repository:
 
432
                return UseExistingRepository(repository, stack_on,
 
433
                    stack_on_pwd, require_stacking=require_stacking), True
 
434
            else:
 
435
                return CreateRepository(self, stack_on, stack_on_pwd,
 
436
                    require_stacking=require_stacking), True
 
437
 
 
438
        if not force_new_repo:
 
439
            if stack_on is None:
 
440
                policy = self._find_containing(repository_policy)
 
441
                if policy is not None:
 
442
                    return policy
 
443
            else:
 
444
                try:
 
445
                    return UseExistingRepository(self.open_repository(),
 
446
                        stack_on, stack_on_pwd,
 
447
                        require_stacking=require_stacking)
 
448
                except errors.NoRepositoryPresent:
 
449
                    pass
 
450
        return CreateRepository(self, stack_on, stack_on_pwd,
 
451
                                require_stacking=require_stacking)
 
452
 
255
453
    def _find_or_create_repository(self, force_new_repo):
256
454
        """Create a new repository if needed, returning the repository."""
257
 
        if force_new_repo:
258
 
            return self.create_repository()
259
 
        try:
260
 
            return self.find_repository()
261
 
        except errors.NoRepositoryPresent:
262
 
            return self.create_repository()
263
 
        
 
455
        policy = self.determine_repository_policy(force_new_repo)
 
456
        return policy.acquire_repository()[0]
 
457
 
264
458
    @staticmethod
265
459
    def create_branch_convenience(base, force_new_repo=False,
266
 
                                  force_new_tree=None, format=None):
 
460
                                  force_new_tree=None, format=None,
 
461
                                  possible_transports=None):
267
462
        """Create a new BzrDir, Branch and Repository at the url 'base'.
268
463
 
269
464
        This is a convenience function - it will use an existing repository
270
465
        if possible, can be told explicitly whether to create a working tree or
271
466
        not.
272
467
 
273
 
        This will use the current default BzrDirFormat, and use whatever 
 
468
        This will use the current default BzrDirFormat unless one is
 
469
        specified, and use whatever
274
470
        repository format that that uses via bzrdir.create_branch and
275
471
        create_repository. If a shared repository is available that is used
276
472
        preferentially. Whatever repository is used, its tree creation policy
278
474
 
279
475
        The created Branch object is returned.
280
476
        If a working tree cannot be made due to base not being a file:// url,
281
 
        no error is raised unless force_new_tree is True, in which case no 
 
477
        no error is raised unless force_new_tree is True, in which case no
282
478
        data is created on disk and NotLocalUrl is raised.
283
479
 
284
480
        :param base: The URL to create the branch at.
285
481
        :param force_new_repo: If True a new repository is always created.
286
 
        :param force_new_tree: If True or False force creation of a tree or 
 
482
        :param force_new_tree: If True or False force creation of a tree or
287
483
                               prevent such creation respectively.
288
 
        :param format: Override for the for the bzrdir format to create
 
484
        :param format: Override for the bzrdir format to create.
 
485
        :param possible_transports: An optional reusable transports list.
289
486
        """
290
487
        if force_new_tree:
291
488
            # check for non local urls
292
 
            t = get_transport(safe_unicode(base))
293
 
            if not isinstance(t, LocalTransport):
 
489
            t = get_transport(base, possible_transports)
 
490
            if not isinstance(t, local.LocalTransport):
294
491
                raise errors.NotLocalUrl(base)
295
 
        bzrdir = BzrDir.create(base, format)
 
492
        bzrdir = BzrDir.create(base, format, possible_transports)
296
493
        repo = bzrdir._find_or_create_repository(force_new_repo)
297
494
        result = bzrdir.create_branch()
298
 
        if force_new_tree or (repo.make_working_trees() and 
 
495
        if force_new_tree or (repo.make_working_trees() and
299
496
                              force_new_tree is None):
300
497
            try:
301
498
                bzrdir.create_workingtree()
302
499
            except errors.NotLocalUrl:
303
500
                pass
304
501
        return result
305
 
        
306
 
    @staticmethod
307
 
    def create_repository(base, shared=False, format=None):
308
 
        """Create a new BzrDir and Repository at the url 'base'.
309
 
 
310
 
        If no format is supplied, this will default to the current default
311
 
        BzrDirFormat by default, and use whatever repository format that that
312
 
        uses for bzrdirformat.create_repository.
313
 
 
314
 
        :param shared: Create a shared repository rather than a standalone
315
 
                       repository.
316
 
        The Repository object is returned.
317
 
 
318
 
        This must be overridden as an instance method in child classes, where
319
 
        it should take no parameters and construct whatever repository format
320
 
        that child class desires.
321
 
        """
322
 
        bzrdir = BzrDir.create(base, format)
323
 
        return bzrdir.create_repository(shared)
324
502
 
325
503
    @staticmethod
326
504
    def create_standalone_workingtree(base, format=None):
328
506
 
329
507
        'base' must be a local path or a file:// url.
330
508
 
331
 
        This will use the current default BzrDirFormat, and use whatever 
 
509
        This will use the current default BzrDirFormat unless one is
 
510
        specified, and use whatever
332
511
        repository format that that uses for bzrdirformat.create_workingtree,
333
512
        create_branch and create_repository.
334
513
 
 
514
        :param format: Override for the bzrdir format to create.
335
515
        :return: The WorkingTree object.
336
516
        """
337
 
        t = get_transport(safe_unicode(base))
338
 
        if not isinstance(t, LocalTransport):
 
517
        t = get_transport(base)
 
518
        if not isinstance(t, local.LocalTransport):
339
519
            raise errors.NotLocalUrl(base)
340
 
        bzrdir = BzrDir.create_branch_and_repo(safe_unicode(base),
 
520
        bzrdir = BzrDir.create_branch_and_repo(base,
341
521
                                               force_new_repo=True,
342
522
                                               format=format).bzrdir
343
523
        return bzrdir.create_workingtree()
344
524
 
345
 
    def create_workingtree(self, revision_id=None):
 
525
    def create_workingtree(self, revision_id=None, from_branch=None,
 
526
        accelerator_tree=None, hardlink=False):
346
527
        """Create a working tree at this BzrDir.
347
 
        
348
 
        revision_id: create it as of this revision id.
 
528
 
 
529
        :param revision_id: create it as of this revision id.
 
530
        :param from_branch: override bzrdir branch (for lightweight checkouts)
 
531
        :param accelerator_tree: A tree which can be used for retrieving file
 
532
            contents more quickly than the revision tree, i.e. a workingtree.
 
533
            The revision tree will be used for cases where accelerator_tree's
 
534
            content is different.
349
535
        """
350
536
        raise NotImplementedError(self.create_workingtree)
351
537
 
352
 
    def retire_bzrdir(self):
 
538
    def backup_bzrdir(self):
 
539
        """Backup this bzr control directory.
 
540
 
 
541
        :return: Tuple with old path name and new path name
 
542
        """
 
543
        pb = ui.ui_factory.nested_progress_bar()
 
544
        try:
 
545
            # FIXME: bug 300001 -- the backup fails if the backup directory
 
546
            # already exists, but it should instead either remove it or make
 
547
            # a new backup directory.
 
548
            #
 
549
            # FIXME: bug 262450 -- the backup directory should have the same
 
550
            # permissions as the .bzr directory (probably a bug in copy_tree)
 
551
            old_path = self.root_transport.abspath('.bzr')
 
552
            new_path = self.root_transport.abspath('backup.bzr')
 
553
            pb.note('making backup of %s' % (old_path,))
 
554
            pb.note('  to %s' % (new_path,))
 
555
            self.root_transport.copy_tree('.bzr', 'backup.bzr')
 
556
            return (old_path, new_path)
 
557
        finally:
 
558
            pb.finished()
 
559
 
 
560
    def retire_bzrdir(self, limit=10000):
353
561
        """Permanently disable the bzrdir.
354
562
 
355
563
        This is done by renaming it to give the user some ability to recover
357
565
 
358
566
        This will have horrible consequences if anyone has anything locked or
359
567
        in use.
 
568
        :param limit: number of times to retry
360
569
        """
361
 
        for i in xrange(10000):
 
570
        i  = 0
 
571
        while True:
362
572
            try:
363
573
                to_path = '.bzr.retired.%d' % i
364
574
                self.root_transport.rename('.bzr', to_path)
365
575
                note("renamed %s to %s"
366
576
                    % (self.root_transport.abspath('.bzr'), to_path))
367
 
                break
 
577
                return
368
578
            except (errors.TransportError, IOError, errors.PathError):
369
 
                pass
 
579
                i += 1
 
580
                if i > limit:
 
581
                    raise
 
582
                else:
 
583
                    pass
370
584
 
371
585
    def destroy_workingtree(self):
372
586
        """Destroy the working tree at this BzrDir.
383
597
        """
384
598
        raise NotImplementedError(self.destroy_workingtree_metadata)
385
599
 
 
600
    def _find_containing(self, evaluate):
 
601
        """Find something in a containing control directory.
 
602
 
 
603
        This method will scan containing control dirs, until it finds what
 
604
        it is looking for, decides that it will never find it, or runs out
 
605
        of containing control directories to check.
 
606
 
 
607
        It is used to implement find_repository and
 
608
        determine_repository_policy.
 
609
 
 
610
        :param evaluate: A function returning (value, stop).  If stop is True,
 
611
            the value will be returned.
 
612
        """
 
613
        found_bzrdir = self
 
614
        while True:
 
615
            result, stop = evaluate(found_bzrdir)
 
616
            if stop:
 
617
                return result
 
618
            next_transport = found_bzrdir.root_transport.clone('..')
 
619
            if (found_bzrdir.root_transport.base == next_transport.base):
 
620
                # top of the file system
 
621
                return None
 
622
            # find the next containing bzrdir
 
623
            try:
 
624
                found_bzrdir = BzrDir.open_containing_from_transport(
 
625
                    next_transport)[0]
 
626
            except errors.NotBranchError:
 
627
                return None
 
628
 
386
629
    def find_repository(self):
387
 
        """Find the repository that should be used for a_bzrdir.
 
630
        """Find the repository that should be used.
388
631
 
389
632
        This does not require a branch as we use it to find the repo for
390
633
        new branches as well as to hook existing branches up to their
391
634
        repository.
392
635
        """
393
 
        try:
394
 
            return self.open_repository()
395
 
        except errors.NoRepositoryPresent:
396
 
            pass
397
 
        next_transport = self.root_transport.clone('..')
398
 
        while True:
399
 
            # find the next containing bzrdir
400
 
            try:
401
 
                found_bzrdir = BzrDir.open_containing_from_transport(
402
 
                    next_transport)[0]
403
 
            except errors.NotBranchError:
404
 
                # none found
405
 
                raise errors.NoRepositoryPresent(self)
 
636
        def usable_repository(found_bzrdir):
406
637
            # does it have a repository ?
407
638
            try:
408
639
                repository = found_bzrdir.open_repository()
409
640
            except errors.NoRepositoryPresent:
410
 
                next_transport = found_bzrdir.root_transport.clone('..')
411
 
                if (found_bzrdir.root_transport.base == next_transport.base):
412
 
                    # top of the file system
413
 
                    break
414
 
                else:
415
 
                    continue
416
 
            if ((found_bzrdir.root_transport.base == 
417
 
                 self.root_transport.base) or repository.is_shared()):
418
 
                return repository
 
641
                return None, False
 
642
            if found_bzrdir.root_transport.base == self.root_transport.base:
 
643
                return repository, True
 
644
            elif repository.is_shared():
 
645
                return repository, True
419
646
            else:
420
 
                raise errors.NoRepositoryPresent(self)
421
 
        raise errors.NoRepositoryPresent(self)
 
647
                return None, True
 
648
 
 
649
        found_repo = self._find_containing(usable_repository)
 
650
        if found_repo is None:
 
651
            raise errors.NoRepositoryPresent(self)
 
652
        return found_repo
 
653
 
 
654
    def get_branch_reference(self):
 
655
        """Return the referenced URL for the branch in this bzrdir.
 
656
 
 
657
        :raises NotBranchError: If there is no Branch.
 
658
        :return: The URL the branch in this bzrdir references if it is a
 
659
            reference branch, or None for regular branches.
 
660
        """
 
661
        return None
422
662
 
423
663
    def get_branch_transport(self, branch_format):
424
664
        """Get the transport for use by branch format in this BzrDir.
427
667
        IncompatibleFormat if the branch format they are given has
428
668
        a format string, and vice versa.
429
669
 
430
 
        If branch_format is None, the transport is returned with no 
431
 
        checking. if it is not None, then the returned transport is
 
670
        If branch_format is None, the transport is returned with no
 
671
        checking. If it is not None, then the returned transport is
432
672
        guaranteed to point to an existing directory ready for use.
433
673
        """
434
674
        raise NotImplementedError(self.get_branch_transport)
435
 
        
 
675
 
 
676
    def _find_creation_modes(self):
 
677
        """Determine the appropriate modes for files and directories.
 
678
 
 
679
        They're always set to be consistent with the base directory,
 
680
        assuming that this transport allows setting modes.
 
681
        """
 
682
        # TODO: Do we need or want an option (maybe a config setting) to turn
 
683
        # this off or override it for particular locations? -- mbp 20080512
 
684
        if self._mode_check_done:
 
685
            return
 
686
        self._mode_check_done = True
 
687
        try:
 
688
            st = self.transport.stat('.')
 
689
        except errors.TransportNotPossible:
 
690
            self._dir_mode = None
 
691
            self._file_mode = None
 
692
        else:
 
693
            # Check the directory mode, but also make sure the created
 
694
            # directories and files are read-write for this user. This is
 
695
            # mostly a workaround for filesystems which lie about being able to
 
696
            # write to a directory (cygwin & win32)
 
697
            if (st.st_mode & 07777 == 00000):
 
698
                # FTP allows stat but does not return dir/file modes
 
699
                self._dir_mode = None
 
700
                self._file_mode = None
 
701
            else:
 
702
                self._dir_mode = (st.st_mode & 07777) | 00700
 
703
                # Remove the sticky and execute bits for files
 
704
                self._file_mode = self._dir_mode & ~07111
 
705
 
 
706
    def _get_file_mode(self):
 
707
        """Return Unix mode for newly created files, or None.
 
708
        """
 
709
        if not self._mode_check_done:
 
710
            self._find_creation_modes()
 
711
        return self._file_mode
 
712
 
 
713
    def _get_dir_mode(self):
 
714
        """Return Unix mode for newly created directories, or None.
 
715
        """
 
716
        if not self._mode_check_done:
 
717
            self._find_creation_modes()
 
718
        return self._dir_mode
 
719
 
436
720
    def get_repository_transport(self, repository_format):
437
721
        """Get the transport for use by repository format in this BzrDir.
438
722
 
440
724
        IncompatibleFormat if the repository format they are given has
441
725
        a format string, and vice versa.
442
726
 
443
 
        If repository_format is None, the transport is returned with no 
444
 
        checking. if it is not None, then the returned transport is
 
727
        If repository_format is None, the transport is returned with no
 
728
        checking. If it is not None, then the returned transport is
445
729
        guaranteed to point to an existing directory ready for use.
446
730
        """
447
731
        raise NotImplementedError(self.get_repository_transport)
448
 
        
 
732
 
449
733
    def get_workingtree_transport(self, tree_format):
450
734
        """Get the transport for use by workingtree format in this BzrDir.
451
735
 
453
737
        IncompatibleFormat if the workingtree format they are given has a
454
738
        format string, and vice versa.
455
739
 
456
 
        If workingtree_format is None, the transport is returned with no 
457
 
        checking. if it is not None, then the returned transport is
 
740
        If workingtree_format is None, the transport is returned with no
 
741
        checking. If it is not None, then the returned transport is
458
742
        guaranteed to point to an existing directory ready for use.
459
743
        """
460
744
        raise NotImplementedError(self.get_workingtree_transport)
461
 
        
 
745
 
 
746
    def get_config(self):
 
747
        if getattr(self, '_get_config', None) is None:
 
748
            return None
 
749
        return self._get_config()
 
750
 
462
751
    def __init__(self, _transport, _format):
463
752
        """Initialize a Bzr control dir object.
464
 
        
 
753
 
465
754
        Only really common logic should reside here, concrete classes should be
466
755
        made with varying behaviours.
467
756
 
471
760
        self._format = _format
472
761
        self.transport = _transport.clone('.bzr')
473
762
        self.root_transport = _transport
 
763
        self._mode_check_done = False
474
764
 
475
765
    def is_control_filename(self, filename):
476
766
        """True if filename is the name of a path which is reserved for bzrdir's.
477
 
        
 
767
 
478
768
        :param filename: A filename within the root transport of this bzrdir.
479
769
 
480
770
        This is true IF and ONLY IF the filename is part of the namespace reserved
483
773
        this in the future - for instance to make bzr talk with svn working
484
774
        trees.
485
775
        """
486
 
        # this might be better on the BzrDirFormat class because it refers to 
487
 
        # all the possible bzrdir disk formats. 
488
 
        # This method is tested via the workingtree is_control_filename tests- 
489
 
        # it was extracted from WorkingTree.is_control_filename. If the methods
490
 
        # contract is extended beyond the current trivial  implementation please
 
776
        # this might be better on the BzrDirFormat class because it refers to
 
777
        # all the possible bzrdir disk formats.
 
778
        # This method is tested via the workingtree is_control_filename tests-
 
779
        # it was extracted from WorkingTree.is_control_filename. If the method's
 
780
        # contract is extended beyond the current trivial implementation, please
491
781
        # add new tests for it to the appropriate place.
492
782
        return filename == '.bzr' or filename.startswith('.bzr/')
493
783
 
494
784
    def needs_format_conversion(self, format=None):
495
785
        """Return true if this bzrdir needs convert_format run on it.
496
 
        
497
 
        For instance, if the repository format is out of date but the 
 
786
 
 
787
        For instance, if the repository format is out of date but the
498
788
        branch and working tree are not, this should return True.
499
789
 
500
790
        :param format: Optional parameter indicating a specific desired
506
796
    def open_unsupported(base):
507
797
        """Open a branch which is not supported."""
508
798
        return BzrDir.open(base, _unsupported=True)
509
 
        
 
799
 
510
800
    @staticmethod
511
 
    def open(base, _unsupported=False):
512
 
        """Open an existing bzrdir, rooted at 'base' (url)
513
 
        
514
 
        _unsupported is a private parameter to the BzrDir class.
 
801
    def open(base, _unsupported=False, possible_transports=None):
 
802
        """Open an existing bzrdir, rooted at 'base' (url).
 
803
 
 
804
        :param _unsupported: a private parameter to the BzrDir class.
515
805
        """
516
 
        t = get_transport(base)
 
806
        t = get_transport(base, possible_transports=possible_transports)
517
807
        return BzrDir.open_from_transport(t, _unsupported=_unsupported)
518
808
 
519
809
    @staticmethod
520
 
    def open_from_transport(transport, _unsupported=False):
 
810
    def open_from_transport(transport, _unsupported=False,
 
811
                            _server_formats=True):
521
812
        """Open a bzrdir within a particular directory.
522
813
 
523
814
        :param transport: Transport containing the bzrdir.
524
815
        :param _unsupported: private.
525
816
        """
 
817
        for hook in BzrDir.hooks['pre_open']:
 
818
            hook(transport)
 
819
        # Keep initial base since 'transport' may be modified while following
 
820
        # the redirections.
526
821
        base = transport.base
527
 
 
528
822
        def find_format(transport):
529
 
            return transport, BzrDirFormat.find_format(transport)
 
823
            return transport, BzrDirFormat.find_format(
 
824
                transport, _server_formats=_server_formats)
530
825
 
531
826
        def redirected(transport, e, redirection_notice):
532
 
            qualified_source = e.get_source_url()
533
 
            relpath = transport.relpath(qualified_source)
534
 
            if not e.target.endswith(relpath):
535
 
                # Not redirected to a branch-format, not a branch
536
 
                raise errors.NotBranchError(path=e.target)
537
 
            target = e.target[:-len(relpath)]
 
827
            redirected_transport = transport._redirected_to(e.source, e.target)
 
828
            if redirected_transport is None:
 
829
                raise errors.NotBranchError(base)
538
830
            note('%s is%s redirected to %s',
539
 
                 transport.base, e.permanently, target)
540
 
            # Let's try with a new transport
541
 
            qualified_target = e.get_target_url()[:-len(relpath)]
542
 
            # FIXME: If 'transport' has a qualifier, this should
543
 
            # be applied again to the new transport *iff* the
544
 
            # schemes used are the same. It's a bit tricky to
545
 
            # verify, so I'll punt for now
546
 
            # -- vila20070212
547
 
            return get_transport(target)
 
831
                 transport.base, e.permanently, redirected_transport.base)
 
832
            return redirected_transport
548
833
 
549
834
        try:
550
835
            transport, format = do_catching_redirections(find_format,
556
841
        BzrDir._check_supported(format, _unsupported)
557
842
        return format.open(transport, _found=True)
558
843
 
559
 
    def open_branch(self, unsupported=False):
 
844
    def open_branch(self, unsupported=False, ignore_fallbacks=False):
560
845
        """Open the branch object at this BzrDir if one is present.
561
846
 
562
847
        If unsupported is True, then no longer supported branch formats can
563
848
        still be opened.
564
 
        
 
849
 
565
850
        TODO: static convenience version of this?
566
851
        """
567
852
        raise NotImplementedError(self.open_branch)
568
853
 
569
854
    @staticmethod
570
 
    def open_containing(url):
 
855
    def open_containing(url, possible_transports=None):
571
856
        """Open an existing branch which contains url.
572
 
        
 
857
 
573
858
        :param url: url to search from.
574
859
        See open_containing_from_transport for more detail.
575
860
        """
576
 
        return BzrDir.open_containing_from_transport(get_transport(url))
577
 
    
 
861
        transport = get_transport(url, possible_transports)
 
862
        return BzrDir.open_containing_from_transport(transport)
 
863
 
578
864
    @staticmethod
579
865
    def open_containing_from_transport(a_transport):
580
 
        """Open an existing branch which contains a_transport.base
 
866
        """Open an existing branch which contains a_transport.base.
581
867
 
582
868
        This probes for a branch at a_transport, and searches upwards from there.
583
869
 
584
870
        Basically we keep looking up until we find the control directory or
585
871
        run into the root.  If there isn't one, raises NotBranchError.
586
 
        If there is one and it is either an unrecognised format or an unsupported 
 
872
        If there is one and it is either an unrecognised format or an unsupported
587
873
        format, UnknownFormatError or UnsupportedFormatError are raised.
588
874
        If there is one, it is returned, along with the unused portion of url.
589
875
 
590
 
        :return: The BzrDir that contains the path, and a Unicode path 
 
876
        :return: The BzrDir that contains the path, and a Unicode path
591
877
                for the rest of the URL.
592
878
        """
593
879
        # this gets the normalised url back. I.e. '.' -> the full path.
598
884
                return result, urlutils.unescape(a_transport.relpath(url))
599
885
            except errors.NotBranchError, e:
600
886
                pass
601
 
            new_t = a_transport.clone('..')
 
887
            try:
 
888
                new_t = a_transport.clone('..')
 
889
            except errors.InvalidURLJoin:
 
890
                # reached the root, whatever that may be
 
891
                raise errors.NotBranchError(path=url)
602
892
            if new_t.base == a_transport.base:
603
893
                # reached the root, whatever that may be
604
894
                raise errors.NotBranchError(path=url)
605
895
            a_transport = new_t
606
896
 
 
897
    def _get_tree_branch(self):
 
898
        """Return the branch and tree, if any, for this bzrdir.
 
899
 
 
900
        Return None for tree if not present or inaccessible.
 
901
        Raise NotBranchError if no branch is present.
 
902
        :return: (tree, branch)
 
903
        """
 
904
        try:
 
905
            tree = self.open_workingtree()
 
906
        except (errors.NoWorkingTree, errors.NotLocalUrl):
 
907
            tree = None
 
908
            branch = self.open_branch()
 
909
        else:
 
910
            branch = tree.branch
 
911
        return tree, branch
 
912
 
 
913
    @classmethod
 
914
    def open_tree_or_branch(klass, location):
 
915
        """Return the branch and working tree at a location.
 
916
 
 
917
        If there is no tree at the location, tree will be None.
 
918
        If there is no branch at the location, an exception will be
 
919
        raised
 
920
        :return: (tree, branch)
 
921
        """
 
922
        bzrdir = klass.open(location)
 
923
        return bzrdir._get_tree_branch()
 
924
 
607
925
    @classmethod
608
926
    def open_containing_tree_or_branch(klass, location):
609
927
        """Return the branch and working tree contained by a location.
615
933
        relpath is the portion of the path that is contained by the branch.
616
934
        """
617
935
        bzrdir, relpath = klass.open_containing(location)
618
 
        try:
619
 
            tree = bzrdir.open_workingtree()
620
 
        except (errors.NoWorkingTree, errors.NotLocalUrl):
621
 
            tree = None
622
 
            branch = bzrdir.open_branch()
623
 
        else:
624
 
            branch = tree.branch
 
936
        tree, branch = bzrdir._get_tree_branch()
625
937
        return tree, branch, relpath
626
938
 
 
939
    @classmethod
 
940
    def open_containing_tree_branch_or_repository(klass, location):
 
941
        """Return the working tree, branch and repo contained by a location.
 
942
 
 
943
        Returns (tree, branch, repository, relpath).
 
944
        If there is no tree containing the location, tree will be None.
 
945
        If there is no branch containing the location, branch will be None.
 
946
        If there is no repository containing the location, repository will be
 
947
        None.
 
948
        relpath is the portion of the path that is contained by the innermost
 
949
        BzrDir.
 
950
 
 
951
        If no tree, branch or repository is found, a NotBranchError is raised.
 
952
        """
 
953
        bzrdir, relpath = klass.open_containing(location)
 
954
        try:
 
955
            tree, branch = bzrdir._get_tree_branch()
 
956
        except errors.NotBranchError:
 
957
            try:
 
958
                repo = bzrdir.find_repository()
 
959
                return None, None, repo, relpath
 
960
            except (errors.NoRepositoryPresent):
 
961
                raise errors.NotBranchError(location)
 
962
        return tree, branch, branch.repository, relpath
 
963
 
627
964
    def open_repository(self, _unsupported=False):
628
965
        """Open the repository object at this BzrDir if one is present.
629
966
 
630
 
        This will not follow the Branch object pointer - its strictly a direct
 
967
        This will not follow the Branch object pointer - it's strictly a direct
631
968
        open facility. Most client code should use open_branch().repository to
632
969
        get at a repository.
633
970
 
634
 
        _unsupported is a private parameter, not part of the api.
 
971
        :param _unsupported: a private parameter, not part of the api.
635
972
        TODO: static convenience version of this?
636
973
        """
637
974
        raise NotImplementedError(self.open_repository)
638
975
 
639
 
    def open_workingtree(self, _unsupported=False):
 
976
    def open_workingtree(self, _unsupported=False,
 
977
                         recommend_upgrade=True, from_branch=None):
640
978
        """Open the workingtree object at this BzrDir if one is present.
641
 
        
642
 
        TODO: static convenience version of this?
 
979
 
 
980
        :param recommend_upgrade: Optional keyword parameter, when True (the
 
981
            default), emit through the ui module a recommendation that the user
 
982
            upgrade the working tree when the workingtree being opened is old
 
983
            (but still fully supported).
 
984
        :param from_branch: override bzrdir branch (for lightweight checkouts)
643
985
        """
644
986
        raise NotImplementedError(self.open_workingtree)
645
987
 
646
988
    def has_branch(self):
647
989
        """Tell if this bzrdir contains a branch.
648
 
        
 
990
 
649
991
        Note: if you're going to open the branch, you should just go ahead
650
 
        and try, and not ask permission first.  (This method just opens the 
651
 
        branch and discards it, and that's somewhat expensive.) 
 
992
        and try, and not ask permission first.  (This method just opens the
 
993
        branch and discards it, and that's somewhat expensive.)
652
994
        """
653
995
        try:
654
996
            self.open_branch()
661
1003
 
662
1004
        This will still raise an exception if the bzrdir has a workingtree that
663
1005
        is remote & inaccessible.
664
 
        
 
1006
 
665
1007
        Note: if you're going to open the working tree, you should just go ahead
666
 
        and try, and not ask permission first.  (This method just opens the 
667
 
        workingtree and discards it, and that's somewhat expensive.) 
 
1008
        and try, and not ask permission first.  (This method just opens the
 
1009
        workingtree and discards it, and that's somewhat expensive.)
668
1010
        """
669
1011
        try:
670
1012
            self.open_workingtree(recommend_upgrade=False)
673
1015
            return False
674
1016
 
675
1017
    def _cloning_metadir(self):
 
1018
        """Produce a metadir suitable for cloning with.
 
1019
 
 
1020
        :returns: (destination_bzrdir_format, source_repository)
 
1021
        """
676
1022
        result_format = self._format.__class__()
677
1023
        try:
678
1024
            try:
679
 
                branch = self.open_branch()
 
1025
                branch = self.open_branch(ignore_fallbacks=True)
680
1026
                source_repository = branch.repository
 
1027
                result_format._branch_format = branch._format
681
1028
            except errors.NotBranchError:
682
1029
                source_branch = None
683
1030
                source_repository = self.open_repository()
684
 
            result_format.repository_format = source_repository._format
685
1031
        except errors.NoRepositoryPresent:
686
1032
            source_repository = None
 
1033
        else:
 
1034
            # XXX TODO: This isinstance is here because we have not implemented
 
1035
            # the fix recommended in bug # 103195 - to delegate this choice the
 
1036
            # repository itself.
 
1037
            repo_format = source_repository._format
 
1038
            if isinstance(repo_format, remote.RemoteRepositoryFormat):
 
1039
                source_repository._ensure_real()
 
1040
                repo_format = source_repository._real_repository._format
 
1041
            result_format.repository_format = repo_format
687
1042
        try:
688
1043
            # TODO: Couldn't we just probe for the format in these cases,
689
1044
            # rather than opening the whole tree?  It would be a little
695
1050
            result_format.workingtree_format = tree._format.__class__()
696
1051
        return result_format, source_repository
697
1052
 
698
 
    def cloning_metadir(self):
 
1053
    def cloning_metadir(self, require_stacking=False):
699
1054
        """Produce a metadir suitable for cloning or sprouting with.
700
1055
 
701
1056
        These operations may produce workingtrees (yes, even though they're
702
 
        "cloning" something that doesn't have a tree, so a viable workingtree
 
1057
        "cloning" something that doesn't have a tree), so a viable workingtree
703
1058
        format must be selected.
 
1059
 
 
1060
        :require_stacking: If True, non-stackable formats will be upgraded
 
1061
            to similar stackable formats.
 
1062
        :returns: a BzrDirFormat with all component formats either set
 
1063
            appropriately or set to None if that component should not be
 
1064
            created.
704
1065
        """
705
1066
        format, repository = self._cloning_metadir()
706
1067
        if format._workingtree_format is None:
708
1069
                return format
709
1070
            tree_format = repository._format._matchingbzrdir.workingtree_format
710
1071
            format.workingtree_format = tree_format.__class__()
 
1072
        if require_stacking:
 
1073
            format.require_stacking()
711
1074
        return format
712
1075
 
713
1076
    def checkout_metadir(self):
714
1077
        return self.cloning_metadir()
715
1078
 
716
1079
    def sprout(self, url, revision_id=None, force_new_repo=False,
717
 
               recurse='down'):
 
1080
               recurse='down', possible_transports=None,
 
1081
               accelerator_tree=None, hardlink=False, stacked=False,
 
1082
               source_branch=None, create_tree_if_local=True):
718
1083
        """Create a copy of this bzrdir prepared for use as a new line of
719
1084
        development.
720
1085
 
721
 
        If urls last component does not exist, it will be created.
 
1086
        If url's last component does not exist, it will be created.
722
1087
 
723
1088
        Attributes related to the identity of the source branch like
724
1089
        branch nickname will be cleaned, a working tree is created
727
1092
 
728
1093
        if revision_id is not None, then the clone operation may tune
729
1094
            itself to download less data.
 
1095
        :param accelerator_tree: A tree which can be used for retrieving file
 
1096
            contents more quickly than the revision tree, i.e. a workingtree.
 
1097
            The revision tree will be used for cases where accelerator_tree's
 
1098
            content is different.
 
1099
        :param hardlink: If true, hard-link files from accelerator_tree,
 
1100
            where possible.
 
1101
        :param stacked: If true, create a stacked branch referring to the
 
1102
            location of this control directory.
 
1103
        :param create_tree_if_local: If true, a working-tree will be created
 
1104
            when working locally.
730
1105
        """
731
 
        self._make_tail(url)
732
 
        cloning_format = self.cloning_metadir()
733
 
        result = cloning_format.initialize(url)
734
 
        try:
735
 
            source_branch = self.open_branch()
 
1106
        target_transport = get_transport(url, possible_transports)
 
1107
        target_transport.ensure_base()
 
1108
        cloning_format = self.cloning_metadir(stacked)
 
1109
        # Create/update the result branch
 
1110
        result = cloning_format.initialize_on_transport(target_transport)
 
1111
        # if a stacked branch wasn't requested, we don't create one
 
1112
        # even if the origin was stacked
 
1113
        stacked_branch_url = None
 
1114
        if source_branch is not None:
 
1115
            if stacked:
 
1116
                stacked_branch_url = self.root_transport.base
736
1117
            source_repository = source_branch.repository
737
 
        except errors.NotBranchError:
738
 
            source_branch = None
739
 
            try:
740
 
                source_repository = self.open_repository()
741
 
            except errors.NoRepositoryPresent:
742
 
                source_repository = None
743
 
        if force_new_repo:
744
 
            result_repo = None
745
 
        else:
746
 
            try:
747
 
                result_repo = result.find_repository()
748
 
            except errors.NoRepositoryPresent:
749
 
                result_repo = None
750
 
        if source_repository is None and result_repo is not None:
751
 
            pass
752
 
        elif source_repository is None and result_repo is None:
753
 
            # no repo available, make a new one
754
 
            result.create_repository()
755
 
        elif source_repository is not None and result_repo is None:
756
 
            # have source, and want to make a new target repo
757
 
            # we don't clone the repo because that preserves attributes
758
 
            # like is_shared(), and we have not yet implemented a 
759
 
            # repository sprout().
760
 
            result_repo = result.create_repository()
761
 
        if result_repo is not None:
762
 
            # fetch needed content into target.
763
 
            if source_repository is not None:
 
1118
        else:
 
1119
            try:
 
1120
                source_branch = self.open_branch()
 
1121
                source_repository = source_branch.repository
 
1122
                if stacked:
 
1123
                    stacked_branch_url = self.root_transport.base
 
1124
            except errors.NotBranchError:
 
1125
                source_branch = None
 
1126
                try:
 
1127
                    source_repository = self.open_repository()
 
1128
                except errors.NoRepositoryPresent:
 
1129
                    source_repository = None
 
1130
        repository_policy = result.determine_repository_policy(
 
1131
            force_new_repo, stacked_branch_url, require_stacking=stacked)
 
1132
        result_repo, is_new_repo = repository_policy.acquire_repository()
 
1133
        if is_new_repo and revision_id is not None and not stacked:
 
1134
            fetch_spec = graph.PendingAncestryResult(
 
1135
                [revision_id], source_repository)
 
1136
        else:
 
1137
            fetch_spec = None
 
1138
        if source_repository is not None:
 
1139
            # Fetch while stacked to prevent unstacked fetch from
 
1140
            # Branch.sprout.
 
1141
            if fetch_spec is None:
764
1142
                result_repo.fetch(source_repository, revision_id=revision_id)
765
 
        if source_branch is not None:
766
 
            source_branch.sprout(result, revision_id=revision_id)
 
1143
            else:
 
1144
                result_repo.fetch(source_repository, fetch_spec=fetch_spec)
 
1145
 
 
1146
        if source_branch is None:
 
1147
            # this is for sprouting a bzrdir without a branch; is that
 
1148
            # actually useful?
 
1149
            # Not especially, but it's part of the contract.
 
1150
            result_branch = result.create_branch()
767
1151
        else:
768
 
            result.create_branch()
769
 
        # TODO: jam 20060426 we probably need a test in here in the
770
 
        #       case that the newly sprouted branch is a remote one
771
 
        if result_repo is None or result_repo.make_working_trees():
772
 
            wt = result.create_workingtree()
 
1152
            result_branch = source_branch.sprout(result,
 
1153
                revision_id=revision_id, repository_policy=repository_policy)
 
1154
        mutter("created new branch %r" % (result_branch,))
 
1155
 
 
1156
        # Create/update the result working tree
 
1157
        if (create_tree_if_local and
 
1158
            isinstance(target_transport, local.LocalTransport) and
 
1159
            (result_repo is None or result_repo.make_working_trees())):
 
1160
            wt = result.create_workingtree(accelerator_tree=accelerator_tree,
 
1161
                hardlink=hardlink)
773
1162
            wt.lock_write()
774
1163
            try:
775
1164
                if wt.path2id('') is None:
786
1175
                basis = wt.basis_tree()
787
1176
                basis.lock_read()
788
1177
                subtrees = basis.iter_references()
789
 
                recurse_branch = wt.branch
 
1178
            elif result_branch is not None:
 
1179
                basis = result_branch.basis_tree()
 
1180
                basis.lock_read()
 
1181
                subtrees = basis.iter_references()
790
1182
            elif source_branch is not None:
791
1183
                basis = source_branch.basis_tree()
792
1184
                basis.lock_read()
793
1185
                subtrees = basis.iter_references()
794
 
                recurse_branch = source_branch
795
1186
            else:
796
1187
                subtrees = []
797
1188
                basis = None
801
1192
                    sublocation = source_branch.reference_parent(file_id, path)
802
1193
                    sublocation.bzrdir.sprout(target,
803
1194
                        basis.get_reference_revision(file_id, path),
804
 
                        force_new_repo=force_new_repo, recurse=recurse)
 
1195
                        force_new_repo=force_new_repo, recurse=recurse,
 
1196
                        stacked=stacked)
805
1197
            finally:
806
1198
                if basis is not None:
807
1199
                    basis.unlock()
808
1200
        return result
809
1201
 
 
1202
    def push_branch(self, source, revision_id=None, overwrite=False, 
 
1203
        remember=False):
 
1204
        """Push the source branch into this BzrDir."""
 
1205
        br_to = None
 
1206
        # If we can open a branch, use its direct repository, otherwise see
 
1207
        # if there is a repository without a branch.
 
1208
        try:
 
1209
            br_to = self.open_branch()
 
1210
        except errors.NotBranchError:
 
1211
            # Didn't find a branch, can we find a repository?
 
1212
            repository_to = self.find_repository()
 
1213
        else:
 
1214
            # Found a branch, so we must have found a repository
 
1215
            repository_to = br_to.repository
 
1216
 
 
1217
        push_result = PushResult()
 
1218
        push_result.source_branch = source
 
1219
        if br_to is None:
 
1220
            # We have a repository but no branch, copy the revisions, and then
 
1221
            # create a branch.
 
1222
            repository_to.fetch(source.repository, revision_id=revision_id)
 
1223
            br_to = source.clone(self, revision_id=revision_id)
 
1224
            if source.get_push_location() is None or remember:
 
1225
                source.set_push_location(br_to.base)
 
1226
            push_result.stacked_on = None
 
1227
            push_result.branch_push_result = None
 
1228
            push_result.old_revno = None
 
1229
            push_result.old_revid = _mod_revision.NULL_REVISION
 
1230
            push_result.target_branch = br_to
 
1231
            push_result.master_branch = None
 
1232
            push_result.workingtree_updated = False
 
1233
        else:
 
1234
            # We have successfully opened the branch, remember if necessary:
 
1235
            if source.get_push_location() is None or remember:
 
1236
                source.set_push_location(br_to.base)
 
1237
            try:
 
1238
                tree_to = self.open_workingtree()
 
1239
            except errors.NotLocalUrl:
 
1240
                push_result.branch_push_result = source.push(br_to, 
 
1241
                    overwrite, stop_revision=revision_id)
 
1242
                push_result.workingtree_updated = False
 
1243
            except errors.NoWorkingTree:
 
1244
                push_result.branch_push_result = source.push(br_to,
 
1245
                    overwrite, stop_revision=revision_id)
 
1246
                push_result.workingtree_updated = None # Not applicable
 
1247
            else:
 
1248
                tree_to.lock_write()
 
1249
                try:
 
1250
                    push_result.branch_push_result = source.push(
 
1251
                        tree_to.branch, overwrite, stop_revision=revision_id)
 
1252
                    tree_to.update()
 
1253
                finally:
 
1254
                    tree_to.unlock()
 
1255
                push_result.workingtree_updated = True
 
1256
            push_result.old_revno = push_result.branch_push_result.old_revno
 
1257
            push_result.old_revid = push_result.branch_push_result.old_revid
 
1258
            push_result.target_branch = \
 
1259
                push_result.branch_push_result.target_branch
 
1260
        return push_result
 
1261
 
 
1262
 
 
1263
class BzrDirHooks(hooks.Hooks):
 
1264
    """Hooks for BzrDir operations."""
 
1265
 
 
1266
    def __init__(self):
 
1267
        """Create the default hooks."""
 
1268
        hooks.Hooks.__init__(self)
 
1269
        self.create_hook(hooks.HookPoint('pre_open',
 
1270
            "Invoked before attempting to open a BzrDir with the transport "
 
1271
            "that the open will use.", (1, 14), None))
 
1272
 
 
1273
# install the default hooks
 
1274
BzrDir.hooks = BzrDirHooks()
 
1275
 
810
1276
 
811
1277
class BzrDirPreSplitOut(BzrDir):
812
1278
    """A common class for the all-in-one formats."""
814
1280
    def __init__(self, _transport, _format):
815
1281
        """See BzrDir.__init__."""
816
1282
        super(BzrDirPreSplitOut, self).__init__(_transport, _format)
817
 
        assert self._format._lock_class == lockable_files.TransportLock
818
 
        assert self._format._lock_file_name == 'branch-lock'
819
1283
        self._control_files = lockable_files.LockableFiles(
820
1284
                                            self.get_branch_transport(None),
821
1285
                                            self._format._lock_file_name,
825
1289
        """Pre-splitout bzrdirs do not suffer from stale locks."""
826
1290
        raise NotImplementedError(self.break_lock)
827
1291
 
828
 
    def clone(self, url, revision_id=None, force_new_repo=False):
829
 
        """See BzrDir.clone()."""
830
 
        from bzrlib.workingtree import WorkingTreeFormat2
 
1292
    def cloning_metadir(self, require_stacking=False):
 
1293
        """Produce a metadir suitable for cloning with."""
 
1294
        if require_stacking:
 
1295
            return format_registry.make_bzrdir('1.6')
 
1296
        return self._format.__class__()
 
1297
 
 
1298
    def clone(self, url, revision_id=None, force_new_repo=False,
 
1299
              preserve_stacking=False):
 
1300
        """See BzrDir.clone().
 
1301
 
 
1302
        force_new_repo has no effect, since this family of formats always
 
1303
        require a new repository.
 
1304
        preserve_stacking has no effect, since no source branch using this
 
1305
        family of formats can be stacked, so there is no stacking to preserve.
 
1306
        """
831
1307
        self._make_tail(url)
832
1308
        result = self._format._initialize_for_clone(url)
833
1309
        self.open_repository().clone(result, revision_id=revision_id)
834
1310
        from_branch = self.open_branch()
835
1311
        from_branch.clone(result, revision_id=revision_id)
836
1312
        try:
837
 
            self.open_workingtree().clone(result)
 
1313
            tree = self.open_workingtree()
838
1314
        except errors.NotLocalUrl:
839
1315
            # make a new one, this format always has to have one.
840
 
            try:
841
 
                WorkingTreeFormat2().initialize(result)
842
 
            except errors.NotLocalUrl:
843
 
                # but we cannot do it for remote trees.
844
 
                to_branch = result.open_branch()
845
 
                WorkingTreeFormat2().stub_initialize_remote(to_branch.control_files)
 
1316
            result._init_workingtree()
 
1317
        else:
 
1318
            tree.clone(result)
846
1319
        return result
847
1320
 
848
1321
    def create_branch(self):
849
1322
        """See BzrDir.create_branch."""
850
 
        return self.open_branch()
 
1323
        return self._format.get_branch_format().initialize(self)
 
1324
 
 
1325
    def destroy_branch(self):
 
1326
        """See BzrDir.destroy_branch."""
 
1327
        raise errors.UnsupportedOperation(self.destroy_branch, self)
851
1328
 
852
1329
    def create_repository(self, shared=False):
853
1330
        """See BzrDir.create_repository."""
855
1332
            raise errors.IncompatibleFormat('shared repository', self._format)
856
1333
        return self.open_repository()
857
1334
 
858
 
    def create_workingtree(self, revision_id=None):
 
1335
    def destroy_repository(self):
 
1336
        """See BzrDir.destroy_repository."""
 
1337
        raise errors.UnsupportedOperation(self.destroy_repository, self)
 
1338
 
 
1339
    def create_workingtree(self, revision_id=None, from_branch=None,
 
1340
                           accelerator_tree=None, hardlink=False):
859
1341
        """See BzrDir.create_workingtree."""
 
1342
        # The workingtree is sometimes created when the bzrdir is created,
 
1343
        # but not when cloning.
 
1344
 
860
1345
        # this looks buggy but is not -really-
861
1346
        # because this format creates the workingtree when the bzrdir is
862
1347
        # created
864
1349
        # and that will have set it for us, its only
865
1350
        # specific uses of create_workingtree in isolation
866
1351
        # that can do wonky stuff here, and that only
867
 
        # happens for creating checkouts, which cannot be 
 
1352
        # happens for creating checkouts, which cannot be
868
1353
        # done on this format anyway. So - acceptable wart.
869
 
        result = self.open_workingtree(recommend_upgrade=False)
 
1354
        try:
 
1355
            result = self.open_workingtree(recommend_upgrade=False)
 
1356
        except errors.NoSuchFile:
 
1357
            result = self._init_workingtree()
870
1358
        if revision_id is not None:
871
1359
            if revision_id == _mod_revision.NULL_REVISION:
872
1360
                result.set_parent_ids([])
874
1362
                result.set_parent_ids([revision_id])
875
1363
        return result
876
1364
 
 
1365
    def _init_workingtree(self):
 
1366
        from bzrlib.workingtree import WorkingTreeFormat2
 
1367
        try:
 
1368
            return WorkingTreeFormat2().initialize(self)
 
1369
        except errors.NotLocalUrl:
 
1370
            # Even though we can't access the working tree, we need to
 
1371
            # create its control files.
 
1372
            return WorkingTreeFormat2()._stub_initialize_on_transport(
 
1373
                self.transport, self._control_files._file_mode)
 
1374
 
877
1375
    def destroy_workingtree(self):
878
1376
        """See BzrDir.destroy_workingtree."""
879
1377
        raise errors.UnsupportedOperation(self.destroy_workingtree, self)
880
1378
 
881
1379
    def destroy_workingtree_metadata(self):
882
1380
        """See BzrDir.destroy_workingtree_metadata."""
883
 
        raise errors.UnsupportedOperation(self.destroy_workingtree_metadata, 
 
1381
        raise errors.UnsupportedOperation(self.destroy_workingtree_metadata,
884
1382
                                          self)
885
1383
 
886
1384
    def get_branch_transport(self, branch_format):
918
1416
        # if the format is not the same as the system default,
919
1417
        # an upgrade is needed.
920
1418
        if format is None:
 
1419
            symbol_versioning.warn(symbol_versioning.deprecated_in((1, 13, 0))
 
1420
                % 'needs_format_conversion(format=None)')
921
1421
            format = BzrDirFormat.get_default_format()
922
1422
        return not isinstance(self._format, format.__class__)
923
1423
 
924
 
    def open_branch(self, unsupported=False):
 
1424
    def open_branch(self, unsupported=False, ignore_fallbacks=False):
925
1425
        """See BzrDir.open_branch."""
926
1426
        from bzrlib.branch import BzrBranchFormat4
927
1427
        format = BzrBranchFormat4()
928
1428
        self._check_supported(format, unsupported)
929
1429
        return format.open(self, _found=True)
930
1430
 
931
 
    def sprout(self, url, revision_id=None, force_new_repo=False):
 
1431
    def sprout(self, url, revision_id=None, force_new_repo=False,
 
1432
               possible_transports=None, accelerator_tree=None,
 
1433
               hardlink=False, stacked=False, create_tree_if_local=True,
 
1434
               source_branch=None):
932
1435
        """See BzrDir.sprout()."""
 
1436
        if source_branch is not None:
 
1437
            my_branch = self.open_branch()
 
1438
            if source_branch.base != my_branch.base:
 
1439
                raise AssertionError(
 
1440
                    "source branch %r is not within %r with branch %r" %
 
1441
                    (source_branch, self, my_branch))
 
1442
        if stacked:
 
1443
            raise errors.UnstackableBranchFormat(
 
1444
                self._format, self.root_transport.base)
 
1445
        if not create_tree_if_local:
 
1446
            raise errors.MustHaveWorkingTree(
 
1447
                self._format, self.root_transport.base)
933
1448
        from bzrlib.workingtree import WorkingTreeFormat2
934
1449
        self._make_tail(url)
935
1450
        result = self._format._initialize_for_clone(url)
941
1456
            self.open_branch().sprout(result, revision_id=revision_id)
942
1457
        except errors.NotBranchError:
943
1458
            pass
 
1459
 
944
1460
        # we always want a working tree
945
 
        WorkingTreeFormat2().initialize(result)
 
1461
        WorkingTreeFormat2().initialize(result,
 
1462
                                        accelerator_tree=accelerator_tree,
 
1463
                                        hardlink=hardlink)
946
1464
        return result
947
1465
 
948
1466
 
949
1467
class BzrDir4(BzrDirPreSplitOut):
950
1468
    """A .bzr version 4 control object.
951
 
    
 
1469
 
952
1470
    This is a deprecated format and may be removed after sept 2006.
953
1471
    """
954
1472
 
958
1476
 
959
1477
    def needs_format_conversion(self, format=None):
960
1478
        """Format 4 dirs are always in need of conversion."""
 
1479
        if format is None:
 
1480
            symbol_versioning.warn(symbol_versioning.deprecated_in((1, 13, 0))
 
1481
                % 'needs_format_conversion(format=None)')
961
1482
        return True
962
1483
 
963
1484
    def open_repository(self):
1009
1530
 
1010
1531
class BzrDirMeta1(BzrDir):
1011
1532
    """A .bzr meta version 1 control object.
1012
 
    
1013
 
    This is the first control object where the 
 
1533
 
 
1534
    This is the first control object where the
1014
1535
    individual aspects are really split out: there are separate repository,
1015
1536
    workingtree and branch subdirectories and any subset of the three can be
1016
1537
    present within a BzrDir.
1024
1545
        """See BzrDir.create_branch."""
1025
1546
        return self._format.get_branch_format().initialize(self)
1026
1547
 
 
1548
    def destroy_branch(self):
 
1549
        """See BzrDir.create_branch."""
 
1550
        self.transport.delete_tree('branch')
 
1551
 
1027
1552
    def create_repository(self, shared=False):
1028
1553
        """See BzrDir.create_repository."""
1029
1554
        return self._format.repository_format.initialize(self, shared)
1030
1555
 
1031
 
    def create_workingtree(self, revision_id=None):
 
1556
    def destroy_repository(self):
 
1557
        """See BzrDir.destroy_repository."""
 
1558
        self.transport.delete_tree('repository')
 
1559
 
 
1560
    def create_workingtree(self, revision_id=None, from_branch=None,
 
1561
                           accelerator_tree=None, hardlink=False):
1032
1562
        """See BzrDir.create_workingtree."""
1033
 
        from bzrlib.workingtree import WorkingTreeFormat
1034
 
        return self._format.workingtree_format.initialize(self, revision_id)
 
1563
        return self._format.workingtree_format.initialize(
 
1564
            self, revision_id, from_branch=from_branch,
 
1565
            accelerator_tree=accelerator_tree, hardlink=hardlink)
1035
1566
 
1036
1567
    def destroy_workingtree(self):
1037
1568
        """See BzrDir.destroy_workingtree."""
1038
1569
        wt = self.open_workingtree(recommend_upgrade=False)
1039
1570
        repository = wt.branch.repository
1040
1571
        empty = repository.revision_tree(_mod_revision.NULL_REVISION)
1041
 
        wt.revert([], old_tree=empty)
 
1572
        wt.revert(old_tree=empty)
1042
1573
        self.destroy_workingtree_metadata()
1043
1574
 
1044
1575
    def destroy_workingtree_metadata(self):
1045
1576
        self.transport.delete_tree('checkout')
1046
1577
 
 
1578
    def find_branch_format(self):
 
1579
        """Find the branch 'format' for this bzrdir.
 
1580
 
 
1581
        This might be a synthetic object for e.g. RemoteBranch and SVN.
 
1582
        """
 
1583
        from bzrlib.branch import BranchFormat
 
1584
        return BranchFormat.find_format(self)
 
1585
 
1047
1586
    def _get_mkdir_mode(self):
1048
1587
        """Figure out the mode to use when creating a bzrdir subdir."""
1049
1588
        temp_control = lockable_files.LockableFiles(self.transport, '',
1050
1589
                                     lockable_files.TransportLock)
1051
1590
        return temp_control._dir_mode
1052
1591
 
 
1592
    def get_branch_reference(self):
 
1593
        """See BzrDir.get_branch_reference()."""
 
1594
        from bzrlib.branch import BranchFormat
 
1595
        format = BranchFormat.find_format(self)
 
1596
        return format.get_reference(self)
 
1597
 
1053
1598
    def get_branch_transport(self, branch_format):
1054
1599
        """See BzrDir.get_branch_transport()."""
1055
1600
        if branch_format is None:
1095
1640
    def needs_format_conversion(self, format=None):
1096
1641
        """See BzrDir.needs_format_conversion()."""
1097
1642
        if format is None:
 
1643
            symbol_versioning.warn(symbol_versioning.deprecated_in((1, 13, 0))
 
1644
                % 'needs_format_conversion(format=None)')
 
1645
        if format is None:
1098
1646
            format = BzrDirFormat.get_default_format()
1099
1647
        if not isinstance(self._format, format.__class__):
1100
1648
            # it is not a meta dir format, conversion is needed.
1124
1672
            pass
1125
1673
        return False
1126
1674
 
1127
 
    def open_branch(self, unsupported=False):
 
1675
    def open_branch(self, unsupported=False, ignore_fallbacks=False):
1128
1676
        """See BzrDir.open_branch."""
1129
 
        from bzrlib.branch import BranchFormat
1130
 
        format = BranchFormat.find_format(self)
 
1677
        format = self.find_branch_format()
1131
1678
        self._check_supported(format, unsupported)
1132
 
        return format.open(self, _found=True)
 
1679
        return format.open(self, _found=True, ignore_fallbacks=ignore_fallbacks)
1133
1680
 
1134
1681
    def open_repository(self, unsupported=False):
1135
1682
        """See BzrDir.open_repository."""
1148
1695
            basedir=self.root_transport.base)
1149
1696
        return format.open(self, _found=True)
1150
1697
 
 
1698
    def _get_config(self):
 
1699
        return config.BzrDirConfig(self.transport)
 
1700
 
1151
1701
 
1152
1702
class BzrDirFormat(object):
1153
1703
    """An encapsulation of the initialization and open routines for a format.
1157
1707
     * a format string,
1158
1708
     * an open routine.
1159
1709
 
1160
 
    Formats are placed in an dict by their format string for reference 
 
1710
    Formats are placed in a dict by their format string for reference
1161
1711
    during bzrdir opening. These should be subclasses of BzrDirFormat
1162
1712
    for consistency.
1163
1713
 
1164
1714
    Once a format is deprecated, just deprecate the initialize and open
1165
 
    methods on the format class. Do not deprecate the object, as the 
 
1715
    methods on the format class. Do not deprecate the object, as the
1166
1716
    object will be created every system load.
1167
1717
    """
1168
1718
 
1174
1724
 
1175
1725
    _control_formats = []
1176
1726
    """The registered control formats - .bzr, ....
1177
 
    
 
1727
 
 
1728
    This is a list of BzrDirFormat objects.
 
1729
    """
 
1730
 
 
1731
    _control_server_formats = []
 
1732
    """The registered control server formats, e.g. RemoteBzrDirs.
 
1733
 
1178
1734
    This is a list of BzrDirFormat objects.
1179
1735
    """
1180
1736
 
1184
1740
    # TransportLock or LockDir
1185
1741
 
1186
1742
    @classmethod
1187
 
    def find_format(klass, transport):
 
1743
    def find_format(klass, transport, _server_formats=True):
1188
1744
        """Return the format present at transport."""
1189
 
        for format in klass._control_formats:
 
1745
        if _server_formats:
 
1746
            formats = klass._control_server_formats + klass._control_formats
 
1747
        else:
 
1748
            formats = klass._control_formats
 
1749
        for format in formats:
1190
1750
            try:
1191
1751
                return format.probe_transport(transport)
1192
1752
            except errors.NotBranchError:
1196
1756
 
1197
1757
    @classmethod
1198
1758
    def probe_transport(klass, transport):
1199
 
        """Return the .bzrdir style transport present at URL."""
 
1759
        """Return the .bzrdir style format present in a directory."""
1200
1760
        try:
1201
1761
            format_string = transport.get(".bzr/branch-format").read()
1202
1762
        except errors.NoSuchFile:
1205
1765
        try:
1206
1766
            return klass._formats[format_string]
1207
1767
        except KeyError:
1208
 
            raise errors.UnknownFormatError(format=format_string)
 
1768
            raise errors.UnknownFormatError(format=format_string, kind='bzrdir')
1209
1769
 
1210
1770
    @classmethod
1211
1771
    def get_default_format(klass):
1229
1789
        current default format. In the case of plugins we can/should provide
1230
1790
        some means for them to extend the range of returnable converters.
1231
1791
 
1232
 
        :param format: Optional format to override the default format of the 
 
1792
        :param format: Optional format to override the default format of the
1233
1793
                       library.
1234
1794
        """
1235
1795
        raise NotImplementedError(self.get_converter)
1236
1796
 
1237
 
    def initialize(self, url):
 
1797
    def initialize(self, url, possible_transports=None):
1238
1798
        """Create a bzr control dir at this url and return an opened copy.
1239
 
        
 
1799
 
1240
1800
        Subclasses should typically override initialize_on_transport
1241
1801
        instead of this method.
1242
1802
        """
1243
 
        return self.initialize_on_transport(get_transport(url))
 
1803
        return self.initialize_on_transport(get_transport(url,
 
1804
                                                          possible_transports))
1244
1805
 
1245
1806
    def initialize_on_transport(self, transport):
1246
1807
        """Initialize a new bzrdir in the base directory of a Transport."""
1247
 
        # Since we don't have a .bzr directory, inherit the
 
1808
        try:
 
1809
            # can we hand off the request to the smart server rather than using
 
1810
            # vfs calls?
 
1811
            client_medium = transport.get_smart_medium()
 
1812
        except errors.NoSmartMedium:
 
1813
            return self._initialize_on_transport_vfs(transport)
 
1814
        else:
 
1815
            # Current RPC's only know how to create bzr metadir1 instances, so
 
1816
            # we still delegate to vfs methods if the requested format is not a
 
1817
            # metadir1
 
1818
            if type(self) != BzrDirMetaFormat1:
 
1819
                return self._initialize_on_transport_vfs(transport)
 
1820
            remote_format = RemoteBzrDirFormat()
 
1821
            self._supply_sub_formats_to(remote_format)
 
1822
            return remote_format.initialize_on_transport(transport)
 
1823
 
 
1824
    def _initialize_on_transport_vfs(self, transport):
 
1825
        """Initialize a new bzrdir using VFS calls.
 
1826
 
 
1827
        :param transport: The transport to create the .bzr directory in.
 
1828
        :return: A
 
1829
        """
 
1830
        # Since we are creating a .bzr directory, inherit the
1248
1831
        # mode from the root directory
1249
1832
        temp_control = lockable_files.LockableFiles(transport,
1250
1833
                            '', lockable_files.TransportLock)
1252
1835
                                      # FIXME: RBC 20060121 don't peek under
1253
1836
                                      # the covers
1254
1837
                                      mode=temp_control._dir_mode)
 
1838
        if sys.platform == 'win32' and isinstance(transport, local.LocalTransport):
 
1839
            win32utils.set_file_attr_hidden(transport._abspath('.bzr'))
1255
1840
        file_mode = temp_control._file_mode
1256
1841
        del temp_control
1257
 
        mutter('created control directory in ' + transport.base)
1258
 
        control = transport.clone('.bzr')
1259
 
        utf8_files = [('README', 
1260
 
                       "This is a Bazaar-NG control directory.\n"
1261
 
                       "Do not change any files in this directory.\n"),
 
1842
        bzrdir_transport = transport.clone('.bzr')
 
1843
        utf8_files = [('README',
 
1844
                       "This is a Bazaar control directory.\n"
 
1845
                       "Do not change any files in this directory.\n"
 
1846
                       "See http://bazaar-vcs.org/ for more information about Bazaar.\n"),
1262
1847
                      ('branch-format', self.get_format_string()),
1263
1848
                      ]
1264
1849
        # NB: no need to escape relative paths that are url safe.
1265
 
        control_files = lockable_files.LockableFiles(control,
1266
 
                            self._lock_file_name, self._lock_class)
 
1850
        control_files = lockable_files.LockableFiles(bzrdir_transport,
 
1851
            self._lock_file_name, self._lock_class)
1267
1852
        control_files.create_lock()
1268
1853
        control_files.lock_write()
1269
1854
        try:
1270
 
            for file, content in utf8_files:
1271
 
                control_files.put_utf8(file, content)
 
1855
            for (filename, content) in utf8_files:
 
1856
                bzrdir_transport.put_bytes(filename, content,
 
1857
                    mode=file_mode)
1272
1858
        finally:
1273
1859
            control_files.unlock()
1274
1860
        return self.open(transport, _found=True)
1277
1863
        """Is this format supported?
1278
1864
 
1279
1865
        Supported formats must be initializable and openable.
1280
 
        Unsupported formats may not support initialization or committing or 
 
1866
        Unsupported formats may not support initialization or committing or
1281
1867
        some other features depending on the reason for not being supported.
1282
1868
        """
1283
1869
        return True
1284
1870
 
 
1871
    def network_name(self):
 
1872
        """A simple byte string uniquely identifying this format for RPC calls.
 
1873
 
 
1874
        Bzr control formats use thir disk format string to identify the format
 
1875
        over the wire. Its possible that other control formats have more
 
1876
        complex detection requirements, so we permit them to use any unique and
 
1877
        immutable string they desire.
 
1878
        """
 
1879
        raise NotImplementedError(self.network_name)
 
1880
 
1285
1881
    def same_model(self, target_format):
1286
 
        return (self.repository_format.rich_root_data == 
 
1882
        return (self.repository_format.rich_root_data ==
1287
1883
            target_format.rich_root_data)
1288
1884
 
1289
1885
    @classmethod
1290
1886
    def known_formats(klass):
1291
1887
        """Return all the known formats.
1292
 
        
 
1888
 
1293
1889
        Concrete formats should override _known_formats.
1294
1890
        """
1295
 
        # There is double indirection here to make sure that control 
1296
 
        # formats used by more than one dir format will only be probed 
 
1891
        # There is double indirection here to make sure that control
 
1892
        # formats used by more than one dir format will only be probed
1297
1893
        # once. This can otherwise be quite expensive for remote connections.
1298
1894
        result = set()
1299
1895
        for format in klass._control_formats:
1300
1896
            result.update(format._known_formats())
1301
1897
        return result
1302
 
    
 
1898
 
1303
1899
    @classmethod
1304
1900
    def _known_formats(klass):
1305
1901
        """Return the known format instances for this control format."""
1307
1903
 
1308
1904
    def open(self, transport, _found=False):
1309
1905
        """Return an instance of this format for the dir transport points at.
1310
 
        
 
1906
 
1311
1907
        _found is a private parameter, do not use it.
1312
1908
        """
1313
1909
        if not _found:
1314
1910
            found_format = BzrDirFormat.find_format(transport)
1315
1911
            if not isinstance(found_format, self.__class__):
1316
1912
                raise AssertionError("%s was asked to open %s, but it seems to need "
1317
 
                        "format %s" 
 
1913
                        "format %s"
1318
1914
                        % (self, transport, found_format))
 
1915
            # Allow subclasses - use the found format.
 
1916
            self._supply_sub_formats_to(found_format)
 
1917
            return found_format._open(transport)
1319
1918
        return self._open(transport)
1320
1919
 
1321
1920
    def _open(self, transport):
1329
1928
    @classmethod
1330
1929
    def register_format(klass, format):
1331
1930
        klass._formats[format.get_format_string()] = format
 
1931
        # bzr native formats have a network name of their format string.
 
1932
        network_format_registry.register(format.get_format_string(), format.__class__)
1332
1933
 
1333
1934
    @classmethod
1334
1935
    def register_control_format(klass, format):
1335
1936
        """Register a format that does not use '.bzr' for its control dir.
1336
1937
 
1337
1938
        TODO: This should be pulled up into a 'ControlDirFormat' base class
1338
 
        which BzrDirFormat can inherit from, and renamed to register_format 
 
1939
        which BzrDirFormat can inherit from, and renamed to register_format
1339
1940
        there. It has been done without that for now for simplicity of
1340
1941
        implementation.
1341
1942
        """
1342
1943
        klass._control_formats.append(format)
1343
1944
 
1344
1945
    @classmethod
1345
 
    @symbol_versioning.deprecated_method(symbol_versioning.zero_fourteen)
1346
 
    def set_default_format(klass, format):
1347
 
        klass._set_default_format(format)
 
1946
    def register_control_server_format(klass, format):
 
1947
        """Register a control format for client-server environments.
 
1948
 
 
1949
        These formats will be tried before ones registered with
 
1950
        register_control_format.  This gives implementations that decide to the
 
1951
        chance to grab it before anything looks at the contents of the format
 
1952
        file.
 
1953
        """
 
1954
        klass._control_server_formats.append(format)
1348
1955
 
1349
1956
    @classmethod
1350
1957
    def _set_default_format(klass, format):
1352
1959
        klass._default_format = format
1353
1960
 
1354
1961
    def __str__(self):
1355
 
        return self.get_format_string()[:-1]
 
1962
        # Trim the newline
 
1963
        return self.get_format_description().rstrip()
 
1964
 
 
1965
    def _supply_sub_formats_to(self, other_format):
 
1966
        """Give other_format the same values for sub formats as this has.
 
1967
 
 
1968
        This method is expected to be used when parameterising a
 
1969
        RemoteBzrDirFormat instance with the parameters from a
 
1970
        BzrDirMetaFormat1 instance.
 
1971
 
 
1972
        :param other_format: other_format is a format which should be
 
1973
            compatible with whatever sub formats are supported by self.
 
1974
        :return: None.
 
1975
        """
1356
1976
 
1357
1977
    @classmethod
1358
1978
    def unregister_format(klass, format):
1359
 
        assert klass._formats[format.get_format_string()] is format
1360
1979
        del klass._formats[format.get_format_string()]
1361
1980
 
1362
1981
    @classmethod
1391
2010
        """See BzrDirFormat.get_converter()."""
1392
2011
        # there is one and only one upgrade path here.
1393
2012
        return ConvertBzrDir4To5()
1394
 
        
 
2013
 
1395
2014
    def initialize_on_transport(self, transport):
1396
2015
        """Format 4 branches cannot be created."""
1397
2016
        raise errors.UninitializableFormat(self)
1400
2019
        """Format 4 is not supported.
1401
2020
 
1402
2021
        It is not supported because the model changed from 4 to 5 and the
1403
 
        conversion logic is expensive - so doing it on the fly was not 
 
2022
        conversion logic is expensive - so doing it on the fly was not
1404
2023
        feasible.
1405
2024
        """
1406
2025
        return False
1407
2026
 
 
2027
    def network_name(self):
 
2028
        return self.get_format_string()
 
2029
 
1408
2030
    def _open(self, transport):
1409
2031
        """See BzrDirFormat._open."""
1410
2032
        return BzrDir4(transport, self)
1421
2043
 
1422
2044
    This format is a combined format for working tree, branch and repository.
1423
2045
    It has:
1424
 
     - Format 2 working trees [always] 
1425
 
     - Format 4 branches [always] 
 
2046
     - Format 2 working trees [always]
 
2047
     - Format 4 branches [always]
1426
2048
     - Format 5 repositories [always]
1427
2049
       Unhashed stores in the repository.
1428
2050
    """
1433
2055
        """See BzrDirFormat.get_format_string()."""
1434
2056
        return "Bazaar-NG branch, format 5\n"
1435
2057
 
 
2058
    def get_branch_format(self):
 
2059
        from bzrlib import branch
 
2060
        return branch.BzrBranchFormat4()
 
2061
 
1436
2062
    def get_format_description(self):
1437
2063
        """See BzrDirFormat.get_format_description()."""
1438
2064
        return "All-in-one format 5"
1444
2070
 
1445
2071
    def _initialize_for_clone(self, url):
1446
2072
        return self.initialize_on_transport(get_transport(url), _cloning=True)
1447
 
        
 
2073
 
1448
2074
    def initialize_on_transport(self, transport, _cloning=False):
1449
2075
        """Format 5 dirs always have working tree, branch and repository.
1450
 
        
 
2076
 
1451
2077
        Except when they are being cloned.
1452
2078
        """
1453
2079
        from bzrlib.branch import BzrBranchFormat4
1454
2080
        from bzrlib.repofmt.weaverepo import RepositoryFormat5
1455
 
        from bzrlib.workingtree import WorkingTreeFormat2
1456
2081
        result = (super(BzrDirFormat5, self).initialize_on_transport(transport))
1457
2082
        RepositoryFormat5().initialize(result, _internal=True)
1458
2083
        if not _cloning:
1459
2084
            branch = BzrBranchFormat4().initialize(result)
1460
 
            try:
1461
 
                WorkingTreeFormat2().initialize(result)
1462
 
            except errors.NotLocalUrl:
1463
 
                # Even though we can't access the working tree, we need to
1464
 
                # create its control files.
1465
 
                WorkingTreeFormat2().stub_initialize_remote(branch.control_files)
 
2085
            result._init_workingtree()
1466
2086
        return result
1467
2087
 
 
2088
    def network_name(self):
 
2089
        return self.get_format_string()
 
2090
 
1468
2091
    def _open(self, transport):
1469
2092
        """See BzrDirFormat._open."""
1470
2093
        return BzrDir5(transport, self)
1481
2104
 
1482
2105
    This format is a combined format for working tree, branch and repository.
1483
2106
    It has:
1484
 
     - Format 2 working trees [always] 
1485
 
     - Format 4 branches [always] 
 
2107
     - Format 2 working trees [always]
 
2108
     - Format 4 branches [always]
1486
2109
     - Format 6 repositories [always]
1487
2110
    """
1488
2111
 
1496
2119
        """See BzrDirFormat.get_format_description()."""
1497
2120
        return "All-in-one format 6"
1498
2121
 
 
2122
    def get_branch_format(self):
 
2123
        from bzrlib import branch
 
2124
        return branch.BzrBranchFormat4()
 
2125
 
1499
2126
    def get_converter(self, format=None):
1500
2127
        """See BzrDirFormat.get_converter()."""
1501
2128
        # there is one and only one upgrade path here.
1502
2129
        return ConvertBzrDir6ToMeta()
1503
 
        
 
2130
 
1504
2131
    def _initialize_for_clone(self, url):
1505
2132
        return self.initialize_on_transport(get_transport(url), _cloning=True)
1506
2133
 
1507
2134
    def initialize_on_transport(self, transport, _cloning=False):
1508
2135
        """Format 6 dirs always have working tree, branch and repository.
1509
 
        
 
2136
 
1510
2137
        Except when they are being cloned.
1511
2138
        """
1512
2139
        from bzrlib.branch import BzrBranchFormat4
1513
2140
        from bzrlib.repofmt.weaverepo import RepositoryFormat6
1514
 
        from bzrlib.workingtree import WorkingTreeFormat2
1515
2141
        result = super(BzrDirFormat6, self).initialize_on_transport(transport)
1516
2142
        RepositoryFormat6().initialize(result, _internal=True)
1517
2143
        if not _cloning:
1518
2144
            branch = BzrBranchFormat4().initialize(result)
1519
 
            try:
1520
 
                WorkingTreeFormat2().initialize(result)
1521
 
            except errors.NotLocalUrl:
1522
 
                # Even though we can't access the working tree, we need to
1523
 
                # create its control files.
1524
 
                WorkingTreeFormat2().stub_initialize_remote(branch.control_files)
 
2145
            result._init_workingtree()
1525
2146
        return result
1526
2147
 
 
2148
    def network_name(self):
 
2149
        return self.get_format_string()
 
2150
 
1527
2151
    def _open(self, transport):
1528
2152
        """See BzrDirFormat._open."""
1529
2153
        return BzrDir6(transport, self)
1551
2175
    def __init__(self):
1552
2176
        self._workingtree_format = None
1553
2177
        self._branch_format = None
 
2178
        self._repository_format = None
1554
2179
 
1555
2180
    def __eq__(self, other):
1556
2181
        if other.__class__ is not self.__class__:
1573
2198
    def set_branch_format(self, format):
1574
2199
        self._branch_format = format
1575
2200
 
 
2201
    def require_stacking(self):
 
2202
        if not self.get_branch_format().supports_stacking():
 
2203
            # We need to make a stacked branch, but the default format for the
 
2204
            # target doesn't support stacking.  So force a branch that *can*
 
2205
            # support stacking.
 
2206
            from bzrlib.branch import BzrBranchFormat7
 
2207
            branch_format = BzrBranchFormat7()
 
2208
            self.set_branch_format(branch_format)
 
2209
            mutter("using %r for stacking" % (branch_format,))
 
2210
            from bzrlib.repofmt import pack_repo
 
2211
            if self.repository_format.rich_root_data:
 
2212
                bzrdir_format_name = '1.6.1-rich-root'
 
2213
                repo_format = pack_repo.RepositoryFormatKnitPack5RichRoot()
 
2214
            else:
 
2215
                bzrdir_format_name = '1.6'
 
2216
                repo_format = pack_repo.RepositoryFormatKnitPack5()
 
2217
            note('Source format does not support stacking, using format:'
 
2218
                 ' \'%s\'\n  %s\n',
 
2219
                 bzrdir_format_name, repo_format.get_format_description())
 
2220
            self.repository_format = repo_format
 
2221
 
1576
2222
    def get_converter(self, format=None):
1577
2223
        """See BzrDirFormat.get_converter()."""
1578
2224
        if format is None:
1590
2236
        """See BzrDirFormat.get_format_description()."""
1591
2237
        return "Meta directory format 1"
1592
2238
 
 
2239
    def network_name(self):
 
2240
        return self.get_format_string()
 
2241
 
1593
2242
    def _open(self, transport):
1594
2243
        """See BzrDirFormat._open."""
1595
2244
        return BzrDirMeta1(transport, self)
1596
2245
 
1597
2246
    def __return_repository_format(self):
1598
2247
        """Circular import protection."""
1599
 
        if getattr(self, '_repository_format', None):
 
2248
        if self._repository_format:
1600
2249
            return self._repository_format
1601
2250
        from bzrlib.repository import RepositoryFormat
1602
2251
        return RepositoryFormat.get_default_format()
1603
2252
 
1604
 
    def __set_repository_format(self, value):
1605
 
        """Allow changint the repository format for metadir formats."""
 
2253
    def _set_repository_format(self, value):
 
2254
        """Allow changing the repository format for metadir formats."""
1606
2255
        self._repository_format = value
1607
2256
 
1608
 
    repository_format = property(__return_repository_format, __set_repository_format)
 
2257
    repository_format = property(__return_repository_format,
 
2258
        _set_repository_format)
 
2259
 
 
2260
    def _supply_sub_formats_to(self, other_format):
 
2261
        """Give other_format the same values for sub formats as this has.
 
2262
 
 
2263
        This method is expected to be used when parameterising a
 
2264
        RemoteBzrDirFormat instance with the parameters from a
 
2265
        BzrDirMetaFormat1 instance.
 
2266
 
 
2267
        :param other_format: other_format is a format which should be
 
2268
            compatible with whatever sub formats are supported by self.
 
2269
        :return: None.
 
2270
        """
 
2271
        if getattr(self, '_repository_format', None) is not None:
 
2272
            other_format.repository_format = self.repository_format
 
2273
        if self._branch_format is not None:
 
2274
            other_format._branch_format = self._branch_format
 
2275
        if self._workingtree_format is not None:
 
2276
            other_format.workingtree_format = self.workingtree_format
1609
2277
 
1610
2278
    def __get_workingtree_format(self):
1611
2279
        if self._workingtree_format is None:
1620
2288
                                  __set_workingtree_format)
1621
2289
 
1622
2290
 
 
2291
network_format_registry = registry.FormatRegistry()
 
2292
"""Registry of formats indexed by their network name.
 
2293
 
 
2294
The network name for a BzrDirFormat is an identifier that can be used when
 
2295
referring to formats with smart server operations. See
 
2296
BzrDirFormat.network_name() for more detail.
 
2297
"""
 
2298
 
 
2299
 
1623
2300
# Register bzr control format
1624
2301
BzrDirFormat.register_control_format(BzrDirFormat)
1625
2302
 
1632
2309
BzrDirFormat._default_format = __default_format
1633
2310
 
1634
2311
 
1635
 
class BzrDirTestProviderAdapter(object):
1636
 
    """A tool to generate a suite testing multiple bzrdir formats at once.
1637
 
 
1638
 
    This is done by copying the test once for each transport and injecting
1639
 
    the transport_server, transport_readonly_server, and bzrdir_format
1640
 
    classes into each copy. Each copy is also given a new id() to make it
1641
 
    easy to identify.
1642
 
    """
1643
 
 
1644
 
    def __init__(self, transport_server, transport_readonly_server, formats):
1645
 
        self._transport_server = transport_server
1646
 
        self._transport_readonly_server = transport_readonly_server
1647
 
        self._formats = formats
1648
 
    
1649
 
    def adapt(self, test):
1650
 
        result = unittest.TestSuite()
1651
 
        for format in self._formats:
1652
 
            new_test = deepcopy(test)
1653
 
            new_test.transport_server = self._transport_server
1654
 
            new_test.transport_readonly_server = self._transport_readonly_server
1655
 
            new_test.bzrdir_format = format
1656
 
            def make_new_test_id():
1657
 
                new_id = "%s(%s)" % (new_test.id(), format.__class__.__name__)
1658
 
                return lambda: new_id
1659
 
            new_test.id = make_new_test_id()
1660
 
            result.addTest(new_test)
1661
 
        return result
1662
 
 
1663
 
 
1664
2312
class Converter(object):
1665
2313
    """Converts a disk format object from one format to another."""
1666
2314
 
1686
2334
        self.absent_revisions = set()
1687
2335
        self.text_count = 0
1688
2336
        self.revisions = {}
1689
 
        
 
2337
 
1690
2338
    def convert(self, to_convert, pb):
1691
2339
        """See Converter.convert()."""
1692
2340
        self.bzrdir = to_convert
1693
2341
        self.pb = pb
1694
2342
        self.pb.note('starting upgrade from format 4 to 5')
1695
 
        if isinstance(self.bzrdir.transport, LocalTransport):
 
2343
        if isinstance(self.bzrdir.transport, local.LocalTransport):
1696
2344
            self.bzrdir.get_workingtree_transport(None).delete('stat-cache')
1697
2345
        self._convert_to_weaves()
1698
2346
        return BzrDir.open(self.bzrdir.root_transport.base)
1737
2385
        self.pb.note('  %6d revisions not present', len(self.absent_revisions))
1738
2386
        self.pb.note('  %6d texts', self.text_count)
1739
2387
        self._cleanup_spare_files_after_format4()
1740
 
        self.branch.control_files.put_utf8('branch-format', BzrDirFormat5().get_format_string())
 
2388
        self.branch._transport.put_bytes(
 
2389
            'branch-format',
 
2390
            BzrDirFormat5().get_format_string(),
 
2391
            mode=self.bzrdir._get_file_mode())
1741
2392
 
1742
2393
    def _cleanup_spare_files_after_format4(self):
1743
2394
        # FIXME working tree upgrade foo.
1752
2403
 
1753
2404
    def _convert_working_inv(self):
1754
2405
        inv = xml4.serializer_v4.read_inventory(
1755
 
                    self.branch.control_files.get('inventory'))
1756
 
        new_inv_xml = xml5.serializer_v5.write_inventory_to_string(inv)
1757
 
        # FIXME inventory is a working tree change.
1758
 
        self.branch.control_files.put('inventory', StringIO(new_inv_xml))
 
2406
                self.branch._transport.get('inventory'))
 
2407
        new_inv_xml = xml5.serializer_v5.write_inventory_to_string(inv, working=True)
 
2408
        self.branch._transport.put_bytes('inventory', new_inv_xml,
 
2409
            mode=self.bzrdir._get_file_mode())
1759
2410
 
1760
2411
    def _write_all_weaves(self):
1761
2412
        controlweaves = WeaveStore(self.bzrdir.transport, prefixed=False)
1781
2432
        self.bzrdir.transport.mkdir('revision-store')
1782
2433
        revision_transport = self.bzrdir.transport.clone('revision-store')
1783
2434
        # TODO permissions
1784
 
        _revision_store = TextRevisionStore(TextStore(revision_transport,
1785
 
                                                      prefixed=False,
1786
 
                                                      compressed=True))
 
2435
        from bzrlib.xml5 import serializer_v5
 
2436
        from bzrlib.repofmt.weaverepo import RevisionTextStore
 
2437
        revision_store = RevisionTextStore(revision_transport,
 
2438
            serializer_v5, False, versionedfile.PrefixMapper(),
 
2439
            lambda:True, lambda:True)
1787
2440
        try:
1788
 
            transaction = WriteTransaction()
1789
2441
            for i, rev_id in enumerate(self.converted_revs):
1790
2442
                self.pb.update('write revision', i, len(self.converted_revs))
1791
 
                _revision_store.add_revision(self.revisions[rev_id], transaction)
 
2443
                text = serializer_v5.write_revision_to_string(
 
2444
                    self.revisions[rev_id])
 
2445
                key = (rev_id,)
 
2446
                revision_store.add_lines(key, None, osutils.split_lines(text))
1792
2447
        finally:
1793
2448
            self.pb.clear()
1794
 
            
 
2449
 
1795
2450
    def _load_one_rev(self, rev_id):
1796
2451
        """Load a revision object into memory.
1797
2452
 
1807
2462
                         rev_id)
1808
2463
            self.absent_revisions.add(rev_id)
1809
2464
        else:
1810
 
            rev = self.branch.repository._revision_store.get_revision(rev_id,
1811
 
                self.branch.repository.get_transaction())
 
2465
            rev = self.branch.repository.get_revision(rev_id)
1812
2466
            for parent_id in rev.parent_ids:
1813
2467
                self.known_revisions.add(parent_id)
1814
2468
                self.to_read.append(parent_id)
1815
2469
            self.revisions[rev_id] = rev
1816
2470
 
1817
2471
    def _load_old_inventory(self, rev_id):
1818
 
        assert rev_id not in self.converted_revs
1819
2472
        old_inv_xml = self.branch.repository.inventory_store.get(rev_id).read()
1820
2473
        inv = xml4.serializer_v4.read_inventory_from_string(old_inv_xml)
1821
2474
        inv.revision_id = rev_id
1822
2475
        rev = self.revisions[rev_id]
1823
 
        if rev.inventory_sha1:
1824
 
            assert rev.inventory_sha1 == sha_string(old_inv_xml), \
1825
 
                'inventory sha mismatch for {%s}' % rev_id
1826
2476
        return inv
1827
2477
 
1828
2478
    def _load_updated_inventory(self, rev_id):
1829
 
        assert rev_id in self.converted_revs
1830
2479
        inv_xml = self.inv_weave.get_text(rev_id)
1831
 
        inv = xml5.serializer_v5.read_inventory_from_string(inv_xml)
 
2480
        inv = xml5.serializer_v5.read_inventory_from_string(inv_xml, rev_id)
1832
2481
        return inv
1833
2482
 
1834
2483
    def _convert_one_rev(self, rev_id):
1838
2487
        present_parents = [p for p in rev.parent_ids
1839
2488
                           if p not in self.absent_revisions]
1840
2489
        self._convert_revision_contents(rev, inv, present_parents)
1841
 
        self._store_new_weave(rev, inv, present_parents)
 
2490
        self._store_new_inv(rev, inv, present_parents)
1842
2491
        self.converted_revs.add(rev_id)
1843
2492
 
1844
 
    def _store_new_weave(self, rev, inv, present_parents):
1845
 
        # the XML is now updated with text versions
1846
 
        if __debug__:
1847
 
            entries = inv.iter_entries()
1848
 
            entries.next()
1849
 
            for path, ie in entries:
1850
 
                assert getattr(ie, 'revision', None) is not None, \
1851
 
                    'no revision on {%s} in {%s}' % \
1852
 
                    (file_id, rev.revision_id)
 
2493
    def _store_new_inv(self, rev, inv, present_parents):
1853
2494
        new_inv_xml = xml5.serializer_v5.write_inventory_to_string(inv)
1854
2495
        new_inv_sha1 = sha_string(new_inv_xml)
1855
 
        self.inv_weave.add_lines(rev.revision_id, 
 
2496
        self.inv_weave.add_lines(rev.revision_id,
1856
2497
                                 present_parents,
1857
2498
                                 new_inv_xml.splitlines(True))
1858
2499
        rev.inventory_sha1 = new_inv_sha1
1883
2524
            w = Weave(file_id)
1884
2525
            self.text_weaves[file_id] = w
1885
2526
        text_changed = False
1886
 
        previous_entries = ie.find_previous_heads(parent_invs,
1887
 
                                                  None,
1888
 
                                                  None,
1889
 
                                                  entry_vf=w)
1890
 
        for old_revision in previous_entries:
1891
 
                # if this fails, its a ghost ?
1892
 
                assert old_revision in self.converted_revs, \
1893
 
                    "Revision {%s} not in converted_revs" % old_revision
 
2527
        parent_candiate_entries = ie.parent_candidates(parent_invs)
 
2528
        heads = graph.Graph(self).heads(parent_candiate_entries.keys())
 
2529
        # XXX: Note that this is unordered - and this is tolerable because
 
2530
        # the previous code was also unordered.
 
2531
        previous_entries = dict((head, parent_candiate_entries[head]) for head
 
2532
            in heads)
1894
2533
        self.snapshot_ie(previous_entries, ie, w, rev_id)
1895
2534
        del ie.text_id
1896
 
        assert getattr(ie, 'revision', None) is not None
 
2535
 
 
2536
    def get_parent_map(self, revision_ids):
 
2537
        """See graph._StackedParentsProvider.get_parent_map"""
 
2538
        return dict((revision_id, self.revisions[revision_id])
 
2539
                    for revision_id in revision_ids
 
2540
                     if revision_id in self.revisions)
1897
2541
 
1898
2542
    def snapshot_ie(self, previous_revisions, ie, w, rev_id):
1899
2543
        # TODO: convert this logic, which is ~= snapshot to
1900
2544
        # a call to:. This needs the path figured out. rather than a work_tree
1901
2545
        # a v4 revision_tree can be given, or something that looks enough like
1902
2546
        # one to give the file content to the entry if it needs it.
1903
 
        # and we need something that looks like a weave store for snapshot to 
 
2547
        # and we need something that looks like a weave store for snapshot to
1904
2548
        # save against.
1905
2549
        #ie.snapshot(rev, PATH, previous_revisions, REVISION_TREE, InMemoryWeaveStore(self.text_weaves))
1906
2550
        if len(previous_revisions) == 1:
1909
2553
                ie.revision = previous_ie.revision
1910
2554
                return
1911
2555
        if ie.has_text():
1912
 
            text = self.branch.repository.text_store.get(ie.text_id)
 
2556
            text = self.branch.repository._text_store.get(ie.text_id)
1913
2557
            file_lines = text.readlines()
1914
 
            assert sha_strings(file_lines) == ie.text_sha1
1915
 
            assert sum(map(len, file_lines)) == ie.text_size
1916
2558
            w.add_lines(rev_id, previous_revisions, file_lines)
1917
2559
            self.text_count += 1
1918
2560
        else:
1965
2607
                if (filename.endswith(".weave") or
1966
2608
                    filename.endswith(".gz") or
1967
2609
                    filename.endswith(".sig")):
1968
 
                    file_id = os.path.splitext(filename)[0]
 
2610
                    file_id, suffix = os.path.splitext(filename)
1969
2611
                else:
1970
2612
                    file_id = filename
1971
 
                prefix_dir = store.hash_prefix(file_id)
 
2613
                    suffix = ''
 
2614
                new_name = store._mapper.map((file_id,)) + suffix
1972
2615
                # FIXME keep track of the dirs made RBC 20060121
1973
2616
                try:
1974
 
                    store_transport.move(filename, prefix_dir + '/' + filename)
 
2617
                    store_transport.move(filename, new_name)
1975
2618
                except errors.NoSuchFile: # catches missing dirs strangely enough
1976
 
                    store_transport.mkdir(prefix_dir)
1977
 
                    store_transport.move(filename, prefix_dir + '/' + filename)
1978
 
        self.bzrdir._control_files.put_utf8('branch-format', BzrDirFormat6().get_format_string())
 
2619
                    store_transport.mkdir(osutils.dirname(new_name))
 
2620
                    store_transport.move(filename, new_name)
 
2621
        self.bzrdir.transport.put_bytes(
 
2622
            'branch-format',
 
2623
            BzrDirFormat6().get_format_string(),
 
2624
            mode=self.bzrdir._get_file_mode())
1979
2625
 
1980
2626
 
1981
2627
class ConvertBzrDir6ToMeta(Converter):
1990
2636
        self.count = 0
1991
2637
        self.total = 20 # the steps we know about
1992
2638
        self.garbage_inventories = []
 
2639
        self.dir_mode = self.bzrdir._get_dir_mode()
 
2640
        self.file_mode = self.bzrdir._get_file_mode()
1993
2641
 
1994
2642
        self.pb.note('starting upgrade from format 6 to metadir')
1995
 
        self.bzrdir._control_files.put_utf8('branch-format', "Converting to format 6")
 
2643
        self.bzrdir.transport.put_bytes(
 
2644
                'branch-format',
 
2645
                "Converting to format 6",
 
2646
                mode=self.file_mode)
1996
2647
        # its faster to move specific files around than to open and use the apis...
1997
2648
        # first off, nuke ancestry.weave, it was never used.
1998
2649
        try:
2008
2659
            if name.startswith('basis-inventory.'):
2009
2660
                self.garbage_inventories.append(name)
2010
2661
        # create new directories for repository, working tree and branch
2011
 
        self.dir_mode = self.bzrdir._control_files._dir_mode
2012
 
        self.file_mode = self.bzrdir._control_files._file_mode
2013
2662
        repository_names = [('inventory.weave', True),
2014
2663
                            ('revision-store', True),
2015
2664
                            ('weaves', True)]
2017
2666
        self.bzrdir.transport.mkdir('repository', mode=self.dir_mode)
2018
2667
        self.make_lock('repository')
2019
2668
        # we hard code the formats here because we are converting into
2020
 
        # the meta format. The meta format upgrader can take this to a 
 
2669
        # the meta format. The meta format upgrader can take this to a
2021
2670
        # future format within each component.
2022
2671
        self.put_format('repository', RepositoryFormat7())
2023
2672
        for entry in repository_names:
2063
2712
            for entry in checkout_files:
2064
2713
                self.move_entry('checkout', entry)
2065
2714
            if last_revision is not None:
2066
 
                self.bzrdir._control_files.put_utf8(
 
2715
                self.bzrdir.transport.put_bytes(
2067
2716
                    'checkout/last-revision', last_revision)
2068
 
        self.bzrdir._control_files.put_utf8(
2069
 
            'branch-format', BzrDirMetaFormat1().get_format_string())
 
2717
        self.bzrdir.transport.put_bytes(
 
2718
            'branch-format',
 
2719
            BzrDirMetaFormat1().get_format_string(),
 
2720
            mode=self.file_mode)
2070
2721
        return BzrDir.open(self.bzrdir.root_transport.base)
2071
2722
 
2072
2723
    def make_lock(self, name):
2090
2741
                raise
2091
2742
 
2092
2743
    def put_format(self, dirname, format):
2093
 
        self.bzrdir._control_files.put_utf8('%s/format' % dirname, format.get_format_string())
 
2744
        self.bzrdir.transport.put_bytes('%s/format' % dirname,
 
2745
            format.get_format_string(),
 
2746
            self.file_mode)
2094
2747
 
2095
2748
 
2096
2749
class ConvertMetaToMeta(Converter):
2126
2779
            pass
2127
2780
        else:
2128
2781
            # TODO: conversions of Branch and Tree should be done by
2129
 
            # InterXFormat lookups
 
2782
            # InterXFormat lookups/some sort of registry.
2130
2783
            # Avoid circular imports
2131
2784
            from bzrlib import branch as _mod_branch
2132
 
            if (branch._format.__class__ is _mod_branch.BzrBranchFormat5 and
2133
 
                self.target_format.get_branch_format().__class__ is
2134
 
                _mod_branch.BzrBranchFormat6):
2135
 
                branch_converter = _mod_branch.Converter5to6()
 
2785
            old = branch._format.__class__
 
2786
            new = self.target_format.get_branch_format().__class__
 
2787
            while old != new:
 
2788
                if (old == _mod_branch.BzrBranchFormat5 and
 
2789
                    new in (_mod_branch.BzrBranchFormat6,
 
2790
                        _mod_branch.BzrBranchFormat7)):
 
2791
                    branch_converter = _mod_branch.Converter5to6()
 
2792
                elif (old == _mod_branch.BzrBranchFormat6 and
 
2793
                    new == _mod_branch.BzrBranchFormat7):
 
2794
                    branch_converter = _mod_branch.Converter6to7()
 
2795
                else:
 
2796
                    raise errors.BadConversionTarget("No converter", new)
2136
2797
                branch_converter.convert(branch)
 
2798
                branch = self.bzrdir.open_branch()
 
2799
                old = branch._format.__class__
2137
2800
        try:
2138
2801
            tree = self.bzrdir.open_workingtree(recommend_upgrade=False)
2139
2802
        except (errors.NoWorkingTree, errors.NotLocalUrl):
2142
2805
            # TODO: conversions of Branch and Tree should be done by
2143
2806
            # InterXFormat lookups
2144
2807
            if (isinstance(tree, workingtree.WorkingTree3) and
2145
 
                not isinstance(tree, workingtree_4.WorkingTree4) and
 
2808
                not isinstance(tree, workingtree_4.DirStateWorkingTree) and
2146
2809
                isinstance(self.target_format.workingtree_format,
2147
 
                    workingtree_4.WorkingTreeFormat4)):
 
2810
                    workingtree_4.DirStateWorkingTreeFormat)):
2148
2811
                workingtree_4.Converter3to4().convert(tree)
 
2812
            if (isinstance(tree, workingtree_4.DirStateWorkingTree) and
 
2813
                not isinstance(tree, workingtree_4.WorkingTree5) and
 
2814
                isinstance(self.target_format.workingtree_format,
 
2815
                    workingtree_4.WorkingTreeFormat5)):
 
2816
                workingtree_4.Converter4to5().convert(tree)
 
2817
            if (isinstance(tree, workingtree_4.DirStateWorkingTree) and
 
2818
                not isinstance(tree, workingtree_4.WorkingTree6) and
 
2819
                isinstance(self.target_format.workingtree_format,
 
2820
                    workingtree_4.WorkingTreeFormat6)):
 
2821
                workingtree_4.Converter4or5to6().convert(tree)
2149
2822
        return to_convert
2150
2823
 
2151
2824
 
 
2825
# This is not in remote.py because it's small, and needs to be registered.
 
2826
# Putting it in remote.py creates a circular import problem.
 
2827
# we can make it a lazy object if the control formats is turned into something
 
2828
# like a registry.
 
2829
class RemoteBzrDirFormat(BzrDirMetaFormat1):
 
2830
    """Format representing bzrdirs accessed via a smart server"""
 
2831
 
 
2832
    def __init__(self):
 
2833
        BzrDirMetaFormat1.__init__(self)
 
2834
        self._network_name = None
 
2835
 
 
2836
    def get_format_description(self):
 
2837
        return 'bzr remote bzrdir'
 
2838
 
 
2839
    def get_format_string(self):
 
2840
        raise NotImplementedError(self.get_format_string)
 
2841
 
 
2842
    def network_name(self):
 
2843
        if self._network_name:
 
2844
            return self._network_name
 
2845
        else:
 
2846
            raise AssertionError("No network name set.")
 
2847
 
 
2848
    @classmethod
 
2849
    def probe_transport(klass, transport):
 
2850
        """Return a RemoteBzrDirFormat object if it looks possible."""
 
2851
        try:
 
2852
            medium = transport.get_smart_medium()
 
2853
        except (NotImplementedError, AttributeError,
 
2854
                errors.TransportNotPossible, errors.NoSmartMedium,
 
2855
                errors.SmartProtocolError):
 
2856
            # no smart server, so not a branch for this format type.
 
2857
            raise errors.NotBranchError(path=transport.base)
 
2858
        else:
 
2859
            # Decline to open it if the server doesn't support our required
 
2860
            # version (3) so that the VFS-based transport will do it.
 
2861
            if medium.should_probe():
 
2862
                try:
 
2863
                    server_version = medium.protocol_version()
 
2864
                except errors.SmartProtocolError:
 
2865
                    # Apparently there's no usable smart server there, even though
 
2866
                    # the medium supports the smart protocol.
 
2867
                    raise errors.NotBranchError(path=transport.base)
 
2868
                if server_version != '2':
 
2869
                    raise errors.NotBranchError(path=transport.base)
 
2870
            return klass()
 
2871
 
 
2872
    def initialize_on_transport(self, transport):
 
2873
        try:
 
2874
            # hand off the request to the smart server
 
2875
            client_medium = transport.get_smart_medium()
 
2876
        except errors.NoSmartMedium:
 
2877
            # TODO: lookup the local format from a server hint.
 
2878
            local_dir_format = BzrDirMetaFormat1()
 
2879
            return local_dir_format.initialize_on_transport(transport)
 
2880
        client = _SmartClient(client_medium)
 
2881
        path = client.remote_path_from_transport(transport)
 
2882
        response = client.call('BzrDirFormat.initialize', path)
 
2883
        if response[0] != 'ok':
 
2884
            raise errors.SmartProtocolError('unexpected response code %s' % (response,))
 
2885
        format = RemoteBzrDirFormat()
 
2886
        self._supply_sub_formats_to(format)
 
2887
        return remote.RemoteBzrDir(transport, format)
 
2888
 
 
2889
    def _open(self, transport):
 
2890
        return remote.RemoteBzrDir(transport, self)
 
2891
 
 
2892
    def __eq__(self, other):
 
2893
        if not isinstance(other, RemoteBzrDirFormat):
 
2894
            return False
 
2895
        return self.get_format_description() == other.get_format_description()
 
2896
 
 
2897
    def __return_repository_format(self):
 
2898
        # Always return a RemoteRepositoryFormat object, but if a specific bzr
 
2899
        # repository format has been asked for, tell the RemoteRepositoryFormat
 
2900
        # that it should use that for init() etc.
 
2901
        result = remote.RemoteRepositoryFormat()
 
2902
        custom_format = getattr(self, '_repository_format', None)
 
2903
        if custom_format:
 
2904
            if isinstance(custom_format, remote.RemoteRepositoryFormat):
 
2905
                return custom_format
 
2906
            else:
 
2907
                # We will use the custom format to create repositories over the
 
2908
                # wire; expose its details like rich_root_data for code to
 
2909
                # query
 
2910
                result._custom_format = custom_format
 
2911
        return result
 
2912
 
 
2913
    def get_branch_format(self):
 
2914
        result = BzrDirMetaFormat1.get_branch_format(self)
 
2915
        if not isinstance(result, remote.RemoteBranchFormat):
 
2916
            new_result = remote.RemoteBranchFormat()
 
2917
            new_result._custom_format = result
 
2918
            # cache the result
 
2919
            self.set_branch_format(new_result)
 
2920
            result = new_result
 
2921
        return result
 
2922
 
 
2923
    repository_format = property(__return_repository_format,
 
2924
        BzrDirMetaFormat1._set_repository_format) #.im_func)
 
2925
 
 
2926
 
 
2927
BzrDirFormat.register_control_server_format(RemoteBzrDirFormat)
 
2928
 
 
2929
 
2152
2930
class BzrDirFormatInfo(object):
2153
2931
 
2154
 
    def __init__(self, native, deprecated, hidden):
 
2932
    def __init__(self, native, deprecated, hidden, experimental):
2155
2933
        self.deprecated = deprecated
2156
2934
        self.native = native
2157
2935
        self.hidden = hidden
 
2936
        self.experimental = experimental
2158
2937
 
2159
2938
 
2160
2939
class BzrDirFormatRegistry(registry.Registry):
2161
2940
    """Registry of user-selectable BzrDir subformats.
2162
 
    
 
2941
 
2163
2942
    Differs from BzrDirFormat._control_formats in that it provides sub-formats,
2164
2943
    e.g. BzrDirMeta1 with weave repository.  Also, it's more user-oriented.
2165
2944
    """
2166
2945
 
 
2946
    def __init__(self):
 
2947
        """Create a BzrDirFormatRegistry."""
 
2948
        self._aliases = set()
 
2949
        self._registration_order = list()
 
2950
        super(BzrDirFormatRegistry, self).__init__()
 
2951
 
 
2952
    def aliases(self):
 
2953
        """Return a set of the format names which are aliases."""
 
2954
        return frozenset(self._aliases)
 
2955
 
2167
2956
    def register_metadir(self, key,
2168
2957
             repository_format, help, native=True, deprecated=False,
2169
2958
             branch_format=None,
2170
2959
             tree_format=None,
2171
 
             hidden=False):
 
2960
             hidden=False,
 
2961
             experimental=False,
 
2962
             alias=False):
2172
2963
        """Register a metadir subformat.
2173
2964
 
2174
2965
        These all use a BzrDirMetaFormat1 bzrdir, but can be parameterized
2175
 
        by the Repository format.
 
2966
        by the Repository/Branch/WorkingTreeformats.
2176
2967
 
2177
2968
        :param repository_format: The fully-qualified repository format class
2178
2969
            name as a string.
2206
2997
            if repository_format is not None:
2207
2998
                bd.repository_format = _load(repository_format)
2208
2999
            return bd
2209
 
        self.register(key, helper, help, native, deprecated, hidden)
 
3000
        self.register(key, helper, help, native, deprecated, hidden,
 
3001
            experimental, alias)
2210
3002
 
2211
3003
    def register(self, key, factory, help, native=True, deprecated=False,
2212
 
                 hidden=False):
 
3004
                 hidden=False, experimental=False, alias=False):
2213
3005
        """Register a BzrDirFormat factory.
2214
 
        
 
3006
 
2215
3007
        The factory must be a callable that takes one parameter: the key.
2216
3008
        It must produce an instance of the BzrDirFormat when called.
2217
3009
 
2218
3010
        This function mainly exists to prevent the info object from being
2219
3011
        supplied directly.
2220
3012
        """
2221
 
        registry.Registry.register(self, key, factory, help, 
2222
 
            BzrDirFormatInfo(native, deprecated, hidden))
 
3013
        registry.Registry.register(self, key, factory, help,
 
3014
            BzrDirFormatInfo(native, deprecated, hidden, experimental))
 
3015
        if alias:
 
3016
            self._aliases.add(key)
 
3017
        self._registration_order.append(key)
2223
3018
 
2224
3019
    def register_lazy(self, key, module_name, member_name, help, native=True,
2225
 
                      deprecated=False, hidden=False):
2226
 
        registry.Registry.register_lazy(self, key, module_name, member_name, 
2227
 
            help, BzrDirFormatInfo(native, deprecated, hidden))
 
3020
        deprecated=False, hidden=False, experimental=False, alias=False):
 
3021
        registry.Registry.register_lazy(self, key, module_name, member_name,
 
3022
            help, BzrDirFormatInfo(native, deprecated, hidden, experimental))
 
3023
        if alias:
 
3024
            self._aliases.add(key)
 
3025
        self._registration_order.append(key)
2228
3026
 
2229
3027
    def set_default(self, key):
2230
3028
        """Set the 'default' key to be a clone of the supplied key.
2231
 
        
 
3029
 
2232
3030
        This method must be called once and only once.
2233
3031
        """
2234
 
        registry.Registry.register(self, 'default', self.get(key), 
 
3032
        registry.Registry.register(self, 'default', self.get(key),
2235
3033
            self.get_help(key), info=self.get_info(key))
 
3034
        self._aliases.add('default')
2236
3035
 
2237
3036
    def set_default_repository(self, key):
2238
3037
        """Set the FormatRegistry default and Repository default.
2239
 
        
 
3038
 
2240
3039
        This is a transitional method while Repository.set_default_format
2241
3040
        is deprecated.
2242
3041
        """
2244
3043
            self.remove('default')
2245
3044
        self.set_default(key)
2246
3045
        format = self.get('default')()
2247
 
        assert isinstance(format, BzrDirMetaFormat1)
2248
3046
 
2249
3047
    def make_bzrdir(self, key):
2250
3048
        return self.get(key)()
2251
3049
 
2252
3050
    def help_topic(self, topic):
2253
 
        output = textwrap.dedent("""\
2254
 
            Bazaar directory formats
2255
 
            ------------------------
2256
 
 
2257
 
            These formats can be used for creating branches, working trees, and
2258
 
            repositories.
2259
 
 
2260
 
            """)
 
3051
        output = ""
 
3052
        default_realkey = None
2261
3053
        default_help = self.get_help('default')
2262
3054
        help_pairs = []
2263
 
        for key in self.keys():
 
3055
        for key in self._registration_order:
2264
3056
            if key == 'default':
2265
3057
                continue
2266
3058
            help = self.get_help(key)
2272
3064
        def wrapped(key, help, info):
2273
3065
            if info.native:
2274
3066
                help = '(native) ' + help
2275
 
            return '  %s:\n%s\n\n' % (key, 
2276
 
                    textwrap.fill(help, initial_indent='    ', 
 
3067
            return ':%s:\n%s\n\n' % (key,
 
3068
                    textwrap.fill(help, initial_indent='    ',
2277
3069
                    subsequent_indent='    '))
2278
 
        output += wrapped('%s/default' % default_realkey, default_help,
2279
 
                          self.get_info('default'))
 
3070
        if default_realkey is not None:
 
3071
            output += wrapped(default_realkey, '(default) %s' % default_help,
 
3072
                              self.get_info('default'))
2280
3073
        deprecated_pairs = []
 
3074
        experimental_pairs = []
2281
3075
        for key, help in help_pairs:
2282
3076
            info = self.get_info(key)
2283
3077
            if info.hidden:
2284
3078
                continue
2285
3079
            elif info.deprecated:
2286
3080
                deprecated_pairs.append((key, help))
 
3081
            elif info.experimental:
 
3082
                experimental_pairs.append((key, help))
2287
3083
            else:
2288
3084
                output += wrapped(key, help, info)
 
3085
        output += "\nSee ``bzr help formats`` for more about storage formats."
 
3086
        other_output = ""
 
3087
        if len(experimental_pairs) > 0:
 
3088
            other_output += "Experimental formats are shown below.\n\n"
 
3089
            for key, help in experimental_pairs:
 
3090
                info = self.get_info(key)
 
3091
                other_output += wrapped(key, help, info)
 
3092
        else:
 
3093
            other_output += \
 
3094
                "No experimental formats are available.\n\n"
2289
3095
        if len(deprecated_pairs) > 0:
2290
 
            output += "Deprecated formats\n------------------\n\n"
 
3096
            other_output += "\nDeprecated formats are shown below.\n\n"
2291
3097
            for key, help in deprecated_pairs:
2292
3098
                info = self.get_info(key)
2293
 
                output += wrapped(key, help, info)
2294
 
 
2295
 
        return output
2296
 
 
2297
 
 
 
3099
                other_output += wrapped(key, help, info)
 
3100
        else:
 
3101
            other_output += \
 
3102
                "\nNo deprecated formats are available.\n\n"
 
3103
        other_output += \
 
3104
            "\nSee ``bzr help formats`` for more about storage formats."
 
3105
 
 
3106
        if topic == 'other-formats':
 
3107
            return other_output
 
3108
        else:
 
3109
            return output
 
3110
 
 
3111
 
 
3112
class RepositoryAcquisitionPolicy(object):
 
3113
    """Abstract base class for repository acquisition policies.
 
3114
 
 
3115
    A repository acquisition policy decides how a BzrDir acquires a repository
 
3116
    for a branch that is being created.  The most basic policy decision is
 
3117
    whether to create a new repository or use an existing one.
 
3118
    """
 
3119
    def __init__(self, stack_on, stack_on_pwd, require_stacking):
 
3120
        """Constructor.
 
3121
 
 
3122
        :param stack_on: A location to stack on
 
3123
        :param stack_on_pwd: If stack_on is relative, the location it is
 
3124
            relative to.
 
3125
        :param require_stacking: If True, it is a failure to not stack.
 
3126
        """
 
3127
        self._stack_on = stack_on
 
3128
        self._stack_on_pwd = stack_on_pwd
 
3129
        self._require_stacking = require_stacking
 
3130
 
 
3131
    def configure_branch(self, branch):
 
3132
        """Apply any configuration data from this policy to the branch.
 
3133
 
 
3134
        Default implementation sets repository stacking.
 
3135
        """
 
3136
        if self._stack_on is None:
 
3137
            return
 
3138
        if self._stack_on_pwd is None:
 
3139
            stack_on = self._stack_on
 
3140
        else:
 
3141
            try:
 
3142
                stack_on = urlutils.rebase_url(self._stack_on,
 
3143
                    self._stack_on_pwd,
 
3144
                    branch.bzrdir.root_transport.base)
 
3145
            except errors.InvalidRebaseURLs:
 
3146
                stack_on = self._get_full_stack_on()
 
3147
        try:
 
3148
            branch.set_stacked_on_url(stack_on)
 
3149
        except (errors.UnstackableBranchFormat,
 
3150
                errors.UnstackableRepositoryFormat):
 
3151
            if self._require_stacking:
 
3152
                raise
 
3153
 
 
3154
    def _get_full_stack_on(self):
 
3155
        """Get a fully-qualified URL for the stack_on location."""
 
3156
        if self._stack_on is None:
 
3157
            return None
 
3158
        if self._stack_on_pwd is None:
 
3159
            return self._stack_on
 
3160
        else:
 
3161
            return urlutils.join(self._stack_on_pwd, self._stack_on)
 
3162
 
 
3163
    def _add_fallback(self, repository, possible_transports=None):
 
3164
        """Add a fallback to the supplied repository, if stacking is set."""
 
3165
        stack_on = self._get_full_stack_on()
 
3166
        if stack_on is None:
 
3167
            return
 
3168
        stacked_dir = BzrDir.open(stack_on,
 
3169
                                  possible_transports=possible_transports)
 
3170
        try:
 
3171
            stacked_repo = stacked_dir.open_branch().repository
 
3172
        except errors.NotBranchError:
 
3173
            stacked_repo = stacked_dir.open_repository()
 
3174
        try:
 
3175
            repository.add_fallback_repository(stacked_repo)
 
3176
        except errors.UnstackableRepositoryFormat:
 
3177
            if self._require_stacking:
 
3178
                raise
 
3179
        else:
 
3180
            self._require_stacking = True
 
3181
 
 
3182
    def acquire_repository(self, make_working_trees=None, shared=False):
 
3183
        """Acquire a repository for this bzrdir.
 
3184
 
 
3185
        Implementations may create a new repository or use a pre-exising
 
3186
        repository.
 
3187
        :param make_working_trees: If creating a repository, set
 
3188
            make_working_trees to this value (if non-None)
 
3189
        :param shared: If creating a repository, make it shared if True
 
3190
        :return: A repository, is_new_flag (True if the repository was
 
3191
            created).
 
3192
        """
 
3193
        raise NotImplemented(RepositoryAcquisitionPolicy.acquire_repository)
 
3194
 
 
3195
 
 
3196
class CreateRepository(RepositoryAcquisitionPolicy):
 
3197
    """A policy of creating a new repository"""
 
3198
 
 
3199
    def __init__(self, bzrdir, stack_on=None, stack_on_pwd=None,
 
3200
                 require_stacking=False):
 
3201
        """
 
3202
        Constructor.
 
3203
        :param bzrdir: The bzrdir to create the repository on.
 
3204
        :param stack_on: A location to stack on
 
3205
        :param stack_on_pwd: If stack_on is relative, the location it is
 
3206
            relative to.
 
3207
        """
 
3208
        RepositoryAcquisitionPolicy.__init__(self, stack_on, stack_on_pwd,
 
3209
                                             require_stacking)
 
3210
        self._bzrdir = bzrdir
 
3211
 
 
3212
    def acquire_repository(self, make_working_trees=None, shared=False):
 
3213
        """Implementation of RepositoryAcquisitionPolicy.acquire_repository
 
3214
 
 
3215
        Creates the desired repository in the bzrdir we already have.
 
3216
        """
 
3217
        stack_on = self._get_full_stack_on()
 
3218
        if stack_on:
 
3219
            # Stacking is desired. requested by the target, but does the place it
 
3220
            # points at support stacking? If it doesn't then we should
 
3221
            # not implicitly upgrade. We check this here.
 
3222
            format = self._bzrdir._format
 
3223
            if not (format.repository_format.supports_external_lookups
 
3224
                and format.get_branch_format().supports_stacking()):
 
3225
                # May need to upgrade - but only do if the target also
 
3226
                # supports stacking. Note that this currently wastes
 
3227
                # network round trips to check - but we only do this
 
3228
                # when the source can't stack so it will fade away
 
3229
                # as people do upgrade.
 
3230
                try:
 
3231
                    target_dir = BzrDir.open(stack_on,
 
3232
                        possible_transports=[self._bzrdir.root_transport])
 
3233
                except errors.NotBranchError:
 
3234
                    # Nothing there, don't change formats
 
3235
                    pass
 
3236
                else:
 
3237
                    try:
 
3238
                        target_branch = target_dir.open_branch()
 
3239
                    except errors.NotBranchError:
 
3240
                        # No branch, don't change formats
 
3241
                        pass
 
3242
                    else:
 
3243
                        branch_format = target_branch._format
 
3244
                        repo_format = target_branch.repository._format
 
3245
                        if not (branch_format.supports_stacking()
 
3246
                            and repo_format.supports_external_lookups):
 
3247
                            # Doesn't stack itself, don't force an upgrade
 
3248
                            pass
 
3249
                        else:
 
3250
                            # Does support stacking, use its format.
 
3251
                            format.repository_format = repo_format
 
3252
                            format.set_branch_format(branch_format)
 
3253
                            note('Source format does not support stacking, '
 
3254
                                'using format: \'%s\'\n  %s\n',
 
3255
                                branch_format.get_format_description(),
 
3256
                                repo_format.get_format_description())
 
3257
            if not self._require_stacking:
 
3258
                # We have picked up automatic stacking somewhere.
 
3259
                note('Using default stacking branch %s at %s', self._stack_on,
 
3260
                    self._stack_on_pwd)
 
3261
        repository = self._bzrdir.create_repository(shared=shared)
 
3262
        self._add_fallback(repository,
 
3263
                           possible_transports=[self._bzrdir.transport])
 
3264
        if make_working_trees is not None:
 
3265
            repository.set_make_working_trees(make_working_trees)
 
3266
        return repository, True
 
3267
 
 
3268
 
 
3269
class UseExistingRepository(RepositoryAcquisitionPolicy):
 
3270
    """A policy of reusing an existing repository"""
 
3271
 
 
3272
    def __init__(self, repository, stack_on=None, stack_on_pwd=None,
 
3273
                 require_stacking=False):
 
3274
        """Constructor.
 
3275
 
 
3276
        :param repository: The repository to use.
 
3277
        :param stack_on: A location to stack on
 
3278
        :param stack_on_pwd: If stack_on is relative, the location it is
 
3279
            relative to.
 
3280
        """
 
3281
        RepositoryAcquisitionPolicy.__init__(self, stack_on, stack_on_pwd,
 
3282
                                             require_stacking)
 
3283
        self._repository = repository
 
3284
 
 
3285
    def acquire_repository(self, make_working_trees=None, shared=False):
 
3286
        """Implementation of RepositoryAcquisitionPolicy.acquire_repository
 
3287
 
 
3288
        Returns an existing repository to use.
 
3289
        """
 
3290
        self._add_fallback(self._repository,
 
3291
                       possible_transports=[self._repository.bzrdir.transport])
 
3292
        return self._repository, False
 
3293
 
 
3294
 
 
3295
# Please register new formats after old formats so that formats
 
3296
# appear in chronological order and format descriptions can build
 
3297
# on previous ones.
2298
3298
format_registry = BzrDirFormatRegistry()
 
3299
# The pre-0.8 formats have their repository format network name registered in
 
3300
# repository.py. MetaDir formats have their repository format network name
 
3301
# inferred from their disk format string.
2299
3302
format_registry.register('weave', BzrDirFormat6,
2300
3303
    'Pre-0.8 format.  Slower than knit and does not'
2301
3304
    ' support checkouts or shared repositories.',
2302
3305
    deprecated=True)
2303
 
format_registry.register_metadir('knit',
2304
 
    'bzrlib.repofmt.knitrepo.RepositoryFormatKnit1',
2305
 
    'Format using knits.  Recommended for interoperation with bzr <= 0.14.',
2306
 
    branch_format='bzrlib.branch.BzrBranchFormat5',
2307
 
    tree_format='bzrlib.workingtree.WorkingTreeFormat3')
2308
3306
format_registry.register_metadir('metaweave',
2309
3307
    'bzrlib.repofmt.weaverepo.RepositoryFormat7',
2310
3308
    'Transitional format in 0.8.  Slower than knit.',
2311
3309
    branch_format='bzrlib.branch.BzrBranchFormat5',
2312
3310
    tree_format='bzrlib.workingtree.WorkingTreeFormat3',
2313
3311
    deprecated=True)
 
3312
format_registry.register_metadir('knit',
 
3313
    'bzrlib.repofmt.knitrepo.RepositoryFormatKnit1',
 
3314
    'Format using knits.  Recommended for interoperation with bzr <= 0.14.',
 
3315
    branch_format='bzrlib.branch.BzrBranchFormat5',
 
3316
    tree_format='bzrlib.workingtree.WorkingTreeFormat3',
 
3317
    deprecated=True)
2314
3318
format_registry.register_metadir('dirstate',
2315
3319
    'bzrlib.repofmt.knitrepo.RepositoryFormatKnit1',
2316
3320
    help='New in 0.15: Fast local operations. Compatible with bzr 0.8 and '
2319
3323
    # this uses bzrlib.workingtree.WorkingTreeFormat4 because importing
2320
3324
    # directly from workingtree_4 triggers a circular import.
2321
3325
    tree_format='bzrlib.workingtree.WorkingTreeFormat4',
2322
 
    )
 
3326
    deprecated=True)
2323
3327
format_registry.register_metadir('dirstate-tags',
2324
3328
    'bzrlib.repofmt.knitrepo.RepositoryFormatKnit1',
2325
3329
    help='New in 0.15: Fast local operations and improved scaling for '
2327
3331
        ' Incompatible with bzr < 0.15.',
2328
3332
    branch_format='bzrlib.branch.BzrBranchFormat6',
2329
3333
    tree_format='bzrlib.workingtree.WorkingTreeFormat4',
2330
 
    )
 
3334
    deprecated=True)
 
3335
format_registry.register_metadir('rich-root',
 
3336
    'bzrlib.repofmt.knitrepo.RepositoryFormatKnit4',
 
3337
    help='New in 1.0.  Better handling of tree roots.  Incompatible with'
 
3338
        ' bzr < 1.0.',
 
3339
    branch_format='bzrlib.branch.BzrBranchFormat6',
 
3340
    tree_format='bzrlib.workingtree.WorkingTreeFormat4',
 
3341
    deprecated=True)
2331
3342
format_registry.register_metadir('dirstate-with-subtree',
2332
3343
    'bzrlib.repofmt.knitrepo.RepositoryFormatKnit3',
2333
3344
    help='New in 0.15: Fast local operations and improved scaling for '
2335
3346
        'bzr branches. Incompatible with bzr < 0.15.',
2336
3347
    branch_format='bzrlib.branch.BzrBranchFormat6',
2337
3348
    tree_format='bzrlib.workingtree.WorkingTreeFormat4',
2338
 
    hidden=True,
2339
 
    )
2340
 
format_registry.set_default('dirstate')
 
3349
    experimental=True,
 
3350
    hidden=True,
 
3351
    )
 
3352
format_registry.register_metadir('pack-0.92',
 
3353
    'bzrlib.repofmt.pack_repo.RepositoryFormatKnitPack1',
 
3354
    help='New in 0.92: Pack-based format with data compatible with '
 
3355
        'dirstate-tags format repositories. Interoperates with '
 
3356
        'bzr repositories before 0.92 but cannot be read by bzr < 0.92. '
 
3357
        'Previously called knitpack-experimental.  '
 
3358
        'For more information, see '
 
3359
        'http://doc.bazaar-vcs.org/latest/developers/packrepo.html.',
 
3360
    branch_format='bzrlib.branch.BzrBranchFormat6',
 
3361
    tree_format='bzrlib.workingtree.WorkingTreeFormat4',
 
3362
    )
 
3363
format_registry.register_metadir('pack-0.92-subtree',
 
3364
    'bzrlib.repofmt.pack_repo.RepositoryFormatKnitPack3',
 
3365
    help='New in 0.92: Pack-based format with data compatible with '
 
3366
        'dirstate-with-subtree format repositories. Interoperates with '
 
3367
        'bzr repositories before 0.92 but cannot be read by bzr < 0.92. '
 
3368
        'Previously called knitpack-experimental.  '
 
3369
        'For more information, see '
 
3370
        'http://doc.bazaar-vcs.org/latest/developers/packrepo.html.',
 
3371
    branch_format='bzrlib.branch.BzrBranchFormat6',
 
3372
    tree_format='bzrlib.workingtree.WorkingTreeFormat4',
 
3373
    hidden=True,
 
3374
    experimental=True,
 
3375
    )
 
3376
format_registry.register_metadir('rich-root-pack',
 
3377
    'bzrlib.repofmt.pack_repo.RepositoryFormatKnitPack4',
 
3378
    help='New in 1.0: A variant of pack-0.92 that supports rich-root data '
 
3379
         '(needed for bzr-svn and bzr-git).',
 
3380
    branch_format='bzrlib.branch.BzrBranchFormat6',
 
3381
    tree_format='bzrlib.workingtree.WorkingTreeFormat4',
 
3382
    )
 
3383
format_registry.register_metadir('1.6',
 
3384
    'bzrlib.repofmt.pack_repo.RepositoryFormatKnitPack5',
 
3385
    help='A format that allows a branch to indicate that there is another '
 
3386
         '(stacked) repository that should be used to access data that is '
 
3387
         'not present locally.',
 
3388
    branch_format='bzrlib.branch.BzrBranchFormat7',
 
3389
    tree_format='bzrlib.workingtree.WorkingTreeFormat4',
 
3390
    )
 
3391
format_registry.register_metadir('1.6.1-rich-root',
 
3392
    'bzrlib.repofmt.pack_repo.RepositoryFormatKnitPack5RichRoot',
 
3393
    help='A variant of 1.6 that supports rich-root data '
 
3394
         '(needed for bzr-svn and bzr-git).',
 
3395
    branch_format='bzrlib.branch.BzrBranchFormat7',
 
3396
    tree_format='bzrlib.workingtree.WorkingTreeFormat4',
 
3397
    )
 
3398
format_registry.register_metadir('1.9',
 
3399
    'bzrlib.repofmt.pack_repo.RepositoryFormatKnitPack6',
 
3400
    help='A repository format using B+tree indexes. These indexes '
 
3401
         'are smaller in size, have smarter caching and provide faster '
 
3402
         'performance for most operations.',
 
3403
    branch_format='bzrlib.branch.BzrBranchFormat7',
 
3404
    tree_format='bzrlib.workingtree.WorkingTreeFormat4',
 
3405
    )
 
3406
format_registry.register_metadir('1.9-rich-root',
 
3407
    'bzrlib.repofmt.pack_repo.RepositoryFormatKnitPack6RichRoot',
 
3408
    help='A variant of 1.9 that supports rich-root data '
 
3409
         '(needed for bzr-svn and bzr-git).',
 
3410
    branch_format='bzrlib.branch.BzrBranchFormat7',
 
3411
    tree_format='bzrlib.workingtree.WorkingTreeFormat4',
 
3412
    )
 
3413
format_registry.register_metadir('1.14',
 
3414
    'bzrlib.repofmt.pack_repo.RepositoryFormatKnitPack6',
 
3415
    help='A working-tree format that supports content filtering.',
 
3416
    branch_format='bzrlib.branch.BzrBranchFormat7',
 
3417
    tree_format='bzrlib.workingtree.WorkingTreeFormat5',
 
3418
    )
 
3419
format_registry.register_metadir('1.14-rich-root',
 
3420
    'bzrlib.repofmt.pack_repo.RepositoryFormatKnitPack6RichRoot',
 
3421
    help='A variant of 1.14 that supports rich-root data '
 
3422
         '(needed for bzr-svn and bzr-git).',
 
3423
    branch_format='bzrlib.branch.BzrBranchFormat7',
 
3424
    tree_format='bzrlib.workingtree.WorkingTreeFormat5',
 
3425
    )
 
3426
# The following un-numbered 'development' formats should always just be aliases.
 
3427
format_registry.register_metadir('development-rich-root',
 
3428
    'bzrlib.repofmt.groupcompress_repo.RepositoryFormatCHK1',
 
3429
    help='Current development format. Can convert data to and from pack-0.92 '
 
3430
        '(and anything compatible with pack-0.92) format repositories. '
 
3431
        'Repositories and branches in this format can only be read by bzr.dev. '
 
3432
        'Please read '
 
3433
        'http://doc.bazaar-vcs.org/latest/developers/development-repo.html '
 
3434
        'before use.',
 
3435
    branch_format='bzrlib.branch.BzrBranchFormat7',
 
3436
    tree_format='bzrlib.workingtree.WorkingTreeFormat6',
 
3437
    experimental=True,
 
3438
    alias=True,
 
3439
    )
 
3440
format_registry.register_metadir('development-subtree',
 
3441
    'bzrlib.repofmt.pack_repo.RepositoryFormatPackDevelopment2Subtree',
 
3442
    help='Current development format, subtree variant. Can convert data to and '
 
3443
        'from pack-0.92-subtree (and anything compatible with '
 
3444
        'pack-0.92-subtree) format repositories. Repositories and branches in '
 
3445
        'this format can only be read by bzr.dev. Please read '
 
3446
        'http://doc.bazaar-vcs.org/latest/developers/development-repo.html '
 
3447
        'before use.',
 
3448
    branch_format='bzrlib.branch.BzrBranchFormat7',
 
3449
    tree_format='bzrlib.workingtree.WorkingTreeFormat6',
 
3450
    experimental=True,
 
3451
    alias=False, # Restore to being an alias when an actual development subtree format is added
 
3452
                 # This current non-alias status is simply because we did not introduce a
 
3453
                 # chk based subtree format.
 
3454
    )
 
3455
 
 
3456
# And the development formats above will have aliased one of the following:
 
3457
format_registry.register_metadir('development6-rich-root',
 
3458
    'bzrlib.repofmt.groupcompress_repo.RepositoryFormatCHK1',
 
3459
    help='pack-1.9 with 255-way hashed CHK inv, group compress, rich roots '
 
3460
        'Please read '
 
3461
        'http://doc.bazaar-vcs.org/latest/developers/development-repo.html '
 
3462
        'before use.',
 
3463
    branch_format='bzrlib.branch.BzrBranchFormat7',
 
3464
    tree_format='bzrlib.workingtree.WorkingTreeFormat6',
 
3465
    hidden=True,
 
3466
    experimental=True,
 
3467
    )
 
3468
 
 
3469
# The following format should be an alias for the rich root equivalent 
 
3470
# of the default format
 
3471
format_registry.register_metadir('default-rich-root',
 
3472
    'bzrlib.repofmt.pack_repo.RepositoryFormatKnitPack4',
 
3473
    help='Default format, rich root variant. (needed for bzr-svn and bzr-git).',
 
3474
    branch_format='bzrlib.branch.BzrBranchFormat6',
 
3475
    tree_format='bzrlib.workingtree.WorkingTreeFormat4',
 
3476
    alias=True,
 
3477
    )
 
3478
# The current format that is made on 'bzr init'.
 
3479
format_registry.set_default('pack-0.92')