~bzr-pqm/bzr/bzr.dev

« back to all changes in this revision

Viewing changes to bzrlib/bzrdir.py

  • Committer: John Arbash Meinel
  • Date: 2006-08-28 17:04:38 UTC
  • mto: This revision was merged to the branch mainline in revision 1965.
  • Revision ID: john@arbash-meinel.com-20060828170438-5da90625125dd4fc
Add a deprecation symbol for bzr-0.11

Show diffs side-by-side

added added

removed removed

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