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