/brz/remove-bazaar

To get this branch, use:
bzr branch http://gegoxaren.bato24.eu/bzr/brz/remove-bazaar
3416.2.1 by Martin Pool
Add BzrDir._get_file_mode and _get_dir_mode
1
# Copyright (C) 2005, 2006, 2007, 2008 Canonical Ltd
1887.1.1 by Adeodato Simó
Do not separate paragraphs in the copyright statement with blank lines,
2
#
1534.4.39 by Robert Collins
Basic BzrDir support.
3
# This program is free software; you can redistribute it and/or modify
4
# it under the terms of the GNU General Public License as published by
5
# the Free Software Foundation; either version 2 of the License, or
6
# (at your option) any later version.
1887.1.1 by Adeodato Simó
Do not separate paragraphs in the copyright statement with blank lines,
7
#
1534.4.39 by Robert Collins
Basic BzrDir support.
8
# This program is distributed in the hope that it will be useful,
9
# but WITHOUT ANY WARRANTY; without even the implied warranty of
10
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
11
# GNU General Public License for more details.
1887.1.1 by Adeodato Simó
Do not separate paragraphs in the copyright statement with blank lines,
12
#
1534.4.39 by Robert Collins
Basic BzrDir support.
13
# You should have received a copy of the GNU General Public License
14
# along with this program; if not, write to the Free Software
15
# Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
16
17
"""BzrDir logic. The BzrDir is the basic control directory used by bzr.
18
19
At format 7 this was split out into Branch, Repository and Checkout control
20
directories.
2830.1.1 by Ian Clatworthy
bzrdir.py code clean-ups
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.
1534.4.39 by Robert Collins
Basic BzrDir support.
26
"""
27
2830.1.1 by Ian Clatworthy
bzrdir.py code clean-ups
28
# TODO: Move old formats into a plugin to make this file smaller.
1910.7.17 by Andrew Bennetts
Various cosmetic changes.
29
1773.4.1 by Martin Pool
Add pyflakes makefile target; fix many warnings
30
from cStringIO import StringIO
1534.5.7 by Robert Collins
Start factoring out the upgrade policy logic.
31
import os
3023.1.1 by Alexander Belchenko
Mark .bzr directories as "hidden" on Windows (#71147)
32
import sys
1996.3.3 by John Arbash Meinel
Shave off another 40ms by demand loading branch and bzrdir
33
34
from bzrlib.lazy_import import lazy_import
35
lazy_import(globals(), """
1773.4.1 by Martin Pool
Add pyflakes makefile target; fix many warnings
36
from stat import S_ISDIR
2711.2.1 by Martin Pool
Deprecate BzrDir.create_repository
37
import textwrap
38
from warnings import warn
1534.4.39 by Robert Collins
Basic BzrDir support.
39
40
import bzrlib
1996.3.3 by John Arbash Meinel
Shave off another 40ms by demand loading branch and bzrdir
41
from bzrlib import (
3242.1.1 by Aaron Bentley
Implement BzrDir configuration
42
    config,
1996.3.3 by John Arbash Meinel
Shave off another 40ms by demand loading branch and bzrdir
43
    errors,
2776.1.5 by Robert Collins
Add reasonably comprehensive tests for path last modified and per file graph behaviour.
44
    graph,
1996.3.3 by John Arbash Meinel
Shave off another 40ms by demand loading branch and bzrdir
45
    lockable_files,
46
    lockdir,
3350.6.1 by Robert Collins
* New ``versionedfile.KeyMapper`` interface to abstract out the access to
47
    osutils,
2204.4.1 by Aaron Bentley
Add 'formats' help topic
48
    registry,
2018.5.25 by Andrew Bennetts
Make sure RemoteBzrDirFormat is always registered (John Arbash Meinel, Robert Collins, Andrew Bennetts).
49
    remote,
1996.3.12 by John Arbash Meinel
Change how 'revision' is imported to avoid problems later
50
    revision as _mod_revision,
2204.4.12 by Aaron Bentley
Deprecate bzrdir.BzrDirFormat.set_default_format
51
    symbol_versioning,
2323.6.4 by Martin Pool
BzrDir._check_supported now also takes care of recommending upgrades, which
52
    ui,
1996.3.3 by John Arbash Meinel
Shave off another 40ms by demand loading branch and bzrdir
53
    urlutils,
3350.6.4 by Robert Collins
First cut at pluralised VersionedFiles. Some rather massive API incompatabilities, primarily because of the difficulty of coherence among competing stores.
54
    versionedfile,
3023.1.2 by Alexander Belchenko
Martin's review.
55
    win32utils,
56
    workingtree,
57
    workingtree_4,
3586.1.8 by Ian Clatworthy
add workingtree_5 and initial upgrade code
58
    workingtree_5,
1996.3.6 by John Arbash Meinel
Find a few places that weren't importing their dependencies.
59
    xml4,
60
    xml5,
1996.3.3 by John Arbash Meinel
Shave off another 40ms by demand loading branch and bzrdir
61
    )
1534.5.7 by Robert Collins
Start factoring out the upgrade policy logic.
62
from bzrlib.osutils import (
1996.3.3 by John Arbash Meinel
Shave off another 40ms by demand loading branch and bzrdir
63
    sha_strings,
64
    sha_string,
65
    )
3015.3.39 by Daniel Watkins
Added classmethod bzrlib.bzrdir.BzrDir.open_containing_tree_branch_or_repository.
66
from bzrlib.repository import Repository
2018.5.159 by Andrew Bennetts
Rename SmartClient to _SmartClient.
67
from bzrlib.smart.client import _SmartClient
2432.3.1 by Andrew Bennetts
Try a version 1 hello probe to determine if we can use RemoteBzrDir on a particular transport, allowing smooth interoperation with older servers.
68
from bzrlib.smart import protocol
1563.2.25 by Robert Collins
Merge in upstream.
69
from bzrlib.store.versioned import WeaveStore
1563.2.34 by Robert Collins
Remove the commit and rollback transaction methods as misleading, and implement a WriteTransaction
70
from bzrlib.transactions import WriteTransaction
2164.2.21 by Vincent Ladeuil
Take bundles into account.
71
from bzrlib.transport import (
72
    do_catching_redirections,
73
    get_transport,
74
    )
1534.5.7 by Robert Collins
Start factoring out the upgrade policy logic.
75
from bzrlib.weave import Weave
1996.3.3 by John Arbash Meinel
Shave off another 40ms by demand loading branch and bzrdir
76
""")
77
2164.2.1 by v.ladeuil+lp at free
First rough http branch redirection implementation.
78
from bzrlib.trace import (
79
    mutter,
80
    note,
81
    )
1996.3.3 by John Arbash Meinel
Shave off another 40ms by demand loading branch and bzrdir
82
from bzrlib.transport.local import LocalTransport
2711.2.1 by Martin Pool
Deprecate BzrDir.create_repository
83
from bzrlib.symbol_versioning import (
84
    deprecated_function,
85
    deprecated_method,
86
    )
1534.4.39 by Robert Collins
Basic BzrDir support.
87
88
89
class BzrDir(object):
90
    """A .bzr control diretory.
91
    
92
    BzrDir instances let you create or open any of the things that can be
93
    found within .bzr - checkouts, branches and repositories.
94
    
3407.2.13 by Martin Pool
Remove indirection through control_files to get transports
95
    :ivar transport:
1534.4.40 by Robert Collins
Add RepositoryFormats and allow bzrdir.open or create _repository to be used.
96
        the transport which this bzr dir is rooted at (i.e. file:///.../.bzr/)
3407.2.13 by Martin Pool
Remove indirection through control_files to get transports
97
    :ivar root_transport:
2830.1.1 by Ian Clatworthy
bzrdir.py code clean-ups
98
        a transport connected to the directory this bzr was opened from
99
        (i.e. the parent directory holding the .bzr directory).
3416.2.1 by Martin Pool
Add BzrDir._get_file_mode and _get_dir_mode
100
101
    Everything in the bzrdir should have the same file permissions.
1534.4.39 by Robert Collins
Basic BzrDir support.
102
    """
103
1687.1.12 by Robert Collins
Hook in the full break-lock ui.
104
    def break_lock(self):
105
        """Invoke break_lock on the first object in the bzrdir.
106
107
        If there is a tree, the tree is opened and break_lock() called.
108
        Otherwise, branch is tried, and finally repository.
109
        """
1752.2.52 by Andrew Bennetts
Flesh out more Remote* methods needed to open and initialise remote branches/trees/repositories.
110
        # XXX: This seems more like a UI function than something that really
111
        # belongs in this class.
1687.1.12 by Robert Collins
Hook in the full break-lock ui.
112
        try:
113
            thing_to_unlock = self.open_workingtree()
114
        except (errors.NotLocalUrl, errors.NoWorkingTree):
115
            try:
116
                thing_to_unlock = self.open_branch()
117
            except errors.NotBranchError:
118
                try:
119
                    thing_to_unlock = self.open_repository()
120
                except errors.NoRepositoryPresent:
121
                    return
122
        thing_to_unlock.break_lock()
123
1534.5.16 by Robert Collins
Review feedback.
124
    def can_convert_format(self):
125
        """Return true if this bzrdir is one whose format we can convert from."""
1534.5.7 by Robert Collins
Start factoring out the upgrade policy logic.
126
        return True
127
1910.2.12 by Aaron Bentley
Implement knit repo format 2
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
1596.2.1 by Robert Collins
Fix BzrDir.open_containing of unsupported branches.
133
    @staticmethod
2323.6.4 by Martin Pool
BzrDir._check_supported now also takes care of recommending upgrades, which
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.
1534.4.44 by Robert Collins
Make a new BzrDir format that uses a versioned branch format in a branch/ subdirectory.
149
        """
2323.5.19 by Martin Pool
No upgrade recommendation on source when cloning
150
        # TODO: perhaps move this into a base Format class; it's not BzrDir
151
        # specific. mbp 20070323
1534.4.44 by Robert Collins
Make a new BzrDir format that uses a versioned branch format in a branch/ subdirectory.
152
        if not allow_unsupported and not format.is_supported():
1596.2.1 by Robert Collins
Fix BzrDir.open_containing of unsupported branches.
153
            # see open_downlevel to open legacy branches.
1740.5.6 by Martin Pool
Clean up many exception classes.
154
            raise errors.UnsupportedFormatError(format=format)
2323.6.4 by Martin Pool
BzrDir._check_supported now also takes care of recommending upgrades, which
155
        if recommend_upgrade \
156
            and getattr(format, 'upgrade_recommended', False):
157
            ui.ui_factory.recommend_upgrade(
158
                format.get_format_description(),
159
                basedir)
1534.4.44 by Robert Collins
Make a new BzrDir format that uses a versioned branch format in a branch/ subdirectory.
160
3242.3.24 by Aaron Bentley
Fix test failures
161
    def clone(self, url, revision_id=None, force_new_repo=False,
162
              preserve_stacking=False):
1534.4.50 by Robert Collins
Got the bzrdir api straightened out, plenty of refactoring to use it pending, but the api is up and running.
163
        """Clone this bzrdir and its contents to url verbatim.
164
3242.3.36 by Aaron Bentley
Updates from review comments
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
1534.4.50 by Robert Collins
Got the bzrdir api straightened out, plenty of refactoring to use it pending, but the api is up and running.
169
            itself to download less data.
3242.3.36 by Aaron Bentley
Updates from review comments
170
        :param force_new_repo: Do not use a shared repository for the target
1534.6.6 by Robert Collins
Move find_repository to bzrdir, its not quite ideal there but its simpler and until someone chooses to vary the search by branch type its completely sufficient.
171
                               even if one is available.
3242.3.36 by Aaron Bentley
Updates from review comments
172
        :param preserve_stacking: When cloning a stacked branch, stack the
173
            new branch on top of the other branch's stacked-on branch.
1534.4.50 by Robert Collins
Got the bzrdir api straightened out, plenty of refactoring to use it pending, but the api is up and running.
174
        """
2475.3.1 by John Arbash Meinel
Fix bug #75721. Update the BzrDir api to add clone_on_transport()
175
        return self.clone_on_transport(get_transport(url),
176
                                       revision_id=revision_id,
3242.3.24 by Aaron Bentley
Fix test failures
177
                                       force_new_repo=force_new_repo,
178
                                       preserve_stacking=preserve_stacking)
2475.3.1 by John Arbash Meinel
Fix bug #75721. Update the BzrDir api to add clone_on_transport()
179
180
    def clone_on_transport(self, transport, revision_id=None,
3242.3.22 by Aaron Bentley
Make clone stacking optional
181
                           force_new_repo=False, preserve_stacking=False):
2475.3.1 by John Arbash Meinel
Fix bug #75721. Update the BzrDir api to add clone_on_transport()
182
        """Clone this bzrdir and its contents to transport verbatim.
183
3242.3.36 by Aaron Bentley
Updates from review comments
184
        :param transport: The transport for the location to produce the clone
185
            at.  If the target directory does not exist, it will be created.
186
        :param revision_id: The tip revision-id to use for any branch or
187
            working tree.  If not None, then the clone operation may tune
2475.3.1 by John Arbash Meinel
Fix bug #75721. Update the BzrDir api to add clone_on_transport()
188
            itself to download less data.
3242.3.35 by Aaron Bentley
Cleanups and documentation
189
        :param force_new_repo: Do not use a shared repository for the target,
2475.3.1 by John Arbash Meinel
Fix bug #75721. Update the BzrDir api to add clone_on_transport()
190
                               even if one is available.
3242.3.22 by Aaron Bentley
Make clone stacking optional
191
        :param preserve_stacking: When cloning a stacked branch, stack the
192
            new branch on top of the other branch's stacked-on branch.
2475.3.1 by John Arbash Meinel
Fix bug #75721. Update the BzrDir api to add clone_on_transport()
193
        """
2475.3.3 by John Arbash Meinel
Change calls to try/mkdir('.')/except FileExists to ensure_base()
194
        transport.ensure_base()
3242.2.11 by Aaron Bentley
Ensure that correct repository format is used when cloning
195
        result = self.cloning_metadir().initialize_on_transport(transport)
3242.3.5 by Aaron Bentley
Implement stacking for clone_on_transport
196
        repository_policy = None
3242.3.30 by Aaron Bentley
Handle adding fallback repositories in acquire_repository
197
        stack_on = None
1534.4.50 by Robert Collins
Got the bzrdir api straightened out, plenty of refactoring to use it pending, but the api is up and running.
198
        try:
1534.6.6 by Robert Collins
Move find_repository to bzrdir, its not quite ideal there but its simpler and until someone chooses to vary the search by branch type its completely sufficient.
199
            local_repo = self.find_repository()
1534.4.50 by Robert Collins
Got the bzrdir api straightened out, plenty of refactoring to use it pending, but the api is up and running.
200
        except errors.NoRepositoryPresent:
1534.6.6 by Robert Collins
Move find_repository to bzrdir, its not quite ideal there but its simpler and until someone chooses to vary the search by branch type its completely sufficient.
201
            local_repo = None
3242.3.30 by Aaron Bentley
Handle adding fallback repositories in acquire_repository
202
        try:
203
            local_branch = self.open_branch()
204
        except errors.NotBranchError:
205
            local_branch = None
206
        else:
207
            # enable fallbacks when branch is not a branch reference
208
            if local_branch.repository.has_same_location(local_repo):
209
                local_repo = local_branch.repository
210
            if preserve_stacking:
211
                try:
3537.3.5 by Martin Pool
merge trunk including stacking policy
212
                    stack_on = local_branch.get_stacked_on_url()
3242.3.30 by Aaron Bentley
Handle adding fallback repositories in acquire_repository
213
                except (errors.UnstackableBranchFormat,
214
                        errors.UnstackableRepositoryFormat,
215
                        errors.NotStacked):
216
                    pass
217
1534.6.6 by Robert Collins
Move find_repository to bzrdir, its not quite ideal there but its simpler and until someone chooses to vary the search by branch type its completely sufficient.
218
        if local_repo:
219
            # may need to copy content in
3242.3.5 by Aaron Bentley
Implement stacking for clone_on_transport
220
            repository_policy = result.determine_repository_policy(
3567.3.1 by Jonathan Lange"
jml's one line fix
221
                force_new_repo, stack_on, self.root_transport.base)
3242.2.14 by Aaron Bentley
Update from review comments
222
            make_working_trees = local_repo.make_working_trees()
3242.2.10 by Aaron Bentley
Rename RepositoryPolicy.apply to acquire_repository
223
            result_repo = repository_policy.acquire_repository(
3242.2.14 by Aaron Bentley
Update from review comments
224
                make_working_trees, local_repo.is_shared())
3242.3.30 by Aaron Bentley
Handle adding fallback repositories in acquire_repository
225
            result_repo.fetch(local_repo, revision_id=revision_id)
226
        else:
227
            result_repo = None
1534.6.6 by Robert Collins
Move find_repository to bzrdir, its not quite ideal there but its simpler and until someone chooses to vary the search by branch type its completely sufficient.
228
        # 1 if there is a branch present
229
        #   make sure its content is available in the target repository
230
        #   clone it.
3242.3.37 by Aaron Bentley
Updates from reviews
231
        if local_branch is not None:
3242.3.5 by Aaron Bentley
Implement stacking for clone_on_transport
232
            result_branch = local_branch.clone(result, revision_id=revision_id)
3242.2.6 by Aaron Bentley
Don't try to use a repository policy, when none exists
233
            if repository_policy is not None:
234
                repository_policy.configure_branch(result_branch)
2991.1.2 by Daniel Watkins
Working trees are no longer created by pushing into a local no-trees repo.
235
        if result_repo is None or result_repo.make_working_trees():
236
            try:
237
                self.open_workingtree().clone(result)
238
            except (errors.NoWorkingTree, errors.NotLocalUrl):
239
                pass
1534.4.50 by Robert Collins
Got the bzrdir api straightened out, plenty of refactoring to use it pending, but the api is up and running.
240
        return result
241
1685.1.61 by Martin Pool
[broken] Change BzrDir._make_tail to use urlutils.split
242
    # TODO: This should be given a Transport, and should chdir up; otherwise
243
    # this will open a new connection.
1534.4.50 by Robert Collins
Got the bzrdir api straightened out, plenty of refactoring to use it pending, but the api is up and running.
244
    def _make_tail(self, url):
2475.3.3 by John Arbash Meinel
Change calls to try/mkdir('.')/except FileExists to ensure_base()
245
        t = get_transport(url)
246
        t.ensure_base()
2475.3.1 by John Arbash Meinel
Fix bug #75721. Update the BzrDir api to add clone_on_transport()
247
1553.5.71 by Martin Pool
Change branch format 5 to use LockDirs, not transport locks
248
    @classmethod
2476.3.8 by Vincent Ladeuil
Mark transports that need to be instrumented or refactored to check
249
    def create(cls, base, format=None, possible_transports=None):
1534.4.40 by Robert Collins
Add RepositoryFormats and allow bzrdir.open or create _repository to be used.
250
        """Create a new BzrDir at the url 'base'.
1534.4.39 by Robert Collins
Basic BzrDir support.
251
        
2204.4.13 by Aaron Bentley
Update all test cases to avoid set_default_format
252
        :param format: If supplied, the format of branch to create.  If not
253
            supplied, the default is used.
2476.3.8 by Vincent Ladeuil
Mark transports that need to be instrumented or refactored to check
254
        :param possible_transports: If supplied, a list of transports that 
255
            can be reused to share a remote connection.
1534.4.39 by Robert Collins
Basic BzrDir support.
256
        """
1553.5.71 by Martin Pool
Change branch format 5 to use LockDirs, not transport locks
257
        if cls is not BzrDir:
2204.4.13 by Aaron Bentley
Update all test cases to avoid set_default_format
258
            raise AssertionError("BzrDir.create always creates the default"
259
                " format, not one of %r" % cls)
2476.3.8 by Vincent Ladeuil
Mark transports that need to be instrumented or refactored to check
260
        t = get_transport(base, possible_transports)
2475.3.3 by John Arbash Meinel
Change calls to try/mkdir('.')/except FileExists to ensure_base()
261
        t.ensure_base()
2204.4.13 by Aaron Bentley
Update all test cases to avoid set_default_format
262
        if format is None:
263
            format = BzrDirFormat.get_default_format()
2830.1.1 by Ian Clatworthy
bzrdir.py code clean-ups
264
        return format.initialize_on_transport(t)
1534.4.39 by Robert Collins
Basic BzrDir support.
265
3140.1.1 by Aaron Bentley
Implement find_bzrdir functionality
266
    @staticmethod
267
    def find_bzrdirs(transport, evaluate=None, list_current=None):
268
        """Find bzrdirs recursively from current location.
269
270
        This is intended primarily as a building block for more sophisticated
271
        functionality, like finding trees under a directory, or finding
272
        branches that use a given repository.
273
        :param evaluate: An optional callable that yields recurse, value,
274
            where recurse controls whether this bzrdir is recursed into
275
            and value is the value to yield.  By default, all bzrdirs
276
            are recursed into, and the return value is the bzrdir.
277
        :param list_current: if supplied, use this function to list the current
278
            directory, instead of Transport.list_dir
279
        :return: a generator of found bzrdirs, or whatever evaluate returns.
280
        """
281
        if list_current is None:
282
            def list_current(transport):
283
                return transport.list_dir('')
284
        if evaluate is None:
285
            def evaluate(bzrdir):
286
                return True, bzrdir
287
288
        pending = [transport]
289
        while len(pending) > 0:
290
            current_transport = pending.pop()
291
            recurse = True
292
            try:
293
                bzrdir = BzrDir.open_from_transport(current_transport)
294
            except errors.NotBranchError:
295
                pass
296
            else:
297
                recurse, value = evaluate(bzrdir)
298
                yield value
299
            try:
300
                subdirs = list_current(current_transport)
301
            except errors.NoSuchFile:
302
                continue
303
            if recurse:
304
                for subdir in sorted(subdirs, reverse=True):
305
                    pending.append(current_transport.clone(subdir))
306
3140.1.3 by Aaron Bentley
Add support for finding branches to BzrDir
307
    @staticmethod
308
    def find_branches(transport):
3140.1.7 by Aaron Bentley
Update docs
309
        """Find all branches under a transport.
310
311
        This will find all branches below the transport, including branches
312
        inside other branches.  Where possible, it will use
313
        Repository.find_branches.
314
315
        To list all the branches that use a particular Repository, see
316
        Repository.find_branches
317
        """
3140.1.3 by Aaron Bentley
Add support for finding branches to BzrDir
318
        def evaluate(bzrdir):
319
            try:
320
                repository = bzrdir.open_repository()
321
            except errors.NoRepositoryPresent:
322
                pass
323
            else:
324
                return False, (None, repository)
325
            try:
326
                branch = bzrdir.open_branch()
327
            except errors.NotBranchError:
328
                return True, (None, None)
329
            else:
330
                return True, (branch, None)
331
        branches = []
332
        for branch, repo in BzrDir.find_bzrdirs(transport, evaluate=evaluate):
333
            if repo is not None:
334
                branches.extend(repo.find_branches())
335
            if branch is not None:
336
                branches.append(branch)
337
        return branches
338
2796.2.19 by Aaron Bentley
Support reconfigure --lightweight-checkout
339
    def destroy_repository(self):
340
        """Destroy the repository in this BzrDir"""
341
        raise NotImplementedError(self.destroy_repository)
342
1534.4.41 by Robert Collins
Branch now uses BzrDir reasonably sanely.
343
    def create_branch(self):
344
        """Create a branch in this BzrDir.
345
2830.1.1 by Ian Clatworthy
bzrdir.py code clean-ups
346
        The bzrdir's format will control what branch format is created.
1534.4.41 by Robert Collins
Branch now uses BzrDir reasonably sanely.
347
        For more control see BranchFormatXX.create(a_bzrdir).
348
        """
349
        raise NotImplementedError(self.create_branch)
350
2796.2.6 by Aaron Bentley
Implement destroy_branch
351
    def destroy_branch(self):
2796.2.16 by Aaron Bentley
Documentation updates from review
352
        """Destroy the branch in this BzrDir"""
2796.2.6 by Aaron Bentley
Implement destroy_branch
353
        raise NotImplementedError(self.destroy_branch)
354
1534.4.41 by Robert Collins
Branch now uses BzrDir reasonably sanely.
355
    @staticmethod
2204.4.13 by Aaron Bentley
Update all test cases to avoid set_default_format
356
    def create_branch_and_repo(base, force_new_repo=False, format=None):
1534.4.41 by Robert Collins
Branch now uses BzrDir reasonably sanely.
357
        """Create a new BzrDir, Branch and Repository at the url 'base'.
358
2830.1.1 by Ian Clatworthy
bzrdir.py code clean-ups
359
        This will use the current default BzrDirFormat unless one is
360
        specified, and use whatever 
1534.4.41 by Robert Collins
Branch now uses BzrDir reasonably sanely.
361
        repository format that that uses via bzrdir.create_branch and
1534.6.6 by Robert Collins
Move find_repository to bzrdir, its not quite ideal there but its simpler and until someone chooses to vary the search by branch type its completely sufficient.
362
        create_repository. If a shared repository is available that is used
363
        preferentially.
1534.4.41 by Robert Collins
Branch now uses BzrDir reasonably sanely.
364
365
        The created Branch object is returned.
1534.6.6 by Robert Collins
Move find_repository to bzrdir, its not quite ideal there but its simpler and until someone chooses to vary the search by branch type its completely sufficient.
366
367
        :param base: The URL to create the branch at.
368
        :param force_new_repo: If True a new repository is always created.
2830.1.1 by Ian Clatworthy
bzrdir.py code clean-ups
369
        :param format: If supplied, the format of branch to create.  If not
370
            supplied, the default is used.
1534.4.41 by Robert Collins
Branch now uses BzrDir reasonably sanely.
371
        """
2204.4.13 by Aaron Bentley
Update all test cases to avoid set_default_format
372
        bzrdir = BzrDir.create(base, format)
1534.6.11 by Robert Collins
Review feedback.
373
        bzrdir._find_or_create_repository(force_new_repo)
1534.4.41 by Robert Collins
Branch now uses BzrDir reasonably sanely.
374
        return bzrdir.create_branch()
1534.6.11 by Robert Collins
Review feedback.
375
3242.3.32 by Aaron Bentley
Defer handling relative stacking URLs as late as possible.
376
    def determine_repository_policy(self, force_new_repo=False, stack_on=None,
3242.3.40 by Aaron Bentley
Turn failing test into KnownFailure
377
                                    stack_on_pwd=None, require_stacking=False):
3242.2.13 by Aaron Bentley
Update docs
378
        """Return an object representing a policy to use.
379
380
        This controls whether a new repository is created, or a shared
381
        repository used instead.
3242.3.35 by Aaron Bentley
Cleanups and documentation
382
383
        If stack_on is supplied, will not seek a containing shared repo.
3575.2.2 by Martin Pool
branch --stacked should force a stacked format
384
3242.3.35 by Aaron Bentley
Cleanups and documentation
385
        :param force_new_repo: If True, require a new repository to be created.
386
        :param stack_on: If supplied, the location to stack on.  If not
387
            supplied, a default_stack_on location may be used.
388
        :param stack_on_pwd: If stack_on is relative, the location it is
389
            relative to.
3242.2.13 by Aaron Bentley
Update docs
390
        """
3242.3.3 by Aaron Bentley
Use _find_containing to determine repository policy
391
        def repository_policy(found_bzrdir):
3242.3.4 by Aaron Bentley
Initial determination of stacking policy
392
            stack_on = None
3242.3.32 by Aaron Bentley
Defer handling relative stacking URLs as late as possible.
393
            stack_on_pwd = None
3242.3.4 by Aaron Bentley
Initial determination of stacking policy
394
            config = found_bzrdir.get_config()
395
            stop = False
396
            if config is not None:
3242.3.11 by Aaron Bentley
Clean up BzrDirConfig usage
397
                stack_on = config.get_default_stack_on()
3242.3.4 by Aaron Bentley
Initial determination of stacking policy
398
                if stack_on is not None:
3242.3.32 by Aaron Bentley
Defer handling relative stacking URLs as late as possible.
399
                    stack_on_pwd = found_bzrdir.root_transport.base
3242.3.4 by Aaron Bentley
Initial determination of stacking policy
400
                    stop = True
3242.3.34 by Aaron Bentley
Add notification of default stacking
401
                    note('Using default stacking branch %s at %s', stack_on,
402
                         stack_on_pwd)
3242.3.3 by Aaron Bentley
Use _find_containing to determine repository policy
403
            # does it have a repository ?
404
            try:
405
                repository = found_bzrdir.open_repository()
406
            except errors.NoRepositoryPresent:
3242.3.4 by Aaron Bentley
Initial determination of stacking policy
407
                repository = None
408
            else:
409
                if ((found_bzrdir.root_transport.base !=
410
                     self.root_transport.base) and not repository.is_shared()):
411
                    repository = None
412
                else:
413
                    stop = True
414
            if not stop:
3242.3.3 by Aaron Bentley
Use _find_containing to determine repository policy
415
                return None, False
3242.3.4 by Aaron Bentley
Initial determination of stacking policy
416
            if repository:
3242.3.32 by Aaron Bentley
Defer handling relative stacking URLs as late as possible.
417
                return UseExistingRepository(repository, stack_on,
3242.3.40 by Aaron Bentley
Turn failing test into KnownFailure
418
                    stack_on_pwd, require_stacking=require_stacking), True
3242.3.3 by Aaron Bentley
Use _find_containing to determine repository policy
419
            else:
3242.3.40 by Aaron Bentley
Turn failing test into KnownFailure
420
                return CreateRepository(self, stack_on, stack_on_pwd,
421
                    require_stacking=require_stacking), True
3242.3.3 by Aaron Bentley
Use _find_containing to determine repository policy
422
3242.2.1 by Aaron Bentley
Abstract policy decisions into determine_repository_policy
423
        if not force_new_repo:
3242.3.30 by Aaron Bentley
Handle adding fallback repositories in acquire_repository
424
            if stack_on is None:
425
                policy = self._find_containing(repository_policy)
426
                if policy is not None:
427
                    return policy
428
            else:
429
                try:
430
                    return UseExistingRepository(self.open_repository(),
3242.3.40 by Aaron Bentley
Turn failing test into KnownFailure
431
                        stack_on, stack_on_pwd,
432
                        require_stacking=require_stacking)
3242.3.30 by Aaron Bentley
Handle adding fallback repositories in acquire_repository
433
                except errors.NoRepositoryPresent:
434
                    pass
3242.3.40 by Aaron Bentley
Turn failing test into KnownFailure
435
        return CreateRepository(self, stack_on, stack_on_pwd,
436
                                require_stacking=require_stacking)
3242.2.1 by Aaron Bentley
Abstract policy decisions into determine_repository_policy
437
1534.6.11 by Robert Collins
Review feedback.
438
    def _find_or_create_repository(self, force_new_repo):
439
        """Create a new repository if needed, returning the repository."""
3242.2.10 by Aaron Bentley
Rename RepositoryPolicy.apply to acquire_repository
440
        policy = self.determine_repository_policy(force_new_repo)
441
        return policy.acquire_repository()
442
1534.4.40 by Robert Collins
Add RepositoryFormats and allow bzrdir.open or create _repository to be used.
443
    @staticmethod
2476.3.6 by Vincent Ladeuil
Fix the 'init connects multiple times' in a different way.
444
    def create_branch_convenience(base, force_new_repo=False,
445
                                  force_new_tree=None, format=None,
2476.3.11 by Vincent Ladeuil
Cosmetic changes.
446
                                  possible_transports=None):
1534.6.10 by Robert Collins
Finish use of repositories support.
447
        """Create a new BzrDir, Branch and Repository at the url 'base'.
448
449
        This is a convenience function - it will use an existing repository
450
        if possible, can be told explicitly whether to create a working tree or
1534.6.12 by Robert Collins
Typo found by John Meinel.
451
        not.
1534.6.10 by Robert Collins
Finish use of repositories support.
452
2830.1.1 by Ian Clatworthy
bzrdir.py code clean-ups
453
        This will use the current default BzrDirFormat unless one is
454
        specified, and use whatever 
1534.6.10 by Robert Collins
Finish use of repositories support.
455
        repository format that that uses via bzrdir.create_branch and
456
        create_repository. If a shared repository is available that is used
457
        preferentially. Whatever repository is used, its tree creation policy
458
        is followed.
459
460
        The created Branch object is returned.
461
        If a working tree cannot be made due to base not being a file:// url,
1563.1.6 by Robert Collins
Add tests for sftp push, and NonLocalTets for BzrDir.create_branch_convenience, before fixing the failure of it to work on non-local urls.
462
        no error is raised unless force_new_tree is True, in which case no 
463
        data is created on disk and NotLocalUrl is raised.
1534.6.10 by Robert Collins
Finish use of repositories support.
464
465
        :param base: The URL to create the branch at.
466
        :param force_new_repo: If True a new repository is always created.
467
        :param force_new_tree: If True or False force creation of a tree or 
468
                               prevent such creation respectively.
2830.1.1 by Ian Clatworthy
bzrdir.py code clean-ups
469
        :param format: Override for the bzrdir format to create.
2476.3.8 by Vincent Ladeuil
Mark transports that need to be instrumented or refactored to check
470
        :param possible_transports: An optional reusable transports list.
1534.6.10 by Robert Collins
Finish use of repositories support.
471
        """
1563.1.6 by Robert Collins
Add tests for sftp push, and NonLocalTets for BzrDir.create_branch_convenience, before fixing the failure of it to work on non-local urls.
472
        if force_new_tree:
473
            # check for non local urls
2485.8.45 by Vincent Ladeuil
Take jam's remarks into account.
474
            t = get_transport(base, possible_transports)
2476.3.6 by Vincent Ladeuil
Fix the 'init connects multiple times' in a different way.
475
            if not isinstance(t, LocalTransport):
476
                raise errors.NotLocalUrl(base)
2476.3.8 by Vincent Ladeuil
Mark transports that need to be instrumented or refactored to check
477
        bzrdir = BzrDir.create(base, format, possible_transports)
1534.6.11 by Robert Collins
Review feedback.
478
        repo = bzrdir._find_or_create_repository(force_new_repo)
1534.6.10 by Robert Collins
Finish use of repositories support.
479
        result = bzrdir.create_branch()
2476.3.4 by Vincent Ladeuil
Add tests.
480
        if force_new_tree or (repo.make_working_trees() and
1534.6.10 by Robert Collins
Finish use of repositories support.
481
                              force_new_tree is None):
1563.1.6 by Robert Collins
Add tests for sftp push, and NonLocalTets for BzrDir.create_branch_convenience, before fixing the failure of it to work on non-local urls.
482
            try:
483
                bzrdir.create_workingtree()
484
            except errors.NotLocalUrl:
485
                pass
1534.6.10 by Robert Collins
Finish use of repositories support.
486
        return result
2476.3.4 by Vincent Ladeuil
Add tests.
487
1551.8.2 by Aaron Bentley
Add create_checkout_convenience
488
    @staticmethod
2204.4.13 by Aaron Bentley
Update all test cases to avoid set_default_format
489
    def create_standalone_workingtree(base, format=None):
1534.4.42 by Robert Collins
add working tree to the BzrDir facilities.
490
        """Create a new BzrDir, WorkingTree, Branch and Repository at 'base'.
491
492
        'base' must be a local path or a file:// url.
493
2830.1.1 by Ian Clatworthy
bzrdir.py code clean-ups
494
        This will use the current default BzrDirFormat unless one is
495
        specified, and use whatever 
1534.4.42 by Robert Collins
add working tree to the BzrDir facilities.
496
        repository format that that uses for bzrdirformat.create_workingtree,
497
        create_branch and create_repository.
498
2830.1.1 by Ian Clatworthy
bzrdir.py code clean-ups
499
        :param format: Override for the bzrdir format to create.
1910.7.17 by Andrew Bennetts
Various cosmetic changes.
500
        :return: The WorkingTree object.
1534.4.42 by Robert Collins
add working tree to the BzrDir facilities.
501
        """
2485.8.45 by Vincent Ladeuil
Take jam's remarks into account.
502
        t = get_transport(base)
1534.4.42 by Robert Collins
add working tree to the BzrDir facilities.
503
        if not isinstance(t, LocalTransport):
504
            raise errors.NotLocalUrl(base)
2485.8.45 by Vincent Ladeuil
Take jam's remarks into account.
505
        bzrdir = BzrDir.create_branch_and_repo(base,
2204.4.13 by Aaron Bentley
Update all test cases to avoid set_default_format
506
                                               force_new_repo=True,
507
                                               format=format).bzrdir
1534.4.42 by Robert Collins
add working tree to the BzrDir facilities.
508
        return bzrdir.create_workingtree()
509
3123.5.17 by Aaron Bentley
Update docs
510
    def create_workingtree(self, revision_id=None, from_branch=None,
3136.1.3 by Aaron Bentley
Implement hard-link support for branch and checkout
511
        accelerator_tree=None, hardlink=False):
1508.1.21 by Robert Collins
Implement -r limit for checkout command.
512
        """Create a working tree at this BzrDir.
513
        
2955.5.3 by Vincent Ladeuil
Fix second unwanted connection by providing the right branch to create_checkout.
514
        :param revision_id: create it as of this revision id.
515
        :param from_branch: override bzrdir branch (for lightweight checkouts)
3123.5.17 by Aaron Bentley
Update docs
516
        :param accelerator_tree: A tree which can be used for retrieving file
517
            contents more quickly than the revision tree, i.e. a workingtree.
518
            The revision tree will be used for cases where accelerator_tree's
519
            content is different.
1508.1.21 by Robert Collins
Implement -r limit for checkout command.
520
        """
1534.4.42 by Robert Collins
add working tree to the BzrDir facilities.
521
        raise NotImplementedError(self.create_workingtree)
522
2830.1.2 by Ian Clatworthy
Incorporate feedback from poolie's review
523
    def retire_bzrdir(self, limit=10000):
2255.14.1 by Martin Pool
Add BzrDir.retire_bzrdir and partly fix subsume
524
        """Permanently disable the bzrdir.
525
526
        This is done by renaming it to give the user some ability to recover
527
        if there was a problem.
528
529
        This will have horrible consequences if anyone has anything locked or
530
        in use.
2830.1.2 by Ian Clatworthy
Incorporate feedback from poolie's review
531
        :param limit: number of times to retry
2255.14.1 by Martin Pool
Add BzrDir.retire_bzrdir and partly fix subsume
532
        """
2830.1.2 by Ian Clatworthy
Incorporate feedback from poolie's review
533
        i  = 0
534
        while True:
2255.14.1 by Martin Pool
Add BzrDir.retire_bzrdir and partly fix subsume
535
            try:
536
                to_path = '.bzr.retired.%d' % i
537
                self.root_transport.rename('.bzr', to_path)
538
                note("renamed %s to %s"
539
                    % (self.root_transport.abspath('.bzr'), to_path))
2830.1.1 by Ian Clatworthy
bzrdir.py code clean-ups
540
                return
2255.14.1 by Martin Pool
Add BzrDir.retire_bzrdir and partly fix subsume
541
            except (errors.TransportError, IOError, errors.PathError):
2830.1.2 by Ian Clatworthy
Incorporate feedback from poolie's review
542
                i += 1
543
                if i > limit:
544
                    raise
545
                else:
546
                    pass
2255.14.1 by Martin Pool
Add BzrDir.retire_bzrdir and partly fix subsume
547
1551.8.37 by Aaron Bentley
Cleaner implementation of destroy_working_tree
548
    def destroy_workingtree(self):
1551.8.36 by Aaron Bentley
Introduce BzrDir.destroy_workingtree
549
        """Destroy the working tree at this BzrDir.
550
551
        Formats that do not support this may raise UnsupportedOperation.
552
        """
553
        raise NotImplementedError(self.destroy_workingtree)
554
1551.8.37 by Aaron Bentley
Cleaner implementation of destroy_working_tree
555
    def destroy_workingtree_metadata(self):
556
        """Destroy the control files for the working tree at this BzrDir.
557
558
        The contents of working tree files are not affected.
559
        Formats that do not support this may raise UnsupportedOperation.
560
        """
561
        raise NotImplementedError(self.destroy_workingtree_metadata)
562
3242.3.2 by Aaron Bentley
Split _find_containing out of find_repository
563
    def _find_containing(self, evaluate):
3242.2.13 by Aaron Bentley
Update docs
564
        """Find something in a containing control directory.
565
566
        This method will scan containing control dirs, until it finds what
567
        it is looking for, decides that it will never find it, or runs out
568
        of containing control directories to check.
569
570
        It is used to implement find_repository and
571
        determine_repository_policy.
572
573
        :param evaluate: A function returning (value, stop).  If stop is True,
574
            the value will be returned.
575
        """
3242.3.2 by Aaron Bentley
Split _find_containing out of find_repository
576
        found_bzrdir = self
577
        while True:
578
            result, stop = evaluate(found_bzrdir)
579
            if stop:
580
                return result
581
            next_transport = found_bzrdir.root_transport.clone('..')
582
            if (found_bzrdir.root_transport.base == next_transport.base):
583
                # top of the file system
584
                return None
585
            # find the next containing bzrdir
586
            try:
587
                found_bzrdir = BzrDir.open_containing_from_transport(
588
                    next_transport)[0]
589
            except errors.NotBranchError:
590
                return None
591
1534.6.6 by Robert Collins
Move find_repository to bzrdir, its not quite ideal there but its simpler and until someone chooses to vary the search by branch type its completely sufficient.
592
    def find_repository(self):
2830.1.1 by Ian Clatworthy
bzrdir.py code clean-ups
593
        """Find the repository that should be used.
1534.6.6 by Robert Collins
Move find_repository to bzrdir, its not quite ideal there but its simpler and until someone chooses to vary the search by branch type its completely sufficient.
594
595
        This does not require a branch as we use it to find the repo for
596
        new branches as well as to hook existing branches up to their
597
        repository.
598
        """
3242.3.2 by Aaron Bentley
Split _find_containing out of find_repository
599
        def usable_repository(found_bzrdir):
1725.2.5 by Robert Collins
Bugfix create_branch_convenience at the root of a file system to not loop
600
            # does it have a repository ?
1534.6.6 by Robert Collins
Move find_repository to bzrdir, its not quite ideal there but its simpler and until someone chooses to vary the search by branch type its completely sufficient.
601
            try:
602
                repository = found_bzrdir.open_repository()
603
            except errors.NoRepositoryPresent:
3242.3.2 by Aaron Bentley
Split _find_containing out of find_repository
604
                return None, False
3242.2.5 by Aaron Bentley
Avoid unnecessary is_shared check
605
            if found_bzrdir.root_transport.base == self.root_transport.base:
606
                return repository, True
607
            elif repository.is_shared():
3242.3.2 by Aaron Bentley
Split _find_containing out of find_repository
608
                return repository, True
1534.6.6 by Robert Collins
Move find_repository to bzrdir, its not quite ideal there but its simpler and until someone chooses to vary the search by branch type its completely sufficient.
609
            else:
3242.2.5 by Aaron Bentley
Avoid unnecessary is_shared check
610
                return None, True
3242.3.2 by Aaron Bentley
Split _find_containing out of find_repository
611
612
        found_repo = self._find_containing(usable_repository)
613
        if found_repo is None:
614
            raise errors.NoRepositoryPresent(self)
615
        return found_repo
1534.6.6 by Robert Collins
Move find_repository to bzrdir, its not quite ideal there but its simpler and until someone chooses to vary the search by branch type its completely sufficient.
616
2414.2.1 by Andrew Bennetts
Some miscellaneous new APIs, tests and other changes from the hpss branch.
617
    def get_branch_reference(self):
618
        """Return the referenced URL for the branch in this bzrdir.
619
620
        :raises NotBranchError: If there is no Branch.
621
        :return: The URL the branch in this bzrdir references if it is a
622
            reference branch, or None for regular branches.
623
        """
624
        return None
625
1534.4.44 by Robert Collins
Make a new BzrDir format that uses a versioned branch format in a branch/ subdirectory.
626
    def get_branch_transport(self, branch_format):
627
        """Get the transport for use by branch format in this BzrDir.
628
629
        Note that bzr dirs that do not support format strings will raise
630
        IncompatibleFormat if the branch format they are given has
1759.2.1 by Jelmer Vernooij
Fix some types (found using aspell).
631
        a format string, and vice versa.
1534.4.44 by Robert Collins
Make a new BzrDir format that uses a versioned branch format in a branch/ subdirectory.
632
633
        If branch_format is None, the transport is returned with no 
2830.1.1 by Ian Clatworthy
bzrdir.py code clean-ups
634
        checking. If it is not None, then the returned transport is
1534.4.44 by Robert Collins
Make a new BzrDir format that uses a versioned branch format in a branch/ subdirectory.
635
        guaranteed to point to an existing directory ready for use.
636
        """
637
        raise NotImplementedError(self.get_branch_transport)
3416.2.1 by Martin Pool
Add BzrDir._get_file_mode and _get_dir_mode
638
639
    def _find_creation_modes(self):
640
        """Determine the appropriate modes for files and directories.
641
        
642
        They're always set to be consistent with the base directory,
643
        assuming that this transport allows setting modes.
644
        """
645
        # TODO: Do we need or want an option (maybe a config setting) to turn
646
        # this off or override it for particular locations? -- mbp 20080512
647
        if self._mode_check_done:
648
            return
649
        self._mode_check_done = True
650
        try:
651
            st = self.transport.stat('.')
652
        except errors.TransportNotPossible:
653
            self._dir_mode = None
654
            self._file_mode = None
655
        else:
656
            # Check the directory mode, but also make sure the created
657
            # directories and files are read-write for this user. This is
658
            # mostly a workaround for filesystems which lie about being able to
659
            # write to a directory (cygwin & win32)
660
            self._dir_mode = (st.st_mode & 07777) | 00700
661
            # Remove the sticky and execute bits for files
662
            self._file_mode = self._dir_mode & ~07111
663
664
    def _get_file_mode(self):
665
        """Return Unix mode for newly created files, or None.
666
        """
667
        if not self._mode_check_done:
668
            self._find_creation_modes()
669
        return self._file_mode
670
671
    def _get_dir_mode(self):
672
        """Return Unix mode for newly created directories, or None.
673
        """
674
        if not self._mode_check_done:
675
            self._find_creation_modes()
676
        return self._dir_mode
1534.4.44 by Robert Collins
Make a new BzrDir format that uses a versioned branch format in a branch/ subdirectory.
677
        
1534.4.47 by Robert Collins
Split out repository into .bzr/repository
678
    def get_repository_transport(self, repository_format):
679
        """Get the transport for use by repository format in this BzrDir.
680
681
        Note that bzr dirs that do not support format strings will raise
682
        IncompatibleFormat if the repository format they are given has
1759.2.1 by Jelmer Vernooij
Fix some types (found using aspell).
683
        a format string, and vice versa.
1534.4.47 by Robert Collins
Split out repository into .bzr/repository
684
685
        If repository_format is None, the transport is returned with no 
2830.1.1 by Ian Clatworthy
bzrdir.py code clean-ups
686
        checking. If it is not None, then the returned transport is
1534.4.47 by Robert Collins
Split out repository into .bzr/repository
687
        guaranteed to point to an existing directory ready for use.
688
        """
689
        raise NotImplementedError(self.get_repository_transport)
690
        
1534.4.53 by Robert Collins
Review feedback from John Meinel.
691
    def get_workingtree_transport(self, tree_format):
1534.4.45 by Robert Collins
Start WorkingTree -> .bzr/checkout transition
692
        """Get the transport for use by workingtree format in this BzrDir.
693
694
        Note that bzr dirs that do not support format strings will raise
2100.3.11 by Aaron Bentley
Add join --reference support
695
        IncompatibleFormat if the workingtree format they are given has a
696
        format string, and vice versa.
1534.4.45 by Robert Collins
Start WorkingTree -> .bzr/checkout transition
697
698
        If workingtree_format is None, the transport is returned with no 
2830.1.1 by Ian Clatworthy
bzrdir.py code clean-ups
699
        checking. If it is not None, then the returned transport is
1534.4.45 by Robert Collins
Start WorkingTree -> .bzr/checkout transition
700
        guaranteed to point to an existing directory ready for use.
701
        """
702
        raise NotImplementedError(self.get_workingtree_transport)
3242.1.1 by Aaron Bentley
Implement BzrDir configuration
703
704
    def get_config(self):
705
        if getattr(self, '_get_config', None) is None:
706
            return None
707
        return self._get_config()
708
1534.4.39 by Robert Collins
Basic BzrDir support.
709
    def __init__(self, _transport, _format):
710
        """Initialize a Bzr control dir object.
711
        
712
        Only really common logic should reside here, concrete classes should be
713
        made with varying behaviours.
714
1534.4.53 by Robert Collins
Review feedback from John Meinel.
715
        :param _format: the format that is creating this BzrDir instance.
716
        :param _transport: the transport this dir is based at.
1534.4.39 by Robert Collins
Basic BzrDir support.
717
        """
718
        self._format = _format
1534.4.41 by Robert Collins
Branch now uses BzrDir reasonably sanely.
719
        self.transport = _transport.clone('.bzr')
1534.4.50 by Robert Collins
Got the bzrdir api straightened out, plenty of refactoring to use it pending, but the api is up and running.
720
        self.root_transport = _transport
3416.2.1 by Martin Pool
Add BzrDir._get_file_mode and _get_dir_mode
721
        self._mode_check_done = False
1534.4.39 by Robert Collins
Basic BzrDir support.
722
1713.1.9 by Robert Collins
Paired performance tuning of bzr add. (Robert Collins, Martin Pool).
723
    def is_control_filename(self, filename):
724
        """True if filename is the name of a path which is reserved for bzrdir's.
725
        
726
        :param filename: A filename within the root transport of this bzrdir.
727
728
        This is true IF and ONLY IF the filename is part of the namespace reserved
729
        for bzr control dirs. Currently this is the '.bzr' directory in the root
730
        of the root_transport. it is expected that plugins will need to extend
731
        this in the future - for instance to make bzr talk with svn working
732
        trees.
733
        """
734
        # this might be better on the BzrDirFormat class because it refers to 
735
        # all the possible bzrdir disk formats. 
736
        # This method is tested via the workingtree is_control_filename tests- 
2830.1.1 by Ian Clatworthy
bzrdir.py code clean-ups
737
        # it was extracted from WorkingTree.is_control_filename. If the method's
738
        # contract is extended beyond the current trivial implementation, please
1713.1.9 by Robert Collins
Paired performance tuning of bzr add. (Robert Collins, Martin Pool).
739
        # add new tests for it to the appropriate place.
740
        return filename == '.bzr' or filename.startswith('.bzr/')
741
1534.5.16 by Robert Collins
Review feedback.
742
    def needs_format_conversion(self, format=None):
743
        """Return true if this bzrdir needs convert_format run on it.
1534.5.7 by Robert Collins
Start factoring out the upgrade policy logic.
744
        
745
        For instance, if the repository format is out of date but the 
746
        branch and working tree are not, this should return True.
1534.5.13 by Robert Collins
Correct buggy test.
747
748
        :param format: Optional parameter indicating a specific desired
1534.5.16 by Robert Collins
Review feedback.
749
                       format we plan to arrive at.
1534.5.7 by Robert Collins
Start factoring out the upgrade policy logic.
750
        """
1556.1.4 by Robert Collins
Add a new format for what will become knit, and the surrounding logic to upgrade repositories within metadirs, and tests for the same.
751
        raise NotImplementedError(self.needs_format_conversion)
1534.5.7 by Robert Collins
Start factoring out the upgrade policy logic.
752
1534.4.39 by Robert Collins
Basic BzrDir support.
753
    @staticmethod
754
    def open_unsupported(base):
755
        """Open a branch which is not supported."""
756
        return BzrDir.open(base, _unsupported=True)
757
        
758
    @staticmethod
2806.2.2 by Vincent Ladeuil
Fix #128076 and #131396 by reusing bound branch transport.
759
    def open(base, _unsupported=False, possible_transports=None):
2830.1.1 by Ian Clatworthy
bzrdir.py code clean-ups
760
        """Open an existing bzrdir, rooted at 'base' (url).
1534.4.39 by Robert Collins
Basic BzrDir support.
761
        
2830.1.1 by Ian Clatworthy
bzrdir.py code clean-ups
762
        :param _unsupported: a private parameter to the BzrDir class.
1534.4.39 by Robert Collins
Basic BzrDir support.
763
        """
2806.2.2 by Vincent Ladeuil
Fix #128076 and #131396 by reusing bound branch transport.
764
        t = get_transport(base, possible_transports=possible_transports)
1910.11.1 by Andrew Bennetts
Add BzrDir.open_from_transport, refactored from duplicate code, no explicit tests.
765
        return BzrDir.open_from_transport(t, _unsupported=_unsupported)
766
767
    @staticmethod
2018.5.169 by Andrew Bennetts
Add a _server_formats flag to BzrDir.open_from_transport and BzrDirFormat.find_format, make RemoteBranch.control_files into a property.
768
    def open_from_transport(transport, _unsupported=False,
769
                            _server_formats=True):
1910.11.1 by Andrew Bennetts
Add BzrDir.open_from_transport, refactored from duplicate code, no explicit tests.
770
        """Open a bzrdir within a particular directory.
771
772
        :param transport: Transport containing the bzrdir.
773
        :param _unsupported: private.
774
        """
2164.2.21 by Vincent Ladeuil
Take bundles into account.
775
        base = transport.base
776
777
        def find_format(transport):
2018.5.169 by Andrew Bennetts
Add a _server_formats flag to BzrDir.open_from_transport and BzrDirFormat.find_format, make RemoteBranch.control_files into a property.
778
            return transport, BzrDirFormat.find_format(
779
                transport, _server_formats=_server_formats)
2164.2.21 by Vincent Ladeuil
Take bundles into account.
780
781
        def redirected(transport, e, redirection_notice):
782
            qualified_source = e.get_source_url()
783
            relpath = transport.relpath(qualified_source)
784
            if not e.target.endswith(relpath):
785
                # Not redirected to a branch-format, not a branch
786
                raise errors.NotBranchError(path=e.target)
787
            target = e.target[:-len(relpath)]
788
            note('%s is%s redirected to %s',
789
                 transport.base, e.permanently, target)
790
            # Let's try with a new transport
2164.2.22 by Vincent Ladeuil
Take Aaron's review comments into account.
791
            # FIXME: If 'transport' has a qualifier, this should
2164.2.21 by Vincent Ladeuil
Take bundles into account.
792
            # be applied again to the new transport *iff* the
2830.1.2 by Ian Clatworthy
Incorporate feedback from poolie's review
793
            # schemes used are the same. Uncomment this code
794
            # once the function (and tests) exist.
2164.2.21 by Vincent Ladeuil
Take bundles into account.
795
            # -- vila20070212
2830.1.2 by Ian Clatworthy
Incorporate feedback from poolie's review
796
            #target = urlutils.copy_url_qualifiers(original, target)
2164.2.21 by Vincent Ladeuil
Take bundles into account.
797
            return get_transport(target)
798
2164.2.22 by Vincent Ladeuil
Take Aaron's review comments into account.
799
        try:
2164.2.28 by Vincent Ladeuil
TestingHTTPServer.test_case_server renamed from test_case to avoid confusions.
800
            transport, format = do_catching_redirections(find_format,
801
                                                         transport,
2164.2.22 by Vincent Ladeuil
Take Aaron's review comments into account.
802
                                                         redirected)
803
        except errors.TooManyRedirections:
804
            raise errors.NotBranchError(base)
2164.2.21 by Vincent Ladeuil
Take bundles into account.
805
1596.2.1 by Robert Collins
Fix BzrDir.open_containing of unsupported branches.
806
        BzrDir._check_supported(format, _unsupported)
1910.11.1 by Andrew Bennetts
Add BzrDir.open_from_transport, refactored from duplicate code, no explicit tests.
807
        return format.open(transport, _found=True)
1534.4.41 by Robert Collins
Branch now uses BzrDir reasonably sanely.
808
1534.4.44 by Robert Collins
Make a new BzrDir format that uses a versioned branch format in a branch/ subdirectory.
809
    def open_branch(self, unsupported=False):
1534.4.41 by Robert Collins
Branch now uses BzrDir reasonably sanely.
810
        """Open the branch object at this BzrDir if one is present.
1534.4.44 by Robert Collins
Make a new BzrDir format that uses a versioned branch format in a branch/ subdirectory.
811
812
        If unsupported is True, then no longer supported branch formats can
813
        still be opened.
1534.4.41 by Robert Collins
Branch now uses BzrDir reasonably sanely.
814
        
815
        TODO: static convenience version of this?
816
        """
817
        raise NotImplementedError(self.open_branch)
1534.4.39 by Robert Collins
Basic BzrDir support.
818
819
    @staticmethod
2485.8.37 by Vincent Ladeuil
Fix merge multiple connections. Test suite *not* passing (sftp
820
    def open_containing(url, possible_transports=None):
1534.4.39 by Robert Collins
Basic BzrDir support.
821
        """Open an existing branch which contains url.
822
        
1534.6.3 by Robert Collins
find_repository sufficiently robust.
823
        :param url: url to search from.
1534.6.11 by Robert Collins
Review feedback.
824
        See open_containing_from_transport for more detail.
1534.6.3 by Robert Collins
find_repository sufficiently robust.
825
        """
2485.8.37 by Vincent Ladeuil
Fix merge multiple connections. Test suite *not* passing (sftp
826
        transport = get_transport(url, possible_transports)
827
        return BzrDir.open_containing_from_transport(transport)
1534.6.3 by Robert Collins
find_repository sufficiently robust.
828
    
829
    @staticmethod
1534.6.11 by Robert Collins
Review feedback.
830
    def open_containing_from_transport(a_transport):
2830.1.1 by Ian Clatworthy
bzrdir.py code clean-ups
831
        """Open an existing branch which contains a_transport.base.
1534.6.3 by Robert Collins
find_repository sufficiently robust.
832
833
        This probes for a branch at a_transport, and searches upwards from there.
1534.4.39 by Robert Collins
Basic BzrDir support.
834
835
        Basically we keep looking up until we find the control directory or
836
        run into the root.  If there isn't one, raises NotBranchError.
837
        If there is one and it is either an unrecognised format or an unsupported 
838
        format, UnknownFormatError or UnsupportedFormatError are raised.
839
        If there is one, it is returned, along with the unused portion of url.
1685.1.27 by John Arbash Meinel
BzrDir works in URLs, but WorkingTree works in unicode paths
840
1685.1.28 by John Arbash Meinel
Changing open_containing to always return a unicode path.
841
        :return: The BzrDir that contains the path, and a Unicode path 
842
                for the rest of the URL.
1534.4.39 by Robert Collins
Basic BzrDir support.
843
        """
844
        # this gets the normalised url back. I.e. '.' -> the full path.
1534.6.3 by Robert Collins
find_repository sufficiently robust.
845
        url = a_transport.base
1534.4.39 by Robert Collins
Basic BzrDir support.
846
        while True:
847
            try:
1910.11.1 by Andrew Bennetts
Add BzrDir.open_from_transport, refactored from duplicate code, no explicit tests.
848
                result = BzrDir.open_from_transport(a_transport)
849
                return result, urlutils.unescape(a_transport.relpath(url))
1534.4.39 by Robert Collins
Basic BzrDir support.
850
            except errors.NotBranchError, e:
1685.1.60 by Martin Pool
[broken] NotBranchError should unescape the url if possible
851
                pass
2018.14.1 by Andrew Bennetts
Update to current hpss branch? Fix lots of test failures.
852
            try:
853
                new_t = a_transport.clone('..')
854
            except errors.InvalidURLJoin:
855
                # reached the root, whatever that may be
856
                raise errors.NotBranchError(path=url)
1534.6.3 by Robert Collins
find_repository sufficiently robust.
857
            if new_t.base == a_transport.base:
1534.4.39 by Robert Collins
Basic BzrDir support.
858
                # reached the root, whatever that may be
859
                raise errors.NotBranchError(path=url)
1534.6.3 by Robert Collins
find_repository sufficiently robust.
860
            a_transport = new_t
1534.4.39 by Robert Collins
Basic BzrDir support.
861
3123.5.11 by Aaron Bentley
Accelerate branching from a lightweight checkout
862
    def _get_tree_branch(self):
863
        """Return the branch and tree, if any, for this bzrdir.
864
3211.4.1 by Robert Collins
* ``RemoteBzrDir._get_tree_branch`` no longer triggers ``_ensure_real``,
865
        Return None for tree if not present or inaccessible.
3123.5.11 by Aaron Bentley
Accelerate branching from a lightweight checkout
866
        Raise NotBranchError if no branch is present.
867
        :return: (tree, branch)
868
        """
869
        try:
870
            tree = self.open_workingtree()
871
        except (errors.NoWorkingTree, errors.NotLocalUrl):
872
            tree = None
873
            branch = self.open_branch()
874
        else:
875
            branch = tree.branch
876
        return tree, branch
877
878
    @classmethod
879
    def open_tree_or_branch(klass, location):
880
        """Return the branch and working tree at a location.
881
882
        If there is no tree at the location, tree will be None.
883
        If there is no branch at the location, an exception will be
884
        raised
885
        :return: (tree, branch)
886
        """
887
        bzrdir = klass.open(location)
888
        return bzrdir._get_tree_branch()
889
2215.3.2 by Aaron Bentley
Add open_containing_tree_or_branch
890
    @classmethod
891
    def open_containing_tree_or_branch(klass, location):
892
        """Return the branch and working tree contained by a location.
893
894
        Returns (tree, branch, relpath).
895
        If there is no tree at containing the location, tree will be None.
896
        If there is no branch containing the location, an exception will be
897
        raised
898
        relpath is the portion of the path that is contained by the branch.
899
        """
900
        bzrdir, relpath = klass.open_containing(location)
3123.5.11 by Aaron Bentley
Accelerate branching from a lightweight checkout
901
        tree, branch = bzrdir._get_tree_branch()
2215.3.2 by Aaron Bentley
Add open_containing_tree_or_branch
902
        return tree, branch, relpath
903
3015.3.39 by Daniel Watkins
Added classmethod bzrlib.bzrdir.BzrDir.open_containing_tree_branch_or_repository.
904
    @classmethod
905
    def open_containing_tree_branch_or_repository(klass, location):
3015.3.57 by Daniel Watkins
Made changes to BzrDir.open_containing_tree_branch_or_repository suggested on list.
906
        """Return the working tree, branch and repo contained by a location.
3015.3.39 by Daniel Watkins
Added classmethod bzrlib.bzrdir.BzrDir.open_containing_tree_branch_or_repository.
907
3015.3.57 by Daniel Watkins
Made changes to BzrDir.open_containing_tree_branch_or_repository suggested on list.
908
        Returns (tree, branch, repository, relpath).
3015.3.39 by Daniel Watkins
Added classmethod bzrlib.bzrdir.BzrDir.open_containing_tree_branch_or_repository.
909
        If there is no tree containing the location, tree will be None.
910
        If there is no branch containing the location, branch will be None.
911
        If there is no repository containing the location, repository will be
912
        None.
3015.3.57 by Daniel Watkins
Made changes to BzrDir.open_containing_tree_branch_or_repository suggested on list.
913
        relpath is the portion of the path that is contained by the innermost
914
        BzrDir.
3015.3.39 by Daniel Watkins
Added classmethod bzrlib.bzrdir.BzrDir.open_containing_tree_branch_or_repository.
915
3015.3.59 by Daniel Watkins
Further tweaks as requested on-list.
916
        If no tree, branch or repository is found, a NotBranchError is raised.
3015.3.39 by Daniel Watkins
Added classmethod bzrlib.bzrdir.BzrDir.open_containing_tree_branch_or_repository.
917
        """
3015.3.57 by Daniel Watkins
Made changes to BzrDir.open_containing_tree_branch_or_repository suggested on list.
918
        bzrdir, relpath = klass.open_containing(location)
3015.3.39 by Daniel Watkins
Added classmethod bzrlib.bzrdir.BzrDir.open_containing_tree_branch_or_repository.
919
        try:
3015.3.51 by Daniel Watkins
Modified open_containing_tree_branch_or_repository as per Aaron's suggestion.
920
            tree, branch = bzrdir._get_tree_branch()
3015.3.39 by Daniel Watkins
Added classmethod bzrlib.bzrdir.BzrDir.open_containing_tree_branch_or_repository.
921
        except errors.NotBranchError:
922
            try:
3015.3.59 by Daniel Watkins
Further tweaks as requested on-list.
923
                repo = bzrdir.find_repository()
3015.3.57 by Daniel Watkins
Made changes to BzrDir.open_containing_tree_branch_or_repository suggested on list.
924
                return None, None, repo, relpath
925
            except (errors.NoRepositoryPresent):
926
                raise errors.NotBranchError(location)
927
        return tree, branch, branch.repository, relpath
3015.3.39 by Daniel Watkins
Added classmethod bzrlib.bzrdir.BzrDir.open_containing_tree_branch_or_repository.
928
1534.4.47 by Robert Collins
Split out repository into .bzr/repository
929
    def open_repository(self, _unsupported=False):
1534.4.40 by Robert Collins
Add RepositoryFormats and allow bzrdir.open or create _repository to be used.
930
        """Open the repository object at this BzrDir if one is present.
1534.4.47 by Robert Collins
Split out repository into .bzr/repository
931
2830.1.1 by Ian Clatworthy
bzrdir.py code clean-ups
932
        This will not follow the Branch object pointer - it's strictly a direct
1534.4.47 by Robert Collins
Split out repository into .bzr/repository
933
        open facility. Most client code should use open_branch().repository to
934
        get at a repository.
935
2830.1.1 by Ian Clatworthy
bzrdir.py code clean-ups
936
        :param _unsupported: a private parameter, not part of the api.
1534.4.40 by Robert Collins
Add RepositoryFormats and allow bzrdir.open or create _repository to be used.
937
        TODO: static convenience version of this?
938
        """
939
        raise NotImplementedError(self.open_repository)
940
2400.2.2 by Robert Collins
Document BzrDir.open_workingtree's new recommend_upgrade parameter.
941
    def open_workingtree(self, _unsupported=False,
2955.5.3 by Vincent Ladeuil
Fix second unwanted connection by providing the right branch to create_checkout.
942
                         recommend_upgrade=True, from_branch=None):
1534.4.42 by Robert Collins
add working tree to the BzrDir facilities.
943
        """Open the workingtree object at this BzrDir if one is present.
2400.2.2 by Robert Collins
Document BzrDir.open_workingtree's new recommend_upgrade parameter.
944
945
        :param recommend_upgrade: Optional keyword parameter, when True (the
946
            default), emit through the ui module a recommendation that the user
947
            upgrade the working tree when the workingtree being opened is old
948
            (but still fully supported).
2955.5.3 by Vincent Ladeuil
Fix second unwanted connection by providing the right branch to create_checkout.
949
        :param from_branch: override bzrdir branch (for lightweight checkouts)
1534.4.42 by Robert Collins
add working tree to the BzrDir facilities.
950
        """
951
        raise NotImplementedError(self.open_workingtree)
952
1662.1.19 by Martin Pool
Better error message when initting existing tree
953
    def has_branch(self):
954
        """Tell if this bzrdir contains a branch.
955
        
956
        Note: if you're going to open the branch, you should just go ahead
957
        and try, and not ask permission first.  (This method just opens the 
958
        branch and discards it, and that's somewhat expensive.) 
959
        """
960
        try:
961
            self.open_branch()
962
            return True
963
        except errors.NotBranchError:
964
            return False
965
966
    def has_workingtree(self):
967
        """Tell if this bzrdir contains a working tree.
968
969
        This will still raise an exception if the bzrdir has a workingtree that
970
        is remote & inaccessible.
971
        
972
        Note: if you're going to open the working tree, you should just go ahead
973
        and try, and not ask permission first.  (This method just opens the 
974
        workingtree and discards it, and that's somewhat expensive.) 
975
        """
976
        try:
2323.6.4 by Martin Pool
BzrDir._check_supported now also takes care of recommending upgrades, which
977
            self.open_workingtree(recommend_upgrade=False)
1662.1.19 by Martin Pool
Better error message when initting existing tree
978
            return True
979
        except errors.NoWorkingTree:
980
            return False
981
2018.5.96 by Andrew Bennetts
Merge from bzr.dev, resolving the worst of the semantic conflicts, but there's
982
    def _cloning_metadir(self):
3575.2.2 by Martin Pool
branch --stacked should force a stacked format
983
        """Produce a metadir suitable for cloning with.
984
        
985
        :returns: (destination_bzrdir_format, source_repository)
986
        """
2387.1.1 by Robert Collins
Remove the --basis parameter to clone etc. (Robert Collins)
987
        result_format = self._format.__class__()
988
        try:
1910.2.41 by Aaron Bentley
Clean up clone format creation
989
            try:
2387.1.1 by Robert Collins
Remove the --basis parameter to clone etc. (Robert Collins)
990
                branch = self.open_branch()
991
                source_repository = branch.repository
1910.2.41 by Aaron Bentley
Clean up clone format creation
992
            except errors.NotBranchError:
993
                source_branch = None
2387.1.1 by Robert Collins
Remove the --basis parameter to clone etc. (Robert Collins)
994
                source_repository = self.open_repository()
2305.3.1 by Andrew Bennetts
Tidy up BzrDir.cloning_metadir: bogus try/except, and basis argument isn't actually used.
995
        except errors.NoRepositoryPresent:
2100.3.24 by Aaron Bentley
Get all tests passing again
996
            source_repository = None
2305.3.1 by Andrew Bennetts
Tidy up BzrDir.cloning_metadir: bogus try/except, and basis argument isn't actually used.
997
        else:
2018.5.138 by Robert Collins
Merge bzr.dev.
998
            # XXX TODO: This isinstance is here because we have not implemented
999
            # the fix recommended in bug # 103195 - to delegate this choice the
1000
            # repository itself.
2018.5.94 by Andrew Bennetts
Various small changes in aid of making tests pass (including deleting one invalid test).
1001
            repo_format = source_repository._format
1002
            if not isinstance(repo_format, remote.RemoteRepositoryFormat):
1003
                result_format.repository_format = repo_format
2100.3.28 by Aaron Bentley
Make sprout recursive
1004
        try:
2323.5.19 by Martin Pool
No upgrade recommendation on source when cloning
1005
            # TODO: Couldn't we just probe for the format in these cases,
1006
            # rather than opening the whole tree?  It would be a little
1007
            # faster. mbp 20070401
1008
            tree = self.open_workingtree(recommend_upgrade=False)
2100.3.28 by Aaron Bentley
Make sprout recursive
1009
        except (errors.NoWorkingTree, errors.NotLocalUrl):
1010
            result_format.workingtree_format = None
1011
        else:
1012
            result_format.workingtree_format = tree._format.__class__()
2100.3.21 by Aaron Bentley
Work on checking out by-reference trees
1013
        return result_format, source_repository
1014
2018.5.96 by Andrew Bennetts
Merge from bzr.dev, resolving the worst of the semantic conflicts, but there's
1015
    def cloning_metadir(self):
2100.3.32 by Aaron Bentley
fix tree format, basis_tree call, in sprout
1016
        """Produce a metadir suitable for cloning or sprouting with.
1910.2.41 by Aaron Bentley
Clean up clone format creation
1017
2100.3.32 by Aaron Bentley
fix tree format, basis_tree call, in sprout
1018
        These operations may produce workingtrees (yes, even though they're
2830.1.1 by Ian Clatworthy
bzrdir.py code clean-ups
1019
        "cloning" something that doesn't have a tree), so a viable workingtree
2100.3.32 by Aaron Bentley
fix tree format, basis_tree call, in sprout
1020
        format must be selected.
3575.2.2 by Martin Pool
branch --stacked should force a stacked format
1021
1022
        :returns: a BzrDirFormat with all component formats either set
1023
            appropriately or set to None if that component should not be 
1024
            created.
2100.3.32 by Aaron Bentley
fix tree format, basis_tree call, in sprout
1025
        """
2100.3.21 by Aaron Bentley
Work on checking out by-reference trees
1026
        format, repository = self._cloning_metadir()
2100.3.32 by Aaron Bentley
fix tree format, basis_tree call, in sprout
1027
        if format._workingtree_format is None:
2100.3.34 by Aaron Bentley
Fix BzrDir.cloning_metadir with no format
1028
            if repository is None:
1029
                return format
2100.3.21 by Aaron Bentley
Work on checking out by-reference trees
1030
            tree_format = repository._format._matchingbzrdir.workingtree_format
2100.3.28 by Aaron Bentley
Make sprout recursive
1031
            format.workingtree_format = tree_format.__class__()
2100.3.21 by Aaron Bentley
Work on checking out by-reference trees
1032
        return format
1033
2100.3.32 by Aaron Bentley
fix tree format, basis_tree call, in sprout
1034
    def checkout_metadir(self):
1035
        return self.cloning_metadir()
1036
2387.1.1 by Robert Collins
Remove the --basis parameter to clone etc. (Robert Collins)
1037
    def sprout(self, url, revision_id=None, force_new_repo=False,
3123.5.8 by Aaron Bentley
Work around double-opening lock issue
1038
               recurse='down', possible_transports=None,
3221.18.4 by Ian Clatworthy
shallow -> stacked
1039
               accelerator_tree=None, hardlink=False, stacked=False):
1534.4.50 by Robert Collins
Got the bzrdir api straightened out, plenty of refactoring to use it pending, but the api is up and running.
1040
        """Create a copy of this bzrdir prepared for use as a new line of
1041
        development.
1042
2830.1.1 by Ian Clatworthy
bzrdir.py code clean-ups
1043
        If url's last component does not exist, it will be created.
1534.4.50 by Robert Collins
Got the bzrdir api straightened out, plenty of refactoring to use it pending, but the api is up and running.
1044
1045
        Attributes related to the identity of the source branch like
1046
        branch nickname will be cleaned, a working tree is created
1047
        whether one existed before or not; and a local branch is always
1048
        created.
1049
1050
        if revision_id is not None, then the clone operation may tune
1051
            itself to download less data.
3123.5.17 by Aaron Bentley
Update docs
1052
        :param accelerator_tree: A tree which can be used for retrieving file
1053
            contents more quickly than the revision tree, i.e. a workingtree.
1054
            The revision tree will be used for cases where accelerator_tree's
1055
            content is different.
3136.1.3 by Aaron Bentley
Implement hard-link support for branch and checkout
1056
        :param hardlink: If true, hard-link files from accelerator_tree,
1057
            where possible.
3221.18.4 by Ian Clatworthy
shallow -> stacked
1058
        :param stacked: If true, create a stacked branch referring to the
3221.13.2 by Robert Collins
Add a shallow parameter to bzrdir.sprout, which involved fixing a lateny bug in pack to pack fetching with ghost discovery.
1059
            location of this control directory.
1534.4.50 by Robert Collins
Got the bzrdir api straightened out, plenty of refactoring to use it pending, but the api is up and running.
1060
        """
2485.8.56 by Vincent Ladeuil
Fix bug #112173 and bzr branch multiple connections.
1061
        target_transport = get_transport(url, possible_transports)
2475.3.3 by John Arbash Meinel
Change calls to try/mkdir('.')/except FileExists to ensure_base()
1062
        target_transport.ensure_base()
2305.3.1 by Andrew Bennetts
Tidy up BzrDir.cloning_metadir: bogus try/except, and basis argument isn't actually used.
1063
        cloning_format = self.cloning_metadir()
2475.3.1 by John Arbash Meinel
Fix bug #75721. Update the BzrDir api to add clone_on_transport()
1064
        result = cloning_format.initialize_on_transport(target_transport)
1534.4.50 by Robert Collins
Got the bzrdir api straightened out, plenty of refactoring to use it pending, but the api is up and running.
1065
        try:
1066
            source_branch = self.open_branch()
1067
            source_repository = source_branch.repository
3221.18.4 by Ian Clatworthy
shallow -> stacked
1068
            if stacked:
1069
                stacked_branch_url = self.root_transport.base
3221.11.20 by Robert Collins
Support --shallow on branch.
1070
            else:
3549.1.4 by Martin Pool
Branching a stacked branch should not automatically turn on stacking
1071
                # if a stacked branch wasn't requested, we don't create one
1072
                # even if the origin was stacked
1073
                stacked_branch_url = None
1534.4.50 by Robert Collins
Got the bzrdir api straightened out, plenty of refactoring to use it pending, but the api is up and running.
1074
        except errors.NotBranchError:
1075
            source_branch = None
1076
            try:
1077
                source_repository = self.open_repository()
1078
            except errors.NoRepositoryPresent:
2387.1.1 by Robert Collins
Remove the --basis parameter to clone etc. (Robert Collins)
1079
                source_repository = None
3221.18.4 by Ian Clatworthy
shallow -> stacked
1080
            stacked_branch_url = None
3242.3.32 by Aaron Bentley
Defer handling relative stacking URLs as late as possible.
1081
        repository_policy = result.determine_repository_policy(
3242.3.40 by Aaron Bentley
Turn failing test into KnownFailure
1082
            force_new_repo, stacked_branch_url, require_stacking=stacked)
3242.3.28 by Aaron Bentley
Use repository acquisition policy for sprouting
1083
        result_repo = repository_policy.acquire_repository()
3242.3.32 by Aaron Bentley
Defer handling relative stacking URLs as late as possible.
1084
        if source_repository is not None:
3575.2.2 by Martin Pool
branch --stacked should force a stacked format
1085
            # XXX: Isn't this redundant with the copy_content_into used below
1086
            # after creating the branch? -- mbp 20080724
3242.3.30 by Aaron Bentley
Handle adding fallback repositories in acquire_repository
1087
            result_repo.fetch(source_repository, revision_id=revision_id)
3221.18.1 by Ian Clatworthy
tweaks by ianc during review
1088
1089
        # Create/update the result branch
3575.2.2 by Martin Pool
branch --stacked should force a stacked format
1090
        if ((stacked 
1091
             or repository_policy._require_stacking 
1092
             or repository_policy._stack_on)
1093
            and not result._format.get_branch_format().supports_stacking()):
1094
            # force a branch that can support stacking 
1095
            from bzrlib.branch import BzrBranchFormat7
1096
            format = BzrBranchFormat7()
1097
            result_branch = format.initialize(result)
1098
            mutter("using %r for stacking" % (format,))
1099
        elif source_branch is None:
1100
            # this is for sprouting a bzrdir without a branch; is that
1101
            # actually useful?
3221.11.20 by Robert Collins
Support --shallow on branch.
1102
            result_branch = result.create_branch()
3575.2.2 by Martin Pool
branch --stacked should force a stacked format
1103
        else:
1104
            result_branch = source_branch._format.initialize(result)
1105
        mutter("created new branch %r" % (result_branch,))
3242.3.28 by Aaron Bentley
Use repository acquisition policy for sprouting
1106
        repository_policy.configure_branch(result_branch)
3575.2.2 by Martin Pool
branch --stacked should force a stacked format
1107
        if source_branch is not None:
1108
            # XXX: this duplicates Branch.sprout(); it probably belongs on an
1109
            # InterBranch method? -- mbp 20080724
1110
            source_branch.copy_content_into(result_branch,
1111
                 revision_id=revision_id)
1112
            result_branch.set_parent(self.root_transport.base)
3221.18.1 by Ian Clatworthy
tweaks by ianc during review
1113
1114
        # Create/update the result working tree
2485.8.56 by Vincent Ladeuil
Fix bug #112173 and bzr branch multiple connections.
1115
        if isinstance(target_transport, LocalTransport) and (
1116
            result_repo is None or result_repo.make_working_trees()):
3136.1.3 by Aaron Bentley
Implement hard-link support for branch and checkout
1117
            wt = result.create_workingtree(accelerator_tree=accelerator_tree,
1118
                hardlink=hardlink)
2255.2.77 by Robert Collins
Tune working inventory generation more: walk the blocks, skipping deleted rows.
1119
            wt.lock_write()
1120
            try:
1121
                if wt.path2id('') is None:
3123.5.10 by Aaron Bentley
Restore old handling of set_root_id
1122
                    try:
1123
                        wt.set_root_id(self.open_workingtree.get_root_id())
1124
                    except errors.NoWorkingTree:
1125
                        pass
2255.2.77 by Robert Collins
Tune working inventory generation more: walk the blocks, skipping deleted rows.
1126
            finally:
1127
                wt.unlock()
2100.3.28 by Aaron Bentley
Make sprout recursive
1128
        else:
1129
            wt = None
1130
        if recurse == 'down':
1131
            if wt is not None:
2255.2.226 by Robert Collins
Get merge_nested finally working: change nested tree iterators to take file_ids, and ensure the right branch is connected to in the merge logic. May not be suitable for shared repositories yet.
1132
                basis = wt.basis_tree()
1133
                basis.lock_read()
1134
                subtrees = basis.iter_references()
2100.3.28 by Aaron Bentley
Make sprout recursive
1135
            elif source_branch is not None:
2255.2.226 by Robert Collins
Get merge_nested finally working: change nested tree iterators to take file_ids, and ensure the right branch is connected to in the merge logic. May not be suitable for shared repositories yet.
1136
                basis = source_branch.basis_tree()
1137
                basis.lock_read()
1138
                subtrees = basis.iter_references()
2100.3.28 by Aaron Bentley
Make sprout recursive
1139
            else:
2255.2.226 by Robert Collins
Get merge_nested finally working: change nested tree iterators to take file_ids, and ensure the right branch is connected to in the merge logic. May not be suitable for shared repositories yet.
1140
                subtrees = []
1141
                basis = None
1142
            try:
1143
                for path, file_id in subtrees:
1144
                    target = urlutils.join(url, urlutils.escape(path))
1145
                    sublocation = source_branch.reference_parent(file_id, path)
1146
                    sublocation.bzrdir.sprout(target,
1147
                        basis.get_reference_revision(file_id, path),
3221.18.1 by Ian Clatworthy
tweaks by ianc during review
1148
                        force_new_repo=force_new_repo, recurse=recurse,
3221.18.4 by Ian Clatworthy
shallow -> stacked
1149
                        stacked=stacked)
2255.2.226 by Robert Collins
Get merge_nested finally working: change nested tree iterators to take file_ids, and ensure the right branch is connected to in the merge logic. May not be suitable for shared repositories yet.
1150
            finally:
1151
                if basis is not None:
1152
                    basis.unlock()
1534.4.50 by Robert Collins
Got the bzrdir api straightened out, plenty of refactoring to use it pending, but the api is up and running.
1153
        return result
1154
1534.4.40 by Robert Collins
Add RepositoryFormats and allow bzrdir.open or create _repository to be used.
1155
1534.4.44 by Robert Collins
Make a new BzrDir format that uses a versioned branch format in a branch/ subdirectory.
1156
class BzrDirPreSplitOut(BzrDir):
1157
    """A common class for the all-in-one formats."""
1158
1534.5.3 by Robert Collins
Make format 4/5/6 branches share a single LockableFiles instance across wt/branch/repository.
1159
    def __init__(self, _transport, _format):
1160
        """See BzrDir.__init__."""
1161
        super(BzrDirPreSplitOut, self).__init__(_transport, _format)
1996.3.3 by John Arbash Meinel
Shave off another 40ms by demand loading branch and bzrdir
1162
        self._control_files = lockable_files.LockableFiles(
1163
                                            self.get_branch_transport(None),
1553.5.69 by Martin Pool
BzrDirFormat subclasses can now control what kind of overall lock is used.
1164
                                            self._format._lock_file_name,
1165
                                            self._format._lock_class)
1534.5.3 by Robert Collins
Make format 4/5/6 branches share a single LockableFiles instance across wt/branch/repository.
1166
1687.1.12 by Robert Collins
Hook in the full break-lock ui.
1167
    def break_lock(self):
1168
        """Pre-splitout bzrdirs do not suffer from stale locks."""
1169
        raise NotImplementedError(self.break_lock)
1170
3242.2.12 by Aaron Bentley
Get cloning_metadir working properly for old formats
1171
    def cloning_metadir(self):
1172
        """Produce a metadir suitable for cloning with."""
1173
        return self._format.__class__()
1174
3242.3.37 by Aaron Bentley
Updates from reviews
1175
    def clone(self, url, revision_id=None, force_new_repo=False,
1176
              preserve_stacking=False):
1177
        """See BzrDir.clone().
1178
1179
        force_new_repo has no effect, since this family of formats always
1180
        require a new repository.
1181
        preserve_stacking has no effect, since no source branch using this
1182
        family of formats can be stacked, so there is no stacking to preserve.
1183
        """
1534.4.50 by Robert Collins
Got the bzrdir api straightened out, plenty of refactoring to use it pending, but the api is up and running.
1184
        from bzrlib.workingtree import WorkingTreeFormat2
1185
        self._make_tail(url)
1651.1.6 by Martin Pool
Clean up clone-bzrdir code
1186
        result = self._format._initialize_for_clone(url)
2387.1.1 by Robert Collins
Remove the --basis parameter to clone etc. (Robert Collins)
1187
        self.open_repository().clone(result, revision_id=revision_id)
1692.7.9 by Martin Pool
Don't create broken standalone branches over sftp (Malone #43064)
1188
        from_branch = self.open_branch()
1189
        from_branch.clone(result, revision_id=revision_id)
1534.4.50 by Robert Collins
Got the bzrdir api straightened out, plenty of refactoring to use it pending, but the api is up and running.
1190
        try:
2387.1.1 by Robert Collins
Remove the --basis parameter to clone etc. (Robert Collins)
1191
            self.open_workingtree().clone(result)
1534.4.50 by Robert Collins
Got the bzrdir api straightened out, plenty of refactoring to use it pending, but the api is up and running.
1192
        except errors.NotLocalUrl:
1193
            # make a new one, this format always has to have one.
1563.2.38 by Robert Collins
make push preserve tree formats.
1194
            try:
1195
                WorkingTreeFormat2().initialize(result)
1196
            except errors.NotLocalUrl:
1692.7.9 by Martin Pool
Don't create broken standalone branches over sftp (Malone #43064)
1197
                # but we cannot do it for remote trees.
1198
                to_branch = result.open_branch()
3407.2.15 by Martin Pool
Move stub_initialize_remote away from using LockableFiles
1199
                WorkingTreeFormat2()._stub_initialize_remote(to_branch)
1534.4.50 by Robert Collins
Got the bzrdir api straightened out, plenty of refactoring to use it pending, but the api is up and running.
1200
        return result
1201
1534.4.44 by Robert Collins
Make a new BzrDir format that uses a versioned branch format in a branch/ subdirectory.
1202
    def create_branch(self):
1203
        """See BzrDir.create_branch."""
1534.4.50 by Robert Collins
Got the bzrdir api straightened out, plenty of refactoring to use it pending, but the api is up and running.
1204
        return self.open_branch()
1205
2796.2.6 by Aaron Bentley
Implement destroy_branch
1206
    def destroy_branch(self):
2796.2.16 by Aaron Bentley
Documentation updates from review
1207
        """See BzrDir.destroy_branch."""
2796.2.6 by Aaron Bentley
Implement destroy_branch
1208
        raise errors.UnsupportedOperation(self.destroy_branch, self)
1209
1534.6.1 by Robert Collins
allow API creation of shared repositories
1210
    def create_repository(self, shared=False):
1534.4.50 by Robert Collins
Got the bzrdir api straightened out, plenty of refactoring to use it pending, but the api is up and running.
1211
        """See BzrDir.create_repository."""
1534.6.1 by Robert Collins
allow API creation of shared repositories
1212
        if shared:
1213
            raise errors.IncompatibleFormat('shared repository', self._format)
1534.4.50 by Robert Collins
Got the bzrdir api straightened out, plenty of refactoring to use it pending, but the api is up and running.
1214
        return self.open_repository()
1215
2796.2.19 by Aaron Bentley
Support reconfigure --lightweight-checkout
1216
    def destroy_repository(self):
1217
        """See BzrDir.destroy_repository."""
1218
        raise errors.UnsupportedOperation(self.destroy_repository, self)
1219
3123.5.2 by Aaron Bentley
Allow checkout --files_from
1220
    def create_workingtree(self, revision_id=None, from_branch=None,
3136.1.3 by Aaron Bentley
Implement hard-link support for branch and checkout
1221
                           accelerator_tree=None, hardlink=False):
1534.4.50 by Robert Collins
Got the bzrdir api straightened out, plenty of refactoring to use it pending, but the api is up and running.
1222
        """See BzrDir.create_workingtree."""
1508.1.21 by Robert Collins
Implement -r limit for checkout command.
1223
        # this looks buggy but is not -really-
2323.6.4 by Martin Pool
BzrDir._check_supported now also takes care of recommending upgrades, which
1224
        # because this format creates the workingtree when the bzrdir is
1225
        # created
1508.1.21 by Robert Collins
Implement -r limit for checkout command.
1226
        # clone and sprout will have set the revision_id
1227
        # and that will have set it for us, its only
1228
        # specific uses of create_workingtree in isolation
1229
        # that can do wonky stuff here, and that only
1230
        # happens for creating checkouts, which cannot be 
1231
        # done on this format anyway. So - acceptable wart.
2323.6.4 by Martin Pool
BzrDir._check_supported now also takes care of recommending upgrades, which
1232
        result = self.open_workingtree(recommend_upgrade=False)
1508.1.24 by Robert Collins
Add update command for use with checkouts.
1233
        if revision_id is not None:
1996.3.12 by John Arbash Meinel
Change how 'revision' is imported to avoid problems later
1234
            if revision_id == _mod_revision.NULL_REVISION:
1551.8.20 by Aaron Bentley
Fix BzrDir.create_workingtree for NULL_REVISION
1235
                result.set_parent_ids([])
1236
            else:
1237
                result.set_parent_ids([revision_id])
1508.1.21 by Robert Collins
Implement -r limit for checkout command.
1238
        return result
1534.4.44 by Robert Collins
Make a new BzrDir format that uses a versioned branch format in a branch/ subdirectory.
1239
1551.8.37 by Aaron Bentley
Cleaner implementation of destroy_working_tree
1240
    def destroy_workingtree(self):
1551.8.36 by Aaron Bentley
Introduce BzrDir.destroy_workingtree
1241
        """See BzrDir.destroy_workingtree."""
1242
        raise errors.UnsupportedOperation(self.destroy_workingtree, self)
1243
1551.8.37 by Aaron Bentley
Cleaner implementation of destroy_working_tree
1244
    def destroy_workingtree_metadata(self):
1245
        """See BzrDir.destroy_workingtree_metadata."""
1246
        raise errors.UnsupportedOperation(self.destroy_workingtree_metadata, 
1247
                                          self)
1248
1534.4.44 by Robert Collins
Make a new BzrDir format that uses a versioned branch format in a branch/ subdirectory.
1249
    def get_branch_transport(self, branch_format):
1250
        """See BzrDir.get_branch_transport()."""
1251
        if branch_format is None:
1252
            return self.transport
1253
        try:
1254
            branch_format.get_format_string()
1255
        except NotImplementedError:
1256
            return self.transport
1257
        raise errors.IncompatibleFormat(branch_format, self._format)
1258
1534.4.47 by Robert Collins
Split out repository into .bzr/repository
1259
    def get_repository_transport(self, repository_format):
1260
        """See BzrDir.get_repository_transport()."""
1261
        if repository_format is None:
1262
            return self.transport
1263
        try:
1264
            repository_format.get_format_string()
1265
        except NotImplementedError:
1266
            return self.transport
1267
        raise errors.IncompatibleFormat(repository_format, self._format)
1268
1534.4.45 by Robert Collins
Start WorkingTree -> .bzr/checkout transition
1269
    def get_workingtree_transport(self, workingtree_format):
1270
        """See BzrDir.get_workingtree_transport()."""
1271
        if workingtree_format is None:
1272
            return self.transport
1273
        try:
1274
            workingtree_format.get_format_string()
1275
        except NotImplementedError:
1276
            return self.transport
1277
        raise errors.IncompatibleFormat(workingtree_format, self._format)
1278
1556.1.4 by Robert Collins
Add a new format for what will become knit, and the surrounding logic to upgrade repositories within metadirs, and tests for the same.
1279
    def needs_format_conversion(self, format=None):
1280
        """See BzrDir.needs_format_conversion()."""
1281
        # if the format is not the same as the system default,
1282
        # an upgrade is needed.
1283
        if format is None:
1284
            format = BzrDirFormat.get_default_format()
1285
        return not isinstance(self._format, format.__class__)
1286
1534.4.44 by Robert Collins
Make a new BzrDir format that uses a versioned branch format in a branch/ subdirectory.
1287
    def open_branch(self, unsupported=False):
1288
        """See BzrDir.open_branch."""
1289
        from bzrlib.branch import BzrBranchFormat4
1290
        format = BzrBranchFormat4()
1291
        self._check_supported(format, unsupported)
1292
        return format.open(self, _found=True)
1293
2485.8.56 by Vincent Ladeuil
Fix bug #112173 and bzr branch multiple connections.
1294
    def sprout(self, url, revision_id=None, force_new_repo=False,
3136.1.3 by Aaron Bentley
Implement hard-link support for branch and checkout
1295
               possible_transports=None, accelerator_tree=None,
3221.18.4 by Ian Clatworthy
shallow -> stacked
1296
               hardlink=False, stacked=False):
1534.4.50 by Robert Collins
Got the bzrdir api straightened out, plenty of refactoring to use it pending, but the api is up and running.
1297
        """See BzrDir.sprout()."""
3221.18.4 by Ian Clatworthy
shallow -> stacked
1298
        if stacked:
3221.13.2 by Robert Collins
Add a shallow parameter to bzrdir.sprout, which involved fixing a lateny bug in pack to pack fetching with ghost discovery.
1299
            raise errors.UnstackableBranchFormat(
1300
                self._format, self.root_transport.base)
1534.4.50 by Robert Collins
Got the bzrdir api straightened out, plenty of refactoring to use it pending, but the api is up and running.
1301
        from bzrlib.workingtree import WorkingTreeFormat2
1302
        self._make_tail(url)
1651.1.6 by Martin Pool
Clean up clone-bzrdir code
1303
        result = self._format._initialize_for_clone(url)
1534.4.50 by Robert Collins
Got the bzrdir api straightened out, plenty of refactoring to use it pending, but the api is up and running.
1304
        try:
2387.1.1 by Robert Collins
Remove the --basis parameter to clone etc. (Robert Collins)
1305
            self.open_repository().clone(result, revision_id=revision_id)
1534.4.50 by Robert Collins
Got the bzrdir api straightened out, plenty of refactoring to use it pending, but the api is up and running.
1306
        except errors.NoRepositoryPresent:
1307
            pass
1308
        try:
1309
            self.open_branch().sprout(result, revision_id=revision_id)
1310
        except errors.NotBranchError:
1311
            pass
1587.1.5 by Robert Collins
Put bzr branch behaviour back to the 0.7 ignore-working-tree state.
1312
        # we always want a working tree
3123.5.8 by Aaron Bentley
Work around double-opening lock issue
1313
        WorkingTreeFormat2().initialize(result,
3136.1.3 by Aaron Bentley
Implement hard-link support for branch and checkout
1314
                                        accelerator_tree=accelerator_tree,
1315
                                        hardlink=hardlink)
1534.4.50 by Robert Collins
Got the bzrdir api straightened out, plenty of refactoring to use it pending, but the api is up and running.
1316
        return result
1317
1534.4.44 by Robert Collins
Make a new BzrDir format that uses a versioned branch format in a branch/ subdirectory.
1318
1319
class BzrDir4(BzrDirPreSplitOut):
1508.1.25 by Robert Collins
Update per review comments.
1320
    """A .bzr version 4 control object.
1321
    
1322
    This is a deprecated format and may be removed after sept 2006.
1323
    """
1534.4.40 by Robert Collins
Add RepositoryFormats and allow bzrdir.open or create _repository to be used.
1324
1534.6.1 by Robert Collins
allow API creation of shared repositories
1325
    def create_repository(self, shared=False):
1534.4.40 by Robert Collins
Add RepositoryFormats and allow bzrdir.open or create _repository to be used.
1326
        """See BzrDir.create_repository."""
1556.1.4 by Robert Collins
Add a new format for what will become knit, and the surrounding logic to upgrade repositories within metadirs, and tests for the same.
1327
        return self._format.repository_format.initialize(self, shared)
1534.4.40 by Robert Collins
Add RepositoryFormats and allow bzrdir.open or create _repository to be used.
1328
1534.5.16 by Robert Collins
Review feedback.
1329
    def needs_format_conversion(self, format=None):
1330
        """Format 4 dirs are always in need of conversion."""
1534.5.7 by Robert Collins
Start factoring out the upgrade policy logic.
1331
        return True
1332
1534.4.40 by Robert Collins
Add RepositoryFormats and allow bzrdir.open or create _repository to be used.
1333
    def open_repository(self):
1334
        """See BzrDir.open_repository."""
2241.1.4 by Martin Pool
Moved old weave-based repository formats into bzrlib.repofmt.weaverepo.
1335
        from bzrlib.repofmt.weaverepo import RepositoryFormat4
1534.4.40 by Robert Collins
Add RepositoryFormats and allow bzrdir.open or create _repository to be used.
1336
        return RepositoryFormat4().open(self, _found=True)
1337
1338
1534.4.44 by Robert Collins
Make a new BzrDir format that uses a versioned branch format in a branch/ subdirectory.
1339
class BzrDir5(BzrDirPreSplitOut):
1508.1.25 by Robert Collins
Update per review comments.
1340
    """A .bzr version 5 control object.
1341
1342
    This is a deprecated format and may be removed after sept 2006.
1343
    """
1534.4.40 by Robert Collins
Add RepositoryFormats and allow bzrdir.open or create _repository to be used.
1344
1345
    def open_repository(self):
1346
        """See BzrDir.open_repository."""
2241.1.4 by Martin Pool
Moved old weave-based repository formats into bzrlib.repofmt.weaverepo.
1347
        from bzrlib.repofmt.weaverepo import RepositoryFormat5
1534.4.40 by Robert Collins
Add RepositoryFormats and allow bzrdir.open or create _repository to be used.
1348
        return RepositoryFormat5().open(self, _found=True)
1349
2323.6.4 by Martin Pool
BzrDir._check_supported now also takes care of recommending upgrades, which
1350
    def open_workingtree(self, _unsupported=False,
1351
            recommend_upgrade=True):
1534.4.42 by Robert Collins
add working tree to the BzrDir facilities.
1352
        """See BzrDir.create_workingtree."""
1353
        from bzrlib.workingtree import WorkingTreeFormat2
2323.6.4 by Martin Pool
BzrDir._check_supported now also takes care of recommending upgrades, which
1354
        wt_format = WorkingTreeFormat2()
1355
        # we don't warn here about upgrades; that ought to be handled for the
1356
        # bzrdir as a whole
1357
        return wt_format.open(self, _found=True)
1534.4.42 by Robert Collins
add working tree to the BzrDir facilities.
1358
1534.4.40 by Robert Collins
Add RepositoryFormats and allow bzrdir.open or create _repository to be used.
1359
1534.4.44 by Robert Collins
Make a new BzrDir format that uses a versioned branch format in a branch/ subdirectory.
1360
class BzrDir6(BzrDirPreSplitOut):
1508.1.25 by Robert Collins
Update per review comments.
1361
    """A .bzr version 6 control object.
1362
1363
    This is a deprecated format and may be removed after sept 2006.
1364
    """
1534.4.40 by Robert Collins
Add RepositoryFormats and allow bzrdir.open or create _repository to be used.
1365
1534.4.44 by Robert Collins
Make a new BzrDir format that uses a versioned branch format in a branch/ subdirectory.
1366
    def open_repository(self):
1367
        """See BzrDir.open_repository."""
2241.1.4 by Martin Pool
Moved old weave-based repository formats into bzrlib.repofmt.weaverepo.
1368
        from bzrlib.repofmt.weaverepo import RepositoryFormat6
1534.4.44 by Robert Collins
Make a new BzrDir format that uses a versioned branch format in a branch/ subdirectory.
1369
        return RepositoryFormat6().open(self, _found=True)
1370
2323.6.4 by Martin Pool
BzrDir._check_supported now also takes care of recommending upgrades, which
1371
    def open_workingtree(self, _unsupported=False,
1372
        recommend_upgrade=True):
1534.4.44 by Robert Collins
Make a new BzrDir format that uses a versioned branch format in a branch/ subdirectory.
1373
        """See BzrDir.create_workingtree."""
2323.6.4 by Martin Pool
BzrDir._check_supported now also takes care of recommending upgrades, which
1374
        # we don't warn here about upgrades; that ought to be handled for the
1375
        # bzrdir as a whole
1534.4.44 by Robert Collins
Make a new BzrDir format that uses a versioned branch format in a branch/ subdirectory.
1376
        from bzrlib.workingtree import WorkingTreeFormat2
1377
        return WorkingTreeFormat2().open(self, _found=True)
1378
1379
1380
class BzrDirMeta1(BzrDir):
1381
    """A .bzr meta version 1 control object.
1382
    
1383
    This is the first control object where the 
1553.5.67 by Martin Pool
doc
1384
    individual aspects are really split out: there are separate repository,
1385
    workingtree and branch subdirectories and any subset of the three can be
1386
    present within a BzrDir.
1534.4.44 by Robert Collins
Make a new BzrDir format that uses a versioned branch format in a branch/ subdirectory.
1387
    """
1388
1534.5.16 by Robert Collins
Review feedback.
1389
    def can_convert_format(self):
1390
        """See BzrDir.can_convert_format()."""
1556.1.4 by Robert Collins
Add a new format for what will become knit, and the surrounding logic to upgrade repositories within metadirs, and tests for the same.
1391
        return True
1534.5.10 by Robert Collins
Make upgrade driver unaware of the specific formats in play.
1392
1534.4.41 by Robert Collins
Branch now uses BzrDir reasonably sanely.
1393
    def create_branch(self):
1394
        """See BzrDir.create_branch."""
2230.3.55 by Aaron Bentley
Updates from review
1395
        return self._format.get_branch_format().initialize(self)
1534.4.41 by Robert Collins
Branch now uses BzrDir reasonably sanely.
1396
2796.2.6 by Aaron Bentley
Implement destroy_branch
1397
    def destroy_branch(self):
1398
        """See BzrDir.create_branch."""
1399
        self.transport.delete_tree('branch')
1400
1534.6.1 by Robert Collins
allow API creation of shared repositories
1401
    def create_repository(self, shared=False):
1534.4.40 by Robert Collins
Add RepositoryFormats and allow bzrdir.open or create _repository to be used.
1402
        """See BzrDir.create_repository."""
1556.1.4 by Robert Collins
Add a new format for what will become knit, and the surrounding logic to upgrade repositories within metadirs, and tests for the same.
1403
        return self._format.repository_format.initialize(self, shared)
1534.4.40 by Robert Collins
Add RepositoryFormats and allow bzrdir.open or create _repository to be used.
1404
2796.2.19 by Aaron Bentley
Support reconfigure --lightweight-checkout
1405
    def destroy_repository(self):
1406
        """See BzrDir.destroy_repository."""
1407
        self.transport.delete_tree('repository')
1408
3123.5.2 by Aaron Bentley
Allow checkout --files_from
1409
    def create_workingtree(self, revision_id=None, from_branch=None,
3136.1.3 by Aaron Bentley
Implement hard-link support for branch and checkout
1410
                           accelerator_tree=None, hardlink=False):
1534.4.42 by Robert Collins
add working tree to the BzrDir facilities.
1411
        """See BzrDir.create_workingtree."""
2955.5.3 by Vincent Ladeuil
Fix second unwanted connection by providing the right branch to create_checkout.
1412
        return self._format.workingtree_format.initialize(
3123.5.2 by Aaron Bentley
Allow checkout --files_from
1413
            self, revision_id, from_branch=from_branch,
3136.1.3 by Aaron Bentley
Implement hard-link support for branch and checkout
1414
            accelerator_tree=accelerator_tree, hardlink=hardlink)
1534.4.42 by Robert Collins
add working tree to the BzrDir facilities.
1415
1551.8.37 by Aaron Bentley
Cleaner implementation of destroy_working_tree
1416
    def destroy_workingtree(self):
1551.8.36 by Aaron Bentley
Introduce BzrDir.destroy_workingtree
1417
        """See BzrDir.destroy_workingtree."""
2323.6.4 by Martin Pool
BzrDir._check_supported now also takes care of recommending upgrades, which
1418
        wt = self.open_workingtree(recommend_upgrade=False)
1551.8.37 by Aaron Bentley
Cleaner implementation of destroy_working_tree
1419
        repository = wt.branch.repository
2094.3.5 by John Arbash Meinel
Fix imports to ensure modules are loaded before they are used
1420
        empty = repository.revision_tree(_mod_revision.NULL_REVISION)
2748.3.2 by Aaron Bentley
Fix revert, remove-tree, and various tests to use None for 'no files specified'
1421
        wt.revert(old_tree=empty)
1551.8.37 by Aaron Bentley
Cleaner implementation of destroy_working_tree
1422
        self.destroy_workingtree_metadata()
1423
1424
    def destroy_workingtree_metadata(self):
1425
        self.transport.delete_tree('checkout')
1551.8.36 by Aaron Bentley
Introduce BzrDir.destroy_workingtree
1426
2414.2.1 by Andrew Bennetts
Some miscellaneous new APIs, tests and other changes from the hpss branch.
1427
    def find_branch_format(self):
1428
        """Find the branch 'format' for this bzrdir.
1429
1430
        This might be a synthetic object for e.g. RemoteBranch and SVN.
1431
        """
1432
        from bzrlib.branch import BranchFormat
1433
        return BranchFormat.find_format(self)
1434
1666.1.4 by Robert Collins
* 'Metadir' is now the default disk format. This improves behaviour in
1435
    def _get_mkdir_mode(self):
1436
        """Figure out the mode to use when creating a bzrdir subdir."""
1996.3.3 by John Arbash Meinel
Shave off another 40ms by demand loading branch and bzrdir
1437
        temp_control = lockable_files.LockableFiles(self.transport, '',
1438
                                     lockable_files.TransportLock)
1666.1.4 by Robert Collins
* 'Metadir' is now the default disk format. This improves behaviour in
1439
        return temp_control._dir_mode
1440
2414.2.1 by Andrew Bennetts
Some miscellaneous new APIs, tests and other changes from the hpss branch.
1441
    def get_branch_reference(self):
1442
        """See BzrDir.get_branch_reference()."""
1443
        from bzrlib.branch import BranchFormat
1444
        format = BranchFormat.find_format(self)
1445
        return format.get_reference(self)
1446
1534.4.44 by Robert Collins
Make a new BzrDir format that uses a versioned branch format in a branch/ subdirectory.
1447
    def get_branch_transport(self, branch_format):
1448
        """See BzrDir.get_branch_transport()."""
1449
        if branch_format is None:
1450
            return self.transport.clone('branch')
1451
        try:
1452
            branch_format.get_format_string()
1453
        except NotImplementedError:
1454
            raise errors.IncompatibleFormat(branch_format, self._format)
1455
        try:
1666.1.4 by Robert Collins
* 'Metadir' is now the default disk format. This improves behaviour in
1456
            self.transport.mkdir('branch', mode=self._get_mkdir_mode())
1534.4.44 by Robert Collins
Make a new BzrDir format that uses a versioned branch format in a branch/ subdirectory.
1457
        except errors.FileExists:
1458
            pass
1459
        return self.transport.clone('branch')
1460
1534.4.47 by Robert Collins
Split out repository into .bzr/repository
1461
    def get_repository_transport(self, repository_format):
1462
        """See BzrDir.get_repository_transport()."""
1463
        if repository_format is None:
1464
            return self.transport.clone('repository')
1465
        try:
1466
            repository_format.get_format_string()
1467
        except NotImplementedError:
1468
            raise errors.IncompatibleFormat(repository_format, self._format)
1469
        try:
1666.1.4 by Robert Collins
* 'Metadir' is now the default disk format. This improves behaviour in
1470
            self.transport.mkdir('repository', mode=self._get_mkdir_mode())
1534.4.47 by Robert Collins
Split out repository into .bzr/repository
1471
        except errors.FileExists:
1472
            pass
1473
        return self.transport.clone('repository')
1474
1534.4.45 by Robert Collins
Start WorkingTree -> .bzr/checkout transition
1475
    def get_workingtree_transport(self, workingtree_format):
1476
        """See BzrDir.get_workingtree_transport()."""
1477
        if workingtree_format is None:
1478
            return self.transport.clone('checkout')
1479
        try:
1480
            workingtree_format.get_format_string()
1481
        except NotImplementedError:
1482
            raise errors.IncompatibleFormat(workingtree_format, self._format)
1483
        try:
1666.1.4 by Robert Collins
* 'Metadir' is now the default disk format. This improves behaviour in
1484
            self.transport.mkdir('checkout', mode=self._get_mkdir_mode())
1534.4.45 by Robert Collins
Start WorkingTree -> .bzr/checkout transition
1485
        except errors.FileExists:
1486
            pass
1487
        return self.transport.clone('checkout')
1488
1534.5.16 by Robert Collins
Review feedback.
1489
    def needs_format_conversion(self, format=None):
1490
        """See BzrDir.needs_format_conversion()."""
1556.1.4 by Robert Collins
Add a new format for what will become knit, and the surrounding logic to upgrade repositories within metadirs, and tests for the same.
1491
        if format is None:
1492
            format = BzrDirFormat.get_default_format()
1493
        if not isinstance(self._format, format.__class__):
1494
            # it is not a meta dir format, conversion is needed.
1495
            return True
1496
        # we might want to push this down to the repository?
1497
        try:
1498
            if not isinstance(self.open_repository()._format,
1499
                              format.repository_format.__class__):
1500
                # the repository needs an upgrade.
1501
                return True
1502
        except errors.NoRepositoryPresent:
1503
            pass
2230.3.29 by Aaron Bentley
Implement conversion to branch 6
1504
        try:
1505
            if not isinstance(self.open_branch()._format,
2230.3.55 by Aaron Bentley
Updates from review
1506
                              format.get_branch_format().__class__):
2255.12.1 by Robert Collins
Implement upgrade for working trees.
1507
                # the branch needs an upgrade.
1508
                return True
1509
        except errors.NotBranchError:
1510
            pass
1511
        try:
2323.6.4 by Martin Pool
BzrDir._check_supported now also takes care of recommending upgrades, which
1512
            my_wt = self.open_workingtree(recommend_upgrade=False)
1513
            if not isinstance(my_wt._format,
2255.12.1 by Robert Collins
Implement upgrade for working trees.
1514
                              format.workingtree_format.__class__):
1515
                # the workingtree needs an upgrade.
1516
                return True
2255.2.196 by Robert Collins
Fix test_upgrade defects related to non local or absent working trees.
1517
        except (errors.NoWorkingTree, errors.NotLocalUrl):
2255.12.1 by Robert Collins
Implement upgrade for working trees.
1518
            pass
1534.5.10 by Robert Collins
Make upgrade driver unaware of the specific formats in play.
1519
        return False
1520
1534.4.44 by Robert Collins
Make a new BzrDir format that uses a versioned branch format in a branch/ subdirectory.
1521
    def open_branch(self, unsupported=False):
1534.4.41 by Robert Collins
Branch now uses BzrDir reasonably sanely.
1522
        """See BzrDir.open_branch."""
2414.2.1 by Andrew Bennetts
Some miscellaneous new APIs, tests and other changes from the hpss branch.
1523
        format = self.find_branch_format()
1534.4.44 by Robert Collins
Make a new BzrDir format that uses a versioned branch format in a branch/ subdirectory.
1524
        self._check_supported(format, unsupported)
1525
        return format.open(self, _found=True)
1534.4.41 by Robert Collins
Branch now uses BzrDir reasonably sanely.
1526
1534.4.47 by Robert Collins
Split out repository into .bzr/repository
1527
    def open_repository(self, unsupported=False):
1534.4.40 by Robert Collins
Add RepositoryFormats and allow bzrdir.open or create _repository to be used.
1528
        """See BzrDir.open_repository."""
1534.4.47 by Robert Collins
Split out repository into .bzr/repository
1529
        from bzrlib.repository import RepositoryFormat
1530
        format = RepositoryFormat.find_format(self)
1531
        self._check_supported(format, unsupported)
1532
        return format.open(self, _found=True)
1534.4.40 by Robert Collins
Add RepositoryFormats and allow bzrdir.open or create _repository to be used.
1533
2323.6.4 by Martin Pool
BzrDir._check_supported now also takes care of recommending upgrades, which
1534
    def open_workingtree(self, unsupported=False,
1535
            recommend_upgrade=True):
1508.1.21 by Robert Collins
Implement -r limit for checkout command.
1536
        """See BzrDir.open_workingtree."""
1534.4.46 by Robert Collins
Nearly complete .bzr/checkout splitout.
1537
        from bzrlib.workingtree import WorkingTreeFormat
1538
        format = WorkingTreeFormat.find_format(self)
2323.6.4 by Martin Pool
BzrDir._check_supported now also takes care of recommending upgrades, which
1539
        self._check_supported(format, unsupported,
1540
            recommend_upgrade,
2323.6.5 by Martin Pool
Recommended-upgrade message should give base dir not the control dir url
1541
            basedir=self.root_transport.base)
1534.4.46 by Robert Collins
Nearly complete .bzr/checkout splitout.
1542
        return format.open(self, _found=True)
1534.4.42 by Robert Collins
add working tree to the BzrDir facilities.
1543
3242.1.1 by Aaron Bentley
Implement BzrDir configuration
1544
    def _get_config(self):
3242.3.14 by Aaron Bentley
Make BzrDirConfig use TransportConfig
1545
        return config.BzrDirConfig(self.transport)
3242.1.1 by Aaron Bentley
Implement BzrDir configuration
1546
1534.4.39 by Robert Collins
Basic BzrDir support.
1547
1548
class BzrDirFormat(object):
1549
    """An encapsulation of the initialization and open routines for a format.
1550
1551
    Formats provide three things:
1552
     * An initialization routine,
1553
     * a format string,
1554
     * an open routine.
1555
2830.1.1 by Ian Clatworthy
bzrdir.py code clean-ups
1556
    Formats are placed in a dict by their format string for reference 
1534.4.39 by Robert Collins
Basic BzrDir support.
1557
    during bzrdir opening. These should be subclasses of BzrDirFormat
1558
    for consistency.
1559
1560
    Once a format is deprecated, just deprecate the initialize and open
1561
    methods on the format class. Do not deprecate the object, as the 
1562
    object will be created every system load.
1563
    """
1564
1565
    _default_format = None
1534.4.40 by Robert Collins
Add RepositoryFormats and allow bzrdir.open or create _repository to be used.
1566
    """The default format used for new .bzr dirs."""
1534.4.39 by Robert Collins
Basic BzrDir support.
1567
1568
    _formats = {}
1569
    """The known formats."""
1570
1733.1.7 by Jelmer Vernooij
Change set of control dir formats to list.
1571
    _control_formats = []
1733.1.6 by Jelmer Vernooij
Fix a couple of minor issues after review by Martin.
1572
    """The registered control formats - .bzr, ....
1573
    
1733.1.7 by Jelmer Vernooij
Change set of control dir formats to list.
1574
    This is a list of BzrDirFormat objects.
1733.1.6 by Jelmer Vernooij
Fix a couple of minor issues after review by Martin.
1575
    """
1733.1.1 by Robert Collins
Support non '.bzr' control directories in bzrdir.
1576
2018.5.169 by Andrew Bennetts
Add a _server_formats flag to BzrDir.open_from_transport and BzrDirFormat.find_format, make RemoteBranch.control_files into a property.
1577
    _control_server_formats = []
1578
    """The registered control server formats, e.g. RemoteBzrDirs.
1579
1580
    This is a list of BzrDirFormat objects.
1581
    """
1582
1553.5.69 by Martin Pool
BzrDirFormat subclasses can now control what kind of overall lock is used.
1583
    _lock_file_name = 'branch-lock'
1584
1585
    # _lock_class must be set in subclasses to the lock type, typ.
1586
    # TransportLock or LockDir
1587
1534.4.39 by Robert Collins
Basic BzrDir support.
1588
    @classmethod
2018.5.169 by Andrew Bennetts
Add a _server_formats flag to BzrDir.open_from_transport and BzrDirFormat.find_format, make RemoteBranch.control_files into a property.
1589
    def find_format(klass, transport, _server_formats=True):
1733.1.1 by Robert Collins
Support non '.bzr' control directories in bzrdir.
1590
        """Return the format present at transport."""
2018.5.169 by Andrew Bennetts
Add a _server_formats flag to BzrDir.open_from_transport and BzrDirFormat.find_format, make RemoteBranch.control_files into a property.
1591
        if _server_formats:
1592
            formats = klass._control_server_formats + klass._control_formats
1593
        else:
1594
            formats = klass._control_formats
1595
        for format in formats:
1733.1.1 by Robert Collins
Support non '.bzr' control directories in bzrdir.
1596
            try:
1597
                return format.probe_transport(transport)
1598
            except errors.NotBranchError:
1599
                # this format does not find a control dir here.
1600
                pass
1601
        raise errors.NotBranchError(path=transport.base)
1602
1603
    @classmethod
1604
    def probe_transport(klass, transport):
1752.2.52 by Andrew Bennetts
Flesh out more Remote* methods needed to open and initialise remote branches/trees/repositories.
1605
        """Return the .bzrdir style format present in a directory."""
1534.4.39 by Robert Collins
Basic BzrDir support.
1606
        try:
2164.2.18 by Vincent Ladeuil
Take Aaron comments into account.
1607
            format_string = transport.get(".bzr/branch-format").read()
1733.2.3 by Michael Ellerman
Don't coallesce try blocks, it can lead to confusing exceptions.
1608
        except errors.NoSuchFile:
1609
            raise errors.NotBranchError(path=transport.base)
1610
1611
        try:
1534.4.39 by Robert Collins
Basic BzrDir support.
1612
            return klass._formats[format_string]
1613
        except KeyError:
3246.3.2 by Daniel Watkins
Modified uses of errors.UnknownFormatError.
1614
            raise errors.UnknownFormatError(format=format_string, kind='bzrdir')
1534.4.39 by Robert Collins
Basic BzrDir support.
1615
1616
    @classmethod
1617
    def get_default_format(klass):
1618
        """Return the current default format."""
1619
        return klass._default_format
1620
1621
    def get_format_string(self):
1622
        """Return the ASCII format string that identifies this format."""
1623
        raise NotImplementedError(self.get_format_string)
1624
1624.3.19 by Olaf Conradi
New call get_format_description to give a user-friendly description of a
1625
    def get_format_description(self):
1626
        """Return the short description for this format."""
1627
        raise NotImplementedError(self.get_format_description)
1628
1534.5.16 by Robert Collins
Review feedback.
1629
    def get_converter(self, format=None):
1630
        """Return the converter to use to convert bzrdirs needing converts.
1534.5.10 by Robert Collins
Make upgrade driver unaware of the specific formats in play.
1631
1632
        This returns a bzrlib.bzrdir.Converter object.
1633
1634
        This should return the best upgrader to step this format towards the
1759.2.1 by Jelmer Vernooij
Fix some types (found using aspell).
1635
        current default format. In the case of plugins we can/should provide
1534.5.10 by Robert Collins
Make upgrade driver unaware of the specific formats in play.
1636
        some means for them to extend the range of returnable converters.
1534.5.13 by Robert Collins
Correct buggy test.
1637
1759.2.1 by Jelmer Vernooij
Fix some types (found using aspell).
1638
        :param format: Optional format to override the default format of the 
1534.5.13 by Robert Collins
Correct buggy test.
1639
                       library.
1534.5.10 by Robert Collins
Make upgrade driver unaware of the specific formats in play.
1640
        """
1534.5.16 by Robert Collins
Review feedback.
1641
        raise NotImplementedError(self.get_converter)
1534.5.10 by Robert Collins
Make upgrade driver unaware of the specific formats in play.
1642
2476.3.8 by Vincent Ladeuil
Mark transports that need to be instrumented or refactored to check
1643
    def initialize(self, url, possible_transports=None):
1608.2.8 by Martin Pool
Separate out BzrDir.initialize_on_transport so it
1644
        """Create a bzr control dir at this url and return an opened copy.
1645
        
1646
        Subclasses should typically override initialize_on_transport
1647
        instead of this method.
1648
        """
2476.3.8 by Vincent Ladeuil
Mark transports that need to be instrumented or refactored to check
1649
        return self.initialize_on_transport(get_transport(url,
1650
                                                          possible_transports))
1608.2.8 by Martin Pool
Separate out BzrDir.initialize_on_transport so it
1651
1651.1.6 by Martin Pool
Clean up clone-bzrdir code
1652
    def initialize_on_transport(self, transport):
1608.2.8 by Martin Pool
Separate out BzrDir.initialize_on_transport so it
1653
        """Initialize a new bzrdir in the base directory of a Transport."""
1759.2.1 by Jelmer Vernooij
Fix some types (found using aspell).
1654
        # Since we don't have a .bzr directory, inherit the
1534.4.39 by Robert Collins
Basic BzrDir support.
1655
        # mode from the root directory
1996.3.3 by John Arbash Meinel
Shave off another 40ms by demand loading branch and bzrdir
1656
        temp_control = lockable_files.LockableFiles(transport,
1657
                            '', lockable_files.TransportLock)
1534.4.39 by Robert Collins
Basic BzrDir support.
1658
        temp_control._transport.mkdir('.bzr',
1759.2.2 by Jelmer Vernooij
Revert some of my spelling fixes and fix some typos after review by Aaron.
1659
                                      # FIXME: RBC 20060121 don't peek under
1534.4.39 by Robert Collins
Basic BzrDir support.
1660
                                      # the covers
1661
                                      mode=temp_control._dir_mode)
3023.1.1 by Alexander Belchenko
Mark .bzr directories as "hidden" on Windows (#71147)
1662
        if sys.platform == 'win32' and isinstance(transport, LocalTransport):
3023.1.2 by Alexander Belchenko
Martin's review.
1663
            win32utils.set_file_attr_hidden(transport._abspath('.bzr'))
1534.4.39 by Robert Collins
Basic BzrDir support.
1664
        file_mode = temp_control._file_mode
1665
        del temp_control
3407.2.5 by Martin Pool
Deprecate LockableFiles.put_utf8
1666
        bzrdir_transport = transport.clone('.bzr')
1667
        utf8_files = [('README',
3250.2.1 by Marius Kruger
update .bzr/README to not refer to Bazaar-NG, and add link to website.
1668
                       "This is a Bazaar control directory.\n"
1669
                       "Do not change any files in this directory.\n"
1670
                       "See http://bazaar-vcs.org/ for more information about Bazaar.\n"),
1534.4.39 by Robert Collins
Basic BzrDir support.
1671
                      ('branch-format', self.get_format_string()),
1672
                      ]
1673
        # NB: no need to escape relative paths that are url safe.
3407.2.5 by Martin Pool
Deprecate LockableFiles.put_utf8
1674
        control_files = lockable_files.LockableFiles(bzrdir_transport,
1675
            self._lock_file_name, self._lock_class)
1553.5.60 by Martin Pool
New LockableFiles.create_lock() method
1676
        control_files.create_lock()
1534.4.39 by Robert Collins
Basic BzrDir support.
1677
        control_files.lock_write()
1678
        try:
3407.2.5 by Martin Pool
Deprecate LockableFiles.put_utf8
1679
            for (filename, content) in utf8_files:
3407.2.12 by Martin Pool
Fix creation mode of control files
1680
                bzrdir_transport.put_bytes(filename, content,
1681
                    mode=file_mode)
1534.4.39 by Robert Collins
Basic BzrDir support.
1682
        finally:
1683
            control_files.unlock()
1608.2.8 by Martin Pool
Separate out BzrDir.initialize_on_transport so it
1684
        return self.open(transport, _found=True)
1534.4.39 by Robert Collins
Basic BzrDir support.
1685
1686
    def is_supported(self):
1687
        """Is this format supported?
1688
1689
        Supported formats must be initializable and openable.
1690
        Unsupported formats may not support initialization or committing or 
1691
        some other features depending on the reason for not being supported.
1692
        """
1693
        return True
1694
1910.2.14 by Aaron Bentley
Fail when trying to use interrepository on Knit2 and Knit1
1695
    def same_model(self, target_format):
1696
        return (self.repository_format.rich_root_data == 
1697
            target_format.rich_root_data)
1698
1733.1.3 by Robert Collins
Extend the test suite to run bzrdir conformance tests on non .bzr based control dirs.
1699
    @classmethod
1700
    def known_formats(klass):
1701
        """Return all the known formats.
1702
        
1703
        Concrete formats should override _known_formats.
1704
        """
1733.1.6 by Jelmer Vernooij
Fix a couple of minor issues after review by Martin.
1705
        # There is double indirection here to make sure that control 
1706
        # formats used by more than one dir format will only be probed 
1707
        # once. This can otherwise be quite expensive for remote connections.
1733.1.3 by Robert Collins
Extend the test suite to run bzrdir conformance tests on non .bzr based control dirs.
1708
        result = set()
1709
        for format in klass._control_formats:
1710
            result.update(format._known_formats())
1711
        return result
1712
    
1713
    @classmethod
1714
    def _known_formats(klass):
1715
        """Return the known format instances for this control format."""
1716
        return set(klass._formats.values())
1717
1534.4.39 by Robert Collins
Basic BzrDir support.
1718
    def open(self, transport, _found=False):
1719
        """Return an instance of this format for the dir transport points at.
1720
        
1721
        _found is a private parameter, do not use it.
1722
        """
1723
        if not _found:
2090.2.2 by Martin Pool
Fix an assertion with side effects
1724
            found_format = BzrDirFormat.find_format(transport)
1725
            if not isinstance(found_format, self.__class__):
1726
                raise AssertionError("%s was asked to open %s, but it seems to need "
1727
                        "format %s" 
1728
                        % (self, transport, found_format))
1534.4.40 by Robert Collins
Add RepositoryFormats and allow bzrdir.open or create _repository to be used.
1729
        return self._open(transport)
1730
1731
    def _open(self, transport):
1732
        """Template method helper for opening BzrDirectories.
1733
1734
        This performs the actual open and any additional logic or parameter
1735
        passing.
1736
        """
1737
        raise NotImplementedError(self._open)
1534.4.39 by Robert Collins
Basic BzrDir support.
1738
1739
    @classmethod
1740
    def register_format(klass, format):
1741
        klass._formats[format.get_format_string()] = format
1742
1743
    @classmethod
1733.1.1 by Robert Collins
Support non '.bzr' control directories in bzrdir.
1744
    def register_control_format(klass, format):
2164.2.13 by v.ladeuil+lp at free
Add tests for redirection. Preserve transport decorations.
1745
        """Register a format that does not use '.bzr' for its control dir.
1733.1.1 by Robert Collins
Support non '.bzr' control directories in bzrdir.
1746
1747
        TODO: This should be pulled up into a 'ControlDirFormat' base class
1748
        which BzrDirFormat can inherit from, and renamed to register_format 
1749
        there. It has been done without that for now for simplicity of
1750
        implementation.
1751
        """
1733.1.7 by Jelmer Vernooij
Change set of control dir formats to list.
1752
        klass._control_formats.append(format)
1733.1.1 by Robert Collins
Support non '.bzr' control directories in bzrdir.
1753
1754
    @classmethod
2018.5.163 by Andrew Bennetts
Deal with various review comments from Robert.
1755
    def register_control_server_format(klass, format):
1756
        """Register a control format for client-server environments.
1757
1758
        These formats will be tried before ones registered with
1759
        register_control_format.  This gives implementations that decide to the
1760
        chance to grab it before anything looks at the contents of the format
1761
        file.
1762
        """
2018.5.169 by Andrew Bennetts
Add a _server_formats flag to BzrDir.open_from_transport and BzrDirFormat.find_format, make RemoteBranch.control_files into a property.
1763
        klass._control_server_formats.append(format)
2018.5.163 by Andrew Bennetts
Deal with various review comments from Robert.
1764
1765
    @classmethod
2204.4.13 by Aaron Bentley
Update all test cases to avoid set_default_format
1766
    def _set_default_format(klass, format):
1767
        """Set default format (for testing behavior of defaults only)"""
1768
        klass._default_format = format
1769
1534.5.1 by Robert Collins
Give info some reasonable output and tests.
1770
    def __str__(self):
2830.1.1 by Ian Clatworthy
bzrdir.py code clean-ups
1771
        # Trim the newline
1772
        return self.get_format_string().rstrip()
1534.5.1 by Robert Collins
Give info some reasonable output and tests.
1773
1534.4.39 by Robert Collins
Basic BzrDir support.
1774
    @classmethod
1775
    def unregister_format(klass, format):
1776
        del klass._formats[format.get_format_string()]
1777
1733.1.1 by Robert Collins
Support non '.bzr' control directories in bzrdir.
1778
    @classmethod
1779
    def unregister_control_format(klass, format):
1780
        klass._control_formats.remove(format)
1781
1782
1534.4.39 by Robert Collins
Basic BzrDir support.
1783
class BzrDirFormat4(BzrDirFormat):
1784
    """Bzr dir format 4.
1785
1786
    This format is a combined format for working tree, branch and repository.
1787
    It has:
1534.4.50 by Robert Collins
Got the bzrdir api straightened out, plenty of refactoring to use it pending, but the api is up and running.
1788
     - Format 1 working trees [always]
1789
     - Format 4 branches [always]
1790
     - Format 4 repositories [always]
1534.4.39 by Robert Collins
Basic BzrDir support.
1791
1792
    This format is deprecated: it indexes texts using a text it which is
1793
    removed in format 5; write support for this format has been removed.
1794
    """
1795
1996.3.3 by John Arbash Meinel
Shave off another 40ms by demand loading branch and bzrdir
1796
    _lock_class = lockable_files.TransportLock
1553.5.69 by Martin Pool
BzrDirFormat subclasses can now control what kind of overall lock is used.
1797
1534.4.39 by Robert Collins
Basic BzrDir support.
1798
    def get_format_string(self):
1799
        """See BzrDirFormat.get_format_string()."""
1800
        return "Bazaar-NG branch, format 0.0.4\n"
1801
1624.3.19 by Olaf Conradi
New call get_format_description to give a user-friendly description of a
1802
    def get_format_description(self):
1803
        """See BzrDirFormat.get_format_description()."""
1804
        return "All-in-one format 4"
1805
1534.5.16 by Robert Collins
Review feedback.
1806
    def get_converter(self, format=None):
1807
        """See BzrDirFormat.get_converter()."""
1534.5.13 by Robert Collins
Correct buggy test.
1808
        # there is one and only one upgrade path here.
1534.5.10 by Robert Collins
Make upgrade driver unaware of the specific formats in play.
1809
        return ConvertBzrDir4To5()
1810
        
1651.1.6 by Martin Pool
Clean up clone-bzrdir code
1811
    def initialize_on_transport(self, transport):
1534.4.39 by Robert Collins
Basic BzrDir support.
1812
        """Format 4 branches cannot be created."""
1813
        raise errors.UninitializableFormat(self)
1814
1815
    def is_supported(self):
1816
        """Format 4 is not supported.
1817
1818
        It is not supported because the model changed from 4 to 5 and the
1819
        conversion logic is expensive - so doing it on the fly was not 
1820
        feasible.
1821
        """
1822
        return False
1823
1534.4.40 by Robert Collins
Add RepositoryFormats and allow bzrdir.open or create _repository to be used.
1824
    def _open(self, transport):
1825
        """See BzrDirFormat._open."""
1826
        return BzrDir4(transport, self)
1827
1556.1.4 by Robert Collins
Add a new format for what will become knit, and the surrounding logic to upgrade repositories within metadirs, and tests for the same.
1828
    def __return_repository_format(self):
1829
        """Circular import protection."""
2241.1.4 by Martin Pool
Moved old weave-based repository formats into bzrlib.repofmt.weaverepo.
1830
        from bzrlib.repofmt.weaverepo import RepositoryFormat4
1910.2.12 by Aaron Bentley
Implement knit repo format 2
1831
        return RepositoryFormat4()
1556.1.4 by Robert Collins
Add a new format for what will become knit, and the surrounding logic to upgrade repositories within metadirs, and tests for the same.
1832
    repository_format = property(__return_repository_format)
1833
1534.4.39 by Robert Collins
Basic BzrDir support.
1834
1835
class BzrDirFormat5(BzrDirFormat):
1836
    """Bzr control format 5.
1837
1838
    This format is a combined format for working tree, branch and repository.
1839
    It has:
1534.4.50 by Robert Collins
Got the bzrdir api straightened out, plenty of refactoring to use it pending, but the api is up and running.
1840
     - Format 2 working trees [always] 
1841
     - Format 4 branches [always] 
1534.4.53 by Robert Collins
Review feedback from John Meinel.
1842
     - Format 5 repositories [always]
1534.4.50 by Robert Collins
Got the bzrdir api straightened out, plenty of refactoring to use it pending, but the api is up and running.
1843
       Unhashed stores in the repository.
1534.4.39 by Robert Collins
Basic BzrDir support.
1844
    """
1845
1996.3.3 by John Arbash Meinel
Shave off another 40ms by demand loading branch and bzrdir
1846
    _lock_class = lockable_files.TransportLock
1553.5.69 by Martin Pool
BzrDirFormat subclasses can now control what kind of overall lock is used.
1847
1534.4.39 by Robert Collins
Basic BzrDir support.
1848
    def get_format_string(self):
1849
        """See BzrDirFormat.get_format_string()."""
1850
        return "Bazaar-NG branch, format 5\n"
1851
1624.3.19 by Olaf Conradi
New call get_format_description to give a user-friendly description of a
1852
    def get_format_description(self):
1853
        """See BzrDirFormat.get_format_description()."""
1854
        return "All-in-one format 5"
1855
1534.5.16 by Robert Collins
Review feedback.
1856
    def get_converter(self, format=None):
1857
        """See BzrDirFormat.get_converter()."""
1534.5.13 by Robert Collins
Correct buggy test.
1858
        # there is one and only one upgrade path here.
1534.5.10 by Robert Collins
Make upgrade driver unaware of the specific formats in play.
1859
        return ConvertBzrDir5To6()
1651.1.6 by Martin Pool
Clean up clone-bzrdir code
1860
1861
    def _initialize_for_clone(self, url):
1862
        return self.initialize_on_transport(get_transport(url), _cloning=True)
1534.5.10 by Robert Collins
Make upgrade driver unaware of the specific formats in play.
1863
        
1608.2.8 by Martin Pool
Separate out BzrDir.initialize_on_transport so it
1864
    def initialize_on_transport(self, transport, _cloning=False):
1534.4.50 by Robert Collins
Got the bzrdir api straightened out, plenty of refactoring to use it pending, but the api is up and running.
1865
        """Format 5 dirs always have working tree, branch and repository.
1866
        
1867
        Except when they are being cloned.
1868
        """
1869
        from bzrlib.branch import BzrBranchFormat4
2241.1.4 by Martin Pool
Moved old weave-based repository formats into bzrlib.repofmt.weaverepo.
1870
        from bzrlib.repofmt.weaverepo import RepositoryFormat5
1534.4.50 by Robert Collins
Got the bzrdir api straightened out, plenty of refactoring to use it pending, but the api is up and running.
1871
        from bzrlib.workingtree import WorkingTreeFormat2
1651.1.6 by Martin Pool
Clean up clone-bzrdir code
1872
        result = (super(BzrDirFormat5, self).initialize_on_transport(transport))
1534.4.50 by Robert Collins
Got the bzrdir api straightened out, plenty of refactoring to use it pending, but the api is up and running.
1873
        RepositoryFormat5().initialize(result, _internal=True)
1874
        if not _cloning:
1910.5.1 by Andrew Bennetts
Make some old formats create at least a stub working tree rather than incomplete bzrdirs, and change some tests to use the test suite transport rather than hard-coded to local-only.
1875
            branch = BzrBranchFormat4().initialize(result)
1876
            try:
1877
                WorkingTreeFormat2().initialize(result)
1878
            except errors.NotLocalUrl:
1879
                # Even though we can't access the working tree, we need to
1880
                # create its control files.
3407.2.15 by Martin Pool
Move stub_initialize_remote away from using LockableFiles
1881
                WorkingTreeFormat2()._stub_initialize_remote(branch)
1534.4.50 by Robert Collins
Got the bzrdir api straightened out, plenty of refactoring to use it pending, but the api is up and running.
1882
        return result
1883
1534.4.40 by Robert Collins
Add RepositoryFormats and allow bzrdir.open or create _repository to be used.
1884
    def _open(self, transport):
1885
        """See BzrDirFormat._open."""
1886
        return BzrDir5(transport, self)
1887
1556.1.4 by Robert Collins
Add a new format for what will become knit, and the surrounding logic to upgrade repositories within metadirs, and tests for the same.
1888
    def __return_repository_format(self):
1889
        """Circular import protection."""
2241.1.4 by Martin Pool
Moved old weave-based repository formats into bzrlib.repofmt.weaverepo.
1890
        from bzrlib.repofmt.weaverepo import RepositoryFormat5
1910.2.12 by Aaron Bentley
Implement knit repo format 2
1891
        return RepositoryFormat5()
1556.1.4 by Robert Collins
Add a new format for what will become knit, and the surrounding logic to upgrade repositories within metadirs, and tests for the same.
1892
    repository_format = property(__return_repository_format)
1893
1534.4.39 by Robert Collins
Basic BzrDir support.
1894
1895
class BzrDirFormat6(BzrDirFormat):
1896
    """Bzr control format 6.
1897
1898
    This format is a combined format for working tree, branch and repository.
1899
    It has:
1534.4.50 by Robert Collins
Got the bzrdir api straightened out, plenty of refactoring to use it pending, but the api is up and running.
1900
     - Format 2 working trees [always] 
1901
     - Format 4 branches [always] 
1902
     - Format 6 repositories [always]
1534.4.39 by Robert Collins
Basic BzrDir support.
1903
    """
1904
1996.3.3 by John Arbash Meinel
Shave off another 40ms by demand loading branch and bzrdir
1905
    _lock_class = lockable_files.TransportLock
1553.5.69 by Martin Pool
BzrDirFormat subclasses can now control what kind of overall lock is used.
1906
1534.4.39 by Robert Collins
Basic BzrDir support.
1907
    def get_format_string(self):
1908
        """See BzrDirFormat.get_format_string()."""
1909
        return "Bazaar-NG branch, format 6\n"
1910
1624.3.19 by Olaf Conradi
New call get_format_description to give a user-friendly description of a
1911
    def get_format_description(self):
1912
        """See BzrDirFormat.get_format_description()."""
1913
        return "All-in-one format 6"
1914
1534.5.16 by Robert Collins
Review feedback.
1915
    def get_converter(self, format=None):
1916
        """See BzrDirFormat.get_converter()."""
1534.5.13 by Robert Collins
Correct buggy test.
1917
        # there is one and only one upgrade path here.
1534.5.10 by Robert Collins
Make upgrade driver unaware of the specific formats in play.
1918
        return ConvertBzrDir6ToMeta()
1919
        
1651.1.6 by Martin Pool
Clean up clone-bzrdir code
1920
    def _initialize_for_clone(self, url):
1921
        return self.initialize_on_transport(get_transport(url), _cloning=True)
1922
1608.2.8 by Martin Pool
Separate out BzrDir.initialize_on_transport so it
1923
    def initialize_on_transport(self, transport, _cloning=False):
1534.4.50 by Robert Collins
Got the bzrdir api straightened out, plenty of refactoring to use it pending, but the api is up and running.
1924
        """Format 6 dirs always have working tree, branch and repository.
1925
        
1926
        Except when they are being cloned.
1927
        """
1928
        from bzrlib.branch import BzrBranchFormat4
2241.1.4 by Martin Pool
Moved old weave-based repository formats into bzrlib.repofmt.weaverepo.
1929
        from bzrlib.repofmt.weaverepo import RepositoryFormat6
1534.4.50 by Robert Collins
Got the bzrdir api straightened out, plenty of refactoring to use it pending, but the api is up and running.
1930
        from bzrlib.workingtree import WorkingTreeFormat2
1651.1.6 by Martin Pool
Clean up clone-bzrdir code
1931
        result = super(BzrDirFormat6, self).initialize_on_transport(transport)
1534.4.50 by Robert Collins
Got the bzrdir api straightened out, plenty of refactoring to use it pending, but the api is up and running.
1932
        RepositoryFormat6().initialize(result, _internal=True)
1933
        if not _cloning:
1910.5.1 by Andrew Bennetts
Make some old formats create at least a stub working tree rather than incomplete bzrdirs, and change some tests to use the test suite transport rather than hard-coded to local-only.
1934
            branch = BzrBranchFormat4().initialize(result)
1534.4.50 by Robert Collins
Got the bzrdir api straightened out, plenty of refactoring to use it pending, but the api is up and running.
1935
            try:
1936
                WorkingTreeFormat2().initialize(result)
1937
            except errors.NotLocalUrl:
1910.5.1 by Andrew Bennetts
Make some old formats create at least a stub working tree rather than incomplete bzrdirs, and change some tests to use the test suite transport rather than hard-coded to local-only.
1938
                # Even though we can't access the working tree, we need to
1939
                # create its control files.
3407.2.15 by Martin Pool
Move stub_initialize_remote away from using LockableFiles
1940
                WorkingTreeFormat2()._stub_initialize_remote(branch)
1534.4.50 by Robert Collins
Got the bzrdir api straightened out, plenty of refactoring to use it pending, but the api is up and running.
1941
        return result
1942
1534.4.40 by Robert Collins
Add RepositoryFormats and allow bzrdir.open or create _repository to be used.
1943
    def _open(self, transport):
1944
        """See BzrDirFormat._open."""
1945
        return BzrDir6(transport, self)
1946
1556.1.4 by Robert Collins
Add a new format for what will become knit, and the surrounding logic to upgrade repositories within metadirs, and tests for the same.
1947
    def __return_repository_format(self):
1948
        """Circular import protection."""
2241.1.4 by Martin Pool
Moved old weave-based repository formats into bzrlib.repofmt.weaverepo.
1949
        from bzrlib.repofmt.weaverepo import RepositoryFormat6
1910.2.12 by Aaron Bentley
Implement knit repo format 2
1950
        return RepositoryFormat6()
1556.1.4 by Robert Collins
Add a new format for what will become knit, and the surrounding logic to upgrade repositories within metadirs, and tests for the same.
1951
    repository_format = property(__return_repository_format)
1952
1534.4.39 by Robert Collins
Basic BzrDir support.
1953
1534.4.44 by Robert Collins
Make a new BzrDir format that uses a versioned branch format in a branch/ subdirectory.
1954
class BzrDirMetaFormat1(BzrDirFormat):
1955
    """Bzr meta control format 1
1956
1957
    This is the first format with split out working tree, branch and repository
1958
    disk storage.
1959
    It has:
1534.4.50 by Robert Collins
Got the bzrdir api straightened out, plenty of refactoring to use it pending, but the api is up and running.
1960
     - Format 3 working trees [optional]
1961
     - Format 5 branches [optional]
1962
     - Format 7 repositories [optional]
1534.4.44 by Robert Collins
Make a new BzrDir format that uses a versioned branch format in a branch/ subdirectory.
1963
    """
1964
1996.3.3 by John Arbash Meinel
Shave off another 40ms by demand loading branch and bzrdir
1965
    _lock_class = lockdir.LockDir
1553.5.69 by Martin Pool
BzrDirFormat subclasses can now control what kind of overall lock is used.
1966
2100.3.10 by Aaron Bentley
Ensure added references are serialized properly, beef up Workingtreee3
1967
    def __init__(self):
1968
        self._workingtree_format = None
2230.3.1 by Aaron Bentley
Get branch6 creation working
1969
        self._branch_format = None
2100.3.10 by Aaron Bentley
Ensure added references are serialized properly, beef up Workingtreee3
1970
2100.3.15 by Aaron Bentley
get test suite passing
1971
    def __eq__(self, other):
1972
        if other.__class__ is not self.__class__:
1973
            return False
1974
        if other.repository_format != self.repository_format:
1975
            return False
1976
        if other.workingtree_format != self.workingtree_format:
1977
            return False
1978
        return True
1979
2100.3.35 by Aaron Bentley
equality operations on bzrdir
1980
    def __ne__(self, other):
1981
        return not self == other
1982
2230.3.55 by Aaron Bentley
Updates from review
1983
    def get_branch_format(self):
2230.3.1 by Aaron Bentley
Get branch6 creation working
1984
        if self._branch_format is None:
1985
            from bzrlib.branch import BranchFormat
1986
            self._branch_format = BranchFormat.get_default_format()
1987
        return self._branch_format
1988
2230.3.55 by Aaron Bentley
Updates from review
1989
    def set_branch_format(self, format):
2230.3.1 by Aaron Bentley
Get branch6 creation working
1990
        self._branch_format = format
1991
1556.1.4 by Robert Collins
Add a new format for what will become knit, and the surrounding logic to upgrade repositories within metadirs, and tests for the same.
1992
    def get_converter(self, format=None):
1993
        """See BzrDirFormat.get_converter()."""
1994
        if format is None:
1995
            format = BzrDirFormat.get_default_format()
1996
        if not isinstance(self, format.__class__):
1997
            # converting away from metadir is not implemented
1998
            raise NotImplementedError(self.get_converter)
1999
        return ConvertMetaToMeta(format)
2000
1534.4.44 by Robert Collins
Make a new BzrDir format that uses a versioned branch format in a branch/ subdirectory.
2001
    def get_format_string(self):
2002
        """See BzrDirFormat.get_format_string()."""
2003
        return "Bazaar-NG meta directory, format 1\n"
2004
1624.3.19 by Olaf Conradi
New call get_format_description to give a user-friendly description of a
2005
    def get_format_description(self):
2006
        """See BzrDirFormat.get_format_description()."""
2007
        return "Meta directory format 1"
2008
1534.4.44 by Robert Collins
Make a new BzrDir format that uses a versioned branch format in a branch/ subdirectory.
2009
    def _open(self, transport):
2010
        """See BzrDirFormat._open."""
2230.3.24 by Aaron Bentley
Remove format-on-open code
2011
        return BzrDirMeta1(transport, self)
1534.4.44 by Robert Collins
Make a new BzrDir format that uses a versioned branch format in a branch/ subdirectory.
2012
1556.1.4 by Robert Collins
Add a new format for what will become knit, and the surrounding logic to upgrade repositories within metadirs, and tests for the same.
2013
    def __return_repository_format(self):
2014
        """Circular import protection."""
2015
        if getattr(self, '_repository_format', None):
2016
            return self._repository_format
2017
        from bzrlib.repository import RepositoryFormat
2018
        return RepositoryFormat.get_default_format()
2019
2020
    def __set_repository_format(self, value):
3015.2.8 by Robert Collins
Typo in __set_repository_format's docstring.
2021
        """Allow changing the repository format for metadir formats."""
1556.1.4 by Robert Collins
Add a new format for what will become knit, and the surrounding logic to upgrade repositories within metadirs, and tests for the same.
2022
        self._repository_format = value
1553.5.72 by Martin Pool
Clean up test for Branch5 lockdirs
2023
1556.1.4 by Robert Collins
Add a new format for what will become knit, and the surrounding logic to upgrade repositories within metadirs, and tests for the same.
2024
    repository_format = property(__return_repository_format, __set_repository_format)
2025
2100.3.10 by Aaron Bentley
Ensure added references are serialized properly, beef up Workingtreee3
2026
    def __get_workingtree_format(self):
2027
        if self._workingtree_format is None:
2028
            from bzrlib.workingtree import WorkingTreeFormat
2029
            self._workingtree_format = WorkingTreeFormat.get_default_format()
2030
        return self._workingtree_format
2031
2032
    def __set_workingtree_format(self, wt_format):
2033
        self._workingtree_format = wt_format
2034
2035
    workingtree_format = property(__get_workingtree_format,
2036
                                  __set_workingtree_format)
2037
1534.4.44 by Robert Collins
Make a new BzrDir format that uses a versioned branch format in a branch/ subdirectory.
2038
2164.2.19 by Vincent Ladeuil
Revert BzrDirFormat1 registering.
2039
# Register bzr control format
2040
BzrDirFormat.register_control_format(BzrDirFormat)
2164.2.13 by v.ladeuil+lp at free
Add tests for redirection. Preserve transport decorations.
2041
2042
# Register bzr formats
1534.4.39 by Robert Collins
Basic BzrDir support.
2043
BzrDirFormat.register_format(BzrDirFormat4())
2044
BzrDirFormat.register_format(BzrDirFormat5())
1666.1.4 by Robert Collins
* 'Metadir' is now the default disk format. This improves behaviour in
2045
BzrDirFormat.register_format(BzrDirFormat6())
2046
__default_format = BzrDirMetaFormat1()
1534.4.39 by Robert Collins
Basic BzrDir support.
2047
BzrDirFormat.register_format(__default_format)
2204.4.13 by Aaron Bentley
Update all test cases to avoid set_default_format
2048
BzrDirFormat._default_format = __default_format
1534.4.39 by Robert Collins
Basic BzrDir support.
2049
2050
1534.5.7 by Robert Collins
Start factoring out the upgrade policy logic.
2051
class Converter(object):
2052
    """Converts a disk format object from one format to another."""
2053
1534.5.10 by Robert Collins
Make upgrade driver unaware of the specific formats in play.
2054
    def convert(self, to_convert, pb):
2055
        """Perform the conversion of to_convert, giving feedback via pb.
1534.5.7 by Robert Collins
Start factoring out the upgrade policy logic.
2056
1534.5.10 by Robert Collins
Make upgrade driver unaware of the specific formats in play.
2057
        :param to_convert: The disk object to convert.
1534.5.7 by Robert Collins
Start factoring out the upgrade policy logic.
2058
        :param pb: a progress bar to use for progress information.
2059
        """
2060
1556.1.4 by Robert Collins
Add a new format for what will become knit, and the surrounding logic to upgrade repositories within metadirs, and tests for the same.
2061
    def step(self, message):
2062
        """Update the pb by a step."""
2063
        self.count +=1
2064
        self.pb.update(message, self.count, self.total)
2065
1534.5.7 by Robert Collins
Start factoring out the upgrade policy logic.
2066
2067
class ConvertBzrDir4To5(Converter):
2068
    """Converts format 4 bzr dirs to format 5."""
2069
1534.5.10 by Robert Collins
Make upgrade driver unaware of the specific formats in play.
2070
    def __init__(self):
2071
        super(ConvertBzrDir4To5, self).__init__()
1534.5.7 by Robert Collins
Start factoring out the upgrade policy logic.
2072
        self.converted_revs = set()
2073
        self.absent_revisions = set()
2074
        self.text_count = 0
2075
        self.revisions = {}
2076
        
1534.5.10 by Robert Collins
Make upgrade driver unaware of the specific formats in play.
2077
    def convert(self, to_convert, pb):
1534.5.7 by Robert Collins
Start factoring out the upgrade policy logic.
2078
        """See Converter.convert()."""
1534.5.10 by Robert Collins
Make upgrade driver unaware of the specific formats in play.
2079
        self.bzrdir = to_convert
2080
        self.pb = pb
1534.5.7 by Robert Collins
Start factoring out the upgrade policy logic.
2081
        self.pb.note('starting upgrade from format 4 to 5')
2082
        if isinstance(self.bzrdir.transport, LocalTransport):
2083
            self.bzrdir.get_workingtree_transport(None).delete('stat-cache')
2084
        self._convert_to_weaves()
2085
        return BzrDir.open(self.bzrdir.root_transport.base)
2086
2087
    def _convert_to_weaves(self):
2088
        self.pb.note('note: upgrade may be faster if all store files are ungzipped first')
2089
        try:
2090
            # TODO permissions
2091
            stat = self.bzrdir.transport.stat('weaves')
2092
            if not S_ISDIR(stat.st_mode):
2093
                self.bzrdir.transport.delete('weaves')
2094
                self.bzrdir.transport.mkdir('weaves')
2095
        except errors.NoSuchFile:
2096
            self.bzrdir.transport.mkdir('weaves')
1563.2.10 by Robert Collins
Change weave store to be a versioned store, using WeaveFiles which maintain integrity without needing explicit 'put' operations.
2097
        # deliberately not a WeaveFile as we want to build it up slowly.
1534.5.7 by Robert Collins
Start factoring out the upgrade policy logic.
2098
        self.inv_weave = Weave('inventory')
2099
        # holds in-memory weaves for all files
2100
        self.text_weaves = {}
2101
        self.bzrdir.transport.delete('branch-format')
2102
        self.branch = self.bzrdir.open_branch()
2103
        self._convert_working_inv()
2104
        rev_history = self.branch.revision_history()
2105
        # to_read is a stack holding the revisions we still need to process;
2106
        # appending to it adds new highest-priority revisions
2107
        self.known_revisions = set(rev_history)
2108
        self.to_read = rev_history[-1:]
2109
        while self.to_read:
2110
            rev_id = self.to_read.pop()
2111
            if (rev_id not in self.revisions
2112
                and rev_id not in self.absent_revisions):
2113
                self._load_one_rev(rev_id)
2114
        self.pb.clear()
2115
        to_import = self._make_order()
2116
        for i, rev_id in enumerate(to_import):
2117
            self.pb.update('converting revision', i, len(to_import))
2118
            self._convert_one_rev(rev_id)
2119
        self.pb.clear()
2120
        self._write_all_weaves()
2121
        self._write_all_revs()
2122
        self.pb.note('upgraded to weaves:')
2123
        self.pb.note('  %6d revisions and inventories', len(self.revisions))
2124
        self.pb.note('  %6d revisions not present', len(self.absent_revisions))
2125
        self.pb.note('  %6d texts', self.text_count)
2126
        self._cleanup_spare_files_after_format4()
3407.2.13 by Martin Pool
Remove indirection through control_files to get transports
2127
        self.branch._transport.put_bytes(
3407.2.5 by Martin Pool
Deprecate LockableFiles.put_utf8
2128
            'branch-format',
2129
            BzrDirFormat5().get_format_string(),
3446.1.1 by Martin Pool
merge further LockableFile deprecations
2130
            mode=self.bzrdir._get_file_mode())
1534.5.7 by Robert Collins
Start factoring out the upgrade policy logic.
2131
2132
    def _cleanup_spare_files_after_format4(self):
2133
        # FIXME working tree upgrade foo.
2134
        for n in 'merged-patches', 'pending-merged-patches':
2135
            try:
2136
                ## assert os.path.getsize(p) == 0
2137
                self.bzrdir.transport.delete(n)
2138
            except errors.NoSuchFile:
2139
                pass
2140
        self.bzrdir.transport.delete_tree('inventory-store')
2141
        self.bzrdir.transport.delete_tree('text-store')
2142
2143
    def _convert_working_inv(self):
1996.3.6 by John Arbash Meinel
Find a few places that weren't importing their dependencies.
2144
        inv = xml4.serializer_v4.read_inventory(
3407.2.1 by Martin Pool
Deprecate LockableFiles.get
2145
                self.branch._transport.get('inventory'))
2817.2.1 by Robert Collins
* Inventory serialisation no longer double-sha's the content.
2146
        new_inv_xml = xml5.serializer_v5.write_inventory_to_string(inv, working=True)
3407.2.1 by Martin Pool
Deprecate LockableFiles.get
2147
        self.branch._transport.put_bytes('inventory', new_inv_xml,
3446.1.1 by Martin Pool
merge further LockableFile deprecations
2148
            mode=self.bzrdir._get_file_mode())
1534.5.7 by Robert Collins
Start factoring out the upgrade policy logic.
2149
2150
    def _write_all_weaves(self):
2151
        controlweaves = WeaveStore(self.bzrdir.transport, prefixed=False)
2152
        weave_transport = self.bzrdir.transport.clone('weaves')
2153
        weaves = WeaveStore(weave_transport, prefixed=False)
1563.2.34 by Robert Collins
Remove the commit and rollback transaction methods as misleading, and implement a WriteTransaction
2154
        transaction = WriteTransaction()
1534.5.7 by Robert Collins
Start factoring out the upgrade policy logic.
2155
2156
        try:
1563.2.10 by Robert Collins
Change weave store to be a versioned store, using WeaveFiles which maintain integrity without needing explicit 'put' operations.
2157
            i = 0
1534.5.7 by Robert Collins
Start factoring out the upgrade policy logic.
2158
            for file_id, file_weave in self.text_weaves.items():
2159
                self.pb.update('writing weave', i, len(self.text_weaves))
1563.2.10 by Robert Collins
Change weave store to be a versioned store, using WeaveFiles which maintain integrity without needing explicit 'put' operations.
2160
                weaves._put_weave(file_id, file_weave, transaction)
1534.5.7 by Robert Collins
Start factoring out the upgrade policy logic.
2161
                i += 1
1563.2.10 by Robert Collins
Change weave store to be a versioned store, using WeaveFiles which maintain integrity without needing explicit 'put' operations.
2162
            self.pb.update('inventory', 0, 1)
2163
            controlweaves._put_weave('inventory', self.inv_weave, transaction)
2164
            self.pb.update('inventory', 1, 1)
1534.5.7 by Robert Collins
Start factoring out the upgrade policy logic.
2165
        finally:
2166
            self.pb.clear()
2167
2168
    def _write_all_revs(self):
2169
        """Write all revisions out in new form."""
2170
        self.bzrdir.transport.delete_tree('revision-store')
2171
        self.bzrdir.transport.mkdir('revision-store')
2172
        revision_transport = self.bzrdir.transport.clone('revision-store')
2173
        # TODO permissions
3350.6.4 by Robert Collins
First cut at pluralised VersionedFiles. Some rather massive API incompatabilities, primarily because of the difficulty of coherence among competing stores.
2174
        from bzrlib.xml5 import serializer_v5
3350.6.10 by Martin Pool
VersionedFiles review cleanups
2175
        from bzrlib.repofmt.weaverepo import RevisionTextStore
3350.6.4 by Robert Collins
First cut at pluralised VersionedFiles. Some rather massive API incompatabilities, primarily because of the difficulty of coherence among competing stores.
2176
        revision_store = RevisionTextStore(revision_transport,
2177
            serializer_v5, False, versionedfile.PrefixMapper(),
2178
            lambda:True, lambda:True)
1534.5.7 by Robert Collins
Start factoring out the upgrade policy logic.
2179
        try:
2180
            for i, rev_id in enumerate(self.converted_revs):
2181
                self.pb.update('write revision', i, len(self.converted_revs))
3350.6.4 by Robert Collins
First cut at pluralised VersionedFiles. Some rather massive API incompatabilities, primarily because of the difficulty of coherence among competing stores.
2182
                text = serializer_v5.write_revision_to_string(
2183
                    self.revisions[rev_id])
2184
                key = (rev_id,)
2185
                revision_store.add_lines(key, None, osutils.split_lines(text))
1534.5.7 by Robert Collins
Start factoring out the upgrade policy logic.
2186
        finally:
2187
            self.pb.clear()
2188
            
2189
    def _load_one_rev(self, rev_id):
2190
        """Load a revision object into memory.
2191
2192
        Any parents not either loaded or abandoned get queued to be
2193
        loaded."""
2194
        self.pb.update('loading revision',
2195
                       len(self.revisions),
2196
                       len(self.known_revisions))
1563.2.22 by Robert Collins
Move responsibility for repository.has_revision into RevisionStore
2197
        if not self.branch.repository.has_revision(rev_id):
1534.5.7 by Robert Collins
Start factoring out the upgrade policy logic.
2198
            self.pb.clear()
2199
            self.pb.note('revision {%s} not present in branch; '
2200
                         'will be converted as a ghost',
2201
                         rev_id)
2202
            self.absent_revisions.add(rev_id)
2203
        else:
3350.6.4 by Robert Collins
First cut at pluralised VersionedFiles. Some rather massive API incompatabilities, primarily because of the difficulty of coherence among competing stores.
2204
            rev = self.branch.repository.get_revision(rev_id)
1534.5.7 by Robert Collins
Start factoring out the upgrade policy logic.
2205
            for parent_id in rev.parent_ids:
2206
                self.known_revisions.add(parent_id)
2207
                self.to_read.append(parent_id)
2208
            self.revisions[rev_id] = rev
2209
2210
    def _load_old_inventory(self, rev_id):
2211
        old_inv_xml = self.branch.repository.inventory_store.get(rev_id).read()
1996.3.6 by John Arbash Meinel
Find a few places that weren't importing their dependencies.
2212
        inv = xml4.serializer_v4.read_inventory_from_string(old_inv_xml)
1910.2.36 by Aaron Bentley
Get upgrade from format4 under test and fixed for all formats
2213
        inv.revision_id = rev_id
1534.5.7 by Robert Collins
Start factoring out the upgrade policy logic.
2214
        rev = self.revisions[rev_id]
2215
        return inv
2216
2217
    def _load_updated_inventory(self, rev_id):
2218
        inv_xml = self.inv_weave.get_text(rev_id)
3169.2.2 by Robert Collins
Add a test to Repository.deserialise_inventory that the resulting ivnentory is the one asked for, and update relevant tests. Also tweak the model 1 to 2 regenerate inventories logic to use the revision trees parent marker which is more accurate in some cases.
2219
        inv = xml5.serializer_v5.read_inventory_from_string(inv_xml, rev_id)
1534.5.7 by Robert Collins
Start factoring out the upgrade policy logic.
2220
        return inv
2221
2222
    def _convert_one_rev(self, rev_id):
2223
        """Convert revision and all referenced objects to new format."""
2224
        rev = self.revisions[rev_id]
2225
        inv = self._load_old_inventory(rev_id)
2226
        present_parents = [p for p in rev.parent_ids
2227
                           if p not in self.absent_revisions]
2228
        self._convert_revision_contents(rev, inv, present_parents)
2817.2.1 by Robert Collins
* Inventory serialisation no longer double-sha's the content.
2229
        self._store_new_inv(rev, inv, present_parents)
1534.5.7 by Robert Collins
Start factoring out the upgrade policy logic.
2230
        self.converted_revs.add(rev_id)
2231
2817.2.1 by Robert Collins
* Inventory serialisation no longer double-sha's the content.
2232
    def _store_new_inv(self, rev, inv, present_parents):
1996.3.6 by John Arbash Meinel
Find a few places that weren't importing their dependencies.
2233
        new_inv_xml = xml5.serializer_v5.write_inventory_to_string(inv)
1534.5.7 by Robert Collins
Start factoring out the upgrade policy logic.
2234
        new_inv_sha1 = sha_string(new_inv_xml)
2817.2.1 by Robert Collins
* Inventory serialisation no longer double-sha's the content.
2235
        self.inv_weave.add_lines(rev.revision_id,
1563.2.28 by Robert Collins
Add total_size to the revision_store api.
2236
                                 present_parents,
2237
                                 new_inv_xml.splitlines(True))
1534.5.7 by Robert Collins
Start factoring out the upgrade policy logic.
2238
        rev.inventory_sha1 = new_inv_sha1
2239
2240
    def _convert_revision_contents(self, rev, inv, present_parents):
2241
        """Convert all the files within a revision.
2242
2243
        Also upgrade the inventory to refer to the text revision ids."""
2244
        rev_id = rev.revision_id
2245
        mutter('converting texts of revision {%s}',
2246
               rev_id)
2247
        parent_invs = map(self._load_updated_inventory, present_parents)
1731.1.62 by Aaron Bentley
Changes from review comments
2248
        entries = inv.iter_entries()
2249
        entries.next()
2250
        for path, ie in entries:
1534.5.7 by Robert Collins
Start factoring out the upgrade policy logic.
2251
            self._convert_file_version(rev, ie, parent_invs)
2252
2253
    def _convert_file_version(self, rev, ie, parent_invs):
2254
        """Convert one version of one file.
2255
2256
        The file needs to be added into the weave if it is a merge
2257
        of >=2 parents or if it's changed from its parent.
2258
        """
2259
        file_id = ie.file_id
2260
        rev_id = rev.revision_id
2261
        w = self.text_weaves.get(file_id)
2262
        if w is None:
2263
            w = Weave(file_id)
2264
            self.text_weaves[file_id] = w
2265
        text_changed = False
2776.1.5 by Robert Collins
Add reasonably comprehensive tests for path last modified and per file graph behaviour.
2266
        parent_candiate_entries = ie.parent_candidates(parent_invs)
2267
        heads = graph.Graph(self).heads(parent_candiate_entries.keys())
2268
        # XXX: Note that this is unordered - and this is tolerable because 
2269
        # the previous code was also unordered.
2270
        previous_entries = dict((head, parent_candiate_entries[head]) for head
2271
            in heads)
1534.5.7 by Robert Collins
Start factoring out the upgrade policy logic.
2272
        self.snapshot_ie(previous_entries, ie, w, rev_id)
2273
        del ie.text_id
2274
3099.3.7 by John Arbash Meinel
Another parent provider I didn't realize existed.
2275
    @symbol_versioning.deprecated_method(symbol_versioning.one_one)
2776.1.5 by Robert Collins
Add reasonably comprehensive tests for path last modified and per file graph behaviour.
2276
    def get_parents(self, revision_ids):
2277
        for revision_id in revision_ids:
2278
            yield self.revisions[revision_id].parent_ids
2279
3099.3.7 by John Arbash Meinel
Another parent provider I didn't realize existed.
2280
    def get_parent_map(self, revision_ids):
2281
        """See graph._StackedParentsProvider.get_parent_map"""
2282
        return dict((revision_id, self.revisions[revision_id])
2283
                    for revision_id in revision_ids
2284
                     if revision_id in self.revisions)
2285
1534.5.7 by Robert Collins
Start factoring out the upgrade policy logic.
2286
    def snapshot_ie(self, previous_revisions, ie, w, rev_id):
2287
        # TODO: convert this logic, which is ~= snapshot to
2288
        # a call to:. This needs the path figured out. rather than a work_tree
2289
        # a v4 revision_tree can be given, or something that looks enough like
2290
        # one to give the file content to the entry if it needs it.
2291
        # and we need something that looks like a weave store for snapshot to 
2292
        # save against.
2293
        #ie.snapshot(rev, PATH, previous_revisions, REVISION_TREE, InMemoryWeaveStore(self.text_weaves))
2294
        if len(previous_revisions) == 1:
2295
            previous_ie = previous_revisions.values()[0]
2296
            if ie._unchanged(previous_ie):
2297
                ie.revision = previous_ie.revision
2298
                return
2299
        if ie.has_text():
3350.6.4 by Robert Collins
First cut at pluralised VersionedFiles. Some rather massive API incompatabilities, primarily because of the difficulty of coherence among competing stores.
2300
            text = self.branch.repository._text_store.get(ie.text_id)
1534.5.7 by Robert Collins
Start factoring out the upgrade policy logic.
2301
            file_lines = text.readlines()
1563.2.18 by Robert Collins
get knit repositories really using knits for text storage.
2302
            w.add_lines(rev_id, previous_revisions, file_lines)
1534.5.7 by Robert Collins
Start factoring out the upgrade policy logic.
2303
            self.text_count += 1
2304
        else:
1563.2.18 by Robert Collins
get knit repositories really using knits for text storage.
2305
            w.add_lines(rev_id, previous_revisions, [])
1534.5.7 by Robert Collins
Start factoring out the upgrade policy logic.
2306
        ie.revision = rev_id
2307
2308
    def _make_order(self):
2309
        """Return a suitable order for importing revisions.
2310
2311
        The order must be such that an revision is imported after all
2312
        its (present) parents.
2313
        """
2314
        todo = set(self.revisions.keys())
2315
        done = self.absent_revisions.copy()
1534.5.11 by Robert Collins
Implement upgrades to Metaformat trees.
2316
        order = []
1534.5.7 by Robert Collins
Start factoring out the upgrade policy logic.
2317
        while todo:
2318
            # scan through looking for a revision whose parents
2319
            # are all done
2320
            for rev_id in sorted(list(todo)):
2321
                rev = self.revisions[rev_id]
2322
                parent_ids = set(rev.parent_ids)
2323
                if parent_ids.issubset(done):
2324
                    # can take this one now
1534.5.11 by Robert Collins
Implement upgrades to Metaformat trees.
2325
                    order.append(rev_id)
1534.5.7 by Robert Collins
Start factoring out the upgrade policy logic.
2326
                    todo.remove(rev_id)
2327
                    done.add(rev_id)
1534.5.11 by Robert Collins
Implement upgrades to Metaformat trees.
2328
        return order
1534.5.7 by Robert Collins
Start factoring out the upgrade policy logic.
2329
2330
2331
class ConvertBzrDir5To6(Converter):
2332
    """Converts format 5 bzr dirs to format 6."""
2333
1534.5.10 by Robert Collins
Make upgrade driver unaware of the specific formats in play.
2334
    def convert(self, to_convert, pb):
2335
        """See Converter.convert()."""
1534.5.7 by Robert Collins
Start factoring out the upgrade policy logic.
2336
        self.bzrdir = to_convert
1534.5.10 by Robert Collins
Make upgrade driver unaware of the specific formats in play.
2337
        self.pb = pb
1534.5.7 by Robert Collins
Start factoring out the upgrade policy logic.
2338
        self.pb.note('starting upgrade from format 5 to 6')
2339
        self._convert_to_prefixed()
2340
        return BzrDir.open(self.bzrdir.root_transport.base)
2341
2342
    def _convert_to_prefixed(self):
1608.2.1 by Martin Pool
[merge] Storage filename escaping
2343
        from bzrlib.store import TransportStore
1534.5.7 by Robert Collins
Start factoring out the upgrade policy logic.
2344
        self.bzrdir.transport.delete('branch-format')
2345
        for store_name in ["weaves", "revision-store"]:
1608.2.1 by Martin Pool
[merge] Storage filename escaping
2346
            self.pb.note("adding prefixes to %s" % store_name)
1534.5.7 by Robert Collins
Start factoring out the upgrade policy logic.
2347
            store_transport = self.bzrdir.transport.clone(store_name)
1608.2.1 by Martin Pool
[merge] Storage filename escaping
2348
            store = TransportStore(store_transport, prefixed=True)
1608.1.1 by Martin Pool
[patch] LocalTransport.list_dir should return url-quoted strings (ddaa)
2349
            for urlfilename in store_transport.list_dir('.'):
1685.1.45 by John Arbash Meinel
Moved url functions into bzrlib.urlutils
2350
                filename = urlutils.unescape(urlfilename)
1534.5.7 by Robert Collins
Start factoring out the upgrade policy logic.
2351
                if (filename.endswith(".weave") or
2352
                    filename.endswith(".gz") or
2353
                    filename.endswith(".sig")):
3350.6.1 by Robert Collins
* New ``versionedfile.KeyMapper`` interface to abstract out the access to
2354
                    file_id, suffix = os.path.splitext(filename)
1534.5.7 by Robert Collins
Start factoring out the upgrade policy logic.
2355
                else:
2356
                    file_id = filename
3350.6.1 by Robert Collins
* New ``versionedfile.KeyMapper`` interface to abstract out the access to
2357
                    suffix = ''
2358
                new_name = store._mapper.map((file_id,)) + suffix
1534.5.7 by Robert Collins
Start factoring out the upgrade policy logic.
2359
                # FIXME keep track of the dirs made RBC 20060121
2360
                try:
3350.6.1 by Robert Collins
* New ``versionedfile.KeyMapper`` interface to abstract out the access to
2361
                    store_transport.move(filename, new_name)
1534.5.7 by Robert Collins
Start factoring out the upgrade policy logic.
2362
                except errors.NoSuchFile: # catches missing dirs strangely enough
3350.6.1 by Robert Collins
* New ``versionedfile.KeyMapper`` interface to abstract out the access to
2363
                    store_transport.mkdir(osutils.dirname(new_name))
2364
                    store_transport.move(filename, new_name)
3407.2.5 by Martin Pool
Deprecate LockableFiles.put_utf8
2365
        self.bzrdir.transport.put_bytes(
2366
            'branch-format',
2367
            BzrDirFormat6().get_format_string(),
3446.1.1 by Martin Pool
merge further LockableFile deprecations
2368
            mode=self.bzrdir._get_file_mode())
1534.5.7 by Robert Collins
Start factoring out the upgrade policy logic.
2369
2370
1534.5.10 by Robert Collins
Make upgrade driver unaware of the specific formats in play.
2371
class ConvertBzrDir6ToMeta(Converter):
2372
    """Converts format 6 bzr dirs to metadirs."""
2373
2374
    def convert(self, to_convert, pb):
2375
        """See Converter.convert()."""
2241.1.11 by Martin Pool
Get rid of RepositoryFormat*_instance objects. Instead the format
2376
        from bzrlib.repofmt.weaverepo import RepositoryFormat7
2094.3.5 by John Arbash Meinel
Fix imports to ensure modules are loaded before they are used
2377
        from bzrlib.branch import BzrBranchFormat5
1534.5.10 by Robert Collins
Make upgrade driver unaware of the specific formats in play.
2378
        self.bzrdir = to_convert
2379
        self.pb = pb
1534.5.11 by Robert Collins
Implement upgrades to Metaformat trees.
2380
        self.count = 0
2381
        self.total = 20 # the steps we know about
2382
        self.garbage_inventories = []
3446.1.1 by Martin Pool
merge further LockableFile deprecations
2383
        self.dir_mode = self.bzrdir._get_dir_mode()
2384
        self.file_mode = self.bzrdir._get_file_mode()
1534.5.11 by Robert Collins
Implement upgrades to Metaformat trees.
2385
1534.5.13 by Robert Collins
Correct buggy test.
2386
        self.pb.note('starting upgrade from format 6 to metadir')
3407.2.5 by Martin Pool
Deprecate LockableFiles.put_utf8
2387
        self.bzrdir.transport.put_bytes(
2388
                'branch-format',
2389
                "Converting to format 6",
2390
                mode=self.file_mode)
1534.5.11 by Robert Collins
Implement upgrades to Metaformat trees.
2391
        # its faster to move specific files around than to open and use the apis...
2392
        # first off, nuke ancestry.weave, it was never used.
2393
        try:
2394
            self.step('Removing ancestry.weave')
2395
            self.bzrdir.transport.delete('ancestry.weave')
2396
        except errors.NoSuchFile:
2397
            pass
2398
        # find out whats there
2399
        self.step('Finding branch files')
1666.1.3 by Robert Collins
Fix and test upgrades from bzrdir 6 over SFTP.
2400
        last_revision = self.bzrdir.open_branch().last_revision()
1534.5.11 by Robert Collins
Implement upgrades to Metaformat trees.
2401
        bzrcontents = self.bzrdir.transport.list_dir('.')
2402
        for name in bzrcontents:
2403
            if name.startswith('basis-inventory.'):
2404
                self.garbage_inventories.append(name)
2405
        # create new directories for repository, working tree and branch
2406
        repository_names = [('inventory.weave', True),
2407
                            ('revision-store', True),
2408
                            ('weaves', True)]
2409
        self.step('Upgrading repository  ')
1553.5.79 by Martin Pool
upgrade to metadir should create LockDirs not files
2410
        self.bzrdir.transport.mkdir('repository', mode=self.dir_mode)
1534.5.11 by Robert Collins
Implement upgrades to Metaformat trees.
2411
        self.make_lock('repository')
2412
        # we hard code the formats here because we are converting into
2413
        # the meta format. The meta format upgrader can take this to a 
2414
        # future format within each component.
2241.1.11 by Martin Pool
Get rid of RepositoryFormat*_instance objects. Instead the format
2415
        self.put_format('repository', RepositoryFormat7())
1534.5.11 by Robert Collins
Implement upgrades to Metaformat trees.
2416
        for entry in repository_names:
2417
            self.move_entry('repository', entry)
2418
2419
        self.step('Upgrading branch      ')
1553.5.79 by Martin Pool
upgrade to metadir should create LockDirs not files
2420
        self.bzrdir.transport.mkdir('branch', mode=self.dir_mode)
1534.5.11 by Robert Collins
Implement upgrades to Metaformat trees.
2421
        self.make_lock('branch')
2094.3.5 by John Arbash Meinel
Fix imports to ensure modules are loaded before they are used
2422
        self.put_format('branch', BzrBranchFormat5())
1534.5.11 by Robert Collins
Implement upgrades to Metaformat trees.
2423
        branch_files = [('revision-history', True),
2424
                        ('branch-name', True),
2425
                        ('parent', False)]
2426
        for entry in branch_files:
2427
            self.move_entry('branch', entry)
2428
2429
        checkout_files = [('pending-merges', True),
2430
                          ('inventory', True),
2431
                          ('stat-cache', False)]
1959.3.1 by John Arbash Meinel
David Allouche: bzr upgrade should work if there is no working tree
2432
        # If a mandatory checkout file is not present, the branch does not have
2433
        # a functional checkout. Do not create a checkout in the converted
2434
        # branch.
2435
        for name, mandatory in checkout_files:
2436
            if mandatory and name not in bzrcontents:
2437
                has_checkout = False
2438
                break
2439
        else:
2440
            has_checkout = True
2441
        if not has_checkout:
2442
            self.pb.note('No working tree.')
2443
            # If some checkout files are there, we may as well get rid of them.
2444
            for name, mandatory in checkout_files:
2445
                if name in bzrcontents:
2446
                    self.bzrdir.transport.delete(name)
2447
        else:
2123.2.1 by John Arbash Meinel
Fix bug #70716, make bzrlib.bzrdir directly import bzrlib.workingtree
2448
            from bzrlib.workingtree import WorkingTreeFormat3
1959.3.1 by John Arbash Meinel
David Allouche: bzr upgrade should work if there is no working tree
2449
            self.step('Upgrading working tree')
2450
            self.bzrdir.transport.mkdir('checkout', mode=self.dir_mode)
2451
            self.make_lock('checkout')
2452
            self.put_format(
2123.2.1 by John Arbash Meinel
Fix bug #70716, make bzrlib.bzrdir directly import bzrlib.workingtree
2453
                'checkout', WorkingTreeFormat3())
1959.3.1 by John Arbash Meinel
David Allouche: bzr upgrade should work if there is no working tree
2454
            self.bzrdir.transport.delete_multi(
2455
                self.garbage_inventories, self.pb)
2456
            for entry in checkout_files:
2457
                self.move_entry('checkout', entry)
2458
            if last_revision is not None:
3407.2.5 by Martin Pool
Deprecate LockableFiles.put_utf8
2459
                self.bzrdir.transport.put_bytes(
1959.3.1 by John Arbash Meinel
David Allouche: bzr upgrade should work if there is no working tree
2460
                    'checkout/last-revision', last_revision)
3407.2.5 by Martin Pool
Deprecate LockableFiles.put_utf8
2461
        self.bzrdir.transport.put_bytes(
2462
            'branch-format',
2463
            BzrDirMetaFormat1().get_format_string(),
2464
            mode=self.file_mode)
1534.5.10 by Robert Collins
Make upgrade driver unaware of the specific formats in play.
2465
        return BzrDir.open(self.bzrdir.root_transport.base)
2466
1534.5.11 by Robert Collins
Implement upgrades to Metaformat trees.
2467
    def make_lock(self, name):
2468
        """Make a lock for the new control dir name."""
2469
        self.step('Make %s lock' % name)
1996.3.3 by John Arbash Meinel
Shave off another 40ms by demand loading branch and bzrdir
2470
        ld = lockdir.LockDir(self.bzrdir.transport,
2471
                             '%s/lock' % name,
2472
                             file_modebits=self.file_mode,
2473
                             dir_modebits=self.dir_mode)
1553.5.79 by Martin Pool
upgrade to metadir should create LockDirs not files
2474
        ld.create()
1534.5.11 by Robert Collins
Implement upgrades to Metaformat trees.
2475
2476
    def move_entry(self, new_dir, entry):
2477
        """Move then entry name into new_dir."""
2478
        name = entry[0]
2479
        mandatory = entry[1]
2480
        self.step('Moving %s' % name)
2481
        try:
2482
            self.bzrdir.transport.move(name, '%s/%s' % (new_dir, name))
2483
        except errors.NoSuchFile:
2484
            if mandatory:
2485
                raise
2486
2487
    def put_format(self, dirname, format):
3407.2.5 by Martin Pool
Deprecate LockableFiles.put_utf8
2488
        self.bzrdir.transport.put_bytes('%s/format' % dirname,
2489
            format.get_format_string(),
2490
            self.file_mode)
1534.5.11 by Robert Collins
Implement upgrades to Metaformat trees.
2491
1556.1.4 by Robert Collins
Add a new format for what will become knit, and the surrounding logic to upgrade repositories within metadirs, and tests for the same.
2492
2493
class ConvertMetaToMeta(Converter):
2494
    """Converts the components of metadirs."""
2495
2496
    def __init__(self, target_format):
2497
        """Create a metadir to metadir converter.
2498
2499
        :param target_format: The final metadir format that is desired.
2500
        """
2501
        self.target_format = target_format
2502
2503
    def convert(self, to_convert, pb):
2504
        """See Converter.convert()."""
2505
        self.bzrdir = to_convert
2506
        self.pb = pb
2507
        self.count = 0
2508
        self.total = 1
2509
        self.step('checking repository format')
2510
        try:
2511
            repo = self.bzrdir.open_repository()
2512
        except errors.NoRepositoryPresent:
2513
            pass
2514
        else:
2515
            if not isinstance(repo._format, self.target_format.repository_format.__class__):
2516
                from bzrlib.repository import CopyConverter
2517
                self.pb.note('starting repository conversion')
2518
                converter = CopyConverter(self.target_format.repository_format)
2519
                converter.convert(repo, pb)
2230.3.29 by Aaron Bentley
Implement conversion to branch 6
2520
        try:
2521
            branch = self.bzrdir.open_branch()
2522
        except errors.NotBranchError:
2523
            pass
2524
        else:
2255.12.1 by Robert Collins
Implement upgrade for working trees.
2525
            # TODO: conversions of Branch and Tree should be done by
3221.11.5 by Robert Collins
Correctly handle multi-step branch upgrades.
2526
            # InterXFormat lookups/some sort of registry.
2230.3.29 by Aaron Bentley
Implement conversion to branch 6
2527
            # Avoid circular imports
2528
            from bzrlib import branch as _mod_branch
3221.11.5 by Robert Collins
Correctly handle multi-step branch upgrades.
2529
            old = branch._format.__class__
2530
            new = self.target_format.get_branch_format().__class__
2531
            while old != new:
2532
                if (old == _mod_branch.BzrBranchFormat5 and
2533
                    new in (_mod_branch.BzrBranchFormat6,
2534
                        _mod_branch.BzrBranchFormat7)):
2535
                    branch_converter = _mod_branch.Converter5to6()
2536
                elif (old == _mod_branch.BzrBranchFormat6 and
2537
                    new == _mod_branch.BzrBranchFormat7):
2538
                    branch_converter = _mod_branch.Converter6to7()
2539
                else:
2540
                    raise errors.BadConversionTarget("No converter", new)
2230.3.29 by Aaron Bentley
Implement conversion to branch 6
2541
                branch_converter.convert(branch)
3221.11.5 by Robert Collins
Correctly handle multi-step branch upgrades.
2542
                branch = self.bzrdir.open_branch()
2543
                old = branch._format.__class__
2255.12.1 by Robert Collins
Implement upgrade for working trees.
2544
        try:
2323.6.4 by Martin Pool
BzrDir._check_supported now also takes care of recommending upgrades, which
2545
            tree = self.bzrdir.open_workingtree(recommend_upgrade=False)
2255.2.196 by Robert Collins
Fix test_upgrade defects related to non local or absent working trees.
2546
        except (errors.NoWorkingTree, errors.NotLocalUrl):
2255.12.1 by Robert Collins
Implement upgrade for working trees.
2547
            pass
2548
        else:
2549
            # TODO: conversions of Branch and Tree should be done by
2550
            # InterXFormat lookups
2551
            if (isinstance(tree, workingtree.WorkingTree3) and
2255.2.212 by Robert Collins
Fix upgrade bug exposed via repository tests, dont replace dirstate format trees during upgrade.
2552
                not isinstance(tree, workingtree_4.WorkingTree4) and
2255.12.1 by Robert Collins
Implement upgrade for working trees.
2553
                isinstance(self.target_format.workingtree_format,
2554
                    workingtree_4.WorkingTreeFormat4)):
2555
                workingtree_4.Converter3to4().convert(tree)
3586.1.8 by Ian Clatworthy
add workingtree_5 and initial upgrade code
2556
            if (isinstance(tree, workingtree_4.WorkingTree4) and
2557
                not isinstance(tree, workingtree_5.WorkingTree5) and
2558
                isinstance(self.target_format.workingtree_format,
2559
                    workingtree_5.WorkingTreeFormat5)):
2560
                workingtree_5.Converter4to5().convert(tree)
1556.1.4 by Robert Collins
Add a new format for what will become knit, and the surrounding logic to upgrade repositories within metadirs, and tests for the same.
2561
        return to_convert
1731.2.18 by Aaron Bentley
Get extract in repository under test
2562
2563
2018.5.25 by Andrew Bennetts
Make sure RemoteBzrDirFormat is always registered (John Arbash Meinel, Robert Collins, Andrew Bennetts).
2564
# This is not in remote.py because it's small, and needs to be registered.
2565
# Putting it in remote.py creates a circular import problem.
2018.5.28 by Robert Collins
Fix RemoteBzrDirFormat probe api usage.
2566
# we can make it a lazy object if the control formats is turned into something
2567
# like a registry.
2018.5.25 by Andrew Bennetts
Make sure RemoteBzrDirFormat is always registered (John Arbash Meinel, Robert Collins, Andrew Bennetts).
2568
class RemoteBzrDirFormat(BzrDirMetaFormat1):
2569
    """Format representing bzrdirs accessed via a smart server"""
2570
2571
    def get_format_description(self):
2572
        return 'bzr remote bzrdir'
2573
    
2018.5.28 by Robert Collins
Fix RemoteBzrDirFormat probe api usage.
2574
    @classmethod
2575
    def probe_transport(klass, transport):
2576
        """Return a RemoteBzrDirFormat object if it looks possible."""
2018.5.25 by Andrew Bennetts
Make sure RemoteBzrDirFormat is always registered (John Arbash Meinel, Robert Collins, Andrew Bennetts).
2577
        try:
3241.1.4 by Andrew Bennetts
Use get_smart_medium as suggested by Robert, and deal with the fallout.
2578
            medium = transport.get_smart_medium()
2018.5.25 by Andrew Bennetts
Make sure RemoteBzrDirFormat is always registered (John Arbash Meinel, Robert Collins, Andrew Bennetts).
2579
        except (NotImplementedError, AttributeError,
3245.4.47 by Andrew Bennetts
Don't automatically send 'hello' requests from RemoteBzrDirFormat.probe_transport unless we have to (i.e. the transport is HTTP).
2580
                errors.TransportNotPossible, errors.NoSmartMedium,
2581
                errors.SmartProtocolError):
2018.5.28 by Robert Collins
Fix RemoteBzrDirFormat probe api usage.
2582
            # no smart server, so not a branch for this format type.
2583
            raise errors.NotBranchError(path=transport.base)
2018.5.25 by Andrew Bennetts
Make sure RemoteBzrDirFormat is always registered (John Arbash Meinel, Robert Collins, Andrew Bennetts).
2584
        else:
3241.1.2 by Andrew Bennetts
Tidy comments.
2585
            # Decline to open it if the server doesn't support our required
3245.4.14 by Andrew Bennetts
Merge from bzr.dev (via loom thread).
2586
            # version (3) so that the VFS-based transport will do it.
3245.4.47 by Andrew Bennetts
Don't automatically send 'hello' requests from RemoteBzrDirFormat.probe_transport unless we have to (i.e. the transport is HTTP).
2587
            if medium.should_probe():
2588
                try:
2589
                    server_version = medium.protocol_version()
2590
                except errors.SmartProtocolError:
2591
                    # Apparently there's no usable smart server there, even though
2592
                    # the medium supports the smart protocol.
2593
                    raise errors.NotBranchError(path=transport.base)
2594
                if server_version != '2':
2595
                    raise errors.NotBranchError(path=transport.base)
2018.5.28 by Robert Collins
Fix RemoteBzrDirFormat probe api usage.
2596
            return klass()
2018.5.25 by Andrew Bennetts
Make sure RemoteBzrDirFormat is always registered (John Arbash Meinel, Robert Collins, Andrew Bennetts).
2597
2018.5.42 by Robert Collins
Various hopefully improvements, but wsgi is broken, handing over to spiv :).
2598
    def initialize_on_transport(self, transport):
2018.5.128 by Robert Collins
Have RemoteBzrDirFormat create a local format object when it is asked to initialize something on a non-smart transport - allowing sprout to work cleanly.
2599
        try:
2600
            # hand off the request to the smart server
3313.2.1 by Andrew Bennetts
Change _SmartClient's API to accept a medium and a base, rather than a _SharedConnection.
2601
            client_medium = transport.get_smart_medium()
2018.5.128 by Robert Collins
Have RemoteBzrDirFormat create a local format object when it is asked to initialize something on a non-smart transport - allowing sprout to work cleanly.
2602
        except errors.NoSmartMedium:
2603
            # TODO: lookup the local format from a server hint.
2604
            local_dir_format = BzrDirMetaFormat1()
2605
            return local_dir_format.initialize_on_transport(transport)
3431.3.2 by Andrew Bennetts
Remove 'base' from _SmartClient entirely, now that the medium has it.
2606
        client = _SmartClient(client_medium)
2018.5.42 by Robert Collins
Various hopefully improvements, but wsgi is broken, handing over to spiv :).
2607
        path = client.remote_path_from_transport(transport)
3313.2.1 by Andrew Bennetts
Change _SmartClient's API to accept a medium and a base, rather than a _SharedConnection.
2608
        response = client.call('BzrDirFormat.initialize', path)
3376.2.4 by Martin Pool
Remove every assert statement from bzrlib!
2609
        if response[0] != 'ok':
2610
            raise errors.SmartProtocolError('unexpected response code %s' % (response,))
2018.5.42 by Robert Collins
Various hopefully improvements, but wsgi is broken, handing over to spiv :).
2611
        return remote.RemoteBzrDir(transport)
2612
2018.5.25 by Andrew Bennetts
Make sure RemoteBzrDirFormat is always registered (John Arbash Meinel, Robert Collins, Andrew Bennetts).
2613
    def _open(self, transport):
2614
        return remote.RemoteBzrDir(transport)
2615
2616
    def __eq__(self, other):
2617
        if not isinstance(other, RemoteBzrDirFormat):
2618
            return False
2619
        return self.get_format_description() == other.get_format_description()
2620
2621
2018.5.163 by Andrew Bennetts
Deal with various review comments from Robert.
2622
BzrDirFormat.register_control_server_format(RemoteBzrDirFormat)
2018.5.45 by Andrew Bennetts
Merge from bzr.dev
2623
2624
2204.4.4 by Aaron Bentley
Use BzrDirFormatInfo to distinguish native and deprecated formats
2625
class BzrDirFormatInfo(object):
2626
2939.2.2 by Ian Clatworthy
allow bzrdir formats to be registered as experimental
2627
    def __init__(self, native, deprecated, hidden, experimental):
2204.4.4 by Aaron Bentley
Use BzrDirFormatInfo to distinguish native and deprecated formats
2628
        self.deprecated = deprecated
2629
        self.native = native
1551.13.2 by Aaron Bentley
Hide dirstate-with-subtree format
2630
        self.hidden = hidden
2939.2.2 by Ian Clatworthy
allow bzrdir formats to be registered as experimental
2631
        self.experimental = experimental
2204.4.4 by Aaron Bentley
Use BzrDirFormatInfo to distinguish native and deprecated formats
2632
2633
2204.4.1 by Aaron Bentley
Add 'formats' help topic
2634
class BzrDirFormatRegistry(registry.Registry):
2635
    """Registry of user-selectable BzrDir subformats.
2636
    
2637
    Differs from BzrDirFormat._control_formats in that it provides sub-formats,
2638
    e.g. BzrDirMeta1 with weave repository.  Also, it's more user-oriented.
2639
    """
2640
3152.2.2 by Robert Collins
The bzrdir format registry now accepts an ``alias`` keyword to
2641
    def __init__(self):
2642
        """Create a BzrDirFormatRegistry."""
2643
        self._aliases = set()
2644
        super(BzrDirFormatRegistry, self).__init__()
2645
2646
    def aliases(self):
2647
        """Return a set of the format names which are aliases."""
2648
        return frozenset(self._aliases)
2649
2255.2.158 by Martin Pool
Most of the integration of dirstate and subtree
2650
    def register_metadir(self, key,
2651
             repository_format, help, native=True, deprecated=False,
2652
             branch_format=None,
1551.13.2 by Aaron Bentley
Hide dirstate-with-subtree format
2653
             tree_format=None,
2939.2.2 by Ian Clatworthy
allow bzrdir formats to be registered as experimental
2654
             hidden=False,
3152.2.2 by Robert Collins
The bzrdir format registry now accepts an ``alias`` keyword to
2655
             experimental=False,
2656
             alias=False):
2204.4.1 by Aaron Bentley
Add 'formats' help topic
2657
        """Register a metadir subformat.
2241.1.4 by Martin Pool
Moved old weave-based repository formats into bzrlib.repofmt.weaverepo.
2658
2659
        These all use a BzrDirMetaFormat1 bzrdir, but can be parameterized
2660
        by the Repository format.
2661
2255.2.158 by Martin Pool
Most of the integration of dirstate and subtree
2662
        :param repository_format: The fully-qualified repository format class
2663
            name as a string.
2664
        :param branch_format: Fully-qualified branch format class name as
2665
            a string.
2666
        :param tree_format: Fully-qualified tree format class name as
2667
            a string.
2204.4.1 by Aaron Bentley
Add 'formats' help topic
2668
        """
2669
        # This should be expanded to support setting WorkingTree and Branch
2670
        # formats, once BzrDirMetaFormat1 supports that.
2255.2.158 by Martin Pool
Most of the integration of dirstate and subtree
2671
        def _load(full_name):
2672
            mod_name, factory_name = full_name.rsplit('.', 1)
2241.1.21 by Martin Pool
Change register_metadir to take fully-qualified repository class name.
2673
            try:
2674
                mod = __import__(mod_name, globals(), locals(),
2255.2.158 by Martin Pool
Most of the integration of dirstate and subtree
2675
                        [factory_name])
2241.1.21 by Martin Pool
Change register_metadir to take fully-qualified repository class name.
2676
            except ImportError, e:
2255.2.158 by Martin Pool
Most of the integration of dirstate and subtree
2677
                raise ImportError('failed to load %s: %s' % (full_name, e))
2241.1.21 by Martin Pool
Change register_metadir to take fully-qualified repository class name.
2678
            try:
2255.2.158 by Martin Pool
Most of the integration of dirstate and subtree
2679
                factory = getattr(mod, factory_name)
2241.1.4 by Martin Pool
Moved old weave-based repository formats into bzrlib.repofmt.weaverepo.
2680
            except AttributeError:
2255.2.158 by Martin Pool
Most of the integration of dirstate and subtree
2681
                raise AttributeError('no factory %s in module %r'
2682
                    % (full_name, mod))
2683
            return factory()
2684
2685
        def helper():
2204.4.1 by Aaron Bentley
Add 'formats' help topic
2686
            bd = BzrDirMetaFormat1()
2230.3.1 by Aaron Bentley
Get branch6 creation working
2687
            if branch_format is not None:
2255.2.158 by Martin Pool
Most of the integration of dirstate and subtree
2688
                bd.set_branch_format(_load(branch_format))
2689
            if tree_format is not None:
2690
                bd.workingtree_format = _load(tree_format)
2691
            if repository_format is not None:
2692
                bd.repository_format = _load(repository_format)
2204.4.1 by Aaron Bentley
Add 'formats' help topic
2693
            return bd
2939.2.2 by Ian Clatworthy
allow bzrdir formats to be registered as experimental
2694
        self.register(key, helper, help, native, deprecated, hidden,
3152.2.2 by Robert Collins
The bzrdir format registry now accepts an ``alias`` keyword to
2695
            experimental, alias)
2204.4.1 by Aaron Bentley
Add 'formats' help topic
2696
1551.13.2 by Aaron Bentley
Hide dirstate-with-subtree format
2697
    def register(self, key, factory, help, native=True, deprecated=False,
3152.2.2 by Robert Collins
The bzrdir format registry now accepts an ``alias`` keyword to
2698
                 hidden=False, experimental=False, alias=False):
2204.4.1 by Aaron Bentley
Add 'formats' help topic
2699
        """Register a BzrDirFormat factory.
2700
        
2701
        The factory must be a callable that takes one parameter: the key.
2702
        It must produce an instance of the BzrDirFormat when called.
2703
2704
        This function mainly exists to prevent the info object from being
2705
        supplied directly.
2706
        """
3152.2.1 by Robert Collins
* A new repository format 'development' has been added. This format will
2707
        registry.Registry.register(self, key, factory, help,
2939.2.2 by Ian Clatworthy
allow bzrdir formats to be registered as experimental
2708
            BzrDirFormatInfo(native, deprecated, hidden, experimental))
3152.2.2 by Robert Collins
The bzrdir format registry now accepts an ``alias`` keyword to
2709
        if alias:
2710
            self._aliases.add(key)
2204.4.1 by Aaron Bentley
Add 'formats' help topic
2711
2204.4.7 by Aaron Bentley
restore register_lazy, remove register_factory, other updates
2712
    def register_lazy(self, key, module_name, member_name, help, native=True,
3152.2.2 by Robert Collins
The bzrdir format registry now accepts an ``alias`` keyword to
2713
        deprecated=False, hidden=False, experimental=False, alias=False):
3152.2.1 by Robert Collins
* A new repository format 'development' has been added. This format will
2714
        registry.Registry.register_lazy(self, key, module_name, member_name,
2939.2.2 by Ian Clatworthy
allow bzrdir formats to be registered as experimental
2715
            help, BzrDirFormatInfo(native, deprecated, hidden, experimental))
3152.2.2 by Robert Collins
The bzrdir format registry now accepts an ``alias`` keyword to
2716
        if alias:
2717
            self._aliases.add(key)
2204.4.1 by Aaron Bentley
Add 'formats' help topic
2718
2719
    def set_default(self, key):
2720
        """Set the 'default' key to be a clone of the supplied key.
2721
        
2722
        This method must be called once and only once.
2723
        """
3152.2.1 by Robert Collins
* A new repository format 'development' has been added. This format will
2724
        registry.Registry.register(self, 'default', self.get(key),
2204.4.4 by Aaron Bentley
Use BzrDirFormatInfo to distinguish native and deprecated formats
2725
            self.get_help(key), info=self.get_info(key))
3152.2.2 by Robert Collins
The bzrdir format registry now accepts an ``alias`` keyword to
2726
        self._aliases.add('default')
2204.4.1 by Aaron Bentley
Add 'formats' help topic
2727
2204.4.11 by Aaron Bentley
deprecate Repository.set_default_format, update upgrade tests
2728
    def set_default_repository(self, key):
2729
        """Set the FormatRegistry default and Repository default.
2730
        
2731
        This is a transitional method while Repository.set_default_format
2732
        is deprecated.
2733
        """
2734
        if 'default' in self:
2735
            self.remove('default')
2736
        self.set_default(key)
2737
        format = self.get('default')()
2738
2204.4.1 by Aaron Bentley
Add 'formats' help topic
2739
    def make_bzrdir(self, key):
2204.4.7 by Aaron Bentley
restore register_lazy, remove register_factory, other updates
2740
        return self.get(key)()
2204.4.1 by Aaron Bentley
Add 'formats' help topic
2741
2742
    def help_topic(self, topic):
2743
        output = textwrap.dedent("""\
2744
            These formats can be used for creating branches, working trees, and
2745
            repositories.
2204.4.2 by Aaron Bentley
Tweak topic appearance
2746
2204.4.1 by Aaron Bentley
Add 'formats' help topic
2747
            """)
2711.2.4 by Martin Pool
Fix unbound variable error in BzrDirFormatRegistry.get_help (test order dependent)
2748
        default_realkey = None
2204.4.1 by Aaron Bentley
Add 'formats' help topic
2749
        default_help = self.get_help('default')
2750
        help_pairs = []
2751
        for key in self.keys():
2752
            if key == 'default':
2753
                continue
2754
            help = self.get_help(key)
2755
            if help == default_help:
2756
                default_realkey = key
2757
            else:
2758
                help_pairs.append((key, help))
2759
2204.4.4 by Aaron Bentley
Use BzrDirFormatInfo to distinguish native and deprecated formats
2760
        def wrapped(key, help, info):
2761
            if info.native:
2762
                help = '(native) ' + help
2666.1.1 by Ian Clatworthy
Bazaar User Reference generated from online help
2763
            return ':%s:\n%s\n\n' % (key, 
2204.4.1 by Aaron Bentley
Add 'formats' help topic
2764
                    textwrap.fill(help, initial_indent='    ', 
2765
                    subsequent_indent='    '))
2711.2.4 by Martin Pool
Fix unbound variable error in BzrDirFormatRegistry.get_help (test order dependent)
2766
        if default_realkey is not None:
2767
            output += wrapped(default_realkey, '(default) %s' % default_help,
2768
                              self.get_info('default'))
2204.4.4 by Aaron Bentley
Use BzrDirFormatInfo to distinguish native and deprecated formats
2769
        deprecated_pairs = []
2939.2.2 by Ian Clatworthy
allow bzrdir formats to be registered as experimental
2770
        experimental_pairs = []
2204.4.1 by Aaron Bentley
Add 'formats' help topic
2771
        for key, help in help_pairs:
2204.4.4 by Aaron Bentley
Use BzrDirFormatInfo to distinguish native and deprecated formats
2772
            info = self.get_info(key)
1551.13.2 by Aaron Bentley
Hide dirstate-with-subtree format
2773
            if info.hidden:
2774
                continue
2775
            elif info.deprecated:
2204.4.4 by Aaron Bentley
Use BzrDirFormatInfo to distinguish native and deprecated formats
2776
                deprecated_pairs.append((key, help))
2939.2.2 by Ian Clatworthy
allow bzrdir formats to be registered as experimental
2777
            elif info.experimental:
2778
                experimental_pairs.append((key, help))
2204.4.4 by Aaron Bentley
Use BzrDirFormatInfo to distinguish native and deprecated formats
2779
            else:
2780
                output += wrapped(key, help, info)
2939.2.2 by Ian Clatworthy
allow bzrdir formats to be registered as experimental
2781
        if len(experimental_pairs) > 0:
2782
            output += "Experimental formats are shown below.\n\n"
2783
            for key, help in experimental_pairs:
2784
                info = self.get_info(key)
2785
                output += wrapped(key, help, info)
2204.4.4 by Aaron Bentley
Use BzrDirFormatInfo to distinguish native and deprecated formats
2786
        if len(deprecated_pairs) > 0:
2666.1.1 by Ian Clatworthy
Bazaar User Reference generated from online help
2787
            output += "Deprecated formats are shown below.\n\n"
2204.4.4 by Aaron Bentley
Use BzrDirFormatInfo to distinguish native and deprecated formats
2788
            for key, help in deprecated_pairs:
2789
                info = self.get_info(key)
2790
                output += wrapped(key, help, info)
2791
2204.4.1 by Aaron Bentley
Add 'formats' help topic
2792
        return output
2793
2794
3242.2.14 by Aaron Bentley
Update from review comments
2795
class RepositoryAcquisitionPolicy(object):
2796
    """Abstract base class for repository acquisition policies.
3242.3.7 by Aaron Bentley
Delegate stacking to configure_branch
2797
3242.2.14 by Aaron Bentley
Update from review comments
2798
    A repository acquisition policy decides how a BzrDir acquires a repository
2799
    for a branch that is being created.  The most basic policy decision is
2800
    whether to create a new repository or use an existing one.
2801
    """
3242.3.40 by Aaron Bentley
Turn failing test into KnownFailure
2802
    def __init__(self, stack_on, stack_on_pwd, require_stacking):
3242.3.35 by Aaron Bentley
Cleanups and documentation
2803
        """Constructor.
2804
2805
        :param stack_on: A location to stack on
2806
        :param stack_on_pwd: If stack_on is relative, the location it is
2807
            relative to.
3242.3.40 by Aaron Bentley
Turn failing test into KnownFailure
2808
        :param require_stacking: If True, it is a failure to not stack.
3242.3.35 by Aaron Bentley
Cleanups and documentation
2809
        """
3242.3.7 by Aaron Bentley
Delegate stacking to configure_branch
2810
        self._stack_on = stack_on
3242.3.32 by Aaron Bentley
Defer handling relative stacking URLs as late as possible.
2811
        self._stack_on_pwd = stack_on_pwd
3242.3.40 by Aaron Bentley
Turn failing test into KnownFailure
2812
        self._require_stacking = require_stacking
3242.3.7 by Aaron Bentley
Delegate stacking to configure_branch
2813
2814
    def configure_branch(self, branch):
3242.2.13 by Aaron Bentley
Update docs
2815
        """Apply any configuration data from this policy to the branch.
2816
3242.3.18 by Aaron Bentley
Clean up repository-policy work
2817
        Default implementation sets repository stacking.
3242.2.13 by Aaron Bentley
Update docs
2818
        """
3242.3.33 by Aaron Bentley
Handle relative URL stacking cleanly
2819
        if self._stack_on is None:
2820
            return
2821
        if self._stack_on_pwd is None:
2822
            stack_on = self._stack_on
2823
        else:
2824
            try:
3242.3.32 by Aaron Bentley
Defer handling relative stacking URLs as late as possible.
2825
                stack_on = urlutils.rebase_url(self._stack_on,
2826
                    self._stack_on_pwd,
2827
                    branch.bzrdir.root_transport.base)
3242.3.33 by Aaron Bentley
Handle relative URL stacking cleanly
2828
            except errors.InvalidRebaseURLs:
2829
                stack_on = self._get_full_stack_on()
3242.3.37 by Aaron Bentley
Updates from reviews
2830
        try:
3537.3.5 by Martin Pool
merge trunk including stacking policy
2831
            branch.set_stacked_on_url(stack_on)
3242.3.37 by Aaron Bentley
Updates from reviews
2832
        except errors.UnstackableBranchFormat:
3242.3.40 by Aaron Bentley
Turn failing test into KnownFailure
2833
            if self._require_stacking:
2834
                raise
3242.3.33 by Aaron Bentley
Handle relative URL stacking cleanly
2835
2836
    def _get_full_stack_on(self):
3242.3.35 by Aaron Bentley
Cleanups and documentation
2837
        """Get a fully-qualified URL for the stack_on location."""
3242.3.33 by Aaron Bentley
Handle relative URL stacking cleanly
2838
        if self._stack_on is None:
2839
            return None
2840
        if self._stack_on_pwd is None:
2841
            return self._stack_on
2842
        else:
2843
            return urlutils.join(self._stack_on_pwd, self._stack_on)
3242.3.7 by Aaron Bentley
Delegate stacking to configure_branch
2844
3242.3.30 by Aaron Bentley
Handle adding fallback repositories in acquire_repository
2845
    def _add_fallback(self, repository):
3242.3.35 by Aaron Bentley
Cleanups and documentation
2846
        """Add a fallback to the supplied repository, if stacking is set."""
3242.3.33 by Aaron Bentley
Handle relative URL stacking cleanly
2847
        stack_on = self._get_full_stack_on()
2848
        if stack_on is None:
3242.3.30 by Aaron Bentley
Handle adding fallback repositories in acquire_repository
2849
            return
3242.3.33 by Aaron Bentley
Handle relative URL stacking cleanly
2850
        stacked_dir = BzrDir.open(stack_on)
3242.3.30 by Aaron Bentley
Handle adding fallback repositories in acquire_repository
2851
        try:
2852
            stacked_repo = stacked_dir.open_branch().repository
2853
        except errors.NotBranchError:
2854
            stacked_repo = stacked_dir.open_repository()
3242.3.37 by Aaron Bentley
Updates from reviews
2855
        try:
2856
            repository.add_fallback_repository(stacked_repo)
2857
        except errors.UnstackableRepositoryFormat:
3242.3.40 by Aaron Bentley
Turn failing test into KnownFailure
2858
            if self._require_stacking:
2859
                raise
3242.3.30 by Aaron Bentley
Handle adding fallback repositories in acquire_repository
2860
3242.2.10 by Aaron Bentley
Rename RepositoryPolicy.apply to acquire_repository
2861
    def acquire_repository(self, make_working_trees=None, shared=False):
3242.2.14 by Aaron Bentley
Update from review comments
2862
        """Acquire a repository for this bzrdir.
2863
2864
        Implementations may create a new repository or use a pre-exising
2865
        repository.
2866
        :param make_working_trees: If creating a repository, set
2867
            make_working_trees to this value (if non-None)
2868
        :param shared: If creating a repository, make it shared if True
2869
        :return: A repository
2870
        """
2871
        raise NotImplemented(RepositoryAcquisitionPolicy.acquire_repository)
2872
2873
2874
class CreateRepository(RepositoryAcquisitionPolicy):
3242.2.13 by Aaron Bentley
Update docs
2875
    """A policy of creating a new repository"""
3242.2.1 by Aaron Bentley
Abstract policy decisions into determine_repository_policy
2876
3242.3.40 by Aaron Bentley
Turn failing test into KnownFailure
2877
    def __init__(self, bzrdir, stack_on=None, stack_on_pwd=None,
2878
                 require_stacking=False):
3242.3.35 by Aaron Bentley
Cleanups and documentation
2879
        """
2880
        Constructor.
2881
        :param bzrdir: The bzrdir to create the repository on.
2882
        :param stack_on: A location to stack on
2883
        :param stack_on_pwd: If stack_on is relative, the location it is
2884
            relative to.
2885
        """
3242.3.40 by Aaron Bentley
Turn failing test into KnownFailure
2886
        RepositoryAcquisitionPolicy.__init__(self, stack_on, stack_on_pwd,
2887
                                             require_stacking)
3242.2.1 by Aaron Bentley
Abstract policy decisions into determine_repository_policy
2888
        self._bzrdir = bzrdir
2889
3242.2.10 by Aaron Bentley
Rename RepositoryPolicy.apply to acquire_repository
2890
    def acquire_repository(self, make_working_trees=None, shared=False):
3242.2.14 by Aaron Bentley
Update from review comments
2891
        """Implementation of RepositoryAcquisitionPolicy.acquire_repository
3242.2.13 by Aaron Bentley
Update docs
2892
3242.2.14 by Aaron Bentley
Update from review comments
2893
        Creates the desired repository in the bzrdir we already have.
3242.2.13 by Aaron Bentley
Update docs
2894
        """
3575.2.2 by Martin Pool
branch --stacked should force a stacked format
2895
        if self._stack_on or self._require_stacking:
2896
            # we may be coming from a format that doesn't support stacking,
2897
            # but we require it in the destination, so force creation of a new
2898
            # one here.
2899
            #
2900
            # TODO: perhaps this should be treated as a distinct repository
2901
            # acquisition policy?
2902
            repository_format = self._bzrdir._format.repository_format
2903
            if not repository_format.supports_external_lookups:
2904
                # should possibly be controlled by the registry rather than
2905
                # hardcoded here.
2906
                from bzrlib.repofmt import pack_repo
2907
                if repository_format.rich_root_data:
2908
                    repository_format = \
2909
                        pack_repo.RepositoryFormatKnitPack5RichRoot()
2910
                else:
2911
                    repository_format = pack_repo.RepositoryFormatKnitPack5()
2912
                note("using %r for stacking" % (repository_format,))
2913
            repository = repository_format.initialize(self._bzrdir,
2914
                shared=shared)
2915
        else:
2916
            # let bzrdir choose
2917
            repository = self._bzrdir.create_repository(shared=shared)
3242.3.30 by Aaron Bentley
Handle adding fallback repositories in acquire_repository
2918
        self._add_fallback(repository)
3242.2.4 by Aaron Bentley
Only set working tree policty when specified
2919
        if make_working_trees is not None:
3242.3.6 by Aaron Bentley
Work around strange test failure
2920
            repository.set_make_working_trees(make_working_trees)
3242.3.5 by Aaron Bentley
Implement stacking for clone_on_transport
2921
        return repository
3242.2.2 by Aaron Bentley
Merge policy updates from stacked-policy thread
2922
2923
3242.2.14 by Aaron Bentley
Update from review comments
2924
class UseExistingRepository(RepositoryAcquisitionPolicy):
3242.2.13 by Aaron Bentley
Update docs
2925
    """A policy of reusing an existing repository"""
3242.2.1 by Aaron Bentley
Abstract policy decisions into determine_repository_policy
2926
3242.3.40 by Aaron Bentley
Turn failing test into KnownFailure
2927
    def __init__(self, repository, stack_on=None, stack_on_pwd=None,
2928
                 require_stacking=False):
3242.3.35 by Aaron Bentley
Cleanups and documentation
2929
        """Constructor.
2930
2931
        :param repository: The repository to use.
2932
        :param stack_on: A location to stack on
2933
        :param stack_on_pwd: If stack_on is relative, the location it is
2934
            relative to.
2935
        """
3242.3.40 by Aaron Bentley
Turn failing test into KnownFailure
2936
        RepositoryAcquisitionPolicy.__init__(self, stack_on, stack_on_pwd,
2937
                                             require_stacking)
3242.2.1 by Aaron Bentley
Abstract policy decisions into determine_repository_policy
2938
        self._repository = repository
2939
3242.2.10 by Aaron Bentley
Rename RepositoryPolicy.apply to acquire_repository
2940
    def acquire_repository(self, make_working_trees=None, shared=False):
3242.2.14 by Aaron Bentley
Update from review comments
2941
        """Implementation of RepositoryAcquisitionPolicy.acquire_repository
3242.2.13 by Aaron Bentley
Update docs
2942
2943
        Returns an existing repository to use
2944
        """
3242.3.30 by Aaron Bentley
Handle adding fallback repositories in acquire_repository
2945
        self._add_fallback(self._repository)
3242.2.1 by Aaron Bentley
Abstract policy decisions into determine_repository_policy
2946
        return self._repository
2947
2948
2204.4.1 by Aaron Bentley
Add 'formats' help topic
2949
format_registry = BzrDirFormatRegistry()
2204.4.7 by Aaron Bentley
restore register_lazy, remove register_factory, other updates
2950
format_registry.register('weave', BzrDirFormat6,
2204.4.4 by Aaron Bentley
Use BzrDirFormatInfo to distinguish native and deprecated formats
2951
    'Pre-0.8 format.  Slower than knit and does not'
2241.1.6 by Martin Pool
Move Knit repositories into the submodule bzrlib.repofmt.knitrepo and
2952
    ' support checkouts or shared repositories.',
2953
    deprecated=True)
2954
format_registry.register_metadir('knit',
2241.1.21 by Martin Pool
Change register_metadir to take fully-qualified repository class name.
2955
    'bzrlib.repofmt.knitrepo.RepositoryFormatKnit1',
2255.12.1 by Robert Collins
Implement upgrade for working trees.
2956
    'Format using knits.  Recommended for interoperation with bzr <= 0.14.',
2957
    branch_format='bzrlib.branch.BzrBranchFormat5',
2255.2.199 by Robert Collins
Fix definition of knit format; typos are not good.
2958
    tree_format='bzrlib.workingtree.WorkingTreeFormat3')
2241.1.21 by Martin Pool
Change register_metadir to take fully-qualified repository class name.
2959
format_registry.register_metadir('metaweave',
2960
    'bzrlib.repofmt.weaverepo.RepositoryFormat7',
2230.3.30 by Aaron Bentley
Fix whitespace issues
2961
    'Transitional format in 0.8.  Slower than knit.',
2255.12.1 by Robert Collins
Implement upgrade for working trees.
2962
    branch_format='bzrlib.branch.BzrBranchFormat5',
2255.2.209 by Robert Collins
Remove circular imports in bzrdir format definitions.
2963
    tree_format='bzrlib.workingtree.WorkingTreeFormat3',
2204.4.4 by Aaron Bentley
Use BzrDirFormatInfo to distinguish native and deprecated formats
2964
    deprecated=True)
2255.12.1 by Robert Collins
Implement upgrade for working trees.
2965
format_registry.register_metadir('dirstate',
2966
    'bzrlib.repofmt.knitrepo.RepositoryFormatKnit1',
2967
    help='New in 0.15: Fast local operations. Compatible with bzr 0.8 and '
2968
        'above when accessed over the network.',
2969
    branch_format='bzrlib.branch.BzrBranchFormat5',
2255.2.209 by Robert Collins
Remove circular imports in bzrdir format definitions.
2970
    # this uses bzrlib.workingtree.WorkingTreeFormat4 because importing
2971
    # directly from workingtree_4 triggers a circular import.
2972
    tree_format='bzrlib.workingtree.WorkingTreeFormat4',
2255.12.1 by Robert Collins
Implement upgrade for working trees.
2973
    )
1551.13.1 by Aaron Bentley
Introduce dirstate-tags format
2974
format_registry.register_metadir('dirstate-tags',
2975
    'bzrlib.repofmt.knitrepo.RepositoryFormatKnit1',
2976
    help='New in 0.15: Fast local operations and improved scaling for '
1551.13.2 by Aaron Bentley
Hide dirstate-with-subtree format
2977
        'network operations. Additionally adds support for tags.'
2978
        ' Incompatible with bzr < 0.15.',
1551.13.1 by Aaron Bentley
Introduce dirstate-tags format
2979
    branch_format='bzrlib.branch.BzrBranchFormat6',
2980
    tree_format='bzrlib.workingtree.WorkingTreeFormat4',
2981
    )
2996.2.1 by Aaron Bentley
Add KnitRepositoryFormat4
2982
format_registry.register_metadir('rich-root',
2983
    'bzrlib.repofmt.knitrepo.RepositoryFormatKnit4',
2984
    help='New in 1.0.  Better handling of tree roots.  Incompatible with'
2985
        ' bzr < 1.0',
2986
    branch_format='bzrlib.branch.BzrBranchFormat6',
2987
    tree_format='bzrlib.workingtree.WorkingTreeFormat4',
2988
    )
2255.12.1 by Robert Collins
Implement upgrade for working trees.
2989
format_registry.register_metadir('dirstate-with-subtree',
2990
    'bzrlib.repofmt.knitrepo.RepositoryFormatKnit3',
2991
    help='New in 0.15: Fast local operations and improved scaling for '
2992
        'network operations. Additionally adds support for versioning nested '
2993
        'bzr branches. Incompatible with bzr < 0.15.',
2994
    branch_format='bzrlib.branch.BzrBranchFormat6',
2255.2.209 by Robert Collins
Remove circular imports in bzrdir format definitions.
2995
    tree_format='bzrlib.workingtree.WorkingTreeFormat4',
3170.4.3 by Adeodato Simó
Mark the subtree formats as experimental instead of hidden, and remove hidden=True from the rich-root ones.
2996
    experimental=True,
3170.4.4 by Adeodato Simó
Keep the hidden flag for subtree formats after review from Aaron.
2997
    hidden=True,
2255.12.1 by Robert Collins
Implement upgrade for working trees.
2998
    )
3010.3.2 by Martin Pool
Rename pack0.92 to pack-0.92
2999
format_registry.register_metadir('pack-0.92',
2592.3.224 by Martin Pool
Rename GraphKnitRepository etc to KnitPackRepository
3000
    'bzrlib.repofmt.pack_repo.RepositoryFormatKnitPack1',
2939.2.1 by Ian Clatworthy
use 'knitpack' naming instead of 'experimental' for pack formats
3001
    help='New in 0.92: Pack-based format with data compatible with '
2939.2.6 by Ian Clatworthy
more review feedback from lifeless and poolie
3002
        'dirstate-tags format repositories. Interoperates with '
3003
        'bzr repositories before 0.92 but cannot be read by bzr < 0.92. '
3010.3.1 by Martin Pool
Rename knitpack-experimental format to pack0.92 (not experimental)
3004
        'Previously called knitpack-experimental.  '
3005
        'For more information, see '
3006
        'http://doc.bazaar-vcs.org/latest/developers/packrepo.html.',
2592.3.22 by Robert Collins
Add new experimental repository formats.
3007
    branch_format='bzrlib.branch.BzrBranchFormat6',
3008
    tree_format='bzrlib.workingtree.WorkingTreeFormat4',
3009
    )
3010.3.2 by Martin Pool
Rename pack0.92 to pack-0.92
3010
format_registry.register_metadir('pack-0.92-subtree',
2592.3.224 by Martin Pool
Rename GraphKnitRepository etc to KnitPackRepository
3011
    'bzrlib.repofmt.pack_repo.RepositoryFormatKnitPack3',
2939.2.1 by Ian Clatworthy
use 'knitpack' naming instead of 'experimental' for pack formats
3012
    help='New in 0.92: Pack-based format with data compatible with '
2939.2.6 by Ian Clatworthy
more review feedback from lifeless and poolie
3013
        'dirstate-with-subtree format repositories. Interoperates with '
3014
        'bzr repositories before 0.92 but cannot be read by bzr < 0.92. '
3010.3.1 by Martin Pool
Rename knitpack-experimental format to pack0.92 (not experimental)
3015
        'Previously called knitpack-experimental.  '
3016
        'For more information, see '
3017
        'http://doc.bazaar-vcs.org/latest/developers/packrepo.html.',
2592.3.22 by Robert Collins
Add new experimental repository formats.
3018
    branch_format='bzrlib.branch.BzrBranchFormat6',
3019
    tree_format='bzrlib.workingtree.WorkingTreeFormat4',
3190.1.2 by Aaron Bentley
Undo spurious change
3020
    hidden=True,
3170.4.3 by Adeodato Simó
Mark the subtree formats as experimental instead of hidden, and remove hidden=True from the rich-root ones.
3021
    experimental=True,
2592.3.22 by Robert Collins
Add new experimental repository formats.
3022
    )
2996.2.11 by Aaron Bentley
Implement rich-root-pack format ( #164639)
3023
format_registry.register_metadir('rich-root-pack',
3024
    'bzrlib.repofmt.pack_repo.RepositoryFormatKnitPack4',
3025
    help='New in 1.0: Pack-based format with data compatible with '
3139.1.1 by Jelmer Vernooij
No longer mark the rich-root-pack format as experimental.
3026
        'rich-root format repositories. Incompatible with'
3027
        ' bzr < 1.0',
2996.2.11 by Aaron Bentley
Implement rich-root-pack format ( #164639)
3028
    branch_format='bzrlib.branch.BzrBranchFormat6',
3029
    tree_format='bzrlib.workingtree.WorkingTreeFormat4',
3152.2.1 by Robert Collins
* A new repository format 'development' has been added. This format will
3030
    )
3575.2.1 by Martin Pool
Rename stacked format to 1.6
3031
format_registry.register_metadir('1.6',
3549.1.5 by Martin Pool
Add stable format names for stacked branches
3032
    'bzrlib.repofmt.pack_repo.RepositoryFormatKnitPack5',
3033
    help='A branch and pack based repository that supports stacking. ',
3034
    branch_format='bzrlib.branch.BzrBranchFormat7',
3035
    tree_format='bzrlib.workingtree.WorkingTreeFormat4',
3036
    )
3575.2.1 by Martin Pool
Rename stacked format to 1.6
3037
format_registry.register_metadir('1.6-rich-root',
3549.1.6 by Martin Pool
Change stacked-subtree to stacked-rich-root
3038
    'bzrlib.repofmt.pack_repo.RepositoryFormatKnitPack5RichRoot',
3549.1.5 by Martin Pool
Add stable format names for stacked branches
3039
    help='A branch and pack based repository that supports stacking '
3549.1.6 by Martin Pool
Change stacked-subtree to stacked-rich-root
3040
         'and rich root data (needed for bzr-svn). ',
3549.1.5 by Martin Pool
Add stable format names for stacked branches
3041
    branch_format='bzrlib.branch.BzrBranchFormat7',
3042
    tree_format='bzrlib.workingtree.WorkingTreeFormat4',
3043
    )
3152.2.2 by Robert Collins
The bzrdir format registry now accepts an ``alias`` keyword to
3044
# The following two formats should always just be aliases.
3152.2.1 by Robert Collins
* A new repository format 'development' has been added. This format will
3045
format_registry.register_metadir('development',
3221.12.1 by Robert Collins
Backport development1 format (stackable packs) to before-shallow-branches.
3046
    'bzrlib.repofmt.pack_repo.RepositoryFormatPackDevelopment1',
3152.2.1 by Robert Collins
* A new repository format 'development' has been added. This format will
3047
    help='Current development format. Can convert data to and from pack-0.92 '
3048
        '(and anything compatible with pack-0.92) format repositories. '
3221.11.2 by Robert Collins
Create basic stackable branch facility.
3049
        'Repositories and branches in this format can only be read by bzr.dev. '
3152.2.1 by Robert Collins
* A new repository format 'development' has been added. This format will
3050
        'Please read '
3051
        'http://doc.bazaar-vcs.org/latest/developers/development-repo.html '
3052
        'before use.',
3221.11.2 by Robert Collins
Create basic stackable branch facility.
3053
    branch_format='bzrlib.branch.BzrBranchFormat7',
3586.2.2 by Ian Clatworthy
introduce development2 format
3054
    tree_format='bzrlib.workingtree_5.WorkingTreeFormat5',
3152.2.1 by Robert Collins
* A new repository format 'development' has been added. This format will
3055
    experimental=True,
3152.2.2 by Robert Collins
The bzrdir format registry now accepts an ``alias`` keyword to
3056
    alias=True,
3152.2.1 by Robert Collins
* A new repository format 'development' has been added. This format will
3057
    )
3058
format_registry.register_metadir('development-subtree',
3221.12.1 by Robert Collins
Backport development1 format (stackable packs) to before-shallow-branches.
3059
    'bzrlib.repofmt.pack_repo.RepositoryFormatPackDevelopment1Subtree',
3152.2.1 by Robert Collins
* A new repository format 'development' has been added. This format will
3060
    help='Current development format, subtree variant. Can convert data to and '
3221.11.7 by Robert Collins
Merge in real stacked repository work.
3061
        'from pack-0.92-subtree (and anything compatible with '
3062
        'pack-0.92-subtree) format repositories. Repositories and branches in '
3063
        'this format can only be read by bzr.dev. Please read '
3152.2.1 by Robert Collins
* A new repository format 'development' has been added. This format will
3064
        'http://doc.bazaar-vcs.org/latest/developers/development-repo.html '
3065
        'before use.',
3221.11.2 by Robert Collins
Create basic stackable branch facility.
3066
    branch_format='bzrlib.branch.BzrBranchFormat7',
3586.2.2 by Ian Clatworthy
introduce development2 format
3067
    tree_format='bzrlib.workingtree_5.WorkingTreeFormat5',
3152.2.1 by Robert Collins
* A new repository format 'development' has been added. This format will
3068
    experimental=True,
3152.2.2 by Robert Collins
The bzrdir format registry now accepts an ``alias`` keyword to
3069
    alias=True,
3152.2.1 by Robert Collins
* A new repository format 'development' has been added. This format will
3070
    )
3152.2.2 by Robert Collins
The bzrdir format registry now accepts an ``alias`` keyword to
3071
# And the development formats which the will have aliased one of follow:
3152.2.1 by Robert Collins
* A new repository format 'development' has been added. This format will
3072
format_registry.register_metadir('development0',
3073
    'bzrlib.repofmt.pack_repo.RepositoryFormatPackDevelopment0',
3074
    help='Trivial rename of pack-0.92 to provide a development format. '
3075
        'Please read '
3076
        'http://doc.bazaar-vcs.org/latest/developers/development-repo.html '
3077
        'before use.',
3078
    branch_format='bzrlib.branch.BzrBranchFormat6',
3079
    tree_format='bzrlib.workingtree.WorkingTreeFormat4',
3080
    hidden=True,
3081
    experimental=True,
3082
    )
3083
format_registry.register_metadir('development0-subtree',
3084
    'bzrlib.repofmt.pack_repo.RepositoryFormatPackDevelopment0Subtree',
3085
    help='Trivial rename of pack-0.92-subtree to provide a development format. '
3086
        'Please read '
3087
        'http://doc.bazaar-vcs.org/latest/developers/development-repo.html '
3088
        'before use.',
3089
    branch_format='bzrlib.branch.BzrBranchFormat6',
3090
    tree_format='bzrlib.workingtree.WorkingTreeFormat4',
3091
    hidden=True,
2996.2.11 by Aaron Bentley
Implement rich-root-pack format ( #164639)
3092
    experimental=True,
3093
    )
3221.11.2 by Robert Collins
Create basic stackable branch facility.
3094
format_registry.register_metadir('development1',
3221.12.1 by Robert Collins
Backport development1 format (stackable packs) to before-shallow-branches.
3095
    'bzrlib.repofmt.pack_repo.RepositoryFormatPackDevelopment1',
3221.18.1 by Ian Clatworthy
tweaks by ianc during review
3096
    help='A branch and pack based repository that supports stacking. '
3221.11.2 by Robert Collins
Create basic stackable branch facility.
3097
        'Please read '
3098
        'http://doc.bazaar-vcs.org/latest/developers/development-repo.html '
3099
        'before use.',
3100
    branch_format='bzrlib.branch.BzrBranchFormat7',
3101
    tree_format='bzrlib.workingtree.WorkingTreeFormat4',
3102
    hidden=True,
3103
    experimental=True,
3104
    )
3105
format_registry.register_metadir('development1-subtree',
3221.12.1 by Robert Collins
Backport development1 format (stackable packs) to before-shallow-branches.
3106
    'bzrlib.repofmt.pack_repo.RepositoryFormatPackDevelopment1Subtree',
3221.18.1 by Ian Clatworthy
tweaks by ianc during review
3107
    help='A branch and pack based repository that supports stacking. '
3221.11.2 by Robert Collins
Create basic stackable branch facility.
3108
        'Please read '
3109
        'http://doc.bazaar-vcs.org/latest/developers/development-repo.html '
3110
        'before use.',
3111
    branch_format='bzrlib.branch.BzrBranchFormat7',
3112
    tree_format='bzrlib.workingtree.WorkingTreeFormat4',
3113
    hidden=True,
3114
    experimental=True,
3115
    )
3586.2.2 by Ian Clatworthy
introduce development2 format
3116
format_registry.register_metadir('development2',
3117
    'bzrlib.repofmt.pack_repo.RepositoryFormatPackDevelopment1',
3118
    help='A format that supports stacking, filtered views and content filters. '
3119
        'Please read '
3120
        'http://doc.bazaar-vcs.org/latest/developers/development-repo.html '
3121
        'before use.',
3122
    branch_format='bzrlib.branch.BzrBranchFormat7',
3123
    tree_format='bzrlib.workingtree_5.WorkingTreeFormat5',
3124
    hidden=True,
3125
    experimental=True,
3126
    )
3127
format_registry.register_metadir('development2-subtree',
3128
    'bzrlib.repofmt.pack_repo.RepositoryFormatPackDevelopment1Subtree',
3129
    help='A format that supports stacking, filtered views and content filters. '
3130
        'Please read '
3131
        'http://doc.bazaar-vcs.org/latest/developers/development-repo.html '
3132
        'before use.',
3133
    branch_format='bzrlib.branch.BzrBranchFormat7',
3134
    tree_format='bzrlib.workingtree_5.WorkingTreeFormat5',
3135
    hidden=True,
3136
    experimental=True,
3137
    )
3221.11.2 by Robert Collins
Create basic stackable branch facility.
3138
# The current format that is made on 'bzr init'.
3044.1.3 by Martin Pool
Set the default format to pack-0.92
3139
format_registry.set_default('pack-0.92')