/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: Canonical.com Patch Queue Manager
  • Date: 2009-04-16 17:07:46 UTC
  • mfrom: (4282.2.4 fix_mapi_send)
  • Revision ID: pqm@pqm.ubuntu.com-20090416170746-92fj72e2i2qpkojj
(Neil Martinsen-Burrell) Fix 'bzr send' using MAPI.

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