/brz/remove-bazaar

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