~bzr-pqm/bzr/bzr.dev

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