/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: Robert Collins
  • Date: 2009-04-24 00:45:11 UTC
  • mto: This revision was merged to the branch mainline in revision 4304.
  • Revision ID: robertc@robertcollins.net-20090424004511-8oszlwmvehlqwrla
Start building up a BzrDir.initialize_ex verb for the smart server.

Show diffs side-by-side

added added

removed removed

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