/brz/remove-bazaar

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