/brz/remove-bazaar

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