~bzr-pqm/bzr/bzr.dev

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