/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: 2010-02-11 04:02:41 UTC
  • mfrom: (5017.2.2 tariff)
  • Revision ID: pqm@pqm.ubuntu.com-20100211040241-w6n021dz0uus341n
(mbp) add import-tariff tests

Show diffs side-by-side

added added

removed removed

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