/brz/remove-bazaar

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