/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
4183.7.1 by Sabin Iacob
update FSF mailing address
15
# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
1752.2.30 by Martin Pool
Start adding a RemoteBzrDir, etc
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 (
2694.5.4 by Jelmer Vernooij
Move bzrlib.util.bencode to bzrlib._bencode_py.
23
    bencode,
2490.2.5 by Aaron Bentley
Use GraphWalker.unique_ancestor to determine merge base
24
    branch,
4017.3.2 by Robert Collins
Reduce the number of round trips required to create a repository over the network.
25
    bzrdir,
4226.1.5 by Robert Collins
Reinstate the use of the Branch.get_config_file verb.
26
    config,
3192.1.1 by Andrew Bennetts
Add some -Dhpss debugging to get_parent_map.
27
    debug,
2490.2.5 by Aaron Bentley
Use GraphWalker.unique_ancestor to determine merge base
28
    errors,
3172.5.1 by Robert Collins
Create a RemoteRepository get_graph implementation and delegate get_parents_map to the real repository.
29
    graph,
2490.2.5 by Aaron Bentley
Use GraphWalker.unique_ancestor to determine merge base
30
    lockdir,
31
    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.
32
    revision,
4307.2.3 by Robert Collins
Change RemoteRepository.has_revision to use get_parent_map to leverage the caching.
33
    revision as _mod_revision,
3228.4.11 by John Arbash Meinel
Deprecations abound.
34
    symbol_versioning,
2490.2.5 by Aaron Bentley
Use GraphWalker.unique_ancestor to determine merge base
35
)
2535.4.27 by Andrew Bennetts
Remove some unused imports.
36
from bzrlib.branch import BranchReferenceFormat
2018.5.174 by Andrew Bennetts
Various nits discovered by pyflakes.
37
from bzrlib.bzrdir import BzrDir, RemoteBzrDirFormat
2018.14.1 by Andrew Bennetts
Update to current hpss branch? Fix lots of test failures.
38
from bzrlib.decorators import needs_read_lock, needs_write_lock
3376.2.4 by Martin Pool
Remove every assert statement from bzrlib!
39
from bzrlib.errors import (
40
    NoSuchRevision,
41
    SmartProtocolError,
42
    )
2018.5.127 by Andrew Bennetts
Fix most of the lockable_files tests for RemoteBranchLockableFiles.
43
from bzrlib.lockable_files import LockableFiles
4060.1.4 by Robert Collins
Streaming fetch from remote servers.
44
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'.
45
from bzrlib.revision import ensure_null, NULL_REVISION
3441.5.5 by Andrew Bennetts
Some small tweaks and comments.
46
from bzrlib.trace import mutter, note, warning
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()
4118.1.1 by Andrew Bennetts
Fix performance regression (many small round-trips) when pushing to a remote pack, and tidy the tests.
76
    format._rich_root_data = (response[0] == 'yes')
77
    format._supports_tree_reference = (response[1] == 'yes')
78
    format._supports_external_lookups = (response[2] == 'yes')
4032.3.2 by Robert Collins
Create and use a RPC call to create branches on bzr servers rather than using VFS calls.
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)
1752.2.31 by Martin Pool
[broken] some support for write operations over hpss
115
2018.5.70 by Robert Collins
Only try to get real repositories when an operation requires them.
116
    def _ensure_real(self):
117
        """Ensure that there is a _real_bzrdir set.
118
2018.5.163 by Andrew Bennetts
Deal with various review comments from Robert.
119
        Used before calls to self._real_bzrdir.
2018.5.70 by Robert Collins
Only try to get real repositories when an operation requires them.
120
        """
121
        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.
122
            self._real_bzrdir = BzrDir.open_from_transport(
123
                self.root_transport, _server_formats=False)
4070.2.1 by Robert Collins
Add a BzrDirFormat.network_name.
124
            self._format._network_name = \
125
                self._real_bzrdir._format.network_name()
2018.5.70 by Robert Collins
Only try to get real repositories when an operation requires them.
126
3786.2.3 by Andrew Bennetts
Remove duplicated 'call & translate errors' code in bzrlib.remote.
127
    def _translate_error(self, err, **context):
128
        _translate_error(err, bzrdir=self, **context)
129
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.
130
    def break_lock(self):
131
        # Prevent aliasing problems in the next_open_branch_result cache.
132
        # See create_branch for rationale.
133
        self._next_open_branch_result = None
134
        return BzrDir.break_lock(self)
135
4070.2.3 by Robert Collins
Get BzrDir.cloning_metadir working.
136
    def _vfs_cloning_metadir(self, require_stacking=False):
3242.3.28 by Aaron Bentley
Use repository acquisition policy for sprouting
137
        self._ensure_real()
4070.2.3 by Robert Collins
Get BzrDir.cloning_metadir working.
138
        return self._real_bzrdir.cloning_metadir(
139
            require_stacking=require_stacking)
140
141
    def cloning_metadir(self, require_stacking=False):
142
        medium = self._client._medium
143
        if medium._is_remote_before((1, 13)):
144
            return self._vfs_cloning_metadir(require_stacking=require_stacking)
145
        verb = 'BzrDir.cloning_metadir'
146
        if require_stacking:
147
            stacking = 'True'
148
        else:
149
            stacking = 'False'
150
        path = self._path_for_remote_call(self._client)
151
        try:
152
            response = self._call(verb, path, stacking)
153
        except errors.UnknownSmartMethod:
4094.1.1 by Andrew Bennetts
Add some medium._remember_is_before((1, 13)) calls.
154
            medium._remember_remote_is_before((1, 13))
4070.2.3 by Robert Collins
Get BzrDir.cloning_metadir working.
155
            return self._vfs_cloning_metadir(require_stacking=require_stacking)
4160.2.9 by Andrew Bennetts
Fix BzrDir.cloning_metadir RPC to fail on branch references, and make
156
        except errors.UnknownErrorFromSmartServer, err:
157
            if err.error_tuple != ('BranchReference',):
158
                raise
159
            # We need to resolve the branch reference to determine the
160
            # cloning_metadir.  This causes unnecessary RPCs to open the
161
            # referenced branch (and bzrdir, etc) but only when the caller
162
            # didn't already resolve the branch reference.
163
            referenced_branch = self.open_branch()
164
            return referenced_branch.bzrdir.cloning_metadir()
4070.2.3 by Robert Collins
Get BzrDir.cloning_metadir working.
165
        if len(response) != 3:
166
            raise errors.UnexpectedSmartServerResponse(response)
4070.7.4 by Andrew Bennetts
Deal with branch references better in BzrDir.cloning_metadir RPC (changes protocol).
167
        control_name, repo_name, branch_info = response
168
        if len(branch_info) != 2:
169
            raise errors.UnexpectedSmartServerResponse(response)
170
        branch_ref, branch_name = branch_info
4075.2.1 by Robert Collins
Audit and make sure we are registering network_name's as factories, not instances.
171
        format = bzrdir.network_format_registry.get(control_name)
4070.2.3 by Robert Collins
Get BzrDir.cloning_metadir working.
172
        if repo_name:
173
            format.repository_format = repository.network_format_registry.get(
174
                repo_name)
4084.2.2 by Robert Collins
Review feedback.
175
        if branch_ref == 'ref':
4070.7.4 by Andrew Bennetts
Deal with branch references better in BzrDir.cloning_metadir RPC (changes protocol).
176
            # XXX: we need possible_transports here to avoid reopening the
4070.7.5 by Andrew Bennetts
Tweak comment.
177
            # connection to the referenced location
4070.7.4 by Andrew Bennetts
Deal with branch references better in BzrDir.cloning_metadir RPC (changes protocol).
178
            ref_bzrdir = BzrDir.open(branch_name)
179
            branch_format = ref_bzrdir.cloning_metadir().get_branch_format()
180
            format.set_branch_format(branch_format)
4084.2.2 by Robert Collins
Review feedback.
181
        elif branch_ref == 'branch':
4070.7.4 by Andrew Bennetts
Deal with branch references better in BzrDir.cloning_metadir RPC (changes protocol).
182
            if branch_name:
183
                format.set_branch_format(
184
                    branch.network_format_registry.get(branch_name))
185
        else:
186
            raise errors.UnexpectedSmartServerResponse(response)
4070.2.3 by Robert Collins
Get BzrDir.cloning_metadir working.
187
        return format
3242.3.28 by Aaron Bentley
Use repository acquisition policy for sprouting
188
1752.2.39 by Martin Pool
[broken] implement upgrade apis on remote bzrdirs
189
    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.
190
        # as per meta1 formats - just delegate to the format object which may
191
        # be parameterised.
192
        result = self._format.repository_format.initialize(self, shared)
193
        if not isinstance(result, RemoteRepository):
194
            return self.open_repository()
195
        else:
196
            return result
1752.2.50 by Andrew Bennetts
Implement RemoteBzrDir.create_{branch,workingtree}
197
2796.2.19 by Aaron Bentley
Support reconfigure --lightweight-checkout
198
    def destroy_repository(self):
199
        """See BzrDir.destroy_repository"""
200
        self._ensure_real()
201
        self._real_bzrdir.destroy_repository()
202
1752.2.50 by Andrew Bennetts
Implement RemoteBzrDir.create_{branch,workingtree}
203
    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.
204
        # as per meta1 formats - just delegate to the format object which may
205
        # be parameterised.
206
        real_branch = self._format.get_branch_format().initialize(self)
207
        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.
208
            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.
209
        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.
210
            result = real_branch
211
        # BzrDir.clone_on_transport() uses the result of create_branch but does
212
        # not return it to its callers; we save approximately 8% of our round
213
        # trips by handing the branch we created back to the first caller to
214
        # open_branch rather than probing anew. Long term we need a API in
215
        # bzrdir that doesn't discard result objects (like result_branch).
216
        # RBC 20090225
217
        self._next_open_branch_result = result
218
        return result
1752.2.50 by Andrew Bennetts
Implement RemoteBzrDir.create_{branch,workingtree}
219
2796.2.6 by Aaron Bentley
Implement destroy_branch
220
    def destroy_branch(self):
2796.2.16 by Aaron Bentley
Documentation updates from review
221
        """See BzrDir.destroy_branch"""
2796.2.6 by Aaron Bentley
Implement destroy_branch
222
        self._ensure_real()
223
        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.
224
        self._next_open_branch_result = None
2796.2.6 by Aaron Bentley
Implement destroy_branch
225
2955.5.3 by Vincent Ladeuil
Fix second unwanted connection by providing the right branch to create_checkout.
226
    def create_workingtree(self, revision_id=None, from_branch=None):
2018.5.174 by Andrew Bennetts
Various nits discovered by pyflakes.
227
        raise errors.NotLocalUrl(self.transport.base)
1752.2.39 by Martin Pool
[broken] implement upgrade apis on remote bzrdirs
228
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.
229
    def find_branch_format(self):
230
        """Find the branch 'format' for this bzrdir.
231
232
        This might be a synthetic object for e.g. RemoteBranch and SVN.
233
        """
234
        b = self.open_branch()
235
        return b._format
236
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.
237
    def get_branch_reference(self):
238
        """See BzrDir.get_branch_reference()."""
4084.2.1 by Robert Collins
Make accessing a branch.tags.get_tag_dict use a smart[er] method rather than VFS calls and real objects.
239
        response = self._get_branch_reference()
240
        if response[0] == 'ref':
241
            return response[1]
242
        else:
243
            return None
244
245
    def _get_branch_reference(self):
2018.14.1 by Andrew Bennetts
Update to current hpss branch? Fix lots of test failures.
246
        path = self._path_for_remote_call(self._client)
4084.2.1 by Robert Collins
Make accessing a branch.tags.get_tag_dict use a smart[er] method rather than VFS calls and real objects.
247
        medium = self._client._medium
248
        if not medium._is_remote_before((1, 13)):
249
            try:
250
                response = self._call('BzrDir.open_branchV2', path)
251
                if response[0] not in ('ref', 'branch'):
252
                    raise errors.UnexpectedSmartServerResponse(response)
253
                return response
254
            except errors.UnknownSmartMethod:
4094.1.1 by Andrew Bennetts
Add some medium._remember_is_before((1, 13)) calls.
255
                medium._remember_remote_is_before((1, 13))
3786.2.3 by Andrew Bennetts
Remove duplicated 'call & translate errors' code in bzrlib.remote.
256
        response = self._call('BzrDir.open_branch', path)
4084.2.1 by Robert Collins
Make accessing a branch.tags.get_tag_dict use a smart[er] method rather than VFS calls and real objects.
257
        if response[0] != 'ok':
258
            raise errors.UnexpectedSmartServerResponse(response)
259
        if response[1] != '':
260
            return ('ref', response[1])
2018.6.1 by Robert Collins
Implement a BzrDir.open_branch smart server method for opening a branch without VFS.
261
        else:
4084.2.1 by Robert Collins
Make accessing a branch.tags.get_tag_dict use a smart[er] method rather than VFS calls and real objects.
262
            return ('branch', '')
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.
263
3211.4.1 by Robert Collins
* ``RemoteBzrDir._get_tree_branch`` no longer triggers ``_ensure_real``,
264
    def _get_tree_branch(self):
265
        """See BzrDir._get_tree_branch()."""
266
        return None, self.open_branch()
267
4160.2.6 by Andrew Bennetts
Add ignore_fallbacks flag.
268
    def open_branch(self, _unsupported=False, ignore_fallbacks=False):
3376.2.4 by Martin Pool
Remove every assert statement from bzrlib!
269
        if _unsupported:
270
            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.
271
        if self._next_open_branch_result is not None:
272
            # See create_branch for details.
273
            result = self._next_open_branch_result
274
            self._next_open_branch_result = None
275
            return result
4084.2.1 by Robert Collins
Make accessing a branch.tags.get_tag_dict use a smart[er] method rather than VFS calls and real objects.
276
        response = self._get_branch_reference()
277
        if response[0] == 'ref':
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.
278
            # a branch reference, use the existing BranchReference logic.
279
            format = BranchReferenceFormat()
4160.2.6 by Andrew Bennetts
Add ignore_fallbacks flag.
280
            return format.open(self, _found=True, location=response[1],
281
                ignore_fallbacks=ignore_fallbacks)
4084.2.1 by Robert Collins
Make accessing a branch.tags.get_tag_dict use a smart[er] method rather than VFS calls and real objects.
282
        branch_format_name = response[1]
283
        if not branch_format_name:
284
            branch_format_name = None
285
        format = RemoteBranchFormat(network_name=branch_format_name)
4160.2.6 by Andrew Bennetts
Add ignore_fallbacks flag.
286
        return RemoteBranch(self, self.find_repository(), format=format,
287
            setup_stacking=not ignore_fallbacks)
3943.8.1 by Marius Kruger
remove all trailing whitespace from bzr source
288
4053.1.1 by Robert Collins
New version of the BzrDir.find_repository verb supporting _network_name to support removing more _ensure_real calls.
289
    def _open_repo_v1(self, path):
290
        verb = 'BzrDir.find_repository'
291
        response = self._call(verb, path)
292
        if response[0] != 'ok':
293
            raise errors.UnexpectedSmartServerResponse(response)
294
        # servers that only support the v1 method don't support external
295
        # references either.
296
        self._ensure_real()
297
        repo = self._real_bzrdir.open_repository()
298
        response = response + ('no', repo._format.network_name())
299
        return response, repo
300
301
    def _open_repo_v2(self, path):
302
        verb = 'BzrDir.find_repositoryV2'
303
        response = self._call(verb, path)
304
        if response[0] != 'ok':
305
            raise errors.UnexpectedSmartServerResponse(response)
306
        self._ensure_real()
307
        repo = self._real_bzrdir.open_repository()
308
        response = response + (repo._format.network_name(),)
309
        return response, repo
310
311
    def _open_repo_v3(self, path):
312
        verb = 'BzrDir.find_repositoryV3'
4053.1.2 by Robert Collins
Actually make this branch work.
313
        medium = self._client._medium
314
        if medium._is_remote_before((1, 13)):
315
            raise errors.UnknownSmartMethod(verb)
4094.1.1 by Andrew Bennetts
Add some medium._remember_is_before((1, 13)) calls.
316
        try:
317
            response = self._call(verb, path)
318
        except errors.UnknownSmartMethod:
319
            medium._remember_remote_is_before((1, 13))
320
            raise
4053.1.1 by Robert Collins
New version of the BzrDir.find_repository verb supporting _network_name to support removing more _ensure_real calls.
321
        if response[0] != 'ok':
322
            raise errors.UnexpectedSmartServerResponse(response)
323
        return response, None
324
1752.2.31 by Martin Pool
[broken] some support for write operations over hpss
325
    def open_repository(self):
2018.14.1 by Andrew Bennetts
Update to current hpss branch? Fix lots of test failures.
326
        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.
327
        response = None
328
        for probe in [self._open_repo_v3, self._open_repo_v2,
329
            self._open_repo_v1]:
330
            try:
331
                response, real_repo = probe(path)
332
                break
333
            except errors.UnknownSmartMethod:
334
                pass
335
        if response is None:
336
            raise errors.UnknownSmartMethod('BzrDir.find_repository{3,2,}')
3245.4.24 by Andrew Bennetts
Consistently raise errors from the server as ErrorFromSmartServer exceptions.
337
        if response[0] != 'ok':
338
            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.
339
        if len(response) != 6:
3376.2.4 by Martin Pool
Remove every assert statement from bzrlib!
340
            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.
341
        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.
342
            # repo is at this dir.
343
            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.
344
            # Used to support creating a real format instance when needed.
345
            format._creating_bzrdir = self
3990.5.1 by Andrew Bennetts
Add network_name() to RepositoryFormat.
346
            remote_repo = RemoteRepository(self, format)
347
            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.
348
            if real_repo is not None:
349
                remote_repo._set_real_repository(real_repo)
3990.5.1 by Andrew Bennetts
Add network_name() to RepositoryFormat.
350
            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.
351
        else:
352
            raise errors.NoRepositoryPresent(self)
1752.2.30 by Martin Pool
Start adding a RemoteBzrDir, etc
353
2018.5.138 by Robert Collins
Merge bzr.dev.
354
    def open_workingtree(self, recommend_upgrade=True):
2445.1.1 by Andrew Bennetts
Make RemoteBzrDir.open_workingtree raise NoWorkingTree rather than NotLocalUrl
355
        self._ensure_real()
356
        if self._real_bzrdir.has_workingtree():
357
            raise errors.NotLocalUrl(self.root_transport)
358
        else:
359
            raise errors.NoWorkingTree(self.root_transport.base)
1752.2.50 by Andrew Bennetts
Implement RemoteBzrDir.create_{branch,workingtree}
360
2018.5.42 by Robert Collins
Various hopefully improvements, but wsgi is broken, handing over to spiv :).
361
    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.
362
        """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 :).
363
        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.
364
1752.2.31 by Martin Pool
[broken] some support for write operations over hpss
365
    def get_branch_transport(self, branch_format):
2018.5.162 by Andrew Bennetts
Add some missing _ensure_real calls, and a missing import.
366
        self._ensure_real()
1752.2.31 by Martin Pool
[broken] some support for write operations over hpss
367
        return self._real_bzrdir.get_branch_transport(branch_format)
368
1752.2.43 by Andrew Bennetts
Fix get_{branch,repository,workingtree}_transport.
369
    def get_repository_transport(self, repository_format):
2018.5.162 by Andrew Bennetts
Add some missing _ensure_real calls, and a missing import.
370
        self._ensure_real()
1752.2.43 by Andrew Bennetts
Fix get_{branch,repository,workingtree}_transport.
371
        return self._real_bzrdir.get_repository_transport(repository_format)
372
373
    def get_workingtree_transport(self, workingtree_format):
2018.5.162 by Andrew Bennetts
Add some missing _ensure_real calls, and a missing import.
374
        self._ensure_real()
1752.2.43 by Andrew Bennetts
Fix get_{branch,repository,workingtree}_transport.
375
        return self._real_bzrdir.get_workingtree_transport(workingtree_format)
376
1752.2.39 by Martin Pool
[broken] implement upgrade apis on remote bzrdirs
377
    def can_convert_format(self):
378
        """Upgrading of remote bzrdirs is not supported yet."""
379
        return False
380
381
    def needs_format_conversion(self, format=None):
382
        """Upgrading of remote bzrdirs is not supported yet."""
3943.2.5 by Martin Pool
deprecate needs_format_conversion(format=None)
383
        if format is None:
384
            symbol_versioning.warn(symbol_versioning.deprecated_in((1, 13, 0))
385
                % 'needs_format_conversion(format=None)')
1752.2.39 by Martin Pool
[broken] implement upgrade apis on remote bzrdirs
386
        return False
387
3242.3.37 by Aaron Bentley
Updates from reviews
388
    def clone(self, url, revision_id=None, force_new_repo=False,
389
              preserve_stacking=False):
2018.5.94 by Andrew Bennetts
Various small changes in aid of making tests pass (including deleting one invalid test).
390
        self._ensure_real()
391
        return self._real_bzrdir.clone(url, revision_id=revision_id,
3242.3.37 by Aaron Bentley
Updates from reviews
392
            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).
393
4288.1.1 by Robert Collins
Add support for a RemoteBzrDirConfig to support optimising push operations which need to look for default stacking locations.
394
    def _get_config(self):
395
        return RemoteBzrDirConfig(self)
3567.1.3 by Michael Hudson
fix problem
396
1752.2.31 by Martin Pool
[broken] some support for write operations over hpss
397
1752.2.52 by Andrew Bennetts
Flesh out more Remote* methods needed to open and initialise remote branches/trees/repositories.
398
class RemoteRepositoryFormat(repository.RepositoryFormat):
2018.5.159 by Andrew Bennetts
Rename SmartClient to _SmartClient.
399
    """Format for repositories accessed over a _SmartClient.
1752.2.31 by Martin Pool
[broken] some support for write operations over hpss
400
1752.2.50 by Andrew Bennetts
Implement RemoteBzrDir.create_{branch,workingtree}
401
    Instances of this repository are represented by RemoteRepository
1752.2.31 by Martin Pool
[broken] some support for write operations over hpss
402
    instances.
2018.5.118 by Robert Collins
Fix RemoteRepositoryFormat to have appropriate rich_root_data and support_tree_reference.
403
3128.1.3 by Vincent Ladeuil
Since we are there s/parameteris.*/parameteriz&/.
404
    The RemoteRepositoryFormat is parameterized during construction
2018.5.118 by Robert Collins
Fix RemoteRepositoryFormat to have appropriate rich_root_data and support_tree_reference.
405
    to reflect the capabilities of the real, remote format. Specifically
2018.5.138 by Robert Collins
Merge bzr.dev.
406
    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.
407
    on a per instance basis, and are not set (and should not be) at
408
    the class level.
3990.5.3 by Robert Collins
Docs and polish on RepositoryFormat.network_name.
409
4032.1.1 by John Arbash Meinel
Merge the removal of all trailing whitespace, and resolve conflicts.
410
    :ivar _custom_format: If set, a specific concrete repository format that
3990.5.3 by Robert Collins
Docs and polish on RepositoryFormat.network_name.
411
        will be used when initializing a repository with this
412
        RemoteRepositoryFormat.
413
    :ivar _creating_repo: If set, the repository object that this
414
        RemoteRepositoryFormat was created for: it can be called into
3990.5.4 by Robert Collins
Review feedback.
415
        to obtain data like the network name.
1752.2.31 by Martin Pool
[broken] some support for write operations over hpss
416
    """
417
3543.1.2 by Michael Hudson
the two character fix
418
    _matchingbzrdir = RemoteBzrDirFormat()
1752.2.31 by Martin Pool
[broken] some support for write operations over hpss
419
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.
420
    def __init__(self):
421
        repository.RepositoryFormat.__init__(self)
422
        self._custom_format = None
4017.3.2 by Robert Collins
Reduce the number of round trips required to create a repository over the network.
423
        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.
424
        self._creating_bzrdir = None
4476.3.15 by Andrew Bennetts
Partially working fallback for pre-1.17 servers.
425
        self._supports_chks = None
4118.1.1 by Andrew Bennetts
Fix performance regression (many small round-trips) when pushing to a remote pack, and tidy the tests.
426
        self._supports_external_lookups = None
427
        self._supports_tree_reference = None
428
        self._rich_root_data = None
429
430
    @property
4183.5.1 by Robert Collins
Add RepositoryFormat.fast_deltas to signal fast delta creation.
431
    def fast_deltas(self):
432
        self._ensure_real()
433
        return self._custom_format.fast_deltas
434
435
    @property
4118.1.1 by Andrew Bennetts
Fix performance regression (many small round-trips) when pushing to a remote pack, and tidy the tests.
436
    def rich_root_data(self):
437
        if self._rich_root_data is None:
438
            self._ensure_real()
439
            self._rich_root_data = self._custom_format.rich_root_data
440
        return self._rich_root_data
441
442
    @property
4476.3.15 by Andrew Bennetts
Partially working fallback for pre-1.17 servers.
443
    def supports_chks(self):
444
        if self._supports_chks is None:
445
            self._ensure_real()
446
            self._supports_chks = self._custom_format.supports_chks
447
        return self._supports_chks
448
449
    @property
4118.1.1 by Andrew Bennetts
Fix performance regression (many small round-trips) when pushing to a remote pack, and tidy the tests.
450
    def supports_external_lookups(self):
451
        if self._supports_external_lookups is None:
452
            self._ensure_real()
453
            self._supports_external_lookups = \
4104.4.2 by Robert Collins
Fix test_source for 1.13 landing.
454
                self._custom_format.supports_external_lookups
4118.1.1 by Andrew Bennetts
Fix performance regression (many small round-trips) when pushing to a remote pack, and tidy the tests.
455
        return self._supports_external_lookups
456
457
    @property
458
    def supports_tree_reference(self):
459
        if self._supports_tree_reference is None:
460
            self._ensure_real()
461
            self._supports_tree_reference = \
462
                self._custom_format.supports_tree_reference
463
        return self._supports_tree_reference
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.
464
465
    def _vfs_initialize(self, a_bzrdir, shared):
466
        """Helper for common code in initialize."""
467
        if self._custom_format:
468
            # Custom format requested
469
            result = self._custom_format.initialize(a_bzrdir, shared=shared)
470
        elif self._creating_bzrdir is not None:
471
            # Use the format that the repository we were created to back
472
            # has.
473
            prior_repo = self._creating_bzrdir.open_repository()
474
            prior_repo._ensure_real()
475
            result = prior_repo._real_repository._format.initialize(
476
                a_bzrdir, shared=shared)
477
        else:
478
            # assume that a_bzr is a RemoteBzrDir but the smart server didn't
479
            # support remote initialization.
480
            # We delegate to a real object at this point (as RemoteBzrDir
481
            # delegate to the repository format which would lead to infinite
482
            # recursion if we just called a_bzrdir.create_repository.
483
            a_bzrdir._ensure_real()
484
            result = a_bzrdir._real_bzrdir.create_repository(shared=shared)
485
        if not isinstance(result, RemoteRepository):
486
            return self.open(a_bzrdir)
487
        else:
488
            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.
489
1752.2.52 by Andrew Bennetts
Flesh out more Remote* methods needed to open and initialise remote branches/trees/repositories.
490
    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.
491
        # Being asked to create on a non RemoteBzrDir:
492
        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.
493
            return self._vfs_initialize(a_bzrdir, shared)
494
        medium = a_bzrdir._client._medium
495
        if medium._is_remote_before((1, 13)):
496
            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.
497
        # Creating on a remote bzr dir.
498
        # 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.
499
        if self._custom_format:
4017.3.2 by Robert Collins
Reduce the number of round trips required to create a repository over the network.
500
            network_name = self._custom_format.network_name()
4294.2.5 by Robert Collins
Reasonable unit test coverage for initialize_on_transport_ex.
501
        elif self._network_name:
502
            network_name = self._network_name
4017.3.2 by Robert Collins
Reduce the number of round trips required to create a repository over the network.
503
        else:
504
            # Select the current bzrlib default and ask for that.
505
            reference_bzrdir_format = bzrdir.format_registry.get('default')()
506
            reference_format = reference_bzrdir_format.repository_format
507
            network_name = reference_format.network_name()
508
        # 2) try direct creation via RPC
509
        path = a_bzrdir._path_for_remote_call(a_bzrdir._client)
510
        verb = 'BzrDir.create_repository'
511
        if shared:
512
            shared_str = 'True'
513
        else:
514
            shared_str = 'False'
515
        try:
516
            response = a_bzrdir._call(verb, path, network_name, shared_str)
517
        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.
518
            # Fallback - use vfs methods
4094.1.1 by Andrew Bennetts
Add some medium._remember_is_before((1, 13)) calls.
519
            medium._remember_remote_is_before((1, 13))
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.
520
            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.
521
        else:
522
            # 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.
523
            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.
524
            # Used to support creating a real format instance when needed.
525
            format._creating_bzrdir = a_bzrdir
526
            remote_repo = RemoteRepository(a_bzrdir, format)
527
            format._creating_repo = remote_repo
528
            return remote_repo
3943.8.1 by Marius Kruger
remove all trailing whitespace from bzr source
529
1752.2.52 by Andrew Bennetts
Flesh out more Remote* methods needed to open and initialise remote branches/trees/repositories.
530
    def open(self, a_bzrdir):
3376.2.4 by Martin Pool
Remove every assert statement from bzrlib!
531
        if not isinstance(a_bzrdir, RemoteBzrDir):
532
            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.
533
        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.
534
4053.1.4 by Robert Collins
Move the fetch control attributes from Repository to RepositoryFormat.
535
    def _ensure_real(self):
536
        if self._custom_format is None:
537
            self._custom_format = repository.network_format_registry.get(
538
                self._network_name)
539
540
    @property
541
    def _fetch_order(self):
542
        self._ensure_real()
543
        return self._custom_format._fetch_order
544
545
    @property
546
    def _fetch_uses_deltas(self):
547
        self._ensure_real()
548
        return self._custom_format._fetch_uses_deltas
549
550
    @property
551
    def _fetch_reconcile(self):
552
        self._ensure_real()
553
        return self._custom_format._fetch_reconcile
554
1752.2.52 by Andrew Bennetts
Flesh out more Remote* methods needed to open and initialise remote branches/trees/repositories.
555
    def get_format_description(self):
556
        return 'bzr remote repository'
557
558
    def __eq__(self, other):
4088.3.1 by Benjamin Peterson
compare types with 'is' not ==
559
        return self.__class__ is other.__class__
1752.2.87 by Andrew Bennetts
Make tests pass.
560
2018.5.118 by Robert Collins
Fix RemoteRepositoryFormat to have appropriate rich_root_data and support_tree_reference.
561
    def check_conversion_target(self, target_format):
562
        if self.rich_root_data and not target_format.rich_root_data:
563
            raise errors.BadConversionTarget(
564
                'Does not support rich root data.', target_format)
2018.5.138 by Robert Collins
Merge bzr.dev.
565
        if (self.supports_tree_reference and
566
            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.
567
            raise errors.BadConversionTarget(
568
                '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.
569
3990.5.1 by Andrew Bennetts
Add network_name() to RepositoryFormat.
570
    def network_name(self):
4017.3.2 by Robert Collins
Reduce the number of round trips required to create a repository over the network.
571
        if self._network_name:
572
            return self._network_name
3990.5.1 by Andrew Bennetts
Add network_name() to RepositoryFormat.
573
        self._creating_repo._ensure_real()
574
        return self._creating_repo._real_repository._format.network_name()
575
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)
576
    @property
4431.3.7 by Jonathan Lange
Cherrypick bzr.dev 4470, resolving conflicts.
577
    def pack_compresses(self):
578
        self._ensure_real()
579
        return self._custom_format.pack_compresses
580
581
    @property
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)
582
    def _serializer(self):
4053.1.4 by Robert Collins
Move the fetch control attributes from Repository to RepositoryFormat.
583
        self._ensure_real()
584
        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)
585
1752.2.31 by Martin Pool
[broken] some support for write operations over hpss
586
3786.2.3 by Andrew Bennetts
Remove duplicated 'call & translate errors' code in bzrlib.remote.
587
class RemoteRepository(_RpcHelper):
1752.2.31 by Martin Pool
[broken] some support for write operations over hpss
588
    """Repository accessed over rpc.
589
2018.5.163 by Andrew Bennetts
Deal with various review comments from Robert.
590
    For the moment most operations are performed using local transport-backed
591
    Repository objects.
1752.2.31 by Martin Pool
[broken] some support for write operations over hpss
592
    """
593
2018.5.118 by Robert Collins
Fix RemoteRepositoryFormat to have appropriate rich_root_data and support_tree_reference.
594
    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.
595
        """Create a RemoteRepository instance.
3943.8.1 by Marius Kruger
remove all trailing whitespace from bzr source
596
2018.5.34 by Robert Collins
Get test_remote.BasicRemoteObjectTests.test_open_remote_branch passing by implementing a remote method BzrDir.find_repository.
597
        :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.
598
        :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.
599
        :param real_repository: If not None, a local implementation of the
600
            repository logic for the repository, usually accessing the data
601
            via the VFS.
2018.5.57 by Robert Collins
Implement RemoteRepository.is_shared (Robert Collins, Vincent Ladeuil).
602
        :param _client: Private testing parameter - override the smart client
603
            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.
604
        """
605
        if real_repository:
2018.5.36 by Andrew Bennetts
Fix typo, and clean up some ununsed import warnings from pyflakes at the same time.
606
            self._real_repository = real_repository
2018.5.70 by Robert Collins
Only try to get real repositories when an operation requires them.
607
        else:
608
            self._real_repository = None
1752.2.50 by Andrew Bennetts
Implement RemoteBzrDir.create_{branch,workingtree}
609
        self.bzrdir = remote_bzrdir
2018.5.57 by Robert Collins
Implement RemoteRepository.is_shared (Robert Collins, Vincent Ladeuil).
610
        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.
611
            self._client = remote_bzrdir._client
2018.5.57 by Robert Collins
Implement RemoteRepository.is_shared (Robert Collins, Vincent Ladeuil).
612
        else:
613
            self._client = _client
2018.5.118 by Robert Collins
Fix RemoteRepositoryFormat to have appropriate rich_root_data and support_tree_reference.
614
        self._format = format
2018.5.75 by Andrew Bennetts
Add Repository.{dont_,}leave_lock_in_place.
615
        self._lock_mode = None
616
        self._lock_token = None
617
        self._lock_count = 0
2018.5.78 by Andrew Bennetts
Implement RemoteRepository.lock_write/unlock to expect and send tokens over the
618
        self._leave_lock = False
4307.2.4 by Robert Collins
Enable caching of negative revision lookups in RemoteRepository write locks when no _real_repository has been constructed.
619
        # Cache of revision parents; misses are cached during read locks, and
620
        # write locks when no _real_repository has been set.
3835.1.12 by Aaron Bentley
Unify CachingExtraParentsProvider and CachingParentsProvider.
621
        self._unstacked_provider = graph.CachingParentsProvider(
3896.1.1 by Andrew Bennetts
Remove broken debugging cruft, and some unused imports.
622
            get_parent_map=self._get_parent_map_rpc)
3835.1.12 by Aaron Bentley
Unify CachingExtraParentsProvider and CachingParentsProvider.
623
        self._unstacked_provider.disable_cache()
2951.1.10 by Robert Collins
Peer review feedback with Ian.
624
        # For tests:
625
        # These depend on the actual remote format, so force them off for
626
        # maximum compatibility. XXX: In future these should depend on the
627
        # remote repository instance, but this is irrelevant until we perform
628
        # 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.
629
        self._reconcile_does_inventory_gc = False
630
        self._reconcile_fixes_text_parents = False
2951.1.3 by Robert Collins
Partial support for native reconcile with packs.
631
        self._reconcile_backsup_inventory = False
2592.4.5 by Martin Pool
Add Repository.base on all repositories.
632
        self.base = self.bzrdir.transport.base
3221.12.1 by Robert Collins
Backport development1 format (stackable packs) to before-shallow-branches.
633
        # Additional places to query for data.
634
        self._fallback_repositories = []
2592.4.5 by Martin Pool
Add Repository.base on all repositories.
635
636
    def __str__(self):
637
        return "%s(%s)" % (self.__class__.__name__, self.base)
638
639
    __repr__ = __str__
1752.2.52 by Andrew Bennetts
Flesh out more Remote* methods needed to open and initialise remote branches/trees/repositories.
640
3825.4.1 by Andrew Bennetts
Add suppress_errors to abort_write_group.
641
    def abort_write_group(self, suppress_errors=False):
2617.6.7 by Robert Collins
More review feedback.
642
        """Complete a write group on the decorated repository.
3943.8.1 by Marius Kruger
remove all trailing whitespace from bzr source
643
4031.3.3 by Matt Nordhoff
Review tweaks from Ben Finney
644
        Smart methods perform operations in a single step so this API
2617.6.6 by Robert Collins
Some review feedback.
645
        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.
646
        for older plugins that don't use e.g. the CommitBuilder
647
        facility.
3825.4.6 by Andrew Bennetts
Document the suppress_errors flag in the docstring.
648
649
        :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.
650
        """
651
        self._ensure_real()
3825.4.1 by Andrew Bennetts
Add suppress_errors to abort_write_group.
652
        return self._real_repository.abort_write_group(
653
            suppress_errors=suppress_errors)
2617.6.2 by Robert Collins
Add abort_write_group and wire write_groups into fetch and commit.
654
4253.1.1 by Robert Collins
Add chk_bytes property to RemoteRepository
655
    @property
656
    def chk_bytes(self):
657
        """Decorate the real repository for now.
658
659
        In the long term a full blown network facility is needed to avoid
660
        creating a real repository object locally.
661
        """
662
        self._ensure_real()
663
        return self._real_repository.chk_bytes
664
2617.6.2 by Robert Collins
Add abort_write_group and wire write_groups into fetch and commit.
665
    def commit_write_group(self):
2617.6.7 by Robert Collins
More review feedback.
666
        """Complete a write group on the decorated repository.
3943.8.1 by Marius Kruger
remove all trailing whitespace from bzr source
667
4031.3.3 by Matt Nordhoff
Review tweaks from Ben Finney
668
        Smart methods perform operations in a single step so this API
2617.6.6 by Robert Collins
Some review feedback.
669
        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.
670
        for older plugins that don't use e.g. the CommitBuilder
671
        facility.
672
        """
673
        self._ensure_real()
674
        return self._real_repository.commit_write_group()
2617.6.1 by Robert Collins
* New method on Repository - ``start_write_group``, ``end_write_group``
675
4002.1.1 by Andrew Bennetts
Implement suspend_write_group/resume_write_group.
676
    def resume_write_group(self, tokens):
677
        self._ensure_real()
678
        return self._real_repository.resume_write_group(tokens)
679
680
    def suspend_write_group(self):
681
        self._ensure_real()
682
        return self._real_repository.suspend_write_group()
683
4343.3.29 by John Arbash Meinel
Add 'check_for_missing_texts' flag to get_missing_parent_inv..
684
    def get_missing_parent_inventories(self, check_for_missing_texts=True):
4257.4.6 by Andrew Bennetts
Make get_missing_parent_inventories work for all repo formats (it's a no-op for unstackable formats).
685
        self._ensure_real()
4343.3.29 by John Arbash Meinel
Add 'check_for_missing_texts' flag to get_missing_parent_inv..
686
        return self._real_repository.get_missing_parent_inventories(
687
            check_for_missing_texts=check_for_missing_texts)
4257.4.6 by Andrew Bennetts
Make get_missing_parent_inventories work for all repo formats (it's a no-op for unstackable formats).
688
4419.2.9 by Andrew Bennetts
Add per_repository_reference test for get_rev_id_for_revno, fix the bugs it revealed.
689
    def _get_rev_id_for_revno_vfs(self, revno, known_pair):
690
        self._ensure_real()
691
        return self._real_repository.get_rev_id_for_revno(
692
            revno, known_pair)
693
4419.2.5 by Andrew Bennetts
Add Repository.get_rev_id_for_revno, and use it both as the _ensure_real fallback and as the server-side implementation.
694
    def get_rev_id_for_revno(self, revno, known_pair):
695
        """See Repository.get_rev_id_for_revno."""
696
        path = self.bzrdir._path_for_remote_call(self._client)
697
        try:
4476.3.21 by Andrew Bennetts
Clarify some code and comments, and s/1.17/1.18/ in a few places.
698
            if self._client._medium._is_remote_before((1, 18)):
4419.2.9 by Andrew Bennetts
Add per_repository_reference test for get_rev_id_for_revno, fix the bugs it revealed.
699
                return self._get_rev_id_for_revno_vfs(revno, known_pair)
4419.2.5 by Andrew Bennetts
Add Repository.get_rev_id_for_revno, and use it both as the _ensure_real fallback and as the server-side implementation.
700
            response = self._call(
701
                'Repository.get_rev_id_for_revno', path, revno, known_pair)
702
        except errors.UnknownSmartMethod:
4476.3.21 by Andrew Bennetts
Clarify some code and comments, and s/1.17/1.18/ in a few places.
703
            self._client._medium._remember_remote_is_before((1, 18))
4419.2.9 by Andrew Bennetts
Add per_repository_reference test for get_rev_id_for_revno, fix the bugs it revealed.
704
            return self._get_rev_id_for_revno_vfs(revno, known_pair)
4419.2.5 by Andrew Bennetts
Add Repository.get_rev_id_for_revno, and use it both as the _ensure_real fallback and as the server-side implementation.
705
        if response[0] == 'ok':
706
            return True, response[1]
707
        elif response[0] == 'history-incomplete':
4419.2.8 by Andrew Bennetts
Add unit test for RemoteRepository.get_rev_id_for_revno using fallbacks if it gets a history-incomplete response.
708
            known_pair = response[1:3]
709
            for fallback in self._fallback_repositories:
710
                found, result = fallback.get_rev_id_for_revno(revno, known_pair)
711
                if found:
712
                    return True, result
713
                else:
714
                    known_pair = result
715
            # Not found in any fallbacks
716
            return False, known_pair
4419.2.5 by Andrew Bennetts
Add Repository.get_rev_id_for_revno, and use it both as the _ensure_real fallback and as the server-side implementation.
717
        else:
718
            raise errors.UnexpectedSmartServerResponse(response)
719
2018.5.70 by Robert Collins
Only try to get real repositories when an operation requires them.
720
    def _ensure_real(self):
721
        """Ensure that there is a _real_repository set.
722
2018.5.163 by Andrew Bennetts
Deal with various review comments from Robert.
723
        Used before calls to self._real_repository.
4145.1.1 by Robert Collins
Explicitly prevent fetching while the target repository is in a write group.
724
725
        Note that _ensure_real causes many roundtrips to the server which are
726
        not desirable, and prevents the use of smart one-roundtrip RPC's to
727
        perform complex operations (such as accessing parent data, streaming
728
        revisions etc). Adding calls to _ensure_real should only be done when
729
        bringing up new functionality, adding fallbacks for smart methods that
730
        require a fallback path, and never to replace an existing smart method
731
        invocation. If in doubt chat to the bzr network team.
2018.5.70 by Robert Collins
Only try to get real repositories when an operation requires them.
732
        """
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.
733
        if self._real_repository is None:
4509.2.2 by Martin Pool
Use only -Dhpssvfs for tracebacks, and document -Dhpssdetail
734
            if 'hpssvfs' in debug.debug_flags:
4347.1.1 by Robert Collins
Show a traceback when VFS operations are started on a smart server hosted repository.
735
                import traceback
736
                warning('VFS Repository access triggered\n%s',
737
                    ''.join(traceback.format_stack()))
4307.2.4 by Robert Collins
Enable caching of negative revision lookups in RemoteRepository write locks when no _real_repository has been constructed.
738
            self._unstacked_provider.missing_keys.clear()
2018.5.70 by Robert Collins
Only try to get real repositories when an operation requires them.
739
            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.
740
            self._set_real_repository(
741
                self.bzrdir._real_bzrdir.open_repository())
2018.5.70 by Robert Collins
Only try to get real repositories when an operation requires them.
742
3533.3.1 by Andrew Bennetts
Remove duplication of error translation in bzrlib/remote.py.
743
    def _translate_error(self, err, **context):
744
        self.bzrdir._translate_error(err, repository=self, **context)
745
2988.1.2 by Robert Collins
New Repository API find_text_key_references for use by reconcile and check.
746
    def find_text_key_references(self):
747
        """Find the text key references within the repository.
748
749
        :return: a dictionary mapping (file_id, revision_id) tuples to altered file-ids to an iterable of
750
        revision_ids. Each altered file-ids has the exact revision_ids that
751
        altered it listed explicitly.
752
        :return: A dictionary mapping text keys ((fileid, revision_id) tuples)
753
            to whether they were referred to by the inventory of the
754
            revision_id that they contain. The inventory texts from all present
755
            revision ids are assessed to generate this report.
756
        """
757
        self._ensure_real()
758
        return self._real_repository.find_text_key_references()
759
2988.1.3 by Robert Collins
Add a new repositoy method _generate_text_key_index for use by reconcile/check.
760
    def _generate_text_key_index(self):
761
        """Generate a new text key index for the repository.
762
763
        This is an expensive function that will take considerable time to run.
764
765
        :return: A dict mapping (file_id, revision_id) tuples to a list of
766
            parents, also (file_id, revision_id) tuples.
767
        """
768
        self._ensure_real()
769
        return self._real_repository._generate_text_key_index()
770
3287.6.4 by Robert Collins
Fix up deprecation warnings for get_revision_graph.
771
    def _get_revision_graph(self, revision_id):
772
        """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)
773
        if revision_id is None:
774
            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.
775
        elif revision.is_null(revision_id):
2018.5.67 by Wouter van Heyst
Implement RemoteRepository.get_revision_graph (Wouter van Heyst, Robert Collins)
776
            return {}
777
778
        path = self.bzrdir._path_for_remote_call(self._client)
3786.2.3 by Andrew Bennetts
Remove duplicated 'call & translate errors' code in bzrlib.remote.
779
        response = self._call_expecting_body(
780
            '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.
781
        response_tuple, response_handler = response
782
        if response_tuple[0] != 'ok':
783
            raise errors.UnexpectedSmartServerResponse(response_tuple)
784
        coded = response_handler.read_body_bytes()
3245.4.24 by Andrew Bennetts
Consistently raise errors from the server as ErrorFromSmartServer exceptions.
785
        if coded == '':
786
            # no revisions in this repository!
787
            return {}
788
        lines = coded.split('\n')
789
        revision_graph = {}
790
        for line in lines:
791
            d = tuple(line.split())
792
            revision_graph[d[0]] = d[1:]
3943.8.1 by Marius Kruger
remove all trailing whitespace from bzr source
793
3245.4.24 by Andrew Bennetts
Consistently raise errors from the server as ErrorFromSmartServer exceptions.
794
        return revision_graph
2018.5.67 by Wouter van Heyst
Implement RemoteRepository.get_revision_graph (Wouter van Heyst, Robert Collins)
795
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)
796
    def _get_sink(self):
797
        """See Repository._get_sink()."""
4022.1.6 by Robert Collins
Cherrypick and polish the RemoteSink for streaming push.
798
        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)
799
4060.1.3 by Robert Collins
Implement the separate source component for fetch - repository.StreamSource.
800
    def _get_source(self, to_format):
801
        """Return a source for streaming from this repository."""
802
        return RemoteStreamSource(self, to_format)
803
4307.2.3 by Robert Collins
Change RemoteRepository.has_revision to use get_parent_map to leverage the caching.
804
    @needs_read_lock
2018.5.40 by Robert Collins
Implement a remote Repository.has_revision method.
805
    def has_revision(self, revision_id):
4307.2.3 by Robert Collins
Change RemoteRepository.has_revision to use get_parent_map to leverage the caching.
806
        """True if this repository has a copy of the revision."""
807
        # Copy of bzrlib.repository.Repository.has_revision
808
        return revision_id in self.has_revisions((revision_id,))
2018.5.40 by Robert Collins
Implement a remote Repository.has_revision method.
809
4307.2.3 by Robert Collins
Change RemoteRepository.has_revision to use get_parent_map to leverage the caching.
810
    @needs_read_lock
3172.3.1 by Robert Collins
Repository has a new method ``has_revisions`` which signals the presence
811
    def has_revisions(self, revision_ids):
4307.2.3 by Robert Collins
Change RemoteRepository.has_revision to use get_parent_map to leverage the caching.
812
        """Probe to find out the presence of multiple revisions.
813
814
        :param revision_ids: An iterable of revision_ids.
815
        :return: A set of the revision_ids that were present.
816
        """
817
        # Copy of bzrlib.repository.Repository.has_revisions
818
        parent_map = self.get_parent_map(revision_ids)
819
        result = set(parent_map)
820
        if _mod_revision.NULL_REVISION in revision_ids:
821
            result.add(_mod_revision.NULL_REVISION)
3172.3.1 by Robert Collins
Repository has a new method ``has_revisions`` which signals the presence
822
        return result
823
2617.6.9 by Robert Collins
Merge bzr.dev.
824
    def has_same_location(self, other):
4088.3.1 by Benjamin Peterson
compare types with 'is' not ==
825
        return (self.__class__ is other.__class__ and
2592.3.162 by Robert Collins
Remove some arbitrary differences from bzr.dev.
826
                self.bzrdir.transport.base == other.bzrdir.transport.base)
3835.1.1 by Aaron Bentley
Stack get_parent_map on fallback repos
827
2490.2.21 by Aaron Bentley
Rename graph to deprecated_graph
828
    def get_graph(self, other_repository=None):
829
        """Return the graph for this repository format"""
3835.1.17 by Aaron Bentley
Fix stacking bug
830
        parents_provider = self._make_parents_provider(other_repository)
3441.5.24 by Andrew Bennetts
Remove RemoteGraph experiment.
831
        return graph.Graph(parents_provider)
2490.2.5 by Aaron Bentley
Use GraphWalker.unique_ancestor to determine merge base
832
2018.14.1 by Andrew Bennetts
Update to current hpss branch? Fix lots of test failures.
833
    def gather_stats(self, revid=None, committers=None):
2018.5.62 by Robert Collins
Stub out RemoteRepository.gather_stats while its implemented in parallel.
834
        """See Repository.gather_stats()."""
2018.10.3 by v.ladeuil+lp at free
more tests for gather_stats
835
        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.
836
        # revid can be None to indicate no revisions, not just NULL_REVISION
837
        if revid is None or revision.is_null(revid):
2018.10.3 by v.ladeuil+lp at free
more tests for gather_stats
838
            fmt_revid = ''
839
        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.
840
            fmt_revid = revid
2018.14.1 by Andrew Bennetts
Update to current hpss branch? Fix lots of test failures.
841
        if committers is None or not committers:
2018.10.3 by v.ladeuil+lp at free
more tests for gather_stats
842
            fmt_committers = 'no'
843
        else:
844
            fmt_committers = 'yes'
3786.2.3 by Andrew Bennetts
Remove duplicated 'call & translate errors' code in bzrlib.remote.
845
        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.
846
            '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.
847
        if response_tuple[0] != 'ok':
848
            raise errors.UnexpectedSmartServerResponse(response_tuple)
2018.10.3 by v.ladeuil+lp at free
more tests for gather_stats
849
3245.4.58 by Andrew Bennetts
Unpack call_expecting_body's return value into variables, to avoid lots of ugly subscripting.
850
        body = response_handler.read_body_bytes()
2018.10.3 by v.ladeuil+lp at free
more tests for gather_stats
851
        result = {}
852
        for line in body.split('\n'):
853
            if not line:
854
                continue
855
            key, val_text = line.split(':')
856
            if key in ('revisions', 'size', 'committers'):
857
                result[key] = int(val_text)
858
            elif key in ('firstrev', 'latestrev'):
859
                values = val_text.split(' ')[1:]
860
                result[key] = (float(values[0]), long(values[1]))
861
862
        return result
2018.5.62 by Robert Collins
Stub out RemoteRepository.gather_stats while its implemented in parallel.
863
3140.1.2 by Aaron Bentley
Add ability to find branches inside repositories
864
    def find_branches(self, using=False):
865
        """See Repository.find_branches()."""
866
        # should be an API call to the server.
867
        self._ensure_real()
868
        return self._real_repository.find_branches(using=using)
869
2018.5.60 by Robert Collins
More missing methods from RemoteBranch and RemoteRepository to let 'info' get further.
870
    def get_physical_lock_status(self):
871
        """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.
872
        # should be an API call to the server.
873
        self._ensure_real()
874
        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.
875
2617.6.1 by Robert Collins
* New method on Repository - ``start_write_group``, ``end_write_group``
876
    def is_in_write_group(self):
877
        """Return True if there is an open write group.
878
879
        write groups are only applicable locally for the smart server..
880
        """
881
        if self._real_repository:
882
            return self._real_repository.is_in_write_group()
883
884
    def is_locked(self):
885
        return self._lock_count >= 1
886
2018.5.57 by Robert Collins
Implement RemoteRepository.is_shared (Robert Collins, Vincent Ladeuil).
887
    def is_shared(self):
888
        """See Repository.is_shared()."""
889
        path = self.bzrdir._path_for_remote_call(self._client)
3786.2.3 by Andrew Bennetts
Remove duplicated 'call & translate errors' code in bzrlib.remote.
890
        response = self._call('Repository.is_shared', path)
3376.2.4 by Martin Pool
Remove every assert statement from bzrlib!
891
        if response[0] not in ('yes', 'no'):
892
            raise SmartProtocolError('unexpected response code %s' % (response,))
2018.5.57 by Robert Collins
Implement RemoteRepository.is_shared (Robert Collins, Vincent Ladeuil).
893
        return response[0] == 'yes'
894
2904.1.1 by Robert Collins
* New method ``bzrlib.repository.Repository.is_write_locked`` useful for
895
    def is_write_locked(self):
896
        return self._lock_mode == 'w'
897
2018.5.60 by Robert Collins
More missing methods from RemoteBranch and RemoteRepository to let 'info' get further.
898
    def lock_read(self):
899
        # wrong eventually - want a local lock cache context
2018.5.75 by Andrew Bennetts
Add Repository.{dont_,}leave_lock_in_place.
900
        if not self._lock_mode:
901
            self._lock_mode = 'r'
902
            self._lock_count = 1
4190.1.1 by Robert Collins
Negatively cache misses during read-locks in RemoteRepository.
903
            self._unstacked_provider.enable_cache(cache_misses=True)
2018.5.78 by Andrew Bennetts
Implement RemoteRepository.lock_write/unlock to expect and send tokens over the
904
            if self._real_repository is not None:
905
                self._real_repository.lock_read()
4379.2.1 by John Arbash Meinel
Change the fallback repository code to only lock/unlock on transition.
906
            for repo in self._fallback_repositories:
907
                repo.lock_read()
2018.5.75 by Andrew Bennetts
Add Repository.{dont_,}leave_lock_in_place.
908
        else:
909
            self._lock_count += 1
2018.5.78 by Andrew Bennetts
Implement RemoteRepository.lock_write/unlock to expect and send tokens over the
910
2018.14.1 by Andrew Bennetts
Update to current hpss branch? Fix lots of test failures.
911
    def _remote_lock_write(self, token):
2018.5.78 by Andrew Bennetts
Implement RemoteRepository.lock_write/unlock to expect and send tokens over the
912
        path = self.bzrdir._path_for_remote_call(self._client)
913
        if token is None:
914
            token = ''
3786.2.3 by Andrew Bennetts
Remove duplicated 'call & translate errors' code in bzrlib.remote.
915
        err_context = {'token': token}
916
        response = self._call('Repository.lock_write', path, token,
917
                              **err_context)
2018.5.78 by Andrew Bennetts
Implement RemoteRepository.lock_write/unlock to expect and send tokens over the
918
        if response[0] == 'ok':
919
            ok, token = response
920
            return token
921
        else:
2555.1.1 by Martin Pool
Remove use of 'assert False' to raise an exception unconditionally
922
            raise errors.UnexpectedSmartServerResponse(response)
2018.5.60 by Robert Collins
More missing methods from RemoteBranch and RemoteRepository to let 'info' get further.
923
3692.1.1 by Andrew Bennetts
Make RemoteBranch.lock_write lock the repository too.
924
    def lock_write(self, token=None, _skip_rpc=False):
2018.5.75 by Andrew Bennetts
Add Repository.{dont_,}leave_lock_in_place.
925
        if not self._lock_mode:
3692.1.1 by Andrew Bennetts
Make RemoteBranch.lock_write lock the repository too.
926
            if _skip_rpc:
927
                if self._lock_token is not None:
928
                    if token != self._lock_token:
3695.1.1 by Andrew Bennetts
Remove some unused imports and fix a couple of trivially broken raise statements.
929
                        raise errors.TokenMismatch(token, self._lock_token)
3692.1.1 by Andrew Bennetts
Make RemoteBranch.lock_write lock the repository too.
930
                self._lock_token = token
931
            else:
932
                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.
933
            # if self._lock_token is None, then this is something like packs or
934
            # svn where we don't get to lock the repo, or a weave style repository
935
            # where we cannot lock it over the wire and attempts to do so will
936
            # fail.
2018.5.78 by Andrew Bennetts
Implement RemoteRepository.lock_write/unlock to expect and send tokens over the
937
            if self._real_repository is not None:
938
                self._real_repository.lock_write(token=self._lock_token)
939
            if token is not None:
940
                self._leave_lock = True
941
            else:
942
                self._leave_lock = False
2018.5.75 by Andrew Bennetts
Add Repository.{dont_,}leave_lock_in_place.
943
            self._lock_mode = 'w'
944
            self._lock_count = 1
4307.2.4 by Robert Collins
Enable caching of negative revision lookups in RemoteRepository write locks when no _real_repository has been constructed.
945
            cache_misses = self._real_repository is None
946
            self._unstacked_provider.enable_cache(cache_misses=cache_misses)
4379.2.1 by John Arbash Meinel
Change the fallback repository code to only lock/unlock on transition.
947
            for repo in self._fallback_repositories:
948
                # Writes don't affect fallback repos
949
                repo.lock_read()
2018.5.75 by Andrew Bennetts
Add Repository.{dont_,}leave_lock_in_place.
950
        elif self._lock_mode == 'r':
2018.14.1 by Andrew Bennetts
Update to current hpss branch? Fix lots of test failures.
951
            raise errors.ReadOnlyError(self)
2018.5.75 by Andrew Bennetts
Add Repository.{dont_,}leave_lock_in_place.
952
        else:
953
            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.
954
        return self._lock_token or None
2018.5.75 by Andrew Bennetts
Add Repository.{dont_,}leave_lock_in_place.
955
956
    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.
957
        if not self._lock_token:
958
            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
959
        self._leave_lock = True
2018.5.75 by Andrew Bennetts
Add Repository.{dont_,}leave_lock_in_place.
960
961
    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.
962
        if not self._lock_token:
3015.2.15 by Robert Collins
Review feedback.
963
            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
964
        self._leave_lock = False
2018.5.75 by Andrew Bennetts
Add Repository.{dont_,}leave_lock_in_place.
965
966
    def _set_real_repository(self, repository):
967
        """Set the _real_repository for this repository.
968
969
        :param repository: The repository to fallback to for non-hpss
970
            implemented operations.
971
        """
4053.1.5 by Robert Collins
Review feedback on RemoteRepository._set_real_revision.
972
        if self._real_repository is not None:
973
            # Replacing an already set real repository.
974
            # We cannot do this [currently] if the repository is locked -
975
            # synchronised state might be lost.
976
            if self.is_locked():
977
                raise AssertionError('_real_repository is already set')
3376.2.4 by Martin Pool
Remove every assert statement from bzrlib!
978
        if isinstance(repository, RemoteRepository):
979
            raise AssertionError()
2018.5.75 by Andrew Bennetts
Add Repository.{dont_,}leave_lock_in_place.
980
        self._real_repository = repository
4226.2.5 by Robert Collins
Fix handling of fallback repositories some more.
981
        # three code paths happen here:
982
        # 1) old servers, RemoteBranch.open() calls _ensure_real before setting
983
        # up stacking. In this case self._fallback_repositories is [], and the
984
        # real repo is already setup. Preserve the real repo and
985
        # RemoteRepository.add_fallback_repository will avoid adding
986
        # duplicates.
987
        # 2) new servers, RemoteBranch.open() sets up stacking, and when
988
        # ensure_real is triggered from a branch, the real repository to
989
        # set already has a matching list with separate instances, but
990
        # as they are also RemoteRepositories we don't worry about making the
991
        # lists be identical.
992
        # 3) new servers, RemoteRepository.ensure_real is triggered before
993
        # RemoteBranch.ensure real, in this case we get a repo with no fallbacks
994
        # and need to populate it.
995
        if (self._fallback_repositories and
996
            len(self._real_repository._fallback_repositories) !=
4226.2.2 by Robert Collins
Fix setting config options to support unicode values and don't attempt to reset repositories _fallback_repositories as the simple approach fails to work.
997
            len(self._fallback_repositories)):
998
            if len(self._real_repository._fallback_repositories):
999
                raise AssertionError(
1000
                    "cannot cleanly remove existing _fallback_repositories")
3691.2.12 by Martin Pool
Add test for coping without Branch.get_stacked_on_url
1001
        for fb in self._fallback_repositories:
1002
            self._real_repository.add_fallback_repository(fb)
2018.5.75 by Andrew Bennetts
Add Repository.{dont_,}leave_lock_in_place.
1003
        if self._lock_mode == 'w':
1004
            # if we are already locked, the real repository must be able to
1005
            # acquire the lock with our token.
1006
            self._real_repository.lock_write(self._lock_token)
2018.14.1 by Andrew Bennetts
Update to current hpss branch? Fix lots of test failures.
1007
        elif self._lock_mode == 'r':
1008
            self._real_repository.lock_read()
2018.5.60 by Robert Collins
More missing methods from RemoteBranch and RemoteRepository to let 'info' get further.
1009
2617.6.1 by Robert Collins
* New method on Repository - ``start_write_group``, ``end_write_group``
1010
    def start_write_group(self):
1011
        """Start a write group on the decorated repository.
3943.8.1 by Marius Kruger
remove all trailing whitespace from bzr source
1012
4031.3.3 by Matt Nordhoff
Review tweaks from Ben Finney
1013
        Smart methods perform operations in a single step so this API
2617.6.6 by Robert Collins
Some review feedback.
1014
        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``
1015
        for older plugins that don't use e.g. the CommitBuilder
1016
        facility.
1017
        """
1018
        self._ensure_real()
1019
        return self._real_repository.start_write_group()
1020
2018.5.78 by Andrew Bennetts
Implement RemoteRepository.lock_write/unlock to expect and send tokens over the
1021
    def _unlock(self, token):
1022
        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.
1023
        if not token:
1024
            # with no token the remote repository is not persistently locked.
1025
            return
3786.2.3 by Andrew Bennetts
Remove duplicated 'call & translate errors' code in bzrlib.remote.
1026
        err_context = {'token': token}
1027
        response = self._call('Repository.unlock', path, token,
1028
                              **err_context)
2018.5.78 by Andrew Bennetts
Implement RemoteRepository.lock_write/unlock to expect and send tokens over the
1029
        if response == ('ok',):
1030
            return
1031
        else:
2555.1.1 by Martin Pool
Remove use of 'assert False' to raise an exception unconditionally
1032
            raise errors.UnexpectedSmartServerResponse(response)
2018.5.78 by Andrew Bennetts
Implement RemoteRepository.lock_write/unlock to expect and send tokens over the
1033
2018.5.60 by Robert Collins
More missing methods from RemoteBranch and RemoteRepository to let 'info' get further.
1034
    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.
1035
        if not self._lock_count:
1036
            raise errors.LockNotHeld(self)
2018.5.75 by Andrew Bennetts
Add Repository.{dont_,}leave_lock_in_place.
1037
        self._lock_count -= 1
2592.3.244 by Martin Pool
unlock while in a write group now aborts the write group, unlocks, and errors.
1038
        if self._lock_count > 0:
1039
            return
3835.1.8 by Aaron Bentley
Make UnstackedParentsProvider manage the cache
1040
        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.
1041
        old_mode = self._lock_mode
1042
        self._lock_mode = None
1043
        try:
1044
            # The real repository is responsible at present for raising an
1045
            # exception if it's in an unfinished write group.  However, it
1046
            # normally will *not* actually remove the lock from disk - that's
1047
            # done by the server on receiving the Repository.unlock call.
1048
            # 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
1049
            if self._real_repository is not None:
1050
                self._real_repository.unlock()
2592.3.244 by Martin Pool
unlock while in a write group now aborts the write group, unlocks, and errors.
1051
        finally:
1052
            # The rpc-level lock should be released even if there was a
1053
            # problem releasing the vfs-based lock.
1054
            if old_mode == 'w':
2018.5.163 by Andrew Bennetts
Deal with various review comments from Robert.
1055
                # Only write-locked repositories need to make a remote method
4031.3.1 by Frank Aspell
Fixing various typos
1056
                # call to perform the unlock.
2592.3.244 by Martin Pool
unlock while in a write group now aborts the write group, unlocks, and errors.
1057
                old_token = self._lock_token
1058
                self._lock_token = None
1059
                if not self._leave_lock:
1060
                    self._unlock(old_token)
4379.2.1 by John Arbash Meinel
Change the fallback repository code to only lock/unlock on transition.
1061
        # Fallbacks are always 'lock_read()' so we don't pay attention to
1062
        # self._leave_lock
1063
        for repo in self._fallback_repositories:
1064
            repo.unlock()
2018.5.60 by Robert Collins
More missing methods from RemoteBranch and RemoteRepository to let 'info' get further.
1065
1066
    def break_lock(self):
2018.5.78 by Andrew Bennetts
Implement RemoteRepository.lock_write/unlock to expect and send tokens over the
1067
        # should hand off to the network
2018.5.70 by Robert Collins
Only try to get real repositories when an operation requires them.
1068
        self._ensure_real()
2018.5.60 by Robert Collins
More missing methods from RemoteBranch and RemoteRepository to let 'info' get further.
1069
        return self._real_repository.break_lock()
1070
2018.18.8 by Ian Clatworthy
Tarball proxy code & tests
1071
    def _get_tarball(self, compression):
2814.10.2 by Andrew Bennetts
Make the fallback a little tidier.
1072
        """Return a TemporaryFile containing a repository tarball.
3943.8.1 by Marius Kruger
remove all trailing whitespace from bzr source
1073
2814.10.2 by Andrew Bennetts
Make the fallback a little tidier.
1074
        Returns None if the server does not support sending tarballs.
1075
        """
2018.18.25 by Martin Pool
Repository.tarball fixes for python2.4
1076
        import tempfile
2018.18.8 by Ian Clatworthy
Tarball proxy code & tests
1077
        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.
1078
        try:
3786.2.3 by Andrew Bennetts
Remove duplicated 'call & translate errors' code in bzrlib.remote.
1079
            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.
1080
                'Repository.tarball', path, compression)
1081
        except errors.UnknownSmartMethod:
1082
            protocol.cancel_read_body()
1083
            return None
2018.18.8 by Ian Clatworthy
Tarball proxy code & tests
1084
        if response[0] == 'ok':
1085
            # Extract the tarball and return it
2018.18.25 by Martin Pool
Repository.tarball fixes for python2.4
1086
            t = tempfile.NamedTemporaryFile()
1087
            # TODO: rpc layer should read directly into it...
1088
            t.write(protocol.read_body_bytes())
1089
            t.seek(0)
1090
            return t
2814.10.1 by Andrew Bennetts
Cope gracefully if the server doesn't support the Repository.tarball smart request.
1091
        raise errors.UnexpectedSmartServerResponse(response)
2018.18.8 by Ian Clatworthy
Tarball proxy code & tests
1092
2440.1.1 by Martin Pool
Add new Repository.sprout,
1093
    def sprout(self, to_bzrdir, revision_id=None):
1094
        # 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.
1095
        self._ensure_real()
3047.1.4 by Andrew Bennetts
Simplify RemoteRepository.sprout thanks to review comments.
1096
        dest_repo = self._real_repository._format.initialize(to_bzrdir,
1097
                                                             shared=False)
2535.3.17 by Andrew Bennetts
[broken] Closer to a working Repository.fetch_revisions smart request.
1098
        dest_repo.fetch(self, revision_id=revision_id)
1099
        return dest_repo
2440.1.1 by Martin Pool
Add new Repository.sprout,
1100
2018.14.1 by Andrew Bennetts
Update to current hpss branch? Fix lots of test failures.
1101
    ### These methods are just thin shims to the VFS object for now.
1102
1103
    def revision_tree(self, revision_id):
1104
        self._ensure_real()
1105
        return self._real_repository.revision_tree(revision_id)
1106
2520.4.113 by Aaron Bentley
Avoid peeking at Repository._serializer
1107
    def get_serializer_format(self):
1108
        self._ensure_real()
1109
        return self._real_repository.get_serializer_format()
1110
2018.14.1 by Andrew Bennetts
Update to current hpss branch? Fix lots of test failures.
1111
    def get_commit_builder(self, branch, parents, config, timestamp=None,
1112
                           timezone=None, committer=None, revprops=None,
1113
                           revision_id=None):
1114
        # FIXME: It ought to be possible to call this without immediately
1115
        # triggering _ensure_real.  For now it's the easiest thing to do.
1116
        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.
1117
        real_repo = self._real_repository
1118
        builder = real_repo.get_commit_builder(branch, parents,
2018.14.1 by Andrew Bennetts
Update to current hpss branch? Fix lots of test failures.
1119
                config, timestamp=timestamp, timezone=timezone,
1120
                committer=committer, revprops=revprops, revision_id=revision_id)
1121
        return builder
1122
3221.12.1 by Robert Collins
Backport development1 format (stackable packs) to before-shallow-branches.
1123
    def add_fallback_repository(self, repository):
1124
        """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
1125
3221.12.1 by Robert Collins
Backport development1 format (stackable packs) to before-shallow-branches.
1126
        :param repository: A repository.
1127
        """
4118.1.1 by Andrew Bennetts
Fix performance regression (many small round-trips) when pushing to a remote pack, and tidy the tests.
1128
        if not self._format.supports_external_lookups:
1129
            raise errors.UnstackableRepositoryFormat(
1130
                self._format.network_name(), self.base)
3221.12.1 by Robert Collins
Backport development1 format (stackable packs) to before-shallow-branches.
1131
        # We need to accumulate additional repositories here, to pass them in
1132
        # on various RPC's.
4035.2.3 by Robert Collins
Fix trailing whitespace.
1133
        #
4379.2.2 by John Arbash Meinel
Change the Repository.add_fallback_repository() contract slightly.
1134
        if self.is_locked():
1135
            # We will call fallback.unlock() when we transition to the unlocked
1136
            # state, so always add a lock here. If a caller passes us a locked
1137
            # repository, they are responsible for unlocking it later.
1138
            repository.lock_read()
3221.12.1 by Robert Collins
Backport development1 format (stackable packs) to before-shallow-branches.
1139
        self._fallback_repositories.append(repository)
4035.2.2 by Robert Collins
Minor tweaks to fix failing tests.
1140
        # If self._real_repository was parameterised already (e.g. because a
1141
        # _real_branch had its get_stacked_on_url method called), then the
1142
        # 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.
1143
        if self._real_repository is not None:
4226.2.5 by Robert Collins
Fix handling of fallback repositories some more.
1144
            fallback_locations = [repo.bzrdir.root_transport.base for repo in
1145
                self._real_repository._fallback_repositories]
1146
            if repository.bzrdir.root_transport.base not in fallback_locations:
4035.2.2 by Robert Collins
Minor tweaks to fix failing tests.
1147
                self._real_repository.add_fallback_repository(repository)
3221.12.1 by Robert Collins
Backport development1 format (stackable packs) to before-shallow-branches.
1148
2018.14.1 by Andrew Bennetts
Update to current hpss branch? Fix lots of test failures.
1149
    def add_inventory(self, revid, inv, parents):
1150
        self._ensure_real()
1151
        return self._real_repository.add_inventory(revid, inv, parents)
1152
3879.2.2 by John Arbash Meinel
Rename add_inventory_delta to add_inventory_by_delta.
1153
    def add_inventory_by_delta(self, basis_revision_id, delta, new_revision_id,
1154
                               parents):
3775.2.1 by Robert Collins
Create bzrlib.repository.Repository.add_inventory_delta for adding inventories via deltas.
1155
        self._ensure_real()
3879.2.2 by John Arbash Meinel
Rename add_inventory_delta to add_inventory_by_delta.
1156
        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.
1157
            delta, new_revision_id, parents)
1158
2018.14.1 by Andrew Bennetts
Update to current hpss branch? Fix lots of test failures.
1159
    def add_revision(self, rev_id, rev, inv=None, config=None):
1160
        self._ensure_real()
1161
        return self._real_repository.add_revision(
1162
            rev_id, rev, inv=inv, config=config)
1163
1164
    @needs_read_lock
1165
    def get_inventory(self, revision_id):
1166
        self._ensure_real()
1167
        return self._real_repository.get_inventory(revision_id)
1168
4476.3.15 by Andrew Bennetts
Partially working fallback for pre-1.17 servers.
1169
    def iter_inventories(self, revision_ids, ordering='unordered'):
3169.2.1 by Robert Collins
New method ``iter_inventories`` on Repository for access to many
1170
        self._ensure_real()
4476.3.15 by Andrew Bennetts
Partially working fallback for pre-1.17 servers.
1171
        return self._real_repository.iter_inventories(revision_ids, ordering)
3169.2.1 by Robert Collins
New method ``iter_inventories`` on Repository for access to many
1172
2018.14.1 by Andrew Bennetts
Update to current hpss branch? Fix lots of test failures.
1173
    @needs_read_lock
1174
    def get_revision(self, revision_id):
1175
        self._ensure_real()
1176
        return self._real_repository.get_revision(revision_id)
1177
1178
    def get_transaction(self):
1179
        self._ensure_real()
1180
        return self._real_repository.get_transaction()
1181
1182
    @needs_read_lock
2018.5.138 by Robert Collins
Merge bzr.dev.
1183
    def clone(self, a_bzrdir, revision_id=None):
2018.14.1 by Andrew Bennetts
Update to current hpss branch? Fix lots of test failures.
1184
        self._ensure_real()
2018.5.138 by Robert Collins
Merge bzr.dev.
1185
        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.
1186
1187
    def make_working_trees(self):
3349.1.1 by Aaron Bentley
Enable setting and getting make_working_trees for all repositories
1188
        """See Repository.make_working_trees"""
1189
        self._ensure_real()
1190
        return self._real_repository.make_working_trees()
2018.14.1 by Andrew Bennetts
Update to current hpss branch? Fix lots of test failures.
1191
4145.1.2 by Robert Collins
Add a refresh_data method on Repository allowing cleaner handling of insertions into RemoteRepository objects with _real_repository instances.
1192
    def refresh_data(self):
1193
        """Re-read any data needed to to synchronise with disk.
1194
1195
        This method is intended to be called after another repository instance
1196
        (such as one used by a smart server) has inserted data into the
1197
        repository. It may not be called during a write group, but may be
1198
        called at any other time.
1199
        """
1200
        if self.is_in_write_group():
1201
            raise errors.InternalBzrError(
1202
                "May not refresh_data while in a write group.")
1203
        if self._real_repository is not None:
1204
            self._real_repository.refresh_data()
1205
3184.1.9 by Robert Collins
* ``Repository.get_data_stream`` is now deprecated in favour of
1206
    def revision_ids_to_search_result(self, result_set):
1207
        """Convert a set of revision ids to a graph SearchResult."""
1208
        result_parents = set()
1209
        for parents in self.get_graph().get_parent_map(
1210
            result_set).itervalues():
1211
            result_parents.update(parents)
1212
        included_keys = result_set.intersection(result_parents)
1213
        start_keys = result_set.difference(included_keys)
1214
        exclude_keys = result_parents.difference(result_set)
1215
        result = graph.SearchResult(start_keys, exclude_keys,
1216
            len(result_set), result_set)
1217
        return result
1218
1219
    @needs_read_lock
1220
    def search_missing_revision_ids(self, other, revision_id=None, find_ghosts=True):
1221
        """Return the revision ids that other has that this does not.
3943.8.1 by Marius Kruger
remove all trailing whitespace from bzr source
1222
3184.1.9 by Robert Collins
* ``Repository.get_data_stream`` is now deprecated in favour of
1223
        These are returned in topological order.
1224
1225
        revision_id: only return revision ids included by revision_id.
1226
        """
1227
        return repository.InterRepository.get(
1228
            other, self).search_missing_revision_ids(revision_id, find_ghosts)
1229
4070.9.2 by Andrew Bennetts
Rough prototype of allowing a SearchResult to be passed to fetch, and using that to improve network conversations.
1230
    def fetch(self, source, revision_id=None, pb=None, find_ghosts=False,
1231
            fetch_spec=None):
4145.1.1 by Robert Collins
Explicitly prevent fetching while the target repository is in a write group.
1232
        # No base implementation to use as RemoteRepository is not a subclass
1233
        # of Repository; so this is a copy of Repository.fetch().
4070.9.2 by Andrew Bennetts
Rough prototype of allowing a SearchResult to be passed to fetch, and using that to improve network conversations.
1234
        if fetch_spec is not None and revision_id is not None:
1235
            raise AssertionError(
1236
                "fetch_spec and revision_id are mutually exclusive.")
4145.1.1 by Robert Collins
Explicitly prevent fetching while the target repository is in a write group.
1237
        if self.is_in_write_group():
4145.1.3 by Robert Collins
NEWS conflicts.
1238
            raise errors.InternalBzrError(
1239
                "May not fetch while in a write group.")
4145.1.1 by Robert Collins
Explicitly prevent fetching while the target repository is in a write group.
1240
        # fast path same-url fetch operations
4070.9.2 by Andrew Bennetts
Rough prototype of allowing a SearchResult to be passed to fetch, and using that to improve network conversations.
1241
        if self.has_same_location(source) and fetch_spec is None:
2881.4.1 by Robert Collins
Move responsibility for detecting same-repo fetching from the
1242
            # check that last_revision is in 'from' and then return a
1243
            # no-operation.
1244
            if (revision_id is not None and
4145.1.5 by Robert Collins
More fixes from grabbing the Repository implementation of fetch for RemoteRepository.
1245
                not revision.is_null(revision_id)):
2881.4.1 by Robert Collins
Move responsibility for detecting same-repo fetching from the
1246
                self.get_revision(revision_id)
2592.4.5 by Martin Pool
Add Repository.base on all repositories.
1247
            return 0, []
4145.1.1 by Robert Collins
Explicitly prevent fetching while the target repository is in a write group.
1248
        # if there is no specific appropriate InterRepository, this will get
1249
        # the InterRepository base class, which raises an
1250
        # IncompatibleRepositories when asked to fetch.
4145.1.2 by Robert Collins
Add a refresh_data method on Repository allowing cleaner handling of insertions into RemoteRepository objects with _real_repository instances.
1251
        inter = repository.InterRepository.get(source, self)
4145.1.1 by Robert Collins
Explicitly prevent fetching while the target repository is in a write group.
1252
        return inter.fetch(revision_id=revision_id, pb=pb,
1253
            find_ghosts=find_ghosts, fetch_spec=fetch_spec)
2018.14.1 by Andrew Bennetts
Update to current hpss branch? Fix lots of test failures.
1254
2520.4.54 by Aaron Bentley
Hang a create_bundle method off repository
1255
    def create_bundle(self, target, base, fileobj, format=None):
1256
        self._ensure_real()
1257
        self._real_repository.create_bundle(target, base, fileobj, format)
1258
2018.14.1 by Andrew Bennetts
Update to current hpss branch? Fix lots of test failures.
1259
    @needs_read_lock
2530.1.1 by Aaron Bentley
Make topological sorting optional for get_ancestry
1260
    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.
1261
        self._ensure_real()
2530.1.1 by Aaron Bentley
Make topological sorting optional for get_ancestry
1262
        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.
1263
1264
    def fileids_altered_by_revision_ids(self, revision_ids):
1265
        self._ensure_real()
1266
        return self._real_repository.fileids_altered_by_revision_ids(revision_ids)
1267
3036.1.3 by Robert Collins
Privatise VersionedFileChecker.
1268
    def _get_versioned_file_checker(self, revisions, revision_versions_cache):
2745.6.1 by Aaron Bentley
Initial checking of knit graphs
1269
        self._ensure_real()
3036.1.3 by Robert Collins
Privatise VersionedFileChecker.
1270
        return self._real_repository._get_versioned_file_checker(
2745.6.50 by Andrew Bennetts
Remove find_bad_ancestors; it's not needed anymore.
1271
            revisions, revision_versions_cache)
3943.8.1 by Marius Kruger
remove all trailing whitespace from bzr source
1272
2708.1.7 by Aaron Bentley
Rename extract_files_bytes to iter_files_bytes
1273
    def iter_files_bytes(self, desired_files):
2708.1.9 by Aaron Bentley
Clean-up docs and imports
1274
        """See Repository.iter_file_bytes.
2708.1.3 by Aaron Bentley
Implement extract_files_bytes on Repository
1275
        """
1276
        self._ensure_real()
2708.1.7 by Aaron Bentley
Rename extract_files_bytes to iter_files_bytes
1277
        return self._real_repository.iter_files_bytes(desired_files)
2708.1.3 by Aaron Bentley
Implement extract_files_bytes on Repository
1278
3835.1.1 by Aaron Bentley
Stack get_parent_map on fallback repos
1279
    def get_parent_map(self, revision_ids):
3835.1.6 by Aaron Bentley
Reduce inefficiency when doing make_parents_provider frequently
1280
        """See bzrlib.Graph.get_parent_map()."""
3835.1.5 by Aaron Bentley
Fix make_parents_provider
1281
        return self._make_parents_provider().get_parent_map(revision_ids)
3835.1.1 by Aaron Bentley
Stack get_parent_map on fallback repos
1282
1283
    def _get_parent_map_rpc(self, keys):
3172.5.6 by Robert Collins
Create new smart server verb Repository.get_parent_map.
1284
        """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.
1285
        medium = self._client._medium
3453.4.10 by Andrew Bennetts
Change _is_remote_at_least to _is_remote_before.
1286
        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.
1287
            # We already found out that the server can't understand
3213.1.3 by Andrew Bennetts
Fix typo in comment.
1288
            # 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.
1289
            # graph.
3948.3.7 by Martin Pool
Updated tests for RemoteRepository.get_parent_map on old servers.
1290
            #
1291
            # Note that this reads the whole graph, when only some keys are
1292
            # wanted.  On this old server there's no way (?) to get them all
1293
            # in one go, and the user probably will have seen a warning about
1294
            # the server being old anyhow.
1295
            rg = self._get_revision_graph(None)
4031.3.3 by Matt Nordhoff
Review tweaks from Ben Finney
1296
            # There is an API discrepancy between get_parent_map and
3389.1.1 by John Arbash Meinel
Fix bug #214894. Fix RemoteRepository.get_parent_map() when server is <v1.2
1297
            # get_revision_graph. Specifically, a "key:()" pair in
1298
            # get_revision_graph just means a node has no parents. For
1299
            # "get_parent_map" it means the node is a ghost. So fix up the
1300
            # graph to correct this.
1301
            #   https://bugs.launchpad.net/bzr/+bug/214894
1302
            # There is one other "bug" which is that ghosts in
1303
            # get_revision_graph() are not returned at all. But we won't worry
1304
            # about that for now.
1305
            for node_id, parent_ids in rg.iteritems():
1306
                if parent_ids == ():
1307
                    rg[node_id] = (NULL_REVISION,)
1308
            rg[NULL_REVISION] = ()
1309
            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.
1310
3172.5.6 by Robert Collins
Create new smart server verb Repository.get_parent_map.
1311
        keys = set(keys)
3373.5.2 by John Arbash Meinel
Add repository_implementation tests for get_parent_map
1312
        if None in keys:
1313
            raise ValueError('get_parent_map(None) is not valid')
3172.5.6 by Robert Collins
Create new smart server verb Repository.get_parent_map.
1314
        if NULL_REVISION in keys:
1315
            keys.discard(NULL_REVISION)
1316
            found_parents = {NULL_REVISION:()}
1317
            if not keys:
1318
                return found_parents
1319
        else:
1320
            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.
1321
        # TODO(Needs analysis): We could assume that the keys being requested
1322
        # from get_parent_map are in a breadth first search, so typically they
1323
        # will all be depth N from some common parent, and we don't have to
1324
        # have the server iterate from the root parent, but rather from the
1325
        # keys we're searching; and just tell the server the keyspace we
1326
        # already have; but this may be more traffic again.
1327
1328
        # Transform self._parents_map into a search request recipe.
1329
        # TODO: Manage this incrementally to avoid covering the same path
1330
        # repeatedly. (The server will have to on each request, but the less
1331
        # work done the better).
4190.1.3 by Robert Collins
Allow optional inclusion of ghost data in server get_parent_map calls.
1332
        #
1333
        # Negative caching notes:
1334
        # new server sends missing when a request including the revid
1335
        # 'include-missing:' is present in the request.
1336
        # missing keys are serialised as missing:X, and we then call
1337
        # provider.note_missing(X) for-all X
3835.1.8 by Aaron Bentley
Make UnstackedParentsProvider manage the cache
1338
        parents_map = self._unstacked_provider.get_cached_map()
3213.1.8 by Andrew Bennetts
Merge from bzr.dev.
1339
        if parents_map is None:
1340
            # Repository is not locked, so there's no cache.
1341
            parents_map = {}
4190.1.3 by Robert Collins
Allow optional inclusion of ghost data in server get_parent_map calls.
1342
        # start_set is all the keys in the cache
3213.1.8 by Andrew Bennetts
Merge from bzr.dev.
1343
        start_set = set(parents_map)
4190.1.3 by Robert Collins
Allow optional inclusion of ghost data in server get_parent_map calls.
1344
        # result set is all the references to keys in the cache
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.
1345
        result_parents = set()
3213.1.8 by Andrew Bennetts
Merge from bzr.dev.
1346
        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.
1347
            result_parents.update(parents)
1348
        stop_keys = result_parents.difference(start_set)
4190.1.4 by Robert Collins
Cache ghosts when we can get them from a RemoteRepository in get_parent_map.
1349
        # We don't need to send ghosts back to the server as a position to
1350
        # stop either.
1351
        stop_keys.difference_update(self._unstacked_provider.missing_keys)
4214.2.5 by Andrew Bennetts
Fix the bug.
1352
        key_count = len(parents_map)
1353
        if (NULL_REVISION in result_parents
1354
            and NULL_REVISION in self._unstacked_provider.missing_keys):
1355
            # If we pruned NULL_REVISION from the stop_keys because it's also
1356
            # in our cache of "missing" keys we need to increment our key count
1357
            # by 1, because the reconsitituted SearchResult on the server will
1358
            # still consider NULL_REVISION to be an included key.
1359
            key_count += 1
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.
1360
        included_keys = start_set.intersection(result_parents)
1361
        start_set.difference_update(included_keys)
4214.2.5 by Andrew Bennetts
Fix the bug.
1362
        recipe = ('manual', start_set, stop_keys, key_count)
3842.3.20 by Andrew Bennetts
Re-revert changes from another thread that accidentally got reinstated here.
1363
        body = self._serialise_search_recipe(recipe)
3172.5.6 by Robert Collins
Create new smart server verb Repository.get_parent_map.
1364
        path = self.bzrdir._path_for_remote_call(self._client)
1365
        for key in keys:
3360.2.8 by Martin Pool
Change assertion to a plain raise
1366
            if type(key) is not str:
1367
                raise ValueError(
1368
                    "key %r not a plain string" % (key,))
3172.5.8 by Robert Collins
Review feedback.
1369
        verb = 'Repository.get_parent_map'
4190.1.4 by Robert Collins
Cache ghosts when we can get them from a RemoteRepository in get_parent_map.
1370
        args = (path, 'include-missing:') + 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.
1371
        try:
3786.2.3 by Andrew Bennetts
Remove duplicated 'call & translate errors' code in bzrlib.remote.
1372
            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.
1373
                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.
1374
        except errors.UnknownSmartMethod:
3213.1.2 by Andrew Bennetts
Add test for reconnection if get_parent_map is unknown by the server.
1375
            # 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.
1376
            # Worse, we have to force a disconnection, because the server now
1377
            # doesn't realise it has a body on the wire to consume, so the
1378
            # only way to recover is to abandon the connection.
3213.1.6 by Andrew Bennetts
Emit warnings when forcing a reconnect.
1379
            warning(
1380
                'Server is too old for fast get_parent_map, reconnecting.  '
1381
                '(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.
1382
            medium.disconnect()
1383
            # To avoid having to disconnect repeatedly, we keep track of the
1384
            # 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.
1385
            medium._remember_remote_is_before((1, 2))
3948.3.7 by Martin Pool
Updated tests for RemoteRepository.get_parent_map on old servers.
1386
            # Recurse just once and we should use the fallback code.
1387
            return self._get_parent_map_rpc(keys)
3245.4.58 by Andrew Bennetts
Unpack call_expecting_body's return value into variables, to avoid lots of ugly subscripting.
1388
        response_tuple, response_handler = response
1389
        if response_tuple[0] not in ['ok']:
1390
            response_handler.cancel_read_body()
1391
            raise errors.UnexpectedSmartServerResponse(response_tuple)
1392
        if response_tuple[0] == 'ok':
1393
            coded = bz2.decompress(response_handler.read_body_bytes())
3172.5.6 by Robert Collins
Create new smart server verb Repository.get_parent_map.
1394
            if coded == '':
1395
                # no revisions found
1396
                return {}
1397
            lines = coded.split('\n')
1398
            revision_graph = {}
1399
            for line in lines:
1400
                d = tuple(line.split())
1401
                if len(d) > 1:
1402
                    revision_graph[d[0]] = d[1:]
1403
                else:
4190.1.4 by Robert Collins
Cache ghosts when we can get them from a RemoteRepository in get_parent_map.
1404
                    # No parents:
1405
                    if d[0].startswith('missing:'):
1406
                        revid = d[0][8:]
1407
                        self._unstacked_provider.note_missing_key(revid)
1408
                    else:
1409
                        # no parents - so give the Graph result
1410
                        # (NULL_REVISION,).
1411
                        revision_graph[d[0]] = (NULL_REVISION,)
3172.5.6 by Robert Collins
Create new smart server verb Repository.get_parent_map.
1412
            return revision_graph
1413
2018.14.1 by Andrew Bennetts
Update to current hpss branch? Fix lots of test failures.
1414
    @needs_read_lock
1415
    def get_signature_text(self, revision_id):
1416
        self._ensure_real()
1417
        return self._real_repository.get_signature_text(revision_id)
1418
1419
    @needs_read_lock
1420
    def get_inventory_xml(self, revision_id):
1421
        self._ensure_real()
1422
        return self._real_repository.get_inventory_xml(revision_id)
1423
1424
    def deserialise_inventory(self, revision_id, xml):
1425
        self._ensure_real()
1426
        return self._real_repository.deserialise_inventory(revision_id, xml)
1427
1428
    def reconcile(self, other=None, thorough=False):
1429
        self._ensure_real()
1430
        return self._real_repository.reconcile(other=other, thorough=thorough)
3943.8.1 by Marius Kruger
remove all trailing whitespace from bzr source
1431
2018.14.1 by Andrew Bennetts
Update to current hpss branch? Fix lots of test failures.
1432
    def all_revision_ids(self):
1433
        self._ensure_real()
1434
        return self._real_repository.all_revision_ids()
3943.8.1 by Marius Kruger
remove all trailing whitespace from bzr source
1435
2018.14.1 by Andrew Bennetts
Update to current hpss branch? Fix lots of test failures.
1436
    @needs_read_lock
4137.3.2 by Ian Clatworthy
Repository.get_deltas_for_revisions() now supports file-id filtering
1437
    def get_deltas_for_revisions(self, revisions, specific_fileids=None):
2018.14.1 by Andrew Bennetts
Update to current hpss branch? Fix lots of test failures.
1438
        self._ensure_real()
4137.3.2 by Ian Clatworthy
Repository.get_deltas_for_revisions() now supports file-id filtering
1439
        return self._real_repository.get_deltas_for_revisions(revisions,
1440
            specific_fileids=specific_fileids)
2018.14.1 by Andrew Bennetts
Update to current hpss branch? Fix lots of test failures.
1441
1442
    @needs_read_lock
4137.3.2 by Ian Clatworthy
Repository.get_deltas_for_revisions() now supports file-id filtering
1443
    def get_revision_delta(self, revision_id, specific_fileids=None):
2018.14.1 by Andrew Bennetts
Update to current hpss branch? Fix lots of test failures.
1444
        self._ensure_real()
4137.3.2 by Ian Clatworthy
Repository.get_deltas_for_revisions() now supports file-id filtering
1445
        return self._real_repository.get_revision_delta(revision_id,
1446
            specific_fileids=specific_fileids)
2018.14.1 by Andrew Bennetts
Update to current hpss branch? Fix lots of test failures.
1447
1448
    @needs_read_lock
1449
    def revision_trees(self, revision_ids):
1450
        self._ensure_real()
1451
        return self._real_repository.revision_trees(revision_ids)
1452
1453
    @needs_read_lock
1454
    def get_revision_reconcile(self, revision_id):
1455
        self._ensure_real()
1456
        return self._real_repository.get_revision_reconcile(revision_id)
1457
1458
    @needs_read_lock
2745.6.36 by Andrew Bennetts
Deprecate revision_ids arg to Repository.check and other tweaks.
1459
    def check(self, revision_ids=None):
2018.14.1 by Andrew Bennetts
Update to current hpss branch? Fix lots of test failures.
1460
        self._ensure_real()
2745.6.36 by Andrew Bennetts
Deprecate revision_ids arg to Repository.check and other tweaks.
1461
        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.
1462
2018.5.138 by Robert Collins
Merge bzr.dev.
1463
    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.
1464
        self._ensure_real()
1465
        return self._real_repository.copy_content_into(
2018.5.138 by Robert Collins
Merge bzr.dev.
1466
            destination, revision_id=revision_id)
2018.14.1 by Andrew Bennetts
Update to current hpss branch? Fix lots of test failures.
1467
2814.10.2 by Andrew Bennetts
Make the fallback a little tidier.
1468
    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.
1469
        # get a tarball of the remote repository, and copy from that into the
1470
        # destination
1471
        from bzrlib import osutils
2018.18.9 by Martin Pool
remote Repository.tarball builds a temporary directory and tars that
1472
        import tarfile
2018.18.20 by Martin Pool
Route branch operations through remote copy_content_into
1473
        # TODO: Maybe a progress bar while streaming the tarball?
1474
        note("Copying repository content as tarball...")
2018.18.25 by Martin Pool
Repository.tarball fixes for python2.4
1475
        tar_file = self._get_tarball('bz2')
2814.10.2 by Andrew Bennetts
Make the fallback a little tidier.
1476
        if tar_file is None:
1477
            return None
1478
        destination = to_bzrdir.create_repository()
2018.18.10 by Martin Pool
copy_content_into from Remote repositories by using temporary directories on both ends.
1479
        try:
2018.18.25 by Martin Pool
Repository.tarball fixes for python2.4
1480
            tar = tarfile.open('repository', fileobj=tar_file,
1481
                mode='r|bz2')
3638.3.2 by Vincent Ladeuil
Fix all calls to tempfile.mkdtemp to osutils.mkdtemp.
1482
            tmpdir = osutils.mkdtemp()
2018.18.25 by Martin Pool
Repository.tarball fixes for python2.4
1483
            try:
1484
                _extract_tar(tar, tmpdir)
1485
                tmp_bzrdir = BzrDir.open(tmpdir)
1486
                tmp_repo = tmp_bzrdir.open_repository()
1487
                tmp_repo.copy_content_into(destination, revision_id)
1488
            finally:
1489
                osutils.rmtree(tmpdir)
2018.18.10 by Martin Pool
copy_content_into from Remote repositories by using temporary directories on both ends.
1490
        finally:
2018.18.25 by Martin Pool
Repository.tarball fixes for python2.4
1491
            tar_file.close()
2814.10.2 by Andrew Bennetts
Make the fallback a little tidier.
1492
        return destination
2018.18.23 by Martin Pool
review cleanups
1493
        # TODO: Suggestion from john: using external tar is much faster than
1494
        # 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.
1495
3842.3.20 by Andrew Bennetts
Re-revert changes from another thread that accidentally got reinstated here.
1496
    @property
1497
    def inventories(self):
1498
        """Decorate the real repository for now.
1499
1500
        In the long term a full blown network facility is needed to
1501
        avoid creating a real repository object locally.
1502
        """
1503
        self._ensure_real()
1504
        return self._real_repository.inventories
1505
2604.2.1 by Robert Collins
(robertc) Introduce a pack command.
1506
    @needs_write_lock
4431.3.7 by Jonathan Lange
Cherrypick bzr.dev 4470, resolving conflicts.
1507
    def pack(self, hint=None):
2604.2.1 by Robert Collins
(robertc) Introduce a pack command.
1508
        """Compress the data within the repository.
1509
1510
        This is not currently implemented within the smart server.
1511
        """
1512
        self._ensure_real()
4431.3.7 by Jonathan Lange
Cherrypick bzr.dev 4470, resolving conflicts.
1513
        return self._real_repository.pack(hint=hint)
2604.2.1 by Robert Collins
(robertc) Introduce a pack command.
1514
3842.3.20 by Andrew Bennetts
Re-revert changes from another thread that accidentally got reinstated here.
1515
    @property
1516
    def revisions(self):
1517
        """Decorate the real repository for now.
1518
1519
        In the short term this should become a real object to intercept graph
1520
        lookups.
1521
1522
        In the long term a full blown network facility is needed.
1523
        """
1524
        self._ensure_real()
1525
        return self._real_repository.revisions
1526
2018.14.1 by Andrew Bennetts
Update to current hpss branch? Fix lots of test failures.
1527
    def set_make_working_trees(self, new_value):
4017.3.4 by Robert Collins
Create a verb for Repository.set_make_working_trees.
1528
        if new_value:
1529
            new_value_str = "True"
1530
        else:
1531
            new_value_str = "False"
1532
        path = self.bzrdir._path_for_remote_call(self._client)
1533
        try:
1534
            response = self._call(
1535
                'Repository.set_make_working_trees', path, new_value_str)
1536
        except errors.UnknownSmartMethod:
1537
            self._ensure_real()
1538
            self._real_repository.set_make_working_trees(new_value)
1539
        else:
1540
            if response[0] != 'ok':
1541
                raise errors.UnexpectedSmartServerResponse(response)
2018.14.1 by Andrew Bennetts
Update to current hpss branch? Fix lots of test failures.
1542
3842.3.20 by Andrew Bennetts
Re-revert changes from another thread that accidentally got reinstated here.
1543
    @property
1544
    def signatures(self):
1545
        """Decorate the real repository for now.
1546
1547
        In the long term a full blown network facility is needed to avoid
1548
        creating a real repository object locally.
1549
        """
1550
        self._ensure_real()
1551
        return self._real_repository.signatures
1552
2018.14.1 by Andrew Bennetts
Update to current hpss branch? Fix lots of test failures.
1553
    @needs_write_lock
1554
    def sign_revision(self, revision_id, gpg_strategy):
1555
        self._ensure_real()
1556
        return self._real_repository.sign_revision(revision_id, gpg_strategy)
1557
3842.3.20 by Andrew Bennetts
Re-revert changes from another thread that accidentally got reinstated here.
1558
    @property
1559
    def texts(self):
1560
        """Decorate the real repository for now.
1561
1562
        In the long term a full blown network facility is needed to avoid
1563
        creating a real repository object locally.
1564
        """
1565
        self._ensure_real()
1566
        return self._real_repository.texts
1567
2018.14.1 by Andrew Bennetts
Update to current hpss branch? Fix lots of test failures.
1568
    @needs_read_lock
1569
    def get_revisions(self, revision_ids):
1570
        self._ensure_real()
1571
        return self._real_repository.get_revisions(revision_ids)
1572
1573
    def supports_rich_root(self):
4053.1.4 by Robert Collins
Move the fetch control attributes from Repository to RepositoryFormat.
1574
        return self._format.rich_root_data
2018.14.1 by Andrew Bennetts
Update to current hpss branch? Fix lots of test failures.
1575
2018.5.83 by Andrew Bennetts
Fix some test failures caused by the switch from unicode to UTF-8-encoded strs for revision IDs.
1576
    def iter_reverse_revision_history(self, revision_id):
1577
        self._ensure_real()
1578
        return self._real_repository.iter_reverse_revision_history(revision_id)
1579
2018.5.96 by Andrew Bennetts
Merge from bzr.dev, resolving the worst of the semantic conflicts, but there's
1580
    @property
1581
    def _serializer(self):
4053.1.4 by Robert Collins
Move the fetch control attributes from Repository to RepositoryFormat.
1582
        return self._format._serializer
2018.5.96 by Andrew Bennetts
Merge from bzr.dev, resolving the worst of the semantic conflicts, but there's
1583
2018.5.97 by Andrew Bennetts
Fix more tests.
1584
    def store_revision_signature(self, gpg_strategy, plaintext, revision_id):
1585
        self._ensure_real()
1586
        return self._real_repository.store_revision_signature(
1587
            gpg_strategy, plaintext, revision_id)
1588
2996.2.8 by Aaron Bentley
Fix add_signature discrepancies
1589
    def add_signature_text(self, revision_id, signature):
2996.2.3 by Aaron Bentley
Add tests for install_revisions and add_signature
1590
        self._ensure_real()
2996.2.8 by Aaron Bentley
Fix add_signature discrepancies
1591
        return self._real_repository.add_signature_text(revision_id, signature)
2996.2.3 by Aaron Bentley
Add tests for install_revisions and add_signature
1592
2018.5.97 by Andrew Bennetts
Fix more tests.
1593
    def has_signature_for_revision_id(self, revision_id):
1594
        self._ensure_real()
1595
        return self._real_repository.has_signature_for_revision_id(revision_id)
1596
2535.3.45 by Andrew Bennetts
Add item_keys_introduced_by to RemoteRepository.
1597
    def item_keys_introduced_by(self, revision_ids, _files_pb=None):
1598
        self._ensure_real()
1599
        return self._real_repository.item_keys_introduced_by(revision_ids,
1600
            _files_pb=_files_pb)
1601
2819.2.4 by Andrew Bennetts
Add a 'revision_graph_can_have_wrong_parents' method to repository.
1602
    def revision_graph_can_have_wrong_parents(self):
1603
        # The answer depends on the remote repo format.
1604
        self._ensure_real()
1605
        return self._real_repository.revision_graph_can_have_wrong_parents()
1606
2819.2.5 by Andrew Bennetts
Make reconcile abort gracefully if the revision index has bad parents.
1607
    def _find_inconsistent_revision_parents(self):
1608
        self._ensure_real()
1609
        return self._real_repository._find_inconsistent_revision_parents()
1610
1611
    def _check_for_inconsistent_revision_parents(self):
1612
        self._ensure_real()
1613
        return self._real_repository._check_for_inconsistent_revision_parents()
1614
3835.1.17 by Aaron Bentley
Fix stacking bug
1615
    def _make_parents_provider(self, other=None):
3835.1.8 by Aaron Bentley
Make UnstackedParentsProvider manage the cache
1616
        providers = [self._unstacked_provider]
3835.1.17 by Aaron Bentley
Fix stacking bug
1617
        if other is not None:
1618
            providers.insert(0, other)
3835.1.7 by Aaron Bentley
Updates from review
1619
        providers.extend(r._make_parents_provider() for r in
1620
                         self._fallback_repositories)
4379.3.3 by Gary van der Merwe
Rename and add doc string for StackedParentsProvider.
1621
        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.
1622
3842.3.20 by Andrew Bennetts
Re-revert changes from another thread that accidentally got reinstated here.
1623
    def _serialise_search_recipe(self, recipe):
1624
        """Serialise a graph search recipe.
1625
1626
        :param recipe: A search recipe (start, stop, count).
1627
        :return: Serialised bytes.
1628
        """
4152.1.2 by Robert Collins
Add streaming from a stacked branch when the sort order is compatible with doing so.
1629
        start_keys = ' '.join(recipe[1])
1630
        stop_keys = ' '.join(recipe[2])
1631
        count = str(recipe[3])
3842.3.20 by Andrew Bennetts
Re-revert changes from another thread that accidentally got reinstated here.
1632
        return '\n'.join((start_keys, stop_keys, count))
1633
4070.9.5 by Andrew Bennetts
Better wire protocol: don't shoehorn MiniSearchResult serialisation into previous serialisation format.
1634
    def _serialise_search_result(self, search_result):
4070.9.14 by Andrew Bennetts
Tweaks requested by Robert's review.
1635
        if isinstance(search_result, graph.PendingAncestryResult):
1636
            parts = ['ancestry-of']
1637
            parts.extend(search_result.heads)
4070.9.5 by Andrew Bennetts
Better wire protocol: don't shoehorn MiniSearchResult serialisation into previous serialisation format.
1638
        else:
1639
            recipe = search_result.get_recipe()
4152.1.2 by Robert Collins
Add streaming from a stacked branch when the sort order is compatible with doing so.
1640
            parts = [recipe[0], self._serialise_search_recipe(recipe)]
4070.9.5 by Andrew Bennetts
Better wire protocol: don't shoehorn MiniSearchResult serialisation into previous serialisation format.
1641
        return '\n'.join(parts)
1642
3842.3.2 by Andrew Bennetts
Revert the RemoteVersionedFiles.get_parent_map implementation, leaving just the skeleton of RemoteVersionedFiles.
1643
    def autopack(self):
1644
        path = self.bzrdir._path_for_remote_call(self._client)
1645
        try:
1646
            response = self._call('PackRepository.autopack', path)
1647
        except errors.UnknownSmartMethod:
1648
            self._ensure_real()
1649
            self._real_repository._pack_collection.autopack()
1650
            return
4145.1.2 by Robert Collins
Add a refresh_data method on Repository allowing cleaner handling of insertions into RemoteRepository objects with _real_repository instances.
1651
        self.refresh_data()
3842.3.2 by Andrew Bennetts
Revert the RemoteVersionedFiles.get_parent_map implementation, leaving just the skeleton of RemoteVersionedFiles.
1652
        if response[0] != 'ok':
1653
            raise errors.UnexpectedSmartServerResponse(response)
1654
1655
4022.1.6 by Robert Collins
Cherrypick and polish the RemoteSink for streaming push.
1656
class RemoteStreamSink(repository.StreamSink):
1657
4476.3.15 by Andrew Bennetts
Partially working fallback for pre-1.17 servers.
1658
    def __init__(self, target_repo):
1659
        repository.StreamSink.__init__(self, target_repo)
1660
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.
1661
    def _insert_real(self, stream, src_format, resume_tokens):
4022.1.6 by Robert Collins
Cherrypick and polish the RemoteSink for streaming push.
1662
        self.target_repo._ensure_real()
1663
        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.
1664
        result = sink.insert_stream(stream, src_format, resume_tokens)
4029.2.1 by Robert Collins
Support streaming push to stacked branches.
1665
        if not result:
1666
            self.target_repo.autopack()
1667
        return result
4022.1.6 by Robert Collins
Cherrypick and polish the RemoteSink for streaming push.
1668
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.
1669
    def insert_stream(self, stream, src_format, resume_tokens):
4144.3.2 by Andrew Bennetts
Use Repository.insert_stream_locked if there is a lock_token for the remote repo.
1670
        target = self.target_repo
4307.2.4 by Robert Collins
Enable caching of negative revision lookups in RemoteRepository write locks when no _real_repository has been constructed.
1671
        target._unstacked_provider.missing_keys.clear()
4476.3.21 by Andrew Bennetts
Clarify some code and comments, and s/1.17/1.18/ in a few places.
1672
        candidate_calls = [('Repository.insert_stream_1.18', (1, 18))]
4144.3.2 by Andrew Bennetts
Use Repository.insert_stream_locked if there is a lock_token for the remote repo.
1673
        if target._lock_token:
4476.3.15 by Andrew Bennetts
Partially working fallback for pre-1.17 servers.
1674
            candidate_calls.append(('Repository.insert_stream_locked', (1, 14)))
1675
            lock_args = (target._lock_token or '',)
4144.3.2 by Andrew Bennetts
Use Repository.insert_stream_locked if there is a lock_token for the remote repo.
1676
        else:
4476.3.15 by Andrew Bennetts
Partially working fallback for pre-1.17 servers.
1677
            candidate_calls.append(('Repository.insert_stream', (1, 13)))
1678
            lock_args = ()
4144.3.2 by Andrew Bennetts
Use Repository.insert_stream_locked if there is a lock_token for the remote repo.
1679
        client = target._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)
1680
        medium = client._medium
4144.3.2 by Andrew Bennetts
Use Repository.insert_stream_locked if there is a lock_token for the remote repo.
1681
        path = target.bzrdir._path_for_remote_call(client)
4476.3.15 by Andrew Bennetts
Partially working fallback for pre-1.17 servers.
1682
        found_verb = False
1683
        for verb, required_version in candidate_calls:
1684
            if medium._is_remote_before(required_version):
1685
                continue
4060.1.4 by Robert Collins
Streaming fetch from remote servers.
1686
            byte_stream = smart_repo._stream_to_byte_stream([], src_format)
4029.2.1 by Robert Collins
Support streaming push to stacked branches.
1687
            try:
1688
                response = client.call_with_body_stream(
4476.3.15 by Andrew Bennetts
Partially working fallback for pre-1.17 servers.
1689
                    (verb, path, '') + lock_args, byte_stream)
4029.2.1 by Robert Collins
Support streaming push to stacked branches.
1690
            except errors.UnknownSmartMethod:
4144.3.2 by Andrew Bennetts
Use Repository.insert_stream_locked if there is a lock_token for the remote repo.
1691
                medium._remember_remote_is_before(required_version)
4476.3.15 by Andrew Bennetts
Partially working fallback for pre-1.17 servers.
1692
            else:
1693
                found_verb = True
1694
                break
1695
        if not found_verb:
1696
            # Have to use VFS.
1697
            return self._insert_real(stream, src_format, resume_tokens)
1698
        self._last_inv_record = None
1699
        self._last_substream = None
4476.3.21 by Andrew Bennetts
Clarify some code and comments, and s/1.17/1.18/ in a few places.
1700
        if required_version < (1, 18):
4476.3.15 by Andrew Bennetts
Partially working fallback for pre-1.17 servers.
1701
            # Remote side doesn't support inventory deltas.
1702
            stream = self._stop_stream_if_inventory_delta(stream)
4060.1.4 by Robert Collins
Streaming fetch from remote servers.
1703
        byte_stream = smart_repo._stream_to_byte_stream(
1704
            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.
1705
        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)
1706
        response = client.call_with_body_stream(
4476.3.15 by Andrew Bennetts
Partially working fallback for pre-1.17 servers.
1707
            (verb, path, resume_tokens) + lock_args, byte_stream)
4029.2.1 by Robert Collins
Support streaming push to stacked branches.
1708
        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)
1709
            raise errors.UnexpectedSmartServerResponse(response)
4476.3.15 by Andrew Bennetts
Partially working fallback for pre-1.17 servers.
1710
        if self._last_inv_record is not None:
4476.3.21 by Andrew Bennetts
Clarify some code and comments, and s/1.17/1.18/ in a few places.
1711
            # The stream included an inventory-delta record, but the remote
1712
            # side isn't new enough to support them.  So we need to send the
1713
            # rest of the stream via VFS.
1714
            return self._resume_stream_with_vfs(response, src_format)
4029.2.1 by Robert Collins
Support streaming push to stacked branches.
1715
        if response[0][0] == 'missing-basis':
1716
            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.
1717
            resume_tokens = tokens
4257.3.3 by Andrew Bennetts
missing_keys from sink.insert_stream should be a set, not a tuple.
1718
            return resume_tokens, set(missing_keys)
4029.2.1 by Robert Collins
Support streaming push to stacked branches.
1719
        else:
4145.1.2 by Robert Collins
Add a refresh_data method on Repository allowing cleaner handling of insertions into RemoteRepository objects with _real_repository instances.
1720
            self.target_repo.refresh_data()
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.
1721
            return [], set()
4032.1.1 by John Arbash Meinel
Merge the removal of all trailing whitespace, and resolve conflicts.
1722
4476.3.21 by Andrew Bennetts
Clarify some code and comments, and s/1.17/1.18/ in a few places.
1723
    def _resume_stream_with_vfs(self, response, src_format):
1724
        """Resume sending a stream via VFS, first resending the record and
1725
        substream that couldn't be sent via an insert_stream verb.
1726
        """
4476.3.15 by Andrew Bennetts
Partially working fallback for pre-1.17 servers.
1727
        if response[0][0] == 'missing-basis':
1728
            tokens, missing_keys = bencode.bdecode_as_tuple(response[0][1])
1729
            # Ignore missing_keys, we haven't finished inserting yet
1730
        else:
1731
            tokens = []
4476.3.21 by Andrew Bennetts
Clarify some code and comments, and s/1.17/1.18/ in a few places.
1732
        def resume_substream():
1733
            # First yield the record we stopped at.
1734
            yield self._last_inv_record
1735
            self._last_inv_record = None
1736
            # Then yield the rest of the substream that was interrupted.
1737
            for record in self._last_substream:
1738
                yield record
1739
            self._last_substream = None
4476.3.15 by Andrew Bennetts
Partially working fallback for pre-1.17 servers.
1740
        def resume_stream():
4476.3.21 by Andrew Bennetts
Clarify some code and comments, and s/1.17/1.18/ in a few places.
1741
            # Finish sending the interrupted substream
4476.3.15 by Andrew Bennetts
Partially working fallback for pre-1.17 servers.
1742
            yield ('inventories', resume_substream())
4476.3.21 by Andrew Bennetts
Clarify some code and comments, and s/1.17/1.18/ in a few places.
1743
            # Then simply continue sending the rest of the stream.
4476.3.15 by Andrew Bennetts
Partially working fallback for pre-1.17 servers.
1744
            for substream_kind, substream in self._last_stream:
1745
                yield substream_kind, substream
1746
        return self._insert_real(resume_stream(), src_format, tokens)
1747
1748
    def _stop_stream_if_inventory_delta(self, stream):
4476.3.21 by Andrew Bennetts
Clarify some code and comments, and s/1.17/1.18/ in a few places.
1749
        """Normally this just lets the original stream pass-through unchanged.
1750
1751
        However if any 'inventories' substream includes an inventory-delta
1752
        record it will stop streaming, and store the interrupted record,
1753
        substream and stream in self._last_inv_record, self._last_substream and
1754
        self._last_stream so that the stream can be resumed by
1755
        _resume_stream_with_vfs.
1756
        """
4476.3.15 by Andrew Bennetts
Partially working fallback for pre-1.17 servers.
1757
        def filter_inv_substream(inv_substream):
1758
            substream_iter = iter(inv_substream)
1759
            for record in substream_iter:
1760
                if record.storage_kind == 'inventory-delta':
1761
                    self._last_inv_record = record
1762
                    self._last_substream = substream_iter
1763
                    return
1764
                else:
1765
                    yield record
1766
                    
1767
        stream_iter = iter(stream)
1768
        for substream_kind, substream in stream_iter:
1769
            if substream_kind == 'inventories':
1770
                yield substream_kind, filter_inv_substream(substream)
1771
                if self._last_inv_record is not None:
1772
                    self._last_stream = stream_iter
1773
                    return
1774
            else:
1775
                yield substream_kind, substream
1776
            
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)
1777
4060.1.3 by Robert Collins
Implement the separate source component for fetch - repository.StreamSource.
1778
class RemoteStreamSource(repository.StreamSource):
1779
    """Stream data from a remote server."""
1780
4060.1.4 by Robert Collins
Streaming fetch from remote servers.
1781
    def get_stream(self, search):
4152.1.2 by Robert Collins
Add streaming from a stacked branch when the sort order is compatible with doing so.
1782
        if (self.from_repository._fallback_repositories and
1783
            self.to_format._fetch_order == 'topological'):
1784
            return self._real_stream(self.from_repository, search)
1785
        return self.missing_parents_chain(search, [self.from_repository] +
1786
            self.from_repository._fallback_repositories)
1787
4476.3.16 by Andrew Bennetts
Only make inv deltas against bases we've already sent, and other tweaks.
1788
    def get_stream_for_missing_keys(self, missing_keys):
1789
        self.from_repository._ensure_real()
1790
        real_repo = self.from_repository._real_repository
1791
        real_source = real_repo._get_source(self.to_format)
1792
        return real_source.get_stream_for_missing_keys(missing_keys)
1793
4152.1.2 by Robert Collins
Add streaming from a stacked branch when the sort order is compatible with doing so.
1794
    def _real_stream(self, repo, search):
1795
        """Get a stream for search from repo.
1796
        
1797
        This never called RemoteStreamSource.get_stream, and is a heler
1798
        for RemoteStreamSource._get_stream to allow getting a stream 
1799
        reliably whether fallback back because of old servers or trying
1800
        to stream from a non-RemoteRepository (which the stacked support
1801
        code will do).
1802
        """
1803
        source = repo._get_source(self.to_format)
1804
        if isinstance(source, RemoteStreamSource):
1805
            return repository.StreamSource.get_stream(source, search)
1806
        return source.get_stream(search)
1807
1808
    def _get_stream(self, repo, search):
1809
        """Core worker to get a stream from repo for search.
1810
1811
        This is used by both get_stream and the stacking support logic. It
1812
        deliberately gets a stream for repo which does not need to be
1813
        self.from_repository. In the event that repo is not Remote, or
1814
        cannot do a smart stream, a fallback is made to the generic
1815
        repository._get_stream() interface, via self._real_stream.
1816
1817
        In the event of stacking, streams from _get_stream will not
1818
        contain all the data for search - this is normal (see get_stream).
1819
1820
        :param repo: A repository.
1821
        :param search: A search.
1822
        """
1823
        # Fallbacks may be non-smart
1824
        if not isinstance(repo, RemoteRepository):
1825
            return self._real_stream(repo, search)
4060.1.4 by Robert Collins
Streaming fetch from remote servers.
1826
        client = repo._client
1827
        medium = client._medium
1828
        if medium._is_remote_before((1, 13)):
4152.1.2 by Robert Collins
Add streaming from a stacked branch when the sort order is compatible with doing so.
1829
            # streaming was added in 1.13
1830
            return self._real_stream(repo, search)
4060.1.4 by Robert Collins
Streaming fetch from remote servers.
1831
        path = repo.bzrdir._path_for_remote_call(client)
1832
        try:
4070.9.5 by Andrew Bennetts
Better wire protocol: don't shoehorn MiniSearchResult serialisation into previous serialisation format.
1833
            search_bytes = repo._serialise_search_result(search)
4060.1.4 by Robert Collins
Streaming fetch from remote servers.
1834
            response = repo._call_with_body_bytes_expecting_body(
4060.1.5 by Robert Collins
Verb change name requested by Andrew.
1835
                'Repository.get_stream',
4070.9.5 by Andrew Bennetts
Better wire protocol: don't shoehorn MiniSearchResult serialisation into previous serialisation format.
1836
                (path, self.to_format.network_name()), search_bytes)
4060.1.4 by Robert Collins
Streaming fetch from remote servers.
1837
            response_tuple, response_handler = response
1838
        except errors.UnknownSmartMethod:
1839
            medium._remember_remote_is_before((1,13))
4152.1.2 by Robert Collins
Add streaming from a stacked branch when the sort order is compatible with doing so.
1840
            return self._real_stream(repo, search)
4060.1.4 by Robert Collins
Streaming fetch from remote servers.
1841
        if response_tuple[0] != 'ok':
1842
            raise errors.UnexpectedSmartServerResponse(response_tuple)
1843
        byte_stream = response_handler.read_streamed_body()
1844
        src_format, stream = smart_repo._byte_stream_to_stream(byte_stream)
1845
        if src_format.network_name() != repo._format.network_name():
1846
            raise AssertionError(
1847
                "Mismatched RemoteRepository and stream src %r, %r" % (
1848
                src_format.network_name(), repo._format.network_name()))
1849
        return stream
1850
4152.1.2 by Robert Collins
Add streaming from a stacked branch when the sort order is compatible with doing so.
1851
    def missing_parents_chain(self, search, sources):
1852
        """Chain multiple streams together to handle stacking.
1853
1854
        :param search: The overall search to satisfy with streams.
1855
        :param sources: A list of Repository objects to query.
1856
        """
1857
        self.serialiser = self.to_format._serializer
1858
        self.seen_revs = set()
1859
        self.referenced_revs = set()
1860
        # If there are heads in the search, or the key count is > 0, we are not
1861
        # done.
1862
        while not search.is_empty() and len(sources) > 1:
1863
            source = sources.pop(0)
1864
            stream = self._get_stream(source, search)
1865
            for kind, substream in stream:
1866
                if kind != 'revisions':
1867
                    yield kind, substream
1868
                else:
1869
                    yield kind, self.missing_parents_rev_handler(substream)
1870
            search = search.refine(self.seen_revs, self.referenced_revs)
1871
            self.seen_revs = set()
1872
            self.referenced_revs = set()
1873
        if not search.is_empty():
1874
            for kind, stream in self._get_stream(sources[0], search):
1875
                yield kind, stream
1876
1877
    def missing_parents_rev_handler(self, substream):
1878
        for content in substream:
1879
            revision_bytes = content.get_bytes_as('fulltext')
1880
            revision = self.serialiser.read_revision_from_string(revision_bytes)
1881
            self.seen_revs.add(content.key[-1])
1882
            self.referenced_revs.update(revision.parent_ids)
1883
            yield content
1884
4060.1.3 by Robert Collins
Implement the separate source component for fetch - repository.StreamSource.
1885
2018.5.127 by Andrew Bennetts
Fix most of the lockable_files tests for RemoteBranchLockableFiles.
1886
class RemoteBranchLockableFiles(LockableFiles):
2018.5.59 by Robert Collins
Get BranchConfig working somewhat on RemoteBranches (Robert Collins, Vincent Ladeuil).
1887
    """A 'LockableFiles' implementation that talks to a smart server.
3943.8.1 by Marius Kruger
remove all trailing whitespace from bzr source
1888
2018.5.59 by Robert Collins
Get BranchConfig working somewhat on RemoteBranches (Robert Collins, Vincent Ladeuil).
1889
    This is not a public interface class.
1890
    """
1891
1892
    def __init__(self, bzrdir, _client):
1893
        self.bzrdir = bzrdir
1894
        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.
1895
        self._need_find_modes = True
2018.5.133 by Andrew Bennetts
All TestLockableFiles_RemoteLockDir tests passing.
1896
        LockableFiles.__init__(
2018.5.163 by Andrew Bennetts
Deal with various review comments from Robert.
1897
            self, bzrdir.get_branch_transport(None),
2018.5.133 by Andrew Bennetts
All TestLockableFiles_RemoteLockDir tests passing.
1898
            'lock', lockdir.LockDir)
2018.5.59 by Robert Collins
Get BranchConfig working somewhat on RemoteBranches (Robert Collins, Vincent Ladeuil).
1899
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.
1900
    def _find_modes(self):
1901
        # RemoteBranches don't let the client set the mode of control files.
1902
        self._dir_mode = None
1903
        self._file_mode = None
1904
2018.5.59 by Robert Collins
Get BranchConfig working somewhat on RemoteBranches (Robert Collins, Vincent Ladeuil).
1905
1752.2.31 by Martin Pool
[broken] some support for write operations over hpss
1906
class RemoteBranchFormat(branch.BranchFormat):
1907
4084.2.1 by Robert Collins
Make accessing a branch.tags.get_tag_dict use a smart[er] method rather than VFS calls and real objects.
1908
    def __init__(self, network_name=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.
1909
        super(RemoteBranchFormat, self).__init__()
1910
        self._matchingbzrdir = RemoteBzrDirFormat()
1911
        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.
1912
        self._custom_format = None
4084.2.1 by Robert Collins
Make accessing a branch.tags.get_tag_dict use a smart[er] method rather than VFS calls and real objects.
1913
        self._network_name = network_name
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.
1914
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.
1915
    def __eq__(self, other):
3943.8.1 by Marius Kruger
remove all trailing whitespace from bzr source
1916
        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.
1917
            self.__dict__ == other.__dict__)
1918
4084.2.1 by Robert Collins
Make accessing a branch.tags.get_tag_dict use a smart[er] method rather than VFS calls and real objects.
1919
    def _ensure_real(self):
1920
        if self._custom_format is None:
1921
            self._custom_format = branch.network_format_registry.get(
1922
                self._network_name)
1923
2018.5.60 by Robert Collins
More missing methods from RemoteBranch and RemoteRepository to let 'info' get further.
1924
    def get_format_description(self):
1925
        return 'Remote BZR Branch'
1926
4032.3.1 by Robert Collins
Add a BranchFormat.network_name() method as preparation for creating branches via RPC calls.
1927
    def network_name(self):
1928
        return self._network_name
1929
4160.2.6 by Andrew Bennetts
Add ignore_fallbacks flag.
1930
    def open(self, a_bzrdir, ignore_fallbacks=False):
1931
        return a_bzrdir.open_branch(ignore_fallbacks=ignore_fallbacks)
1752.2.52 by Andrew Bennetts
Flesh out more Remote* methods needed to open and initialise remote branches/trees/repositories.
1932
4032.3.2 by Robert Collins
Create and use a RPC call to create branches on bzr servers rather than using VFS calls.
1933
    def _vfs_initialize(self, a_bzrdir):
1934
        # Initialisation when using a local bzrdir object, or a non-vfs init
1935
        # method is not available on the server.
1936
        # self._custom_format is always set - the start of initialize ensures
1937
        # that.
1938
        if isinstance(a_bzrdir, RemoteBzrDir):
1939
            a_bzrdir._ensure_real()
1940
            result = self._custom_format.initialize(a_bzrdir._real_bzrdir)
1941
        else:
1942
            # We assume the bzrdir is parameterised; it may not be.
1943
            result = self._custom_format.initialize(a_bzrdir)
1944
        if (isinstance(a_bzrdir, RemoteBzrDir) and
1945
            not isinstance(result, RemoteBranch)):
1946
            result = RemoteBranch(a_bzrdir, a_bzrdir.find_repository(), result)
1947
        return result
1948
1752.2.52 by Andrew Bennetts
Flesh out more Remote* methods needed to open and initialise remote branches/trees/repositories.
1949
    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.
1950
        # 1) get the network name to use.
1951
        if self._custom_format:
1952
            network_name = self._custom_format.network_name()
1953
        else:
1954
            # Select the current bzrlib default and ask for that.
1955
            reference_bzrdir_format = bzrdir.format_registry.get('default')()
1956
            reference_format = reference_bzrdir_format.get_branch_format()
1957
            self._custom_format = reference_format
1958
            network_name = reference_format.network_name()
1959
        # 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.
1960
        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.
1961
            return self._vfs_initialize(a_bzrdir)
1962
        medium = a_bzrdir._client._medium
1963
        if medium._is_remote_before((1, 13)):
1964
            return self._vfs_initialize(a_bzrdir)
1965
        # Creating on a remote bzr dir.
1966
        # 2) try direct creation via RPC
1967
        path = a_bzrdir._path_for_remote_call(a_bzrdir._client)
1968
        verb = 'BzrDir.create_branch'
1969
        try:
1970
            response = a_bzrdir._call(verb, path, network_name)
1971
        except errors.UnknownSmartMethod:
1972
            # Fallback - use vfs methods
4094.1.1 by Andrew Bennetts
Add some medium._remember_is_before((1, 13)) calls.
1973
            medium._remember_remote_is_before((1, 13))
4032.3.2 by Robert Collins
Create and use a RPC call to create branches on bzr servers rather than using VFS calls.
1974
            return self._vfs_initialize(a_bzrdir)
1975
        if response[0] != 'ok':
1976
            raise errors.UnexpectedSmartServerResponse(response)
1977
        # Turn the response into a RemoteRepository object.
4084.2.1 by Robert Collins
Make accessing a branch.tags.get_tag_dict use a smart[er] method rather than VFS calls and real objects.
1978
        format = RemoteBranchFormat(network_name=response[1])
4032.3.2 by Robert Collins
Create and use a RPC call to create branches on bzr servers rather than using VFS calls.
1979
        repo_format = response_tuple_to_repo_format(response[3:])
1980
        if response[2] == '':
1981
            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.
1982
        else:
4032.3.2 by Robert Collins
Create and use a RPC call to create branches on bzr servers rather than using VFS calls.
1983
            repo_bzrdir = RemoteBzrDir(
1984
                a_bzrdir.root_transport.clone(response[2]), a_bzrdir._format,
1985
                a_bzrdir._client)
1986
        remote_repo = RemoteRepository(repo_bzrdir, repo_format)
1987
        remote_branch = RemoteBranch(a_bzrdir, remote_repo,
1988
            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.
1989
        # XXX: We know this is a new branch, so it must have revno 0, revid
1990
        # NULL_REVISION. Creating the branch locked would make this be unable
1991
        # to be wrong; here its simply very unlikely to be wrong. RBC 20090225
1992
        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.
1993
        return remote_branch
1752.2.31 by Martin Pool
[broken] some support for write operations over hpss
1994
4084.2.1 by Robert Collins
Make accessing a branch.tags.get_tag_dict use a smart[er] method rather than VFS calls and real objects.
1995
    def make_tags(self, branch):
1996
        self._ensure_real()
1997
        return self._custom_format.make_tags(branch)
1998
2696.3.6 by Martin Pool
Mark RemoteBranch as (possibly) supporting tags
1999
    def supports_tags(self):
2000
        # Remote branches might support tags, but we won't know until we
2001
        # access the real remote branch.
4084.2.1 by Robert Collins
Make accessing a branch.tags.get_tag_dict use a smart[er] method rather than VFS calls and real objects.
2002
        self._ensure_real()
2003
        return self._custom_format.supports_tags()
2696.3.6 by Martin Pool
Mark RemoteBranch as (possibly) supporting tags
2004
4103.2.2 by Andrew Bennetts
Fix RemoteBranchFormat.supports_stacking()
2005
    def supports_stacking(self):
2006
        self._ensure_real()
2007
        return self._custom_format.supports_stacking()
2008
4301.3.3 by Andrew Bennetts
Move check onto base Branch class, and add a supports_set_append_revisions_only method to BranchFormat, as suggested by Robert.
2009
    def supports_set_append_revisions_only(self):
2010
        self._ensure_real()
2011
        return self._custom_format.supports_set_append_revisions_only()
2012
1752.2.31 by Martin Pool
[broken] some support for write operations over hpss
2013
3786.2.3 by Andrew Bennetts
Remove duplicated 'call & translate errors' code in bzrlib.remote.
2014
class RemoteBranch(branch.Branch, _RpcHelper):
1752.2.31 by Martin Pool
[broken] some support for write operations over hpss
2015
    """Branch stored on a server accessed by HPSS RPC.
2016
2017
    At the moment most operations are mapped down to simple file operations.
2018
    """
1752.2.30 by Martin Pool
Start adding a RemoteBzrDir, etc
2019
2018.5.51 by Wouter van Heyst
Test and implement RemoteBranch.last_revision_info()
2020
    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.
2021
        _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.
2022
        """Create a RemoteBranch instance.
2023
2024
        :param real_branch: An optional local implementation of the branch
2025
            format, usually accessing the data via the VFS.
2018.5.51 by Wouter van Heyst
Test and implement RemoteBranch.last_revision_info()
2026
        :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.
2027
        :param format: A RemoteBranchFormat object, None to create one
2028
            automatically. If supplied it should have a network_name already
2029
            supplied.
2030
        :param setup_stacking: If True make an RPC call to determine the
2031
            stacked (or not) status of the branch. If False assume the branch
2032
            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.
2033
        """
2018.5.163 by Andrew Bennetts
Deal with various review comments from Robert.
2034
        # We intentionally don't call the parent class's __init__, because it
2035
        # will try to assign to self.tags, which is a property in this subclass.
2036
        # And the parent's __init__ doesn't do much anyway.
1752.2.64 by Andrew Bennetts
Improve how RemoteBzrDir.open_branch works to handle references and not double-open repositories.
2037
        self.bzrdir = remote_bzrdir
2018.5.51 by Wouter van Heyst
Test and implement RemoteBranch.last_revision_info()
2038
        if _client is not None:
2039
            self._client = _client
2040
        else:
3313.2.1 by Andrew Bennetts
Change _SmartClient's API to accept a medium and a base, rather than a _SharedConnection.
2041
            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.
2042
        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.
2043
        if real_branch is not None:
2044
            self._real_branch = real_branch
2018.5.79 by Andrew Bennetts
Implement RemoteBranch.lock_write/unlock as smart operations.
2045
            # Give the remote repository the matching real repo.
2018.5.97 by Andrew Bennetts
Fix more tests.
2046
            real_repo = self._real_branch.repository
2047
            if isinstance(real_repo, RemoteRepository):
2048
                real_repo._ensure_real()
2049
                real_repo = real_repo._real_repository
2050
            self.repository._set_real_repository(real_repo)
2018.5.79 by Andrew Bennetts
Implement RemoteBranch.lock_write/unlock as smart operations.
2051
            # Give the branch the remote repository to let fast-pathing happen.
2052
            self._real_branch.repository = self.repository
2018.5.70 by Robert Collins
Only try to get real repositories when an operation requires them.
2053
        else:
2054
            self._real_branch = None
4031.3.3 by Matt Nordhoff
Review tweaks from Ben Finney
2055
        # Fill out expected attributes of branch for bzrlib API users.
4419.2.2 by Andrew Bennetts
Read lock branch_from in cmd_pull, avoids refetching last_revision_info and so reduces test_pull acceptance ratchet.
2056
        self._clear_cached_state()
2018.5.55 by Robert Collins
Give RemoteBranch a base url in line with the Branch protocol.
2057
        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.
2058
        self._control_files = None
2018.5.79 by Andrew Bennetts
Implement RemoteBranch.lock_write/unlock as smart operations.
2059
        self._lock_mode = None
2060
        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.
2061
        self._repo_lock_token = None
2018.5.79 by Andrew Bennetts
Implement RemoteBranch.lock_write/unlock as smart operations.
2062
        self._lock_count = 0
2063
        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.
2064
        # Setup a format: note that we cannot call _ensure_real until all the
2065
        # attributes above are set: This code cannot be moved higher up in this
2066
        # function.
2067
        if format is None:
2068
            self._format = RemoteBranchFormat()
2069
            if real_branch is not None:
2070
                self._format._network_name = \
2071
                    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.
2072
        else:
4032.3.2 by Robert Collins
Create and use a RPC call to create branches on bzr servers rather than using VFS calls.
2073
            self._format = format
4084.2.1 by Robert Collins
Make accessing a branch.tags.get_tag_dict use a smart[er] method rather than VFS calls and real objects.
2074
        if not self._format._network_name:
2075
            # Did not get from open_branchV2 - old server.
2076
            self._ensure_real()
2077
            self._format._network_name = \
2078
                self._real_branch._format.network_name()
2079
        self.tags = self._format.make_tags(self)
3681.1.2 by Robert Collins
Adjust for trunk.
2080
        # 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)
2081
        hooks = branch.Branch.hooks['open']
2082
        for hook in hooks:
2083
            hook(self)
4419.1.3 by Andrew Bennetts
Quick fix by using self._ensure_real.
2084
        self._is_stacked = False
4032.3.2 by Robert Collins
Create and use a RPC call to create branches on bzr servers rather than using VFS calls.
2085
        if setup_stacking:
2086
            self._setup_stacking()
3691.2.1 by Martin Pool
RemoteBranch must configure stacking into the repository
2087
2088
    def _setup_stacking(self):
2089
        # 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
2090
        # the vfs branch.
3691.2.1 by Martin Pool
RemoteBranch must configure stacking into the repository
2091
        try:
2092
            fallback_url = self.get_stacked_on_url()
2093
        except (errors.NotStacked, errors.UnstackableBranchFormat,
2094
            errors.UnstackableRepositoryFormat), e:
3691.2.7 by Martin Pool
FakeClient can know what calls to expect
2095
            return
4419.1.3 by Andrew Bennetts
Quick fix by using self._ensure_real.
2096
        self._is_stacked = True
4379.2.2 by John Arbash Meinel
Change the Repository.add_fallback_repository() contract slightly.
2097
        self._activate_fallback_location(fallback_url)
1752.2.64 by Andrew Bennetts
Improve how RemoteBzrDir.open_branch works to handle references and not double-open repositories.
2098
4226.1.5 by Robert Collins
Reinstate the use of the Branch.get_config_file verb.
2099
    def _get_config(self):
2100
        return RemoteBranchConfig(self)
2101
3407.2.17 by Martin Pool
better name: _get_real_transport
2102
    def _get_real_transport(self):
3407.2.16 by Martin Pool
Remove RemoteBranch reliance on control_files._transport
2103
        # if we try vfs access, return the real branch's vfs transport
2104
        self._ensure_real()
2105
        return self._real_branch._transport
2106
3407.2.17 by Martin Pool
better name: _get_real_transport
2107
    _transport = property(_get_real_transport)
3407.2.16 by Martin Pool
Remove RemoteBranch reliance on control_files._transport
2108
2477.1.1 by Martin Pool
Add RemoteBranch repr
2109
    def __str__(self):
2110
        return "%s(%s)" % (self.__class__.__name__, self.base)
2111
2112
    __repr__ = __str__
2113
2018.5.70 by Robert Collins
Only try to get real repositories when an operation requires them.
2114
    def _ensure_real(self):
2115
        """Ensure that there is a _real_branch set.
2116
2018.5.163 by Andrew Bennetts
Deal with various review comments from Robert.
2117
        Used before calls to self._real_branch.
2018.5.70 by Robert Collins
Only try to get real repositories when an operation requires them.
2118
        """
3407.2.16 by Martin Pool
Remove RemoteBranch reliance on control_files._transport
2119
        if self._real_branch is None:
3376.2.4 by Martin Pool
Remove every assert statement from bzrlib!
2120
            if not vfs.vfs_enabled():
2121
                raise AssertionError('smart server vfs must be enabled '
2122
                    'to use vfs implementation')
2018.5.70 by Robert Collins
Only try to get real repositories when an operation requires them.
2123
            self.bzrdir._ensure_real()
2124
            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.
2125
            if self.repository._real_repository is None:
2126
                # Give the remote repository the matching real repo.
2127
                real_repo = self._real_branch.repository
2128
                if isinstance(real_repo, RemoteRepository):
2129
                    real_repo._ensure_real()
2130
                    real_repo = real_repo._real_repository
2131
                self.repository._set_real_repository(real_repo)
2132
            # Give the real branch the remote repository to let fast-pathing
2133
            # happen.
2018.5.70 by Robert Collins
Only try to get real repositories when an operation requires them.
2134
            self._real_branch.repository = self.repository
2018.14.1 by Andrew Bennetts
Update to current hpss branch? Fix lots of test failures.
2135
            if self._lock_mode == 'r':
2136
                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.
2137
            elif self._lock_mode == 'w':
2138
                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.
2139
3533.3.1 by Andrew Bennetts
Remove duplication of error translation in bzrlib/remote.py.
2140
    def _translate_error(self, err, **context):
2141
        self.repository._translate_error(err, branch=self, **context)
2142
3441.5.1 by Andrew Bennetts
Avoid necessarily calling get_parent_map when pushing.
2143
    def _clear_cached_state(self):
2144
        super(RemoteBranch, self)._clear_cached_state()
3441.5.5 by Andrew Bennetts
Some small tweaks and comments.
2145
        if self._real_branch is not None:
2146
            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.
2147
2148
    def _clear_cached_state_of_remote_branch_only(self):
2149
        """Like _clear_cached_state, but doesn't clear the cache of
2150
        self._real_branch.
2151
2152
        This is useful when falling back to calling a method of
2153
        self._real_branch that changes state.  In that case the underlying
2154
        branch changes, so we need to invalidate this RemoteBranch's cache of
2155
        it.  However, there's no need to invalidate the _real_branch's cache
2156
        too, in fact doing so might harm performance.
2157
        """
2158
        super(RemoteBranch, self)._clear_cached_state()
3943.8.1 by Marius Kruger
remove all trailing whitespace from bzr source
2159
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.
2160
    @property
2161
    def control_files(self):
2162
        # Defer actually creating RemoteBranchLockableFiles until its needed,
2163
        # because it triggers an _ensure_real that we otherwise might not need.
2164
        if self._control_files is None:
2165
            self._control_files = RemoteBranchLockableFiles(
2166
                self.bzrdir, self._client)
2167
        return self._control_files
2168
2018.5.166 by Andrew Bennetts
Small changes in response to Aaron's review.
2169
    def _get_checkout_format(self):
2170
        self._ensure_real()
2171
        return self._real_branch._get_checkout_format()
2172
2018.5.60 by Robert Collins
More missing methods from RemoteBranch and RemoteRepository to let 'info' get further.
2173
    def get_physical_lock_status(self):
2174
        """See Branch.get_physical_lock_status()."""
2175
        # 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.
2176
        self._ensure_real()
2018.5.60 by Robert Collins
More missing methods from RemoteBranch and RemoteRepository to let 'info' get further.
2177
        return self._real_branch.get_physical_lock_status()
2178
3537.3.1 by Martin Pool
Rename branch.get_stacked_on to get_stacked_on_url
2179
    def get_stacked_on_url(self):
3221.11.2 by Robert Collins
Create basic stackable branch facility.
2180
        """Get the URL this branch is stacked against.
2181
2182
        :raises NotStacked: If the branch is not stacked.
2183
        :raises UnstackableBranchFormat: If the branch does not support
2184
            stacking.
2185
        :raises UnstackableRepositoryFormat: If the repository does not support
2186
            stacking.
2187
        """
3691.2.12 by Martin Pool
Add test for coping without Branch.get_stacked_on_url
2188
        try:
3786.2.3 by Andrew Bennetts
Remove duplicated 'call & translate errors' code in bzrlib.remote.
2189
            # there may not be a repository yet, so we can't use
2190
            # 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
2191
            response = self._client.call('Branch.get_stacked_on_url',
2192
                self._remote_path())
2193
        except errors.ErrorFromSmartServer, err:
2194
            # there may not be a repository yet, so we can't call through
2195
            # its _translate_error
2196
            _translate_error(err, branch=self)
2197
        except errors.UnknownSmartMethod, err:
2198
            self._ensure_real()
2199
            return self._real_branch.get_stacked_on_url()
3786.2.3 by Andrew Bennetts
Remove duplicated 'call & translate errors' code in bzrlib.remote.
2200
        if response[0] != 'ok':
2201
            raise errors.UnexpectedSmartServerResponse(response)
2202
        return response[1]
3221.11.2 by Robert Collins
Create basic stackable branch facility.
2203
4419.1.3 by Andrew Bennetts
Quick fix by using self._ensure_real.
2204
    def set_stacked_on_url(self, url):
2205
        branch.Branch.set_stacked_on_url(self, url)
2206
        if not url:
2207
            self._is_stacked = False
2208
        else:
2209
            self._is_stacked = True
2210
        
4084.2.1 by Robert Collins
Make accessing a branch.tags.get_tag_dict use a smart[er] method rather than VFS calls and real objects.
2211
    def _vfs_get_tags_bytes(self):
2212
        self._ensure_real()
2213
        return self._real_branch._get_tags_bytes()
2214
2215
    def _get_tags_bytes(self):
2216
        medium = self._client._medium
2217
        if medium._is_remote_before((1, 13)):
2218
            return self._vfs_get_tags_bytes()
2219
        try:
2220
            response = self._call('Branch.get_tags_bytes', self._remote_path())
2221
        except errors.UnknownSmartMethod:
4094.1.1 by Andrew Bennetts
Add some medium._remember_is_before((1, 13)) calls.
2222
            medium._remember_remote_is_before((1, 13))
4084.2.1 by Robert Collins
Make accessing a branch.tags.get_tag_dict use a smart[er] method rather than VFS calls and real objects.
2223
            return self._vfs_get_tags_bytes()
2224
        return response[0]
2225
1752.2.31 by Martin Pool
[broken] some support for write operations over hpss
2226
    def lock_read(self):
3692.1.1 by Andrew Bennetts
Make RemoteBranch.lock_write lock the repository too.
2227
        self.repository.lock_read()
2018.14.1 by Andrew Bennetts
Update to current hpss branch? Fix lots of test failures.
2228
        if not self._lock_mode:
2229
            self._lock_mode = 'r'
2230
            self._lock_count = 1
2231
            if self._real_branch is not None:
2232
                self._real_branch.lock_read()
2233
        else:
2234
            self._lock_count += 1
1752.2.52 by Andrew Bennetts
Flesh out more Remote* methods needed to open and initialise remote branches/trees/repositories.
2235
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).
2236
    def _remote_lock_write(self, token):
2237
        if token is None:
2018.5.79 by Andrew Bennetts
Implement RemoteBranch.lock_write/unlock as smart operations.
2238
            branch_token = repo_token = ''
2239
        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).
2240
            branch_token = token
2241
            repo_token = self.repository.lock_write()
2242
            self.repository.unlock()
3786.2.3 by Andrew Bennetts
Remove duplicated 'call & translate errors' code in bzrlib.remote.
2243
        err_context = {'token': token}
2244
        response = self._call(
2245
            'Branch.lock_write', self._remote_path(), branch_token,
2246
            repo_token or '', **err_context)
3245.4.24 by Andrew Bennetts
Consistently raise errors from the server as ErrorFromSmartServer exceptions.
2247
        if response[0] != 'ok':
2555.1.1 by Martin Pool
Remove use of 'assert False' to raise an exception unconditionally
2248
            raise errors.UnexpectedSmartServerResponse(response)
3245.4.24 by Andrew Bennetts
Consistently raise errors from the server as ErrorFromSmartServer exceptions.
2249
        ok, branch_token, repo_token = response
2250
        return branch_token, repo_token
3943.8.1 by Marius Kruger
remove all trailing whitespace from bzr source
2251
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).
2252
    def lock_write(self, token=None):
2018.5.79 by Andrew Bennetts
Implement RemoteBranch.lock_write/unlock as smart operations.
2253
        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.
2254
            # 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).
2255
            remote_tokens = self._remote_lock_write(token)
2018.5.79 by Andrew Bennetts
Implement RemoteBranch.lock_write/unlock as smart operations.
2256
            self._lock_token, self._repo_lock_token = remote_tokens
3376.2.4 by Martin Pool
Remove every assert statement from bzrlib!
2257
            if not self._lock_token:
2258
                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.
2259
            # 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.
2260
            self.repository.lock_write(
2261
                self._repo_lock_token, _skip_rpc=True)
3692.1.1 by Andrew Bennetts
Make RemoteBranch.lock_write lock the repository too.
2262
2018.5.79 by Andrew Bennetts
Implement RemoteBranch.lock_write/unlock as smart operations.
2263
            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.
2264
                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).
2265
            if token is not None:
2018.5.79 by Andrew Bennetts
Implement RemoteBranch.lock_write/unlock as smart operations.
2266
                self._leave_lock = True
2267
            else:
2268
                self._leave_lock = False
2269
            self._lock_mode = 'w'
2270
            self._lock_count = 1
2271
        elif self._lock_mode == 'r':
2272
            raise errors.ReadOnlyTransaction
2273
        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).
2274
            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.
2275
                # A token was given to lock_write, and we're relocking, so
2276
                # check that the given token actually matches the one we
2277
                # 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).
2278
                if token != self._lock_token:
2279
                    raise errors.TokenMismatch(token, self._lock_token)
2018.5.79 by Andrew Bennetts
Implement RemoteBranch.lock_write/unlock as smart operations.
2280
            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.
2281
            # Re-lock the repository too.
3692.1.2 by Andrew Bennetts
Fix regression introduced by fix, and add a test for that regression.
2282
            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.
2283
        return self._lock_token or None
2018.5.79 by Andrew Bennetts
Implement RemoteBranch.lock_write/unlock as smart operations.
2284
4084.2.1 by Robert Collins
Make accessing a branch.tags.get_tag_dict use a smart[er] method rather than VFS calls and real objects.
2285
    def _set_tags_bytes(self, bytes):
2286
        self._ensure_real()
2287
        return self._real_branch._set_tags_bytes(bytes)
2288
2018.5.79 by Andrew Bennetts
Implement RemoteBranch.lock_write/unlock as smart operations.
2289
    def _unlock(self, branch_token, repo_token):
3786.2.3 by Andrew Bennetts
Remove duplicated 'call & translate errors' code in bzrlib.remote.
2290
        err_context = {'token': str((branch_token, repo_token))}
2291
        response = self._call(
2292
            'Branch.unlock', self._remote_path(), branch_token,
2293
            repo_token or '', **err_context)
2018.5.79 by Andrew Bennetts
Implement RemoteBranch.lock_write/unlock as smart operations.
2294
        if response == ('ok',):
2295
            return
3245.4.24 by Andrew Bennetts
Consistently raise errors from the server as ErrorFromSmartServer exceptions.
2296
        raise errors.UnexpectedSmartServerResponse(response)
1752.2.31 by Martin Pool
[broken] some support for write operations over hpss
2297
2298
    def unlock(self):
3692.1.1 by Andrew Bennetts
Make RemoteBranch.lock_write lock the repository too.
2299
        try:
2300
            self._lock_count -= 1
2301
            if not self._lock_count:
2302
                self._clear_cached_state()
2303
                mode = self._lock_mode
2304
                self._lock_mode = None
2305
                if self._real_branch is not None:
2306
                    if (not self._leave_lock and mode == 'w' and
2307
                        self._repo_lock_token):
2308
                        # If this RemoteBranch will remove the physical lock
2309
                        # for the repository, make sure the _real_branch
2310
                        # doesn't do it first.  (Because the _real_branch's
2311
                        # repository is set to be the RemoteRepository.)
2312
                        self._real_branch.repository.leave_lock_in_place()
2313
                    self._real_branch.unlock()
2314
                if mode != 'w':
2315
                    # Only write-locked branched need to make a remote method
4031.3.1 by Frank Aspell
Fixing various typos
2316
                    # call to perform the unlock.
3692.1.1 by Andrew Bennetts
Make RemoteBranch.lock_write lock the repository too.
2317
                    return
2318
                if not self._lock_token:
2319
                    raise AssertionError('Locked, but no token!')
2320
                branch_token = self._lock_token
2321
                repo_token = self._repo_lock_token
2322
                self._lock_token = None
2323
                self._repo_lock_token = None
2324
                if not self._leave_lock:
2325
                    self._unlock(branch_token, repo_token)
2326
        finally:
2327
            self.repository.unlock()
1752.2.52 by Andrew Bennetts
Flesh out more Remote* methods needed to open and initialise remote branches/trees/repositories.
2328
2329
    def break_lock(self):
2018.5.70 by Robert Collins
Only try to get real repositories when an operation requires them.
2330
        self._ensure_real()
1752.2.52 by Andrew Bennetts
Flesh out more Remote* methods needed to open and initialise remote branches/trees/repositories.
2331
        return self._real_branch.break_lock()
1752.2.31 by Martin Pool
[broken] some support for write operations over hpss
2332
2018.5.79 by Andrew Bennetts
Implement RemoteBranch.lock_write/unlock as smart operations.
2333
    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.
2334
        if not self._lock_token:
2335
            raise NotImplementedError(self.leave_lock_in_place)
2018.5.79 by Andrew Bennetts
Implement RemoteBranch.lock_write/unlock as smart operations.
2336
        self._leave_lock = True
2337
2338
    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.
2339
        if not self._lock_token:
3015.2.15 by Robert Collins
Review feedback.
2340
            raise NotImplementedError(self.dont_leave_lock_in_place)
2018.5.79 by Andrew Bennetts
Implement RemoteBranch.lock_write/unlock as smart operations.
2341
        self._leave_lock = False
2342
4419.2.4 by Andrew Bennetts
Add Repository.get_rev_id_for_revno RPC, removes VFS calls from 'pull -r 123' case.
2343
    def get_rev_id(self, revno, history=None):
4419.2.17 by Andrew Bennetts
Fix test failures in test_lookup_revision_id_by_dotted.
2344
        if revno == 0:
2345
            return _mod_revision.NULL_REVISION
4419.2.4 by Andrew Bennetts
Add Repository.get_rev_id_for_revno RPC, removes VFS calls from 'pull -r 123' case.
2346
        last_revision_info = self.last_revision_info()
4419.2.15 by Andrew Bennetts
Simplify RemoteBranch.get_rev_id a little; get_rev_id_for_revno handles stacking for us.
2347
        ok, result = self.repository.get_rev_id_for_revno(
2348
            revno, last_revision_info)
2349
        if ok:
2350
            return result
2351
        missing_parent = result[1]
4419.2.17 by Andrew Bennetts
Fix test failures in test_lookup_revision_id_by_dotted.
2352
        # Either the revision named by the server is missing, or its parent
2353
        # is.  Call get_parent_map to determine which, so that we report a
2354
        # useful error.
2355
        parent_map = self.repository.get_parent_map([missing_parent])
2356
        if missing_parent in parent_map:
2357
            missing_parent = parent_map[missing_parent]
4419.2.4 by Andrew Bennetts
Add Repository.get_rev_id_for_revno RPC, removes VFS calls from 'pull -r 123' case.
2358
        raise errors.RevisionNotPresent(missing_parent, self.repository)
2359
3441.5.1 by Andrew Bennetts
Avoid necessarily calling get_parent_map when pushing.
2360
    def _last_revision_info(self):
3786.2.3 by Andrew Bennetts
Remove duplicated 'call & translate errors' code in bzrlib.remote.
2361
        response = self._call('Branch.last_revision_info', self._remote_path())
3376.2.4 by Martin Pool
Remove every assert statement from bzrlib!
2362
        if response[0] != 'ok':
2363
            raise SmartProtocolError('unexpected response code %s' % (response,))
2018.5.51 by Wouter van Heyst
Test and implement RemoteBranch.last_revision_info()
2364
        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.
2365
        last_revision = response[2]
2018.5.51 by Wouter van Heyst
Test and implement RemoteBranch.last_revision_info()
2366
        return (revno, last_revision)
2367
2018.5.105 by Andrew Bennetts
Implement revision_history caching for RemoteBranch.
2368
    def _gen_revision_history(self):
2369
        """See Branch._gen_revision_history()."""
4419.1.3 by Andrew Bennetts
Quick fix by using self._ensure_real.
2370
        if self._is_stacked:
2371
            self._ensure_real()
2372
            return self._real_branch._gen_revision_history()
3786.2.3 by Andrew Bennetts
Remove duplicated 'call & translate errors' code in bzrlib.remote.
2373
        response_tuple, response_handler = self._call_expecting_body(
3691.2.3 by Martin Pool
Factor out RemoteBranch._remote_path() and disable RemoteBranch stacking
2374
            '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.
2375
        if response_tuple[0] != 'ok':
3452.2.2 by Andrew Bennetts
Experimental PackRepository.{check_references,autopack} RPCs.
2376
            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.
2377
        result = response_handler.read_body_bytes().split('\x00')
2018.5.38 by Robert Collins
Implement RemoteBranch.revision_history().
2378
        if result == ['']:
2379
            return []
2380
        return result
1752.2.30 by Martin Pool
Start adding a RemoteBzrDir, etc
2381
3691.2.3 by Martin Pool
Factor out RemoteBranch._remote_path() and disable RemoteBranch stacking
2382
    def _remote_path(self):
2383
        return self.bzrdir._path_for_remote_call(self._client)
2384
3441.5.18 by Andrew Bennetts
Fix some test failures.
2385
    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.
2386
            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.
2387
        # This performs additional work to meet the hook contract; while its
2388
        # undesirable, we have to synthesise the revno to call the hook, and
2389
        # not calling the hook is worse as it means changes can't be prevented.
2390
        # Having calculated this though, we can't just call into
2391
        # set_last_revision_info as a simple call, because there is a set_rh
2392
        # hook that some folk may still be using.
2393
        old_revno, old_revid = self.last_revision_info()
2394
        history = self._lefthand_history(revision_id)
2395
        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.
2396
        err_context = {'other_branch': other_branch}
2397
        response = self._call('Branch.set_last_revision_ex',
2398
            self._remote_path(), self._lock_token, self._repo_lock_token,
2399
            revision_id, int(allow_diverged), int(allow_overwrite_descendant),
2400
            **err_context)
3441.5.6 by Andrew Bennetts
Greatly simplify RemoteBranch.update_revisions. Still needs more tests.
2401
        self._clear_cached_state()
3441.5.18 by Andrew Bennetts
Fix some test failures.
2402
        if len(response) != 3 and response[0] != 'ok':
3441.5.6 by Andrew Bennetts
Greatly simplify RemoteBranch.update_revisions. Still needs more tests.
2403
            raise errors.UnexpectedSmartServerResponse(response)
3441.5.18 by Andrew Bennetts
Fix some test failures.
2404
        new_revno, new_revision_id = response[1:]
2405
        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.
2406
        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.
2407
        if self._real_branch is not None:
2408
            cache = new_revno, new_revision_id
2409
            self._real_branch._last_revision_info_cache = cache
3441.5.6 by Andrew Bennetts
Greatly simplify RemoteBranch.update_revisions. Still needs more tests.
2410
3441.5.1 by Andrew Bennetts
Avoid necessarily calling get_parent_map when pushing.
2411
    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.
2412
        old_revno, old_revid = self.last_revision_info()
2413
        # This performs additional work to meet the hook contract; while its
2414
        # undesirable, we have to synthesise the revno to call the hook, and
2415
        # not calling the hook is worse as it means changes can't be prevented.
2416
        # Having calculated this though, we can't just call into
2417
        # set_last_revision_info as a simple call, because there is a set_rh
2418
        # hook that some folk may still be using.
2419
        history = self._lefthand_history(revision_id)
2420
        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.
2421
        self._clear_cached_state()
3786.2.3 by Andrew Bennetts
Remove duplicated 'call & translate errors' code in bzrlib.remote.
2422
        response = self._call('Branch.set_last_revision',
2423
            self._remote_path(), self._lock_token, self._repo_lock_token,
2424
            revision_id)
3441.5.1 by Andrew Bennetts
Avoid necessarily calling get_parent_map when pushing.
2425
        if response != ('ok',):
2426
            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.
2427
        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.
2428
2018.14.1 by Andrew Bennetts
Update to current hpss branch? Fix lots of test failures.
2429
    @needs_write_lock
1752.2.52 by Andrew Bennetts
Flesh out more Remote* methods needed to open and initialise remote branches/trees/repositories.
2430
    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.
2431
        # Send just the tip revision of the history; the server will generate
2432
        # the full history from that.  If the revision doesn't exist in this
2433
        # branch, NoSuchRevision will be raised.
2434
        if rev_history == []:
2018.5.170 by Andrew Bennetts
Use 'null:' instead of '' to mean NULL_REVISION on the wire.
2435
            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.
2436
        else:
2437
            rev_id = rev_history[-1]
3441.5.1 by Andrew Bennetts
Avoid necessarily calling get_parent_map when pushing.
2438
        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.
2439
        for hook in branch.Branch.hooks['set_rh']:
2440
            hook(self, rev_history)
2018.5.105 by Andrew Bennetts
Implement revision_history caching for RemoteBranch.
2441
        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.
2442
4078.2.1 by Robert Collins
Add a Branch.get_parent remote call for RemoteBranch.
2443
    def _get_parent_location(self):
2444
        medium = self._client._medium
2445
        if medium._is_remote_before((1, 13)):
2446
            return self._vfs_get_parent_location()
2447
        try:
4083.1.4 by Andrew Bennetts
Fix trivial bug in get_parent RPC.
2448
            response = self._call('Branch.get_parent', self._remote_path())
4078.2.1 by Robert Collins
Add a Branch.get_parent remote call for RemoteBranch.
2449
        except errors.UnknownSmartMethod:
4094.1.1 by Andrew Bennetts
Add some medium._remember_is_before((1, 13)) calls.
2450
            medium._remember_remote_is_before((1, 13))
4078.2.1 by Robert Collins
Add a Branch.get_parent remote call for RemoteBranch.
2451
            return self._vfs_get_parent_location()
4083.1.4 by Andrew Bennetts
Fix trivial bug in get_parent RPC.
2452
        if len(response) != 1:
4083.1.6 by Andrew Bennetts
Fix trivial bug in my trivial bug fix :)
2453
            raise errors.UnexpectedSmartServerResponse(response)
4083.1.4 by Andrew Bennetts
Fix trivial bug in get_parent RPC.
2454
        parent_location = response[0]
2455
        if parent_location == '':
4078.2.1 by Robert Collins
Add a Branch.get_parent remote call for RemoteBranch.
2456
            return None
4083.1.4 by Andrew Bennetts
Fix trivial bug in get_parent RPC.
2457
        return parent_location
4078.2.1 by Robert Collins
Add a Branch.get_parent remote call for RemoteBranch.
2458
2459
    def _vfs_get_parent_location(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.
2460
        self._ensure_real()
4083.1.5 by Andrew Bennetts
Fix trivial bug in get_parent RPC.
2461
        return self._real_branch._get_parent_location()
4032.1.1 by John Arbash Meinel
Merge the removal of all trailing whitespace, and resolve conflicts.
2462
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.
2463
    def _set_parent_location(self, url):
4288.1.7 by Robert Collins
Add new remote server verb Branch.set_parent_location, dropping roundtrips further on push operations.
2464
        medium = self._client._medium
2465
        if medium._is_remote_before((1, 15)):
2466
            return self._vfs_set_parent_location(url)
2467
        try:
2468
            call_url = url or ''
2469
            if type(call_url) is not str:
2470
                raise AssertionError('url must be a str or None (%s)' % url)
2471
            response = self._call('Branch.set_parent_location',
2472
                self._remote_path(), self._lock_token, self._repo_lock_token,
2473
                call_url)
2474
        except errors.UnknownSmartMethod:
2475
            medium._remember_remote_is_before((1, 15))
2476
            return self._vfs_set_parent_location(url)
2477
        if response != ():
2478
            raise errors.UnexpectedSmartServerResponse(response)
2479
2480
    def _vfs_set_parent_location(self, url):
4288.1.4 by Robert Collins
Remove the explicit set_parent method on RemoteBranch in favour of inheriting from Branch.
2481
        self._ensure_real()
2482
        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.
2483
2018.14.1 by Andrew Bennetts
Update to current hpss branch? Fix lots of test failures.
2484
    @needs_write_lock
2477.1.2 by Martin Pool
Rename push/pull back to 'run_hooks' (jameinel)
2485
    def pull(self, source, overwrite=False, stop_revision=None,
2477.1.9 by Martin Pool
Review cleanups from John, mostly docs
2486
             **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.
2487
        self._clear_cached_state_of_remote_branch_only()
2018.14.1 by Andrew Bennetts
Update to current hpss branch? Fix lots of test failures.
2488
        self._ensure_real()
3482.1.1 by John Arbash Meinel
Fix bug #238149, RemoteBranch.pull needs to return the _real_branch's pull result.
2489
        return self._real_branch.pull(
2477.1.2 by Martin Pool
Rename push/pull back to 'run_hooks' (jameinel)
2490
            source, overwrite=overwrite, stop_revision=stop_revision,
3489.2.4 by Andrew Bennetts
Fix all tests broken by fixing make_branch_and_tree.
2491
            _override_hook_target=self, **kwargs)
2018.14.1 by Andrew Bennetts
Update to current hpss branch? Fix lots of test failures.
2492
2018.14.3 by Andrew Bennetts
Make a couple more branch_implementations tests pass.
2493
    @needs_read_lock
2494
    def push(self, target, overwrite=False, stop_revision=None):
2495
        self._ensure_real()
2018.5.97 by Andrew Bennetts
Fix more tests.
2496
        return self._real_branch.push(
2477.1.5 by Martin Pool
More cleanups of Branch.push to get the right behaviour with RemoteBranches
2497
            target, overwrite=overwrite, stop_revision=stop_revision,
2498
            _override_hook_source_branch=self)
2018.14.3 by Andrew Bennetts
Make a couple more branch_implementations tests pass.
2499
2500
    def is_locked(self):
2501
        return self._lock_count >= 1
2502
3634.2.1 by John Arbash Meinel
Thunk over to the real branch's revision_id_to_revno.
2503
    @needs_read_lock
2504
    def revision_id_to_revno(self, revision_id):
2505
        self._ensure_real()
2506
        return self._real_branch.revision_id_to_revno(revision_id)
2507
2892.2.1 by Andrew Bennetts
Add Branch.set_last_revision_info smart method, and make the RemoteBranch client use it.
2508
    @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.
2509
    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.
2510
        # XXX: These should be returned by the set_last_revision_info verb
2511
        old_revno, old_revid = self.last_revision_info()
2512
        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.
2513
        revision_id = ensure_null(revision_id)
3297.4.2 by Andrew Bennetts
Add backwards compatibility for servers older than 1.4.
2514
        try:
3786.2.3 by Andrew Bennetts
Remove duplicated 'call & translate errors' code in bzrlib.remote.
2515
            response = self._call('Branch.set_last_revision_info',
2516
                self._remote_path(), self._lock_token, self._repo_lock_token,
2517
                str(revno), revision_id)
3297.4.2 by Andrew Bennetts
Add backwards compatibility for servers older than 1.4.
2518
        except errors.UnknownSmartMethod:
2519
            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.
2520
            self._clear_cached_state_of_remote_branch_only()
3441.5.1 by Andrew Bennetts
Avoid necessarily calling get_parent_map when pushing.
2521
            self._real_branch.set_last_revision_info(revno, revision_id)
2522
            self._last_revision_info_cache = revno, revision_id
2523
            return
2892.2.1 by Andrew Bennetts
Add Branch.set_last_revision_info smart method, and make the RemoteBranch client use it.
2524
        if response == ('ok',):
2525
            self._clear_cached_state()
3441.5.1 by Andrew Bennetts
Avoid necessarily calling get_parent_map when pushing.
2526
            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.
2527
            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.
2528
            # Update the _real_branch's cache too.
2529
            if self._real_branch is not None:
2530
                cache = self._last_revision_info_cache
2531
                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.
2532
        else:
2533
            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.
2534
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.
2535
    @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.
2536
    def generate_revision_history(self, revision_id, last_rev=None,
2537
                                  other_branch=None):
3441.5.6 by Andrew Bennetts
Greatly simplify RemoteBranch.update_revisions. Still needs more tests.
2538
        medium = self._client._medium
3441.5.23 by Andrew Bennetts
Fix test failures.
2539
        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.
2540
            # 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.
2541
            try:
3441.5.18 by Andrew Bennetts
Fix some test failures.
2542
                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.
2543
                    allow_diverged=True, allow_overwrite_descendant=True)
3441.5.6 by Andrew Bennetts
Greatly simplify RemoteBranch.update_revisions. Still needs more tests.
2544
                return
3441.5.18 by Andrew Bennetts
Fix some test failures.
2545
            except errors.UnknownSmartMethod:
3441.5.23 by Andrew Bennetts
Fix test failures.
2546
                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.
2547
        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.
2548
        self.set_revision_history(self._lefthand_history(revision_id,
2549
            last_rev=last_rev,other_branch=other_branch))
2018.5.96 by Andrew Bennetts
Merge from bzr.dev, resolving the worst of the semantic conflicts, but there's
2550
2018.5.97 by Andrew Bennetts
Fix more tests.
2551
    def set_push_location(self, location):
2552
        self._ensure_real()
2553
        return self._real_branch.set_push_location(location)
2554
2018.18.25 by Martin Pool
Repository.tarball fixes for python2.4
2555
4288.1.1 by Robert Collins
Add support for a RemoteBzrDirConfig to support optimising push operations which need to look for default stacking locations.
2556
class RemoteConfig(object):
2557
    """A Config that reads and writes from smart verbs.
4226.1.5 by Robert Collins
Reinstate the use of the Branch.get_config_file verb.
2558
2559
    It is a low-level object that considers config data to be name/value pairs
2560
    that may be associated with a section. Assigning meaning to the these
2561
    values is done at higher levels like bzrlib.config.TreeConfig.
2562
    """
2563
2564
    def get_option(self, name, section=None, default=None):
2565
        """Return the value associated with a named option.
2566
2567
        :param name: The name of the value
2568
        :param section: The section the option is in (if any)
2569
        :param default: The value to return if the value is not set
2570
        :return: The value or default value
2571
        """
4288.1.1 by Robert Collins
Add support for a RemoteBzrDirConfig to support optimising push operations which need to look for default stacking locations.
2572
        try:
2573
            configobj = self._get_configobj()
2574
            if section is None:
2575
                section_obj = configobj
2576
            else:
2577
                try:
2578
                    section_obj = configobj[section]
2579
                except KeyError:
2580
                    return default
2581
            return section_obj.get(name, default)
2582
        except errors.UnknownSmartMethod:
2583
            return self._vfs_get_option(name, section, default)
4226.1.5 by Robert Collins
Reinstate the use of the Branch.get_config_file verb.
2584
4288.1.1 by Robert Collins
Add support for a RemoteBzrDirConfig to support optimising push operations which need to look for default stacking locations.
2585
    def _response_to_configobj(self, response):
4288.1.2 by Robert Collins
Create a server verb for doing BzrDir.get_config()
2586
        if len(response[0]) and response[0][0] != 'ok':
4288.1.4 by Robert Collins
Remove the explicit set_parent method on RemoteBranch in favour of inheriting from Branch.
2587
            raise errors.UnexpectedSmartServerResponse(response)
4241.5.1 by Matt Nordhoff
Fix Branch.get_config_file smart verb on multi-line config files. (Bug #354075)
2588
        lines = response[1].read_body_bytes().splitlines()
2589
        return config.ConfigObj(lines, encoding='utf-8')
4226.1.5 by Robert Collins
Reinstate the use of the Branch.get_config_file verb.
2590
4288.1.1 by Robert Collins
Add support for a RemoteBzrDirConfig to support optimising push operations which need to look for default stacking locations.
2591
2592
class RemoteBranchConfig(RemoteConfig):
2593
    """A RemoteConfig for Branches."""
2594
2595
    def __init__(self, branch):
2596
        self._branch = branch
2597
2598
    def _get_configobj(self):
2599
        path = self._branch._remote_path()
2600
        response = self._branch._client.call_expecting_body(
2601
            'Branch.get_config_file', path)
2602
        return self._response_to_configobj(response)
2603
4226.1.5 by Robert Collins
Reinstate the use of the Branch.get_config_file verb.
2604
    def set_option(self, value, name, section=None):
2605
        """Set the value associated with a named option.
2606
2607
        :param value: The value to set
2608
        :param name: The name of the value to set
2609
        :param section: The section the option is in (if any)
2610
        """
4226.2.1 by Robert Collins
Set branch config options via a smart method.
2611
        medium = self._branch._client._medium
2612
        if medium._is_remote_before((1, 14)):
2613
            return self._vfs_set_option(value, name, section)
2614
        try:
2615
            path = self._branch._remote_path()
2616
            response = self._branch._client.call('Branch.set_config_option',
2617
                path, self._branch._lock_token, self._branch._repo_lock_token,
4226.2.2 by Robert Collins
Fix setting config options to support unicode values and don't attempt to reset repositories _fallback_repositories as the simple approach fails to work.
2618
                value.encode('utf8'), name, section or '')
4226.2.1 by Robert Collins
Set branch config options via a smart method.
2619
        except errors.UnknownSmartMethod:
2620
            medium._remember_remote_is_before((1, 14))
2621
            return self._vfs_set_option(value, name, section)
2622
        if response != ():
2623
            raise errors.UnexpectedSmartServerResponse(response)
4226.1.5 by Robert Collins
Reinstate the use of the Branch.get_config_file verb.
2624
4288.1.1 by Robert Collins
Add support for a RemoteBzrDirConfig to support optimising push operations which need to look for default stacking locations.
2625
    def _real_object(self):
2626
        self._branch._ensure_real()
2627
        return self._branch._real_branch
2628
4226.1.5 by Robert Collins
Reinstate the use of the Branch.get_config_file verb.
2629
    def _vfs_set_option(self, value, name, section=None):
4288.1.1 by Robert Collins
Add support for a RemoteBzrDirConfig to support optimising push operations which need to look for default stacking locations.
2630
        return self._real_object()._get_config().set_option(
2631
            value, name, section)
2632
2633
2634
class RemoteBzrDirConfig(RemoteConfig):
2635
    """A RemoteConfig for BzrDirs."""
2636
2637
    def __init__(self, bzrdir):
2638
        self._bzrdir = bzrdir
2639
2640
    def _get_configobj(self):
4288.1.4 by Robert Collins
Remove the explicit set_parent method on RemoteBranch in favour of inheriting from Branch.
2641
        medium = self._bzrdir._client._medium
2642
        verb = 'BzrDir.get_config_file'
2643
        if medium._is_remote_before((1, 15)):
2644
            raise errors.UnknownSmartMethod(verb)
4288.1.1 by Robert Collins
Add support for a RemoteBzrDirConfig to support optimising push operations which need to look for default stacking locations.
2645
        path = self._bzrdir._path_for_remote_call(self._bzrdir._client)
2646
        response = self._bzrdir._call_expecting_body(
4288.1.4 by Robert Collins
Remove the explicit set_parent method on RemoteBranch in favour of inheriting from Branch.
2647
            verb, path)
4288.1.1 by Robert Collins
Add support for a RemoteBzrDirConfig to support optimising push operations which need to look for default stacking locations.
2648
        return self._response_to_configobj(response)
2649
2650
    def _vfs_get_option(self, name, section, default):
2651
        return self._real_object()._get_config().get_option(
2652
            name, section, default)
2653
2654
    def set_option(self, value, name, section=None):
2655
        """Set the value associated with a named option.
2656
2657
        :param value: The value to set
2658
        :param name: The name of the value to set
2659
        :param section: The section the option is in (if any)
2660
        """
2661
        return self._real_object()._get_config().set_option(
2662
            value, name, section)
2663
2664
    def _real_object(self):
2665
        self._bzrdir._ensure_real()
2666
        return self._bzrdir._real_bzrdir
2667
4226.1.5 by Robert Collins
Reinstate the use of the Branch.get_config_file verb.
2668
2669
2018.18.25 by Martin Pool
Repository.tarball fixes for python2.4
2670
def _extract_tar(tar, to_dir):
2671
    """Extract all the contents of a tarfile object.
2672
2673
    A replacement for extractall, which is not present in python2.4
2674
    """
2675
    for tarinfo in tar:
2676
        tar.extract(tarinfo, to_dir)
3533.3.1 by Andrew Bennetts
Remove duplication of error translation in bzrlib/remote.py.
2677
2678
2679
def _translate_error(err, **context):
2680
    """Translate an ErrorFromSmartServer into a more useful error.
2681
2682
    Possible context keys:
2683
      - branch
2684
      - repository
2685
      - bzrdir
2686
      - token
2687
      - other_branch
3779.3.2 by Andrew Bennetts
Unify error translation done in bzrlib.remote and bzrlib.transport.remote.
2688
      - path
3690.1.1 by Andrew Bennetts
Unexpected error responses from a smart server no longer cause the client to traceback.
2689
2690
    If the error from the server doesn't match a known pattern, then
3690.1.2 by Andrew Bennetts
Rename UntranslateableErrorFromSmartServer -> UnknownErrorFromSmartServer.
2691
    UnknownErrorFromSmartServer is raised.
3533.3.1 by Andrew Bennetts
Remove duplication of error translation in bzrlib/remote.py.
2692
    """
2693
    def find(name):
3533.3.4 by Andrew Bennetts
Add tests for _translate_error's robustness.
2694
        try:
2695
            return context[name]
3779.3.2 by Andrew Bennetts
Unify error translation done in bzrlib.remote and bzrlib.transport.remote.
2696
        except KeyError, key_err:
2697
            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.
2698
            raise err
3779.3.2 by Andrew Bennetts
Unify error translation done in bzrlib.remote and bzrlib.transport.remote.
2699
    def get_path():
3779.3.3 by Andrew Bennetts
Add a docstring.
2700
        """Get the path from the context if present, otherwise use first error
2701
        arg.
2702
        """
3779.3.2 by Andrew Bennetts
Unify error translation done in bzrlib.remote and bzrlib.transport.remote.
2703
        try:
2704
            return context['path']
2705
        except KeyError, key_err:
2706
            try:
2707
                return err.error_args[0]
2708
            except IndexError, idx_err:
2709
                mutter(
2710
                    'Missing key %r in context %r', key_err.args[0], context)
2711
                raise err
2712
3533.3.1 by Andrew Bennetts
Remove duplication of error translation in bzrlib/remote.py.
2713
    if err.error_verb == 'NoSuchRevision':
2714
        raise NoSuchRevision(find('branch'), err.error_args[0])
2715
    elif err.error_verb == 'nosuchrevision':
2716
        raise NoSuchRevision(find('repository'), err.error_args[0])
2717
    elif err.error_tuple == ('nobranch',):
3533.3.4 by Andrew Bennetts
Add tests for _translate_error's robustness.
2718
        raise errors.NotBranchError(path=find('bzrdir').root_transport.base)
3533.3.1 by Andrew Bennetts
Remove duplication of error translation in bzrlib/remote.py.
2719
    elif err.error_verb == 'norepository':
2720
        raise errors.NoRepositoryPresent(find('bzrdir'))
2721
    elif err.error_verb == 'LockContention':
2722
        raise errors.LockContention('(remote lock)')
2723
    elif err.error_verb == 'UnlockableTransport':
3533.3.4 by Andrew Bennetts
Add tests for _translate_error's robustness.
2724
        raise errors.UnlockableTransport(find('bzrdir').root_transport)
3533.3.1 by Andrew Bennetts
Remove duplication of error translation in bzrlib/remote.py.
2725
    elif err.error_verb == 'LockFailed':
2726
        raise errors.LockFailed(err.error_args[0], err.error_args[1])
2727
    elif err.error_verb == 'TokenMismatch':
2728
        raise errors.TokenMismatch(find('token'), '(remote token)')
2729
    elif err.error_verb == 'Diverged':
2730
        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.
2731
    elif err.error_verb == 'TipChangeRejected':
2732
        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
2733
    elif err.error_verb == 'UnstackableBranchFormat':
2734
        raise errors.UnstackableBranchFormat(*err.error_args)
2735
    elif err.error_verb == 'UnstackableRepositoryFormat':
2736
        raise errors.UnstackableRepositoryFormat(*err.error_args)
2737
    elif err.error_verb == 'NotStacked':
2738
        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.
2739
    elif err.error_verb == 'PermissionDenied':
3779.3.2 by Andrew Bennetts
Unify error translation done in bzrlib.remote and bzrlib.transport.remote.
2740
        path = get_path()
3779.3.1 by Andrew Bennetts
Move encoding/decoding logic of PermissionDenied and ReadError so that it happens for all RPCs.
2741
        if len(err.error_args) >= 2:
2742
            extra = err.error_args[1]
3779.3.2 by Andrew Bennetts
Unify error translation done in bzrlib.remote and bzrlib.transport.remote.
2743
        else:
2744
            extra = None
3779.3.1 by Andrew Bennetts
Move encoding/decoding logic of PermissionDenied and ReadError so that it happens for all RPCs.
2745
        raise errors.PermissionDenied(path, extra=extra)
3779.3.2 by Andrew Bennetts
Unify error translation done in bzrlib.remote and bzrlib.transport.remote.
2746
    elif err.error_verb == 'ReadError':
2747
        path = get_path()
2748
        raise errors.ReadError(path)
2749
    elif err.error_verb == 'NoSuchFile':
2750
        path = get_path()
2751
        raise errors.NoSuchFile(path)
2752
    elif err.error_verb == 'FileExists':
2753
        raise errors.FileExists(err.error_args[0])
2754
    elif err.error_verb == 'DirectoryNotEmpty':
2755
        raise errors.DirectoryNotEmpty(err.error_args[0])
2756
    elif err.error_verb == 'ShortReadvError':
2757
        args = err.error_args
2758
        raise errors.ShortReadvError(
2759
            args[0], int(args[1]), int(args[2]), int(args[3]))
2760
    elif err.error_verb in ('UnicodeEncodeError', 'UnicodeDecodeError'):
2761
        encoding = str(err.error_args[0]) # encoding must always be a string
2762
        val = err.error_args[1]
2763
        start = int(err.error_args[2])
2764
        end = int(err.error_args[3])
2765
        reason = str(err.error_args[4]) # reason must always be a string
2766
        if val.startswith('u:'):
2767
            val = val[2:].decode('utf-8')
2768
        elif val.startswith('s:'):
2769
            val = val[2:].decode('base64')
3786.2.3 by Andrew Bennetts
Remove duplicated 'call & translate errors' code in bzrlib.remote.
2770
        if err.error_verb == 'UnicodeDecodeError':
3779.3.2 by Andrew Bennetts
Unify error translation done in bzrlib.remote and bzrlib.transport.remote.
2771
            raise UnicodeDecodeError(encoding, val, start, end, reason)
3786.2.3 by Andrew Bennetts
Remove duplicated 'call & translate errors' code in bzrlib.remote.
2772
        elif err.error_verb == 'UnicodeEncodeError':
3779.3.2 by Andrew Bennetts
Unify error translation done in bzrlib.remote and bzrlib.transport.remote.
2773
            raise UnicodeEncodeError(encoding, val, start, end, reason)
2774
    elif err.error_verb == 'ReadOnlyError':
2775
        raise errors.TransportNotPossible('readonly transport')
3690.1.2 by Andrew Bennetts
Rename UntranslateableErrorFromSmartServer -> UnknownErrorFromSmartServer.
2776
    raise errors.UnknownErrorFromSmartServer(err)