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