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