~bzr-pqm/bzr/bzr.dev

« back to all changes in this revision

Viewing changes to bzrlib/bzrdir.py

  • Committer: Andrew Bennetts
  • Date: 2009-03-10 02:44:15 UTC
  • mto: This revision was merged to the branch mainline in revision 4103.
  • Revision ID: andrew.bennetts@canonical.com-20090310024415-3fl3ie61atq39c81
Fix 'trailing' whitespace (actually just a blank line in an indented docstring).

Show diffs side-by-side

added added

removed removed

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