~bzr-pqm/bzr/bzr.dev

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