~bzr-pqm/bzr/bzr.dev

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
3023.1.1 by Alexander Belchenko
Mark .bzr directories as "hidden" on Windows (#71147)
30
import sys
1996.3.3 by John Arbash Meinel
Shave off another 40ms by demand loading branch and bzrdir
31
32
from bzrlib.lazy_import import lazy_import
33
lazy_import(globals(), """
1773.4.1 by Martin Pool
Add pyflakes makefile target; fix many warnings
34
from stat import S_ISDIR
1534.4.39 by Robert Collins
Basic BzrDir support.
35
36
import bzrlib
1996.3.3 by John Arbash Meinel
Shave off another 40ms by demand loading branch and bzrdir
37
from bzrlib import (
4294.2.8 by Robert Collins
Reduce round trips pushing new branches substantially.
38
    branch,
3242.1.1 by Aaron Bentley
Implement BzrDir configuration
39
    config,
5363.2.20 by Jelmer Vernooij
use controldir.X
40
    controldir,
1996.3.3 by John Arbash Meinel
Shave off another 40ms by demand loading branch and bzrdir
41
    errors,
2776.1.5 by Robert Collins
Add reasonably comprehensive tests for path last modified and per file graph behaviour.
42
    graph,
1996.3.3 by John Arbash Meinel
Shave off another 40ms by demand loading branch and bzrdir
43
    lockable_files,
44
    lockdir,
3350.6.1 by Robert Collins
* New ``versionedfile.KeyMapper`` interface to abstract out the access to
45
    osutils,
5436.2.1 by Andrew Bennetts
Add bzrlib.pyutils, which has get_named_object, a wrapper around __import__.
46
    pyutils,
2018.5.25 by Andrew Bennetts
Make sure RemoteBzrDirFormat is always registered (John Arbash Meinel, Robert Collins, Andrew Bennetts).
47
    remote,
4294.2.5 by Robert Collins
Reasonable unit test coverage for initialize_on_transport_ex.
48
    repository,
1996.3.12 by John Arbash Meinel
Change how 'revision' is imported to avoid problems later
49
    revision as _mod_revision,
5609.9.1 by Martin
Blindly change all users of get_transport to address the function via the transport module
50
    transport as _mod_transport,
2323.6.4 by Martin Pool
BzrDir._check_supported now also takes care of recommending upgrades, which
51
    ui,
1996.3.3 by John Arbash Meinel
Shave off another 40ms by demand loading branch and bzrdir
52
    urlutils,
3350.6.4 by Robert Collins
First cut at pluralised VersionedFiles. Some rather massive API incompatabilities, primarily because of the difficulty of coherence among competing stores.
53
    versionedfile,
3023.1.2 by Alexander Belchenko
Martin's review.
54
    win32utils,
55
    workingtree,
56
    workingtree_4,
1996.3.6 by John Arbash Meinel
Find a few places that weren't importing their dependencies.
57
    xml4,
58
    xml5,
1996.3.3 by John Arbash Meinel
Shave off another 40ms by demand loading branch and bzrdir
59
    )
1534.5.7 by Robert Collins
Start factoring out the upgrade policy logic.
60
from bzrlib.osutils import (
1996.3.3 by John Arbash Meinel
Shave off another 40ms by demand loading branch and bzrdir
61
    sha_string,
62
    )
3978.3.14 by Jelmer Vernooij
Move BranchBzrDirInter.push() to BzrDir.push().
63
from bzrlib.push import (
64
    PushResult,
65
    )
4294.2.8 by Robert Collins
Reduce round trips pushing new branches substantially.
66
from bzrlib.repofmt import pack_repo
2018.5.159 by Andrew Bennetts
Rename SmartClient to _SmartClient.
67
from bzrlib.smart.client import _SmartClient
5582.9.21 by Jelmer Vernooij
Remove weave references from VersionedfileStore.
68
from bzrlib.store.versioned import VersionedFileStore
1563.2.34 by Robert Collins
Remove the commit and rollback transaction methods as misleading, and implement a WriteTransaction
69
from bzrlib.transactions import WriteTransaction
2164.2.21 by Vincent Ladeuil
Take bundles into account.
70
from bzrlib.transport import (
71
    do_catching_redirections,
3224.5.24 by Andrew Bennetts
More minor import tidying suggested by pyflakes.
72
    local,
2164.2.21 by Vincent Ladeuil
Take bundles into account.
73
    )
5582.9.22 by Jelmer Vernooij
fix import.
74
from bzrlib.weave import (
75
    WeaveFile,
76
    Weave,
77
    )
1996.3.3 by John Arbash Meinel
Shave off another 40ms by demand loading branch and bzrdir
78
""")
79
2164.2.1 by v.ladeuil+lp at free
First rough http branch redirection implementation.
80
from bzrlib.trace import (
81
    note,
82
    )
3224.5.24 by Andrew Bennetts
More minor import tidying suggested by pyflakes.
83
84
from bzrlib import (
4160.1.1 by Robert Collins
Add a BzrDir.pre_open hook for use by the smart server gaol.
85
    hooks,
3224.5.24 by Andrew Bennetts
More minor import tidying suggested by pyflakes.
86
    symbol_versioning,
2711.2.1 by Martin Pool
Deprecate BzrDir.create_repository
87
    )
5409.5.4 by Vincent Ladeuil
Deprecate BzrDir.generate_backup_name and use osutils.available_backup_name.
88
from bzrlib.symbol_versioning import (
89
    deprecated_in,
90
    deprecated_method,
91
    )
5363.2.2 by Jelmer Vernooij
Rename per_bzrdir => per_controldir.
92
93
5363.2.20 by Jelmer Vernooij
use controldir.X
94
class BzrDir(controldir.ControlDir):
1534.4.39 by Robert Collins
Basic BzrDir support.
95
    """A .bzr control diretory.
3943.8.1 by Marius Kruger
remove all trailing whitespace from bzr source
96
1534.4.39 by Robert Collins
Basic BzrDir support.
97
    BzrDir instances let you create or open any of the things that can be
98
    found within .bzr - checkouts, branches and repositories.
3943.8.1 by Marius Kruger
remove all trailing whitespace from bzr source
99
3407.2.13 by Martin Pool
Remove indirection through control_files to get transports
100
    :ivar transport:
1534.4.40 by Robert Collins
Add RepositoryFormats and allow bzrdir.open or create _repository to be used.
101
        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
102
    :ivar root_transport:
2830.1.1 by Ian Clatworthy
bzrdir.py code clean-ups
103
        a transport connected to the directory this bzr was opened from
104
        (i.e. the parent directory holding the .bzr directory).
3416.2.1 by Martin Pool
Add BzrDir._get_file_mode and _get_dir_mode
105
106
    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.
107
108
    :cvar hooks: An instance of BzrDirHooks.
1534.4.39 by Robert Collins
Basic BzrDir support.
109
    """
110
1687.1.12 by Robert Collins
Hook in the full break-lock ui.
111
    def break_lock(self):
112
        """Invoke break_lock on the first object in the bzrdir.
113
114
        If there is a tree, the tree is opened and break_lock() called.
115
        Otherwise, branch is tried, and finally repository.
116
        """
1752.2.52 by Andrew Bennetts
Flesh out more Remote* methods needed to open and initialise remote branches/trees/repositories.
117
        # XXX: This seems more like a UI function than something that really
118
        # belongs in this class.
1687.1.12 by Robert Collins
Hook in the full break-lock ui.
119
        try:
120
            thing_to_unlock = self.open_workingtree()
121
        except (errors.NotLocalUrl, errors.NoWorkingTree):
122
            try:
123
                thing_to_unlock = self.open_branch()
124
            except errors.NotBranchError:
125
                try:
126
                    thing_to_unlock = self.open_repository()
127
                except errors.NoRepositoryPresent:
128
                    return
129
        thing_to_unlock.break_lock()
130
1910.2.12 by Aaron Bentley
Implement knit repo format 2
131
    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.
132
        """Check that a bzrdir as a whole can be converted to a new format."""
133
        # The only current restriction is that the repository content can be 
134
        # fetched compatibly with the target.
1910.2.12 by Aaron Bentley
Implement knit repo format 2
135
        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.
136
        try:
137
            self.open_repository()._format.check_conversion_target(
138
                target_repo_format)
139
        except errors.NoRepositoryPresent:
140
            # No repo, no problem.
141
            pass
1910.2.12 by Aaron Bentley
Implement knit repo format 2
142
1596.2.1 by Robert Collins
Fix BzrDir.open_containing of unsupported branches.
143
    @staticmethod
2323.6.4 by Martin Pool
BzrDir._check_supported now also takes care of recommending upgrades, which
144
    def _check_supported(format, allow_unsupported,
145
        recommend_upgrade=True,
146
        basedir=None):
147
        """Give an error or warning on old formats.
148
3943.8.1 by Marius Kruger
remove all trailing whitespace from bzr source
149
        :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
150
        or repository.
151
3943.8.1 by Marius Kruger
remove all trailing whitespace from bzr source
152
        :param allow_unsupported: If true, allow opening
153
        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
154
        have limited functionality.
155
156
        :param recommend_upgrade: If true (default), warn
157
        the user through the ui object that they may wish
158
        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.
159
        """
2323.5.19 by Martin Pool
No upgrade recommendation on source when cloning
160
        # TODO: perhaps move this into a base Format class; it's not BzrDir
161
        # specific. mbp 20070323
1534.4.44 by Robert Collins
Make a new BzrDir format that uses a versioned branch format in a branch/ subdirectory.
162
        if not allow_unsupported and not format.is_supported():
1596.2.1 by Robert Collins
Fix BzrDir.open_containing of unsupported branches.
163
            # see open_downlevel to open legacy branches.
1740.5.6 by Martin Pool
Clean up many exception classes.
164
            raise errors.UnsupportedFormatError(format=format)
2323.6.4 by Martin Pool
BzrDir._check_supported now also takes care of recommending upgrades, which
165
        if recommend_upgrade \
166
            and getattr(format, 'upgrade_recommended', False):
167
            ui.ui_factory.recommend_upgrade(
168
                format.get_format_description(),
169
                basedir)
1534.4.44 by Robert Collins
Make a new BzrDir format that uses a versioned branch format in a branch/ subdirectory.
170
2475.3.1 by John Arbash Meinel
Fix bug #75721. Update the BzrDir api to add clone_on_transport()
171
    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.
172
        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.
173
        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()
174
        """Clone this bzrdir and its contents to transport verbatim.
175
3242.3.36 by Aaron Bentley
Updates from review comments
176
        :param transport: The transport for the location to produce the clone
177
            at.  If the target directory does not exist, it will be created.
178
        :param revision_id: The tip revision-id to use for any branch or
179
            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()
180
            itself to download less data.
3242.3.35 by Aaron Bentley
Cleanups and documentation
181
        :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()
182
                               even if one is available.
3242.3.22 by Aaron Bentley
Make clone stacking optional
183
        :param preserve_stacking: When cloning a stacked branch, stack the
184
            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.
185
        :param create_prefix: Create any missing directories leading up to
186
            to_transport.
187
        :param use_existing_dir: Use an existing directory if one exists.
5664.1.1 by Jelmer Vernooij
Document no_tree option to ControlDir.clone_on_transport.
188
        :param no_tree: If set to true prevents creation of a working tree.
2475.3.1 by John Arbash Meinel
Fix bug #75721. Update the BzrDir api to add clone_on_transport()
189
        """
4294.2.4 by Robert Collins
Move dir, bzrdir and repo acquisition into a single method on bzrdir format.
190
        # Overview: put together a broad description of what we want to end up
191
        # with; then make as few api calls as possible to do it.
5363.2.2 by Jelmer Vernooij
Rename per_bzrdir => per_controldir.
192
4294.2.4 by Robert Collins
Move dir, bzrdir and repo acquisition into a single method on bzrdir format.
193
        # We may want to create a repo/branch/tree, if we do so what format
194
        # would we want for each:
3650.5.1 by Aaron Bentley
Fix push to use clone all the time.
195
        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.
196
        format = self.cloning_metadir(require_stacking)
5363.2.2 by Jelmer Vernooij
Rename per_bzrdir => per_controldir.
197
4294.2.4 by Robert Collins
Move dir, bzrdir and repo acquisition into a single method on bzrdir format.
198
        # 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.
199
        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.
200
            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.
201
        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.
202
            local_repo = None
3242.3.30 by Aaron Bentley
Handle adding fallback repositories in acquire_repository
203
        try:
204
            local_branch = self.open_branch()
205
        except errors.NotBranchError:
206
            local_branch = None
207
        else:
208
            # enable fallbacks when branch is not a branch reference
209
            if local_branch.repository.has_same_location(local_repo):
210
                local_repo = local_branch.repository
211
            if preserve_stacking:
212
                try:
3650.5.1 by Aaron Bentley
Fix push to use clone all the time.
213
                    stacked_on = local_branch.get_stacked_on_url()
3242.3.30 by Aaron Bentley
Handle adding fallback repositories in acquire_repository
214
                except (errors.UnstackableBranchFormat,
215
                        errors.UnstackableRepositoryFormat,
216
                        errors.NotStacked):
217
                    pass
4294.2.4 by Robert Collins
Move dir, bzrdir and repo acquisition into a single method on bzrdir format.
218
        # Bug: We create a metadir without knowing if it can support stacking,
219
        # we should look up the policy needs first, or just use it as a hint,
220
        # 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.
221
        if local_repo:
5448.6.1 by Matthew Gordon
Added --no-tree option to pull. Needs testing and help text.
222
            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.
223
            want_shared = local_repo.is_shared()
224
            repo_format_name = format.repository_format.network_name()
225
        else:
226
            make_working_trees = False
227
            want_shared = False
228
            repo_format_name = None
229
230
        result_repo, result, require_stacking, repository_policy = \
231
            format.initialize_on_transport_ex(transport,
232
            use_existing_dir=use_existing_dir, create_prefix=create_prefix,
233
            force_new_repo=force_new_repo, stacked_on=stacked_on,
234
            stack_on_pwd=self.root_transport.base,
235
            repo_format_name=repo_format_name,
236
            make_working_trees=make_working_trees, shared_repo=want_shared)
237
        if repo_format_name:
4307.2.2 by Robert Collins
Lock repositories created by BzrDirFormat.initialize_on_transport_ex.
238
            try:
239
                # If the result repository is in the same place as the
240
                # resulting bzr dir, it will have no content, further if the
241
                # result is not stacked then we know all content should be
242
                # copied, and finally if we are copying up to a specific
243
                # revision_id then we can use the pending-ancestry-result which
244
                # does not require traversing all of history to describe it.
5158.6.9 by Martin Pool
Simplify various code to use user_url
245
                if (result_repo.user_url == result.user_url
246
                    and not require_stacking and
4307.2.2 by Robert Collins
Lock repositories created by BzrDirFormat.initialize_on_transport_ex.
247
                    revision_id is not None):
248
                    fetch_spec = graph.PendingAncestryResult(
249
                        [revision_id], local_repo)
250
                    result_repo.fetch(local_repo, fetch_spec=fetch_spec)
251
                else:
252
                    result_repo.fetch(local_repo, revision_id=revision_id)
253
            finally:
254
                result_repo.unlock()
3242.3.30 by Aaron Bentley
Handle adding fallback repositories in acquire_repository
255
        else:
4307.2.2 by Robert Collins
Lock repositories created by BzrDirFormat.initialize_on_transport_ex.
256
            if result_repo is not None:
257
                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.
258
        # 1 if there is a branch present
259
        #   make sure its content is available in the target repository
260
        #   clone it.
3242.3.37 by Aaron Bentley
Updates from reviews
261
        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.
262
            result_branch = local_branch.clone(result, revision_id=revision_id,
263
                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.
264
        try:
265
            # Cheaper to check if the target is not local, than to try making
266
            # the tree and fail.
267
            result.root_transport.local_abspath('.')
268
            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.
269
                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.
270
        except (errors.NoWorkingTree, errors.NotLocalUrl):
271
            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.
272
        return result
273
1685.1.61 by Martin Pool
[broken] Change BzrDir._make_tail to use urlutils.split
274
    # TODO: This should be given a Transport, and should chdir up; otherwise
275
    # 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.
276
    def _make_tail(self, url):
5609.9.1 by Martin
Blindly change all users of get_transport to address the function via the transport module
277
        t = _mod_transport.get_transport(url)
2475.3.3 by John Arbash Meinel
Change calls to try/mkdir('.')/except FileExists to ensure_base()
278
        t.ensure_base()
2475.3.1 by John Arbash Meinel
Fix bug #75721. Update the BzrDir api to add clone_on_transport()
279
3140.1.1 by Aaron Bentley
Implement find_bzrdir functionality
280
    @staticmethod
281
    def find_bzrdirs(transport, evaluate=None, list_current=None):
282
        """Find bzrdirs recursively from current location.
283
284
        This is intended primarily as a building block for more sophisticated
285
        functionality, like finding trees under a directory, or finding
286
        branches that use a given repository.
287
        :param evaluate: An optional callable that yields recurse, value,
288
            where recurse controls whether this bzrdir is recursed into
289
            and value is the value to yield.  By default, all bzrdirs
290
            are recursed into, and the return value is the bzrdir.
291
        :param list_current: if supplied, use this function to list the current
292
            directory, instead of Transport.list_dir
293
        :return: a generator of found bzrdirs, or whatever evaluate returns.
294
        """
295
        if list_current is None:
296
            def list_current(transport):
297
                return transport.list_dir('')
298
        if evaluate is None:
299
            def evaluate(bzrdir):
300
                return True, bzrdir
301
302
        pending = [transport]
303
        while len(pending) > 0:
304
            current_transport = pending.pop()
305
            recurse = True
306
            try:
307
                bzrdir = BzrDir.open_from_transport(current_transport)
5215.3.3 by Marius Kruger
remove inappropriate catches
308
            except (errors.NotBranchError, errors.PermissionDenied):
3140.1.1 by Aaron Bentley
Implement find_bzrdir functionality
309
                pass
310
            else:
311
                recurse, value = evaluate(bzrdir)
312
                yield value
313
            try:
314
                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
315
            except (errors.NoSuchFile, errors.PermissionDenied):
3140.1.1 by Aaron Bentley
Implement find_bzrdir functionality
316
                continue
317
            if recurse:
318
                for subdir in sorted(subdirs, reverse=True):
319
                    pending.append(current_transport.clone(subdir))
320
3140.1.3 by Aaron Bentley
Add support for finding branches to BzrDir
321
    @staticmethod
322
    def find_branches(transport):
3140.1.7 by Aaron Bentley
Update docs
323
        """Find all branches under a transport.
324
325
        This will find all branches below the transport, including branches
326
        inside other branches.  Where possible, it will use
327
        Repository.find_branches.
328
329
        To list all the branches that use a particular Repository, see
330
        Repository.find_branches
331
        """
3140.1.3 by Aaron Bentley
Add support for finding branches to BzrDir
332
        def evaluate(bzrdir):
333
            try:
334
                repository = bzrdir.open_repository()
335
            except errors.NoRepositoryPresent:
336
                pass
337
            else:
4997.1.2 by Jelmer Vernooij
Use list_branches rather than open_branch in find_branches.
338
                return False, ([], repository)
339
            return True, (bzrdir.list_branches(), None)
340
        ret = []
341
        for branches, repo in BzrDir.find_bzrdirs(transport,
342
                                                  evaluate=evaluate):
3140.1.3 by Aaron Bentley
Add support for finding branches to BzrDir
343
            if repo is not None:
4997.1.2 by Jelmer Vernooij
Use list_branches rather than open_branch in find_branches.
344
                ret.extend(repo.find_branches())
345
            if branches is not None:
346
                ret.extend(branches)
347
        return ret
3140.1.3 by Aaron Bentley
Add support for finding branches to BzrDir
348
1534.4.41 by Robert Collins
Branch now uses BzrDir reasonably sanely.
349
    @staticmethod
2204.4.13 by Aaron Bentley
Update all test cases to avoid set_default_format
350
    def create_branch_and_repo(base, force_new_repo=False, format=None):
1534.4.41 by Robert Collins
Branch now uses BzrDir reasonably sanely.
351
        """Create a new BzrDir, Branch and Repository at the url 'base'.
352
2830.1.1 by Ian Clatworthy
bzrdir.py code clean-ups
353
        This will use the current default BzrDirFormat unless one is
3943.8.1 by Marius Kruger
remove all trailing whitespace from bzr source
354
        specified, and use whatever
1534.4.41 by Robert Collins
Branch now uses BzrDir reasonably sanely.
355
        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.
356
        create_repository. If a shared repository is available that is used
357
        preferentially.
1534.4.41 by Robert Collins
Branch now uses BzrDir reasonably sanely.
358
359
        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.
360
361
        :param base: The URL to create the branch at.
362
        :param force_new_repo: If True a new repository is always created.
2830.1.1 by Ian Clatworthy
bzrdir.py code clean-ups
363
        :param format: If supplied, the format of branch to create.  If not
364
            supplied, the default is used.
1534.4.41 by Robert Collins
Branch now uses BzrDir reasonably sanely.
365
        """
2204.4.13 by Aaron Bentley
Update all test cases to avoid set_default_format
366
        bzrdir = BzrDir.create(base, format)
1534.6.11 by Robert Collins
Review feedback.
367
        bzrdir._find_or_create_repository(force_new_repo)
1534.4.41 by Robert Collins
Branch now uses BzrDir reasonably sanely.
368
        return bzrdir.create_branch()
1534.6.11 by Robert Collins
Review feedback.
369
3242.3.32 by Aaron Bentley
Defer handling relative stacking URLs as late as possible.
370
    def determine_repository_policy(self, force_new_repo=False, stack_on=None,
3242.3.40 by Aaron Bentley
Turn failing test into KnownFailure
371
                                    stack_on_pwd=None, require_stacking=False):
3242.2.13 by Aaron Bentley
Update docs
372
        """Return an object representing a policy to use.
373
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.
374
        This controls whether a new repository is created, and the format of
375
        that repository, or some existing shared repository used instead.
3242.3.35 by Aaron Bentley
Cleanups and documentation
376
377
        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
378
3242.3.35 by Aaron Bentley
Cleanups and documentation
379
        :param force_new_repo: If True, require a new repository to be created.
380
        :param stack_on: If supplied, the location to stack on.  If not
381
            supplied, a default_stack_on location may be used.
382
        :param stack_on_pwd: If stack_on is relative, the location it is
383
            relative to.
3242.2.13 by Aaron Bentley
Update docs
384
        """
3242.3.3 by Aaron Bentley
Use _find_containing to determine repository policy
385
        def repository_policy(found_bzrdir):
3242.3.4 by Aaron Bentley
Initial determination of stacking policy
386
            stack_on = None
3242.3.32 by Aaron Bentley
Defer handling relative stacking URLs as late as possible.
387
            stack_on_pwd = None
3641.1.1 by John Arbash Meinel
Merge in 1.6rc5 and revert disabling default stack on policy
388
            config = found_bzrdir.get_config()
3242.3.4 by Aaron Bentley
Initial determination of stacking policy
389
            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.
390
            stack_on = config.get_default_stack_on()
391
            if stack_on is not None:
5158.6.9 by Martin Pool
Simplify various code to use user_url
392
                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.
393
                stop = True
3242.3.3 by Aaron Bentley
Use _find_containing to determine repository policy
394
            # does it have a repository ?
395
            try:
396
                repository = found_bzrdir.open_repository()
397
            except errors.NoRepositoryPresent:
3242.3.4 by Aaron Bentley
Initial determination of stacking policy
398
                repository = None
399
            else:
5158.6.9 by Martin Pool
Simplify various code to use user_url
400
                if (found_bzrdir.user_url != self.user_url 
401
                    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.
402
                    # Don't look higher, can't use a higher shared repo.
3242.3.4 by Aaron Bentley
Initial determination of stacking policy
403
                    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.
404
                    stop = True
3242.3.4 by Aaron Bentley
Initial determination of stacking policy
405
                else:
406
                    stop = True
407
            if not stop:
3242.3.3 by Aaron Bentley
Use _find_containing to determine repository policy
408
                return None, False
3242.3.4 by Aaron Bentley
Initial determination of stacking policy
409
            if repository:
3242.3.32 by Aaron Bentley
Defer handling relative stacking URLs as late as possible.
410
                return UseExistingRepository(repository, stack_on,
3242.3.40 by Aaron Bentley
Turn failing test into KnownFailure
411
                    stack_on_pwd, require_stacking=require_stacking), True
3242.3.3 by Aaron Bentley
Use _find_containing to determine repository policy
412
            else:
3242.3.40 by Aaron Bentley
Turn failing test into KnownFailure
413
                return CreateRepository(self, stack_on, stack_on_pwd,
414
                    require_stacking=require_stacking), True
3242.3.3 by Aaron Bentley
Use _find_containing to determine repository policy
415
3242.2.1 by Aaron Bentley
Abstract policy decisions into determine_repository_policy
416
        if not force_new_repo:
3242.3.30 by Aaron Bentley
Handle adding fallback repositories in acquire_repository
417
            if stack_on is None:
418
                policy = self._find_containing(repository_policy)
419
                if policy is not None:
420
                    return policy
421
            else:
422
                try:
423
                    return UseExistingRepository(self.open_repository(),
3242.3.40 by Aaron Bentley
Turn failing test into KnownFailure
424
                        stack_on, stack_on_pwd,
425
                        require_stacking=require_stacking)
3242.3.30 by Aaron Bentley
Handle adding fallback repositories in acquire_repository
426
                except errors.NoRepositoryPresent:
427
                    pass
3242.3.40 by Aaron Bentley
Turn failing test into KnownFailure
428
        return CreateRepository(self, stack_on, stack_on_pwd,
429
                                require_stacking=require_stacking)
3242.2.1 by Aaron Bentley
Abstract policy decisions into determine_repository_policy
430
1534.6.11 by Robert Collins
Review feedback.
431
    def _find_or_create_repository(self, force_new_repo):
432
        """Create a new repository if needed, returning the repository."""
3242.2.10 by Aaron Bentley
Rename RepositoryPolicy.apply to acquire_repository
433
        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.
434
        return policy.acquire_repository()[0]
3242.2.10 by Aaron Bentley
Rename RepositoryPolicy.apply to acquire_repository
435
1534.4.40 by Robert Collins
Add RepositoryFormats and allow bzrdir.open or create _repository to be used.
436
    @staticmethod
2476.3.6 by Vincent Ladeuil
Fix the 'init connects multiple times' in a different way.
437
    def create_branch_convenience(base, force_new_repo=False,
438
                                  force_new_tree=None, format=None,
2476.3.11 by Vincent Ladeuil
Cosmetic changes.
439
                                  possible_transports=None):
1534.6.10 by Robert Collins
Finish use of repositories support.
440
        """Create a new BzrDir, Branch and Repository at the url 'base'.
441
442
        This is a convenience function - it will use an existing repository
443
        if possible, can be told explicitly whether to create a working tree or
1534.6.12 by Robert Collins
Typo found by John Meinel.
444
        not.
1534.6.10 by Robert Collins
Finish use of repositories support.
445
2830.1.1 by Ian Clatworthy
bzrdir.py code clean-ups
446
        This will use the current default BzrDirFormat unless one is
3943.8.1 by Marius Kruger
remove all trailing whitespace from bzr source
447
        specified, and use whatever
1534.6.10 by Robert Collins
Finish use of repositories support.
448
        repository format that that uses via bzrdir.create_branch and
449
        create_repository. If a shared repository is available that is used
450
        preferentially. Whatever repository is used, its tree creation policy
451
        is followed.
452
453
        The created Branch object is returned.
454
        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
455
        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.
456
        data is created on disk and NotLocalUrl is raised.
1534.6.10 by Robert Collins
Finish use of repositories support.
457
458
        :param base: The URL to create the branch at.
459
        :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
460
        :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.
461
                               prevent such creation respectively.
2830.1.1 by Ian Clatworthy
bzrdir.py code clean-ups
462
        :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
463
        :param possible_transports: An optional reusable transports list.
1534.6.10 by Robert Collins
Finish use of repositories support.
464
        """
1563.1.6 by Robert Collins
Add tests for sftp push, and NonLocalTets for BzrDir.create_branch_convenience, before fixing the failure of it to work on non-local urls.
465
        if force_new_tree:
466
            # check for non local urls
5609.9.1 by Martin
Blindly change all users of get_transport to address the function via the transport module
467
            t = _mod_transport.get_transport(base, possible_transports)
3224.5.24 by Andrew Bennetts
More minor import tidying suggested by pyflakes.
468
            if not isinstance(t, local.LocalTransport):
2476.3.6 by Vincent Ladeuil
Fix the 'init connects multiple times' in a different way.
469
                raise errors.NotLocalUrl(base)
2476.3.8 by Vincent Ladeuil
Mark transports that need to be instrumented or refactored to check
470
        bzrdir = BzrDir.create(base, format, possible_transports)
1534.6.11 by Robert Collins
Review feedback.
471
        repo = bzrdir._find_or_create_repository(force_new_repo)
1534.6.10 by Robert Collins
Finish use of repositories support.
472
        result = bzrdir.create_branch()
2476.3.4 by Vincent Ladeuil
Add tests.
473
        if force_new_tree or (repo.make_working_trees() and
1534.6.10 by Robert Collins
Finish use of repositories support.
474
                              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.
475
            try:
476
                bzrdir.create_workingtree()
477
            except errors.NotLocalUrl:
478
                pass
1534.6.10 by Robert Collins
Finish use of repositories support.
479
        return result
2476.3.4 by Vincent Ladeuil
Add tests.
480
1551.8.2 by Aaron Bentley
Add create_checkout_convenience
481
    @staticmethod
2204.4.13 by Aaron Bentley
Update all test cases to avoid set_default_format
482
    def create_standalone_workingtree(base, format=None):
1534.4.42 by Robert Collins
add working tree to the BzrDir facilities.
483
        """Create a new BzrDir, WorkingTree, Branch and Repository at 'base'.
484
485
        'base' must be a local path or a file:// url.
486
2830.1.1 by Ian Clatworthy
bzrdir.py code clean-ups
487
        This will use the current default BzrDirFormat unless one is
3943.8.1 by Marius Kruger
remove all trailing whitespace from bzr source
488
        specified, and use whatever
1534.4.42 by Robert Collins
add working tree to the BzrDir facilities.
489
        repository format that that uses for bzrdirformat.create_workingtree,
490
        create_branch and create_repository.
491
2830.1.1 by Ian Clatworthy
bzrdir.py code clean-ups
492
        :param format: Override for the bzrdir format to create.
1910.7.17 by Andrew Bennetts
Various cosmetic changes.
493
        :return: The WorkingTree object.
1534.4.42 by Robert Collins
add working tree to the BzrDir facilities.
494
        """
5609.9.1 by Martin
Blindly change all users of get_transport to address the function via the transport module
495
        t = _mod_transport.get_transport(base)
3224.5.24 by Andrew Bennetts
More minor import tidying suggested by pyflakes.
496
        if not isinstance(t, local.LocalTransport):
1534.4.42 by Robert Collins
add working tree to the BzrDir facilities.
497
            raise errors.NotLocalUrl(base)
2485.8.45 by Vincent Ladeuil
Take jam's remarks into account.
498
        bzrdir = BzrDir.create_branch_and_repo(base,
2204.4.13 by Aaron Bentley
Update all test cases to avoid set_default_format
499
                                               force_new_repo=True,
500
                                               format=format).bzrdir
1534.4.42 by Robert Collins
add working tree to the BzrDir facilities.
501
        return bzrdir.create_workingtree()
502
5409.5.4 by Vincent Ladeuil
Deprecate BzrDir.generate_backup_name and use osutils.available_backup_name.
503
    @deprecated_method(deprecated_in((2, 3, 0)))
5340.8.4 by Marius Kruger
* gen_backup_name => generate_backup_name
504
    def generate_backup_name(self, base):
5409.5.4 by Vincent Ladeuil
Deprecate BzrDir.generate_backup_name and use osutils.available_backup_name.
505
        return self._available_backup_name(base)
506
507
    def _available_backup_name(self, base):
5409.5.8 by Vincent Ladeuil
Be more explicit about race conditions and LBYL being discouraged
508
        """Find a non-existing backup file name based on base.
509
510
        See bzrlib.osutils.available_backup_name about race conditions.
511
        """
5409.5.4 by Vincent Ladeuil
Deprecate BzrDir.generate_backup_name and use osutils.available_backup_name.
512
        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
513
3872.3.2 by Jelmer Vernooij
make backup_bzrdir determine the name for the backup files.
514
    def backup_bzrdir(self):
3872.3.1 by Jelmer Vernooij
Allow BzrDir implementation to implement backing up of control directory.
515
        """Backup this bzr control directory.
3943.8.1 by Marius Kruger
remove all trailing whitespace from bzr source
516
3872.3.2 by Jelmer Vernooij
make backup_bzrdir determine the name for the backup files.
517
        :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.
518
        """
5035.4.1 by Parth Malwankar
fixes 335033.
519
3943.2.4 by Martin Pool
Move backup progress indicators from upgrade.py into backup_bzrdir, and tweak text
520
        pb = ui.ui_factory.nested_progress_bar()
521
        try:
522
            old_path = self.root_transport.abspath('.bzr')
5409.5.4 by Vincent Ladeuil
Deprecate BzrDir.generate_backup_name and use osutils.available_backup_name.
523
            backup_dir = self._available_backup_name('backup.bzr')
5035.4.2 by Parth Malwankar
name_gen now works with all transports.
524
            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.
525
            ui.ui_factory.note('making backup of %s\n  to %s'
526
                               % (old_path, new_path,))
5035.4.2 by Parth Malwankar
name_gen now works with all transports.
527
            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
528
            return (old_path, new_path)
529
        finally:
530
            pb.finished()
3872.3.1 by Jelmer Vernooij
Allow BzrDir implementation to implement backing up of control directory.
531
2830.1.2 by Ian Clatworthy
Incorporate feedback from poolie's review
532
    def retire_bzrdir(self, limit=10000):
2255.14.1 by Martin Pool
Add BzrDir.retire_bzrdir and partly fix subsume
533
        """Permanently disable the bzrdir.
534
535
        This is done by renaming it to give the user some ability to recover
536
        if there was a problem.
537
538
        This will have horrible consequences if anyone has anything locked or
539
        in use.
2830.1.2 by Ian Clatworthy
Incorporate feedback from poolie's review
540
        :param limit: number of times to retry
2255.14.1 by Martin Pool
Add BzrDir.retire_bzrdir and partly fix subsume
541
        """
2830.1.2 by Ian Clatworthy
Incorporate feedback from poolie's review
542
        i  = 0
543
        while True:
2255.14.1 by Martin Pool
Add BzrDir.retire_bzrdir and partly fix subsume
544
            try:
545
                to_path = '.bzr.retired.%d' % i
546
                self.root_transport.rename('.bzr', to_path)
547
                note("renamed %s to %s"
548
                    % (self.root_transport.abspath('.bzr'), to_path))
2830.1.1 by Ian Clatworthy
bzrdir.py code clean-ups
549
                return
2255.14.1 by Martin Pool
Add BzrDir.retire_bzrdir and partly fix subsume
550
            except (errors.TransportError, IOError, errors.PathError):
2830.1.2 by Ian Clatworthy
Incorporate feedback from poolie's review
551
                i += 1
552
                if i > limit:
553
                    raise
554
                else:
555
                    pass
2255.14.1 by Martin Pool
Add BzrDir.retire_bzrdir and partly fix subsume
556
3242.3.2 by Aaron Bentley
Split _find_containing out of find_repository
557
    def _find_containing(self, evaluate):
3242.2.13 by Aaron Bentley
Update docs
558
        """Find something in a containing control directory.
559
560
        This method will scan containing control dirs, until it finds what
561
        it is looking for, decides that it will never find it, or runs out
562
        of containing control directories to check.
563
564
        It is used to implement find_repository and
565
        determine_repository_policy.
566
567
        :param evaluate: A function returning (value, stop).  If stop is True,
568
            the value will be returned.
569
        """
3242.3.2 by Aaron Bentley
Split _find_containing out of find_repository
570
        found_bzrdir = self
571
        while True:
572
            result, stop = evaluate(found_bzrdir)
573
            if stop:
574
                return result
575
            next_transport = found_bzrdir.root_transport.clone('..')
5158.6.9 by Martin Pool
Simplify various code to use user_url
576
            if (found_bzrdir.user_url == next_transport.base):
3242.3.2 by Aaron Bentley
Split _find_containing out of find_repository
577
                # top of the file system
578
                return None
579
            # find the next containing bzrdir
580
            try:
581
                found_bzrdir = BzrDir.open_containing_from_transport(
582
                    next_transport)[0]
583
            except errors.NotBranchError:
584
                return None
585
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.
586
    def find_repository(self):
2830.1.1 by Ian Clatworthy
bzrdir.py code clean-ups
587
        """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.
588
589
        This does not require a branch as we use it to find the repo for
590
        new branches as well as to hook existing branches up to their
591
        repository.
592
        """
3242.3.2 by Aaron Bentley
Split _find_containing out of find_repository
593
        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
594
            # 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.
595
            try:
596
                repository = found_bzrdir.open_repository()
597
            except errors.NoRepositoryPresent:
3242.3.2 by Aaron Bentley
Split _find_containing out of find_repository
598
                return None, False
5158.6.9 by Martin Pool
Simplify various code to use user_url
599
            if found_bzrdir.user_url == self.user_url:
3242.2.5 by Aaron Bentley
Avoid unnecessary is_shared check
600
                return repository, True
601
            elif repository.is_shared():
3242.3.2 by Aaron Bentley
Split _find_containing out of find_repository
602
                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.
603
            else:
3242.2.5 by Aaron Bentley
Avoid unnecessary is_shared check
604
                return None, True
3242.3.2 by Aaron Bentley
Split _find_containing out of find_repository
605
606
        found_repo = self._find_containing(usable_repository)
607
        if found_repo is None:
608
            raise errors.NoRepositoryPresent(self)
609
        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.
610
3416.2.1 by Martin Pool
Add BzrDir._get_file_mode and _get_dir_mode
611
    def _find_creation_modes(self):
612
        """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
613
3416.2.1 by Martin Pool
Add BzrDir._get_file_mode and _get_dir_mode
614
        They're always set to be consistent with the base directory,
615
        assuming that this transport allows setting modes.
616
        """
617
        # TODO: Do we need or want an option (maybe a config setting) to turn
618
        # this off or override it for particular locations? -- mbp 20080512
619
        if self._mode_check_done:
620
            return
621
        self._mode_check_done = True
622
        try:
623
            st = self.transport.stat('.')
624
        except errors.TransportNotPossible:
625
            self._dir_mode = None
626
            self._file_mode = None
627
        else:
628
            # Check the directory mode, but also make sure the created
629
            # directories and files are read-write for this user. This is
630
            # mostly a workaround for filesystems which lie about being able to
631
            # 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
632
            if (st.st_mode & 07777 == 00000):
633
                # FTP allows stat but does not return dir/file modes
634
                self._dir_mode = None
635
                self._file_mode = None
636
            else:
637
                self._dir_mode = (st.st_mode & 07777) | 00700
638
                # Remove the sticky and execute bits for files
639
                self._file_mode = self._dir_mode & ~07111
3416.2.1 by Martin Pool
Add BzrDir._get_file_mode and _get_dir_mode
640
641
    def _get_file_mode(self):
642
        """Return Unix mode for newly created files, or None.
643
        """
644
        if not self._mode_check_done:
645
            self._find_creation_modes()
646
        return self._file_mode
647
648
    def _get_dir_mode(self):
649
        """Return Unix mode for newly created directories, or None.
650
        """
651
        if not self._mode_check_done:
652
            self._find_creation_modes()
653
        return self._dir_mode
3943.8.1 by Marius Kruger
remove all trailing whitespace from bzr source
654
3242.1.1 by Aaron Bentley
Implement BzrDir configuration
655
    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.
656
        """Get configuration for this BzrDir."""
657
        return config.BzrDirConfig(self)
658
659
    def _get_config(self):
660
        """By default, no configuration is available."""
661
        return None
3242.1.1 by Aaron Bentley
Implement BzrDir configuration
662
1534.4.39 by Robert Collins
Basic BzrDir support.
663
    def __init__(self, _transport, _format):
664
        """Initialize a Bzr control dir object.
3943.8.1 by Marius Kruger
remove all trailing whitespace from bzr source
665
1534.4.39 by Robert Collins
Basic BzrDir support.
666
        Only really common logic should reside here, concrete classes should be
667
        made with varying behaviours.
668
1534.4.53 by Robert Collins
Review feedback from John Meinel.
669
        :param _format: the format that is creating this BzrDir instance.
670
        :param _transport: the transport this dir is based at.
1534.4.39 by Robert Collins
Basic BzrDir support.
671
        """
672
        self._format = _format
5158.6.1 by Martin Pool
Add ControlComponent interface and make BzrDir implement it
673
        # these are also under the more standard names of 
674
        # control_transport and user_transport
1534.4.41 by Robert Collins
Branch now uses BzrDir reasonably sanely.
675
        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.
676
        self.root_transport = _transport
3416.2.1 by Martin Pool
Add BzrDir._get_file_mode and _get_dir_mode
677
        self._mode_check_done = False
5363.2.2 by Jelmer Vernooij
Rename per_bzrdir => per_controldir.
678
5158.6.1 by Martin Pool
Add ControlComponent interface and make BzrDir implement it
679
    @property 
680
    def user_transport(self):
681
        return self.root_transport
5363.2.2 by Jelmer Vernooij
Rename per_bzrdir => per_controldir.
682
5158.6.1 by Martin Pool
Add ControlComponent interface and make BzrDir implement it
683
    @property
684
    def control_transport(self):
685
        return self.transport
1534.4.39 by Robert Collins
Basic BzrDir support.
686
1713.1.9 by Robert Collins
Paired performance tuning of bzr add. (Robert Collins, Martin Pool).
687
    def is_control_filename(self, filename):
688
        """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
689
1713.1.9 by Robert Collins
Paired performance tuning of bzr add. (Robert Collins, Martin Pool).
690
        :param filename: A filename within the root transport of this bzrdir.
691
692
        This is true IF and ONLY IF the filename is part of the namespace reserved
693
        for bzr control dirs. Currently this is the '.bzr' directory in the root
5363.2.2 by Jelmer Vernooij
Rename per_bzrdir => per_controldir.
694
        of the root_transport. 
1713.1.9 by Robert Collins
Paired performance tuning of bzr add. (Robert Collins, Martin Pool).
695
        """
3943.8.1 by Marius Kruger
remove all trailing whitespace from bzr source
696
        # this might be better on the BzrDirFormat class because it refers to
697
        # all the possible bzrdir disk formats.
698
        # This method is tested via the workingtree is_control_filename tests-
2830.1.1 by Ian Clatworthy
bzrdir.py code clean-ups
699
        # it was extracted from WorkingTree.is_control_filename. If the method's
700
        # 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).
701
        # add new tests for it to the appropriate place.
702
        return filename == '.bzr' or filename.startswith('.bzr/')
703
1534.4.39 by Robert Collins
Basic BzrDir support.
704
    @staticmethod
705
    def open_unsupported(base):
706
        """Open a branch which is not supported."""
707
        return BzrDir.open(base, _unsupported=True)
3943.8.1 by Marius Kruger
remove all trailing whitespace from bzr source
708
1534.4.39 by Robert Collins
Basic BzrDir support.
709
    @staticmethod
2806.2.2 by Vincent Ladeuil
Fix #128076 and #131396 by reusing bound branch transport.
710
    def open(base, _unsupported=False, possible_transports=None):
2830.1.1 by Ian Clatworthy
bzrdir.py code clean-ups
711
        """Open an existing bzrdir, rooted at 'base' (url).
3943.8.1 by Marius Kruger
remove all trailing whitespace from bzr source
712
2830.1.1 by Ian Clatworthy
bzrdir.py code clean-ups
713
        :param _unsupported: a private parameter to the BzrDir class.
1534.4.39 by Robert Collins
Basic BzrDir support.
714
        """
5609.9.1 by Martin
Blindly change all users of get_transport to address the function via the transport module
715
        t = _mod_transport.get_transport(base, possible_transports)
1910.11.1 by Andrew Bennetts
Add BzrDir.open_from_transport, refactored from duplicate code, no explicit tests.
716
        return BzrDir.open_from_transport(t, _unsupported=_unsupported)
717
718
    @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.
719
    def open_from_transport(transport, _unsupported=False,
720
                            _server_formats=True):
1910.11.1 by Andrew Bennetts
Add BzrDir.open_from_transport, refactored from duplicate code, no explicit tests.
721
        """Open a bzrdir within a particular directory.
722
723
        :param transport: Transport containing the bzrdir.
724
        :param _unsupported: private.
725
        """
4160.1.1 by Robert Collins
Add a BzrDir.pre_open hook for use by the smart server gaol.
726
        for hook in BzrDir.hooks['pre_open']:
727
            hook(transport)
3878.4.1 by Vincent Ladeuil
Fix bug #245964 by preserving decorators during redirections (when
728
        # Keep initial base since 'transport' may be modified while following
729
        # the redirections.
2164.2.21 by Vincent Ladeuil
Take bundles into account.
730
        base = transport.base
731
        def find_format(transport):
5363.2.20 by Jelmer Vernooij
use controldir.X
732
            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.
733
                transport, _server_formats=_server_formats)
2164.2.21 by Vincent Ladeuil
Take bundles into account.
734
735
        def redirected(transport, e, redirection_notice):
3878.4.5 by Vincent Ladeuil
Don't use the exception as a parameter for _redirected_to.
736
            redirected_transport = transport._redirected_to(e.source, e.target)
3878.4.1 by Vincent Ladeuil
Fix bug #245964 by preserving decorators during redirections (when
737
            if redirected_transport is None:
738
                raise errors.NotBranchError(base)
2164.2.21 by Vincent Ladeuil
Take bundles into account.
739
            note('%s is%s redirected to %s',
3878.4.1 by Vincent Ladeuil
Fix bug #245964 by preserving decorators during redirections (when
740
                 transport.base, e.permanently, redirected_transport.base)
741
            return redirected_transport
2164.2.21 by Vincent Ladeuil
Take bundles into account.
742
2164.2.22 by Vincent Ladeuil
Take Aaron's review comments into account.
743
        try:
2164.2.28 by Vincent Ladeuil
TestingHTTPServer.test_case_server renamed from test_case to avoid confusions.
744
            transport, format = do_catching_redirections(find_format,
745
                                                         transport,
2164.2.22 by Vincent Ladeuil
Take Aaron's review comments into account.
746
                                                         redirected)
747
        except errors.TooManyRedirections:
748
            raise errors.NotBranchError(base)
2164.2.21 by Vincent Ladeuil
Take bundles into account.
749
1596.2.1 by Robert Collins
Fix BzrDir.open_containing of unsupported branches.
750
        BzrDir._check_supported(format, _unsupported)
1910.11.1 by Andrew Bennetts
Add BzrDir.open_from_transport, refactored from duplicate code, no explicit tests.
751
        return format.open(transport, _found=True)
1534.4.41 by Robert Collins
Branch now uses BzrDir reasonably sanely.
752
1534.4.39 by Robert Collins
Basic BzrDir support.
753
    @staticmethod
2485.8.37 by Vincent Ladeuil
Fix merge multiple connections. Test suite *not* passing (sftp
754
    def open_containing(url, possible_transports=None):
1534.4.39 by Robert Collins
Basic BzrDir support.
755
        """Open an existing branch which contains url.
3943.8.1 by Marius Kruger
remove all trailing whitespace from bzr source
756
1534.6.3 by Robert Collins
find_repository sufficiently robust.
757
        :param url: url to search from.
1534.6.11 by Robert Collins
Review feedback.
758
        See open_containing_from_transport for more detail.
1534.6.3 by Robert Collins
find_repository sufficiently robust.
759
        """
5609.9.1 by Martin
Blindly change all users of get_transport to address the function via the transport module
760
        transport = _mod_transport.get_transport(url, possible_transports)
2485.8.37 by Vincent Ladeuil
Fix merge multiple connections. Test suite *not* passing (sftp
761
        return BzrDir.open_containing_from_transport(transport)
3943.8.1 by Marius Kruger
remove all trailing whitespace from bzr source
762
1534.6.3 by Robert Collins
find_repository sufficiently robust.
763
    @staticmethod
1534.6.11 by Robert Collins
Review feedback.
764
    def open_containing_from_transport(a_transport):
2830.1.1 by Ian Clatworthy
bzrdir.py code clean-ups
765
        """Open an existing branch which contains a_transport.base.
1534.6.3 by Robert Collins
find_repository sufficiently robust.
766
767
        This probes for a branch at a_transport, and searches upwards from there.
1534.4.39 by Robert Collins
Basic BzrDir support.
768
769
        Basically we keep looking up until we find the control directory or
770
        run into the root.  If there isn't one, raises NotBranchError.
3943.8.1 by Marius Kruger
remove all trailing whitespace from bzr source
771
        If there is one and it is either an unrecognised format or an unsupported
1534.4.39 by Robert Collins
Basic BzrDir support.
772
        format, UnknownFormatError or UnsupportedFormatError are raised.
773
        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
774
3943.8.1 by Marius Kruger
remove all trailing whitespace from bzr source
775
        :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.
776
                for the rest of the URL.
1534.4.39 by Robert Collins
Basic BzrDir support.
777
        """
778
        # this gets the normalised url back. I.e. '.' -> the full path.
1534.6.3 by Robert Collins
find_repository sufficiently robust.
779
        url = a_transport.base
1534.4.39 by Robert Collins
Basic BzrDir support.
780
        while True:
781
            try:
1910.11.1 by Andrew Bennetts
Add BzrDir.open_from_transport, refactored from duplicate code, no explicit tests.
782
                result = BzrDir.open_from_transport(a_transport)
783
                return result, urlutils.unescape(a_transport.relpath(url))
1534.4.39 by Robert Collins
Basic BzrDir support.
784
            except errors.NotBranchError, e:
1685.1.60 by Martin Pool
[broken] NotBranchError should unescape the url if possible
785
                pass
2018.14.1 by Andrew Bennetts
Update to current hpss branch? Fix lots of test failures.
786
            try:
787
                new_t = a_transport.clone('..')
788
            except errors.InvalidURLJoin:
789
                # reached the root, whatever that may be
790
                raise errors.NotBranchError(path=url)
1534.6.3 by Robert Collins
find_repository sufficiently robust.
791
            if new_t.base == a_transport.base:
1534.4.39 by Robert Collins
Basic BzrDir support.
792
                # reached the root, whatever that may be
793
                raise errors.NotBranchError(path=url)
1534.6.3 by Robert Collins
find_repository sufficiently robust.
794
            a_transport = new_t
1534.4.39 by Robert Collins
Basic BzrDir support.
795
3123.5.11 by Aaron Bentley
Accelerate branching from a lightweight checkout
796
    @classmethod
797
    def open_tree_or_branch(klass, location):
798
        """Return the branch and working tree at a location.
799
800
        If there is no tree at the location, tree will be None.
801
        If there is no branch at the location, an exception will be
802
        raised
803
        :return: (tree, branch)
804
        """
805
        bzrdir = klass.open(location)
806
        return bzrdir._get_tree_branch()
807
2215.3.2 by Aaron Bentley
Add open_containing_tree_or_branch
808
    @classmethod
809
    def open_containing_tree_or_branch(klass, location):
810
        """Return the branch and working tree contained by a location.
811
812
        Returns (tree, branch, relpath).
813
        If there is no tree at containing the location, tree will be None.
814
        If there is no branch containing the location, an exception will be
815
        raised
816
        relpath is the portion of the path that is contained by the branch.
817
        """
818
        bzrdir, relpath = klass.open_containing(location)
3123.5.11 by Aaron Bentley
Accelerate branching from a lightweight checkout
819
        tree, branch = bzrdir._get_tree_branch()
2215.3.2 by Aaron Bentley
Add open_containing_tree_or_branch
820
        return tree, branch, relpath
821
3015.3.39 by Daniel Watkins
Added classmethod bzrlib.bzrdir.BzrDir.open_containing_tree_branch_or_repository.
822
    @classmethod
823
    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.
824
        """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.
825
3015.3.57 by Daniel Watkins
Made changes to BzrDir.open_containing_tree_branch_or_repository suggested on list.
826
        Returns (tree, branch, repository, relpath).
3015.3.39 by Daniel Watkins
Added classmethod bzrlib.bzrdir.BzrDir.open_containing_tree_branch_or_repository.
827
        If there is no tree containing the location, tree will be None.
828
        If there is no branch containing the location, branch will be None.
829
        If there is no repository containing the location, repository will be
830
        None.
3015.3.57 by Daniel Watkins
Made changes to BzrDir.open_containing_tree_branch_or_repository suggested on list.
831
        relpath is the portion of the path that is contained by the innermost
832
        BzrDir.
3015.3.39 by Daniel Watkins
Added classmethod bzrlib.bzrdir.BzrDir.open_containing_tree_branch_or_repository.
833
3015.3.59 by Daniel Watkins
Further tweaks as requested on-list.
834
        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.
835
        """
3015.3.57 by Daniel Watkins
Made changes to BzrDir.open_containing_tree_branch_or_repository suggested on list.
836
        bzrdir, relpath = klass.open_containing(location)
3015.3.39 by Daniel Watkins
Added classmethod bzrlib.bzrdir.BzrDir.open_containing_tree_branch_or_repository.
837
        try:
3015.3.51 by Daniel Watkins
Modified open_containing_tree_branch_or_repository as per Aaron's suggestion.
838
            tree, branch = bzrdir._get_tree_branch()
3015.3.39 by Daniel Watkins
Added classmethod bzrlib.bzrdir.BzrDir.open_containing_tree_branch_or_repository.
839
        except errors.NotBranchError:
840
            try:
3015.3.59 by Daniel Watkins
Further tweaks as requested on-list.
841
                repo = bzrdir.find_repository()
3015.3.57 by Daniel Watkins
Made changes to BzrDir.open_containing_tree_branch_or_repository suggested on list.
842
                return None, None, repo, relpath
843
            except (errors.NoRepositoryPresent):
844
                raise errors.NotBranchError(location)
845
        return tree, branch, branch.repository, relpath
3015.3.39 by Daniel Watkins
Added classmethod bzrlib.bzrdir.BzrDir.open_containing_tree_branch_or_repository.
846
2018.5.96 by Andrew Bennetts
Merge from bzr.dev, resolving the worst of the semantic conflicts, but there's
847
    def _cloning_metadir(self):
3575.2.2 by Martin Pool
branch --stacked should force a stacked format
848
        """Produce a metadir suitable for cloning with.
3943.8.1 by Marius Kruger
remove all trailing whitespace from bzr source
849
3575.2.2 by Martin Pool
branch --stacked should force a stacked format
850
        :returns: (destination_bzrdir_format, source_repository)
851
        """
2387.1.1 by Robert Collins
Remove the --basis parameter to clone etc. (Robert Collins)
852
        result_format = self._format.__class__()
853
        try:
1910.2.41 by Aaron Bentley
Clean up clone format creation
854
            try:
4160.2.6 by Andrew Bennetts
Add ignore_fallbacks flag.
855
                branch = self.open_branch(ignore_fallbacks=True)
2387.1.1 by Robert Collins
Remove the --basis parameter to clone etc. (Robert Collins)
856
                source_repository = branch.repository
3650.2.5 by Aaron Bentley
Stop creating a new instance
857
                result_format._branch_format = branch._format
1910.2.41 by Aaron Bentley
Clean up clone format creation
858
            except errors.NotBranchError:
859
                source_branch = None
2387.1.1 by Robert Collins
Remove the --basis parameter to clone etc. (Robert Collins)
860
                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.
861
        except errors.NoRepositoryPresent:
2100.3.24 by Aaron Bentley
Get all tests passing again
862
            source_repository = None
2305.3.1 by Andrew Bennetts
Tidy up BzrDir.cloning_metadir: bogus try/except, and basis argument isn't actually used.
863
        else:
2018.5.138 by Robert Collins
Merge bzr.dev.
864
            # XXX TODO: This isinstance is here because we have not implemented
865
            # the fix recommended in bug # 103195 - to delegate this choice the
866
            # repository itself.
2018.5.94 by Andrew Bennetts
Various small changes in aid of making tests pass (including deleting one invalid test).
867
            repo_format = source_repository._format
3705.2.1 by Andrew Bennetts
Possible fix for bug 269214
868
            if isinstance(repo_format, remote.RemoteRepositoryFormat):
869
                source_repository._ensure_real()
870
                repo_format = source_repository._real_repository._format
871
            result_format.repository_format = repo_format
2100.3.28 by Aaron Bentley
Make sprout recursive
872
        try:
2323.5.19 by Martin Pool
No upgrade recommendation on source when cloning
873
            # TODO: Couldn't we just probe for the format in these cases,
874
            # rather than opening the whole tree?  It would be a little
875
            # faster. mbp 20070401
876
            tree = self.open_workingtree(recommend_upgrade=False)
2100.3.28 by Aaron Bentley
Make sprout recursive
877
        except (errors.NoWorkingTree, errors.NotLocalUrl):
878
            result_format.workingtree_format = None
879
        else:
880
            result_format.workingtree_format = tree._format.__class__()
2100.3.21 by Aaron Bentley
Work on checking out by-reference trees
881
        return result_format, source_repository
882
3650.3.13 by Aaron Bentley
Make cloning_metadir handle stacking requirements
883
    def cloning_metadir(self, require_stacking=False):
2100.3.32 by Aaron Bentley
fix tree format, basis_tree call, in sprout
884
        """Produce a metadir suitable for cloning or sprouting with.
1910.2.41 by Aaron Bentley
Clean up clone format creation
885
2100.3.32 by Aaron Bentley
fix tree format, basis_tree call, in sprout
886
        These operations may produce workingtrees (yes, even though they're
2830.1.1 by Ian Clatworthy
bzrdir.py code clean-ups
887
        "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
888
        format must be selected.
3575.2.2 by Martin Pool
branch --stacked should force a stacked format
889
3650.3.13 by Aaron Bentley
Make cloning_metadir handle stacking requirements
890
        :require_stacking: If True, non-stackable formats will be upgraded
891
            to similar stackable formats.
3575.2.2 by Martin Pool
branch --stacked should force a stacked format
892
        :returns: a BzrDirFormat with all component formats either set
3650.3.13 by Aaron Bentley
Make cloning_metadir handle stacking requirements
893
            appropriately or set to None if that component should not be
3575.2.2 by Martin Pool
branch --stacked should force a stacked format
894
            created.
2100.3.32 by Aaron Bentley
fix tree format, basis_tree call, in sprout
895
        """
2100.3.21 by Aaron Bentley
Work on checking out by-reference trees
896
        format, repository = self._cloning_metadir()
2100.3.32 by Aaron Bentley
fix tree format, basis_tree call, in sprout
897
        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.
898
            # No tree in self.
2100.3.34 by Aaron Bentley
Fix BzrDir.cloning_metadir with no format
899
            if repository is None:
4294.2.4 by Robert Collins
Move dir, bzrdir and repo acquisition into a single method on bzrdir format.
900
                # No repository either
2100.3.34 by Aaron Bentley
Fix BzrDir.cloning_metadir with no format
901
                return format
4294.2.4 by Robert Collins
Move dir, bzrdir and repo acquisition into a single method on bzrdir format.
902
            # We have a repository, so set a working tree? (Why? This seems to
903
            # contradict the stated return value in the docstring).
2100.3.21 by Aaron Bentley
Work on checking out by-reference trees
904
            tree_format = repository._format._matchingbzrdir.workingtree_format
2100.3.28 by Aaron Bentley
Make sprout recursive
905
            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.
906
        if require_stacking:
907
            format.require_stacking()
3650.3.13 by Aaron Bentley
Make cloning_metadir handle stacking requirements
908
        return format
909
5363.2.14 by Jelmer Vernooij
Move ControlDir.create back to BzrDir.create.
910
    @classmethod
911
    def create(cls, base, format=None, possible_transports=None):
912
        """Create a new BzrDir at the url 'base'.
913
914
        :param format: If supplied, the format of branch to create.  If not
915
            supplied, the default is used.
916
        :param possible_transports: If supplied, a list of transports that
917
            can be reused to share a remote connection.
918
        """
919
        if cls is not BzrDir:
920
            raise AssertionError("BzrDir.create always creates the"
921
                "default format, not one of %r" % cls)
5609.9.1 by Martin
Blindly change all users of get_transport to address the function via the transport module
922
        t = _mod_transport.get_transport(base, possible_transports)
5363.2.14 by Jelmer Vernooij
Move ControlDir.create back to BzrDir.create.
923
        t.ensure_base()
924
        if format is None:
5363.2.20 by Jelmer Vernooij
use controldir.X
925
            format = controldir.ControlDirFormat.get_default_format()
5363.2.14 by Jelmer Vernooij
Move ControlDir.create back to BzrDir.create.
926
        return format.initialize_on_transport(t)
927
928
4160.1.1 by Robert Collins
Add a BzrDir.pre_open hook for use by the smart server gaol.
929
class BzrDirHooks(hooks.Hooks):
930
    """Hooks for BzrDir operations."""
931
932
    def __init__(self):
933
        """Create the default hooks."""
934
        hooks.Hooks.__init__(self)
935
        self.create_hook(hooks.HookPoint('pre_open',
936
            "Invoked before attempting to open a BzrDir with the transport "
937
            "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',
938
        self.create_hook(hooks.HookPoint('post_repo_init',
939
            "Invoked after a repository has been initialized. "
940
            "post_repo_init is called with a "
941
            "bzrlib.bzrdir.RepoInitHookParams.",
942
            (2, 2), None))
4160.1.1 by Robert Collins
Add a BzrDir.pre_open hook for use by the smart server gaol.
943
944
# install the default hooks
945
BzrDir.hooks = BzrDirHooks()
946
947
5107.3.1 by Marco Pantaleoni
Added the new hooks 'post_branch', 'post_switch' and 'post_repo_init',
948
class RepoInitHookParams(object):
949
    """Object holding parameters passed to *_repo_init hooks.
950
951
    There are 4 fields that hooks may wish to access:
952
953
    :ivar repository: Repository created
954
    :ivar format: Repository format
955
    :ivar bzrdir: The bzrdir for the repository
956
    :ivar shared: The repository is shared
957
    """
958
959
    def __init__(self, repository, format, a_bzrdir, shared):
960
        """Create a group of RepoInitHook parameters.
961
962
        :param repository: Repository created
963
        :param format: Repository format
964
        :param bzrdir: The bzrdir for the repository
965
        :param shared: The repository is shared
966
        """
5107.3.4 by Marco Pantaleoni
Applied suggestions from merge reviewer (John A Meinel):
967
        self.repository = repository
968
        self.format = format
969
        self.bzrdir = a_bzrdir
970
        self.shared = shared
5107.3.1 by Marco Pantaleoni
Added the new hooks 'post_branch', 'post_switch' and 'post_repo_init',
971
972
    def __eq__(self, other):
973
        return self.__dict__ == other.__dict__
974
975
    def __repr__(self):
976
        if self.repository:
977
            return "<%s for %s>" % (self.__class__.__name__,
978
                self.repository)
979
        else:
980
            return "<%s for %s>" % (self.__class__.__name__,
981
                self.bzrdir)
982
983
1534.4.44 by Robert Collins
Make a new BzrDir format that uses a versioned branch format in a branch/ subdirectory.
984
class BzrDirMeta1(BzrDir):
985
    """A .bzr meta version 1 control object.
3943.8.1 by Marius Kruger
remove all trailing whitespace from bzr source
986
987
    This is the first control object where the
1553.5.67 by Martin Pool
doc
988
    individual aspects are really split out: there are separate repository,
989
    workingtree and branch subdirectories and any subset of the three can be
990
    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.
991
    """
992
1534.5.16 by Robert Collins
Review feedback.
993
    def can_convert_format(self):
994
        """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.
995
        return True
1534.5.10 by Robert Collins
Make upgrade driver unaware of the specific formats in play.
996
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.
997
    def create_branch(self, name=None, repository=None):
1534.4.41 by Robert Collins
Branch now uses BzrDir reasonably sanely.
998
        """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.
999
        return self._format.get_branch_format().initialize(self, name=name,
1000
                repository=repository)
1534.4.41 by Robert Collins
Branch now uses BzrDir reasonably sanely.
1001
5051.3.1 by Jelmer Vernooij
Add optional name argument to BzrDir.destroy_branch.
1002
    def destroy_branch(self, name=None):
2796.2.6 by Aaron Bentley
Implement destroy_branch
1003
        """See BzrDir.create_branch."""
5051.3.1 by Jelmer Vernooij
Add optional name argument to BzrDir.destroy_branch.
1004
        if name is not None:
1005
            raise errors.NoColocatedBranchSupport(self)
2796.2.6 by Aaron Bentley
Implement destroy_branch
1006
        self.transport.delete_tree('branch')
1007
1534.6.1 by Robert Collins
allow API creation of shared repositories
1008
    def create_repository(self, shared=False):
1534.4.40 by Robert Collins
Add RepositoryFormats and allow bzrdir.open or create _repository to be used.
1009
        """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.
1010
        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.
1011
2796.2.19 by Aaron Bentley
Support reconfigure --lightweight-checkout
1012
    def destroy_repository(self):
1013
        """See BzrDir.destroy_repository."""
1014
        self.transport.delete_tree('repository')
1015
3123.5.2 by Aaron Bentley
Allow checkout --files_from
1016
    def create_workingtree(self, revision_id=None, from_branch=None,
3136.1.3 by Aaron Bentley
Implement hard-link support for branch and checkout
1017
                           accelerator_tree=None, hardlink=False):
1534.4.42 by Robert Collins
add working tree to the BzrDir facilities.
1018
        """See BzrDir.create_workingtree."""
2955.5.3 by Vincent Ladeuil
Fix second unwanted connection by providing the right branch to create_checkout.
1019
        return self._format.workingtree_format.initialize(
3123.5.2 by Aaron Bentley
Allow checkout --files_from
1020
            self, revision_id, from_branch=from_branch,
3136.1.3 by Aaron Bentley
Implement hard-link support for branch and checkout
1021
            accelerator_tree=accelerator_tree, hardlink=hardlink)
1534.4.42 by Robert Collins
add working tree to the BzrDir facilities.
1022
1551.8.37 by Aaron Bentley
Cleaner implementation of destroy_working_tree
1023
    def destroy_workingtree(self):
1551.8.36 by Aaron Bentley
Introduce BzrDir.destroy_workingtree
1024
        """See BzrDir.destroy_workingtree."""
2323.6.4 by Martin Pool
BzrDir._check_supported now also takes care of recommending upgrades, which
1025
        wt = self.open_workingtree(recommend_upgrade=False)
1551.8.37 by Aaron Bentley
Cleaner implementation of destroy_working_tree
1026
        repository = wt.branch.repository
2094.3.5 by John Arbash Meinel
Fix imports to ensure modules are loaded before they are used
1027
        empty = repository.revision_tree(_mod_revision.NULL_REVISION)
5409.1.7 by Vincent Ladeuil
First orphaning implementation (some tests lacking).
1028
        # We ignore the conflicts returned by wt.revert since we're about to
1029
        # 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
1030
        # detritus. But see bug #634470 about subtree .bzr dirs.
5409.1.7 by Vincent Ladeuil
First orphaning implementation (some tests lacking).
1031
        conflicts = wt.revert(old_tree=empty)
1551.8.37 by Aaron Bentley
Cleaner implementation of destroy_working_tree
1032
        self.destroy_workingtree_metadata()
1033
1034
    def destroy_workingtree_metadata(self):
1035
        self.transport.delete_tree('checkout')
1551.8.36 by Aaron Bentley
Introduce BzrDir.destroy_workingtree
1036
5147.4.1 by Jelmer Vernooij
Pass branch names in more places.
1037
    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.
1038
        """Find the branch 'format' for this bzrdir.
1039
1040
        This might be a synthetic object for e.g. RemoteBranch and SVN.
1041
        """
1042
        from bzrlib.branch import BranchFormat
5147.4.3 by Jelmer Vernooij
Support branch name argument to BzrDir.get_branch_reference.
1043
        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.
1044
1666.1.4 by Robert Collins
* 'Metadir' is now the default disk format. This improves behaviour in
1045
    def _get_mkdir_mode(self):
1046
        """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
1047
        temp_control = lockable_files.LockableFiles(self.transport, '',
1048
                                     lockable_files.TransportLock)
1666.1.4 by Robert Collins
* 'Metadir' is now the default disk format. This improves behaviour in
1049
        return temp_control._dir_mode
1050
5147.4.3 by Jelmer Vernooij
Support branch name argument to BzrDir.get_branch_reference.
1051
    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.
1052
        """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)
1053
        from bzrlib.branch import BranchFormat
5147.4.3 by Jelmer Vernooij
Support branch name argument to BzrDir.get_branch_reference.
1054
        format = BranchFormat.find_format(self, name=name)
1055
        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.
1056
5051.3.10 by Jelmer Vernooij
Pass colocated branch name around in more places.
1057
    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.
1058
        """See BzrDir.get_branch_transport()."""
5051.3.10 by Jelmer Vernooij
Pass colocated branch name around in more places.
1059
        if name is not None:
1060
            raise errors.NoColocatedBranchSupport(self)
4570.3.6 by Martin Pool
doc
1061
        # XXX: this shouldn't implicitly create the directory if it's just
1062
        # 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.
1063
        if branch_format is None:
1064
            return self.transport.clone('branch')
1065
        try:
1066
            branch_format.get_format_string()
1067
        except NotImplementedError:
1068
            raise errors.IncompatibleFormat(branch_format, self._format)
1069
        try:
1666.1.4 by Robert Collins
* 'Metadir' is now the default disk format. This improves behaviour in
1070
            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.
1071
        except errors.FileExists:
1072
            pass
1073
        return self.transport.clone('branch')
1074
1534.4.47 by Robert Collins
Split out repository into .bzr/repository
1075
    def get_repository_transport(self, repository_format):
1076
        """See BzrDir.get_repository_transport()."""
1077
        if repository_format is None:
1078
            return self.transport.clone('repository')
1079
        try:
1080
            repository_format.get_format_string()
1081
        except NotImplementedError:
1082
            raise errors.IncompatibleFormat(repository_format, self._format)
1083
        try:
1666.1.4 by Robert Collins
* 'Metadir' is now the default disk format. This improves behaviour in
1084
            self.transport.mkdir('repository', mode=self._get_mkdir_mode())
1534.4.47 by Robert Collins
Split out repository into .bzr/repository
1085
        except errors.FileExists:
1086
            pass
1087
        return self.transport.clone('repository')
1088
1534.4.45 by Robert Collins
Start WorkingTree -> .bzr/checkout transition
1089
    def get_workingtree_transport(self, workingtree_format):
1090
        """See BzrDir.get_workingtree_transport()."""
1091
        if workingtree_format is None:
1092
            return self.transport.clone('checkout')
1093
        try:
1094
            workingtree_format.get_format_string()
1095
        except NotImplementedError:
1096
            raise errors.IncompatibleFormat(workingtree_format, self._format)
1097
        try:
1666.1.4 by Robert Collins
* 'Metadir' is now the default disk format. This improves behaviour in
1098
            self.transport.mkdir('checkout', mode=self._get_mkdir_mode())
1534.4.45 by Robert Collins
Start WorkingTree -> .bzr/checkout transition
1099
        except errors.FileExists:
1100
            pass
1101
        return self.transport.clone('checkout')
1102
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.
1103
    def has_workingtree(self):
1104
        """Tell if this bzrdir contains a working tree.
1105
1106
        This will still raise an exception if the bzrdir has a workingtree that
1107
        is remote & inaccessible.
1108
1109
        Note: if you're going to open the working tree, you should just go
1110
        ahead and try, and not ask permission first.
1111
        """
1112
        from bzrlib.workingtree import WorkingTreeFormat
1113
        try:
1114
            WorkingTreeFormat.find_format(self)
1115
        except errors.NoWorkingTree:
1116
            return False
1117
        return True
1118
1534.5.16 by Robert Collins
Review feedback.
1119
    def needs_format_conversion(self, format=None):
1120
        """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.
1121
        if format is None:
3943.2.5 by Martin Pool
deprecate needs_format_conversion(format=None)
1122
            symbol_versioning.warn(symbol_versioning.deprecated_in((1, 13, 0))
1123
                % 'needs_format_conversion(format=None)')
1124
        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.
1125
            format = BzrDirFormat.get_default_format()
1126
        if not isinstance(self._format, format.__class__):
1127
            # it is not a meta dir format, conversion is needed.
1128
            return True
1129
        # we might want to push this down to the repository?
1130
        try:
1131
            if not isinstance(self.open_repository()._format,
1132
                              format.repository_format.__class__):
1133
                # the repository needs an upgrade.
1134
                return True
1135
        except errors.NoRepositoryPresent:
1136
            pass
5051.3.4 by Jelmer Vernooij
Support name to BzrDir.open_branch.
1137
        for branch in self.list_branches():
1138
            if not isinstance(branch._format,
2230.3.55 by Aaron Bentley
Updates from review
1139
                              format.get_branch_format().__class__):
2255.12.1 by Robert Collins
Implement upgrade for working trees.
1140
                # the branch needs an upgrade.
1141
                return True
1142
        try:
2323.6.4 by Martin Pool
BzrDir._check_supported now also takes care of recommending upgrades, which
1143
            my_wt = self.open_workingtree(recommend_upgrade=False)
1144
            if not isinstance(my_wt._format,
2255.12.1 by Robert Collins
Implement upgrade for working trees.
1145
                              format.workingtree_format.__class__):
1146
                # the workingtree needs an upgrade.
1147
                return True
2255.2.196 by Robert Collins
Fix test_upgrade defects related to non local or absent working trees.
1148
        except (errors.NoWorkingTree, errors.NotLocalUrl):
2255.12.1 by Robert Collins
Implement upgrade for working trees.
1149
            pass
1534.5.10 by Robert Collins
Make upgrade driver unaware of the specific formats in play.
1150
        return False
1151
5051.3.4 by Jelmer Vernooij
Support name to BzrDir.open_branch.
1152
    def open_branch(self, name=None, unsupported=False,
1153
                    ignore_fallbacks=False):
1534.4.41 by Robert Collins
Branch now uses BzrDir reasonably sanely.
1154
        """See BzrDir.open_branch."""
5147.4.3 by Jelmer Vernooij
Support branch name argument to BzrDir.get_branch_reference.
1155
        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)
1156
        self._check_supported(format, unsupported)
5051.3.13 by Jelmer Vernooij
Pass colocated branch name around rather than raising an exception directly.
1157
        return format.open(self, name=name,
1158
            _found=True, ignore_fallbacks=ignore_fallbacks)
1534.4.41 by Robert Collins
Branch now uses BzrDir reasonably sanely.
1159
1534.4.47 by Robert Collins
Split out repository into .bzr/repository
1160
    def open_repository(self, unsupported=False):
1534.4.40 by Robert Collins
Add RepositoryFormats and allow bzrdir.open or create _repository to be used.
1161
        """See BzrDir.open_repository."""
1534.4.47 by Robert Collins
Split out repository into .bzr/repository
1162
        from bzrlib.repository import RepositoryFormat
1163
        format = RepositoryFormat.find_format(self)
1164
        self._check_supported(format, unsupported)
1165
        return format.open(self, _found=True)
1534.4.40 by Robert Collins
Add RepositoryFormats and allow bzrdir.open or create _repository to be used.
1166
2323.6.4 by Martin Pool
BzrDir._check_supported now also takes care of recommending upgrades, which
1167
    def open_workingtree(self, unsupported=False,
1168
            recommend_upgrade=True):
1508.1.21 by Robert Collins
Implement -r limit for checkout command.
1169
        """See BzrDir.open_workingtree."""
1534.4.46 by Robert Collins
Nearly complete .bzr/checkout splitout.
1170
        from bzrlib.workingtree import WorkingTreeFormat
1171
        format = WorkingTreeFormat.find_format(self)
2323.6.4 by Martin Pool
BzrDir._check_supported now also takes care of recommending upgrades, which
1172
        self._check_supported(format, unsupported,
1173
            recommend_upgrade,
2323.6.5 by Martin Pool
Recommended-upgrade message should give base dir not the control dir url
1174
            basedir=self.root_transport.base)
1534.4.46 by Robert Collins
Nearly complete .bzr/checkout splitout.
1175
        return format.open(self, _found=True)
1534.4.42 by Robert Collins
add working tree to the BzrDir facilities.
1176
3242.1.1 by Aaron Bentley
Implement BzrDir configuration
1177
    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.
1178
        return config.TransportConfig(self.transport, 'control.conf')
3242.1.1 by Aaron Bentley
Implement BzrDir configuration
1179
4294.2.4 by Robert Collins
Move dir, bzrdir and repo acquisition into a single method on bzrdir format.
1180
5363.2.20 by Jelmer Vernooij
use controldir.X
1181
class BzrProber(controldir.Prober):
5363.2.8 by Jelmer Vernooij
Docstrings.
1182
    """Prober for formats that use a .bzr/ control directory."""
5363.2.4 by Jelmer Vernooij
Introduce probers, use controldir in a couple more places.
1183
1184
    _formats = {}
1185
    """The known .bzr formats."""
1186
1187
    @classmethod
1188
    def register_bzrdir_format(klass, format):
1189
        klass._formats[format.get_format_string()] = format
1190
1191
    @classmethod
5363.2.6 by Jelmer Vernooij
Add ControlDirFormat.{un,}register_{server_,}prober.
1192
    def unregister_bzrdir_format(klass, format):
5363.2.4 by Jelmer Vernooij
Introduce probers, use controldir in a couple more places.
1193
        del klass._formats[format.get_format_string()]
1194
5363.2.7 by Jelmer Vernooij
Fix tests.
1195
    @classmethod
1196
    def probe_transport(klass, transport):
5363.2.4 by Jelmer Vernooij
Introduce probers, use controldir in a couple more places.
1197
        """Return the .bzrdir style format present in a directory."""
1198
        try:
1199
            format_string = transport.get_bytes(".bzr/branch-format")
1200
        except errors.NoSuchFile:
1201
            raise errors.NotBranchError(path=transport.base)
1202
        try:
5363.2.7 by Jelmer Vernooij
Fix tests.
1203
            return klass._formats[format_string]
5363.2.4 by Jelmer Vernooij
Introduce probers, use controldir in a couple more places.
1204
        except KeyError:
1205
            raise errors.UnknownFormatError(format=format_string, kind='bzrdir')
1206
1207
5363.2.20 by Jelmer Vernooij
use controldir.X
1208
controldir.ControlDirFormat.register_prober(BzrProber)
1209
1210
1211
class RemoteBzrProber(controldir.Prober):
5363.2.8 by Jelmer Vernooij
Docstrings.
1212
    """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.
1213
1214
    @classmethod
1215
    def probe_transport(klass, transport):
1216
        """Return a RemoteBzrDirFormat object if it looks possible."""
1217
        try:
1218
            medium = transport.get_smart_medium()
1219
        except (NotImplementedError, AttributeError,
1220
                errors.TransportNotPossible, errors.NoSmartMedium,
1221
                errors.SmartProtocolError):
1222
            # no smart server, so not a branch for this format type.
1223
            raise errors.NotBranchError(path=transport.base)
1224
        else:
1225
            # Decline to open it if the server doesn't support our required
1226
            # version (3) so that the VFS-based transport will do it.
1227
            if medium.should_probe():
1228
                try:
1229
                    server_version = medium.protocol_version()
1230
                except errors.SmartProtocolError:
1231
                    # Apparently there's no usable smart server there, even though
1232
                    # the medium supports the smart protocol.
1233
                    raise errors.NotBranchError(path=transport.base)
1234
                if server_version != '2':
1235
                    raise errors.NotBranchError(path=transport.base)
5363.2.7 by Jelmer Vernooij
Fix tests.
1236
            return RemoteBzrDirFormat()
5363.2.4 by Jelmer Vernooij
Introduce probers, use controldir in a couple more places.
1237
1238
5363.2.20 by Jelmer Vernooij
use controldir.X
1239
class BzrDirFormat(controldir.ControlDirFormat):
5363.2.3 by Jelmer Vernooij
Add ControlDirFormat.
1240
    """ControlDirFormat base class for .bzr/ directories.
1534.4.39 by Robert Collins
Basic BzrDir support.
1241
3943.8.1 by Marius Kruger
remove all trailing whitespace from bzr source
1242
    Formats are placed in a dict by their format string for reference
1534.4.39 by Robert Collins
Basic BzrDir support.
1243
    during bzrdir opening. These should be subclasses of BzrDirFormat
1244
    for consistency.
1245
1246
    Once a format is deprecated, just deprecate the initialize and open
3943.8.1 by Marius Kruger
remove all trailing whitespace from bzr source
1247
    methods on the format class. Do not deprecate the object, as the
1534.4.39 by Robert Collins
Basic BzrDir support.
1248
    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.
1249
    """
1250
1553.5.69 by Martin Pool
BzrDirFormat subclasses can now control what kind of overall lock is used.
1251
    _lock_file_name = 'branch-lock'
1252
1253
    # _lock_class must be set in subclasses to the lock type, typ.
1254
    # TransportLock or LockDir
1255
1534.4.39 by Robert Collins
Basic BzrDir support.
1256
    def get_format_string(self):
1257
        """Return the ASCII format string that identifies this format."""
1258
        raise NotImplementedError(self.get_format_string)
1259
1651.1.6 by Martin Pool
Clean up clone-bzrdir code
1260
    def initialize_on_transport(self, transport):
1608.2.8 by Martin Pool
Separate out BzrDir.initialize_on_transport so it
1261
        """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)
1262
        try:
1263
            # can we hand off the request to the smart server rather than using
1264
            # vfs calls?
1265
            client_medium = transport.get_smart_medium()
1266
        except errors.NoSmartMedium:
1267
            return self._initialize_on_transport_vfs(transport)
1268
        else:
1269
            # Current RPC's only know how to create bzr metadir1 instances, so
1270
            # we still delegate to vfs methods if the requested format is not a
1271
            # metadir1
1272
            if type(self) != BzrDirMetaFormat1:
1273
                return self._initialize_on_transport_vfs(transport)
1274
            remote_format = RemoteBzrDirFormat()
1275
            self._supply_sub_formats_to(remote_format)
1276
            return remote_format.initialize_on_transport(transport)
1277
4294.2.4 by Robert Collins
Move dir, bzrdir and repo acquisition into a single method on bzrdir format.
1278
    def initialize_on_transport_ex(self, transport, use_existing_dir=False,
1279
        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.
1280
        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.
1281
        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.
1282
        """Create this format on transport.
1283
4294.2.7 by Robert Collins
Start building up a BzrDir.initialize_ex verb for the smart server.
1284
        The directory to initialize will be created.
1285
4294.2.4 by Robert Collins
Move dir, bzrdir and repo acquisition into a single method on bzrdir format.
1286
        :param force_new_repo: Do not use a shared repository for the target,
1287
                               even if one is available.
1288
        :param create_prefix: Create any missing directories leading up to
1289
            to_transport.
1290
        :param use_existing_dir: Use an existing directory if one exists.
1291
        :param stacked_on: A url to stack any created branch on, None to follow
1292
            any target stacking policy.
1293
        :param stack_on_pwd: If stack_on is relative, the location it is
1294
            relative to.
1295
        :param repo_format_name: If non-None, a repository will be
1296
            made-or-found. Should none be found, or if force_new_repo is True
1297
            the repo_format_name is used to select the format of repository to
1298
            create.
1299
        :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.
1300
            for a new shared repository when one is made. None to use whatever
1301
            default the format has.
4294.2.4 by Robert Collins
Move dir, bzrdir and repo acquisition into a single method on bzrdir format.
1302
        :param shared_repo: Control whether made repositories are shared or
1303
            not.
4294.2.8 by Robert Collins
Reduce round trips pushing new branches substantially.
1304
        :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.
1305
        :return: repo, bzrdir, require_stacking, repository_policy. repo is
1306
            None if none was created or found, bzrdir is always valid.
1307
            require_stacking is the result of examining the stacked_on
1308
            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.
1309
        """
4294.2.8 by Robert Collins
Reduce round trips pushing new branches substantially.
1310
        if not vfs_only:
1311
            # Try to hand off to a smart server 
1312
            try:
1313
                client_medium = transport.get_smart_medium()
1314
            except errors.NoSmartMedium:
1315
                pass
1316
            else:
1317
                # TODO: lookup the local format from a server hint.
1318
                remote_dir_format = RemoteBzrDirFormat()
1319
                remote_dir_format._network_name = self.network_name()
1320
                self._supply_sub_formats_to(remote_dir_format)
1321
                return remote_dir_format.initialize_on_transport_ex(transport,
1322
                    use_existing_dir=use_existing_dir, create_prefix=create_prefix,
1323
                    force_new_repo=force_new_repo, stacked_on=stacked_on,
1324
                    stack_on_pwd=stack_on_pwd, repo_format_name=repo_format_name,
1325
                    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.
1326
        # XXX: Refactor the create_prefix/no_create_prefix code into a
1327
        #      common helper function
1328
        # The destination may not exist - if so make it according to policy.
1329
        def make_directory(transport):
1330
            transport.mkdir('.')
1331
            return transport
1332
        def redirected(transport, e, redirection_notice):
1333
            note(redirection_notice)
1334
            return transport._redirected_to(e.source, e.target)
1335
        try:
1336
            transport = do_catching_redirections(make_directory, transport,
1337
                redirected)
1338
        except errors.FileExists:
1339
            if not use_existing_dir:
1340
                raise
1341
        except errors.NoSuchFile:
1342
            if not create_prefix:
1343
                raise
1344
            transport.create_prefix()
1345
1346
        require_stacking = (stacked_on is not None)
1347
        # Now the target directory exists, but doesn't have a .bzr
1348
        # directory. So we need to create it, along with any work to create
1349
        # all of the dependent branches, etc.
4294.2.5 by Robert Collins
Reasonable unit test coverage for initialize_on_transport_ex.
1350
4294.2.4 by Robert Collins
Move dir, bzrdir and repo acquisition into a single method on bzrdir format.
1351
        result = self.initialize_on_transport(transport)
1352
        if repo_format_name:
4294.2.5 by Robert Collins
Reasonable unit test coverage for initialize_on_transport_ex.
1353
            try:
1354
                # use a custom format
1355
                result._format.repository_format = \
1356
                    repository.network_format_registry.get(repo_format_name)
1357
            except AttributeError:
1358
                # The format didn't permit it to be set.
1359
                pass
4294.2.4 by Robert Collins
Move dir, bzrdir and repo acquisition into a single method on bzrdir format.
1360
            # A repository is desired, either in-place or shared.
1361
            repository_policy = result.determine_repository_policy(
1362
                force_new_repo, stacked_on, stack_on_pwd,
1363
                require_stacking=require_stacking)
1364
            result_repo, is_new_repo = repository_policy.acquire_repository(
1365
                make_working_trees, shared_repo)
1366
            if not require_stacking and repository_policy._require_stacking:
1367
                require_stacking = True
1368
                result._format.require_stacking()
4307.2.2 by Robert Collins
Lock repositories created by BzrDirFormat.initialize_on_transport_ex.
1369
            result_repo.lock_write()
4294.2.4 by Robert Collins
Move dir, bzrdir and repo acquisition into a single method on bzrdir format.
1370
        else:
1371
            result_repo = None
1372
            repository_policy = None
1373
        return result_repo, result, require_stacking, repository_policy
1374
4017.2.2 by Robert Collins
Perform creation of BzrDirMetaFormat1 control directories using an RPC where possible. (Robert Collins)
1375
    def _initialize_on_transport_vfs(self, transport):
1376
        """Initialize a new bzrdir using VFS calls.
4032.1.2 by John Arbash Meinel
Track down a few more files that have trailing whitespace.
1377
4017.2.2 by Robert Collins
Perform creation of BzrDirMetaFormat1 control directories using an RPC where possible. (Robert Collins)
1378
        :param transport: The transport to create the .bzr directory in.
1379
        :return: A
1380
        """
1381
        # Since we are creating a .bzr directory, inherit the
1534.4.39 by Robert Collins
Basic BzrDir support.
1382
        # mode from the root directory
1996.3.3 by John Arbash Meinel
Shave off another 40ms by demand loading branch and bzrdir
1383
        temp_control = lockable_files.LockableFiles(transport,
1384
                            '', lockable_files.TransportLock)
1534.4.39 by Robert Collins
Basic BzrDir support.
1385
        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.
1386
                                      # FIXME: RBC 20060121 don't peek under
1534.4.39 by Robert Collins
Basic BzrDir support.
1387
                                      # the covers
1388
                                      mode=temp_control._dir_mode)
3224.5.24 by Andrew Bennetts
More minor import tidying suggested by pyflakes.
1389
        if sys.platform == 'win32' and isinstance(transport, local.LocalTransport):
3023.1.2 by Alexander Belchenko
Martin's review.
1390
            win32utils.set_file_attr_hidden(transport._abspath('.bzr'))
1534.4.39 by Robert Collins
Basic BzrDir support.
1391
        file_mode = temp_control._file_mode
1392
        del temp_control
3407.2.5 by Martin Pool
Deprecate LockableFiles.put_utf8
1393
        bzrdir_transport = transport.clone('.bzr')
1394
        utf8_files = [('README',
3250.2.1 by Marius Kruger
update .bzr/README to not refer to Bazaar-NG, and add link to website.
1395
                       "This is a Bazaar control directory.\n"
1396
                       "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).
1397
                       "See http://bazaar.canonical.com/ for more information about Bazaar.\n"),
1534.4.39 by Robert Collins
Basic BzrDir support.
1398
                      ('branch-format', self.get_format_string()),
1399
                      ]
1400
        # NB: no need to escape relative paths that are url safe.
3407.2.5 by Martin Pool
Deprecate LockableFiles.put_utf8
1401
        control_files = lockable_files.LockableFiles(bzrdir_transport,
1402
            self._lock_file_name, self._lock_class)
1553.5.60 by Martin Pool
New LockableFiles.create_lock() method
1403
        control_files.create_lock()
1534.4.39 by Robert Collins
Basic BzrDir support.
1404
        control_files.lock_write()
1405
        try:
3407.2.5 by Martin Pool
Deprecate LockableFiles.put_utf8
1406
            for (filename, content) in utf8_files:
3407.2.12 by Martin Pool
Fix creation mode of control files
1407
                bzrdir_transport.put_bytes(filename, content,
1408
                    mode=file_mode)
1534.4.39 by Robert Collins
Basic BzrDir support.
1409
        finally:
1410
            control_files.unlock()
4017.2.2 by Robert Collins
Perform creation of BzrDirMetaFormat1 control directories using an RPC where possible. (Robert Collins)
1411
        return self.open(transport, _found=True)
1534.4.39 by Robert Collins
Basic BzrDir support.
1412
1413
    def open(self, transport, _found=False):
1414
        """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
1415
1534.4.39 by Robert Collins
Basic BzrDir support.
1416
        _found is a private parameter, do not use it.
1417
        """
1418
        if not _found:
5363.2.20 by Jelmer Vernooij
use controldir.X
1419
            found_format = controldir.ControlDirFormat.find_format(transport)
2090.2.2 by Martin Pool
Fix an assertion with side effects
1420
            if not isinstance(found_format, self.__class__):
1421
                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
1422
                        "format %s"
2090.2.2 by Martin Pool
Fix an assertion with side effects
1423
                        % (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.
1424
            # Allow subclasses - use the found format.
1425
            self._supply_sub_formats_to(found_format)
1426
            return found_format._open(transport)
1534.4.40 by Robert Collins
Add RepositoryFormats and allow bzrdir.open or create _repository to be used.
1427
        return self._open(transport)
1428
1429
    def _open(self, transport):
1430
        """Template method helper for opening BzrDirectories.
1431
1432
        This performs the actual open and any additional logic or parameter
1433
        passing.
1434
        """
1435
        raise NotImplementedError(self._open)
1534.4.39 by Robert Collins
Basic BzrDir support.
1436
1437
    @classmethod
1438
    def register_format(klass, format):
5363.2.4 by Jelmer Vernooij
Introduce probers, use controldir in a couple more places.
1439
        BzrProber.register_bzrdir_format(format)
4070.2.1 by Robert Collins
Add a BzrDirFormat.network_name.
1440
        # bzr native formats have a network name of their format string.
5363.2.23 by Jelmer Vernooij
Move network_format_registry to bzrlib.controldir.
1441
        controldir.network_format_registry.register(format.get_format_string(), format.__class__)
5363.2.20 by Jelmer Vernooij
use controldir.X
1442
        controldir.ControlDirFormat.register_format(format)
2204.4.13 by Aaron Bentley
Update all test cases to avoid set_default_format
1443
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.
1444
    def _supply_sub_formats_to(self, other_format):
1445
        """Give other_format the same values for sub formats as this has.
1446
1447
        This method is expected to be used when parameterising a
1448
        RemoteBzrDirFormat instance with the parameters from a
1449
        BzrDirMetaFormat1 instance.
1450
1451
        :param other_format: other_format is a format which should be
1452
            compatible with whatever sub formats are supported by self.
1453
        :return: None.
1454
        """
1455
1534.4.39 by Robert Collins
Basic BzrDir support.
1456
    @classmethod
1457
    def unregister_format(klass, format):
5363.2.6 by Jelmer Vernooij
Add ControlDirFormat.{un,}register_{server_,}prober.
1458
        BzrProber.unregister_bzrdir_format(format)
5363.2.20 by Jelmer Vernooij
use controldir.X
1459
        controldir.ControlDirFormat.unregister_format(format)
5363.2.23 by Jelmer Vernooij
Move network_format_registry to bzrlib.controldir.
1460
        controldir.network_format_registry.remove(format.get_format_string())
1733.1.1 by Robert Collins
Support non '.bzr' control directories in bzrdir.
1461
1462
1534.4.44 by Robert Collins
Make a new BzrDir format that uses a versioned branch format in a branch/ subdirectory.
1463
class BzrDirMetaFormat1(BzrDirFormat):
1464
    """Bzr meta control format 1
1465
1466
    This is the first format with split out working tree, branch and repository
1467
    disk storage.
1468
    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.
1469
     - Format 3 working trees [optional]
1470
     - Format 5 branches [optional]
1471
     - 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.
1472
    """
1473
1996.3.3 by John Arbash Meinel
Shave off another 40ms by demand loading branch and bzrdir
1474
    _lock_class = lockdir.LockDir
1553.5.69 by Martin Pool
BzrDirFormat subclasses can now control what kind of overall lock is used.
1475
2100.3.10 by Aaron Bentley
Ensure added references are serialized properly, beef up Workingtreee3
1476
    def __init__(self):
1477
        self._workingtree_format = None
2230.3.1 by Aaron Bentley
Get branch6 creation working
1478
        self._branch_format = None
4070.2.3 by Robert Collins
Get BzrDir.cloning_metadir working.
1479
        self._repository_format = None
2100.3.10 by Aaron Bentley
Ensure added references are serialized properly, beef up Workingtreee3
1480
2100.3.15 by Aaron Bentley
get test suite passing
1481
    def __eq__(self, other):
1482
        if other.__class__ is not self.__class__:
1483
            return False
1484
        if other.repository_format != self.repository_format:
1485
            return False
1486
        if other.workingtree_format != self.workingtree_format:
1487
            return False
1488
        return True
1489
2100.3.35 by Aaron Bentley
equality operations on bzrdir
1490
    def __ne__(self, other):
1491
        return not self == other
1492
2230.3.55 by Aaron Bentley
Updates from review
1493
    def get_branch_format(self):
2230.3.1 by Aaron Bentley
Get branch6 creation working
1494
        if self._branch_format is None:
1495
            from bzrlib.branch import BranchFormat
1496
            self._branch_format = BranchFormat.get_default_format()
1497
        return self._branch_format
1498
2230.3.55 by Aaron Bentley
Updates from review
1499
    def set_branch_format(self, format):
2230.3.1 by Aaron Bentley
Get branch6 creation working
1500
        self._branch_format = format
1501
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.
1502
    def require_stacking(self, stack_on=None, possible_transports=None,
1503
            _skip_repo=False):
4401.1.2 by John Arbash Meinel
Move the logic back up into BzrDirFormat1.require_stacking, passing in the extra params.
1504
        """We have a request to stack, try to ensure the formats support it.
1505
1506
        :param stack_on: If supplied, it is the URL to a branch that we want to
1507
            stack on. Check to see if that format supports stacking before
1508
            forcing an upgrade.
1509
        """
1510
        # Stacking is desired. requested by the target, but does the place it
1511
        # points at support stacking? If it doesn't then we should
1512
        # not implicitly upgrade. We check this here.
1513
        new_repo_format = None
1514
        new_branch_format = None
1515
1516
        # a bit of state for get_target_branch so that we don't try to open it
1517
        # 2 times, for both repo *and* branch
1518
        target = [None, False, None] # target_branch, checked, upgrade anyway
1519
        def get_target_branch():
1520
            if target[1]:
1521
                # We've checked, don't check again
1522
                return target
1523
            if stack_on is None:
1524
                # No target format, that means we want to force upgrading
1525
                target[:] = [None, True, True]
1526
                return target
1527
            try:
1528
                target_dir = BzrDir.open(stack_on,
1529
                    possible_transports=possible_transports)
1530
            except errors.NotBranchError:
1531
                # Nothing there, don't change formats
1532
                target[:] = [None, True, False]
1533
                return target
1534
            except errors.JailBreak:
1535
                # JailBreak, JFDI and upgrade anyway
1536
                target[:] = [None, True, True]
1537
                return target
1538
            try:
1539
                target_branch = target_dir.open_branch()
1540
            except errors.NotBranchError:
1541
                # No branch, don't upgrade formats
1542
                target[:] = [None, True, False]
1543
                return target
1544
            target[:] = [target_branch, True, False]
1545
            return target
1546
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.
1547
        if (not _skip_repo and
1548
                 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.
1549
            # We need to upgrade the Repository.
1550
            target_branch, _, do_upgrade = get_target_branch()
1551
            if target_branch is None:
1552
                # We don't have a target branch, should we upgrade anyway?
1553
                if do_upgrade:
1554
                    # stack_on is inaccessible, JFDI.
1555
                    # TODO: bad monkey, hard-coded formats...
1556
                    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.
1557
                        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.
1558
                    else:
4401.1.3 by John Arbash Meinel
Change back to defaulting to --1.6 format, and update the blackbox tests.
1559
                        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.
1560
            else:
1561
                # If the target already supports stacking, then we know the
1562
                # project is already able to use stacking, so auto-upgrade
1563
                # for them
1564
                new_repo_format = target_branch.repository._format
1565
                if not new_repo_format.supports_external_lookups:
1566
                    # target doesn't, source doesn't, so don't auto upgrade
1567
                    # repo
1568
                    new_repo_format = None
1569
            if new_repo_format is not None:
1570
                self.repository_format = new_repo_format
1571
                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.
1572
                     ' 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.
1573
                     new_repo_format.get_format_description())
1574
3904.3.1 by Andrew Bennetts
Probable fix for GaryvdM's bug when pushing a stacked qbzr branch to Launchpad.
1575
        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.
1576
            # We just checked the repo, now lets check if we need to
1577
            # upgrade the branch format
1578
            target_branch, _, do_upgrade = get_target_branch()
1579
            if target_branch is None:
1580
                if do_upgrade:
1581
                    # TODO: bad monkey, hard-coded formats...
1582
                    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.
1583
            else:
4401.1.2 by John Arbash Meinel
Move the logic back up into BzrDirFormat1.require_stacking, passing in the extra params.
1584
                new_branch_format = target_branch._format
1585
                if not new_branch_format.supports_stacking():
1586
                    new_branch_format = None
1587
            if new_branch_format is not None:
1588
                # Does support stacking, use its format.
1589
                self.set_branch_format(new_branch_format)
1590
                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.
1591
                     ' 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.
1592
                     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.
1593
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.
1594
    def get_converter(self, format=None):
1595
        """See BzrDirFormat.get_converter()."""
1596
        if format is None:
1597
            format = BzrDirFormat.get_default_format()
1598
        if not isinstance(self, format.__class__):
1599
            # converting away from metadir is not implemented
1600
            raise NotImplementedError(self.get_converter)
1601
        return ConvertMetaToMeta(format)
1602
1534.4.44 by Robert Collins
Make a new BzrDir format that uses a versioned branch format in a branch/ subdirectory.
1603
    def get_format_string(self):
1604
        """See BzrDirFormat.get_format_string()."""
1605
        return "Bazaar-NG meta directory, format 1\n"
1606
1624.3.19 by Olaf Conradi
New call get_format_description to give a user-friendly description of a
1607
    def get_format_description(self):
1608
        """See BzrDirFormat.get_format_description()."""
1609
        return "Meta directory format 1"
1610
4070.2.1 by Robert Collins
Add a BzrDirFormat.network_name.
1611
    def network_name(self):
1612
        return self.get_format_string()
1613
1534.4.44 by Robert Collins
Make a new BzrDir format that uses a versioned branch format in a branch/ subdirectory.
1614
    def _open(self, transport):
1615
        """See BzrDirFormat._open."""
4294.2.12 by Robert Collins
Prevent aliasing issues with BzrDirMetaFormat1 by making a new format object in _open.
1616
        # Create a new format instance because otherwise initialisation of new
1617
        # metadirs share the global default format object leading to alias
1618
        # problems.
1619
        format = BzrDirMetaFormat1()
1620
        self._supply_sub_formats_to(format)
1621
        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.
1622
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.
1623
    def __return_repository_format(self):
1624
        """Circular import protection."""
4070.2.3 by Robert Collins
Get BzrDir.cloning_metadir working.
1625
        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.
1626
            return self._repository_format
5651.3.2 by Jelmer Vernooij
Fix deprecation warnings in test suite.
1627
        from bzrlib.repository import format_registry
1628
        return format_registry.get_default()
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.
1629
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.
1630
    def _set_repository_format(self, value):
3015.2.8 by Robert Collins
Typo in __set_repository_format's docstring.
1631
        """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.
1632
        self._repository_format = value
1553.5.72 by Martin Pool
Clean up test for Branch5 lockdirs
1633
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.
1634
    repository_format = property(__return_repository_format,
1635
        _set_repository_format)
1636
1637
    def _supply_sub_formats_to(self, other_format):
1638
        """Give other_format the same values for sub formats as this has.
1639
1640
        This method is expected to be used when parameterising a
1641
        RemoteBzrDirFormat instance with the parameters from a
1642
        BzrDirMetaFormat1 instance.
1643
1644
        :param other_format: other_format is a format which should be
1645
            compatible with whatever sub formats are supported by self.
1646
        :return: None.
1647
        """
1648
        if getattr(self, '_repository_format', None) is not None:
1649
            other_format.repository_format = self.repository_format
1650
        if self._branch_format is not None:
1651
            other_format._branch_format = self._branch_format
1652
        if self._workingtree_format is not None:
1653
            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.
1654
2100.3.10 by Aaron Bentley
Ensure added references are serialized properly, beef up Workingtreee3
1655
    def __get_workingtree_format(self):
1656
        if self._workingtree_format is None:
1657
            from bzrlib.workingtree import WorkingTreeFormat
1658
            self._workingtree_format = WorkingTreeFormat.get_default_format()
1659
        return self._workingtree_format
1660
1661
    def __set_workingtree_format(self, wt_format):
1662
        self._workingtree_format = wt_format
1663
1664
    workingtree_format = property(__get_workingtree_format,
1665
                                  __set_workingtree_format)
1666
1534.4.44 by Robert Collins
Make a new BzrDir format that uses a versioned branch format in a branch/ subdirectory.
1667
2164.2.13 by v.ladeuil+lp at free
Add tests for redirection. Preserve transport decorations.
1668
# Register bzr formats
1666.1.4 by Robert Collins
* 'Metadir' is now the default disk format. This improves behaviour in
1669
__default_format = BzrDirMetaFormat1()
1534.4.39 by Robert Collins
Basic BzrDir support.
1670
BzrDirFormat.register_format(__default_format)
5363.2.20 by Jelmer Vernooij
use controldir.X
1671
controldir.ControlDirFormat._default_format = __default_format
1534.4.39 by Robert Collins
Basic BzrDir support.
1672
1673
1534.5.7 by Robert Collins
Start factoring out the upgrade policy logic.
1674
class Converter(object):
1675
    """Converts a disk format object from one format to another."""
1676
1534.5.10 by Robert Collins
Make upgrade driver unaware of the specific formats in play.
1677
    def convert(self, to_convert, pb):
1678
        """Perform the conversion of to_convert, giving feedback via pb.
1534.5.7 by Robert Collins
Start factoring out the upgrade policy logic.
1679
1534.5.10 by Robert Collins
Make upgrade driver unaware of the specific formats in play.
1680
        :param to_convert: The disk object to convert.
1534.5.7 by Robert Collins
Start factoring out the upgrade policy logic.
1681
        :param pb: a progress bar to use for progress information.
1682
        """
1683
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.
1684
    def step(self, message):
1685
        """Update the pb by a step."""
1686
        self.count +=1
1687
        self.pb.update(message, self.count, self.total)
1688
1534.5.7 by Robert Collins
Start factoring out the upgrade policy logic.
1689
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.
1690
class ConvertMetaToMeta(Converter):
1691
    """Converts the components of metadirs."""
1692
1693
    def __init__(self, target_format):
1694
        """Create a metadir to metadir converter.
1695
1696
        :param target_format: The final metadir format that is desired.
1697
        """
1698
        self.target_format = target_format
1699
1700
    def convert(self, to_convert, pb):
1701
        """See Converter.convert()."""
1702
        self.bzrdir = to_convert
4961.2.14 by Martin Pool
Further pb cleanups
1703
        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.
1704
        self.count = 0
1705
        self.total = 1
1706
        self.step('checking repository format')
1707
        try:
1708
            repo = self.bzrdir.open_repository()
1709
        except errors.NoRepositoryPresent:
1710
            pass
1711
        else:
1712
            if not isinstance(repo._format, self.target_format.repository_format.__class__):
1713
                from bzrlib.repository import CopyConverter
4471.2.2 by Martin Pool
Deprecate ProgressTask.note
1714
                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.
1715
                converter = CopyConverter(self.target_format.repository_format)
1716
                converter.convert(repo, pb)
4997.1.3 by Jelmer Vernooij
Use list_branches during upgrades.
1717
        for branch in self.bzrdir.list_branches():
2255.12.1 by Robert Collins
Implement upgrade for working trees.
1718
            # TODO: conversions of Branch and Tree should be done by
3221.11.5 by Robert Collins
Correctly handle multi-step branch upgrades.
1719
            # InterXFormat lookups/some sort of registry.
2230.3.29 by Aaron Bentley
Implement conversion to branch 6
1720
            # Avoid circular imports
1721
            from bzrlib import branch as _mod_branch
3221.11.5 by Robert Collins
Correctly handle multi-step branch upgrades.
1722
            old = branch._format.__class__
1723
            new = self.target_format.get_branch_format().__class__
1724
            while old != new:
1725
                if (old == _mod_branch.BzrBranchFormat5 and
1726
                    new in (_mod_branch.BzrBranchFormat6,
4273.1.13 by Aaron Bentley
Implement upgrade from branch format 7 to 8.
1727
                        _mod_branch.BzrBranchFormat7,
1728
                        _mod_branch.BzrBranchFormat8)):
3221.11.5 by Robert Collins
Correctly handle multi-step branch upgrades.
1729
                    branch_converter = _mod_branch.Converter5to6()
1730
                elif (old == _mod_branch.BzrBranchFormat6 and
4273.1.13 by Aaron Bentley
Implement upgrade from branch format 7 to 8.
1731
                    new in (_mod_branch.BzrBranchFormat7,
1732
                            _mod_branch.BzrBranchFormat8)):
3221.11.5 by Robert Collins
Correctly handle multi-step branch upgrades.
1733
                    branch_converter = _mod_branch.Converter6to7()
4273.1.13 by Aaron Bentley
Implement upgrade from branch format 7 to 8.
1734
                elif (old == _mod_branch.BzrBranchFormat7 and
1735
                      new is _mod_branch.BzrBranchFormat8):
1736
                    branch_converter = _mod_branch.Converter7to8()
3221.11.5 by Robert Collins
Correctly handle multi-step branch upgrades.
1737
                else:
4608.1.3 by Martin Pool
BadConversionTarget error includes source format
1738
                    raise errors.BadConversionTarget("No converter", new,
1739
                        branch._format)
2230.3.29 by Aaron Bentley
Implement conversion to branch 6
1740
                branch_converter.convert(branch)
3221.11.5 by Robert Collins
Correctly handle multi-step branch upgrades.
1741
                branch = self.bzrdir.open_branch()
1742
                old = branch._format.__class__
2255.12.1 by Robert Collins
Implement upgrade for working trees.
1743
        try:
2323.6.4 by Martin Pool
BzrDir._check_supported now also takes care of recommending upgrades, which
1744
            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.
1745
        except (errors.NoWorkingTree, errors.NotLocalUrl):
2255.12.1 by Robert Collins
Implement upgrade for working trees.
1746
            pass
1747
        else:
1748
            # TODO: conversions of Branch and Tree should be done by
1749
            # InterXFormat lookups
1750
            if (isinstance(tree, workingtree.WorkingTree3) and
3907.2.3 by Ian Clatworthy
DirStateWorkingTree and DirStateWorkingTreeFormat base classes introduced
1751
                not isinstance(tree, workingtree_4.DirStateWorkingTree) and
2255.12.1 by Robert Collins
Implement upgrade for working trees.
1752
                isinstance(self.target_format.workingtree_format,
3907.2.3 by Ian Clatworthy
DirStateWorkingTree and DirStateWorkingTreeFormat base classes introduced
1753
                    workingtree_4.DirStateWorkingTreeFormat)):
2255.12.1 by Robert Collins
Implement upgrade for working trees.
1754
                workingtree_4.Converter3to4().convert(tree)
3907.2.3 by Ian Clatworthy
DirStateWorkingTree and DirStateWorkingTreeFormat base classes introduced
1755
            if (isinstance(tree, workingtree_4.DirStateWorkingTree) and
1756
                not isinstance(tree, workingtree_4.WorkingTree5) and
3586.1.8 by Ian Clatworthy
add workingtree_5 and initial upgrade code
1757
                isinstance(self.target_format.workingtree_format,
3907.2.3 by Ian Clatworthy
DirStateWorkingTree and DirStateWorkingTreeFormat base classes introduced
1758
                    workingtree_4.WorkingTreeFormat5)):
1759
                workingtree_4.Converter4to5().convert(tree)
4210.4.2 by Ian Clatworthy
split filtered views support out into WorkingTreeFormat6
1760
            if (isinstance(tree, workingtree_4.DirStateWorkingTree) and
1761
                not isinstance(tree, workingtree_4.WorkingTree6) and
1762
                isinstance(self.target_format.workingtree_format,
1763
                    workingtree_4.WorkingTreeFormat6)):
1764
                workingtree_4.Converter4or5to6().convert(tree)
4961.2.14 by Martin Pool
Further pb cleanups
1765
        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.
1766
        return to_convert
1731.2.18 by Aaron Bentley
Get extract in repository under test
1767
1768
4294.2.7 by Robert Collins
Start building up a BzrDir.initialize_ex verb for the smart server.
1769
# This is not in remote.py because it's relatively small, and needs to be
1770
# registered. Putting it in remote.py creates a circular import problem.
2018.5.28 by Robert Collins
Fix RemoteBzrDirFormat probe api usage.
1771
# we can make it a lazy object if the control formats is turned into something
1772
# like a registry.
2018.5.25 by Andrew Bennetts
Make sure RemoteBzrDirFormat is always registered (John Arbash Meinel, Robert Collins, Andrew Bennetts).
1773
class RemoteBzrDirFormat(BzrDirMetaFormat1):
1774
    """Format representing bzrdirs accessed via a smart server"""
1775
5393.4.3 by Jelmer Vernooij
Consistent spelling.
1776
    supports_workingtrees = False
5393.4.1 by Jelmer Vernooij
Add ControlDirFormat.supports_workingtrees.
1777
4070.2.1 by Robert Collins
Add a BzrDirFormat.network_name.
1778
    def __init__(self):
1779
        BzrDirMetaFormat1.__init__(self)
4934.4.3 by Martin Pool
Initializing a bzrdir shouldn't mutate the RemoteBzrDirFormat
1780
        # XXX: It's a bit ugly that the network name is here, because we'd
1781
        # like to believe that format objects are stateless or at least
1782
        # 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
1783
        # it's returned.  See <https://bugs.launchpad.net/bzr/+bug/504102>
4070.2.1 by Robert Collins
Add a BzrDirFormat.network_name.
1784
        self._network_name = None
1785
4934.3.2 by Martin Pool
Add RemoteBzrDirFormat repr
1786
    def __repr__(self):
1787
        return "%s(_network_name=%r)" % (self.__class__.__name__,
1788
            self._network_name)
1789
2018.5.25 by Andrew Bennetts
Make sure RemoteBzrDirFormat is always registered (John Arbash Meinel, Robert Collins, Andrew Bennetts).
1790
    def get_format_description(self):
4792.1.1 by Andrew Bennetts
Show real branch/repo format description in 'info -v' over HPSS.
1791
        if self._network_name:
5363.2.23 by Jelmer Vernooij
Move network_format_registry to bzrlib.controldir.
1792
            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
1793
            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).
1794
        return 'bzr remote bzrdir'
3943.8.1 by Marius Kruger
remove all trailing whitespace from bzr source
1795
4032.3.2 by Robert Collins
Create and use a RPC call to create branches on bzr servers rather than using VFS calls.
1796
    def get_format_string(self):
1797
        raise NotImplementedError(self.get_format_string)
4032.3.6 by Robert Collins
Fix test_source errors.
1798
4070.2.1 by Robert Collins
Add a BzrDirFormat.network_name.
1799
    def network_name(self):
1800
        if self._network_name:
1801
            return self._network_name
1802
        else:
1803
            raise AssertionError("No network name set.")
1804
2018.5.42 by Robert Collins
Various hopefully improvements, but wsgi is broken, handing over to spiv :).
1805
    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.
1806
        try:
1807
            # 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.
1808
            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.
1809
        except errors.NoSmartMedium:
1810
            # TODO: lookup the local format from a server hint.
1811
            local_dir_format = BzrDirMetaFormat1()
1812
            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.
1813
        client = _SmartClient(client_medium)
2018.5.42 by Robert Collins
Various hopefully improvements, but wsgi is broken, handing over to spiv :).
1814
        path = client.remote_path_from_transport(transport)
4384.1.1 by Andrew Bennetts
Translate ErrorFromSmartServer in RemoteBzrDirFormat.
1815
        try:
1816
            response = client.call('BzrDirFormat.initialize', path)
1817
        except errors.ErrorFromSmartServer, err:
1818
            remote._translate_error(err, path=path)
3376.2.4 by Martin Pool
Remove every assert statement from bzrlib!
1819
        if response[0] != 'ok':
1820
            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.
1821
        format = RemoteBzrDirFormat()
1822
        self._supply_sub_formats_to(format)
1823
        return remote.RemoteBzrDir(transport, format)
2018.5.42 by Robert Collins
Various hopefully improvements, but wsgi is broken, handing over to spiv :).
1824
4294.2.8 by Robert Collins
Reduce round trips pushing new branches substantially.
1825
    def parse_NoneTrueFalse(self, arg):
1826
        if not arg:
1827
            return None
1828
        if arg == 'False':
1829
            return False
1830
        if arg == 'True':
1831
            return True
1832
        raise AssertionError("invalid arg %r" % arg)
1833
4294.2.7 by Robert Collins
Start building up a BzrDir.initialize_ex verb for the smart server.
1834
    def _serialize_NoneTrueFalse(self, arg):
1835
        if arg is False:
1836
            return 'False'
1837
        if arg:
1838
            return 'True'
1839
        return ''
1840
4294.2.8 by Robert Collins
Reduce round trips pushing new branches substantially.
1841
    def _serialize_NoneString(self, arg):
1842
        return arg or ''
1843
4294.2.7 by Robert Collins
Start building up a BzrDir.initialize_ex verb for the smart server.
1844
    def initialize_on_transport_ex(self, transport, use_existing_dir=False,
1845
        create_prefix=False, force_new_repo=False, stacked_on=None,
1846
        stack_on_pwd=None, repo_format_name=None, make_working_trees=None,
1847
        shared_repo=False):
1848
        try:
1849
            # hand off the request to the smart server
1850
            client_medium = transport.get_smart_medium()
1851
        except errors.NoSmartMedium:
4294.2.9 by Robert Collins
Fixup tests broken by cleaning up the layering.
1852
            do_vfs = True
1853
        else:
1854
            # Decline to open it if the server doesn't support our required
1855
            # version (3) so that the VFS-based transport will do it.
1856
            if client_medium.should_probe():
1857
                try:
1858
                    server_version = client_medium.protocol_version()
1859
                    if server_version != '2':
1860
                        do_vfs = True
1861
                    else:
1862
                        do_vfs = False
1863
                except errors.SmartProtocolError:
1864
                    # Apparently there's no usable smart server there, even though
1865
                    # the medium supports the smart protocol.
1866
                    do_vfs = True
1867
            else:
1868
                do_vfs = False
1869
        if not do_vfs:
1870
            client = _SmartClient(client_medium)
1871
            path = client.remote_path_from_transport(transport)
4436.1.1 by Andrew Bennetts
Rename BzrDirFormat.initialize_ex verb to BzrDirFormat.initialize_ex_1.16.
1872
            if client_medium._is_remote_before((1, 16)):
4294.2.9 by Robert Collins
Fixup tests broken by cleaning up the layering.
1873
                do_vfs = True
1874
        if do_vfs:
4294.2.7 by Robert Collins
Start building up a BzrDir.initialize_ex verb for the smart server.
1875
            # TODO: lookup the local format from a server hint.
1876
            local_dir_format = BzrDirMetaFormat1()
1877
            self._supply_sub_formats_to(local_dir_format)
1878
            return local_dir_format.initialize_on_transport_ex(transport,
1879
                use_existing_dir=use_existing_dir, create_prefix=create_prefix,
1880
                force_new_repo=force_new_repo, stacked_on=stacked_on,
1881
                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.
1882
                make_working_trees=make_working_trees, shared_repo=shared_repo,
1883
                vfs_only=True)
4384.1.1 by Andrew Bennetts
Translate ErrorFromSmartServer in RemoteBzrDirFormat.
1884
        return self._initialize_on_transport_ex_rpc(client, path, transport,
1885
            use_existing_dir, create_prefix, force_new_repo, stacked_on,
1886
            stack_on_pwd, repo_format_name, make_working_trees, shared_repo)
1887
1888
    def _initialize_on_transport_ex_rpc(self, client, path, transport,
1889
        use_existing_dir, create_prefix, force_new_repo, stacked_on,
1890
        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.
1891
        args = []
1892
        args.append(self._serialize_NoneTrueFalse(use_existing_dir))
4294.2.8 by Robert Collins
Reduce round trips pushing new branches substantially.
1893
        args.append(self._serialize_NoneTrueFalse(create_prefix))
1894
        args.append(self._serialize_NoneTrueFalse(force_new_repo))
1895
        args.append(self._serialize_NoneString(stacked_on))
1896
        # stack_on_pwd is often/usually our transport
1897
        if stack_on_pwd:
1898
            try:
1899
                stack_on_pwd = transport.relpath(stack_on_pwd)
1900
                if not stack_on_pwd:
1901
                    stack_on_pwd = '.'
1902
            except errors.PathNotChild:
1903
                pass
1904
        args.append(self._serialize_NoneString(stack_on_pwd))
1905
        args.append(self._serialize_NoneString(repo_format_name))
1906
        args.append(self._serialize_NoneTrueFalse(make_working_trees))
1907
        args.append(self._serialize_NoneTrueFalse(shared_repo))
4934.4.3 by Martin Pool
Initializing a bzrdir shouldn't mutate the RemoteBzrDirFormat
1908
        request_network_name = self._network_name or \
4294.2.8 by Robert Collins
Reduce round trips pushing new branches substantially.
1909
            BzrDirFormat.get_default_format().network_name()
4294.2.7 by Robert Collins
Start building up a BzrDir.initialize_ex verb for the smart server.
1910
        try:
4436.1.1 by Andrew Bennetts
Rename BzrDirFormat.initialize_ex verb to BzrDirFormat.initialize_ex_1.16.
1911
            response = client.call('BzrDirFormat.initialize_ex_1.16',
4934.4.3 by Martin Pool
Initializing a bzrdir shouldn't mutate the RemoteBzrDirFormat
1912
                request_network_name, path, *args)
4294.2.7 by Robert Collins
Start building up a BzrDir.initialize_ex verb for the smart server.
1913
        except errors.UnknownSmartMethod:
4436.1.1 by Andrew Bennetts
Rename BzrDirFormat.initialize_ex verb to BzrDirFormat.initialize_ex_1.16.
1914
            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.
1915
            local_dir_format = BzrDirMetaFormat1()
1916
            self._supply_sub_formats_to(local_dir_format)
1917
            return local_dir_format.initialize_on_transport_ex(transport,
1918
                use_existing_dir=use_existing_dir, create_prefix=create_prefix,
1919
                force_new_repo=force_new_repo, stacked_on=stacked_on,
1920
                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.
1921
                make_working_trees=make_working_trees, shared_repo=shared_repo,
1922
                vfs_only=True)
4384.1.1 by Andrew Bennetts
Translate ErrorFromSmartServer in RemoteBzrDirFormat.
1923
        except errors.ErrorFromSmartServer, err:
1924
            remote._translate_error(err, path=path)
4294.2.8 by Robert Collins
Reduce round trips pushing new branches substantially.
1925
        repo_path = response[0]
1926
        bzrdir_name = response[6]
1927
        require_stacking = response[7]
1928
        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.
1929
        format = RemoteBzrDirFormat()
4294.2.8 by Robert Collins
Reduce round trips pushing new branches substantially.
1930
        format._network_name = bzrdir_name
4294.2.7 by Robert Collins
Start building up a BzrDir.initialize_ex verb for the smart server.
1931
        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.
1932
        bzrdir = remote.RemoteBzrDir(transport, format, _client=client)
4294.2.8 by Robert Collins
Reduce round trips pushing new branches substantially.
1933
        if repo_path:
1934
            repo_format = remote.response_tuple_to_repo_format(response[1:])
1935
            if repo_path == '.':
1936
                repo_path = ''
1937
            if repo_path:
1938
                repo_bzrdir_format = RemoteBzrDirFormat()
1939
                repo_bzrdir_format._network_name = response[5]
1940
                repo_bzr = remote.RemoteBzrDir(transport.clone(repo_path),
1941
                    repo_bzrdir_format)
1942
            else:
1943
                repo_bzr = bzrdir
1944
            final_stack = response[8] or None
1945
            final_stack_pwd = response[9] or None
4416.3.8 by Jonathan Lange
This makes the unit test & one of the acceptance tests pass.
1946
            if final_stack_pwd:
4416.3.15 by Jonathan Lange
Use a URL joiner that works.
1947
                final_stack_pwd = urlutils.join(
1948
                    transport.base, final_stack_pwd)
4294.2.8 by Robert Collins
Reduce round trips pushing new branches substantially.
1949
            remote_repo = remote.RemoteRepository(repo_bzr, repo_format)
4307.2.2 by Robert Collins
Lock repositories created by BzrDirFormat.initialize_on_transport_ex.
1950
            if len(response) > 10:
1951
                # Updated server verb that locks remotely.
1952
                repo_lock_token = response[10] or None
1953
                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).
1954
                if repo_lock_token:
1955
                    remote_repo.dont_leave_lock_in_place()
4307.2.2 by Robert Collins
Lock repositories created by BzrDirFormat.initialize_on_transport_ex.
1956
            else:
4307.2.6 by Robert Collins
Handle repositories that mutex on writes (rather than transactions).
1957
                remote_repo.lock_write()
4294.2.8 by Robert Collins
Reduce round trips pushing new branches substantially.
1958
            policy = UseExistingRepository(remote_repo, final_stack,
1959
                final_stack_pwd, require_stacking)
1960
            policy.acquire_repository()
1961
        else:
1962
            remote_repo = None
1963
            policy = None
4466.1.1 by Andrew Bennetts
Quick fix 388908: set branch format on the result of initialize_ex before calling require_stacking.
1964
        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.
1965
        if require_stacking:
1966
            # The repo has already been created, but we need to make sure that
1967
            # we'll make a stackable branch.
1968
            bzrdir._format.require_stacking(_skip_repo=True)
4294.2.8 by Robert Collins
Reduce round trips pushing new branches substantially.
1969
        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.
1970
2018.5.25 by Andrew Bennetts
Make sure RemoteBzrDirFormat is always registered (John Arbash Meinel, Robert Collins, Andrew Bennetts).
1971
    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.
1972
        return remote.RemoteBzrDir(transport, self)
2018.5.25 by Andrew Bennetts
Make sure RemoteBzrDirFormat is always registered (John Arbash Meinel, Robert Collins, Andrew Bennetts).
1973
1974
    def __eq__(self, other):
1975
        if not isinstance(other, RemoteBzrDirFormat):
1976
            return False
1977
        return self.get_format_description() == other.get_format_description()
1978
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.
1979
    def __return_repository_format(self):
1980
        # Always return a RemoteRepositoryFormat object, but if a specific bzr
1981
        # repository format has been asked for, tell the RemoteRepositoryFormat
1982
        # 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.
1983
        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.
1984
        custom_format = getattr(self, '_repository_format', None)
1985
        if custom_format:
4017.3.2 by Robert Collins
Reduce the number of round trips required to create a repository over the network.
1986
            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.
1987
                return custom_format
4017.3.2 by Robert Collins
Reduce the number of round trips required to create a repository over the network.
1988
            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.
1989
                # We will use the custom format to create repositories over the
1990
                # wire; expose its details like rich_root_data for code to
1991
                # query
4017.3.2 by Robert Collins
Reduce the number of round trips required to create a repository over the network.
1992
                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.
1993
        return result
1994
4032.3.2 by Robert Collins
Create and use a RPC call to create branches on bzr servers rather than using VFS calls.
1995
    def get_branch_format(self):
1996
        result = BzrDirMetaFormat1.get_branch_format(self)
1997
        if not isinstance(result, remote.RemoteBranchFormat):
1998
            new_result = remote.RemoteBranchFormat()
1999
            new_result._custom_format = result
2000
            # cache the result
2001
            self.set_branch_format(new_result)
2002
            result = new_result
2003
        return result
2004
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.
2005
    repository_format = property(__return_repository_format,
2006
        BzrDirMetaFormat1._set_repository_format) #.im_func)
3845.1.1 by John Arbash Meinel
Ensure that RepositoryFormat._matchingbzrdir.repository_format matches.
2007
2018.5.25 by Andrew Bennetts
Make sure RemoteBzrDirFormat is always registered (John Arbash Meinel, Robert Collins, Andrew Bennetts).
2008
5363.2.20 by Jelmer Vernooij
use controldir.X
2009
controldir.ControlDirFormat.register_server_prober(RemoteBzrProber)
2204.4.1 by Aaron Bentley
Add 'formats' help topic
2010
2011
3242.2.14 by Aaron Bentley
Update from review comments
2012
class RepositoryAcquisitionPolicy(object):
2013
    """Abstract base class for repository acquisition policies.
3242.3.7 by Aaron Bentley
Delegate stacking to configure_branch
2014
3242.2.14 by Aaron Bentley
Update from review comments
2015
    A repository acquisition policy decides how a BzrDir acquires a repository
2016
    for a branch that is being created.  The most basic policy decision is
2017
    whether to create a new repository or use an existing one.
2018
    """
3242.3.40 by Aaron Bentley
Turn failing test into KnownFailure
2019
    def __init__(self, stack_on, stack_on_pwd, require_stacking):
3242.3.35 by Aaron Bentley
Cleanups and documentation
2020
        """Constructor.
2021
2022
        :param stack_on: A location to stack on
2023
        :param stack_on_pwd: If stack_on is relative, the location it is
2024
            relative to.
3242.3.40 by Aaron Bentley
Turn failing test into KnownFailure
2025
        :param require_stacking: If True, it is a failure to not stack.
3242.3.35 by Aaron Bentley
Cleanups and documentation
2026
        """
3242.3.7 by Aaron Bentley
Delegate stacking to configure_branch
2027
        self._stack_on = stack_on
3242.3.32 by Aaron Bentley
Defer handling relative stacking URLs as late as possible.
2028
        self._stack_on_pwd = stack_on_pwd
3242.3.40 by Aaron Bentley
Turn failing test into KnownFailure
2029
        self._require_stacking = require_stacking
3242.3.7 by Aaron Bentley
Delegate stacking to configure_branch
2030
2031
    def configure_branch(self, branch):
3242.2.13 by Aaron Bentley
Update docs
2032
        """Apply any configuration data from this policy to the branch.
2033
3242.3.18 by Aaron Bentley
Clean up repository-policy work
2034
        Default implementation sets repository stacking.
3242.2.13 by Aaron Bentley
Update docs
2035
        """
3242.3.33 by Aaron Bentley
Handle relative URL stacking cleanly
2036
        if self._stack_on is None:
2037
            return
2038
        if self._stack_on_pwd is None:
2039
            stack_on = self._stack_on
2040
        else:
2041
            try:
3242.3.32 by Aaron Bentley
Defer handling relative stacking URLs as late as possible.
2042
                stack_on = urlutils.rebase_url(self._stack_on,
2043
                    self._stack_on_pwd,
5158.6.9 by Martin Pool
Simplify various code to use user_url
2044
                    branch.user_url)
3242.3.33 by Aaron Bentley
Handle relative URL stacking cleanly
2045
            except errors.InvalidRebaseURLs:
2046
                stack_on = self._get_full_stack_on()
3242.3.37 by Aaron Bentley
Updates from reviews
2047
        try:
3537.3.5 by Martin Pool
merge trunk including stacking policy
2048
            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.
2049
        except (errors.UnstackableBranchFormat,
2050
                errors.UnstackableRepositoryFormat):
3242.3.40 by Aaron Bentley
Turn failing test into KnownFailure
2051
            if self._require_stacking:
2052
                raise
3242.3.33 by Aaron Bentley
Handle relative URL stacking cleanly
2053
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.
2054
    def requires_stacking(self):
2055
        """Return True if this policy requires stacking."""
2056
        return self._stack_on is not None and self._require_stacking
2057
3242.3.33 by Aaron Bentley
Handle relative URL stacking cleanly
2058
    def _get_full_stack_on(self):
3242.3.35 by Aaron Bentley
Cleanups and documentation
2059
        """Get a fully-qualified URL for the stack_on location."""
3242.3.33 by Aaron Bentley
Handle relative URL stacking cleanly
2060
        if self._stack_on is None:
2061
            return None
2062
        if self._stack_on_pwd is None:
2063
            return self._stack_on
2064
        else:
2065
            return urlutils.join(self._stack_on_pwd, self._stack_on)
3242.3.7 by Aaron Bentley
Delegate stacking to configure_branch
2066
3928.3.2 by John Arbash Meinel
Track down the other cause of us connecting multiple times.
2067
    def _add_fallback(self, repository, possible_transports=None):
3242.3.35 by Aaron Bentley
Cleanups and documentation
2068
        """Add a fallback to the supplied repository, if stacking is set."""
3242.3.33 by Aaron Bentley
Handle relative URL stacking cleanly
2069
        stack_on = self._get_full_stack_on()
2070
        if stack_on is None:
3242.3.30 by Aaron Bentley
Handle adding fallback repositories in acquire_repository
2071
            return
4294.2.8 by Robert Collins
Reduce round trips pushing new branches substantially.
2072
        try:
2073
            stacked_dir = BzrDir.open(stack_on,
2074
                                      possible_transports=possible_transports)
2075
        except errors.JailBreak:
2076
            # We keep the stacking details, but we are in the server code so
2077
            # actually stacking is not needed.
2078
            return
3242.3.30 by Aaron Bentley
Handle adding fallback repositories in acquire_repository
2079
        try:
2080
            stacked_repo = stacked_dir.open_branch().repository
2081
        except errors.NotBranchError:
2082
            stacked_repo = stacked_dir.open_repository()
3242.3.37 by Aaron Bentley
Updates from reviews
2083
        try:
2084
            repository.add_fallback_repository(stacked_repo)
2085
        except errors.UnstackableRepositoryFormat:
3242.3.40 by Aaron Bentley
Turn failing test into KnownFailure
2086
            if self._require_stacking:
2087
                raise
3904.3.1 by Andrew Bennetts
Probable fix for GaryvdM's bug when pushing a stacked qbzr branch to Launchpad.
2088
        else:
2089
            self._require_stacking = True
3242.3.30 by Aaron Bentley
Handle adding fallback repositories in acquire_repository
2090
3242.2.10 by Aaron Bentley
Rename RepositoryPolicy.apply to acquire_repository
2091
    def acquire_repository(self, make_working_trees=None, shared=False):
3242.2.14 by Aaron Bentley
Update from review comments
2092
        """Acquire a repository for this bzrdir.
2093
2094
        Implementations may create a new repository or use a pre-exising
2095
        repository.
2096
        :param make_working_trees: If creating a repository, set
2097
            make_working_trees to this value (if non-None)
2098
        :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.
2099
        :return: A repository, is_new_flag (True if the repository was
2100
            created).
3242.2.14 by Aaron Bentley
Update from review comments
2101
        """
2102
        raise NotImplemented(RepositoryAcquisitionPolicy.acquire_repository)
2103
2104
2105
class CreateRepository(RepositoryAcquisitionPolicy):
3242.2.13 by Aaron Bentley
Update docs
2106
    """A policy of creating a new repository"""
3242.2.1 by Aaron Bentley
Abstract policy decisions into determine_repository_policy
2107
3242.3.40 by Aaron Bentley
Turn failing test into KnownFailure
2108
    def __init__(self, bzrdir, stack_on=None, stack_on_pwd=None,
2109
                 require_stacking=False):
3242.3.35 by Aaron Bentley
Cleanups and documentation
2110
        """
2111
        Constructor.
2112
        :param bzrdir: The bzrdir to create the repository on.
2113
        :param stack_on: A location to stack on
2114
        :param stack_on_pwd: If stack_on is relative, the location it is
2115
            relative to.
2116
        """
3242.3.40 by Aaron Bentley
Turn failing test into KnownFailure
2117
        RepositoryAcquisitionPolicy.__init__(self, stack_on, stack_on_pwd,
2118
                                             require_stacking)
3242.2.1 by Aaron Bentley
Abstract policy decisions into determine_repository_policy
2119
        self._bzrdir = bzrdir
2120
3242.2.10 by Aaron Bentley
Rename RepositoryPolicy.apply to acquire_repository
2121
    def acquire_repository(self, make_working_trees=None, shared=False):
3242.2.14 by Aaron Bentley
Update from review comments
2122
        """Implementation of RepositoryAcquisitionPolicy.acquire_repository
3242.2.13 by Aaron Bentley
Update docs
2123
3242.2.14 by Aaron Bentley
Update from review comments
2124
        Creates the desired repository in the bzrdir we already have.
3242.2.13 by Aaron Bentley
Update docs
2125
        """
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.
2126
        stack_on = self._get_full_stack_on()
2127
        if stack_on:
4401.1.2 by John Arbash Meinel
Move the logic back up into BzrDirFormat1.require_stacking, passing in the extra params.
2128
            format = self._bzrdir._format
2129
            format.require_stacking(stack_on=stack_on,
2130
                                    possible_transports=[self._bzrdir.root_transport])
2131
            if not self._require_stacking:
2132
                # We have picked up automatic stacking somewhere.
2133
                note('Using default stacking branch %s at %s', self._stack_on,
2134
                    self._stack_on_pwd)
3650.3.9 by Aaron Bentley
Move responsibility for stackable repo format to _get_metadir
2135
        repository = self._bzrdir.create_repository(shared=shared)
3928.3.2 by John Arbash Meinel
Track down the other cause of us connecting multiple times.
2136
        self._add_fallback(repository,
2137
                           possible_transports=[self._bzrdir.transport])
3242.2.4 by Aaron Bentley
Only set working tree policty when specified
2138
        if make_working_trees is not None:
3242.3.6 by Aaron Bentley
Work around strange test failure
2139
            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.
2140
        return repository, True
3242.2.2 by Aaron Bentley
Merge policy updates from stacked-policy thread
2141
2142
3242.2.14 by Aaron Bentley
Update from review comments
2143
class UseExistingRepository(RepositoryAcquisitionPolicy):
3242.2.13 by Aaron Bentley
Update docs
2144
    """A policy of reusing an existing repository"""
3242.2.1 by Aaron Bentley
Abstract policy decisions into determine_repository_policy
2145
3242.3.40 by Aaron Bentley
Turn failing test into KnownFailure
2146
    def __init__(self, repository, stack_on=None, stack_on_pwd=None,
2147
                 require_stacking=False):
3242.3.35 by Aaron Bentley
Cleanups and documentation
2148
        """Constructor.
2149
2150
        :param repository: The repository to use.
2151
        :param stack_on: A location to stack on
2152
        :param stack_on_pwd: If stack_on is relative, the location it is
2153
            relative to.
2154
        """
3242.3.40 by Aaron Bentley
Turn failing test into KnownFailure
2155
        RepositoryAcquisitionPolicy.__init__(self, stack_on, stack_on_pwd,
2156
                                             require_stacking)
3242.2.1 by Aaron Bentley
Abstract policy decisions into determine_repository_policy
2157
        self._repository = repository
2158
3242.2.10 by Aaron Bentley
Rename RepositoryPolicy.apply to acquire_repository
2159
    def acquire_repository(self, make_working_trees=None, shared=False):
3242.2.14 by Aaron Bentley
Update from review comments
2160
        """Implementation of RepositoryAcquisitionPolicy.acquire_repository
3242.2.13 by Aaron Bentley
Update docs
2161
4070.9.8 by Andrew Bennetts
Use MiniSearchResult in clone_on_transport down (further tightening the test_push ratchets), and improve acquire_repository docstrings.
2162
        Returns an existing repository to use.
3242.2.13 by Aaron Bentley
Update docs
2163
        """
3928.3.2 by John Arbash Meinel
Track down the other cause of us connecting multiple times.
2164
        self._add_fallback(self._repository,
2165
                       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.
2166
        return self._repository, False
3242.2.1 by Aaron Bentley
Abstract policy decisions into determine_repository_policy
2167
2168
5363.2.9 by Jelmer Vernooij
Fix some tests.
2169
def register_metadir(registry, key,
5363.2.6 by Jelmer Vernooij
Add ControlDirFormat.{un,}register_{server_,}prober.
2170
         repository_format, help, native=True, deprecated=False,
2171
         branch_format=None,
2172
         tree_format=None,
2173
         hidden=False,
2174
         experimental=False,
2175
         alias=False):
2176
    """Register a metadir subformat.
2177
2178
    These all use a BzrDirMetaFormat1 bzrdir, but can be parameterized
2179
    by the Repository/Branch/WorkingTreeformats.
2180
2181
    :param repository_format: The fully-qualified repository format class
2182
        name as a string.
2183
    :param branch_format: Fully-qualified branch format class name as
2184
        a string.
2185
    :param tree_format: Fully-qualified tree format class name as
2186
        a string.
2187
    """
2188
    # This should be expanded to support setting WorkingTree and Branch
2189
    # formats, once BzrDirMetaFormat1 supports that.
2190
    def _load(full_name):
2191
        mod_name, factory_name = full_name.rsplit('.', 1)
2192
        try:
5436.2.1 by Andrew Bennetts
Add bzrlib.pyutils, which has get_named_object, a wrapper around __import__.
2193
            factory = pyutils.get_named_object(mod_name, factory_name)
5363.2.6 by Jelmer Vernooij
Add ControlDirFormat.{un,}register_{server_,}prober.
2194
        except ImportError, e:
2195
            raise ImportError('failed to load %s: %s' % (full_name, e))
2196
        except AttributeError:
2197
            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__.
2198
                % (full_name, sys.modules[mod_name]))
5363.2.6 by Jelmer Vernooij
Add ControlDirFormat.{un,}register_{server_,}prober.
2199
        return factory()
2200
2201
    def helper():
2202
        bd = BzrDirMetaFormat1()
2203
        if branch_format is not None:
2204
            bd.set_branch_format(_load(branch_format))
2205
        if tree_format is not None:
2206
            bd.workingtree_format = _load(tree_format)
2207
        if repository_format is not None:
2208
            bd.repository_format = _load(repository_format)
2209
        return bd
5363.2.9 by Jelmer Vernooij
Fix some tests.
2210
    registry.register(key, helper, help, native, deprecated, hidden,
5363.2.6 by Jelmer Vernooij
Add ControlDirFormat.{un,}register_{server_,}prober.
2211
        experimental, alias)
2212
5363.2.20 by Jelmer Vernooij
use controldir.X
2213
register_metadir(controldir.format_registry, 'knit',
3892.1.2 by Ian Clatworthy
split formats topic into multiple topics
2214
    'bzrlib.repofmt.knitrepo.RepositoryFormatKnit1',
2215
    'Format using knits.  Recommended for interoperation with bzr <= 0.14.',
2216
    branch_format='bzrlib.branch.BzrBranchFormat5',
2217
    tree_format='bzrlib.workingtree.WorkingTreeFormat3',
4976.2.1 by Ian Clatworthy
Hide most storage formats
2218
    hidden=True,
3892.1.2 by Ian Clatworthy
split formats topic into multiple topics
2219
    deprecated=True)
5363.2.20 by Jelmer Vernooij
use controldir.X
2220
register_metadir(controldir.format_registry, 'dirstate',
2255.12.1 by Robert Collins
Implement upgrade for working trees.
2221
    'bzrlib.repofmt.knitrepo.RepositoryFormatKnit1',
2222
    help='New in 0.15: Fast local operations. Compatible with bzr 0.8 and '
2223
        'above when accessed over the network.',
2224
    branch_format='bzrlib.branch.BzrBranchFormat5',
2255.2.209 by Robert Collins
Remove circular imports in bzrdir format definitions.
2225
    # this uses bzrlib.workingtree.WorkingTreeFormat4 because importing
2226
    # directly from workingtree_4 triggers a circular import.
2227
    tree_format='bzrlib.workingtree.WorkingTreeFormat4',
4976.2.1 by Ian Clatworthy
Hide most storage formats
2228
    hidden=True,
3892.1.1 by Ian Clatworthy
improve help on storage formats
2229
    deprecated=True)
5363.2.20 by Jelmer Vernooij
use controldir.X
2230
register_metadir(controldir.format_registry, 'dirstate-tags',
1551.13.1 by Aaron Bentley
Introduce dirstate-tags format
2231
    'bzrlib.repofmt.knitrepo.RepositoryFormatKnit1',
2232
    help='New in 0.15: Fast local operations and improved scaling for '
1551.13.2 by Aaron Bentley
Hide dirstate-with-subtree format
2233
        'network operations. Additionally adds support for tags.'
2234
        ' Incompatible with bzr < 0.15.',
1551.13.1 by Aaron Bentley
Introduce dirstate-tags format
2235
    branch_format='bzrlib.branch.BzrBranchFormat6',
2236
    tree_format='bzrlib.workingtree.WorkingTreeFormat4',
4976.2.1 by Ian Clatworthy
Hide most storage formats
2237
    hidden=True,
3892.1.1 by Ian Clatworthy
improve help on storage formats
2238
    deprecated=True)
5363.2.20 by Jelmer Vernooij
use controldir.X
2239
register_metadir(controldir.format_registry, 'rich-root',
2996.2.1 by Aaron Bentley
Add KnitRepositoryFormat4
2240
    'bzrlib.repofmt.knitrepo.RepositoryFormatKnit4',
2241
    help='New in 1.0.  Better handling of tree roots.  Incompatible with'
3892.1.2 by Ian Clatworthy
split formats topic into multiple topics
2242
        ' bzr < 1.0.',
2996.2.1 by Aaron Bentley
Add KnitRepositoryFormat4
2243
    branch_format='bzrlib.branch.BzrBranchFormat6',
2244
    tree_format='bzrlib.workingtree.WorkingTreeFormat4',
4976.2.1 by Ian Clatworthy
Hide most storage formats
2245
    hidden=True,
3892.1.1 by Ian Clatworthy
improve help on storage formats
2246
    deprecated=True)
5363.2.20 by Jelmer Vernooij
use controldir.X
2247
register_metadir(controldir.format_registry, 'dirstate-with-subtree',
2255.12.1 by Robert Collins
Implement upgrade for working trees.
2248
    'bzrlib.repofmt.knitrepo.RepositoryFormatKnit3',
2249
    help='New in 0.15: Fast local operations and improved scaling for '
2250
        'network operations. Additionally adds support for versioning nested '
2251
        'bzr branches. Incompatible with bzr < 0.15.',
2252
    branch_format='bzrlib.branch.BzrBranchFormat6',
2255.2.209 by Robert Collins
Remove circular imports in bzrdir format definitions.
2253
    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.
2254
    experimental=True,
3170.4.4 by Adeodato Simó
Keep the hidden flag for subtree formats after review from Aaron.
2255
    hidden=True,
2255.12.1 by Robert Collins
Implement upgrade for working trees.
2256
    )
5363.2.20 by Jelmer Vernooij
use controldir.X
2257
register_metadir(controldir.format_registry, 'pack-0.92',
2592.3.224 by Martin Pool
Rename GraphKnitRepository etc to KnitPackRepository
2258
    'bzrlib.repofmt.pack_repo.RepositoryFormatKnitPack1',
2939.2.1 by Ian Clatworthy
use 'knitpack' naming instead of 'experimental' for pack formats
2259
    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
2260
        'dirstate-tags format repositories. Interoperates with '
2261
        '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
2262
        ,
2592.3.22 by Robert Collins
Add new experimental repository formats.
2263
    branch_format='bzrlib.branch.BzrBranchFormat6',
2264
    tree_format='bzrlib.workingtree.WorkingTreeFormat4',
2265
    )
5363.2.20 by Jelmer Vernooij
use controldir.X
2266
register_metadir(controldir.format_registry, 'pack-0.92-subtree',
2592.3.224 by Martin Pool
Rename GraphKnitRepository etc to KnitPackRepository
2267
    'bzrlib.repofmt.pack_repo.RepositoryFormatKnitPack3',
2939.2.1 by Ian Clatworthy
use 'knitpack' naming instead of 'experimental' for pack formats
2268
    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
2269
        'dirstate-with-subtree format repositories. Interoperates with '
2270
        '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
2271
        ,
2592.3.22 by Robert Collins
Add new experimental repository formats.
2272
    branch_format='bzrlib.branch.BzrBranchFormat6',
2273
    tree_format='bzrlib.workingtree.WorkingTreeFormat4',
3190.1.2 by Aaron Bentley
Undo spurious change
2274
    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.
2275
    experimental=True,
2592.3.22 by Robert Collins
Add new experimental repository formats.
2276
    )
5363.2.20 by Jelmer Vernooij
use controldir.X
2277
register_metadir(controldir.format_registry, 'rich-root-pack',
2996.2.11 by Aaron Bentley
Implement rich-root-pack format ( #164639)
2278
    'bzrlib.repofmt.pack_repo.RepositoryFormatKnitPack4',
3892.1.2 by Ian Clatworthy
split formats topic into multiple topics
2279
    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.
2280
         '(needed for bzr-svn and bzr-git).',
2996.2.11 by Aaron Bentley
Implement rich-root-pack format ( #164639)
2281
    branch_format='bzrlib.branch.BzrBranchFormat6',
2282
    tree_format='bzrlib.workingtree.WorkingTreeFormat4',
4976.2.1 by Ian Clatworthy
Hide most storage formats
2283
    hidden=True,
3152.2.1 by Robert Collins
* A new repository format 'development' has been added. This format will
2284
    )
5363.2.20 by Jelmer Vernooij
use controldir.X
2285
register_metadir(controldir.format_registry, '1.6',
3549.1.5 by Martin Pool
Add stable format names for stacked branches
2286
    'bzrlib.repofmt.pack_repo.RepositoryFormatKnitPack5',
3892.1.6 by Ian Clatworthy
include feedback from poolie
2287
    help='A format that allows a branch to indicate that there is another '
2288
         '(stacked) repository that should be used to access data that is '
2289
         'not present locally.',
3549.1.5 by Martin Pool
Add stable format names for stacked branches
2290
    branch_format='bzrlib.branch.BzrBranchFormat7',
2291
    tree_format='bzrlib.workingtree.WorkingTreeFormat4',
4976.2.1 by Ian Clatworthy
Hide most storage formats
2292
    hidden=True,
3549.1.5 by Martin Pool
Add stable format names for stacked branches
2293
    )
5363.2.20 by Jelmer Vernooij
use controldir.X
2294
register_metadir(controldir.format_registry, '1.6.1-rich-root',
3549.1.6 by Martin Pool
Change stacked-subtree to stacked-rich-root
2295
    'bzrlib.repofmt.pack_repo.RepositoryFormatKnitPack5RichRoot',
3892.1.2 by Ian Clatworthy
split formats topic into multiple topics
2296
    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.
2297
         '(needed for bzr-svn and bzr-git).',
3549.1.5 by Martin Pool
Add stable format names for stacked branches
2298
    branch_format='bzrlib.branch.BzrBranchFormat7',
2299
    tree_format='bzrlib.workingtree.WorkingTreeFormat4',
4976.2.1 by Ian Clatworthy
Hide most storage formats
2300
    hidden=True,
3549.1.5 by Martin Pool
Add stable format names for stacked branches
2301
    )
5363.2.20 by Jelmer Vernooij
use controldir.X
2302
register_metadir(controldir.format_registry, '1.9',
3805.3.1 by John Arbash Meinel
Add repository 1.9 format, and update the documentation.
2303
    'bzrlib.repofmt.pack_repo.RepositoryFormatKnitPack6',
3892.1.6 by Ian Clatworthy
include feedback from poolie
2304
    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
2305
         'are smaller in size, have smarter caching and provide faster '
2306
         'performance for most operations.',
3805.3.1 by John Arbash Meinel
Add repository 1.9 format, and update the documentation.
2307
    branch_format='bzrlib.branch.BzrBranchFormat7',
2308
    tree_format='bzrlib.workingtree.WorkingTreeFormat4',
4976.2.1 by Ian Clatworthy
Hide most storage formats
2309
    hidden=True,
3805.3.1 by John Arbash Meinel
Add repository 1.9 format, and update the documentation.
2310
    )
5363.2.20 by Jelmer Vernooij
use controldir.X
2311
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.
2312
    'bzrlib.repofmt.pack_repo.RepositoryFormatKnitPack6RichRoot',
3892.1.2 by Ian Clatworthy
split formats topic into multiple topics
2313
    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.
2314
         '(needed for bzr-svn and bzr-git).',
3805.3.1 by John Arbash Meinel
Add repository 1.9 format, and update the documentation.
2315
    branch_format='bzrlib.branch.BzrBranchFormat7',
2316
    tree_format='bzrlib.workingtree.WorkingTreeFormat4',
4976.2.1 by Ian Clatworthy
Hide most storage formats
2317
    hidden=True,
3805.3.1 by John Arbash Meinel
Add repository 1.9 format, and update the documentation.
2318
    )
5363.2.20 by Jelmer Vernooij
use controldir.X
2319
register_metadir(controldir.format_registry, '1.14',
3586.2.10 by Ian Clatworthy
rename formats from 1.7-* to 1.12-*
2320
    'bzrlib.repofmt.pack_repo.RepositoryFormatKnitPack6',
4210.4.2 by Ian Clatworthy
split filtered views support out into WorkingTreeFormat6
2321
    help='A working-tree format that supports content filtering.',
3586.2.6 by Ian Clatworthy
add 1.7 and 1.7-rich-root formats
2322
    branch_format='bzrlib.branch.BzrBranchFormat7',
3995.7.1 by John Arbash Meinel
Fix bug #328135.
2323
    tree_format='bzrlib.workingtree.WorkingTreeFormat5',
3586.2.6 by Ian Clatworthy
add 1.7 and 1.7-rich-root formats
2324
    )
5363.2.20 by Jelmer Vernooij
use controldir.X
2325
register_metadir(controldir.format_registry, '1.14-rich-root',
3586.2.10 by Ian Clatworthy
rename formats from 1.7-* to 1.12-*
2326
    'bzrlib.repofmt.pack_repo.RepositoryFormatKnitPack6RichRoot',
4210.4.1 by Ian Clatworthy
replace experimental development-wt5 formats with 1.14 formats
2327
    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.
2328
         '(needed for bzr-svn and bzr-git).',
3586.2.6 by Ian Clatworthy
add 1.7 and 1.7-rich-root formats
2329
    branch_format='bzrlib.branch.BzrBranchFormat7',
3995.7.1 by John Arbash Meinel
Fix bug #328135.
2330
    tree_format='bzrlib.workingtree.WorkingTreeFormat5',
3586.2.6 by Ian Clatworthy
add 1.7 and 1.7-rich-root formats
2331
    )
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)
2332
# The following un-numbered 'development' formats should always just be aliases.
5363.2.20 by Jelmer Vernooij
use controldir.X
2333
register_metadir(controldir.format_registry, 'development-subtree',
5389.1.1 by Jelmer Vernooij
Add development8-subtree.
2334
    'bzrlib.repofmt.groupcompress_repo.RepositoryFormat2aSubtree',
3152.2.1 by Robert Collins
* A new repository format 'development' has been added. This format will
2335
    help='Current development format, subtree variant. Can convert data to and '
3221.11.7 by Robert Collins
Merge in real stacked repository work.
2336
        'from pack-0.92-subtree (and anything compatible with '
2337
        'pack-0.92-subtree) format repositories. Repositories and branches in '
2338
        '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
2339
        '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
2340
        'before use.',
3221.11.2 by Robert Collins
Create basic stackable branch facility.
2341
    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)
2342
    tree_format='bzrlib.workingtree.WorkingTreeFormat6',
3152.2.1 by Robert Collins
* A new repository format 'development' has been added. This format will
2343
    experimental=True,
4976.2.1 by Ian Clatworthy
Hide most storage formats
2344
    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)
2345
    alias=False, # Restore to being an alias when an actual development subtree format is added
2346
                 # This current non-alias status is simply because we did not introduce a
2347
                 # chk based subtree format.
3152.2.1 by Robert Collins
* A new repository format 'development' has been added. This format will
2348
    )
5546.1.1 by Andrew Bennetts
Remove RepositoryFormatCHK1 and RepositoryFormatCHK2.
2349
register_metadir(controldir.format_registry, 'development5-subtree',
2350
    'bzrlib.repofmt.pack_repo.RepositoryFormatPackDevelopment2Subtree',
2351
    help='Development format, subtree variant. Can convert data to and '
2352
        'from pack-0.92-subtree (and anything compatible with '
2353
        'pack-0.92-subtree) format repositories. Repositories and branches in '
2354
        'this format can only be read by bzr.dev. Please read '
2355
        'http://doc.bazaar.canonical.com/latest/developers/development-repo.html '
2356
        'before use.',
2357
    branch_format='bzrlib.branch.BzrBranchFormat7',
2358
    tree_format='bzrlib.workingtree.WorkingTreeFormat6',
2359
    experimental=True,
2360
    hidden=True,
2361
    alias=False,
2362
    )
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)
2363
3735.1.1 by Robert Collins
Add development2 formats using BTree indices.
2364
# And the development formats above will have aliased one of the following:
5546.1.1 by Andrew Bennetts
Remove RepositoryFormatCHK1 and RepositoryFormatCHK2.
2365
2366
# Finally, the current format.
5363.2.20 by Jelmer Vernooij
use controldir.X
2367
register_metadir(controldir.format_registry, '2a',
4428.2.1 by Martin Pool
Add 2a format
2368
    'bzrlib.repofmt.groupcompress_repo.RepositoryFormat2a',
2369
    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
2370
        'Uses group-compress storage.\n'
4428.2.6 by Martin Pool
Stupid typo fix
2371
        '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
2372
        # 'storage in packs, 255-way hashed CHK inventory, bencode revision, group compress, '
2373
        # 'rich roots. Supported by bzr 1.16 and later.',
4428.2.1 by Martin Pool
Add 2a format
2374
    branch_format='bzrlib.branch.BzrBranchFormat7',
2375
    tree_format='bzrlib.workingtree.WorkingTreeFormat6',
5389.1.1 by Jelmer Vernooij
Add development8-subtree.
2376
    experimental=False,
4428.2.1 by Martin Pool
Add 2a format
2377
    )
4428.2.2 by Martin Pool
Format 2a should not be hidden
2378
4119.6.2 by Jelmer Vernooij
Use existing alias mechanism for default-rich-root.
2379
# The following format should be an alias for the rich root equivalent 
2380
# of the default format
5363.2.20 by Jelmer Vernooij
use controldir.X
2381
register_metadir(controldir.format_registry, 'default-rich-root',
4599.4.37 by Robert Collins
Fix registration of default-rich-root as 2a.
2382
    'bzrlib.repofmt.groupcompress_repo.RepositoryFormat2a',
2383
    branch_format='bzrlib.branch.BzrBranchFormat7',
2384
    tree_format='bzrlib.workingtree.WorkingTreeFormat6',
4599.4.23 by Robert Collins
default-rich-root should be an alias still.
2385
    alias=True,
4976.2.1 by Ian Clatworthy
Hide most storage formats
2386
    hidden=True,
4599.4.22 by mbp at sourcefrog
Don't forget to set default-rich-root to 2a too.
2387
    help='Same as 2a.')
2388
3221.11.2 by Robert Collins
Create basic stackable branch facility.
2389
# 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
2390
format_name = config.GlobalConfig().get_user_option('default_format')
2391
if format_name is None:
2392
    controldir.format_registry.set_default('2a')
2393
else:
2394
    controldir.format_registry.set_default(format_name)
5363.2.22 by Jelmer Vernooij
Provide bzrlib.bzrdir.format_registry.
2395
2396
# XXX 2010-08-20 JRV: There is still a lot of code relying on
2397
# bzrlib.bzrdir.format_registry existing. When BzrDir.create/BzrDir.open/etc
2398
# get changed to ControlDir.create/ControlDir.open/etc this should be removed.
2399
format_registry = controldir.format_registry