/brz/remove-bazaar

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