/brz/remove-bazaar

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