/brz/remove-bazaar

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