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