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