~bzr-pqm/bzr/bzr.dev

« back to all changes in this revision

Viewing changes to bzrlib/bzrdir.py

merge bzr.dev

Show diffs side-by-side

added added

removed removed

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