/brz/remove-bazaar

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