/brz/remove-bazaar

To get this branch, use:
bzr branch http://gegoxaren.bato24.eu/bzr/brz/remove-bazaar

« back to all changes in this revision

Viewing changes to bzrlib/bzrdir.py

  • Committer: Aaron Bentley
  • Date: 2009-03-09 00:48:43 UTC
  • mto: This revision was merged to the branch mainline in revision 4095.
  • Revision ID: aaron@aaronbentley.com-20090309004843-twuto34yqkzez2u3
Remove now-redundant DummyProgress from Merger.__init__

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