/brz/remove-bazaar

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