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