~bzr-pqm/bzr/bzr.dev

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