/brz/remove-bazaar

To get this branch, use:
bzr branch http://gegoxaren.bato24.eu/bzr/brz/remove-bazaar
3407.2.2 by Martin Pool
Remove special case in RemoteBranchLockableFiles for branch.conf
1
# Copyright (C) 2006, 2007, 2008 Canonical Ltd
1752.2.30 by Martin Pool
Start adding a RemoteBzrDir, etc
2
#
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.
7
#
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.
12
#
13
# You should have received a copy of the GNU General Public License
14
# along with this program; if not, write to the Free Software
15
# Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
16
1752.2.39 by Martin Pool
[broken] implement upgrade apis on remote bzrdirs
17
# TODO: At some point, handle upgrades by just passing the whole request
18
# across to run on the server.
19
3211.5.2 by Robert Collins
Change RemoteRepository.get_parent_map to use bz2 not gzip for compression.
20
import bz2
1752.2.30 by Martin Pool
Start adding a RemoteBzrDir, etc
21
2490.2.5 by Aaron Bentley
Use GraphWalker.unique_ancestor to determine merge base
22
from bzrlib import (
23
    branch,
4017.3.2 by Robert Collins
Reduce the number of round trips required to create a repository over the network.
24
    bzrdir,
3192.1.1 by Andrew Bennetts
Add some -Dhpss debugging to get_parent_map.
25
    debug,
2490.2.5 by Aaron Bentley
Use GraphWalker.unique_ancestor to determine merge base
26
    errors,
3172.5.1 by Robert Collins
Create a RemoteRepository get_graph implementation and delegate get_parents_map to the real repository.
27
    graph,
2490.2.5 by Aaron Bentley
Use GraphWalker.unique_ancestor to determine merge base
28
    lockdir,
4022.1.6 by Robert Collins
Cherrypick and polish the RemoteSink for streaming push.
29
    pack,
2490.2.5 by Aaron Bentley
Use GraphWalker.unique_ancestor to determine merge base
30
    repository,
2948.3.1 by John Arbash Meinel
Fix bug #158333, make sure that Repository.fetch(self) is properly a no-op for all Repository implementations.
31
    revision,
3228.4.11 by John Arbash Meinel
Deprecations abound.
32
    symbol_versioning,
3691.2.2 by Martin Pool
Fix some problems in access to stacked repositories over hpss (#261315)
33
    urlutils,
2490.2.5 by Aaron Bentley
Use GraphWalker.unique_ancestor to determine merge base
34
)
2535.4.27 by Andrew Bennetts
Remove some unused imports.
35
from bzrlib.branch import BranchReferenceFormat
2018.5.174 by Andrew Bennetts
Various nits discovered by pyflakes.
36
from bzrlib.bzrdir import BzrDir, RemoteBzrDirFormat
2018.14.1 by Andrew Bennetts
Update to current hpss branch? Fix lots of test failures.
37
from bzrlib.decorators import needs_read_lock, needs_write_lock
3376.2.4 by Martin Pool
Remove every assert statement from bzrlib!
38
from bzrlib.errors import (
39
    NoSuchRevision,
40
    SmartProtocolError,
41
    )
2018.5.127 by Andrew Bennetts
Fix most of the lockable_files tests for RemoteBranchLockableFiles.
42
from bzrlib.lockable_files import LockableFiles
4060.1.4 by Robert Collins
Streaming fetch from remote servers.
43
from bzrlib.smart import client, vfs, repository as smart_repo
3297.4.1 by Andrew Bennetts
Merge 'Add Branch.set_last_revision_info smart method'.
44
from bzrlib.revision import ensure_null, NULL_REVISION
3441.5.5 by Andrew Bennetts
Some small tweaks and comments.
45
from bzrlib.trace import mutter, note, warning
4029.2.1 by Robert Collins
Support streaming push to stacked branches.
46
from bzrlib.util import bencode
1752.2.30 by Martin Pool
Start adding a RemoteBzrDir, etc
47
3445.1.5 by John Arbash Meinel
allow passing a 'graph' object into Branch.update_revisions.
48
3786.2.3 by Andrew Bennetts
Remove duplicated 'call & translate errors' code in bzrlib.remote.
49
class _RpcHelper(object):
50
    """Mixin class that helps with issuing RPCs."""
51
52
    def _call(self, method, *args, **err_context):
53
        try:
54
            return self._client.call(method, *args)
55
        except errors.ErrorFromSmartServer, err:
56
            self._translate_error(err, **err_context)
3943.8.1 by Marius Kruger
remove all trailing whitespace from bzr source
57
3786.2.3 by Andrew Bennetts
Remove duplicated 'call & translate errors' code in bzrlib.remote.
58
    def _call_expecting_body(self, method, *args, **err_context):
59
        try:
60
            return self._client.call_expecting_body(method, *args)
61
        except errors.ErrorFromSmartServer, err:
62
            self._translate_error(err, **err_context)
3943.8.1 by Marius Kruger
remove all trailing whitespace from bzr source
63
3786.2.3 by Andrew Bennetts
Remove duplicated 'call & translate errors' code in bzrlib.remote.
64
    def _call_with_body_bytes_expecting_body(self, method, args, body_bytes,
65
                                             **err_context):
66
        try:
67
            return self._client.call_with_body_bytes_expecting_body(
68
                method, args, body_bytes)
69
        except errors.ErrorFromSmartServer, err:
70
            self._translate_error(err, **err_context)
3943.8.1 by Marius Kruger
remove all trailing whitespace from bzr source
71
4032.3.2 by Robert Collins
Create and use a RPC call to create branches on bzr servers rather than using VFS calls.
72
73
def response_tuple_to_repo_format(response):
74
    """Convert a response tuple describing a repository format to a format."""
75
    format = RemoteRepositoryFormat()
76
    format.rich_root_data = (response[0] == 'yes')
77
    format.supports_tree_reference = (response[1] == 'yes')
78
    format.supports_external_lookups = (response[2] == 'yes')
79
    format._network_name = response[3]
80
    return format
81
82
2018.5.25 by Andrew Bennetts
Make sure RemoteBzrDirFormat is always registered (John Arbash Meinel, Robert Collins, Andrew Bennetts).
83
# Note: RemoteBzrDirFormat is in bzrdir.py
1752.2.30 by Martin Pool
Start adding a RemoteBzrDir, etc
84
3786.2.3 by Andrew Bennetts
Remove duplicated 'call & translate errors' code in bzrlib.remote.
85
class RemoteBzrDir(BzrDir, _RpcHelper):
2018.5.163 by Andrew Bennetts
Deal with various review comments from Robert.
86
    """Control directory on a remote server, accessed via bzr:// or similar."""
1752.2.30 by Martin Pool
Start adding a RemoteBzrDir, etc
87
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.
88
    def __init__(self, transport, format, _client=None):
2018.5.51 by Wouter van Heyst
Test and implement RemoteBranch.last_revision_info()
89
        """Construct a RemoteBzrDir.
90
91
        :param _client: Private parameter for testing. Disables probing and the
92
            use of a real bzrdir.
93
        """
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.
94
        BzrDir.__init__(self, transport, format)
1752.2.31 by Martin Pool
[broken] some support for write operations over hpss
95
        # this object holds a delegated bzrdir that uses file-level operations
96
        # to talk to the other side
2018.5.70 by Robert Collins
Only try to get real repositories when an operation requires them.
97
        self._real_bzrdir = None
4044.1.3 by Robert Collins
Create a one-shot cache of the result of RemoteBzrDir.create_branch, eliminating 3 round trips for nonstacked branches and 5 for stacked.
98
        # 1-shot cache for the call pattern 'create_branch; open_branch' - see
99
        # create_branch for details.
100
        self._next_open_branch_result = None
2018.14.1 by Andrew Bennetts
Update to current hpss branch? Fix lots of test failures.
101
102
        if _client is None:
3313.2.3 by Andrew Bennetts
Deprecate Transport.get_shared_medium.
103
            medium = transport.get_smart_medium()
3431.3.2 by Andrew Bennetts
Remove 'base' from _SmartClient entirely, now that the medium has it.
104
            self._client = client._SmartClient(medium)
2018.14.1 by Andrew Bennetts
Update to current hpss branch? Fix lots of test failures.
105
        else:
106
            self._client = _client
107
            return
108
109
        path = self._path_for_remote_call(self._client)
3786.2.3 by Andrew Bennetts
Remove duplicated 'call & translate errors' code in bzrlib.remote.
110
        response = self._call('BzrDir.open', path)
2018.5.163 by Andrew Bennetts
Deal with various review comments from Robert.
111
        if response not in [('yes',), ('no',)]:
112
            raise errors.UnexpectedSmartServerResponse(response)
2018.5.26 by Andrew Bennetts
Extract a simple SmartClient class from RemoteTransport, and a hack to avoid VFS operations when probing for a bzrdir over a smart transport.
113
        if response == ('no',):
114
            raise errors.NotBranchError(path=transport.base)
4070.2.1 by Robert Collins
Add a BzrDirFormat.network_name.
115
        self._ensure_real()
1752.2.31 by Martin Pool
[broken] some support for write operations over hpss
116
2018.5.70 by Robert Collins
Only try to get real repositories when an operation requires them.
117
    def _ensure_real(self):
118
        """Ensure that there is a _real_bzrdir set.
119
2018.5.163 by Andrew Bennetts
Deal with various review comments from Robert.
120
        Used before calls to self._real_bzrdir.
2018.5.70 by Robert Collins
Only try to get real repositories when an operation requires them.
121
        """
122
        if not self._real_bzrdir:
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.
123
            self._real_bzrdir = BzrDir.open_from_transport(
124
                self.root_transport, _server_formats=False)
4070.2.1 by Robert Collins
Add a BzrDirFormat.network_name.
125
            self._format._network_name = \
126
                self._real_bzrdir._format.network_name()
2018.5.70 by Robert Collins
Only try to get real repositories when an operation requires them.
127
3786.2.3 by Andrew Bennetts
Remove duplicated 'call & translate errors' code in bzrlib.remote.
128
    def _translate_error(self, err, **context):
129
        _translate_error(err, bzrdir=self, **context)
130
4044.1.3 by Robert Collins
Create a one-shot cache of the result of RemoteBzrDir.create_branch, eliminating 3 round trips for nonstacked branches and 5 for stacked.
131
    def break_lock(self):
132
        # Prevent aliasing problems in the next_open_branch_result cache.
133
        # See create_branch for rationale.
134
        self._next_open_branch_result = None
135
        return BzrDir.break_lock(self)
136
3650.3.13 by Aaron Bentley
Make cloning_metadir handle stacking requirements
137
    def cloning_metadir(self, stacked=False):
3242.3.28 by Aaron Bentley
Use repository acquisition policy for sprouting
138
        self._ensure_real()
3650.3.13 by Aaron Bentley
Make cloning_metadir handle stacking requirements
139
        return self._real_bzrdir.cloning_metadir(stacked)
3242.3.28 by Aaron Bentley
Use repository acquisition policy for sprouting
140
1752.2.39 by Martin Pool
[broken] implement upgrade apis on remote bzrdirs
141
    def create_repository(self, shared=False):
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.
142
        # as per meta1 formats - just delegate to the format object which may
143
        # be parameterised.
144
        result = self._format.repository_format.initialize(self, shared)
145
        if not isinstance(result, RemoteRepository):
146
            return self.open_repository()
147
        else:
148
            return result
1752.2.50 by Andrew Bennetts
Implement RemoteBzrDir.create_{branch,workingtree}
149
2796.2.19 by Aaron Bentley
Support reconfigure --lightweight-checkout
150
    def destroy_repository(self):
151
        """See BzrDir.destroy_repository"""
152
        self._ensure_real()
153
        self._real_bzrdir.destroy_repository()
154
1752.2.50 by Andrew Bennetts
Implement RemoteBzrDir.create_{branch,workingtree}
155
    def create_branch(self):
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.
156
        # as per meta1 formats - just delegate to the format object which may
157
        # be parameterised.
158
        real_branch = self._format.get_branch_format().initialize(self)
159
        if not isinstance(real_branch, RemoteBranch):
4044.1.3 by Robert Collins
Create a one-shot cache of the result of RemoteBzrDir.create_branch, eliminating 3 round trips for nonstacked branches and 5 for stacked.
160
            result = RemoteBranch(self, self.find_repository(), real_branch)
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.
161
        else:
4044.1.3 by Robert Collins
Create a one-shot cache of the result of RemoteBzrDir.create_branch, eliminating 3 round trips for nonstacked branches and 5 for stacked.
162
            result = real_branch
163
        # BzrDir.clone_on_transport() uses the result of create_branch but does
164
        # not return it to its callers; we save approximately 8% of our round
165
        # trips by handing the branch we created back to the first caller to
166
        # open_branch rather than probing anew. Long term we need a API in
167
        # bzrdir that doesn't discard result objects (like result_branch).
168
        # RBC 20090225
169
        self._next_open_branch_result = result
170
        return result
1752.2.50 by Andrew Bennetts
Implement RemoteBzrDir.create_{branch,workingtree}
171
2796.2.6 by Aaron Bentley
Implement destroy_branch
172
    def destroy_branch(self):
2796.2.16 by Aaron Bentley
Documentation updates from review
173
        """See BzrDir.destroy_branch"""
2796.2.6 by Aaron Bentley
Implement destroy_branch
174
        self._ensure_real()
175
        self._real_bzrdir.destroy_branch()
4044.1.3 by Robert Collins
Create a one-shot cache of the result of RemoteBzrDir.create_branch, eliminating 3 round trips for nonstacked branches and 5 for stacked.
176
        self._next_open_branch_result = None
2796.2.6 by Aaron Bentley
Implement destroy_branch
177
2955.5.3 by Vincent Ladeuil
Fix second unwanted connection by providing the right branch to create_checkout.
178
    def create_workingtree(self, revision_id=None, from_branch=None):
2018.5.174 by Andrew Bennetts
Various nits discovered by pyflakes.
179
        raise errors.NotLocalUrl(self.transport.base)
1752.2.39 by Martin Pool
[broken] implement upgrade apis on remote bzrdirs
180
2018.5.124 by Robert Collins
Fix test_format_initialize_find_open by delegating Branch formt lookup to the BzrDir, where it should have stayed from the start.
181
    def find_branch_format(self):
182
        """Find the branch 'format' for this bzrdir.
183
184
        This might be a synthetic object for e.g. RemoteBranch and SVN.
185
        """
186
        b = self.open_branch()
187
        return b._format
188
2018.5.132 by Robert Collins
Make all BzrDir implementation tests pass on RemoteBzrDir - fix some things, and remove the incomplete_with_basis tests as cruft.
189
    def get_branch_reference(self):
190
        """See BzrDir.get_branch_reference()."""
2018.14.1 by Andrew Bennetts
Update to current hpss branch? Fix lots of test failures.
191
        path = self._path_for_remote_call(self._client)
3786.2.3 by Andrew Bennetts
Remove duplicated 'call & translate errors' code in bzrlib.remote.
192
        response = self._call('BzrDir.open_branch', path)
2018.14.1 by Andrew Bennetts
Update to current hpss branch? Fix lots of test failures.
193
        if response[0] == 'ok':
194
            if response[1] == '':
195
                # branch at this location.
2018.5.132 by Robert Collins
Make all BzrDir implementation tests pass on RemoteBzrDir - fix some things, and remove the incomplete_with_basis tests as cruft.
196
                return None
2018.14.1 by Andrew Bennetts
Update to current hpss branch? Fix lots of test failures.
197
            else:
198
                # a branch reference, use the existing BranchReference logic.
2018.5.132 by Robert Collins
Make all BzrDir implementation tests pass on RemoteBzrDir - fix some things, and remove the incomplete_with_basis tests as cruft.
199
                return response[1]
2018.6.1 by Robert Collins
Implement a BzrDir.open_branch smart server method for opening a branch without VFS.
200
        else:
2555.1.1 by Martin Pool
Remove use of 'assert False' to raise an exception unconditionally
201
            raise errors.UnexpectedSmartServerResponse(response)
2018.5.132 by Robert Collins
Make all BzrDir implementation tests pass on RemoteBzrDir - fix some things, and remove the incomplete_with_basis tests as cruft.
202
3211.4.1 by Robert Collins
* ``RemoteBzrDir._get_tree_branch`` no longer triggers ``_ensure_real``,
203
    def _get_tree_branch(self):
204
        """See BzrDir._get_tree_branch()."""
205
        return None, self.open_branch()
206
2018.5.132 by Robert Collins
Make all BzrDir implementation tests pass on RemoteBzrDir - fix some things, and remove the incomplete_with_basis tests as cruft.
207
    def open_branch(self, _unsupported=False):
3376.2.4 by Martin Pool
Remove every assert statement from bzrlib!
208
        if _unsupported:
209
            raise NotImplementedError('unsupported flag support not implemented yet.')
4044.1.3 by Robert Collins
Create a one-shot cache of the result of RemoteBzrDir.create_branch, eliminating 3 round trips for nonstacked branches and 5 for stacked.
210
        if self._next_open_branch_result is not None:
211
            # See create_branch for details.
212
            result = self._next_open_branch_result
213
            self._next_open_branch_result = None
214
            return result
2018.5.132 by Robert Collins
Make all BzrDir implementation tests pass on RemoteBzrDir - fix some things, and remove the incomplete_with_basis tests as cruft.
215
        reference_url = self.get_branch_reference()
216
        if reference_url is None:
217
            # branch at this location.
218
            return RemoteBranch(self, self.find_repository())
219
        else:
220
            # a branch reference, use the existing BranchReference logic.
221
            format = BranchReferenceFormat()
222
            return format.open(self, _found=True, location=reference_url)
3943.8.1 by Marius Kruger
remove all trailing whitespace from bzr source
223
4053.1.1 by Robert Collins
New version of the BzrDir.find_repository verb supporting _network_name to support removing more _ensure_real calls.
224
    def _open_repo_v1(self, path):
225
        verb = 'BzrDir.find_repository'
226
        response = self._call(verb, path)
227
        if response[0] != 'ok':
228
            raise errors.UnexpectedSmartServerResponse(response)
229
        # servers that only support the v1 method don't support external
230
        # references either.
231
        self._ensure_real()
232
        repo = self._real_bzrdir.open_repository()
233
        response = response + ('no', repo._format.network_name())
234
        return response, repo
235
236
    def _open_repo_v2(self, path):
237
        verb = 'BzrDir.find_repositoryV2'
238
        response = self._call(verb, path)
239
        if response[0] != 'ok':
240
            raise errors.UnexpectedSmartServerResponse(response)
241
        self._ensure_real()
242
        repo = self._real_bzrdir.open_repository()
243
        response = response + (repo._format.network_name(),)
244
        return response, repo
245
246
    def _open_repo_v3(self, path):
247
        verb = 'BzrDir.find_repositoryV3'
4053.1.2 by Robert Collins
Actually make this branch work.
248
        medium = self._client._medium
249
        if medium._is_remote_before((1, 13)):
250
            raise errors.UnknownSmartMethod(verb)
4053.1.1 by Robert Collins
New version of the BzrDir.find_repository verb supporting _network_name to support removing more _ensure_real calls.
251
        response = self._call(verb, path)
252
        if response[0] != 'ok':
253
            raise errors.UnexpectedSmartServerResponse(response)
254
        return response, None
255
1752.2.31 by Martin Pool
[broken] some support for write operations over hpss
256
    def open_repository(self):
2018.14.1 by Andrew Bennetts
Update to current hpss branch? Fix lots of test failures.
257
        path = self._path_for_remote_call(self._client)
4053.1.1 by Robert Collins
New version of the BzrDir.find_repository verb supporting _network_name to support removing more _ensure_real calls.
258
        response = None
259
        for probe in [self._open_repo_v3, self._open_repo_v2,
260
            self._open_repo_v1]:
261
            try:
262
                response, real_repo = probe(path)
263
                break
264
            except errors.UnknownSmartMethod:
265
                pass
266
        if response is None:
267
            raise errors.UnknownSmartMethod('BzrDir.find_repository{3,2,}')
3245.4.24 by Andrew Bennetts
Consistently raise errors from the server as ErrorFromSmartServer exceptions.
268
        if response[0] != 'ok':
269
            raise errors.UnexpectedSmartServerResponse(response)
4053.1.1 by Robert Collins
New version of the BzrDir.find_repository verb supporting _network_name to support removing more _ensure_real calls.
270
        if len(response) != 6:
3376.2.4 by Martin Pool
Remove every assert statement from bzrlib!
271
            raise SmartProtocolError('incorrect response length %s' % (response,))
2018.5.34 by Robert Collins
Get test_remote.BasicRemoteObjectTests.test_open_remote_branch passing by implementing a remote method BzrDir.find_repository.
272
        if response[1] == '':
4053.1.1 by Robert Collins
New version of the BzrDir.find_repository verb supporting _network_name to support removing more _ensure_real calls.
273
            # repo is at this dir.
274
            format = response_tuple_to_repo_format(response[2:])
3221.15.10 by Robert Collins
Add test that we can stack on a smart server from Jonathan Lange.
275
            # Used to support creating a real format instance when needed.
276
            format._creating_bzrdir = self
3990.5.1 by Andrew Bennetts
Add network_name() to RepositoryFormat.
277
            remote_repo = RemoteRepository(self, format)
278
            format._creating_repo = remote_repo
4053.1.1 by Robert Collins
New version of the BzrDir.find_repository verb supporting _network_name to support removing more _ensure_real calls.
279
            if real_repo is not None:
280
                remote_repo._set_real_repository(real_repo)
3990.5.1 by Andrew Bennetts
Add network_name() to RepositoryFormat.
281
            return remote_repo
2018.5.34 by Robert Collins
Get test_remote.BasicRemoteObjectTests.test_open_remote_branch passing by implementing a remote method BzrDir.find_repository.
282
        else:
283
            raise errors.NoRepositoryPresent(self)
1752.2.30 by Martin Pool
Start adding a RemoteBzrDir, etc
284
2018.5.138 by Robert Collins
Merge bzr.dev.
285
    def open_workingtree(self, recommend_upgrade=True):
2445.1.1 by Andrew Bennetts
Make RemoteBzrDir.open_workingtree raise NoWorkingTree rather than NotLocalUrl
286
        self._ensure_real()
287
        if self._real_bzrdir.has_workingtree():
288
            raise errors.NotLocalUrl(self.root_transport)
289
        else:
290
            raise errors.NoWorkingTree(self.root_transport.base)
1752.2.50 by Andrew Bennetts
Implement RemoteBzrDir.create_{branch,workingtree}
291
2018.5.42 by Robert Collins
Various hopefully improvements, but wsgi is broken, handing over to spiv :).
292
    def _path_for_remote_call(self, client):
2018.6.1 by Robert Collins
Implement a BzrDir.open_branch smart server method for opening a branch without VFS.
293
        """Return the path to be used for this bzrdir in a remote call."""
2018.5.42 by Robert Collins
Various hopefully improvements, but wsgi is broken, handing over to spiv :).
294
        return client.remote_path_from_transport(self.root_transport)
2018.6.1 by Robert Collins
Implement a BzrDir.open_branch smart server method for opening a branch without VFS.
295
1752.2.31 by Martin Pool
[broken] some support for write operations over hpss
296
    def get_branch_transport(self, branch_format):
2018.5.162 by Andrew Bennetts
Add some missing _ensure_real calls, and a missing import.
297
        self._ensure_real()
1752.2.31 by Martin Pool
[broken] some support for write operations over hpss
298
        return self._real_bzrdir.get_branch_transport(branch_format)
299
1752.2.43 by Andrew Bennetts
Fix get_{branch,repository,workingtree}_transport.
300
    def get_repository_transport(self, repository_format):
2018.5.162 by Andrew Bennetts
Add some missing _ensure_real calls, and a missing import.
301
        self._ensure_real()
1752.2.43 by Andrew Bennetts
Fix get_{branch,repository,workingtree}_transport.
302
        return self._real_bzrdir.get_repository_transport(repository_format)
303
304
    def get_workingtree_transport(self, workingtree_format):
2018.5.162 by Andrew Bennetts
Add some missing _ensure_real calls, and a missing import.
305
        self._ensure_real()
1752.2.43 by Andrew Bennetts
Fix get_{branch,repository,workingtree}_transport.
306
        return self._real_bzrdir.get_workingtree_transport(workingtree_format)
307
1752.2.39 by Martin Pool
[broken] implement upgrade apis on remote bzrdirs
308
    def can_convert_format(self):
309
        """Upgrading of remote bzrdirs is not supported yet."""
310
        return False
311
312
    def needs_format_conversion(self, format=None):
313
        """Upgrading of remote bzrdirs is not supported yet."""
3943.2.5 by Martin Pool
deprecate needs_format_conversion(format=None)
314
        if format is None:
315
            symbol_versioning.warn(symbol_versioning.deprecated_in((1, 13, 0))
316
                % 'needs_format_conversion(format=None)')
1752.2.39 by Martin Pool
[broken] implement upgrade apis on remote bzrdirs
317
        return False
318
3242.3.37 by Aaron Bentley
Updates from reviews
319
    def clone(self, url, revision_id=None, force_new_repo=False,
320
              preserve_stacking=False):
2018.5.94 by Andrew Bennetts
Various small changes in aid of making tests pass (including deleting one invalid test).
321
        self._ensure_real()
322
        return self._real_bzrdir.clone(url, revision_id=revision_id,
3242.3.37 by Aaron Bentley
Updates from reviews
323
            force_new_repo=force_new_repo, preserve_stacking=preserve_stacking)
2018.5.94 by Andrew Bennetts
Various small changes in aid of making tests pass (including deleting one invalid test).
324
3567.1.3 by Michael Hudson
fix problem
325
    def get_config(self):
326
        self._ensure_real()
327
        return self._real_bzrdir.get_config()
328
1752.2.31 by Martin Pool
[broken] some support for write operations over hpss
329
1752.2.52 by Andrew Bennetts
Flesh out more Remote* methods needed to open and initialise remote branches/trees/repositories.
330
class RemoteRepositoryFormat(repository.RepositoryFormat):
2018.5.159 by Andrew Bennetts
Rename SmartClient to _SmartClient.
331
    """Format for repositories accessed over a _SmartClient.
1752.2.31 by Martin Pool
[broken] some support for write operations over hpss
332
1752.2.50 by Andrew Bennetts
Implement RemoteBzrDir.create_{branch,workingtree}
333
    Instances of this repository are represented by RemoteRepository
1752.2.31 by Martin Pool
[broken] some support for write operations over hpss
334
    instances.
2018.5.118 by Robert Collins
Fix RemoteRepositoryFormat to have appropriate rich_root_data and support_tree_reference.
335
3128.1.3 by Vincent Ladeuil
Since we are there s/parameteris.*/parameteriz&/.
336
    The RemoteRepositoryFormat is parameterized during construction
2018.5.118 by Robert Collins
Fix RemoteRepositoryFormat to have appropriate rich_root_data and support_tree_reference.
337
    to reflect the capabilities of the real, remote format. Specifically
2018.5.138 by Robert Collins
Merge bzr.dev.
338
    the attributes rich_root_data and supports_tree_reference are set
2018.5.118 by Robert Collins
Fix RemoteRepositoryFormat to have appropriate rich_root_data and support_tree_reference.
339
    on a per instance basis, and are not set (and should not be) at
340
    the class level.
3990.5.3 by Robert Collins
Docs and polish on RepositoryFormat.network_name.
341
4032.1.1 by John Arbash Meinel
Merge the removal of all trailing whitespace, and resolve conflicts.
342
    :ivar _custom_format: If set, a specific concrete repository format that
3990.5.3 by Robert Collins
Docs and polish on RepositoryFormat.network_name.
343
        will be used when initializing a repository with this
344
        RemoteRepositoryFormat.
345
    :ivar _creating_repo: If set, the repository object that this
346
        RemoteRepositoryFormat was created for: it can be called into
3990.5.4 by Robert Collins
Review feedback.
347
        to obtain data like the network name.
1752.2.31 by Martin Pool
[broken] some support for write operations over hpss
348
    """
349
3543.1.2 by Michael Hudson
the two character fix
350
    _matchingbzrdir = RemoteBzrDirFormat()
1752.2.31 by Martin Pool
[broken] some support for write operations over hpss
351
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.
352
    def __init__(self):
353
        repository.RepositoryFormat.__init__(self)
354
        self._custom_format = None
4017.3.2 by Robert Collins
Reduce the number of round trips required to create a repository over the network.
355
        self._network_name = None
4017.3.3 by Robert Collins
Review feedback - make RemoteRepository.initialize use helpers, and version-lock the new method to not attempt the method on older servers.
356
        self._creating_bzrdir = None
357
358
    def _vfs_initialize(self, a_bzrdir, shared):
359
        """Helper for common code in initialize."""
360
        if self._custom_format:
361
            # Custom format requested
362
            result = self._custom_format.initialize(a_bzrdir, shared=shared)
363
        elif self._creating_bzrdir is not None:
364
            # Use the format that the repository we were created to back
365
            # has.
366
            prior_repo = self._creating_bzrdir.open_repository()
367
            prior_repo._ensure_real()
368
            result = prior_repo._real_repository._format.initialize(
369
                a_bzrdir, shared=shared)
370
        else:
371
            # assume that a_bzr is a RemoteBzrDir but the smart server didn't
372
            # support remote initialization.
373
            # We delegate to a real object at this point (as RemoteBzrDir
374
            # delegate to the repository format which would lead to infinite
375
            # recursion if we just called a_bzrdir.create_repository.
376
            a_bzrdir._ensure_real()
377
            result = a_bzrdir._real_bzrdir.create_repository(shared=shared)
378
        if not isinstance(result, RemoteRepository):
379
            return self.open(a_bzrdir)
380
        else:
381
            return result
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.
382
1752.2.52 by Andrew Bennetts
Flesh out more Remote* methods needed to open and initialise remote branches/trees/repositories.
383
    def initialize(self, a_bzrdir, shared=False):
4017.3.2 by Robert Collins
Reduce the number of round trips required to create a repository over the network.
384
        # Being asked to create on a non RemoteBzrDir:
385
        if not isinstance(a_bzrdir, RemoteBzrDir):
4017.3.3 by Robert Collins
Review feedback - make RemoteRepository.initialize use helpers, and version-lock the new method to not attempt the method on older servers.
386
            return self._vfs_initialize(a_bzrdir, shared)
387
        medium = a_bzrdir._client._medium
388
        if medium._is_remote_before((1, 13)):
389
            return self._vfs_initialize(a_bzrdir, shared)
4017.3.2 by Robert Collins
Reduce the number of round trips required to create a repository over the network.
390
        # Creating on a remote bzr dir.
391
        # 1) get the network name to use.
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.
392
        if self._custom_format:
4017.3.2 by Robert Collins
Reduce the number of round trips required to create a repository over the network.
393
            network_name = self._custom_format.network_name()
394
        else:
395
            # Select the current bzrlib default and ask for that.
396
            reference_bzrdir_format = bzrdir.format_registry.get('default')()
397
            reference_format = reference_bzrdir_format.repository_format
398
            network_name = reference_format.network_name()
399
        # 2) try direct creation via RPC
400
        path = a_bzrdir._path_for_remote_call(a_bzrdir._client)
401
        verb = 'BzrDir.create_repository'
402
        if shared:
403
            shared_str = 'True'
404
        else:
405
            shared_str = 'False'
406
        try:
407
            response = a_bzrdir._call(verb, path, network_name, shared_str)
408
        except errors.UnknownSmartMethod:
4017.3.3 by Robert Collins
Review feedback - make RemoteRepository.initialize use helpers, and version-lock the new method to not attempt the method on older servers.
409
            # Fallback - use vfs methods
410
            return self._vfs_initialize(a_bzrdir, shared)
4017.3.2 by Robert Collins
Reduce the number of round trips required to create a repository over the network.
411
        else:
412
            # Turn the response into a RemoteRepository object.
4032.3.2 by Robert Collins
Create and use a RPC call to create branches on bzr servers rather than using VFS calls.
413
            format = response_tuple_to_repo_format(response[1:])
4017.3.2 by Robert Collins
Reduce the number of round trips required to create a repository over the network.
414
            # Used to support creating a real format instance when needed.
415
            format._creating_bzrdir = a_bzrdir
416
            remote_repo = RemoteRepository(a_bzrdir, format)
417
            format._creating_repo = remote_repo
418
            return remote_repo
3943.8.1 by Marius Kruger
remove all trailing whitespace from bzr source
419
1752.2.52 by Andrew Bennetts
Flesh out more Remote* methods needed to open and initialise remote branches/trees/repositories.
420
    def open(self, a_bzrdir):
3376.2.4 by Martin Pool
Remove every assert statement from bzrlib!
421
        if not isinstance(a_bzrdir, RemoteBzrDir):
422
            raise AssertionError('%r is not a RemoteBzrDir' % (a_bzrdir,))
1752.2.72 by Andrew Bennetts
Make Remote* classes in remote.py more consistent and remove some dead code.
423
        return a_bzrdir.open_repository()
1752.2.52 by Andrew Bennetts
Flesh out more Remote* methods needed to open and initialise remote branches/trees/repositories.
424
4053.1.4 by Robert Collins
Move the fetch control attributes from Repository to RepositoryFormat.
425
    def _ensure_real(self):
426
        if self._custom_format is None:
427
            self._custom_format = repository.network_format_registry.get(
428
                self._network_name)
429
430
    @property
431
    def _fetch_order(self):
432
        self._ensure_real()
433
        return self._custom_format._fetch_order
434
435
    @property
436
    def _fetch_uses_deltas(self):
437
        self._ensure_real()
438
        return self._custom_format._fetch_uses_deltas
439
440
    @property
441
    def _fetch_reconcile(self):
442
        self._ensure_real()
443
        return self._custom_format._fetch_reconcile
444
1752.2.52 by Andrew Bennetts
Flesh out more Remote* methods needed to open and initialise remote branches/trees/repositories.
445
    def get_format_description(self):
446
        return 'bzr remote repository'
447
448
    def __eq__(self, other):
1752.2.87 by Andrew Bennetts
Make tests pass.
449
        return self.__class__ == other.__class__
450
2018.5.118 by Robert Collins
Fix RemoteRepositoryFormat to have appropriate rich_root_data and support_tree_reference.
451
    def check_conversion_target(self, target_format):
452
        if self.rich_root_data and not target_format.rich_root_data:
453
            raise errors.BadConversionTarget(
454
                'Does not support rich root data.', target_format)
2018.5.138 by Robert Collins
Merge bzr.dev.
455
        if (self.supports_tree_reference and
456
            not getattr(target_format, 'supports_tree_reference', False)):
2018.5.118 by Robert Collins
Fix RemoteRepositoryFormat to have appropriate rich_root_data and support_tree_reference.
457
            raise errors.BadConversionTarget(
458
                'Does not support nested trees', target_format)
1752.2.52 by Andrew Bennetts
Flesh out more Remote* methods needed to open and initialise remote branches/trees/repositories.
459
3990.5.1 by Andrew Bennetts
Add network_name() to RepositoryFormat.
460
    def network_name(self):
4017.3.2 by Robert Collins
Reduce the number of round trips required to create a repository over the network.
461
        if self._network_name:
462
            return self._network_name
3990.5.1 by Andrew Bennetts
Add network_name() to RepositoryFormat.
463
        self._creating_repo._ensure_real()
464
        return self._creating_repo._real_repository._format.network_name()
465
4022.1.1 by Robert Collins
Refactoring of fetch to have a sender and sink component enabling splitting the logic over a network stream. (Robert Collins, Andrew Bennetts)
466
    @property
467
    def _serializer(self):
4053.1.4 by Robert Collins
Move the fetch control attributes from Repository to RepositoryFormat.
468
        self._ensure_real()
469
        return self._custom_format._serializer
4022.1.1 by Robert Collins
Refactoring of fetch to have a sender and sink component enabling splitting the logic over a network stream. (Robert Collins, Andrew Bennetts)
470
1752.2.31 by Martin Pool
[broken] some support for write operations over hpss
471
3786.2.3 by Andrew Bennetts
Remove duplicated 'call & translate errors' code in bzrlib.remote.
472
class RemoteRepository(_RpcHelper):
1752.2.31 by Martin Pool
[broken] some support for write operations over hpss
473
    """Repository accessed over rpc.
474
2018.5.163 by Andrew Bennetts
Deal with various review comments from Robert.
475
    For the moment most operations are performed using local transport-backed
476
    Repository objects.
1752.2.31 by Martin Pool
[broken] some support for write operations over hpss
477
    """
478
2018.5.118 by Robert Collins
Fix RemoteRepositoryFormat to have appropriate rich_root_data and support_tree_reference.
479
    def __init__(self, remote_bzrdir, format, real_repository=None, _client=None):
2018.5.34 by Robert Collins
Get test_remote.BasicRemoteObjectTests.test_open_remote_branch passing by implementing a remote method BzrDir.find_repository.
480
        """Create a RemoteRepository instance.
3943.8.1 by Marius Kruger
remove all trailing whitespace from bzr source
481
2018.5.34 by Robert Collins
Get test_remote.BasicRemoteObjectTests.test_open_remote_branch passing by implementing a remote method BzrDir.find_repository.
482
        :param remote_bzrdir: The bzrdir hosting this repository.
2018.5.118 by Robert Collins
Fix RemoteRepositoryFormat to have appropriate rich_root_data and support_tree_reference.
483
        :param format: The RemoteFormat object to use.
2018.5.34 by Robert Collins
Get test_remote.BasicRemoteObjectTests.test_open_remote_branch passing by implementing a remote method BzrDir.find_repository.
484
        :param real_repository: If not None, a local implementation of the
485
            repository logic for the repository, usually accessing the data
486
            via the VFS.
2018.5.57 by Robert Collins
Implement RemoteRepository.is_shared (Robert Collins, Vincent Ladeuil).
487
        :param _client: Private testing parameter - override the smart client
488
            to be used by the repository.
2018.5.34 by Robert Collins
Get test_remote.BasicRemoteObjectTests.test_open_remote_branch passing by implementing a remote method BzrDir.find_repository.
489
        """
490
        if real_repository:
2018.5.36 by Andrew Bennetts
Fix typo, and clean up some ununsed import warnings from pyflakes at the same time.
491
            self._real_repository = real_repository
2018.5.70 by Robert Collins
Only try to get real repositories when an operation requires them.
492
        else:
493
            self._real_repository = None
1752.2.50 by Andrew Bennetts
Implement RemoteBzrDir.create_{branch,workingtree}
494
        self.bzrdir = remote_bzrdir
2018.5.57 by Robert Collins
Implement RemoteRepository.is_shared (Robert Collins, Vincent Ladeuil).
495
        if _client is None:
3313.2.1 by Andrew Bennetts
Change _SmartClient's API to accept a medium and a base, rather than a _SharedConnection.
496
            self._client = remote_bzrdir._client
2018.5.57 by Robert Collins
Implement RemoteRepository.is_shared (Robert Collins, Vincent Ladeuil).
497
        else:
498
            self._client = _client
2018.5.118 by Robert Collins
Fix RemoteRepositoryFormat to have appropriate rich_root_data and support_tree_reference.
499
        self._format = format
2018.5.75 by Andrew Bennetts
Add Repository.{dont_,}leave_lock_in_place.
500
        self._lock_mode = None
501
        self._lock_token = None
502
        self._lock_count = 0
2018.5.78 by Andrew Bennetts
Implement RemoteRepository.lock_write/unlock to expect and send tokens over the
503
        self._leave_lock = False
3835.1.12 by Aaron Bentley
Unify CachingExtraParentsProvider and CachingParentsProvider.
504
        self._unstacked_provider = graph.CachingParentsProvider(
3896.1.1 by Andrew Bennetts
Remove broken debugging cruft, and some unused imports.
505
            get_parent_map=self._get_parent_map_rpc)
3835.1.12 by Aaron Bentley
Unify CachingExtraParentsProvider and CachingParentsProvider.
506
        self._unstacked_provider.disable_cache()
2951.1.10 by Robert Collins
Peer review feedback with Ian.
507
        # For tests:
508
        # These depend on the actual remote format, so force them off for
509
        # maximum compatibility. XXX: In future these should depend on the
510
        # remote repository instance, but this is irrelevant until we perform
511
        # reconcile via an RPC call.
2951.1.5 by Robert Collins
Some work towards including the correct changes for TREE_ROOT in check parameterised tests.
512
        self._reconcile_does_inventory_gc = False
513
        self._reconcile_fixes_text_parents = False
2951.1.3 by Robert Collins
Partial support for native reconcile with packs.
514
        self._reconcile_backsup_inventory = False
2592.4.5 by Martin Pool
Add Repository.base on all repositories.
515
        self.base = self.bzrdir.transport.base
3221.12.1 by Robert Collins
Backport development1 format (stackable packs) to before-shallow-branches.
516
        # Additional places to query for data.
517
        self._fallback_repositories = []
2592.4.5 by Martin Pool
Add Repository.base on all repositories.
518
519
    def __str__(self):
520
        return "%s(%s)" % (self.__class__.__name__, self.base)
521
522
    __repr__ = __str__
1752.2.52 by Andrew Bennetts
Flesh out more Remote* methods needed to open and initialise remote branches/trees/repositories.
523
3825.4.1 by Andrew Bennetts
Add suppress_errors to abort_write_group.
524
    def abort_write_group(self, suppress_errors=False):
2617.6.7 by Robert Collins
More review feedback.
525
        """Complete a write group on the decorated repository.
3943.8.1 by Marius Kruger
remove all trailing whitespace from bzr source
526
2617.6.2 by Robert Collins
Add abort_write_group and wire write_groups into fetch and commit.
527
        Smart methods peform operations in a single step so this api
2617.6.6 by Robert Collins
Some review feedback.
528
        is not really applicable except as a compatibility thunk
2617.6.2 by Robert Collins
Add abort_write_group and wire write_groups into fetch and commit.
529
        for older plugins that don't use e.g. the CommitBuilder
530
        facility.
3825.4.6 by Andrew Bennetts
Document the suppress_errors flag in the docstring.
531
532
        :param suppress_errors: see Repository.abort_write_group.
2617.6.2 by Robert Collins
Add abort_write_group and wire write_groups into fetch and commit.
533
        """
534
        self._ensure_real()
3825.4.1 by Andrew Bennetts
Add suppress_errors to abort_write_group.
535
        return self._real_repository.abort_write_group(
536
            suppress_errors=suppress_errors)
2617.6.2 by Robert Collins
Add abort_write_group and wire write_groups into fetch and commit.
537
538
    def commit_write_group(self):
2617.6.7 by Robert Collins
More review feedback.
539
        """Complete a write group on the decorated repository.
3943.8.1 by Marius Kruger
remove all trailing whitespace from bzr source
540
2617.6.2 by Robert Collins
Add abort_write_group and wire write_groups into fetch and commit.
541
        Smart methods peform operations in a single step so this api
2617.6.6 by Robert Collins
Some review feedback.
542
        is not really applicable except as a compatibility thunk
2617.6.2 by Robert Collins
Add abort_write_group and wire write_groups into fetch and commit.
543
        for older plugins that don't use e.g. the CommitBuilder
544
        facility.
545
        """
546
        self._ensure_real()
547
        return self._real_repository.commit_write_group()
2617.6.1 by Robert Collins
* New method on Repository - ``start_write_group``, ``end_write_group``
548
4002.1.1 by Andrew Bennetts
Implement suspend_write_group/resume_write_group.
549
    def resume_write_group(self, tokens):
550
        self._ensure_real()
551
        return self._real_repository.resume_write_group(tokens)
552
553
    def suspend_write_group(self):
554
        self._ensure_real()
555
        return self._real_repository.suspend_write_group()
556
2018.5.70 by Robert Collins
Only try to get real repositories when an operation requires them.
557
    def _ensure_real(self):
558
        """Ensure that there is a _real_repository set.
559
2018.5.163 by Andrew Bennetts
Deal with various review comments from Robert.
560
        Used before calls to self._real_repository.
2018.5.70 by Robert Collins
Only try to get real repositories when an operation requires them.
561
        """
3692.1.3 by Andrew Bennetts
Delete some cruft (like the _ensure_real call in RemoteBranch.lock_write), improve some comments, and wrap some long lines.
562
        if self._real_repository is None:
2018.5.70 by Robert Collins
Only try to get real repositories when an operation requires them.
563
            self.bzrdir._ensure_real()
3692.1.3 by Andrew Bennetts
Delete some cruft (like the _ensure_real call in RemoteBranch.lock_write), improve some comments, and wrap some long lines.
564
            self._set_real_repository(
565
                self.bzrdir._real_bzrdir.open_repository())
2018.5.70 by Robert Collins
Only try to get real repositories when an operation requires them.
566
3533.3.1 by Andrew Bennetts
Remove duplication of error translation in bzrlib/remote.py.
567
    def _translate_error(self, err, **context):
568
        self.bzrdir._translate_error(err, repository=self, **context)
569
2988.1.2 by Robert Collins
New Repository API find_text_key_references for use by reconcile and check.
570
    def find_text_key_references(self):
571
        """Find the text key references within the repository.
572
573
        :return: a dictionary mapping (file_id, revision_id) tuples to altered file-ids to an iterable of
574
        revision_ids. Each altered file-ids has the exact revision_ids that
575
        altered it listed explicitly.
576
        :return: A dictionary mapping text keys ((fileid, revision_id) tuples)
577
            to whether they were referred to by the inventory of the
578
            revision_id that they contain. The inventory texts from all present
579
            revision ids are assessed to generate this report.
580
        """
581
        self._ensure_real()
582
        return self._real_repository.find_text_key_references()
583
2988.1.3 by Robert Collins
Add a new repositoy method _generate_text_key_index for use by reconcile/check.
584
    def _generate_text_key_index(self):
585
        """Generate a new text key index for the repository.
586
587
        This is an expensive function that will take considerable time to run.
588
589
        :return: A dict mapping (file_id, revision_id) tuples to a list of
590
            parents, also (file_id, revision_id) tuples.
591
        """
592
        self._ensure_real()
593
        return self._real_repository._generate_text_key_index()
594
3287.6.1 by Robert Collins
* ``VersionedFile.get_graph`` is deprecated, with no replacement method.
595
    @symbol_versioning.deprecated_method(symbol_versioning.one_four)
2018.5.67 by Wouter van Heyst
Implement RemoteRepository.get_revision_graph (Wouter van Heyst, Robert Collins)
596
    def get_revision_graph(self, revision_id=None):
597
        """See Repository.get_revision_graph()."""
3287.6.4 by Robert Collins
Fix up deprecation warnings for get_revision_graph.
598
        return self._get_revision_graph(revision_id)
599
600
    def _get_revision_graph(self, revision_id):
601
        """Private method for using with old (< 1.2) servers to fallback."""
2018.5.67 by Wouter van Heyst
Implement RemoteRepository.get_revision_graph (Wouter van Heyst, Robert Collins)
602
        if revision_id is None:
603
            revision_id = ''
2948.3.1 by John Arbash Meinel
Fix bug #158333, make sure that Repository.fetch(self) is properly a no-op for all Repository implementations.
604
        elif revision.is_null(revision_id):
2018.5.67 by Wouter van Heyst
Implement RemoteRepository.get_revision_graph (Wouter van Heyst, Robert Collins)
605
            return {}
606
607
        path = self.bzrdir._path_for_remote_call(self._client)
3786.2.3 by Andrew Bennetts
Remove duplicated 'call & translate errors' code in bzrlib.remote.
608
        response = self._call_expecting_body(
609
            'Repository.get_revision_graph', path, revision_id)
3245.4.58 by Andrew Bennetts
Unpack call_expecting_body's return value into variables, to avoid lots of ugly subscripting.
610
        response_tuple, response_handler = response
611
        if response_tuple[0] != 'ok':
612
            raise errors.UnexpectedSmartServerResponse(response_tuple)
613
        coded = response_handler.read_body_bytes()
3245.4.24 by Andrew Bennetts
Consistently raise errors from the server as ErrorFromSmartServer exceptions.
614
        if coded == '':
615
            # no revisions in this repository!
616
            return {}
617
        lines = coded.split('\n')
618
        revision_graph = {}
619
        for line in lines:
620
            d = tuple(line.split())
621
            revision_graph[d[0]] = d[1:]
3943.8.1 by Marius Kruger
remove all trailing whitespace from bzr source
622
3245.4.24 by Andrew Bennetts
Consistently raise errors from the server as ErrorFromSmartServer exceptions.
623
        return revision_graph
2018.5.67 by Wouter van Heyst
Implement RemoteRepository.get_revision_graph (Wouter van Heyst, Robert Collins)
624
4022.1.1 by Robert Collins
Refactoring of fetch to have a sender and sink component enabling splitting the logic over a network stream. (Robert Collins, Andrew Bennetts)
625
    def _get_sink(self):
626
        """See Repository._get_sink()."""
4022.1.6 by Robert Collins
Cherrypick and polish the RemoteSink for streaming push.
627
        return RemoteStreamSink(self)
4022.1.1 by Robert Collins
Refactoring of fetch to have a sender and sink component enabling splitting the logic over a network stream. (Robert Collins, Andrew Bennetts)
628
4060.1.3 by Robert Collins
Implement the separate source component for fetch - repository.StreamSource.
629
    def _get_source(self, to_format):
630
        """Return a source for streaming from this repository."""
631
        return RemoteStreamSource(self, to_format)
632
2018.5.40 by Robert Collins
Implement a remote Repository.has_revision method.
633
    def has_revision(self, revision_id):
634
        """See Repository.has_revision()."""
3172.3.1 by Robert Collins
Repository has a new method ``has_revisions`` which signals the presence
635
        if revision_id == NULL_REVISION:
2018.14.1 by Andrew Bennetts
Update to current hpss branch? Fix lots of test failures.
636
            # The null revision is always present.
637
            return True
2018.5.42 by Robert Collins
Various hopefully improvements, but wsgi is broken, handing over to spiv :).
638
        path = self.bzrdir._path_for_remote_call(self._client)
3786.2.3 by Andrew Bennetts
Remove duplicated 'call & translate errors' code in bzrlib.remote.
639
        response = self._call('Repository.has_revision', path, revision_id)
3376.2.4 by Martin Pool
Remove every assert statement from bzrlib!
640
        if response[0] not in ('yes', 'no'):
3245.4.58 by Andrew Bennetts
Unpack call_expecting_body's return value into variables, to avoid lots of ugly subscripting.
641
            raise errors.UnexpectedSmartServerResponse(response)
3691.2.2 by Martin Pool
Fix some problems in access to stacked repositories over hpss (#261315)
642
        if response[0] == 'yes':
643
            return True
644
        for fallback_repo in self._fallback_repositories:
645
            if fallback_repo.has_revision(revision_id):
646
                return True
647
        return False
2018.5.40 by Robert Collins
Implement a remote Repository.has_revision method.
648
3172.3.1 by Robert Collins
Repository has a new method ``has_revisions`` which signals the presence
649
    def has_revisions(self, revision_ids):
650
        """See Repository.has_revisions()."""
3691.2.2 by Martin Pool
Fix some problems in access to stacked repositories over hpss (#261315)
651
        # FIXME: This does many roundtrips, particularly when there are
652
        # fallback repositories.  -- mbp 20080905
3172.3.1 by Robert Collins
Repository has a new method ``has_revisions`` which signals the presence
653
        result = set()
654
        for revision_id in revision_ids:
655
            if self.has_revision(revision_id):
656
                result.add(revision_id)
657
        return result
658
2617.6.9 by Robert Collins
Merge bzr.dev.
659
    def has_same_location(self, other):
2592.3.162 by Robert Collins
Remove some arbitrary differences from bzr.dev.
660
        return (self.__class__ == other.__class__ and
661
                self.bzrdir.transport.base == other.bzrdir.transport.base)
3835.1.1 by Aaron Bentley
Stack get_parent_map on fallback repos
662
2490.2.21 by Aaron Bentley
Rename graph to deprecated_graph
663
    def get_graph(self, other_repository=None):
664
        """Return the graph for this repository format"""
3835.1.17 by Aaron Bentley
Fix stacking bug
665
        parents_provider = self._make_parents_provider(other_repository)
3441.5.24 by Andrew Bennetts
Remove RemoteGraph experiment.
666
        return graph.Graph(parents_provider)
2490.2.5 by Aaron Bentley
Use GraphWalker.unique_ancestor to determine merge base
667
2018.14.1 by Andrew Bennetts
Update to current hpss branch? Fix lots of test failures.
668
    def gather_stats(self, revid=None, committers=None):
2018.5.62 by Robert Collins
Stub out RemoteRepository.gather_stats while its implemented in parallel.
669
        """See Repository.gather_stats()."""
2018.10.3 by v.ladeuil+lp at free
more tests for gather_stats
670
        path = self.bzrdir._path_for_remote_call(self._client)
2948.3.4 by John Arbash Meinel
Repository.gather_stats() validly can get None for the revid.
671
        # revid can be None to indicate no revisions, not just NULL_REVISION
672
        if revid is None or revision.is_null(revid):
2018.10.3 by v.ladeuil+lp at free
more tests for gather_stats
673
            fmt_revid = ''
674
        else:
2018.5.83 by Andrew Bennetts
Fix some test failures caused by the switch from unicode to UTF-8-encoded strs for revision IDs.
675
            fmt_revid = revid
2018.14.1 by Andrew Bennetts
Update to current hpss branch? Fix lots of test failures.
676
        if committers is None or not committers:
2018.10.3 by v.ladeuil+lp at free
more tests for gather_stats
677
            fmt_committers = 'no'
678
        else:
679
            fmt_committers = 'yes'
3786.2.3 by Andrew Bennetts
Remove duplicated 'call & translate errors' code in bzrlib.remote.
680
        response_tuple, response_handler = self._call_expecting_body(
2018.5.153 by Andrew Bennetts
Rename call2 to call_expecting_body, and other small changes prompted by review.
681
            'Repository.gather_stats', path, fmt_revid, fmt_committers)
3245.4.58 by Andrew Bennetts
Unpack call_expecting_body's return value into variables, to avoid lots of ugly subscripting.
682
        if response_tuple[0] != 'ok':
683
            raise errors.UnexpectedSmartServerResponse(response_tuple)
2018.10.3 by v.ladeuil+lp at free
more tests for gather_stats
684
3245.4.58 by Andrew Bennetts
Unpack call_expecting_body's return value into variables, to avoid lots of ugly subscripting.
685
        body = response_handler.read_body_bytes()
2018.10.3 by v.ladeuil+lp at free
more tests for gather_stats
686
        result = {}
687
        for line in body.split('\n'):
688
            if not line:
689
                continue
690
            key, val_text = line.split(':')
691
            if key in ('revisions', 'size', 'committers'):
692
                result[key] = int(val_text)
693
            elif key in ('firstrev', 'latestrev'):
694
                values = val_text.split(' ')[1:]
695
                result[key] = (float(values[0]), long(values[1]))
696
697
        return result
2018.5.62 by Robert Collins
Stub out RemoteRepository.gather_stats while its implemented in parallel.
698
3140.1.2 by Aaron Bentley
Add ability to find branches inside repositories
699
    def find_branches(self, using=False):
700
        """See Repository.find_branches()."""
701
        # should be an API call to the server.
702
        self._ensure_real()
703
        return self._real_repository.find_branches(using=using)
704
2018.5.60 by Robert Collins
More missing methods from RemoteBranch and RemoteRepository to let 'info' get further.
705
    def get_physical_lock_status(self):
706
        """See Repository.get_physical_lock_status()."""
3015.2.10 by Robert Collins
Fix regression due to other pack related fixes in tests with packs not-default.
707
        # should be an API call to the server.
708
        self._ensure_real()
709
        return self._real_repository.get_physical_lock_status()
2018.5.60 by Robert Collins
More missing methods from RemoteBranch and RemoteRepository to let 'info' get further.
710
2617.6.1 by Robert Collins
* New method on Repository - ``start_write_group``, ``end_write_group``
711
    def is_in_write_group(self):
712
        """Return True if there is an open write group.
713
714
        write groups are only applicable locally for the smart server..
715
        """
716
        if self._real_repository:
717
            return self._real_repository.is_in_write_group()
718
719
    def is_locked(self):
720
        return self._lock_count >= 1
721
2018.5.57 by Robert Collins
Implement RemoteRepository.is_shared (Robert Collins, Vincent Ladeuil).
722
    def is_shared(self):
723
        """See Repository.is_shared()."""
724
        path = self.bzrdir._path_for_remote_call(self._client)
3786.2.3 by Andrew Bennetts
Remove duplicated 'call & translate errors' code in bzrlib.remote.
725
        response = self._call('Repository.is_shared', path)
3376.2.4 by Martin Pool
Remove every assert statement from bzrlib!
726
        if response[0] not in ('yes', 'no'):
727
            raise SmartProtocolError('unexpected response code %s' % (response,))
2018.5.57 by Robert Collins
Implement RemoteRepository.is_shared (Robert Collins, Vincent Ladeuil).
728
        return response[0] == 'yes'
729
2904.1.1 by Robert Collins
* New method ``bzrlib.repository.Repository.is_write_locked`` useful for
730
    def is_write_locked(self):
731
        return self._lock_mode == 'w'
732
2018.5.60 by Robert Collins
More missing methods from RemoteBranch and RemoteRepository to let 'info' get further.
733
    def lock_read(self):
734
        # wrong eventually - want a local lock cache context
2018.5.75 by Andrew Bennetts
Add Repository.{dont_,}leave_lock_in_place.
735
        if not self._lock_mode:
736
            self._lock_mode = 'r'
737
            self._lock_count = 1
3835.1.15 by Aaron Bentley
Allow miss caching to be disabled.
738
            self._unstacked_provider.enable_cache(cache_misses=False)
2018.5.78 by Andrew Bennetts
Implement RemoteRepository.lock_write/unlock to expect and send tokens over the
739
            if self._real_repository is not None:
740
                self._real_repository.lock_read()
2018.5.75 by Andrew Bennetts
Add Repository.{dont_,}leave_lock_in_place.
741
        else:
742
            self._lock_count += 1
2018.5.78 by Andrew Bennetts
Implement RemoteRepository.lock_write/unlock to expect and send tokens over the
743
2018.14.1 by Andrew Bennetts
Update to current hpss branch? Fix lots of test failures.
744
    def _remote_lock_write(self, token):
2018.5.78 by Andrew Bennetts
Implement RemoteRepository.lock_write/unlock to expect and send tokens over the
745
        path = self.bzrdir._path_for_remote_call(self._client)
746
        if token is None:
747
            token = ''
3786.2.3 by Andrew Bennetts
Remove duplicated 'call & translate errors' code in bzrlib.remote.
748
        err_context = {'token': token}
749
        response = self._call('Repository.lock_write', path, token,
750
                              **err_context)
2018.5.78 by Andrew Bennetts
Implement RemoteRepository.lock_write/unlock to expect and send tokens over the
751
        if response[0] == 'ok':
752
            ok, token = response
753
            return token
754
        else:
2555.1.1 by Martin Pool
Remove use of 'assert False' to raise an exception unconditionally
755
            raise errors.UnexpectedSmartServerResponse(response)
2018.5.60 by Robert Collins
More missing methods from RemoteBranch and RemoteRepository to let 'info' get further.
756
3692.1.1 by Andrew Bennetts
Make RemoteBranch.lock_write lock the repository too.
757
    def lock_write(self, token=None, _skip_rpc=False):
2018.5.75 by Andrew Bennetts
Add Repository.{dont_,}leave_lock_in_place.
758
        if not self._lock_mode:
3692.1.1 by Andrew Bennetts
Make RemoteBranch.lock_write lock the repository too.
759
            if _skip_rpc:
760
                if self._lock_token is not None:
761
                    if token != self._lock_token:
3695.1.1 by Andrew Bennetts
Remove some unused imports and fix a couple of trivially broken raise statements.
762
                        raise errors.TokenMismatch(token, self._lock_token)
3692.1.1 by Andrew Bennetts
Make RemoteBranch.lock_write lock the repository too.
763
                self._lock_token = token
764
            else:
765
                self._lock_token = self._remote_lock_write(token)
3015.2.9 by Robert Collins
Handle repositories that do not allow remote locking, like pack repositories, in the client side remote server proxy objects.
766
            # if self._lock_token is None, then this is something like packs or
767
            # svn where we don't get to lock the repo, or a weave style repository
768
            # where we cannot lock it over the wire and attempts to do so will
769
            # fail.
2018.5.78 by Andrew Bennetts
Implement RemoteRepository.lock_write/unlock to expect and send tokens over the
770
            if self._real_repository is not None:
771
                self._real_repository.lock_write(token=self._lock_token)
772
            if token is not None:
773
                self._leave_lock = True
774
            else:
775
                self._leave_lock = False
2018.5.75 by Andrew Bennetts
Add Repository.{dont_,}leave_lock_in_place.
776
            self._lock_mode = 'w'
777
            self._lock_count = 1
3835.1.15 by Aaron Bentley
Allow miss caching to be disabled.
778
            self._unstacked_provider.enable_cache(cache_misses=False)
2018.5.75 by Andrew Bennetts
Add Repository.{dont_,}leave_lock_in_place.
779
        elif self._lock_mode == 'r':
2018.14.1 by Andrew Bennetts
Update to current hpss branch? Fix lots of test failures.
780
            raise errors.ReadOnlyError(self)
2018.5.75 by Andrew Bennetts
Add Repository.{dont_,}leave_lock_in_place.
781
        else:
782
            self._lock_count += 1
3015.2.9 by Robert Collins
Handle repositories that do not allow remote locking, like pack repositories, in the client side remote server proxy objects.
783
        return self._lock_token or None
2018.5.75 by Andrew Bennetts
Add Repository.{dont_,}leave_lock_in_place.
784
785
    def leave_lock_in_place(self):
3015.2.9 by Robert Collins
Handle repositories that do not allow remote locking, like pack repositories, in the client side remote server proxy objects.
786
        if not self._lock_token:
787
            raise NotImplementedError(self.leave_lock_in_place)
2018.5.78 by Andrew Bennetts
Implement RemoteRepository.lock_write/unlock to expect and send tokens over the
788
        self._leave_lock = True
2018.5.75 by Andrew Bennetts
Add Repository.{dont_,}leave_lock_in_place.
789
790
    def dont_leave_lock_in_place(self):
3015.2.9 by Robert Collins
Handle repositories that do not allow remote locking, like pack repositories, in the client side remote server proxy objects.
791
        if not self._lock_token:
3015.2.15 by Robert Collins
Review feedback.
792
            raise NotImplementedError(self.dont_leave_lock_in_place)
2018.5.78 by Andrew Bennetts
Implement RemoteRepository.lock_write/unlock to expect and send tokens over the
793
        self._leave_lock = False
2018.5.75 by Andrew Bennetts
Add Repository.{dont_,}leave_lock_in_place.
794
795
    def _set_real_repository(self, repository):
796
        """Set the _real_repository for this repository.
797
798
        :param repository: The repository to fallback to for non-hpss
799
            implemented operations.
800
        """
4053.1.5 by Robert Collins
Review feedback on RemoteRepository._set_real_revision.
801
        if self._real_repository is not None:
802
            # Replacing an already set real repository.
803
            # We cannot do this [currently] if the repository is locked -
804
            # synchronised state might be lost.
805
            if self.is_locked():
806
                raise AssertionError('_real_repository is already set')
3376.2.4 by Martin Pool
Remove every assert statement from bzrlib!
807
        if isinstance(repository, RemoteRepository):
808
            raise AssertionError()
2018.5.75 by Andrew Bennetts
Add Repository.{dont_,}leave_lock_in_place.
809
        self._real_repository = repository
3691.2.12 by Martin Pool
Add test for coping without Branch.get_stacked_on_url
810
        for fb in self._fallback_repositories:
811
            self._real_repository.add_fallback_repository(fb)
2018.5.75 by Andrew Bennetts
Add Repository.{dont_,}leave_lock_in_place.
812
        if self._lock_mode == 'w':
813
            # if we are already locked, the real repository must be able to
814
            # acquire the lock with our token.
815
            self._real_repository.lock_write(self._lock_token)
2018.14.1 by Andrew Bennetts
Update to current hpss branch? Fix lots of test failures.
816
        elif self._lock_mode == 'r':
817
            self._real_repository.lock_read()
2018.5.60 by Robert Collins
More missing methods from RemoteBranch and RemoteRepository to let 'info' get further.
818
2617.6.1 by Robert Collins
* New method on Repository - ``start_write_group``, ``end_write_group``
819
    def start_write_group(self):
820
        """Start a write group on the decorated repository.
3943.8.1 by Marius Kruger
remove all trailing whitespace from bzr source
821
2617.6.1 by Robert Collins
* New method on Repository - ``start_write_group``, ``end_write_group``
822
        Smart methods peform operations in a single step so this api
2617.6.6 by Robert Collins
Some review feedback.
823
        is not really applicable except as a compatibility thunk
2617.6.1 by Robert Collins
* New method on Repository - ``start_write_group``, ``end_write_group``
824
        for older plugins that don't use e.g. the CommitBuilder
825
        facility.
826
        """
827
        self._ensure_real()
828
        return self._real_repository.start_write_group()
829
2018.5.78 by Andrew Bennetts
Implement RemoteRepository.lock_write/unlock to expect and send tokens over the
830
    def _unlock(self, token):
831
        path = self.bzrdir._path_for_remote_call(self._client)
3015.2.9 by Robert Collins
Handle repositories that do not allow remote locking, like pack repositories, in the client side remote server proxy objects.
832
        if not token:
833
            # with no token the remote repository is not persistently locked.
834
            return
3786.2.3 by Andrew Bennetts
Remove duplicated 'call & translate errors' code in bzrlib.remote.
835
        err_context = {'token': token}
836
        response = self._call('Repository.unlock', path, token,
837
                              **err_context)
2018.5.78 by Andrew Bennetts
Implement RemoteRepository.lock_write/unlock to expect and send tokens over the
838
        if response == ('ok',):
839
            return
840
        else:
2555.1.1 by Martin Pool
Remove use of 'assert False' to raise an exception unconditionally
841
            raise errors.UnexpectedSmartServerResponse(response)
2018.5.78 by Andrew Bennetts
Implement RemoteRepository.lock_write/unlock to expect and send tokens over the
842
2018.5.60 by Robert Collins
More missing methods from RemoteBranch and RemoteRepository to let 'info' get further.
843
    def unlock(self):
4032.3.2 by Robert Collins
Create and use a RPC call to create branches on bzr servers rather than using VFS calls.
844
        if not self._lock_count:
845
            raise errors.LockNotHeld(self)
2018.5.75 by Andrew Bennetts
Add Repository.{dont_,}leave_lock_in_place.
846
        self._lock_count -= 1
2592.3.244 by Martin Pool
unlock while in a write group now aborts the write group, unlocks, and errors.
847
        if self._lock_count > 0:
848
            return
3835.1.8 by Aaron Bentley
Make UnstackedParentsProvider manage the cache
849
        self._unstacked_provider.disable_cache()
2592.3.244 by Martin Pool
unlock while in a write group now aborts the write group, unlocks, and errors.
850
        old_mode = self._lock_mode
851
        self._lock_mode = None
852
        try:
853
            # The real repository is responsible at present for raising an
854
            # exception if it's in an unfinished write group.  However, it
855
            # normally will *not* actually remove the lock from disk - that's
856
            # done by the server on receiving the Repository.unlock call.
857
            # This is just to let the _real_repository stay up to date.
2018.5.78 by Andrew Bennetts
Implement RemoteRepository.lock_write/unlock to expect and send tokens over the
858
            if self._real_repository is not None:
859
                self._real_repository.unlock()
2592.3.244 by Martin Pool
unlock while in a write group now aborts the write group, unlocks, and errors.
860
        finally:
861
            # The rpc-level lock should be released even if there was a
862
            # problem releasing the vfs-based lock.
863
            if old_mode == 'w':
2018.5.163 by Andrew Bennetts
Deal with various review comments from Robert.
864
                # Only write-locked repositories need to make a remote method
865
                # call to perfom the unlock.
2592.3.244 by Martin Pool
unlock while in a write group now aborts the write group, unlocks, and errors.
866
                old_token = self._lock_token
867
                self._lock_token = None
868
                if not self._leave_lock:
869
                    self._unlock(old_token)
2018.5.60 by Robert Collins
More missing methods from RemoteBranch and RemoteRepository to let 'info' get further.
870
871
    def break_lock(self):
2018.5.78 by Andrew Bennetts
Implement RemoteRepository.lock_write/unlock to expect and send tokens over the
872
        # should hand off to the network
2018.5.70 by Robert Collins
Only try to get real repositories when an operation requires them.
873
        self._ensure_real()
2018.5.60 by Robert Collins
More missing methods from RemoteBranch and RemoteRepository to let 'info' get further.
874
        return self._real_repository.break_lock()
875
2018.18.8 by Ian Clatworthy
Tarball proxy code & tests
876
    def _get_tarball(self, compression):
2814.10.2 by Andrew Bennetts
Make the fallback a little tidier.
877
        """Return a TemporaryFile containing a repository tarball.
3943.8.1 by Marius Kruger
remove all trailing whitespace from bzr source
878
2814.10.2 by Andrew Bennetts
Make the fallback a little tidier.
879
        Returns None if the server does not support sending tarballs.
880
        """
2018.18.25 by Martin Pool
Repository.tarball fixes for python2.4
881
        import tempfile
2018.18.8 by Ian Clatworthy
Tarball proxy code & tests
882
        path = self.bzrdir._path_for_remote_call(self._client)
3297.3.3 by Andrew Bennetts
SmartClientRequestProtocol*.read_response_tuple can now raise UnknownSmartMethod. Callers no longer need to do their own ad hoc unknown smart method error detection.
883
        try:
3786.2.3 by Andrew Bennetts
Remove duplicated 'call & translate errors' code in bzrlib.remote.
884
            response, protocol = self._call_expecting_body(
3297.3.3 by Andrew Bennetts
SmartClientRequestProtocol*.read_response_tuple can now raise UnknownSmartMethod. Callers no longer need to do their own ad hoc unknown smart method error detection.
885
                'Repository.tarball', path, compression)
886
        except errors.UnknownSmartMethod:
887
            protocol.cancel_read_body()
888
            return None
2018.18.8 by Ian Clatworthy
Tarball proxy code & tests
889
        if response[0] == 'ok':
890
            # Extract the tarball and return it
2018.18.25 by Martin Pool
Repository.tarball fixes for python2.4
891
            t = tempfile.NamedTemporaryFile()
892
            # TODO: rpc layer should read directly into it...
893
            t.write(protocol.read_body_bytes())
894
            t.seek(0)
895
            return t
2814.10.1 by Andrew Bennetts
Cope gracefully if the server doesn't support the Repository.tarball smart request.
896
        raise errors.UnexpectedSmartServerResponse(response)
2018.18.8 by Ian Clatworthy
Tarball proxy code & tests
897
2440.1.1 by Martin Pool
Add new Repository.sprout,
898
    def sprout(self, to_bzrdir, revision_id=None):
899
        # TODO: Option to control what format is created?
3047.1.1 by Andrew Bennetts
Fix for bug 164626, add test that Repository.sprout preserves format.
900
        self._ensure_real()
3047.1.4 by Andrew Bennetts
Simplify RemoteRepository.sprout thanks to review comments.
901
        dest_repo = self._real_repository._format.initialize(to_bzrdir,
902
                                                             shared=False)
2535.3.17 by Andrew Bennetts
[broken] Closer to a working Repository.fetch_revisions smart request.
903
        dest_repo.fetch(self, revision_id=revision_id)
904
        return dest_repo
2440.1.1 by Martin Pool
Add new Repository.sprout,
905
2018.14.1 by Andrew Bennetts
Update to current hpss branch? Fix lots of test failures.
906
    ### These methods are just thin shims to the VFS object for now.
907
908
    def revision_tree(self, revision_id):
909
        self._ensure_real()
910
        return self._real_repository.revision_tree(revision_id)
911
2520.4.113 by Aaron Bentley
Avoid peeking at Repository._serializer
912
    def get_serializer_format(self):
913
        self._ensure_real()
914
        return self._real_repository.get_serializer_format()
915
2018.14.1 by Andrew Bennetts
Update to current hpss branch? Fix lots of test failures.
916
    def get_commit_builder(self, branch, parents, config, timestamp=None,
917
                           timezone=None, committer=None, revprops=None,
918
                           revision_id=None):
919
        # FIXME: It ought to be possible to call this without immediately
920
        # triggering _ensure_real.  For now it's the easiest thing to do.
921
        self._ensure_real()
3692.1.3 by Andrew Bennetts
Delete some cruft (like the _ensure_real call in RemoteBranch.lock_write), improve some comments, and wrap some long lines.
922
        real_repo = self._real_repository
923
        builder = real_repo.get_commit_builder(branch, parents,
2018.14.1 by Andrew Bennetts
Update to current hpss branch? Fix lots of test failures.
924
                config, timestamp=timestamp, timezone=timezone,
925
                committer=committer, revprops=revprops, revision_id=revision_id)
926
        return builder
927
3221.12.1 by Robert Collins
Backport development1 format (stackable packs) to before-shallow-branches.
928
    def add_fallback_repository(self, repository):
929
        """Add a repository to use for looking up data not held locally.
3943.8.1 by Marius Kruger
remove all trailing whitespace from bzr source
930
3221.12.1 by Robert Collins
Backport development1 format (stackable packs) to before-shallow-branches.
931
        :param repository: A repository.
932
        """
3691.2.11 by Martin Pool
More tests around RemoteBranch stacking.
933
        # XXX: At the moment the RemoteRepository will allow fallbacks
934
        # unconditionally - however, a _real_repository will usually exist,
935
        # and may raise an error if it's not accommodated by the underlying
936
        # format.  Eventually we should check when opening the repository
937
        # whether it's willing to allow them or not.
938
        #
3221.12.1 by Robert Collins
Backport development1 format (stackable packs) to before-shallow-branches.
939
        # We need to accumulate additional repositories here, to pass them in
940
        # on various RPC's.
4035.2.3 by Robert Collins
Fix trailing whitespace.
941
        #
3221.12.1 by Robert Collins
Backport development1 format (stackable packs) to before-shallow-branches.
942
        self._fallback_repositories.append(repository)
4035.2.2 by Robert Collins
Minor tweaks to fix failing tests.
943
        # If self._real_repository was parameterised already (e.g. because a
944
        # _real_branch had its get_stacked_on_url method called), then the
945
        # repository to be added may already be in the _real_repositories list.
4035.2.1 by Andrew Bennetts
Fix unnecessary get_parent_map calls after insert_stream during push.
946
        if self._real_repository is not None:
4035.2.2 by Robert Collins
Minor tweaks to fix failing tests.
947
            if repository not in self._real_repository._fallback_repositories:
948
                self._real_repository.add_fallback_repository(repository)
4035.2.1 by Andrew Bennetts
Fix unnecessary get_parent_map calls after insert_stream during push.
949
        else:
950
            # They are also seen by the fallback repository.  If it doesn't
951
            # exist yet they'll be added then.  This implicitly copies them.
952
            self._ensure_real()
3221.12.1 by Robert Collins
Backport development1 format (stackable packs) to before-shallow-branches.
953
2018.14.1 by Andrew Bennetts
Update to current hpss branch? Fix lots of test failures.
954
    def add_inventory(self, revid, inv, parents):
955
        self._ensure_real()
956
        return self._real_repository.add_inventory(revid, inv, parents)
957
3879.2.2 by John Arbash Meinel
Rename add_inventory_delta to add_inventory_by_delta.
958
    def add_inventory_by_delta(self, basis_revision_id, delta, new_revision_id,
959
                               parents):
3775.2.1 by Robert Collins
Create bzrlib.repository.Repository.add_inventory_delta for adding inventories via deltas.
960
        self._ensure_real()
3879.2.2 by John Arbash Meinel
Rename add_inventory_delta to add_inventory_by_delta.
961
        return self._real_repository.add_inventory_by_delta(basis_revision_id,
3775.2.1 by Robert Collins
Create bzrlib.repository.Repository.add_inventory_delta for adding inventories via deltas.
962
            delta, new_revision_id, parents)
963
2018.14.1 by Andrew Bennetts
Update to current hpss branch? Fix lots of test failures.
964
    def add_revision(self, rev_id, rev, inv=None, config=None):
965
        self._ensure_real()
966
        return self._real_repository.add_revision(
967
            rev_id, rev, inv=inv, config=config)
968
969
    @needs_read_lock
970
    def get_inventory(self, revision_id):
971
        self._ensure_real()
972
        return self._real_repository.get_inventory(revision_id)
973
3169.2.1 by Robert Collins
New method ``iter_inventories`` on Repository for access to many
974
    def iter_inventories(self, revision_ids):
975
        self._ensure_real()
976
        return self._real_repository.iter_inventories(revision_ids)
977
2018.14.1 by Andrew Bennetts
Update to current hpss branch? Fix lots of test failures.
978
    @needs_read_lock
979
    def get_revision(self, revision_id):
980
        self._ensure_real()
981
        return self._real_repository.get_revision(revision_id)
982
983
    def get_transaction(self):
984
        self._ensure_real()
985
        return self._real_repository.get_transaction()
986
987
    @needs_read_lock
2018.5.138 by Robert Collins
Merge bzr.dev.
988
    def clone(self, a_bzrdir, revision_id=None):
2018.14.1 by Andrew Bennetts
Update to current hpss branch? Fix lots of test failures.
989
        self._ensure_real()
2018.5.138 by Robert Collins
Merge bzr.dev.
990
        return self._real_repository.clone(a_bzrdir, revision_id=revision_id)
2018.14.1 by Andrew Bennetts
Update to current hpss branch? Fix lots of test failures.
991
992
    def make_working_trees(self):
3349.1.1 by Aaron Bentley
Enable setting and getting make_working_trees for all repositories
993
        """See Repository.make_working_trees"""
994
        self._ensure_real()
995
        return self._real_repository.make_working_trees()
2018.14.1 by Andrew Bennetts
Update to current hpss branch? Fix lots of test failures.
996
3184.1.9 by Robert Collins
* ``Repository.get_data_stream`` is now deprecated in favour of
997
    def revision_ids_to_search_result(self, result_set):
998
        """Convert a set of revision ids to a graph SearchResult."""
999
        result_parents = set()
1000
        for parents in self.get_graph().get_parent_map(
1001
            result_set).itervalues():
1002
            result_parents.update(parents)
1003
        included_keys = result_set.intersection(result_parents)
1004
        start_keys = result_set.difference(included_keys)
1005
        exclude_keys = result_parents.difference(result_set)
1006
        result = graph.SearchResult(start_keys, exclude_keys,
1007
            len(result_set), result_set)
1008
        return result
1009
1010
    @needs_read_lock
1011
    def search_missing_revision_ids(self, other, revision_id=None, find_ghosts=True):
1012
        """Return the revision ids that other has that this does not.
3943.8.1 by Marius Kruger
remove all trailing whitespace from bzr source
1013
3184.1.9 by Robert Collins
* ``Repository.get_data_stream`` is now deprecated in favour of
1014
        These are returned in topological order.
1015
1016
        revision_id: only return revision ids included by revision_id.
1017
        """
1018
        return repository.InterRepository.get(
1019
            other, self).search_missing_revision_ids(revision_id, find_ghosts)
1020
3452.2.1 by Andrew Bennetts
An experimental InterRepo for remote packs.
1021
    def fetch(self, source, revision_id=None, pb=None, find_ghosts=False):
1022
        # Not delegated to _real_repository so that InterRepository.get has a
1023
        # chance to find an InterRepository specialised for RemoteRepository.
2881.4.1 by Robert Collins
Move responsibility for detecting same-repo fetching from the
1024
        if self.has_same_location(source):
1025
            # check that last_revision is in 'from' and then return a
1026
            # no-operation.
1027
            if (revision_id is not None and
2948.3.1 by John Arbash Meinel
Fix bug #158333, make sure that Repository.fetch(self) is properly a no-op for all Repository implementations.
1028
                not revision.is_null(revision_id)):
2881.4.1 by Robert Collins
Move responsibility for detecting same-repo fetching from the
1029
                self.get_revision(revision_id)
2592.4.5 by Martin Pool
Add Repository.base on all repositories.
1030
            return 0, []
3709.5.1 by Andrew Bennetts
Allow pushing to a pack repo over HPSS use the get_parent_map RPC, and teach the get_parent_map client to cache missing revisions.
1031
        inter = repository.InterRepository.get(source, self)
3452.2.1 by Andrew Bennetts
An experimental InterRepo for remote packs.
1032
        try:
1033
            return inter.fetch(revision_id=revision_id, pb=pb, find_ghosts=find_ghosts)
1034
        except NotImplementedError:
1035
            raise errors.IncompatibleRepositories(source, self)
2018.14.1 by Andrew Bennetts
Update to current hpss branch? Fix lots of test failures.
1036
2520.4.54 by Aaron Bentley
Hang a create_bundle method off repository
1037
    def create_bundle(self, target, base, fileobj, format=None):
1038
        self._ensure_real()
1039
        self._real_repository.create_bundle(target, base, fileobj, format)
1040
2018.14.1 by Andrew Bennetts
Update to current hpss branch? Fix lots of test failures.
1041
    @needs_read_lock
2530.1.1 by Aaron Bentley
Make topological sorting optional for get_ancestry
1042
    def get_ancestry(self, revision_id, topo_sorted=True):
2018.14.1 by Andrew Bennetts
Update to current hpss branch? Fix lots of test failures.
1043
        self._ensure_real()
2530.1.1 by Aaron Bentley
Make topological sorting optional for get_ancestry
1044
        return self._real_repository.get_ancestry(revision_id, topo_sorted)
2018.14.1 by Andrew Bennetts
Update to current hpss branch? Fix lots of test failures.
1045
1046
    def fileids_altered_by_revision_ids(self, revision_ids):
1047
        self._ensure_real()
1048
        return self._real_repository.fileids_altered_by_revision_ids(revision_ids)
1049
3036.1.3 by Robert Collins
Privatise VersionedFileChecker.
1050
    def _get_versioned_file_checker(self, revisions, revision_versions_cache):
2745.6.1 by Aaron Bentley
Initial checking of knit graphs
1051
        self._ensure_real()
3036.1.3 by Robert Collins
Privatise VersionedFileChecker.
1052
        return self._real_repository._get_versioned_file_checker(
2745.6.50 by Andrew Bennetts
Remove find_bad_ancestors; it's not needed anymore.
1053
            revisions, revision_versions_cache)
3943.8.1 by Marius Kruger
remove all trailing whitespace from bzr source
1054
2708.1.7 by Aaron Bentley
Rename extract_files_bytes to iter_files_bytes
1055
    def iter_files_bytes(self, desired_files):
2708.1.9 by Aaron Bentley
Clean-up docs and imports
1056
        """See Repository.iter_file_bytes.
2708.1.3 by Aaron Bentley
Implement extract_files_bytes on Repository
1057
        """
1058
        self._ensure_real()
2708.1.7 by Aaron Bentley
Rename extract_files_bytes to iter_files_bytes
1059
        return self._real_repository.iter_files_bytes(desired_files)
2708.1.3 by Aaron Bentley
Implement extract_files_bytes on Repository
1060
3835.1.1 by Aaron Bentley
Stack get_parent_map on fallback repos
1061
    def get_parent_map(self, revision_ids):
3835.1.6 by Aaron Bentley
Reduce inefficiency when doing make_parents_provider frequently
1062
        """See bzrlib.Graph.get_parent_map()."""
3835.1.5 by Aaron Bentley
Fix make_parents_provider
1063
        return self._make_parents_provider().get_parent_map(revision_ids)
3835.1.1 by Aaron Bentley
Stack get_parent_map on fallback repos
1064
1065
    def _get_parent_map_rpc(self, keys):
3172.5.6 by Robert Collins
Create new smart server verb Repository.get_parent_map.
1066
        """Helper for get_parent_map that performs the RPC."""
3313.2.1 by Andrew Bennetts
Change _SmartClient's API to accept a medium and a base, rather than a _SharedConnection.
1067
        medium = self._client._medium
3453.4.10 by Andrew Bennetts
Change _is_remote_at_least to _is_remote_before.
1068
        if medium._is_remote_before((1, 2)):
3213.1.1 by Andrew Bennetts
Recover (by reconnecting) if the server turns out not to understand the new requests in 1.2 that send bodies.
1069
            # We already found out that the server can't understand
3213.1.3 by Andrew Bennetts
Fix typo in comment.
1070
            # Repository.get_parent_map requests, so just fetch the whole
3213.1.1 by Andrew Bennetts
Recover (by reconnecting) if the server turns out not to understand the new requests in 1.2 that send bodies.
1071
            # graph.
3287.6.1 by Robert Collins
* ``VersionedFile.get_graph`` is deprecated, with no replacement method.
1072
            # XXX: Note that this will issue a deprecation warning. This is ok
1073
            # :- its because we're working with a deprecated server anyway, and
1074
            # the user will almost certainly have seen a warning about the
1075
            # server version already.
3389.1.1 by John Arbash Meinel
Fix bug #214894. Fix RemoteRepository.get_parent_map() when server is <v1.2
1076
            rg = self.get_revision_graph()
1077
            # There is an api discrepency between get_parent_map and
1078
            # get_revision_graph. Specifically, a "key:()" pair in
1079
            # get_revision_graph just means a node has no parents. For
1080
            # "get_parent_map" it means the node is a ghost. So fix up the
1081
            # graph to correct this.
1082
            #   https://bugs.launchpad.net/bzr/+bug/214894
1083
            # There is one other "bug" which is that ghosts in
1084
            # get_revision_graph() are not returned at all. But we won't worry
1085
            # about that for now.
1086
            for node_id, parent_ids in rg.iteritems():
1087
                if parent_ids == ():
1088
                    rg[node_id] = (NULL_REVISION,)
1089
            rg[NULL_REVISION] = ()
1090
            return rg
3213.1.1 by Andrew Bennetts
Recover (by reconnecting) if the server turns out not to understand the new requests in 1.2 that send bodies.
1091
3172.5.6 by Robert Collins
Create new smart server verb Repository.get_parent_map.
1092
        keys = set(keys)
3373.5.2 by John Arbash Meinel
Add repository_implementation tests for get_parent_map
1093
        if None in keys:
1094
            raise ValueError('get_parent_map(None) is not valid')
3172.5.6 by Robert Collins
Create new smart server verb Repository.get_parent_map.
1095
        if NULL_REVISION in keys:
1096
            keys.discard(NULL_REVISION)
1097
            found_parents = {NULL_REVISION:()}
1098
            if not keys:
1099
                return found_parents
1100
        else:
1101
            found_parents = {}
3211.5.1 by Robert Collins
Change the smart server get_parents method to take a graph search to exclude already recieved parents from. This prevents history shortcuts causing huge numbers of duplicates.
1102
        # TODO(Needs analysis): We could assume that the keys being requested
1103
        # from get_parent_map are in a breadth first search, so typically they
1104
        # will all be depth N from some common parent, and we don't have to
1105
        # have the server iterate from the root parent, but rather from the
1106
        # keys we're searching; and just tell the server the keyspace we
1107
        # already have; but this may be more traffic again.
1108
1109
        # Transform self._parents_map into a search request recipe.
1110
        # TODO: Manage this incrementally to avoid covering the same path
1111
        # repeatedly. (The server will have to on each request, but the less
1112
        # work done the better).
3835.1.8 by Aaron Bentley
Make UnstackedParentsProvider manage the cache
1113
        parents_map = self._unstacked_provider.get_cached_map()
3213.1.8 by Andrew Bennetts
Merge from bzr.dev.
1114
        if parents_map is None:
1115
            # Repository is not locked, so there's no cache.
1116
            parents_map = {}
1117
        start_set = set(parents_map)
3211.5.1 by Robert Collins
Change the smart server get_parents method to take a graph search to exclude already recieved parents from. This prevents history shortcuts causing huge numbers of duplicates.
1118
        result_parents = set()
3213.1.8 by Andrew Bennetts
Merge from bzr.dev.
1119
        for parents in parents_map.itervalues():
3211.5.1 by Robert Collins
Change the smart server get_parents method to take a graph search to exclude already recieved parents from. This prevents history shortcuts causing huge numbers of duplicates.
1120
            result_parents.update(parents)
1121
        stop_keys = result_parents.difference(start_set)
1122
        included_keys = start_set.intersection(result_parents)
1123
        start_set.difference_update(included_keys)
3213.1.8 by Andrew Bennetts
Merge from bzr.dev.
1124
        recipe = (start_set, stop_keys, len(parents_map))
3842.3.20 by Andrew Bennetts
Re-revert changes from another thread that accidentally got reinstated here.
1125
        body = self._serialise_search_recipe(recipe)
3172.5.6 by Robert Collins
Create new smart server verb Repository.get_parent_map.
1126
        path = self.bzrdir._path_for_remote_call(self._client)
1127
        for key in keys:
3360.2.8 by Martin Pool
Change assertion to a plain raise
1128
            if type(key) is not str:
1129
                raise ValueError(
1130
                    "key %r not a plain string" % (key,))
3172.5.8 by Robert Collins
Review feedback.
1131
        verb = 'Repository.get_parent_map'
3211.5.1 by Robert Collins
Change the smart server get_parents method to take a graph search to exclude already recieved parents from. This prevents history shortcuts causing huge numbers of duplicates.
1132
        args = (path,) + tuple(keys)
3297.3.3 by Andrew Bennetts
SmartClientRequestProtocol*.read_response_tuple can now raise UnknownSmartMethod. Callers no longer need to do their own ad hoc unknown smart method error detection.
1133
        try:
3786.2.3 by Andrew Bennetts
Remove duplicated 'call & translate errors' code in bzrlib.remote.
1134
            response = self._call_with_body_bytes_expecting_body(
3842.3.20 by Andrew Bennetts
Re-revert changes from another thread that accidentally got reinstated here.
1135
                verb, args, body)
3297.3.3 by Andrew Bennetts
SmartClientRequestProtocol*.read_response_tuple can now raise UnknownSmartMethod. Callers no longer need to do their own ad hoc unknown smart method error detection.
1136
        except errors.UnknownSmartMethod:
3213.1.2 by Andrew Bennetts
Add test for reconnection if get_parent_map is unknown by the server.
1137
            # Server does not support this method, so get the whole graph.
3213.1.1 by Andrew Bennetts
Recover (by reconnecting) if the server turns out not to understand the new requests in 1.2 that send bodies.
1138
            # Worse, we have to force a disconnection, because the server now
1139
            # doesn't realise it has a body on the wire to consume, so the
1140
            # only way to recover is to abandon the connection.
3213.1.6 by Andrew Bennetts
Emit warnings when forcing a reconnect.
1141
            warning(
1142
                'Server is too old for fast get_parent_map, reconnecting.  '
1143
                '(Upgrade the server to Bazaar 1.2 to avoid this)')
3213.1.1 by Andrew Bennetts
Recover (by reconnecting) if the server turns out not to understand the new requests in 1.2 that send bodies.
1144
            medium.disconnect()
1145
            # To avoid having to disconnect repeatedly, we keep track of the
1146
            # fact the server doesn't understand remote methods added in 1.2.
3453.4.9 by Andrew Bennetts
Rename _remote_is_not to _remember_remote_is_before.
1147
            medium._remember_remote_is_before((1, 2))
3297.3.4 by Andrew Bennetts
Merge from bzr.dev.
1148
            return self.get_revision_graph(None)
3245.4.58 by Andrew Bennetts
Unpack call_expecting_body's return value into variables, to avoid lots of ugly subscripting.
1149
        response_tuple, response_handler = response
1150
        if response_tuple[0] not in ['ok']:
1151
            response_handler.cancel_read_body()
1152
            raise errors.UnexpectedSmartServerResponse(response_tuple)
1153
        if response_tuple[0] == 'ok':
1154
            coded = bz2.decompress(response_handler.read_body_bytes())
3172.5.6 by Robert Collins
Create new smart server verb Repository.get_parent_map.
1155
            if coded == '':
1156
                # no revisions found
1157
                return {}
1158
            lines = coded.split('\n')
1159
            revision_graph = {}
1160
            for line in lines:
1161
                d = tuple(line.split())
1162
                if len(d) > 1:
1163
                    revision_graph[d[0]] = d[1:]
1164
                else:
1165
                    # No parents - so give the Graph result (NULL_REVISION,).
1166
                    revision_graph[d[0]] = (NULL_REVISION,)
1167
            return revision_graph
1168
2018.14.1 by Andrew Bennetts
Update to current hpss branch? Fix lots of test failures.
1169
    @needs_read_lock
1170
    def get_signature_text(self, revision_id):
1171
        self._ensure_real()
1172
        return self._real_repository.get_signature_text(revision_id)
1173
1174
    @needs_read_lock
3228.4.11 by John Arbash Meinel
Deprecations abound.
1175
    @symbol_versioning.deprecated_method(symbol_versioning.one_three)
2018.14.1 by Andrew Bennetts
Update to current hpss branch? Fix lots of test failures.
1176
    def get_revision_graph_with_ghosts(self, revision_ids=None):
1177
        self._ensure_real()
1178
        return self._real_repository.get_revision_graph_with_ghosts(
1179
            revision_ids=revision_ids)
1180
1181
    @needs_read_lock
1182
    def get_inventory_xml(self, revision_id):
1183
        self._ensure_real()
1184
        return self._real_repository.get_inventory_xml(revision_id)
1185
1186
    def deserialise_inventory(self, revision_id, xml):
1187
        self._ensure_real()
1188
        return self._real_repository.deserialise_inventory(revision_id, xml)
1189
1190
    def reconcile(self, other=None, thorough=False):
1191
        self._ensure_real()
1192
        return self._real_repository.reconcile(other=other, thorough=thorough)
3943.8.1 by Marius Kruger
remove all trailing whitespace from bzr source
1193
2018.14.1 by Andrew Bennetts
Update to current hpss branch? Fix lots of test failures.
1194
    def all_revision_ids(self):
1195
        self._ensure_real()
1196
        return self._real_repository.all_revision_ids()
3943.8.1 by Marius Kruger
remove all trailing whitespace from bzr source
1197
2018.14.1 by Andrew Bennetts
Update to current hpss branch? Fix lots of test failures.
1198
    @needs_read_lock
1199
    def get_deltas_for_revisions(self, revisions):
1200
        self._ensure_real()
1201
        return self._real_repository.get_deltas_for_revisions(revisions)
1202
1203
    @needs_read_lock
1204
    def get_revision_delta(self, revision_id):
1205
        self._ensure_real()
1206
        return self._real_repository.get_revision_delta(revision_id)
1207
1208
    @needs_read_lock
1209
    def revision_trees(self, revision_ids):
1210
        self._ensure_real()
1211
        return self._real_repository.revision_trees(revision_ids)
1212
1213
    @needs_read_lock
1214
    def get_revision_reconcile(self, revision_id):
1215
        self._ensure_real()
1216
        return self._real_repository.get_revision_reconcile(revision_id)
1217
1218
    @needs_read_lock
2745.6.36 by Andrew Bennetts
Deprecate revision_ids arg to Repository.check and other tweaks.
1219
    def check(self, revision_ids=None):
2018.14.1 by Andrew Bennetts
Update to current hpss branch? Fix lots of test failures.
1220
        self._ensure_real()
2745.6.36 by Andrew Bennetts
Deprecate revision_ids arg to Repository.check and other tweaks.
1221
        return self._real_repository.check(revision_ids=revision_ids)
2018.14.1 by Andrew Bennetts
Update to current hpss branch? Fix lots of test failures.
1222
2018.5.138 by Robert Collins
Merge bzr.dev.
1223
    def copy_content_into(self, destination, revision_id=None):
2018.14.1 by Andrew Bennetts
Update to current hpss branch? Fix lots of test failures.
1224
        self._ensure_real()
1225
        return self._real_repository.copy_content_into(
2018.5.138 by Robert Collins
Merge bzr.dev.
1226
            destination, revision_id=revision_id)
2018.14.1 by Andrew Bennetts
Update to current hpss branch? Fix lots of test failures.
1227
2814.10.2 by Andrew Bennetts
Make the fallback a little tidier.
1228
    def _copy_repository_tarball(self, to_bzrdir, revision_id=None):
2018.18.10 by Martin Pool
copy_content_into from Remote repositories by using temporary directories on both ends.
1229
        # get a tarball of the remote repository, and copy from that into the
1230
        # destination
1231
        from bzrlib import osutils
2018.18.9 by Martin Pool
remote Repository.tarball builds a temporary directory and tars that
1232
        import tarfile
2018.18.20 by Martin Pool
Route branch operations through remote copy_content_into
1233
        # TODO: Maybe a progress bar while streaming the tarball?
1234
        note("Copying repository content as tarball...")
2018.18.25 by Martin Pool
Repository.tarball fixes for python2.4
1235
        tar_file = self._get_tarball('bz2')
2814.10.2 by Andrew Bennetts
Make the fallback a little tidier.
1236
        if tar_file is None:
1237
            return None
1238
        destination = to_bzrdir.create_repository()
2018.18.10 by Martin Pool
copy_content_into from Remote repositories by using temporary directories on both ends.
1239
        try:
2018.18.25 by Martin Pool
Repository.tarball fixes for python2.4
1240
            tar = tarfile.open('repository', fileobj=tar_file,
1241
                mode='r|bz2')
3638.3.2 by Vincent Ladeuil
Fix all calls to tempfile.mkdtemp to osutils.mkdtemp.
1242
            tmpdir = osutils.mkdtemp()
2018.18.25 by Martin Pool
Repository.tarball fixes for python2.4
1243
            try:
1244
                _extract_tar(tar, tmpdir)
1245
                tmp_bzrdir = BzrDir.open(tmpdir)
1246
                tmp_repo = tmp_bzrdir.open_repository()
1247
                tmp_repo.copy_content_into(destination, revision_id)
1248
            finally:
1249
                osutils.rmtree(tmpdir)
2018.18.10 by Martin Pool
copy_content_into from Remote repositories by using temporary directories on both ends.
1250
        finally:
2018.18.25 by Martin Pool
Repository.tarball fixes for python2.4
1251
            tar_file.close()
2814.10.2 by Andrew Bennetts
Make the fallback a little tidier.
1252
        return destination
2018.18.23 by Martin Pool
review cleanups
1253
        # TODO: Suggestion from john: using external tar is much faster than
1254
        # python's tarfile library, but it may not work on windows.
2018.14.1 by Andrew Bennetts
Update to current hpss branch? Fix lots of test failures.
1255
3842.3.20 by Andrew Bennetts
Re-revert changes from another thread that accidentally got reinstated here.
1256
    @property
1257
    def inventories(self):
1258
        """Decorate the real repository for now.
1259
1260
        In the long term a full blown network facility is needed to
1261
        avoid creating a real repository object locally.
1262
        """
1263
        self._ensure_real()
1264
        return self._real_repository.inventories
1265
2604.2.1 by Robert Collins
(robertc) Introduce a pack command.
1266
    @needs_write_lock
1267
    def pack(self):
1268
        """Compress the data within the repository.
1269
1270
        This is not currently implemented within the smart server.
1271
        """
1272
        self._ensure_real()
1273
        return self._real_repository.pack()
1274
3842.3.20 by Andrew Bennetts
Re-revert changes from another thread that accidentally got reinstated here.
1275
    @property
1276
    def revisions(self):
1277
        """Decorate the real repository for now.
1278
1279
        In the short term this should become a real object to intercept graph
1280
        lookups.
1281
1282
        In the long term a full blown network facility is needed.
1283
        """
1284
        self._ensure_real()
1285
        return self._real_repository.revisions
1286
2018.14.1 by Andrew Bennetts
Update to current hpss branch? Fix lots of test failures.
1287
    def set_make_working_trees(self, new_value):
4017.3.4 by Robert Collins
Create a verb for Repository.set_make_working_trees.
1288
        if new_value:
1289
            new_value_str = "True"
1290
        else:
1291
            new_value_str = "False"
1292
        path = self.bzrdir._path_for_remote_call(self._client)
1293
        try:
1294
            response = self._call(
1295
                'Repository.set_make_working_trees', path, new_value_str)
1296
        except errors.UnknownSmartMethod:
1297
            self._ensure_real()
1298
            self._real_repository.set_make_working_trees(new_value)
1299
        else:
1300
            if response[0] != 'ok':
1301
                raise errors.UnexpectedSmartServerResponse(response)
2018.14.1 by Andrew Bennetts
Update to current hpss branch? Fix lots of test failures.
1302
3842.3.20 by Andrew Bennetts
Re-revert changes from another thread that accidentally got reinstated here.
1303
    @property
1304
    def signatures(self):
1305
        """Decorate the real repository for now.
1306
1307
        In the long term a full blown network facility is needed to avoid
1308
        creating a real repository object locally.
1309
        """
1310
        self._ensure_real()
1311
        return self._real_repository.signatures
1312
2018.14.1 by Andrew Bennetts
Update to current hpss branch? Fix lots of test failures.
1313
    @needs_write_lock
1314
    def sign_revision(self, revision_id, gpg_strategy):
1315
        self._ensure_real()
1316
        return self._real_repository.sign_revision(revision_id, gpg_strategy)
1317
3842.3.20 by Andrew Bennetts
Re-revert changes from another thread that accidentally got reinstated here.
1318
    @property
1319
    def texts(self):
1320
        """Decorate the real repository for now.
1321
1322
        In the long term a full blown network facility is needed to avoid
1323
        creating a real repository object locally.
1324
        """
1325
        self._ensure_real()
1326
        return self._real_repository.texts
1327
2018.14.1 by Andrew Bennetts
Update to current hpss branch? Fix lots of test failures.
1328
    @needs_read_lock
1329
    def get_revisions(self, revision_ids):
1330
        self._ensure_real()
1331
        return self._real_repository.get_revisions(revision_ids)
1332
1333
    def supports_rich_root(self):
4053.1.4 by Robert Collins
Move the fetch control attributes from Repository to RepositoryFormat.
1334
        return self._format.rich_root_data
2018.14.1 by Andrew Bennetts
Update to current hpss branch? Fix lots of test failures.
1335
2018.5.83 by Andrew Bennetts
Fix some test failures caused by the switch from unicode to UTF-8-encoded strs for revision IDs.
1336
    def iter_reverse_revision_history(self, revision_id):
1337
        self._ensure_real()
1338
        return self._real_repository.iter_reverse_revision_history(revision_id)
1339
2018.5.96 by Andrew Bennetts
Merge from bzr.dev, resolving the worst of the semantic conflicts, but there's
1340
    @property
1341
    def _serializer(self):
4053.1.4 by Robert Collins
Move the fetch control attributes from Repository to RepositoryFormat.
1342
        return self._format._serializer
2018.5.96 by Andrew Bennetts
Merge from bzr.dev, resolving the worst of the semantic conflicts, but there's
1343
2018.5.97 by Andrew Bennetts
Fix more tests.
1344
    def store_revision_signature(self, gpg_strategy, plaintext, revision_id):
1345
        self._ensure_real()
1346
        return self._real_repository.store_revision_signature(
1347
            gpg_strategy, plaintext, revision_id)
1348
2996.2.8 by Aaron Bentley
Fix add_signature discrepancies
1349
    def add_signature_text(self, revision_id, signature):
2996.2.3 by Aaron Bentley
Add tests for install_revisions and add_signature
1350
        self._ensure_real()
2996.2.8 by Aaron Bentley
Fix add_signature discrepancies
1351
        return self._real_repository.add_signature_text(revision_id, signature)
2996.2.3 by Aaron Bentley
Add tests for install_revisions and add_signature
1352
2018.5.97 by Andrew Bennetts
Fix more tests.
1353
    def has_signature_for_revision_id(self, revision_id):
1354
        self._ensure_real()
1355
        return self._real_repository.has_signature_for_revision_id(revision_id)
1356
2535.3.45 by Andrew Bennetts
Add item_keys_introduced_by to RemoteRepository.
1357
    def item_keys_introduced_by(self, revision_ids, _files_pb=None):
1358
        self._ensure_real()
1359
        return self._real_repository.item_keys_introduced_by(revision_ids,
1360
            _files_pb=_files_pb)
1361
2819.2.4 by Andrew Bennetts
Add a 'revision_graph_can_have_wrong_parents' method to repository.
1362
    def revision_graph_can_have_wrong_parents(self):
1363
        # The answer depends on the remote repo format.
1364
        self._ensure_real()
1365
        return self._real_repository.revision_graph_can_have_wrong_parents()
1366
2819.2.5 by Andrew Bennetts
Make reconcile abort gracefully if the revision index has bad parents.
1367
    def _find_inconsistent_revision_parents(self):
1368
        self._ensure_real()
1369
        return self._real_repository._find_inconsistent_revision_parents()
1370
1371
    def _check_for_inconsistent_revision_parents(self):
1372
        self._ensure_real()
1373
        return self._real_repository._check_for_inconsistent_revision_parents()
1374
3835.1.17 by Aaron Bentley
Fix stacking bug
1375
    def _make_parents_provider(self, other=None):
3835.1.8 by Aaron Bentley
Make UnstackedParentsProvider manage the cache
1376
        providers = [self._unstacked_provider]
3835.1.17 by Aaron Bentley
Fix stacking bug
1377
        if other is not None:
1378
            providers.insert(0, other)
3835.1.7 by Aaron Bentley
Updates from review
1379
        providers.extend(r._make_parents_provider() for r in
1380
                         self._fallback_repositories)
1381
        return graph._StackedParentsProvider(providers)
3172.5.1 by Robert Collins
Create a RemoteRepository get_graph implementation and delegate get_parents_map to the real repository.
1382
3842.3.20 by Andrew Bennetts
Re-revert changes from another thread that accidentally got reinstated here.
1383
    def _serialise_search_recipe(self, recipe):
1384
        """Serialise a graph search recipe.
1385
1386
        :param recipe: A search recipe (start, stop, count).
1387
        :return: Serialised bytes.
1388
        """
1389
        start_keys = ' '.join(recipe[0])
1390
        stop_keys = ' '.join(recipe[1])
1391
        count = str(recipe[2])
1392
        return '\n'.join((start_keys, stop_keys, count))
1393
3842.3.2 by Andrew Bennetts
Revert the RemoteVersionedFiles.get_parent_map implementation, leaving just the skeleton of RemoteVersionedFiles.
1394
    def autopack(self):
1395
        path = self.bzrdir._path_for_remote_call(self._client)
1396
        try:
1397
            response = self._call('PackRepository.autopack', path)
1398
        except errors.UnknownSmartMethod:
1399
            self._ensure_real()
1400
            self._real_repository._pack_collection.autopack()
1401
            return
1402
        if self._real_repository is not None:
1403
            # Reset the real repository's cache of pack names.
1404
            # XXX: At some point we may be able to skip this and just rely on
1405
            # the automatic retry logic to do the right thing, but for now we
1406
            # err on the side of being correct rather than being optimal.
1407
            self._real_repository._pack_collection.reload_pack_names()
1408
        if response[0] != 'ok':
1409
            raise errors.UnexpectedSmartServerResponse(response)
1410
1411
4022.1.6 by Robert Collins
Cherrypick and polish the RemoteSink for streaming push.
1412
class RemoteStreamSink(repository.StreamSink):
1413
4032.3.7 by Robert Collins
Move write locking and write group responsibilities into the Sink objects themselves, allowing complete avoidance of unnecessary calls when the sink is a RemoteSink.
1414
    def _insert_real(self, stream, src_format, resume_tokens):
4022.1.6 by Robert Collins
Cherrypick and polish the RemoteSink for streaming push.
1415
        self.target_repo._ensure_real()
1416
        sink = self.target_repo._real_repository._get_sink()
4032.3.7 by Robert Collins
Move write locking and write group responsibilities into the Sink objects themselves, allowing complete avoidance of unnecessary calls when the sink is a RemoteSink.
1417
        result = sink.insert_stream(stream, src_format, resume_tokens)
4029.2.1 by Robert Collins
Support streaming push to stacked branches.
1418
        if not result:
1419
            self.target_repo.autopack()
1420
        return result
4022.1.6 by Robert Collins
Cherrypick and polish the RemoteSink for streaming push.
1421
4032.3.7 by Robert Collins
Move write locking and write group responsibilities into the Sink objects themselves, allowing complete avoidance of unnecessary calls when the sink is a RemoteSink.
1422
    def insert_stream(self, stream, src_format, resume_tokens):
4022.1.6 by Robert Collins
Cherrypick and polish the RemoteSink for streaming push.
1423
        repo = self.target_repo
1424
        client = repo._client
4022.1.9 by Robert Collins
Fix critical issue in bzr.dev - pushing to an old bzr:// server fails because the stream being consumed before the fallback code occurs, which makes it fail to do the fetch. (Robert Collins, Andrew Bennetts, #332314)
1425
        medium = client._medium
4029.2.1 by Robert Collins
Support streaming push to stacked branches.
1426
        if medium._is_remote_before((1, 13)):
4022.1.9 by Robert Collins
Fix critical issue in bzr.dev - pushing to an old bzr:// server fails because the stream being consumed before the fallback code occurs, which makes it fail to do the fetch. (Robert Collins, Andrew Bennetts, #332314)
1427
            # No possible way this can work.
4032.3.7 by Robert Collins
Move write locking and write group responsibilities into the Sink objects themselves, allowing complete avoidance of unnecessary calls when the sink is a RemoteSink.
1428
            return self._insert_real(stream, src_format, resume_tokens)
4022.1.6 by Robert Collins
Cherrypick and polish the RemoteSink for streaming push.
1429
        path = repo.bzrdir._path_for_remote_call(client)
4032.3.7 by Robert Collins
Move write locking and write group responsibilities into the Sink objects themselves, allowing complete avoidance of unnecessary calls when the sink is a RemoteSink.
1430
        if not resume_tokens:
4029.2.1 by Robert Collins
Support streaming push to stacked branches.
1431
            # XXX: Ugly but important for correctness, *will* be fixed during
1432
            # 1.13 cycle. Pushing a stream that is interrupted results in a
1433
            # fallback to the _real_repositories sink *with a partial stream*.
1434
            # Thats bad because we insert less data than bzr expected. To avoid
1435
            # this we do a trial push to make sure the verb is accessible, and
1436
            # do not fallback when actually pushing the stream. A cleanup patch
1437
            # is going to look at rewinding/restarting the stream/partial
1438
            # buffering etc.
4060.1.4 by Robert Collins
Streaming fetch from remote servers.
1439
            byte_stream = smart_repo._stream_to_byte_stream([], src_format)
4029.2.1 by Robert Collins
Support streaming push to stacked branches.
1440
            try:
1441
                response = client.call_with_body_stream(
4032.3.7 by Robert Collins
Move write locking and write group responsibilities into the Sink objects themselves, allowing complete avoidance of unnecessary calls when the sink is a RemoteSink.
1442
                    ('Repository.insert_stream', path, ''), byte_stream)
4029.2.1 by Robert Collins
Support streaming push to stacked branches.
1443
            except errors.UnknownSmartMethod:
1444
                medium._remember_remote_is_before((1,13))
4032.3.7 by Robert Collins
Move write locking and write group responsibilities into the Sink objects themselves, allowing complete avoidance of unnecessary calls when the sink is a RemoteSink.
1445
                return self._insert_real(stream, src_format, resume_tokens)
4060.1.4 by Robert Collins
Streaming fetch from remote servers.
1446
        byte_stream = smart_repo._stream_to_byte_stream(
1447
            stream, src_format)
4032.3.7 by Robert Collins
Move write locking and write group responsibilities into the Sink objects themselves, allowing complete avoidance of unnecessary calls when the sink is a RemoteSink.
1448
        resume_tokens = ' '.join(resume_tokens)
4022.1.9 by Robert Collins
Fix critical issue in bzr.dev - pushing to an old bzr:// server fails because the stream being consumed before the fallback code occurs, which makes it fail to do the fetch. (Robert Collins, Andrew Bennetts, #332314)
1449
        response = client.call_with_body_stream(
4029.2.1 by Robert Collins
Support streaming push to stacked branches.
1450
            ('Repository.insert_stream', path, resume_tokens), byte_stream)
1451
        if response[0][0] not in ('ok', 'missing-basis'):
4022.1.9 by Robert Collins
Fix critical issue in bzr.dev - pushing to an old bzr:// server fails because the stream being consumed before the fallback code occurs, which makes it fail to do the fetch. (Robert Collins, Andrew Bennetts, #332314)
1452
            raise errors.UnexpectedSmartServerResponse(response)
4029.2.1 by Robert Collins
Support streaming push to stacked branches.
1453
        if response[0][0] == 'missing-basis':
1454
            tokens, missing_keys = bencode.bdecode_as_tuple(response[0][1])
4032.3.7 by Robert Collins
Move write locking and write group responsibilities into the Sink objects themselves, allowing complete avoidance of unnecessary calls when the sink is a RemoteSink.
1455
            resume_tokens = tokens
1456
            return resume_tokens, missing_keys
4029.2.1 by Robert Collins
Support streaming push to stacked branches.
1457
        else:
1458
            if self.target_repo._real_repository is not None:
1459
                collection = getattr(self.target_repo._real_repository,
1460
                    '_pack_collection', None)
1461
                if collection is not None:
1462
                    collection.reload_pack_names()
4032.3.7 by Robert Collins
Move write locking and write group responsibilities into the Sink objects themselves, allowing complete avoidance of unnecessary calls when the sink is a RemoteSink.
1463
            return [], set()
4032.1.1 by John Arbash Meinel
Merge the removal of all trailing whitespace, and resolve conflicts.
1464
4022.1.1 by Robert Collins
Refactoring of fetch to have a sender and sink component enabling splitting the logic over a network stream. (Robert Collins, Andrew Bennetts)
1465
4060.1.3 by Robert Collins
Implement the separate source component for fetch - repository.StreamSource.
1466
class RemoteStreamSource(repository.StreamSource):
1467
    """Stream data from a remote server."""
1468
4060.1.4 by Robert Collins
Streaming fetch from remote servers.
1469
    def get_stream(self, search):
1470
        # streaming with fallback repositories is not well defined yet: The
1471
        # remote repository cannot see the fallback repositories, and thus
1472
        # cannot satisfy the entire search in the general case. Likewise the
1473
        # fallback repositories cannot reify the search to determine what they
1474
        # should send. It likely needs a return value in the stream listing the
1475
        # edge of the search to resume from in fallback repositories.
1476
        if self.from_repository._fallback_repositories:
1477
            return repository.StreamSource.get_stream(self, search)
1478
        repo = self.from_repository
1479
        client = repo._client
1480
        medium = client._medium
1481
        if medium._is_remote_before((1, 13)):
1482
            # No possible way this can work.
1483
            return repository.StreamSource.get_stream(self, search)
1484
        path = repo.bzrdir._path_for_remote_call(client)
1485
        try:
1486
            recipe = repo._serialise_search_recipe(search._recipe)
1487
            response = repo._call_with_body_bytes_expecting_body(
4060.1.5 by Robert Collins
Verb change name requested by Andrew.
1488
                'Repository.get_stream',
4060.1.4 by Robert Collins
Streaming fetch from remote servers.
1489
                (path, self.to_format.network_name()), recipe)
1490
            response_tuple, response_handler = response
1491
        except errors.UnknownSmartMethod:
1492
            medium._remember_remote_is_before((1,13))
1493
            return repository.StreamSource.get_stream(self, search)
1494
        if response_tuple[0] != 'ok':
1495
            raise errors.UnexpectedSmartServerResponse(response_tuple)
1496
        byte_stream = response_handler.read_streamed_body()
1497
        src_format, stream = smart_repo._byte_stream_to_stream(byte_stream)
1498
        if src_format.network_name() != repo._format.network_name():
1499
            raise AssertionError(
1500
                "Mismatched RemoteRepository and stream src %r, %r" % (
1501
                src_format.network_name(), repo._format.network_name()))
1502
        return stream
1503
4060.1.3 by Robert Collins
Implement the separate source component for fetch - repository.StreamSource.
1504
2018.5.127 by Andrew Bennetts
Fix most of the lockable_files tests for RemoteBranchLockableFiles.
1505
class RemoteBranchLockableFiles(LockableFiles):
2018.5.59 by Robert Collins
Get BranchConfig working somewhat on RemoteBranches (Robert Collins, Vincent Ladeuil).
1506
    """A 'LockableFiles' implementation that talks to a smart server.
3943.8.1 by Marius Kruger
remove all trailing whitespace from bzr source
1507
2018.5.59 by Robert Collins
Get BranchConfig working somewhat on RemoteBranches (Robert Collins, Vincent Ladeuil).
1508
    This is not a public interface class.
1509
    """
1510
1511
    def __init__(self, bzrdir, _client):
1512
        self.bzrdir = bzrdir
1513
        self._client = _client
2018.5.135 by Andrew Bennetts
Prevent remote branch clients from determining the 'right' mode for control files, because we don't want clients setting the mode anyway.
1514
        self._need_find_modes = True
2018.5.133 by Andrew Bennetts
All TestLockableFiles_RemoteLockDir tests passing.
1515
        LockableFiles.__init__(
2018.5.163 by Andrew Bennetts
Deal with various review comments from Robert.
1516
            self, bzrdir.get_branch_transport(None),
2018.5.133 by Andrew Bennetts
All TestLockableFiles_RemoteLockDir tests passing.
1517
            'lock', lockdir.LockDir)
2018.5.59 by Robert Collins
Get BranchConfig working somewhat on RemoteBranches (Robert Collins, Vincent Ladeuil).
1518
2018.5.135 by Andrew Bennetts
Prevent remote branch clients from determining the 'right' mode for control files, because we don't want clients setting the mode anyway.
1519
    def _find_modes(self):
1520
        # RemoteBranches don't let the client set the mode of control files.
1521
        self._dir_mode = None
1522
        self._file_mode = None
1523
2018.5.59 by Robert Collins
Get BranchConfig working somewhat on RemoteBranches (Robert Collins, Vincent Ladeuil).
1524
1752.2.31 by Martin Pool
[broken] some support for write operations over hpss
1525
class RemoteBranchFormat(branch.BranchFormat):
1526
3834.5.2 by John Arbash Meinel
Track down the various BranchFormats that weren't setting the branch format as part of the _matchingbzrdir format.
1527
    def __init__(self):
1528
        super(RemoteBranchFormat, self).__init__()
1529
        self._matchingbzrdir = RemoteBzrDirFormat()
1530
        self._matchingbzrdir.set_branch_format(self)
4032.3.2 by Robert Collins
Create and use a RPC call to create branches on bzr servers rather than using VFS calls.
1531
        self._custom_format = None
3834.5.2 by John Arbash Meinel
Track down the various BranchFormats that weren't setting the branch format as part of the _matchingbzrdir format.
1532
2018.5.124 by Robert Collins
Fix test_format_initialize_find_open by delegating Branch formt lookup to the BzrDir, where it should have stayed from the start.
1533
    def __eq__(self, other):
3943.8.1 by Marius Kruger
remove all trailing whitespace from bzr source
1534
        return (isinstance(other, RemoteBranchFormat) and
2018.5.124 by Robert Collins
Fix test_format_initialize_find_open by delegating Branch formt lookup to the BzrDir, where it should have stayed from the start.
1535
            self.__dict__ == other.__dict__)
1536
2018.5.60 by Robert Collins
More missing methods from RemoteBranch and RemoteRepository to let 'info' get further.
1537
    def get_format_description(self):
1538
        return 'Remote BZR Branch'
1539
4032.3.1 by Robert Collins
Add a BranchFormat.network_name() method as preparation for creating branches via RPC calls.
1540
    def network_name(self):
1541
        return self._network_name
1542
1752.2.31 by Martin Pool
[broken] some support for write operations over hpss
1543
    def open(self, a_bzrdir):
1752.2.72 by Andrew Bennetts
Make Remote* classes in remote.py more consistent and remove some dead code.
1544
        return a_bzrdir.open_branch()
1752.2.52 by Andrew Bennetts
Flesh out more Remote* methods needed to open and initialise remote branches/trees/repositories.
1545
4032.3.2 by Robert Collins
Create and use a RPC call to create branches on bzr servers rather than using VFS calls.
1546
    def _vfs_initialize(self, a_bzrdir):
1547
        # Initialisation when using a local bzrdir object, or a non-vfs init
1548
        # method is not available on the server.
1549
        # self._custom_format is always set - the start of initialize ensures
1550
        # that.
1551
        if isinstance(a_bzrdir, RemoteBzrDir):
1552
            a_bzrdir._ensure_real()
1553
            result = self._custom_format.initialize(a_bzrdir._real_bzrdir)
1554
        else:
1555
            # We assume the bzrdir is parameterised; it may not be.
1556
            result = self._custom_format.initialize(a_bzrdir)
1557
        if (isinstance(a_bzrdir, RemoteBzrDir) and
1558
            not isinstance(result, RemoteBranch)):
1559
            result = RemoteBranch(a_bzrdir, a_bzrdir.find_repository(), result)
1560
        return result
1561
1752.2.52 by Andrew Bennetts
Flesh out more Remote* methods needed to open and initialise remote branches/trees/repositories.
1562
    def initialize(self, a_bzrdir):
4032.3.2 by Robert Collins
Create and use a RPC call to create branches on bzr servers rather than using VFS calls.
1563
        # 1) get the network name to use.
1564
        if self._custom_format:
1565
            network_name = self._custom_format.network_name()
1566
        else:
1567
            # Select the current bzrlib default and ask for that.
1568
            reference_bzrdir_format = bzrdir.format_registry.get('default')()
1569
            reference_format = reference_bzrdir_format.get_branch_format()
1570
            self._custom_format = reference_format
1571
            network_name = reference_format.network_name()
1572
        # Being asked to create on a non RemoteBzrDir:
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.
1573
        if not isinstance(a_bzrdir, RemoteBzrDir):
4032.3.2 by Robert Collins
Create and use a RPC call to create branches on bzr servers rather than using VFS calls.
1574
            return self._vfs_initialize(a_bzrdir)
1575
        medium = a_bzrdir._client._medium
1576
        if medium._is_remote_before((1, 13)):
1577
            return self._vfs_initialize(a_bzrdir)
1578
        # Creating on a remote bzr dir.
1579
        # 2) try direct creation via RPC
1580
        path = a_bzrdir._path_for_remote_call(a_bzrdir._client)
1581
        verb = 'BzrDir.create_branch'
1582
        try:
1583
            response = a_bzrdir._call(verb, path, network_name)
1584
        except errors.UnknownSmartMethod:
1585
            # Fallback - use vfs methods
1586
            return self._vfs_initialize(a_bzrdir)
1587
        if response[0] != 'ok':
1588
            raise errors.UnexpectedSmartServerResponse(response)
1589
        # Turn the response into a RemoteRepository object.
1590
        format = RemoteBranchFormat()
1591
        format._network_name = response[1]
1592
        repo_format = response_tuple_to_repo_format(response[3:])
1593
        if response[2] == '':
1594
            repo_bzrdir = a_bzrdir
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.
1595
        else:
4032.3.2 by Robert Collins
Create and use a RPC call to create branches on bzr servers rather than using VFS calls.
1596
            repo_bzrdir = RemoteBzrDir(
1597
                a_bzrdir.root_transport.clone(response[2]), a_bzrdir._format,
1598
                a_bzrdir._client)
1599
        remote_repo = RemoteRepository(repo_bzrdir, repo_format)
1600
        remote_branch = RemoteBranch(a_bzrdir, remote_repo,
1601
            format=format, setup_stacking=False)
4044.1.4 by Robert Collins
Remove a wasted round trip determining the revno and revid of a newly created branch.
1602
        # XXX: We know this is a new branch, so it must have revno 0, revid
1603
        # NULL_REVISION. Creating the branch locked would make this be unable
1604
        # to be wrong; here its simply very unlikely to be wrong. RBC 20090225
1605
        remote_branch._last_revision_info_cache = 0, NULL_REVISION
4032.3.2 by Robert Collins
Create and use a RPC call to create branches on bzr servers rather than using VFS calls.
1606
        return remote_branch
1752.2.31 by Martin Pool
[broken] some support for write operations over hpss
1607
2696.3.6 by Martin Pool
Mark RemoteBranch as (possibly) supporting tags
1608
    def supports_tags(self):
1609
        # Remote branches might support tags, but we won't know until we
1610
        # access the real remote branch.
1611
        return True
1612
1752.2.31 by Martin Pool
[broken] some support for write operations over hpss
1613
3786.2.3 by Andrew Bennetts
Remove duplicated 'call & translate errors' code in bzrlib.remote.
1614
class RemoteBranch(branch.Branch, _RpcHelper):
1752.2.31 by Martin Pool
[broken] some support for write operations over hpss
1615
    """Branch stored on a server accessed by HPSS RPC.
1616
1617
    At the moment most operations are mapped down to simple file operations.
1618
    """
1752.2.30 by Martin Pool
Start adding a RemoteBzrDir, etc
1619
2018.5.51 by Wouter van Heyst
Test and implement RemoteBranch.last_revision_info()
1620
    def __init__(self, remote_bzrdir, remote_repository, real_branch=None,
4032.3.2 by Robert Collins
Create and use a RPC call to create branches on bzr servers rather than using VFS calls.
1621
        _client=None, format=None, setup_stacking=True):
2018.5.34 by Robert Collins
Get test_remote.BasicRemoteObjectTests.test_open_remote_branch passing by implementing a remote method BzrDir.find_repository.
1622
        """Create a RemoteBranch instance.
1623
1624
        :param real_branch: An optional local implementation of the branch
1625
            format, usually accessing the data via the VFS.
2018.5.51 by Wouter van Heyst
Test and implement RemoteBranch.last_revision_info()
1626
        :param _client: Private parameter for testing.
4032.3.2 by Robert Collins
Create and use a RPC call to create branches on bzr servers rather than using VFS calls.
1627
        :param format: A RemoteBranchFormat object, None to create one
1628
            automatically. If supplied it should have a network_name already
1629
            supplied.
1630
        :param setup_stacking: If True make an RPC call to determine the
1631
            stacked (or not) status of the branch. If False assume the branch
1632
            is not stacked.
2018.5.34 by Robert Collins
Get test_remote.BasicRemoteObjectTests.test_open_remote_branch passing by implementing a remote method BzrDir.find_repository.
1633
        """
2018.5.163 by Andrew Bennetts
Deal with various review comments from Robert.
1634
        # We intentionally don't call the parent class's __init__, because it
1635
        # will try to assign to self.tags, which is a property in this subclass.
1636
        # And the parent's __init__ doesn't do much anyway.
2978.7.1 by John Arbash Meinel
Fix bug #162486, by having RemoteBranch properly initialize self._revision_id_to_revno_map.
1637
        self._revision_id_to_revno_cache = None
3949.2.6 by Ian Clatworthy
review feedback from jam
1638
        self._partial_revision_id_to_revno_cache = {}
2018.5.105 by Andrew Bennetts
Implement revision_history caching for RemoteBranch.
1639
        self._revision_history_cache = None
3441.5.1 by Andrew Bennetts
Avoid necessarily calling get_parent_map when pushing.
1640
        self._last_revision_info_cache = None
3949.3.4 by Ian Clatworthy
jam feedback: start & stop limits; simple caching
1641
        self._merge_sorted_revisions_cache = None
1752.2.64 by Andrew Bennetts
Improve how RemoteBzrDir.open_branch works to handle references and not double-open repositories.
1642
        self.bzrdir = remote_bzrdir
2018.5.51 by Wouter van Heyst
Test and implement RemoteBranch.last_revision_info()
1643
        if _client is not None:
1644
            self._client = _client
1645
        else:
3313.2.1 by Andrew Bennetts
Change _SmartClient's API to accept a medium and a base, rather than a _SharedConnection.
1646
            self._client = remote_bzrdir._client
1752.2.64 by Andrew Bennetts
Improve how RemoteBzrDir.open_branch works to handle references and not double-open repositories.
1647
        self.repository = remote_repository
2018.5.34 by Robert Collins
Get test_remote.BasicRemoteObjectTests.test_open_remote_branch passing by implementing a remote method BzrDir.find_repository.
1648
        if real_branch is not None:
1649
            self._real_branch = real_branch
2018.5.79 by Andrew Bennetts
Implement RemoteBranch.lock_write/unlock as smart operations.
1650
            # Give the remote repository the matching real repo.
2018.5.97 by Andrew Bennetts
Fix more tests.
1651
            real_repo = self._real_branch.repository
1652
            if isinstance(real_repo, RemoteRepository):
1653
                real_repo._ensure_real()
1654
                real_repo = real_repo._real_repository
1655
            self.repository._set_real_repository(real_repo)
2018.5.79 by Andrew Bennetts
Implement RemoteBranch.lock_write/unlock as smart operations.
1656
            # Give the branch the remote repository to let fast-pathing happen.
1657
            self._real_branch.repository = self.repository
2018.5.70 by Robert Collins
Only try to get real repositories when an operation requires them.
1658
        else:
1659
            self._real_branch = None
2018.5.59 by Robert Collins
Get BranchConfig working somewhat on RemoteBranches (Robert Collins, Vincent Ladeuil).
1660
        # Fill out expected attributes of branch for bzrlib api users.
2018.5.55 by Robert Collins
Give RemoteBranch a base url in line with the Branch protocol.
1661
        self.base = self.bzrdir.root_transport.base
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.
1662
        self._control_files = None
2018.5.79 by Andrew Bennetts
Implement RemoteBranch.lock_write/unlock as smart operations.
1663
        self._lock_mode = None
1664
        self._lock_token = None
2892.2.1 by Andrew Bennetts
Add Branch.set_last_revision_info smart method, and make the RemoteBranch client use it.
1665
        self._repo_lock_token = None
2018.5.79 by Andrew Bennetts
Implement RemoteBranch.lock_write/unlock as smart operations.
1666
        self._lock_count = 0
1667
        self._leave_lock = False
4032.3.2 by Robert Collins
Create and use a RPC call to create branches on bzr servers rather than using VFS calls.
1668
        # Setup a format: note that we cannot call _ensure_real until all the
1669
        # attributes above are set: This code cannot be moved higher up in this
1670
        # function.
1671
        if format is None:
1672
            self._format = RemoteBranchFormat()
1673
            if real_branch is not None:
1674
                self._format._network_name = \
1675
                    self._real_branch._format.network_name()
1676
            #else:
1677
            #    # XXX: Need to get this from BzrDir.open_branch's return value.
1678
            #    self._ensure_real()
1679
            #    self._format._network_name = \
1680
            #        self._real_branch._format.network_name()
4032.3.1 by Robert Collins
Add a BranchFormat.network_name() method as preparation for creating branches via RPC calls.
1681
        else:
4032.3.2 by Robert Collins
Create and use a RPC call to create branches on bzr servers rather than using VFS calls.
1682
            self._format = format
3681.1.2 by Robert Collins
Adjust for trunk.
1683
        # The base class init is not called, so we duplicate this:
3681.1.1 by Robert Collins
Create a new hook Branch.open. (Robert Collins)
1684
        hooks = branch.Branch.hooks['open']
1685
        for hook in hooks:
1686
            hook(self)
4032.3.2 by Robert Collins
Create and use a RPC call to create branches on bzr servers rather than using VFS calls.
1687
        if setup_stacking:
1688
            self._setup_stacking()
3691.2.1 by Martin Pool
RemoteBranch must configure stacking into the repository
1689
1690
    def _setup_stacking(self):
1691
        # configure stacking into the remote repository, by reading it from
3691.2.3 by Martin Pool
Factor out RemoteBranch._remote_path() and disable RemoteBranch stacking
1692
        # the vfs branch.
3691.2.1 by Martin Pool
RemoteBranch must configure stacking into the repository
1693
        try:
1694
            fallback_url = self.get_stacked_on_url()
1695
        except (errors.NotStacked, errors.UnstackableBranchFormat,
1696
            errors.UnstackableRepositoryFormat), e:
3691.2.7 by Martin Pool
FakeClient can know what calls to expect
1697
            return
1698
        # it's relative to this branch...
1699
        fallback_url = urlutils.join(self.base, fallback_url)
1700
        transports = [self.bzrdir.root_transport]
1701
        if self._real_branch is not None:
4035.2.2 by Robert Collins
Minor tweaks to fix failing tests.
1702
            # The real repository is setup already:
3691.2.7 by Martin Pool
FakeClient can know what calls to expect
1703
            transports.append(self._real_branch._transport)
4035.2.2 by Robert Collins
Minor tweaks to fix failing tests.
1704
            self.repository.add_fallback_repository(
1705
                self.repository._real_repository._fallback_repositories[0])
1706
        else:
1707
            stacked_on = branch.Branch.open(fallback_url,
1708
                                            possible_transports=transports)
1709
            self.repository.add_fallback_repository(stacked_on.repository)
1752.2.64 by Andrew Bennetts
Improve how RemoteBzrDir.open_branch works to handle references and not double-open repositories.
1710
3468.1.1 by Martin Pool
Update more users of default file modes from control_files to bzrdir
1711
    def _get_real_transport(self):
3407.2.16 by Martin Pool
Remove RemoteBranch reliance on control_files._transport
1712
        # if we try vfs access, return the real branch's vfs transport
1713
        self._ensure_real()
1714
        return self._real_branch._transport
1715
3468.1.1 by Martin Pool
Update more users of default file modes from control_files to bzrdir
1716
    _transport = property(_get_real_transport)
3407.2.16 by Martin Pool
Remove RemoteBranch reliance on control_files._transport
1717
2477.1.1 by Martin Pool
Add RemoteBranch repr
1718
    def __str__(self):
1719
        return "%s(%s)" % (self.__class__.__name__, self.base)
1720
1721
    __repr__ = __str__
1722
2018.5.70 by Robert Collins
Only try to get real repositories when an operation requires them.
1723
    def _ensure_real(self):
1724
        """Ensure that there is a _real_branch set.
1725
2018.5.163 by Andrew Bennetts
Deal with various review comments from Robert.
1726
        Used before calls to self._real_branch.
2018.5.70 by Robert Collins
Only try to get real repositories when an operation requires them.
1727
        """
3407.2.16 by Martin Pool
Remove RemoteBranch reliance on control_files._transport
1728
        if self._real_branch is None:
3376.2.4 by Martin Pool
Remove every assert statement from bzrlib!
1729
            if not vfs.vfs_enabled():
1730
                raise AssertionError('smart server vfs must be enabled '
1731
                    'to use vfs implementation')
2018.5.70 by Robert Collins
Only try to get real repositories when an operation requires them.
1732
            self.bzrdir._ensure_real()
1733
            self._real_branch = self.bzrdir._real_bzrdir.open_branch()
3692.1.3 by Andrew Bennetts
Delete some cruft (like the _ensure_real call in RemoteBranch.lock_write), improve some comments, and wrap some long lines.
1734
            if self.repository._real_repository is None:
1735
                # Give the remote repository the matching real repo.
1736
                real_repo = self._real_branch.repository
1737
                if isinstance(real_repo, RemoteRepository):
1738
                    real_repo._ensure_real()
1739
                    real_repo = real_repo._real_repository
1740
                self.repository._set_real_repository(real_repo)
1741
            # Give the real branch the remote repository to let fast-pathing
1742
            # happen.
2018.5.70 by Robert Collins
Only try to get real repositories when an operation requires them.
1743
            self._real_branch.repository = self.repository
2018.14.1 by Andrew Bennetts
Update to current hpss branch? Fix lots of test failures.
1744
            if self._lock_mode == 'r':
1745
                self._real_branch.lock_read()
3692.1.3 by Andrew Bennetts
Delete some cruft (like the _ensure_real call in RemoteBranch.lock_write), improve some comments, and wrap some long lines.
1746
            elif self._lock_mode == 'w':
1747
                self._real_branch.lock_write(token=self._lock_token)
2018.5.70 by Robert Collins
Only try to get real repositories when an operation requires them.
1748
3533.3.1 by Andrew Bennetts
Remove duplication of error translation in bzrlib/remote.py.
1749
    def _translate_error(self, err, **context):
1750
        self.repository._translate_error(err, branch=self, **context)
1751
3441.5.1 by Andrew Bennetts
Avoid necessarily calling get_parent_map when pushing.
1752
    def _clear_cached_state(self):
1753
        super(RemoteBranch, self)._clear_cached_state()
3441.5.5 by Andrew Bennetts
Some small tweaks and comments.
1754
        if self._real_branch is not None:
1755
            self._real_branch._clear_cached_state()
3441.5.29 by Andrew Bennetts
More review tweaks: whitespace nits in test_smart, add (and use) ._clear_cached_state_of_remote_branch_only method in bzrlib/remote.py.
1756
1757
    def _clear_cached_state_of_remote_branch_only(self):
1758
        """Like _clear_cached_state, but doesn't clear the cache of
1759
        self._real_branch.
1760
1761
        This is useful when falling back to calling a method of
1762
        self._real_branch that changes state.  In that case the underlying
1763
        branch changes, so we need to invalidate this RemoteBranch's cache of
1764
        it.  However, there's no need to invalidate the _real_branch's cache
1765
        too, in fact doing so might harm performance.
1766
        """
1767
        super(RemoteBranch, self)._clear_cached_state()
3943.8.1 by Marius Kruger
remove all trailing whitespace from bzr source
1768
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.
1769
    @property
1770
    def control_files(self):
1771
        # Defer actually creating RemoteBranchLockableFiles until its needed,
1772
        # because it triggers an _ensure_real that we otherwise might not need.
1773
        if self._control_files is None:
1774
            self._control_files = RemoteBranchLockableFiles(
1775
                self.bzrdir, self._client)
1776
        return self._control_files
1777
2018.5.166 by Andrew Bennetts
Small changes in response to Aaron's review.
1778
    def _get_checkout_format(self):
1779
        self._ensure_real()
1780
        return self._real_branch._get_checkout_format()
1781
2018.5.60 by Robert Collins
More missing methods from RemoteBranch and RemoteRepository to let 'info' get further.
1782
    def get_physical_lock_status(self):
1783
        """See Branch.get_physical_lock_status()."""
1784
        # should be an API call to the server, as branches must be lockable.
2018.5.70 by Robert Collins
Only try to get real repositories when an operation requires them.
1785
        self._ensure_real()
2018.5.60 by Robert Collins
More missing methods from RemoteBranch and RemoteRepository to let 'info' get further.
1786
        return self._real_branch.get_physical_lock_status()
1787
3537.3.1 by Martin Pool
Rename branch.get_stacked_on to get_stacked_on_url
1788
    def get_stacked_on_url(self):
3221.11.2 by Robert Collins
Create basic stackable branch facility.
1789
        """Get the URL this branch is stacked against.
1790
1791
        :raises NotStacked: If the branch is not stacked.
1792
        :raises UnstackableBranchFormat: If the branch does not support
1793
            stacking.
1794
        :raises UnstackableRepositoryFormat: If the repository does not support
1795
            stacking.
1796
        """
3691.2.12 by Martin Pool
Add test for coping without Branch.get_stacked_on_url
1797
        try:
3786.2.3 by Andrew Bennetts
Remove duplicated 'call & translate errors' code in bzrlib.remote.
1798
            # there may not be a repository yet, so we can't use
1799
            # self._translate_error, so we can't use self._call either.
3691.2.12 by Martin Pool
Add test for coping without Branch.get_stacked_on_url
1800
            response = self._client.call('Branch.get_stacked_on_url',
1801
                self._remote_path())
1802
        except errors.ErrorFromSmartServer, err:
1803
            # there may not be a repository yet, so we can't call through
1804
            # its _translate_error
1805
            _translate_error(err, branch=self)
1806
        except errors.UnknownSmartMethod, err:
1807
            self._ensure_real()
1808
            return self._real_branch.get_stacked_on_url()
3786.2.3 by Andrew Bennetts
Remove duplicated 'call & translate errors' code in bzrlib.remote.
1809
        if response[0] != 'ok':
1810
            raise errors.UnexpectedSmartServerResponse(response)
1811
        return response[1]
3221.11.2 by Robert Collins
Create basic stackable branch facility.
1812
1752.2.31 by Martin Pool
[broken] some support for write operations over hpss
1813
    def lock_read(self):
3692.1.1 by Andrew Bennetts
Make RemoteBranch.lock_write lock the repository too.
1814
        self.repository.lock_read()
2018.14.1 by Andrew Bennetts
Update to current hpss branch? Fix lots of test failures.
1815
        if not self._lock_mode:
1816
            self._lock_mode = 'r'
1817
            self._lock_count = 1
1818
            if self._real_branch is not None:
1819
                self._real_branch.lock_read()
1820
        else:
1821
            self._lock_count += 1
1752.2.52 by Andrew Bennetts
Flesh out more Remote* methods needed to open and initialise remote branches/trees/repositories.
1822
2018.5.142 by Andrew Bennetts
Change Branch.lock_token to only accept and receive the branch lock token (rather than the branch and repo lock tokens).
1823
    def _remote_lock_write(self, token):
1824
        if token is None:
2018.5.79 by Andrew Bennetts
Implement RemoteBranch.lock_write/unlock as smart operations.
1825
            branch_token = repo_token = ''
1826
        else:
2018.5.142 by Andrew Bennetts
Change Branch.lock_token to only accept and receive the branch lock token (rather than the branch and repo lock tokens).
1827
            branch_token = token
1828
            repo_token = self.repository.lock_write()
1829
            self.repository.unlock()
3786.2.3 by Andrew Bennetts
Remove duplicated 'call & translate errors' code in bzrlib.remote.
1830
        err_context = {'token': token}
1831
        response = self._call(
1832
            'Branch.lock_write', self._remote_path(), branch_token,
1833
            repo_token or '', **err_context)
3245.4.24 by Andrew Bennetts
Consistently raise errors from the server as ErrorFromSmartServer exceptions.
1834
        if response[0] != 'ok':
2555.1.1 by Martin Pool
Remove use of 'assert False' to raise an exception unconditionally
1835
            raise errors.UnexpectedSmartServerResponse(response)
3245.4.24 by Andrew Bennetts
Consistently raise errors from the server as ErrorFromSmartServer exceptions.
1836
        ok, branch_token, repo_token = response
1837
        return branch_token, repo_token
3943.8.1 by Marius Kruger
remove all trailing whitespace from bzr source
1838
2018.5.142 by Andrew Bennetts
Change Branch.lock_token to only accept and receive the branch lock token (rather than the branch and repo lock tokens).
1839
    def lock_write(self, token=None):
2018.5.79 by Andrew Bennetts
Implement RemoteBranch.lock_write/unlock as smart operations.
1840
        if not self._lock_mode:
3692.1.3 by Andrew Bennetts
Delete some cruft (like the _ensure_real call in RemoteBranch.lock_write), improve some comments, and wrap some long lines.
1841
            # Lock the branch and repo in one remote call.
2018.5.142 by Andrew Bennetts
Change Branch.lock_token to only accept and receive the branch lock token (rather than the branch and repo lock tokens).
1842
            remote_tokens = self._remote_lock_write(token)
2018.5.79 by Andrew Bennetts
Implement RemoteBranch.lock_write/unlock as smart operations.
1843
            self._lock_token, self._repo_lock_token = remote_tokens
3376.2.4 by Martin Pool
Remove every assert statement from bzrlib!
1844
            if not self._lock_token:
1845
                raise SmartProtocolError('Remote server did not return a token!')
3692.1.3 by Andrew Bennetts
Delete some cruft (like the _ensure_real call in RemoteBranch.lock_write), improve some comments, and wrap some long lines.
1846
            # Tell the self.repository object that it is locked.
3692.1.2 by Andrew Bennetts
Fix regression introduced by fix, and add a test for that regression.
1847
            self.repository.lock_write(
1848
                self._repo_lock_token, _skip_rpc=True)
3692.1.1 by Andrew Bennetts
Make RemoteBranch.lock_write lock the repository too.
1849
2018.5.79 by Andrew Bennetts
Implement RemoteBranch.lock_write/unlock as smart operations.
1850
            if self._real_branch is not None:
3692.1.5 by Andrew Bennetts
Fix bug revealed by removing _ensure_real call from RemoteBranch.lock_write.
1851
                self._real_branch.lock_write(token=self._lock_token)
2018.5.142 by Andrew Bennetts
Change Branch.lock_token to only accept and receive the branch lock token (rather than the branch and repo lock tokens).
1852
            if token is not None:
2018.5.79 by Andrew Bennetts
Implement RemoteBranch.lock_write/unlock as smart operations.
1853
                self._leave_lock = True
1854
            else:
1855
                self._leave_lock = False
1856
            self._lock_mode = 'w'
1857
            self._lock_count = 1
1858
        elif self._lock_mode == 'r':
1859
            raise errors.ReadOnlyTransaction
1860
        else:
2018.5.142 by Andrew Bennetts
Change Branch.lock_token to only accept and receive the branch lock token (rather than the branch and repo lock tokens).
1861
            if token is not None:
3692.1.3 by Andrew Bennetts
Delete some cruft (like the _ensure_real call in RemoteBranch.lock_write), improve some comments, and wrap some long lines.
1862
                # A token was given to lock_write, and we're relocking, so
1863
                # check that the given token actually matches the one we
1864
                # already have.
2018.5.142 by Andrew Bennetts
Change Branch.lock_token to only accept and receive the branch lock token (rather than the branch and repo lock tokens).
1865
                if token != self._lock_token:
1866
                    raise errors.TokenMismatch(token, self._lock_token)
2018.5.79 by Andrew Bennetts
Implement RemoteBranch.lock_write/unlock as smart operations.
1867
            self._lock_count += 1
3692.1.3 by Andrew Bennetts
Delete some cruft (like the _ensure_real call in RemoteBranch.lock_write), improve some comments, and wrap some long lines.
1868
            # Re-lock the repository too.
3692.1.2 by Andrew Bennetts
Fix regression introduced by fix, and add a test for that regression.
1869
            self.repository.lock_write(self._repo_lock_token)
3015.2.9 by Robert Collins
Handle repositories that do not allow remote locking, like pack repositories, in the client side remote server proxy objects.
1870
        return self._lock_token or None
2018.5.79 by Andrew Bennetts
Implement RemoteBranch.lock_write/unlock as smart operations.
1871
1872
    def _unlock(self, branch_token, repo_token):
3786.2.3 by Andrew Bennetts
Remove duplicated 'call & translate errors' code in bzrlib.remote.
1873
        err_context = {'token': str((branch_token, repo_token))}
1874
        response = self._call(
1875
            'Branch.unlock', self._remote_path(), branch_token,
1876
            repo_token or '', **err_context)
2018.5.79 by Andrew Bennetts
Implement RemoteBranch.lock_write/unlock as smart operations.
1877
        if response == ('ok',):
1878
            return
3245.4.24 by Andrew Bennetts
Consistently raise errors from the server as ErrorFromSmartServer exceptions.
1879
        raise errors.UnexpectedSmartServerResponse(response)
1752.2.31 by Martin Pool
[broken] some support for write operations over hpss
1880
1881
    def unlock(self):
3692.1.1 by Andrew Bennetts
Make RemoteBranch.lock_write lock the repository too.
1882
        try:
1883
            self._lock_count -= 1
1884
            if not self._lock_count:
1885
                self._clear_cached_state()
1886
                mode = self._lock_mode
1887
                self._lock_mode = None
1888
                if self._real_branch is not None:
1889
                    if (not self._leave_lock and mode == 'w' and
1890
                        self._repo_lock_token):
1891
                        # If this RemoteBranch will remove the physical lock
1892
                        # for the repository, make sure the _real_branch
1893
                        # doesn't do it first.  (Because the _real_branch's
1894
                        # repository is set to be the RemoteRepository.)
1895
                        self._real_branch.repository.leave_lock_in_place()
1896
                    self._real_branch.unlock()
1897
                if mode != 'w':
1898
                    # Only write-locked branched need to make a remote method
1899
                    # call to perfom the unlock.
1900
                    return
1901
                if not self._lock_token:
1902
                    raise AssertionError('Locked, but no token!')
1903
                branch_token = self._lock_token
1904
                repo_token = self._repo_lock_token
1905
                self._lock_token = None
1906
                self._repo_lock_token = None
1907
                if not self._leave_lock:
1908
                    self._unlock(branch_token, repo_token)
1909
        finally:
1910
            self.repository.unlock()
1752.2.52 by Andrew Bennetts
Flesh out more Remote* methods needed to open and initialise remote branches/trees/repositories.
1911
1912
    def break_lock(self):
2018.5.70 by Robert Collins
Only try to get real repositories when an operation requires them.
1913
        self._ensure_real()
1752.2.52 by Andrew Bennetts
Flesh out more Remote* methods needed to open and initialise remote branches/trees/repositories.
1914
        return self._real_branch.break_lock()
1752.2.31 by Martin Pool
[broken] some support for write operations over hpss
1915
2018.5.79 by Andrew Bennetts
Implement RemoteBranch.lock_write/unlock as smart operations.
1916
    def leave_lock_in_place(self):
3015.2.9 by Robert Collins
Handle repositories that do not allow remote locking, like pack repositories, in the client side remote server proxy objects.
1917
        if not self._lock_token:
1918
            raise NotImplementedError(self.leave_lock_in_place)
2018.5.79 by Andrew Bennetts
Implement RemoteBranch.lock_write/unlock as smart operations.
1919
        self._leave_lock = True
1920
1921
    def dont_leave_lock_in_place(self):
3015.2.9 by Robert Collins
Handle repositories that do not allow remote locking, like pack repositories, in the client side remote server proxy objects.
1922
        if not self._lock_token:
3015.2.15 by Robert Collins
Review feedback.
1923
            raise NotImplementedError(self.dont_leave_lock_in_place)
2018.5.79 by Andrew Bennetts
Implement RemoteBranch.lock_write/unlock as smart operations.
1924
        self._leave_lock = False
1925
3441.5.1 by Andrew Bennetts
Avoid necessarily calling get_parent_map when pushing.
1926
    def _last_revision_info(self):
3786.2.3 by Andrew Bennetts
Remove duplicated 'call & translate errors' code in bzrlib.remote.
1927
        response = self._call('Branch.last_revision_info', self._remote_path())
3376.2.4 by Martin Pool
Remove every assert statement from bzrlib!
1928
        if response[0] != 'ok':
1929
            raise SmartProtocolError('unexpected response code %s' % (response,))
2018.5.51 by Wouter van Heyst
Test and implement RemoteBranch.last_revision_info()
1930
        revno = int(response[1])
2018.5.83 by Andrew Bennetts
Fix some test failures caused by the switch from unicode to UTF-8-encoded strs for revision IDs.
1931
        last_revision = response[2]
2018.5.51 by Wouter van Heyst
Test and implement RemoteBranch.last_revision_info()
1932
        return (revno, last_revision)
1933
2018.5.105 by Andrew Bennetts
Implement revision_history caching for RemoteBranch.
1934
    def _gen_revision_history(self):
1935
        """See Branch._gen_revision_history()."""
3786.2.3 by Andrew Bennetts
Remove duplicated 'call & translate errors' code in bzrlib.remote.
1936
        response_tuple, response_handler = self._call_expecting_body(
3691.2.3 by Martin Pool
Factor out RemoteBranch._remote_path() and disable RemoteBranch stacking
1937
            'Branch.revision_history', self._remote_path())
3245.4.58 by Andrew Bennetts
Unpack call_expecting_body's return value into variables, to avoid lots of ugly subscripting.
1938
        if response_tuple[0] != 'ok':
3452.2.2 by Andrew Bennetts
Experimental PackRepository.{check_references,autopack} RPCs.
1939
            raise errors.UnexpectedSmartServerResponse(response_tuple)
3245.4.58 by Andrew Bennetts
Unpack call_expecting_body's return value into variables, to avoid lots of ugly subscripting.
1940
        result = response_handler.read_body_bytes().split('\x00')
2018.5.38 by Robert Collins
Implement RemoteBranch.revision_history().
1941
        if result == ['']:
1942
            return []
1943
        return result
1752.2.30 by Martin Pool
Start adding a RemoteBzrDir, etc
1944
3691.2.3 by Martin Pool
Factor out RemoteBranch._remote_path() and disable RemoteBranch stacking
1945
    def _remote_path(self):
1946
        return self.bzrdir._path_for_remote_call(self._client)
1947
3441.5.18 by Andrew Bennetts
Fix some test failures.
1948
    def _set_last_revision_descendant(self, revision_id, other_branch,
3441.5.28 by Andrew Bennetts
Another review tweak: rename do_not_overwrite_descendant to allow_overwrite_descendant.
1949
            allow_diverged=False, allow_overwrite_descendant=False):
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.
1950
        # This performs additional work to meet the hook contract; while its
1951
        # undesirable, we have to synthesise the revno to call the hook, and
1952
        # not calling the hook is worse as it means changes can't be prevented.
1953
        # Having calculated this though, we can't just call into
1954
        # set_last_revision_info as a simple call, because there is a set_rh
1955
        # hook that some folk may still be using.
1956
        old_revno, old_revid = self.last_revision_info()
1957
        history = self._lefthand_history(revision_id)
1958
        self._run_pre_change_branch_tip_hooks(len(history), revision_id)
3786.2.3 by Andrew Bennetts
Remove duplicated 'call & translate errors' code in bzrlib.remote.
1959
        err_context = {'other_branch': other_branch}
1960
        response = self._call('Branch.set_last_revision_ex',
1961
            self._remote_path(), self._lock_token, self._repo_lock_token,
1962
            revision_id, int(allow_diverged), int(allow_overwrite_descendant),
1963
            **err_context)
3441.5.6 by Andrew Bennetts
Greatly simplify RemoteBranch.update_revisions. Still needs more tests.
1964
        self._clear_cached_state()
3441.5.18 by Andrew Bennetts
Fix some test failures.
1965
        if len(response) != 3 and response[0] != 'ok':
3441.5.6 by Andrew Bennetts
Greatly simplify RemoteBranch.update_revisions. Still needs more tests.
1966
            raise errors.UnexpectedSmartServerResponse(response)
3441.5.18 by Andrew Bennetts
Fix some test failures.
1967
        new_revno, new_revision_id = response[1:]
1968
        self._last_revision_info_cache = new_revno, new_revision_id
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.
1969
        self._run_post_change_branch_tip_hooks(old_revno, old_revid)
3692.1.5 by Andrew Bennetts
Fix bug revealed by removing _ensure_real call from RemoteBranch.lock_write.
1970
        if self._real_branch is not None:
1971
            cache = new_revno, new_revision_id
1972
            self._real_branch._last_revision_info_cache = cache
3441.5.6 by Andrew Bennetts
Greatly simplify RemoteBranch.update_revisions. Still needs more tests.
1973
3441.5.1 by Andrew Bennetts
Avoid necessarily calling get_parent_map when pushing.
1974
    def _set_last_revision(self, revision_id):
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.
1975
        old_revno, old_revid = self.last_revision_info()
1976
        # This performs additional work to meet the hook contract; while its
1977
        # undesirable, we have to synthesise the revno to call the hook, and
1978
        # not calling the hook is worse as it means changes can't be prevented.
1979
        # Having calculated this though, we can't just call into
1980
        # set_last_revision_info as a simple call, because there is a set_rh
1981
        # hook that some folk may still be using.
1982
        history = self._lefthand_history(revision_id)
1983
        self._run_pre_change_branch_tip_hooks(len(history), revision_id)
3441.5.1 by Andrew Bennetts
Avoid necessarily calling get_parent_map when pushing.
1984
        self._clear_cached_state()
3786.2.3 by Andrew Bennetts
Remove duplicated 'call & translate errors' code in bzrlib.remote.
1985
        response = self._call('Branch.set_last_revision',
1986
            self._remote_path(), self._lock_token, self._repo_lock_token,
1987
            revision_id)
3441.5.1 by Andrew Bennetts
Avoid necessarily calling get_parent_map when pushing.
1988
        if response != ('ok',):
1989
            raise errors.UnexpectedSmartServerResponse(response)
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.
1990
        self._run_post_change_branch_tip_hooks(old_revno, old_revid)
3441.5.1 by Andrew Bennetts
Avoid necessarily calling get_parent_map when pushing.
1991
2018.14.1 by Andrew Bennetts
Update to current hpss branch? Fix lots of test failures.
1992
    @needs_write_lock
1752.2.52 by Andrew Bennetts
Flesh out more Remote* methods needed to open and initialise remote branches/trees/repositories.
1993
    def set_revision_history(self, rev_history):
2018.12.3 by Andrew Bennetts
Add a Branch.set_last_revision smart method, and make RemoteBranch.set_revision_history use it.
1994
        # Send just the tip revision of the history; the server will generate
1995
        # the full history from that.  If the revision doesn't exist in this
1996
        # branch, NoSuchRevision will be raised.
1997
        if rev_history == []:
2018.5.170 by Andrew Bennetts
Use 'null:' instead of '' to mean NULL_REVISION on the wire.
1998
            rev_id = 'null:'
2018.12.3 by Andrew Bennetts
Add a Branch.set_last_revision smart method, and make RemoteBranch.set_revision_history use it.
1999
        else:
2000
            rev_id = rev_history[-1]
3441.5.1 by Andrew Bennetts
Avoid necessarily calling get_parent_map when pushing.
2001
        self._set_last_revision(rev_id)
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.
2002
        for hook in branch.Branch.hooks['set_rh']:
2003
            hook(self, rev_history)
2018.5.105 by Andrew Bennetts
Implement revision_history caching for RemoteBranch.
2004
        self._cache_revision_history(rev_history)
1752.2.52 by Andrew Bennetts
Flesh out more Remote* methods needed to open and initialise remote branches/trees/repositories.
2005
2006
    def get_parent(self):
2018.5.70 by Robert Collins
Only try to get real repositories when an operation requires them.
2007
        self._ensure_real()
1752.2.52 by Andrew Bennetts
Flesh out more Remote* methods needed to open and initialise remote branches/trees/repositories.
2008
        return self._real_branch.get_parent()
3943.8.1 by Marius Kruger
remove all trailing whitespace from bzr source
2009
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.
2010
    def _get_parent_location(self):
2011
        # Used by tests, when checking normalisation of given vs stored paths.
2012
        self._ensure_real()
2013
        return self._real_branch._get_parent_location()
4032.1.1 by John Arbash Meinel
Merge the removal of all trailing whitespace, and resolve conflicts.
2014
1752.2.63 by Andrew Bennetts
Delegate set_parent.
2015
    def set_parent(self, url):
2018.5.70 by Robert Collins
Only try to get real repositories when an operation requires them.
2016
        self._ensure_real()
1752.2.63 by Andrew Bennetts
Delegate set_parent.
2017
        return self._real_branch.set_parent(url)
3943.8.1 by Marius Kruger
remove all trailing whitespace from bzr source
2018
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.
2019
    def _set_parent_location(self, url):
2020
        # Used by tests, to poke bad urls into branch configurations
2021
        if url is None:
2022
            self.set_parent(url)
2023
        else:
2024
            self._ensure_real()
2025
            return self._real_branch._set_parent_location(url)
4032.1.1 by John Arbash Meinel
Merge the removal of all trailing whitespace, and resolve conflicts.
2026
3537.3.3 by Martin Pool
Rename Branch.set_stacked_on to set_stacked_on_url
2027
    def set_stacked_on_url(self, stacked_location):
3221.18.1 by Ian Clatworthy
tweaks by ianc during review
2028
        """Set the URL this branch is stacked against.
3221.11.2 by Robert Collins
Create basic stackable branch facility.
2029
2030
        :raises UnstackableBranchFormat: If the branch does not support
2031
            stacking.
2032
        :raises UnstackableRepositoryFormat: If the repository does not support
2033
            stacking.
2034
        """
2035
        self._ensure_real()
3537.3.3 by Martin Pool
Rename Branch.set_stacked_on to set_stacked_on_url
2036
        return self._real_branch.set_stacked_on_url(stacked_location)
3221.11.2 by Robert Collins
Create basic stackable branch facility.
2037
2018.14.1 by Andrew Bennetts
Update to current hpss branch? Fix lots of test failures.
2038
    @needs_write_lock
2477.1.2 by Martin Pool
Rename push/pull back to 'run_hooks' (jameinel)
2039
    def pull(self, source, overwrite=False, stop_revision=None,
2477.1.9 by Martin Pool
Review cleanups from John, mostly docs
2040
             **kwargs):
3441.5.29 by Andrew Bennetts
More review tweaks: whitespace nits in test_smart, add (and use) ._clear_cached_state_of_remote_branch_only method in bzrlib/remote.py.
2041
        self._clear_cached_state_of_remote_branch_only()
2018.14.1 by Andrew Bennetts
Update to current hpss branch? Fix lots of test failures.
2042
        self._ensure_real()
3482.1.1 by John Arbash Meinel
Fix bug #238149, RemoteBranch.pull needs to return the _real_branch's pull result.
2043
        return self._real_branch.pull(
2477.1.2 by Martin Pool
Rename push/pull back to 'run_hooks' (jameinel)
2044
            source, overwrite=overwrite, stop_revision=stop_revision,
3489.2.4 by Andrew Bennetts
Fix all tests broken by fixing make_branch_and_tree.
2045
            _override_hook_target=self, **kwargs)
2018.14.1 by Andrew Bennetts
Update to current hpss branch? Fix lots of test failures.
2046
2018.14.3 by Andrew Bennetts
Make a couple more branch_implementations tests pass.
2047
    @needs_read_lock
2048
    def push(self, target, overwrite=False, stop_revision=None):
2049
        self._ensure_real()
2018.5.97 by Andrew Bennetts
Fix more tests.
2050
        return self._real_branch.push(
2477.1.5 by Martin Pool
More cleanups of Branch.push to get the right behaviour with RemoteBranches
2051
            target, overwrite=overwrite, stop_revision=stop_revision,
2052
            _override_hook_source_branch=self)
2018.14.3 by Andrew Bennetts
Make a couple more branch_implementations tests pass.
2053
2054
    def is_locked(self):
2055
        return self._lock_count >= 1
2056
3634.2.1 by John Arbash Meinel
Thunk over to the real branch's revision_id_to_revno.
2057
    @needs_read_lock
2058
    def revision_id_to_revno(self, revision_id):
2059
        self._ensure_real()
2060
        return self._real_branch.revision_id_to_revno(revision_id)
2061
2892.2.1 by Andrew Bennetts
Add Branch.set_last_revision_info smart method, and make the RemoteBranch client use it.
2062
    @needs_write_lock
2018.5.83 by Andrew Bennetts
Fix some test failures caused by the switch from unicode to UTF-8-encoded strs for revision IDs.
2063
    def set_last_revision_info(self, revno, revision_id):
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.
2064
        # XXX: These should be returned by the set_last_revision_info verb
2065
        old_revno, old_revid = self.last_revision_info()
2066
        self._run_pre_change_branch_tip_hooks(revno, revision_id)
2892.2.1 by Andrew Bennetts
Add Branch.set_last_revision_info smart method, and make the RemoteBranch client use it.
2067
        revision_id = ensure_null(revision_id)
3297.4.2 by Andrew Bennetts
Add backwards compatibility for servers older than 1.4.
2068
        try:
3786.2.3 by Andrew Bennetts
Remove duplicated 'call & translate errors' code in bzrlib.remote.
2069
            response = self._call('Branch.set_last_revision_info',
2070
                self._remote_path(), self._lock_token, self._repo_lock_token,
2071
                str(revno), revision_id)
3297.4.2 by Andrew Bennetts
Add backwards compatibility for servers older than 1.4.
2072
        except errors.UnknownSmartMethod:
2073
            self._ensure_real()
3441.5.29 by Andrew Bennetts
More review tweaks: whitespace nits in test_smart, add (and use) ._clear_cached_state_of_remote_branch_only method in bzrlib/remote.py.
2074
            self._clear_cached_state_of_remote_branch_only()
3441.5.1 by Andrew Bennetts
Avoid necessarily calling get_parent_map when pushing.
2075
            self._real_branch.set_last_revision_info(revno, revision_id)
2076
            self._last_revision_info_cache = revno, revision_id
2077
            return
2892.2.1 by Andrew Bennetts
Add Branch.set_last_revision_info smart method, and make the RemoteBranch client use it.
2078
        if response == ('ok',):
2079
            self._clear_cached_state()
3441.5.1 by Andrew Bennetts
Avoid necessarily calling get_parent_map when pushing.
2080
            self._last_revision_info_cache = revno, revision_id
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.
2081
            self._run_post_change_branch_tip_hooks(old_revno, old_revid)
3441.5.29 by Andrew Bennetts
More review tweaks: whitespace nits in test_smart, add (and use) ._clear_cached_state_of_remote_branch_only method in bzrlib/remote.py.
2082
            # Update the _real_branch's cache too.
2083
            if self._real_branch is not None:
2084
                cache = self._last_revision_info_cache
2085
                self._real_branch._last_revision_info_cache = cache
2892.2.1 by Andrew Bennetts
Add Branch.set_last_revision_info smart method, and make the RemoteBranch client use it.
2086
        else:
2087
            raise errors.UnexpectedSmartServerResponse(response)
2018.5.83 by Andrew Bennetts
Fix some test failures caused by the switch from unicode to UTF-8-encoded strs for revision IDs.
2088
3441.5.27 by Andrew Bennetts
Tweaks suggested by John's review: rename _check_if_descendant_or_diverged, move caching last_revision_info into base Branch, better use of lock decorators.
2089
    @needs_write_lock
2018.5.95 by Andrew Bennetts
Add a Transport.is_readonly remote call, let {Branch,Repository}.lock_write remote call return UnlockableTransport, and miscellaneous test fixes.
2090
    def generate_revision_history(self, revision_id, last_rev=None,
2091
                                  other_branch=None):
3441.5.6 by Andrew Bennetts
Greatly simplify RemoteBranch.update_revisions. Still needs more tests.
2092
        medium = self._client._medium
3441.5.23 by Andrew Bennetts
Fix test failures.
2093
        if not medium._is_remote_before((1, 6)):
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.
2094
            # Use a smart method for 1.6 and above servers
3441.5.6 by Andrew Bennetts
Greatly simplify RemoteBranch.update_revisions. Still needs more tests.
2095
            try:
3441.5.18 by Andrew Bennetts
Fix some test failures.
2096
                self._set_last_revision_descendant(revision_id, other_branch,
3441.5.28 by Andrew Bennetts
Another review tweak: rename do_not_overwrite_descendant to allow_overwrite_descendant.
2097
                    allow_diverged=True, allow_overwrite_descendant=True)
3441.5.6 by Andrew Bennetts
Greatly simplify RemoteBranch.update_revisions. Still needs more tests.
2098
                return
3441.5.18 by Andrew Bennetts
Fix some test failures.
2099
            except errors.UnknownSmartMethod:
3441.5.23 by Andrew Bennetts
Fix test failures.
2100
                medium._remember_remote_is_before((1, 6))
3441.5.29 by Andrew Bennetts
More review tweaks: whitespace nits in test_smart, add (and use) ._clear_cached_state_of_remote_branch_only method in bzrlib/remote.py.
2101
        self._clear_cached_state_of_remote_branch_only()
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.
2102
        self.set_revision_history(self._lefthand_history(revision_id,
2103
            last_rev=last_rev,other_branch=other_branch))
2018.5.95 by Andrew Bennetts
Add a Transport.is_readonly remote call, let {Branch,Repository}.lock_write remote call return UnlockableTransport, and miscellaneous test fixes.
2104
2018.5.96 by Andrew Bennetts
Merge from bzr.dev, resolving the worst of the semantic conflicts, but there's
2105
    @property
2106
    def tags(self):
2107
        self._ensure_real()
2108
        return self._real_branch.tags
2109
2018.5.97 by Andrew Bennetts
Fix more tests.
2110
    def set_push_location(self, location):
2111
        self._ensure_real()
2112
        return self._real_branch.set_push_location(location)
2113
2018.18.25 by Martin Pool
Repository.tarball fixes for python2.4
2114
2115
def _extract_tar(tar, to_dir):
2116
    """Extract all the contents of a tarfile object.
2117
2118
    A replacement for extractall, which is not present in python2.4
2119
    """
2120
    for tarinfo in tar:
2121
        tar.extract(tarinfo, to_dir)
3533.3.1 by Andrew Bennetts
Remove duplication of error translation in bzrlib/remote.py.
2122
2123
2124
def _translate_error(err, **context):
2125
    """Translate an ErrorFromSmartServer into a more useful error.
2126
2127
    Possible context keys:
2128
      - branch
2129
      - repository
2130
      - bzrdir
2131
      - token
2132
      - other_branch
3779.3.2 by Andrew Bennetts
Unify error translation done in bzrlib.remote and bzrlib.transport.remote.
2133
      - path
3690.1.1 by Andrew Bennetts
Unexpected error responses from a smart server no longer cause the client to traceback.
2134
2135
    If the error from the server doesn't match a known pattern, then
3690.1.2 by Andrew Bennetts
Rename UntranslateableErrorFromSmartServer -> UnknownErrorFromSmartServer.
2136
    UnknownErrorFromSmartServer is raised.
3533.3.1 by Andrew Bennetts
Remove duplication of error translation in bzrlib/remote.py.
2137
    """
2138
    def find(name):
3533.3.4 by Andrew Bennetts
Add tests for _translate_error's robustness.
2139
        try:
2140
            return context[name]
3779.3.2 by Andrew Bennetts
Unify error translation done in bzrlib.remote and bzrlib.transport.remote.
2141
        except KeyError, key_err:
2142
            mutter('Missing key %r in context %r', key_err.args[0], context)
3533.3.4 by Andrew Bennetts
Add tests for _translate_error's robustness.
2143
            raise err
3779.3.2 by Andrew Bennetts
Unify error translation done in bzrlib.remote and bzrlib.transport.remote.
2144
    def get_path():
3779.3.3 by Andrew Bennetts
Add a docstring.
2145
        """Get the path from the context if present, otherwise use first error
2146
        arg.
2147
        """
3779.3.2 by Andrew Bennetts
Unify error translation done in bzrlib.remote and bzrlib.transport.remote.
2148
        try:
2149
            return context['path']
2150
        except KeyError, key_err:
2151
            try:
2152
                return err.error_args[0]
2153
            except IndexError, idx_err:
2154
                mutter(
2155
                    'Missing key %r in context %r', key_err.args[0], context)
2156
                raise err
2157
3533.3.1 by Andrew Bennetts
Remove duplication of error translation in bzrlib/remote.py.
2158
    if err.error_verb == 'NoSuchRevision':
2159
        raise NoSuchRevision(find('branch'), err.error_args[0])
2160
    elif err.error_verb == 'nosuchrevision':
2161
        raise NoSuchRevision(find('repository'), err.error_args[0])
2162
    elif err.error_tuple == ('nobranch',):
3533.3.4 by Andrew Bennetts
Add tests for _translate_error's robustness.
2163
        raise errors.NotBranchError(path=find('bzrdir').root_transport.base)
3533.3.1 by Andrew Bennetts
Remove duplication of error translation in bzrlib/remote.py.
2164
    elif err.error_verb == 'norepository':
2165
        raise errors.NoRepositoryPresent(find('bzrdir'))
2166
    elif err.error_verb == 'LockContention':
2167
        raise errors.LockContention('(remote lock)')
2168
    elif err.error_verb == 'UnlockableTransport':
3533.3.4 by Andrew Bennetts
Add tests for _translate_error's robustness.
2169
        raise errors.UnlockableTransport(find('bzrdir').root_transport)
3533.3.1 by Andrew Bennetts
Remove duplication of error translation in bzrlib/remote.py.
2170
    elif err.error_verb == 'LockFailed':
2171
        raise errors.LockFailed(err.error_args[0], err.error_args[1])
2172
    elif err.error_verb == 'TokenMismatch':
2173
        raise errors.TokenMismatch(find('token'), '(remote token)')
2174
    elif err.error_verb == 'Diverged':
2175
        raise errors.DivergedBranches(find('branch'), find('other_branch'))
3577.1.1 by Andrew Bennetts
Cherry-pick TipChangeRejected changes from pre-branch-tip-changed-hook loom.
2176
    elif err.error_verb == 'TipChangeRejected':
2177
        raise errors.TipChangeRejected(err.error_args[0].decode('utf8'))
3691.2.6 by Martin Pool
Disable RemoteBranch stacking, but get get_stacked_on_url working, and passing back exceptions
2178
    elif err.error_verb == 'UnstackableBranchFormat':
2179
        raise errors.UnstackableBranchFormat(*err.error_args)
2180
    elif err.error_verb == 'UnstackableRepositoryFormat':
2181
        raise errors.UnstackableRepositoryFormat(*err.error_args)
2182
    elif err.error_verb == 'NotStacked':
2183
        raise errors.NotStacked(branch=find('branch'))
3779.3.1 by Andrew Bennetts
Move encoding/decoding logic of PermissionDenied and ReadError so that it happens for all RPCs.
2184
    elif err.error_verb == 'PermissionDenied':
3779.3.2 by Andrew Bennetts
Unify error translation done in bzrlib.remote and bzrlib.transport.remote.
2185
        path = get_path()
3779.3.1 by Andrew Bennetts
Move encoding/decoding logic of PermissionDenied and ReadError so that it happens for all RPCs.
2186
        if len(err.error_args) >= 2:
2187
            extra = err.error_args[1]
3779.3.2 by Andrew Bennetts
Unify error translation done in bzrlib.remote and bzrlib.transport.remote.
2188
        else:
2189
            extra = None
3779.3.1 by Andrew Bennetts
Move encoding/decoding logic of PermissionDenied and ReadError so that it happens for all RPCs.
2190
        raise errors.PermissionDenied(path, extra=extra)
3779.3.2 by Andrew Bennetts
Unify error translation done in bzrlib.remote and bzrlib.transport.remote.
2191
    elif err.error_verb == 'ReadError':
2192
        path = get_path()
2193
        raise errors.ReadError(path)
2194
    elif err.error_verb == 'NoSuchFile':
2195
        path = get_path()
2196
        raise errors.NoSuchFile(path)
2197
    elif err.error_verb == 'FileExists':
2198
        raise errors.FileExists(err.error_args[0])
2199
    elif err.error_verb == 'DirectoryNotEmpty':
2200
        raise errors.DirectoryNotEmpty(err.error_args[0])
2201
    elif err.error_verb == 'ShortReadvError':
2202
        args = err.error_args
2203
        raise errors.ShortReadvError(
2204
            args[0], int(args[1]), int(args[2]), int(args[3]))
2205
    elif err.error_verb in ('UnicodeEncodeError', 'UnicodeDecodeError'):
2206
        encoding = str(err.error_args[0]) # encoding must always be a string
2207
        val = err.error_args[1]
2208
        start = int(err.error_args[2])
2209
        end = int(err.error_args[3])
2210
        reason = str(err.error_args[4]) # reason must always be a string
2211
        if val.startswith('u:'):
2212
            val = val[2:].decode('utf-8')
2213
        elif val.startswith('s:'):
2214
            val = val[2:].decode('base64')
3786.2.3 by Andrew Bennetts
Remove duplicated 'call & translate errors' code in bzrlib.remote.
2215
        if err.error_verb == 'UnicodeDecodeError':
3779.3.2 by Andrew Bennetts
Unify error translation done in bzrlib.remote and bzrlib.transport.remote.
2216
            raise UnicodeDecodeError(encoding, val, start, end, reason)
3786.2.3 by Andrew Bennetts
Remove duplicated 'call & translate errors' code in bzrlib.remote.
2217
        elif err.error_verb == 'UnicodeEncodeError':
3779.3.2 by Andrew Bennetts
Unify error translation done in bzrlib.remote and bzrlib.transport.remote.
2218
            raise UnicodeEncodeError(encoding, val, start, end, reason)
2219
    elif err.error_verb == 'ReadOnlyError':
2220
        raise errors.TransportNotPossible('readonly transport')
3690.1.2 by Andrew Bennetts
Rename UntranslateableErrorFromSmartServer -> UnknownErrorFromSmartServer.
2221
    raise errors.UnknownErrorFromSmartServer(err)