/brz/remove-bazaar

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