/brz/remove-bazaar

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