/brz/remove-bazaar

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