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