/brz/remove-bazaar

To get this branch, use:
bzr branch http://gegoxaren.bato24.eu/bzr/brz/remove-bazaar
5557.1.7 by John Arbash Meinel
Merge in the bzr.dev 5582
1
# Copyright (C) 2006-2011 Canonical Ltd
1752.2.30 by Martin Pool
Start adding a RemoteBzrDir, etc
2
#
3
# This program is free software; you can redistribute it and/or modify
4
# it under the terms of the GNU General Public License as published by
5
# the Free Software Foundation; either version 2 of the License, or
6
# (at your option) any later version.
7
#
8
# This program is distributed in the hope that it will be useful,
9
# but WITHOUT ANY WARRANTY; without even the implied warranty of
10
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
11
# GNU General Public License for more details.
12
#
13
# You should have received a copy of the GNU General Public License
14
# along with this program; if not, write to the Free Software
4183.7.1 by Sabin Iacob
update FSF mailing address
15
# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
1752.2.30 by Martin Pool
Start adding a RemoteBzrDir, etc
16
3211.5.2 by Robert Collins
Change RemoteRepository.get_parent_map to use bz2 not gzip for compression.
17
import bz2
1752.2.30 by Martin Pool
Start adding a RemoteBzrDir, etc
18
2490.2.5 by Aaron Bentley
Use GraphWalker.unique_ancestor to determine merge base
19
from bzrlib import (
2694.5.4 by Jelmer Vernooij
Move bzrlib.util.bencode to bzrlib._bencode_py.
20
    bencode,
2490.2.5 by Aaron Bentley
Use GraphWalker.unique_ancestor to determine merge base
21
    branch,
5712.3.13 by Jelmer Vernooij
Add Prober.known_formats().
22
    bzrdir as _mod_bzrdir,
4226.1.5 by Robert Collins
Reinstate the use of the Branch.get_config_file verb.
23
    config,
5363.2.10 by Jelmer Vernooij
base ControlDir on ControlComponent.
24
    controldir,
3192.1.1 by Andrew Bennetts
Add some -Dhpss debugging to get_parent_map.
25
    debug,
2490.2.5 by Aaron Bentley
Use GraphWalker.unique_ancestor to determine merge base
26
    errors,
6280.8.1 by Jelmer Vernooij
Avoid _ensure_real in RemoteRepository.verify_revision_signature and RemoteRepository.sign_revision.
27
    gpg,
3172.5.1 by Robert Collins
Create a RemoteRepository get_graph implementation and delegate get_parents_map to the real repository.
28
    graph,
4509.3.28 by Martin Pool
Add missing import
29
    lock,
2490.2.5 by Aaron Bentley
Use GraphWalker.unique_ancestor to determine merge base
30
    lockdir,
6284.1.1 by Jelmer Vernooij
Allow registering custom error handlers in the HPSS client.
31
    registry,
5158.4.1 by Andrew Bennetts
Don't allow RemoteRepository to stack on incompatible formats.
32
    repository as _mod_repository,
4307.2.3 by Robert Collins
Change RemoteRepository.has_revision to use get_parent_map to leverage the caching.
33
    revision as _mod_revision,
4913.4.2 by Jelmer Vernooij
Add Repository.get_known_graph_ancestry.
34
    static_tuple,
3228.4.11 by John Arbash Meinel
Deprecations abound.
35
    symbol_versioning,
6280.8.1 by Jelmer Vernooij
Avoid _ensure_real in RemoteRepository.verify_revision_signature and RemoteRepository.sign_revision.
36
    testament as _mod_testament,
5535.3.7 by Andrew Bennetts
Allow for trailing-slash differences between local url path vs. remote url path for remote branch's repository.
37
    urlutils,
5815.4.1 by Jelmer Vernooij
Split versionedfile-specific stuff out into VersionedFileRepository.
38
    vf_repository,
39
    )
5200.3.3 by Robert Collins
Lock methods on ``Tree``, ``Branch`` and ``Repository`` are now
40
from bzrlib.branch import BranchReferenceFormat, BranchWriteLockResult
4634.85.9 by Andrew Bennetts
Add some experimental decorators: @only_raises(..) and @cleanup_method.
41
from bzrlib.decorators import needs_read_lock, needs_write_lock, only_raises
3376.2.4 by Martin Pool
Remove every assert statement from bzrlib!
42
from bzrlib.errors import (
43
    NoSuchRevision,
44
    SmartProtocolError,
45
    )
6138.3.4 by Jonathan Riddell
add gettext() to uses of trace.note()
46
from bzrlib.i18n import gettext
6267.1.3 by Jelmer Vernooij
Fix tests.
47
from bzrlib.inventory import Inventory
2018.5.127 by Andrew Bennetts
Fix most of the lockable_files tests for RemoteBranchLockableFiles.
48
from bzrlib.lockable_files import LockableFiles
4060.1.4 by Robert Collins
Streaming fetch from remote servers.
49
from bzrlib.smart import client, vfs, repository as smart_repo
5712.3.15 by Jelmer Vernooij
Remove unused register format functions.
50
from bzrlib.smart.client import _SmartClient
5712.3.13 by Jelmer Vernooij
Add Prober.known_formats().
51
from bzrlib.revision import NULL_REVISION
6267.1.3 by Jelmer Vernooij
Fix tests.
52
from bzrlib.revisiontree import InventoryRevisionTree
5816.8.3 by Andrew Bennetts
Add test for calling add_fallback_repository after _make_parents_provider, and make it work.
53
from bzrlib.repository import RepositoryWriteLockResult, _LazyListJoin
6280.7.5 by Jelmer Vernooij
Bunch of test fixes.
54
from bzrlib.trace import mutter, note, warning, log_exception_quietly
1752.2.30 by Martin Pool
Start adding a RemoteBzrDir, etc
55
3445.1.5 by John Arbash Meinel
allow passing a 'graph' object into Branch.update_revisions.
56
6015.23.12 by John Arbash Meinel
Going with 100 to be friendlier to bandwith/latency constrained environs.
57
_DEFAULT_SEARCH_DEPTH = 100
6015.23.11 by John Arbash Meinel
allow a bit more flexibilty in how we walk the searches.
58
59
3786.2.3 by Andrew Bennetts
Remove duplicated 'call & translate errors' code in bzrlib.remote.
60
class _RpcHelper(object):
61
    """Mixin class that helps with issuing RPCs."""
62
63
    def _call(self, method, *args, **err_context):
64
        try:
65
            return self._client.call(method, *args)
66
        except errors.ErrorFromSmartServer, err:
67
            self._translate_error(err, **err_context)
3943.8.1 by Marius Kruger
remove all trailing whitespace from bzr source
68
3786.2.3 by Andrew Bennetts
Remove duplicated 'call & translate errors' code in bzrlib.remote.
69
    def _call_expecting_body(self, method, *args, **err_context):
70
        try:
71
            return self._client.call_expecting_body(method, *args)
72
        except errors.ErrorFromSmartServer, err:
73
            self._translate_error(err, **err_context)
3943.8.1 by Marius Kruger
remove all trailing whitespace from bzr source
74
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.
75
    def _call_with_body_bytes(self, method, args, body_bytes, **err_context):
76
        try:
77
            return self._client.call_with_body_bytes(method, args, body_bytes)
78
        except errors.ErrorFromSmartServer, err:
79
            self._translate_error(err, **err_context)
80
3786.2.3 by Andrew Bennetts
Remove duplicated 'call & translate errors' code in bzrlib.remote.
81
    def _call_with_body_bytes_expecting_body(self, method, args, body_bytes,
82
                                             **err_context):
83
        try:
84
            return self._client.call_with_body_bytes_expecting_body(
85
                method, args, body_bytes)
86
        except errors.ErrorFromSmartServer, err:
87
            self._translate_error(err, **err_context)
3943.8.1 by Marius Kruger
remove all trailing whitespace from bzr source
88
4032.3.2 by Robert Collins
Create and use a RPC call to create branches on bzr servers rather than using VFS calls.
89
90
def response_tuple_to_repo_format(response):
91
    """Convert a response tuple describing a repository format to a format."""
92
    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.
93
    format._rich_root_data = (response[0] == 'yes')
94
    format._supports_tree_reference = (response[1] == 'yes')
95
    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.
96
    format._network_name = response[3]
97
    return format
98
99
5712.3.13 by Jelmer Vernooij
Add Prober.known_formats().
100
# Note that RemoteBzrDirProber lives in bzrlib.bzrdir so bzrlib.remote
101
# does not have to be imported unless a remote format is involved.
102
103
class RemoteBzrDirFormat(_mod_bzrdir.BzrDirMetaFormat1):
104
    """Format representing bzrdirs accessed via a smart server"""
105
106
    supports_workingtrees = False
107
108
    def __init__(self):
5712.3.17 by Jelmer Vernooij
more fixes.
109
        _mod_bzrdir.BzrDirMetaFormat1.__init__(self)
5712.3.13 by Jelmer Vernooij
Add Prober.known_formats().
110
        # XXX: It's a bit ugly that the network name is here, because we'd
111
        # like to believe that format objects are stateless or at least
112
        # immutable,  However, we do at least avoid mutating the name after
113
        # it's returned.  See <https://bugs.launchpad.net/bzr/+bug/504102>
114
        self._network_name = None
115
116
    def __repr__(self):
117
        return "%s(_network_name=%r)" % (self.__class__.__name__,
118
            self._network_name)
119
120
    def get_format_description(self):
121
        if self._network_name:
122
            real_format = controldir.network_format_registry.get(self._network_name)
123
            return 'Remote: ' + real_format.get_format_description()
124
        return 'bzr remote bzrdir'
125
126
    def get_format_string(self):
127
        raise NotImplementedError(self.get_format_string)
128
129
    def network_name(self):
130
        if self._network_name:
131
            return self._network_name
132
        else:
133
            raise AssertionError("No network name set.")
134
135
    def initialize_on_transport(self, transport):
136
        try:
137
            # hand off the request to the smart server
138
            client_medium = transport.get_smart_medium()
139
        except errors.NoSmartMedium:
140
            # TODO: lookup the local format from a server hint.
141
            local_dir_format = _mod_bzrdir.BzrDirMetaFormat1()
142
            return local_dir_format.initialize_on_transport(transport)
143
        client = _SmartClient(client_medium)
144
        path = client.remote_path_from_transport(transport)
145
        try:
146
            response = client.call('BzrDirFormat.initialize', path)
147
        except errors.ErrorFromSmartServer, err:
148
            _translate_error(err, path=path)
149
        if response[0] != 'ok':
150
            raise errors.SmartProtocolError('unexpected response code %s' % (response,))
151
        format = RemoteBzrDirFormat()
152
        self._supply_sub_formats_to(format)
153
        return RemoteBzrDir(transport, format)
154
155
    def parse_NoneTrueFalse(self, arg):
156
        if not arg:
157
            return None
158
        if arg == 'False':
159
            return False
160
        if arg == 'True':
161
            return True
162
        raise AssertionError("invalid arg %r" % arg)
163
164
    def _serialize_NoneTrueFalse(self, arg):
165
        if arg is False:
166
            return 'False'
167
        if arg:
168
            return 'True'
169
        return ''
170
171
    def _serialize_NoneString(self, arg):
172
        return arg or ''
173
174
    def initialize_on_transport_ex(self, transport, use_existing_dir=False,
175
        create_prefix=False, force_new_repo=False, stacked_on=None,
176
        stack_on_pwd=None, repo_format_name=None, make_working_trees=None,
177
        shared_repo=False):
178
        try:
179
            # hand off the request to the smart server
180
            client_medium = transport.get_smart_medium()
181
        except errors.NoSmartMedium:
182
            do_vfs = True
183
        else:
184
            # Decline to open it if the server doesn't support our required
185
            # version (3) so that the VFS-based transport will do it.
186
            if client_medium.should_probe():
187
                try:
188
                    server_version = client_medium.protocol_version()
189
                    if server_version != '2':
190
                        do_vfs = True
191
                    else:
192
                        do_vfs = False
193
                except errors.SmartProtocolError:
194
                    # Apparently there's no usable smart server there, even though
195
                    # the medium supports the smart protocol.
196
                    do_vfs = True
197
            else:
198
                do_vfs = False
199
        if not do_vfs:
200
            client = _SmartClient(client_medium)
201
            path = client.remote_path_from_transport(transport)
202
            if client_medium._is_remote_before((1, 16)):
203
                do_vfs = True
204
        if do_vfs:
205
            # TODO: lookup the local format from a server hint.
206
            local_dir_format = _mod_bzrdir.BzrDirMetaFormat1()
207
            self._supply_sub_formats_to(local_dir_format)
208
            return local_dir_format.initialize_on_transport_ex(transport,
209
                use_existing_dir=use_existing_dir, create_prefix=create_prefix,
210
                force_new_repo=force_new_repo, stacked_on=stacked_on,
211
                stack_on_pwd=stack_on_pwd, repo_format_name=repo_format_name,
212
                make_working_trees=make_working_trees, shared_repo=shared_repo,
213
                vfs_only=True)
214
        return self._initialize_on_transport_ex_rpc(client, path, transport,
215
            use_existing_dir, create_prefix, force_new_repo, stacked_on,
216
            stack_on_pwd, repo_format_name, make_working_trees, shared_repo)
217
218
    def _initialize_on_transport_ex_rpc(self, client, path, transport,
219
        use_existing_dir, create_prefix, force_new_repo, stacked_on,
220
        stack_on_pwd, repo_format_name, make_working_trees, shared_repo):
221
        args = []
222
        args.append(self._serialize_NoneTrueFalse(use_existing_dir))
223
        args.append(self._serialize_NoneTrueFalse(create_prefix))
224
        args.append(self._serialize_NoneTrueFalse(force_new_repo))
225
        args.append(self._serialize_NoneString(stacked_on))
226
        # stack_on_pwd is often/usually our transport
227
        if stack_on_pwd:
228
            try:
229
                stack_on_pwd = transport.relpath(stack_on_pwd)
230
                if not stack_on_pwd:
231
                    stack_on_pwd = '.'
232
            except errors.PathNotChild:
233
                pass
234
        args.append(self._serialize_NoneString(stack_on_pwd))
235
        args.append(self._serialize_NoneString(repo_format_name))
236
        args.append(self._serialize_NoneTrueFalse(make_working_trees))
237
        args.append(self._serialize_NoneTrueFalse(shared_repo))
238
        request_network_name = self._network_name or \
239
            _mod_bzrdir.BzrDirFormat.get_default_format().network_name()
240
        try:
241
            response = client.call('BzrDirFormat.initialize_ex_1.16',
242
                request_network_name, path, *args)
243
        except errors.UnknownSmartMethod:
244
            client._medium._remember_remote_is_before((1,16))
245
            local_dir_format = _mod_bzrdir.BzrDirMetaFormat1()
246
            self._supply_sub_formats_to(local_dir_format)
247
            return local_dir_format.initialize_on_transport_ex(transport,
248
                use_existing_dir=use_existing_dir, create_prefix=create_prefix,
249
                force_new_repo=force_new_repo, stacked_on=stacked_on,
250
                stack_on_pwd=stack_on_pwd, repo_format_name=repo_format_name,
251
                make_working_trees=make_working_trees, shared_repo=shared_repo,
252
                vfs_only=True)
253
        except errors.ErrorFromSmartServer, err:
254
            _translate_error(err, path=path)
255
        repo_path = response[0]
256
        bzrdir_name = response[6]
257
        require_stacking = response[7]
258
        require_stacking = self.parse_NoneTrueFalse(require_stacking)
259
        format = RemoteBzrDirFormat()
260
        format._network_name = bzrdir_name
261
        self._supply_sub_formats_to(format)
262
        bzrdir = RemoteBzrDir(transport, format, _client=client)
263
        if repo_path:
264
            repo_format = response_tuple_to_repo_format(response[1:])
265
            if repo_path == '.':
266
                repo_path = ''
267
            if repo_path:
268
                repo_bzrdir_format = RemoteBzrDirFormat()
269
                repo_bzrdir_format._network_name = response[5]
270
                repo_bzr = RemoteBzrDir(transport.clone(repo_path),
271
                    repo_bzrdir_format)
272
            else:
273
                repo_bzr = bzrdir
274
            final_stack = response[8] or None
275
            final_stack_pwd = response[9] or None
276
            if final_stack_pwd:
277
                final_stack_pwd = urlutils.join(
278
                    transport.base, final_stack_pwd)
279
            remote_repo = RemoteRepository(repo_bzr, repo_format)
280
            if len(response) > 10:
281
                # Updated server verb that locks remotely.
282
                repo_lock_token = response[10] or None
283
                remote_repo.lock_write(repo_lock_token, _skip_rpc=True)
284
                if repo_lock_token:
285
                    remote_repo.dont_leave_lock_in_place()
286
            else:
287
                remote_repo.lock_write()
5712.3.17 by Jelmer Vernooij
more fixes.
288
            policy = _mod_bzrdir.UseExistingRepository(remote_repo, final_stack,
5712.3.13 by Jelmer Vernooij
Add Prober.known_formats().
289
                final_stack_pwd, require_stacking)
290
            policy.acquire_repository()
291
        else:
292
            remote_repo = None
293
            policy = None
294
        bzrdir._format.set_branch_format(self.get_branch_format())
295
        if require_stacking:
296
            # The repo has already been created, but we need to make sure that
297
            # we'll make a stackable branch.
298
            bzrdir._format.require_stacking(_skip_repo=True)
299
        return remote_repo, bzrdir, require_stacking, policy
300
301
    def _open(self, transport):
302
        return RemoteBzrDir(transport, self)
303
304
    def __eq__(self, other):
305
        if not isinstance(other, RemoteBzrDirFormat):
306
            return False
307
        return self.get_format_description() == other.get_format_description()
308
309
    def __return_repository_format(self):
310
        # Always return a RemoteRepositoryFormat object, but if a specific bzr
311
        # repository format has been asked for, tell the RemoteRepositoryFormat
312
        # that it should use that for init() etc.
313
        result = RemoteRepositoryFormat()
314
        custom_format = getattr(self, '_repository_format', None)
315
        if custom_format:
316
            if isinstance(custom_format, RemoteRepositoryFormat):
317
                return custom_format
318
            else:
319
                # We will use the custom format to create repositories over the
320
                # wire; expose its details like rich_root_data for code to
321
                # query
322
                result._custom_format = custom_format
323
        return result
324
325
    def get_branch_format(self):
326
        result = _mod_bzrdir.BzrDirMetaFormat1.get_branch_format(self)
327
        if not isinstance(result, RemoteBranchFormat):
328
            new_result = RemoteBranchFormat()
329
            new_result._custom_format = result
330
            # cache the result
331
            self.set_branch_format(new_result)
332
            result = new_result
333
        return result
334
335
    repository_format = property(__return_repository_format,
336
        _mod_bzrdir.BzrDirMetaFormat1._set_repository_format) #.im_func)
337
338
6270.1.6 by Jelmer Vernooij
Provide RemoteControlStore and RemoteBranchStore.
339
class RemoteControlStore(config.IniFileStore):
340
    """Control store which attempts to use HPSS calls to retrieve control store.
341
342
    Note that this is specific to bzr-based formats.
343
    """
344
345
    def __init__(self, bzrdir):
346
        super(RemoteControlStore, self).__init__()
347
        self.bzrdir = bzrdir
6270.1.7 by Jelmer Vernooij
Use _ensure_real.
348
        self._real_store = None
6270.1.6 by Jelmer Vernooij
Provide RemoteControlStore and RemoteBranchStore.
349
6270.1.8 by Jelmer Vernooij
Fix RemoteControlStore.
350
    def lock_write(self, token=None):
351
        self._ensure_real()
352
        return self._real_store.lock_write(token)
353
354
    def unlock(self):
355
        self._ensure_real()
356
        return self._real_store.unlock()
357
358
    @needs_write_lock
359
    def save(self):
360
        # We need to be able to override the undecorated implementation
361
        self.save_without_locking()
362
363
    def save_without_locking(self):
364
        super(RemoteControlStore, self).save()
365
6270.1.7 by Jelmer Vernooij
Use _ensure_real.
366
    def _ensure_real(self):
367
        self.bzrdir._ensure_real()
6270.1.8 by Jelmer Vernooij
Fix RemoteControlStore.
368
        if self._real_store is None:
369
            self._real_store = config.ControlStore(self.bzrdir)
6270.1.6 by Jelmer Vernooij
Provide RemoteControlStore and RemoteBranchStore.
370
371
    def external_url(self):
6270.1.15 by Jelmer Vernooij
Implement sensible .external_url().
372
        return self.bzrdir.user_url
6270.1.6 by Jelmer Vernooij
Provide RemoteControlStore and RemoteBranchStore.
373
374
    def _load_content(self):
375
        medium = self.bzrdir._client._medium
376
        path = self.bzrdir._path_for_remote_call(self.bzrdir._client)
377
        try:
378
            response, handler = self.bzrdir._call_expecting_body(
379
                'BzrDir.get_config_file', path)
380
        except errors.UnknownSmartMethod:
6270.1.7 by Jelmer Vernooij
Use _ensure_real.
381
            self._ensure_real()
382
            return self._real_store._load_content()
6270.1.6 by Jelmer Vernooij
Provide RemoteControlStore and RemoteBranchStore.
383
        if len(response) and response[0] != 'ok':
384
            raise errors.UnexpectedSmartServerResponse(response)
385
        return handler.read_body_bytes()
386
387
    def _save_content(self, content):
6270.1.12 by Jelmer Vernooij
Note HPSS usage.
388
        # FIXME JRV 2011-11-22: Ideally this should use a
389
        # HPSS call too, but at the moment it is not possible
390
        # to write lock control directories.
391
        self._ensure_real()
392
        return self._real_store._save_content(content)
6270.1.6 by Jelmer Vernooij
Provide RemoteControlStore and RemoteBranchStore.
393
394
5712.3.13 by Jelmer Vernooij
Add Prober.known_formats().
395
class RemoteBzrDir(_mod_bzrdir.BzrDir, _RpcHelper):
2018.5.163 by Andrew Bennetts
Deal with various review comments from Robert.
396
    """Control directory on a remote server, accessed via bzr:// or similar."""
1752.2.30 by Martin Pool
Start adding a RemoteBzrDir, etc
397
4634.47.5 by Andrew Bennetts
Add tests, and fix BzrDirMeta1.has_workingtree which was failing if the local transport is decorated with a ChrootTransport or similar.
398
    def __init__(self, transport, format, _client=None, _force_probe=False):
2018.5.51 by Wouter van Heyst
Test and implement RemoteBranch.last_revision_info()
399
        """Construct a RemoteBzrDir.
400
401
        :param _client: Private parameter for testing. Disables probing and the
402
            use of a real bzrdir.
403
        """
5712.3.13 by Jelmer Vernooij
Add Prober.known_formats().
404
        _mod_bzrdir.BzrDir.__init__(self, transport, format)
1752.2.31 by Martin Pool
[broken] some support for write operations over hpss
405
        # this object holds a delegated bzrdir that uses file-level operations
406
        # to talk to the other side
2018.5.70 by Robert Collins
Only try to get real repositories when an operation requires them.
407
        self._real_bzrdir = None
4634.47.3 by Andrew Bennetts
Add a BzrDir.open_2.1 verb that indicates if there is a workingtree present. Removes the last 2 VFS calls from incremental pushes.
408
        self._has_working_tree = 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.
409
        # 1-shot cache for the call pattern 'create_branch; open_branch' - see
410
        # create_branch for details.
411
        self._next_open_branch_result = None
2018.14.1 by Andrew Bennetts
Update to current hpss branch? Fix lots of test failures.
412
413
        if _client is None:
3313.2.3 by Andrew Bennetts
Deprecate Transport.get_shared_medium.
414
            medium = transport.get_smart_medium()
3431.3.2 by Andrew Bennetts
Remove 'base' from _SmartClient entirely, now that the medium has it.
415
            self._client = client._SmartClient(medium)
2018.14.1 by Andrew Bennetts
Update to current hpss branch? Fix lots of test failures.
416
        else:
417
            self._client = _client
4634.47.5 by Andrew Bennetts
Add tests, and fix BzrDirMeta1.has_workingtree which was failing if the local transport is decorated with a ChrootTransport or similar.
418
            if not _force_probe:
419
                return
420
421
        self._probe_bzrdir()
422
4964.2.1 by Martin Pool
Add RemoteBzrDir repr
423
    def __repr__(self):
424
        return '%s(%r)' % (self.__class__.__name__, self._client)
425
4634.47.5 by Andrew Bennetts
Add tests, and fix BzrDirMeta1.has_workingtree which was failing if the local transport is decorated with a ChrootTransport or similar.
426
    def _probe_bzrdir(self):
427
        medium = self._client._medium
2018.14.1 by Andrew Bennetts
Update to current hpss branch? Fix lots of test failures.
428
        path = self._path_for_remote_call(self._client)
4634.47.3 by Andrew Bennetts
Add a BzrDir.open_2.1 verb that indicates if there is a workingtree present. Removes the last 2 VFS calls from incremental pushes.
429
        if medium._is_remote_before((2, 1)):
430
            self._rpc_open(path)
431
            return
432
        try:
433
            self._rpc_open_2_1(path)
434
            return
435
        except errors.UnknownSmartMethod:
436
            medium._remember_remote_is_before((2, 1))
437
            self._rpc_open(path)
438
439
    def _rpc_open_2_1(self, path):
440
        response = self._call('BzrDir.open_2.1', path)
441
        if response == ('no',):
442
            raise errors.NotBranchError(path=self.root_transport.base)
443
        elif response[0] == 'yes':
444
            if response[1] == 'yes':
445
                self._has_working_tree = True
446
            elif response[1] == 'no':
447
                self._has_working_tree = False
448
            else:
449
                raise errors.UnexpectedSmartServerResponse(response)
450
        else:
451
            raise errors.UnexpectedSmartServerResponse(response)
452
453
    def _rpc_open(self, path):
3786.2.3 by Andrew Bennetts
Remove duplicated 'call & translate errors' code in bzrlib.remote.
454
        response = self._call('BzrDir.open', path)
2018.5.163 by Andrew Bennetts
Deal with various review comments from Robert.
455
        if response not in [('yes',), ('no',)]:
456
            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.
457
        if response == ('no',):
4634.47.3 by Andrew Bennetts
Add a BzrDir.open_2.1 verb that indicates if there is a workingtree present. Removes the last 2 VFS calls from incremental pushes.
458
            raise errors.NotBranchError(path=self.root_transport.base)
1752.2.31 by Martin Pool
[broken] some support for write operations over hpss
459
2018.5.70 by Robert Collins
Only try to get real repositories when an operation requires them.
460
    def _ensure_real(self):
461
        """Ensure that there is a _real_bzrdir set.
462
2018.5.163 by Andrew Bennetts
Deal with various review comments from Robert.
463
        Used before calls to self._real_bzrdir.
2018.5.70 by Robert Collins
Only try to get real repositories when an operation requires them.
464
        """
465
        if not self._real_bzrdir:
4789.2.1 by Robert Collins
Trigger hpssvfs backtrace dumps with RemoteBzrDir._ensure_real.
466
            if 'hpssvfs' in debug.debug_flags:
467
                import traceback
468
                warning('VFS BzrDir access triggered\n%s',
469
                    ''.join(traceback.format_stack()))
5712.3.13 by Jelmer Vernooij
Add Prober.known_formats().
470
            self._real_bzrdir = _mod_bzrdir.BzrDir.open_from_transport(
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.
471
                self.root_transport, _server_formats=False)
4070.2.1 by Robert Collins
Add a BzrDirFormat.network_name.
472
            self._format._network_name = \
473
                self._real_bzrdir._format.network_name()
2018.5.70 by Robert Collins
Only try to get real repositories when an operation requires them.
474
3786.2.3 by Andrew Bennetts
Remove duplicated 'call & translate errors' code in bzrlib.remote.
475
    def _translate_error(self, err, **context):
476
        _translate_error(err, bzrdir=self, **context)
477
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.
478
    def break_lock(self):
479
        # Prevent aliasing problems in the next_open_branch_result cache.
480
        # See create_branch for rationale.
481
        self._next_open_branch_result = None
5712.3.13 by Jelmer Vernooij
Add Prober.known_formats().
482
        return _mod_bzrdir.BzrDir.break_lock(self)
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.
483
4070.2.3 by Robert Collins
Get BzrDir.cloning_metadir working.
484
    def _vfs_cloning_metadir(self, require_stacking=False):
3242.3.28 by Aaron Bentley
Use repository acquisition policy for sprouting
485
        self._ensure_real()
4070.2.3 by Robert Collins
Get BzrDir.cloning_metadir working.
486
        return self._real_bzrdir.cloning_metadir(
487
            require_stacking=require_stacking)
488
489
    def cloning_metadir(self, require_stacking=False):
490
        medium = self._client._medium
491
        if medium._is_remote_before((1, 13)):
492
            return self._vfs_cloning_metadir(require_stacking=require_stacking)
493
        verb = 'BzrDir.cloning_metadir'
494
        if require_stacking:
495
            stacking = 'True'
496
        else:
497
            stacking = 'False'
498
        path = self._path_for_remote_call(self._client)
499
        try:
500
            response = self._call(verb, path, stacking)
501
        except errors.UnknownSmartMethod:
4094.1.1 by Andrew Bennetts
Add some medium._remember_is_before((1, 13)) calls.
502
            medium._remember_remote_is_before((1, 13))
4070.2.3 by Robert Collins
Get BzrDir.cloning_metadir working.
503
            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
504
        except errors.UnknownErrorFromSmartServer, err:
505
            if err.error_tuple != ('BranchReference',):
506
                raise
507
            # We need to resolve the branch reference to determine the
508
            # cloning_metadir.  This causes unnecessary RPCs to open the
509
            # referenced branch (and bzrdir, etc) but only when the caller
510
            # didn't already resolve the branch reference.
511
            referenced_branch = self.open_branch()
512
            return referenced_branch.bzrdir.cloning_metadir()
4070.2.3 by Robert Collins
Get BzrDir.cloning_metadir working.
513
        if len(response) != 3:
514
            raise errors.UnexpectedSmartServerResponse(response)
4070.7.4 by Andrew Bennetts
Deal with branch references better in BzrDir.cloning_metadir RPC (changes protocol).
515
        control_name, repo_name, branch_info = response
516
        if len(branch_info) != 2:
517
            raise errors.UnexpectedSmartServerResponse(response)
518
        branch_ref, branch_name = branch_info
5363.2.25 by Jelmer Vernooij
Fix some test failures now that bzrlib.controldir.network_format_registry has moved.
519
        format = controldir.network_format_registry.get(control_name)
4070.2.3 by Robert Collins
Get BzrDir.cloning_metadir working.
520
        if repo_name:
5712.3.13 by Jelmer Vernooij
Add Prober.known_formats().
521
            format.repository_format = _mod_repository.network_format_registry.get(
4070.2.3 by Robert Collins
Get BzrDir.cloning_metadir working.
522
                repo_name)
4084.2.2 by Robert Collins
Review feedback.
523
        if branch_ref == 'ref':
4070.7.4 by Andrew Bennetts
Deal with branch references better in BzrDir.cloning_metadir RPC (changes protocol).
524
            # XXX: we need possible_transports here to avoid reopening the
4070.7.5 by Andrew Bennetts
Tweak comment.
525
            # connection to the referenced location
5712.3.13 by Jelmer Vernooij
Add Prober.known_formats().
526
            ref_bzrdir = _mod_bzrdir.BzrDir.open(branch_name)
4070.7.4 by Andrew Bennetts
Deal with branch references better in BzrDir.cloning_metadir RPC (changes protocol).
527
            branch_format = ref_bzrdir.cloning_metadir().get_branch_format()
528
            format.set_branch_format(branch_format)
4084.2.2 by Robert Collins
Review feedback.
529
        elif branch_ref == 'branch':
4070.7.4 by Andrew Bennetts
Deal with branch references better in BzrDir.cloning_metadir RPC (changes protocol).
530
            if branch_name:
531
                format.set_branch_format(
532
                    branch.network_format_registry.get(branch_name))
533
        else:
534
            raise errors.UnexpectedSmartServerResponse(response)
4070.2.3 by Robert Collins
Get BzrDir.cloning_metadir working.
535
        return format
3242.3.28 by Aaron Bentley
Use repository acquisition policy for sprouting
536
1752.2.39 by Martin Pool
[broken] implement upgrade apis on remote bzrdirs
537
    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.
538
        # as per meta1 formats - just delegate to the format object which may
539
        # be parameterised.
540
        result = self._format.repository_format.initialize(self, shared)
541
        if not isinstance(result, RemoteRepository):
542
            return self.open_repository()
543
        else:
544
            return result
1752.2.50 by Andrew Bennetts
Implement RemoteBzrDir.create_{branch,workingtree}
545
2796.2.19 by Aaron Bentley
Support reconfigure --lightweight-checkout
546
    def destroy_repository(self):
547
        """See BzrDir.destroy_repository"""
6266.2.1 by Jelmer Vernooij
New HPSS call BzrDir.destroy_repository.
548
        path = self._path_for_remote_call(self._client)
549
        try:
550
            response = self._call('BzrDir.destroy_repository', path)
551
        except errors.UnknownSmartMethod:
552
            self._ensure_real()
553
            self._real_bzrdir.destroy_repository()
554
            return
555
        if response[0] != 'ok':
556
            raise SmartProtocolError('unexpected response code %s' % (response,))
2796.2.19 by Aaron Bentley
Support reconfigure --lightweight-checkout
557
6123.9.12 by Jelmer Vernooij
Add append_revisions_only argument to BranchFormat.initialize.
558
    def create_branch(self, name=None, repository=None,
559
                      append_revisions_only=None):
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.
560
        # as per meta1 formats - just delegate to the format object which may
561
        # be parameterised.
5051.3.10 by Jelmer Vernooij
Pass colocated branch name around in more places.
562
        real_branch = self._format.get_branch_format().initialize(self,
6123.9.12 by Jelmer Vernooij
Add append_revisions_only argument to BranchFormat.initialize.
563
            name=name, repository=repository,
564
            append_revisions_only=append_revisions_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.
565
        if not isinstance(real_branch, RemoteBranch):
5536.1.1 by Andrew Bennetts
Avoid reopening (and relocking) the same branches/repositories in ControlDir.sprout. Still a few rough edges, but the tests I've run are passing.
566
            if not isinstance(repository, RemoteRepository):
5536.1.10 by Andrew Bennetts
Give more helpful message in AssertionErrors, just in case.
567
                raise AssertionError(
568
                    'need a RemoteRepository to use with RemoteBranch, got %r'
569
                    % (repository,))
5536.1.1 by Andrew Bennetts
Avoid reopening (and relocking) the same branches/repositories in ControlDir.sprout. Still a few rough edges, but the tests I've run are passing.
570
            result = RemoteBranch(self, repository, real_branch, name=name)
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.
571
        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.
572
            result = real_branch
573
        # BzrDir.clone_on_transport() uses the result of create_branch but does
574
        # not return it to its callers; we save approximately 8% of our round
575
        # trips by handing the branch we created back to the first caller to
576
        # open_branch rather than probing anew. Long term we need a API in
577
        # bzrdir that doesn't discard result objects (like result_branch).
578
        # RBC 20090225
579
        self._next_open_branch_result = result
580
        return result
1752.2.50 by Andrew Bennetts
Implement RemoteBzrDir.create_{branch,workingtree}
581
5051.3.3 by Jelmer Vernooij
Add tests for colo branches.
582
    def destroy_branch(self, name=None):
2796.2.16 by Aaron Bentley
Documentation updates from review
583
        """See BzrDir.destroy_branch"""
6266.4.1 by Jelmer Vernooij
HPSS call 'BzrDir.destroy_branch'.
584
        path = self._path_for_remote_call(self._client)
585
        try:
6266.4.3 by Jelmer Vernooij
fix tests.
586
            if name is not None:
587
                args = (name, )
588
            else:
589
                args = ()
590
            response = self._call('BzrDir.destroy_branch', path, *args)
6266.4.1 by Jelmer Vernooij
HPSS call 'BzrDir.destroy_branch'.
591
        except errors.UnknownSmartMethod:
592
            self._ensure_real()
593
            self._real_bzrdir.destroy_branch(name=name)
594
            self._next_open_branch_result = None
595
            return
6266.4.3 by Jelmer Vernooij
fix tests.
596
        self._next_open_branch_result = None
6266.4.1 by Jelmer Vernooij
HPSS call 'BzrDir.destroy_branch'.
597
        if response[0] != 'ok':
598
            raise SmartProtocolError('unexpected response code %s' % (response,))
2796.2.6 by Aaron Bentley
Implement destroy_branch
599
5042.1.1 by Neil Martinsen-Burrell
Fix signature of RemoteBzrDir.create_workingtree
600
    def create_workingtree(self, revision_id=None, from_branch=None,
601
        accelerator_tree=None, hardlink=False):
2018.5.174 by Andrew Bennetts
Various nits discovered by pyflakes.
602
        raise errors.NotLocalUrl(self.transport.base)
1752.2.39 by Martin Pool
[broken] implement upgrade apis on remote bzrdirs
603
5147.4.1 by Jelmer Vernooij
Pass branch names in more places.
604
    def find_branch_format(self, name=None):
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.
605
        """Find the branch 'format' for this bzrdir.
606
607
        This might be a synthetic object for e.g. RemoteBranch and SVN.
608
        """
5147.4.3 by Jelmer Vernooij
Support branch name argument to BzrDir.get_branch_reference.
609
        b = self.open_branch(name=name)
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.
610
        return b._format
611
5147.4.3 by Jelmer Vernooij
Support branch name argument to BzrDir.get_branch_reference.
612
    def get_branch_reference(self, name=None):
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.
613
        """See BzrDir.get_branch_reference()."""
5147.4.3 by Jelmer Vernooij
Support branch name argument to BzrDir.get_branch_reference.
614
        if name is not None:
615
            # XXX JRV20100304: Support opening colocated branches
616
            raise errors.NoColocatedBranchSupport(self)
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.
617
        response = self._get_branch_reference()
618
        if response[0] == 'ref':
619
            return response[1]
620
        else:
621
            return None
622
623
    def _get_branch_reference(self):
2018.14.1 by Andrew Bennetts
Update to current hpss branch? Fix lots of test failures.
624
        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.
625
        medium = self._client._medium
4734.4.8 by Andrew Bennetts
Fix HPSS tests; pass 'location is a repository' message via smart server when possible (adds BzrDir.open_branchV3 verb).
626
        candidate_calls = [
627
            ('BzrDir.open_branchV3', (2, 1)),
628
            ('BzrDir.open_branchV2', (1, 13)),
629
            ('BzrDir.open_branch', None),
630
            ]
631
        for verb, required_version in candidate_calls:
632
            if required_version and medium._is_remote_before(required_version):
633
                continue
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.
634
            try:
4734.4.8 by Andrew Bennetts
Fix HPSS tests; pass 'location is a repository' message via smart server when possible (adds BzrDir.open_branchV3 verb).
635
                response = self._call(verb, 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.
636
            except errors.UnknownSmartMethod:
4734.4.8 by Andrew Bennetts
Fix HPSS tests; pass 'location is a repository' message via smart server when possible (adds BzrDir.open_branchV3 verb).
637
                if required_version is None:
638
                    raise
639
                medium._remember_remote_is_before(required_version)
640
            else:
641
                break
642
        if verb == 'BzrDir.open_branch':
643
            if response[0] != 'ok':
644
                raise errors.UnexpectedSmartServerResponse(response)
645
            if response[1] != '':
646
                return ('ref', response[1])
647
            else:
648
                return ('branch', '')
649
        if response[0] not in ('ref', '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.
650
            raise errors.UnexpectedSmartServerResponse(response)
4734.4.8 by Andrew Bennetts
Fix HPSS tests; pass 'location is a repository' message via smart server when possible (adds BzrDir.open_branchV3 verb).
651
        return response
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.
652
5147.4.1 by Jelmer Vernooij
Pass branch names in more places.
653
    def _get_tree_branch(self, name=None):
3211.4.1 by Robert Collins
* ``RemoteBzrDir._get_tree_branch`` no longer triggers ``_ensure_real``,
654
        """See BzrDir._get_tree_branch()."""
5147.4.1 by Jelmer Vernooij
Pass branch names in more places.
655
        return None, self.open_branch(name=name)
3211.4.1 by Robert Collins
* ``RemoteBzrDir._get_tree_branch`` no longer triggers ``_ensure_real``,
656
5051.3.4 by Jelmer Vernooij
Support name to BzrDir.open_branch.
657
    def open_branch(self, name=None, unsupported=False,
6305.3.2 by Jelmer Vernooij
Only make a single connection.
658
                    ignore_fallbacks=False, possible_transports=None):
5051.3.4 by Jelmer Vernooij
Support name to BzrDir.open_branch.
659
        if unsupported:
3376.2.4 by Martin Pool
Remove every assert statement from bzrlib!
660
            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.
661
        if self._next_open_branch_result is not None:
662
            # See create_branch for details.
663
            result = self._next_open_branch_result
664
            self._next_open_branch_result = None
665
            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.
666
        response = self._get_branch_reference()
667
        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.
668
            # a branch reference, use the existing BranchReference logic.
669
            format = BranchReferenceFormat()
5051.3.10 by Jelmer Vernooij
Pass colocated branch name around in more places.
670
            return format.open(self, name=name, _found=True,
6305.3.2 by Jelmer Vernooij
Only make a single connection.
671
                location=response[1], ignore_fallbacks=ignore_fallbacks,
672
                possible_transports=possible_transports)
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.
673
        branch_format_name = response[1]
674
        if not branch_format_name:
675
            branch_format_name = None
676
        format = RemoteBranchFormat(network_name=branch_format_name)
4160.2.6 by Andrew Bennetts
Add ignore_fallbacks flag.
677
        return RemoteBranch(self, self.find_repository(), format=format,
6305.3.6 by Jelmer Vernooij
Pass possible_transports along for remote branches.
678
            setup_stacking=not ignore_fallbacks, name=name,
679
            possible_transports=possible_transports)
3943.8.1 by Marius Kruger
remove all trailing whitespace from bzr source
680
4053.1.1 by Robert Collins
New version of the BzrDir.find_repository verb supporting _network_name to support removing more _ensure_real calls.
681
    def _open_repo_v1(self, path):
682
        verb = 'BzrDir.find_repository'
683
        response = self._call(verb, path)
684
        if response[0] != 'ok':
685
            raise errors.UnexpectedSmartServerResponse(response)
686
        # servers that only support the v1 method don't support external
687
        # references either.
688
        self._ensure_real()
689
        repo = self._real_bzrdir.open_repository()
690
        response = response + ('no', repo._format.network_name())
691
        return response, repo
692
693
    def _open_repo_v2(self, path):
694
        verb = 'BzrDir.find_repositoryV2'
695
        response = self._call(verb, path)
696
        if response[0] != 'ok':
697
            raise errors.UnexpectedSmartServerResponse(response)
698
        self._ensure_real()
699
        repo = self._real_bzrdir.open_repository()
700
        response = response + (repo._format.network_name(),)
701
        return response, repo
702
703
    def _open_repo_v3(self, path):
704
        verb = 'BzrDir.find_repositoryV3'
4053.1.2 by Robert Collins
Actually make this branch work.
705
        medium = self._client._medium
706
        if medium._is_remote_before((1, 13)):
707
            raise errors.UnknownSmartMethod(verb)
4094.1.1 by Andrew Bennetts
Add some medium._remember_is_before((1, 13)) calls.
708
        try:
709
            response = self._call(verb, path)
710
        except errors.UnknownSmartMethod:
711
            medium._remember_remote_is_before((1, 13))
712
            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.
713
        if response[0] != 'ok':
714
            raise errors.UnexpectedSmartServerResponse(response)
715
        return response, None
716
1752.2.31 by Martin Pool
[broken] some support for write operations over hpss
717
    def open_repository(self):
2018.14.1 by Andrew Bennetts
Update to current hpss branch? Fix lots of test failures.
718
        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.
719
        response = None
720
        for probe in [self._open_repo_v3, self._open_repo_v2,
721
            self._open_repo_v1]:
722
            try:
723
                response, real_repo = probe(path)
724
                break
725
            except errors.UnknownSmartMethod:
726
                pass
727
        if response is None:
728
            raise errors.UnknownSmartMethod('BzrDir.find_repository{3,2,}')
3245.4.24 by Andrew Bennetts
Consistently raise errors from the server as ErrorFromSmartServer exceptions.
729
        if response[0] != 'ok':
730
            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.
731
        if len(response) != 6:
3376.2.4 by Martin Pool
Remove every assert statement from bzrlib!
732
            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.
733
        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.
734
            # repo is at this dir.
735
            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.
736
            # Used to support creating a real format instance when needed.
737
            format._creating_bzrdir = self
3990.5.1 by Andrew Bennetts
Add network_name() to RepositoryFormat.
738
            remote_repo = RemoteRepository(self, format)
739
            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.
740
            if real_repo is not None:
741
                remote_repo._set_real_repository(real_repo)
3990.5.1 by Andrew Bennetts
Add network_name() to RepositoryFormat.
742
            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.
743
        else:
744
            raise errors.NoRepositoryPresent(self)
1752.2.30 by Martin Pool
Start adding a RemoteBzrDir, etc
745
4634.47.5 by Andrew Bennetts
Add tests, and fix BzrDirMeta1.has_workingtree which was failing if the local transport is decorated with a ChrootTransport or similar.
746
    def has_workingtree(self):
4634.47.3 by Andrew Bennetts
Add a BzrDir.open_2.1 verb that indicates if there is a workingtree present. Removes the last 2 VFS calls from incremental pushes.
747
        if self._has_working_tree is None:
6266.3.1 by Jelmer Vernooij
Add HPSS call for BzrDir.has_workingtree.
748
            path = self._path_for_remote_call(self._client)
749
            try:
750
                response = self._call('BzrDir.has_workingtree', path)
751
            except errors.UnknownSmartMethod:
752
                self._ensure_real()
753
                self._has_working_tree = self._real_bzrdir.has_workingtree()
754
            else:
755
                if response[0] not in ('yes', 'no'):
756
                    raise SmartProtocolError('unexpected response code %s' % (response,))
757
                self._has_working_tree = (response[0] == 'yes')
4634.47.5 by Andrew Bennetts
Add tests, and fix BzrDirMeta1.has_workingtree which was failing if the local transport is decorated with a ChrootTransport or similar.
758
        return self._has_working_tree
759
760
    def open_workingtree(self, recommend_upgrade=True):
761
        if self.has_workingtree():
2445.1.1 by Andrew Bennetts
Make RemoteBzrDir.open_workingtree raise NoWorkingTree rather than NotLocalUrl
762
            raise errors.NotLocalUrl(self.root_transport)
763
        else:
764
            raise errors.NoWorkingTree(self.root_transport.base)
1752.2.50 by Andrew Bennetts
Implement RemoteBzrDir.create_{branch,workingtree}
765
2018.5.42 by Robert Collins
Various hopefully improvements, but wsgi is broken, handing over to spiv :).
766
    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.
767
        """Return the path to be used for this bzrdir in a remote call."""
5268.7.29 by Jelmer Vernooij
Fix remote tests.
768
        return urlutils.split_segment_parameters_raw(
769
            client.remote_path_from_transport(self.root_transport))[0]
2018.6.1 by Robert Collins
Implement a BzrDir.open_branch smart server method for opening a branch without VFS.
770
5051.3.10 by Jelmer Vernooij
Pass colocated branch name around in more places.
771
    def get_branch_transport(self, branch_format, name=None):
2018.5.162 by Andrew Bennetts
Add some missing _ensure_real calls, and a missing import.
772
        self._ensure_real()
5051.3.10 by Jelmer Vernooij
Pass colocated branch name around in more places.
773
        return self._real_bzrdir.get_branch_transport(branch_format, name=name)
1752.2.31 by Martin Pool
[broken] some support for write operations over hpss
774
1752.2.43 by Andrew Bennetts
Fix get_{branch,repository,workingtree}_transport.
775
    def get_repository_transport(self, repository_format):
2018.5.162 by Andrew Bennetts
Add some missing _ensure_real calls, and a missing import.
776
        self._ensure_real()
1752.2.43 by Andrew Bennetts
Fix get_{branch,repository,workingtree}_transport.
777
        return self._real_bzrdir.get_repository_transport(repository_format)
778
779
    def get_workingtree_transport(self, workingtree_format):
2018.5.162 by Andrew Bennetts
Add some missing _ensure_real calls, and a missing import.
780
        self._ensure_real()
1752.2.43 by Andrew Bennetts
Fix get_{branch,repository,workingtree}_transport.
781
        return self._real_bzrdir.get_workingtree_transport(workingtree_format)
782
1752.2.39 by Martin Pool
[broken] implement upgrade apis on remote bzrdirs
783
    def can_convert_format(self):
784
        """Upgrading of remote bzrdirs is not supported yet."""
785
        return False
786
5670.1.1 by Jelmer Vernooij
Remove all methods and arguments that were deprecated before bzr 2.0.0.
787
    def needs_format_conversion(self, format):
1752.2.39 by Martin Pool
[broken] implement upgrade apis on remote bzrdirs
788
        """Upgrading of remote bzrdirs is not supported yet."""
789
        return False
790
4288.1.1 by Robert Collins
Add support for a RemoteBzrDirConfig to support optimising push operations which need to look for default stacking locations.
791
    def _get_config(self):
792
        return RemoteBzrDirConfig(self)
3567.1.3 by Michael Hudson
fix problem
793
6270.1.19 by Jelmer Vernooij
Some changes discussed with vila on IRC.
794
    def _get_config_store(self):
795
        return RemoteControlStore(self)
6270.1.4 by Jelmer Vernooij
Add Branch.get_config_stack / BzrDir.get_config_stack.
796
1752.2.31 by Martin Pool
[broken] some support for write operations over hpss
797
5815.4.5 by Jelmer Vernooij
Use MetaDirVersionedFileRepositoryFormat (a Soyuz worthy name).
798
class RemoteRepositoryFormat(vf_repository.VersionedFileRepositoryFormat):
2018.5.159 by Andrew Bennetts
Rename SmartClient to _SmartClient.
799
    """Format for repositories accessed over a _SmartClient.
1752.2.31 by Martin Pool
[broken] some support for write operations over hpss
800
1752.2.50 by Andrew Bennetts
Implement RemoteBzrDir.create_{branch,workingtree}
801
    Instances of this repository are represented by RemoteRepository
1752.2.31 by Martin Pool
[broken] some support for write operations over hpss
802
    instances.
2018.5.118 by Robert Collins
Fix RemoteRepositoryFormat to have appropriate rich_root_data and support_tree_reference.
803
3128.1.3 by Vincent Ladeuil
Since we are there s/parameteris.*/parameteriz&/.
804
    The RemoteRepositoryFormat is parameterized during construction
2018.5.118 by Robert Collins
Fix RemoteRepositoryFormat to have appropriate rich_root_data and support_tree_reference.
805
    to reflect the capabilities of the real, remote format. Specifically
2018.5.138 by Robert Collins
Merge bzr.dev.
806
    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.
807
    on a per instance basis, and are not set (and should not be) at
808
    the class level.
3990.5.3 by Robert Collins
Docs and polish on RepositoryFormat.network_name.
809
4032.1.1 by John Arbash Meinel
Merge the removal of all trailing whitespace, and resolve conflicts.
810
    :ivar _custom_format: If set, a specific concrete repository format that
3990.5.3 by Robert Collins
Docs and polish on RepositoryFormat.network_name.
811
        will be used when initializing a repository with this
812
        RemoteRepositoryFormat.
813
    :ivar _creating_repo: If set, the repository object that this
814
        RemoteRepositoryFormat was created for: it can be called into
3990.5.4 by Robert Collins
Review feedback.
815
        to obtain data like the network name.
1752.2.31 by Martin Pool
[broken] some support for write operations over hpss
816
    """
817
3543.1.2 by Michael Hudson
the two character fix
818
    _matchingbzrdir = RemoteBzrDirFormat()
5684.2.1 by Jelmer Vernooij
Add bzrlib.tests.per_repository_vf.
819
    supports_full_versioned_files = True
5684.2.6 by Jelmer Vernooij
Implement .supports_funky_characters and .supports_leaving_lock.
820
    supports_leaving_lock = True
1752.2.31 by Martin Pool
[broken] some support for write operations over hpss
821
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.
822
    def __init__(self):
5712.3.17 by Jelmer Vernooij
more fixes.
823
        _mod_repository.RepositoryFormat.__init__(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.
824
        self._custom_format = None
4017.3.2 by Robert Collins
Reduce the number of round trips required to create a repository over the network.
825
        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.
826
        self._creating_bzrdir = None
5766.1.1 by Jelmer Vernooij
Make revision-graph-can-have-wrong-parents a repository format attribute rather than a repository method.
827
        self._revision_graph_can_have_wrong_parents = None
4476.3.15 by Andrew Bennetts
Partially working fallback for pre-1.17 servers.
828
        self._supports_chks = None
4118.1.1 by Andrew Bennetts
Fix performance regression (many small round-trips) when pushing to a remote pack, and tidy the tests.
829
        self._supports_external_lookups = None
830
        self._supports_tree_reference = None
5684.2.6 by Jelmer Vernooij
Implement .supports_funky_characters and .supports_leaving_lock.
831
        self._supports_funky_characters = None
6145.2.2 by Jelmer Vernooij
Set supports_nesting_repositories.
832
        self._supports_nesting_repositories = None
4118.1.1 by Andrew Bennetts
Fix performance regression (many small round-trips) when pushing to a remote pack, and tidy the tests.
833
        self._rich_root_data = None
834
4608.1.2 by Martin Pool
Add RemoteRepositoryFormat repr
835
    def __repr__(self):
836
        return "%s(_network_name=%r)" % (self.__class__.__name__,
837
            self._network_name)
838
4118.1.1 by Andrew Bennetts
Fix performance regression (many small round-trips) when pushing to a remote pack, and tidy the tests.
839
    @property
4183.5.1 by Robert Collins
Add RepositoryFormat.fast_deltas to signal fast delta creation.
840
    def fast_deltas(self):
841
        self._ensure_real()
842
        return self._custom_format.fast_deltas
843
844
    @property
4118.1.1 by Andrew Bennetts
Fix performance regression (many small round-trips) when pushing to a remote pack, and tidy the tests.
845
    def rich_root_data(self):
846
        if self._rich_root_data is None:
847
            self._ensure_real()
848
            self._rich_root_data = self._custom_format.rich_root_data
849
        return self._rich_root_data
850
851
    @property
4476.3.15 by Andrew Bennetts
Partially working fallback for pre-1.17 servers.
852
    def supports_chks(self):
853
        if self._supports_chks is None:
854
            self._ensure_real()
855
            self._supports_chks = self._custom_format.supports_chks
856
        return self._supports_chks
857
858
    @property
4118.1.1 by Andrew Bennetts
Fix performance regression (many small round-trips) when pushing to a remote pack, and tidy the tests.
859
    def supports_external_lookups(self):
860
        if self._supports_external_lookups is None:
861
            self._ensure_real()
862
            self._supports_external_lookups = \
4104.4.2 by Robert Collins
Fix test_source for 1.13 landing.
863
                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.
864
        return self._supports_external_lookups
865
866
    @property
5684.2.6 by Jelmer Vernooij
Implement .supports_funky_characters and .supports_leaving_lock.
867
    def supports_funky_characters(self):
868
        if self._supports_funky_characters is None:
869
            self._ensure_real()
870
            self._supports_funky_characters = \
871
                self._custom_format.supports_funky_characters
872
        return self._supports_funky_characters
873
874
    @property
6145.2.2 by Jelmer Vernooij
Set supports_nesting_repositories.
875
    def supports_nesting_repositories(self):
876
        if self._supports_nesting_repositories is None:
877
            self._ensure_real()
878
            self._supports_nesting_repositories = \
879
                self._custom_format.supports_nesting_repositories
880
        return self._supports_nesting_repositories
881
882
    @property
4118.1.1 by Andrew Bennetts
Fix performance regression (many small round-trips) when pushing to a remote pack, and tidy the tests.
883
    def supports_tree_reference(self):
884
        if self._supports_tree_reference is None:
885
            self._ensure_real()
886
            self._supports_tree_reference = \
887
                self._custom_format.supports_tree_reference
888
        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.
889
5766.1.1 by Jelmer Vernooij
Make revision-graph-can-have-wrong-parents a repository format attribute rather than a repository method.
890
    @property
891
    def revision_graph_can_have_wrong_parents(self):
892
        if self._revision_graph_can_have_wrong_parents is None:
893
            self._ensure_real()
894
            self._revision_graph_can_have_wrong_parents = \
895
                self._custom_format.revision_graph_can_have_wrong_parents
896
        return self._revision_graph_can_have_wrong_parents
897
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.
898
    def _vfs_initialize(self, a_bzrdir, shared):
899
        """Helper for common code in initialize."""
900
        if self._custom_format:
901
            # Custom format requested
902
            result = self._custom_format.initialize(a_bzrdir, shared=shared)
903
        elif self._creating_bzrdir is not None:
904
            # Use the format that the repository we were created to back
905
            # has.
906
            prior_repo = self._creating_bzrdir.open_repository()
907
            prior_repo._ensure_real()
908
            result = prior_repo._real_repository._format.initialize(
909
                a_bzrdir, shared=shared)
910
        else:
911
            # assume that a_bzr is a RemoteBzrDir but the smart server didn't
912
            # support remote initialization.
913
            # We delegate to a real object at this point (as RemoteBzrDir
914
            # delegate to the repository format which would lead to infinite
915
            # recursion if we just called a_bzrdir.create_repository.
916
            a_bzrdir._ensure_real()
917
            result = a_bzrdir._real_bzrdir.create_repository(shared=shared)
918
        if not isinstance(result, RemoteRepository):
919
            return self.open(a_bzrdir)
920
        else:
921
            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.
922
1752.2.52 by Andrew Bennetts
Flesh out more Remote* methods needed to open and initialise remote branches/trees/repositories.
923
    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.
924
        # Being asked to create on a non RemoteBzrDir:
925
        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.
926
            return self._vfs_initialize(a_bzrdir, shared)
927
        medium = a_bzrdir._client._medium
928
        if medium._is_remote_before((1, 13)):
929
            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.
930
        # Creating on a remote bzr dir.
931
        # 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.
932
        if self._custom_format:
4017.3.2 by Robert Collins
Reduce the number of round trips required to create a repository over the network.
933
            network_name = self._custom_format.network_name()
4294.2.5 by Robert Collins
Reasonable unit test coverage for initialize_on_transport_ex.
934
        elif self._network_name:
935
            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.
936
        else:
937
            # Select the current bzrlib default and ask for that.
5712.3.13 by Jelmer Vernooij
Add Prober.known_formats().
938
            reference_bzrdir_format = _mod_bzrdir.format_registry.get('default')()
4017.3.2 by Robert Collins
Reduce the number of round trips required to create a repository over the network.
939
            reference_format = reference_bzrdir_format.repository_format
940
            network_name = reference_format.network_name()
941
        # 2) try direct creation via RPC
942
        path = a_bzrdir._path_for_remote_call(a_bzrdir._client)
943
        verb = 'BzrDir.create_repository'
944
        if shared:
945
            shared_str = 'True'
946
        else:
947
            shared_str = 'False'
948
        try:
949
            response = a_bzrdir._call(verb, path, network_name, shared_str)
950
        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.
951
            # Fallback - use vfs methods
4094.1.1 by Andrew Bennetts
Add some medium._remember_is_before((1, 13)) calls.
952
            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.
953
            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.
954
        else:
955
            # 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.
956
            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.
957
            # Used to support creating a real format instance when needed.
958
            format._creating_bzrdir = a_bzrdir
959
            remote_repo = RemoteRepository(a_bzrdir, format)
960
            format._creating_repo = remote_repo
961
            return remote_repo
3943.8.1 by Marius Kruger
remove all trailing whitespace from bzr source
962
1752.2.52 by Andrew Bennetts
Flesh out more Remote* methods needed to open and initialise remote branches/trees/repositories.
963
    def open(self, a_bzrdir):
3376.2.4 by Martin Pool
Remove every assert statement from bzrlib!
964
        if not isinstance(a_bzrdir, RemoteBzrDir):
965
            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.
966
        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.
967
4053.1.4 by Robert Collins
Move the fetch control attributes from Repository to RepositoryFormat.
968
    def _ensure_real(self):
969
        if self._custom_format is None:
5712.3.13 by Jelmer Vernooij
Add Prober.known_formats().
970
            self._custom_format = _mod_repository.network_format_registry.get(
4053.1.4 by Robert Collins
Move the fetch control attributes from Repository to RepositoryFormat.
971
                self._network_name)
972
973
    @property
974
    def _fetch_order(self):
975
        self._ensure_real()
976
        return self._custom_format._fetch_order
977
978
    @property
979
    def _fetch_uses_deltas(self):
980
        self._ensure_real()
981
        return self._custom_format._fetch_uses_deltas
982
983
    @property
984
    def _fetch_reconcile(self):
985
        self._ensure_real()
986
        return self._custom_format._fetch_reconcile
987
1752.2.52 by Andrew Bennetts
Flesh out more Remote* methods needed to open and initialise remote branches/trees/repositories.
988
    def get_format_description(self):
4792.1.1 by Andrew Bennetts
Show real branch/repo format description in 'info -v' over HPSS.
989
        self._ensure_real()
990
        return 'Remote: ' + self._custom_format.get_format_description()
1752.2.52 by Andrew Bennetts
Flesh out more Remote* methods needed to open and initialise remote branches/trees/repositories.
991
992
    def __eq__(self, other):
4088.3.1 by Benjamin Peterson
compare types with 'is' not ==
993
        return self.__class__ is other.__class__
1752.2.87 by Andrew Bennetts
Make tests pass.
994
3990.5.1 by Andrew Bennetts
Add network_name() to RepositoryFormat.
995
    def network_name(self):
4017.3.2 by Robert Collins
Reduce the number of round trips required to create a repository over the network.
996
        if self._network_name:
997
            return self._network_name
3990.5.1 by Andrew Bennetts
Add network_name() to RepositoryFormat.
998
        self._creating_repo._ensure_real()
999
        return self._creating_repo._real_repository._format.network_name()
1000
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)
1001
    @property
4431.3.7 by Jonathan Lange
Cherrypick bzr.dev 4470, resolving conflicts.
1002
    def pack_compresses(self):
1003
        self._ensure_real()
1004
        return self._custom_format.pack_compresses
1005
1006
    @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)
1007
    def _serializer(self):
4053.1.4 by Robert Collins
Move the fetch control attributes from Repository to RepositoryFormat.
1008
        self._ensure_real()
1009
        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)
1010
1752.2.31 by Martin Pool
[broken] some support for write operations over hpss
1011
6289.1.1 by Jelmer Vernooij
Make Repository a base class of RemoteRepository
1012
class RemoteRepository(_mod_repository.Repository, _RpcHelper,
1013
        lock._RelockDebugMixin):
1752.2.31 by Martin Pool
[broken] some support for write operations over hpss
1014
    """Repository accessed over rpc.
1015
2018.5.163 by Andrew Bennetts
Deal with various review comments from Robert.
1016
    For the moment most operations are performed using local transport-backed
1017
    Repository objects.
1752.2.31 by Martin Pool
[broken] some support for write operations over hpss
1018
    """
1019
2018.5.118 by Robert Collins
Fix RemoteRepositoryFormat to have appropriate rich_root_data and support_tree_reference.
1020
    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.
1021
        """Create a RemoteRepository instance.
3943.8.1 by Marius Kruger
remove all trailing whitespace from bzr source
1022
2018.5.34 by Robert Collins
Get test_remote.BasicRemoteObjectTests.test_open_remote_branch passing by implementing a remote method BzrDir.find_repository.
1023
        :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.
1024
        :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.
1025
        :param real_repository: If not None, a local implementation of the
1026
            repository logic for the repository, usually accessing the data
1027
            via the VFS.
2018.5.57 by Robert Collins
Implement RemoteRepository.is_shared (Robert Collins, Vincent Ladeuil).
1028
        :param _client: Private testing parameter - override the smart client
1029
            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.
1030
        """
1031
        if real_repository:
2018.5.36 by Andrew Bennetts
Fix typo, and clean up some ununsed import warnings from pyflakes at the same time.
1032
            self._real_repository = real_repository
2018.5.70 by Robert Collins
Only try to get real repositories when an operation requires them.
1033
        else:
1034
            self._real_repository = None
1752.2.50 by Andrew Bennetts
Implement RemoteBzrDir.create_{branch,workingtree}
1035
        self.bzrdir = remote_bzrdir
2018.5.57 by Robert Collins
Implement RemoteRepository.is_shared (Robert Collins, Vincent Ladeuil).
1036
        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.
1037
            self._client = remote_bzrdir._client
2018.5.57 by Robert Collins
Implement RemoteRepository.is_shared (Robert Collins, Vincent Ladeuil).
1038
        else:
1039
            self._client = _client
2018.5.118 by Robert Collins
Fix RemoteRepositoryFormat to have appropriate rich_root_data and support_tree_reference.
1040
        self._format = format
2018.5.75 by Andrew Bennetts
Add Repository.{dont_,}leave_lock_in_place.
1041
        self._lock_mode = None
1042
        self._lock_token = None
6280.7.2 by Jelmer Vernooij
Add HPSS calls ``Repository.start_write_group``, ``Repository.abort_write_group`` and ``Repository.commit_write_group``.
1043
        self._write_group_tokens = None
2018.5.75 by Andrew Bennetts
Add Repository.{dont_,}leave_lock_in_place.
1044
        self._lock_count = 0
2018.5.78 by Andrew Bennetts
Implement RemoteRepository.lock_write/unlock to expect and send tokens over the
1045
        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.
1046
        # Cache of revision parents; misses are cached during read locks, and
1047
        # write locks when no _real_repository has been set.
3835.1.12 by Aaron Bentley
Unify CachingExtraParentsProvider and CachingParentsProvider.
1048
        self._unstacked_provider = graph.CachingParentsProvider(
3896.1.1 by Andrew Bennetts
Remove broken debugging cruft, and some unused imports.
1049
            get_parent_map=self._get_parent_map_rpc)
3835.1.12 by Aaron Bentley
Unify CachingExtraParentsProvider and CachingParentsProvider.
1050
        self._unstacked_provider.disable_cache()
2951.1.10 by Robert Collins
Peer review feedback with Ian.
1051
        # For tests:
1052
        # These depend on the actual remote format, so force them off for
1053
        # maximum compatibility. XXX: In future these should depend on the
1054
        # remote repository instance, but this is irrelevant until we perform
1055
        # 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.
1056
        self._reconcile_does_inventory_gc = False
1057
        self._reconcile_fixes_text_parents = False
2951.1.3 by Robert Collins
Partial support for native reconcile with packs.
1058
        self._reconcile_backsup_inventory = False
2592.4.5 by Martin Pool
Add Repository.base on all repositories.
1059
        self.base = self.bzrdir.transport.base
3221.12.1 by Robert Collins
Backport development1 format (stackable packs) to before-shallow-branches.
1060
        # Additional places to query for data.
1061
        self._fallback_repositories = []
2592.4.5 by Martin Pool
Add Repository.base on all repositories.
1062
5158.6.4 by Martin Pool
Repository implements ControlComponent too
1063
    @property
1064
    def user_transport(self):
1065
        return self.bzrdir.user_transport
1066
1067
    @property
1068
    def control_transport(self):
1069
        # XXX: Normally you shouldn't directly get at the remote repository
1070
        # transport, but I'm not sure it's worth making this method
1071
        # optional -- mbp 2010-04-21
1072
        return self.bzrdir.get_repository_transport(None)
5712.3.13 by Jelmer Vernooij
Add Prober.known_formats().
1073
2592.4.5 by Martin Pool
Add Repository.base on all repositories.
1074
    def __str__(self):
1075
        return "%s(%s)" % (self.__class__.__name__, self.base)
1076
1077
    __repr__ = __str__
1752.2.52 by Andrew Bennetts
Flesh out more Remote* methods needed to open and initialise remote branches/trees/repositories.
1078
3825.4.1 by Andrew Bennetts
Add suppress_errors to abort_write_group.
1079
    def abort_write_group(self, suppress_errors=False):
2617.6.7 by Robert Collins
More review feedback.
1080
        """Complete a write group on the decorated repository.
3943.8.1 by Marius Kruger
remove all trailing whitespace from bzr source
1081
4031.3.3 by Matt Nordhoff
Review tweaks from Ben Finney
1082
        Smart methods perform operations in a single step so this API
2617.6.6 by Robert Collins
Some review feedback.
1083
        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.
1084
        for older plugins that don't use e.g. the CommitBuilder
1085
        facility.
3825.4.6 by Andrew Bennetts
Document the suppress_errors flag in the docstring.
1086
1087
        :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.
1088
        """
6280.7.5 by Jelmer Vernooij
Bunch of test fixes.
1089
        if self._real_repository:
6280.7.1 by Jelmer Vernooij
Implement RemoteRepository side of write group HPSS methods.
1090
            self._ensure_real()
1091
            return self._real_repository.abort_write_group(
1092
                suppress_errors=suppress_errors)
6280.7.6 by Jelmer Vernooij
Fix remaining tests.
1093
        if not self.is_in_write_group():
1094
            if suppress_errors:
1095
                mutter('(suppressed) not in write group')
1096
                return
1097
            raise errors.BzrError("not in write group")
6280.7.5 by Jelmer Vernooij
Bunch of test fixes.
1098
        path = self.bzrdir._path_for_remote_call(self._client)
1099
        try:
1100
            response = self._call('Repository.abort_write_group', path,
1101
                self._lock_token, self._write_group_tokens)
1102
        except Exception, exc:
1103
            self._write_group = None
1104
            if not suppress_errors:
1105
                raise
1106
            mutter('abort_write_group failed')
1107
            log_exception_quietly()
1108
            note(gettext('bzr: ERROR (ignored): %s'), exc)
1109
        else:
1110
            if response != ('ok', ):
1111
                raise errors.UnexpectedSmartServerResponse(response)
1112
            self._write_group_tokens = None
2617.6.2 by Robert Collins
Add abort_write_group and wire write_groups into fetch and commit.
1113
4253.1.1 by Robert Collins
Add chk_bytes property to RemoteRepository
1114
    @property
1115
    def chk_bytes(self):
1116
        """Decorate the real repository for now.
1117
1118
        In the long term a full blown network facility is needed to avoid
1119
        creating a real repository object locally.
1120
        """
1121
        self._ensure_real()
1122
        return self._real_repository.chk_bytes
1123
2617.6.2 by Robert Collins
Add abort_write_group and wire write_groups into fetch and commit.
1124
    def commit_write_group(self):
2617.6.7 by Robert Collins
More review feedback.
1125
        """Complete a write group on the decorated repository.
3943.8.1 by Marius Kruger
remove all trailing whitespace from bzr source
1126
4031.3.3 by Matt Nordhoff
Review tweaks from Ben Finney
1127
        Smart methods perform operations in a single step so this API
2617.6.6 by Robert Collins
Some review feedback.
1128
        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.
1129
        for older plugins that don't use e.g. the CommitBuilder
1130
        facility.
1131
        """
6280.7.5 by Jelmer Vernooij
Bunch of test fixes.
1132
        if self._real_repository:
6280.7.1 by Jelmer Vernooij
Implement RemoteRepository side of write group HPSS methods.
1133
            self._ensure_real()
1134
            return self._real_repository.commit_write_group()
6280.7.6 by Jelmer Vernooij
Fix remaining tests.
1135
        if not self.is_in_write_group():
1136
            raise errors.BzrError("not in write group")
6280.7.5 by Jelmer Vernooij
Bunch of test fixes.
1137
        path = self.bzrdir._path_for_remote_call(self._client)
1138
        response = self._call('Repository.commit_write_group', path,
1139
            self._lock_token, self._write_group_tokens)
6280.7.1 by Jelmer Vernooij
Implement RemoteRepository side of write group HPSS methods.
1140
        if response != ('ok', ):
1141
            raise errors.UnexpectedSmartServerResponse(response)
6280.7.4 by Jelmer Vernooij
pass write group tokens as list/tuple.
1142
        self._write_group_tokens = None
2617.6.1 by Robert Collins
* New method on Repository - ``start_write_group``, ``end_write_group``
1143
4002.1.1 by Andrew Bennetts
Implement suspend_write_group/resume_write_group.
1144
    def resume_write_group(self, tokens):
6280.7.2 by Jelmer Vernooij
Add HPSS calls ``Repository.start_write_group``, ``Repository.abort_write_group`` and ``Repository.commit_write_group``.
1145
        if self._real_repository:
6280.7.1 by Jelmer Vernooij
Implement RemoteRepository side of write group HPSS methods.
1146
            return self._real_repository.resume_write_group(tokens)
6280.7.6 by Jelmer Vernooij
Fix remaining tests.
1147
        path = self.bzrdir._path_for_remote_call(self._client)
1148
        try:
1149
            response = self._call('Repository.check_write_group', path,
1150
               self._lock_token, tokens)
1151
        except errors.UnknownSmartMethod:
1152
            self._ensure_real()
1153
            return self._real_repository.resume_write_group(tokens)
1154
        if response != ('ok', ):
1155
            raise errors.UnexpectedSmartServerResponse(response)
6280.7.5 by Jelmer Vernooij
Bunch of test fixes.
1156
        self._write_group_tokens = tokens
4002.1.1 by Andrew Bennetts
Implement suspend_write_group/resume_write_group.
1157
1158
    def suspend_write_group(self):
6280.7.2 by Jelmer Vernooij
Add HPSS calls ``Repository.start_write_group``, ``Repository.abort_write_group`` and ``Repository.commit_write_group``.
1159
        if self._real_repository:
6280.7.1 by Jelmer Vernooij
Implement RemoteRepository side of write group HPSS methods.
1160
            return self._real_repository.suspend_write_group()
6280.7.6 by Jelmer Vernooij
Fix remaining tests.
1161
        ret = self._write_group_tokens or []
6280.7.5 by Jelmer Vernooij
Bunch of test fixes.
1162
        self._write_group_tokens = None
1163
        return ret
4002.1.1 by Andrew Bennetts
Implement suspend_write_group/resume_write_group.
1164
4343.3.29 by John Arbash Meinel
Add 'check_for_missing_texts' flag to get_missing_parent_inv..
1165
    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).
1166
        self._ensure_real()
4343.3.29 by John Arbash Meinel
Add 'check_for_missing_texts' flag to get_missing_parent_inv..
1167
        return self._real_repository.get_missing_parent_inventories(
1168
            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).
1169
4419.2.9 by Andrew Bennetts
Add per_repository_reference test for get_rev_id_for_revno, fix the bugs it revealed.
1170
    def _get_rev_id_for_revno_vfs(self, revno, known_pair):
1171
        self._ensure_real()
1172
        return self._real_repository.get_rev_id_for_revno(
1173
            revno, known_pair)
1174
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.
1175
    def get_rev_id_for_revno(self, revno, known_pair):
1176
        """See Repository.get_rev_id_for_revno."""
1177
        path = self.bzrdir._path_for_remote_call(self._client)
1178
        try:
4476.3.33 by Andrew Bennetts
Revert some accidental s/17/18/ in remote.py.
1179
            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.
1180
                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.
1181
            response = self._call(
1182
                'Repository.get_rev_id_for_revno', path, revno, known_pair)
1183
        except errors.UnknownSmartMethod:
4476.3.33 by Andrew Bennetts
Revert some accidental s/17/18/ in remote.py.
1184
            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.
1185
            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.
1186
        if response[0] == 'ok':
1187
            return True, response[1]
1188
        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.
1189
            known_pair = response[1:3]
1190
            for fallback in self._fallback_repositories:
1191
                found, result = fallback.get_rev_id_for_revno(revno, known_pair)
1192
                if found:
1193
                    return True, result
1194
                else:
1195
                    known_pair = result
1196
            # Not found in any fallbacks
1197
            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.
1198
        else:
1199
            raise errors.UnexpectedSmartServerResponse(response)
1200
2018.5.70 by Robert Collins
Only try to get real repositories when an operation requires them.
1201
    def _ensure_real(self):
1202
        """Ensure that there is a _real_repository set.
1203
2018.5.163 by Andrew Bennetts
Deal with various review comments from Robert.
1204
        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.
1205
1206
        Note that _ensure_real causes many roundtrips to the server which are
1207
        not desirable, and prevents the use of smart one-roundtrip RPC's to
1208
        perform complex operations (such as accessing parent data, streaming
1209
        revisions etc). Adding calls to _ensure_real should only be done when
1210
        bringing up new functionality, adding fallbacks for smart methods that
1211
        require a fallback path, and never to replace an existing smart method
1212
        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.
1213
        """
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.
1214
        if self._real_repository is None:
4509.2.2 by Martin Pool
Use only -Dhpssvfs for tracebacks, and document -Dhpssdetail
1215
            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.
1216
                import traceback
1217
                warning('VFS Repository access triggered\n%s',
1218
                    ''.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.
1219
            self._unstacked_provider.missing_keys.clear()
2018.5.70 by Robert Collins
Only try to get real repositories when an operation requires them.
1220
            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.
1221
            self._set_real_repository(
1222
                self.bzrdir._real_bzrdir.open_repository())
2018.5.70 by Robert Collins
Only try to get real repositories when an operation requires them.
1223
3533.3.1 by Andrew Bennetts
Remove duplication of error translation in bzrlib/remote.py.
1224
    def _translate_error(self, err, **context):
1225
        self.bzrdir._translate_error(err, repository=self, **context)
1226
2988.1.2 by Robert Collins
New Repository API find_text_key_references for use by reconcile and check.
1227
    def find_text_key_references(self):
1228
        """Find the text key references within the repository.
1229
1230
        :return: A dictionary mapping text keys ((fileid, revision_id) tuples)
1231
            to whether they were referred to by the inventory of the
1232
            revision_id that they contain. The inventory texts from all present
1233
            revision ids are assessed to generate this report.
1234
        """
1235
        self._ensure_real()
1236
        return self._real_repository.find_text_key_references()
1237
2988.1.3 by Robert Collins
Add a new repositoy method _generate_text_key_index for use by reconcile/check.
1238
    def _generate_text_key_index(self):
1239
        """Generate a new text key index for the repository.
1240
1241
        This is an expensive function that will take considerable time to run.
1242
1243
        :return: A dict mapping (file_id, revision_id) tuples to a list of
1244
            parents, also (file_id, revision_id) tuples.
1245
        """
1246
        self._ensure_real()
1247
        return self._real_repository._generate_text_key_index()
1248
3287.6.4 by Robert Collins
Fix up deprecation warnings for get_revision_graph.
1249
    def _get_revision_graph(self, revision_id):
1250
        """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)
1251
        if revision_id is None:
1252
            revision_id = ''
5712.3.13 by Jelmer Vernooij
Add Prober.known_formats().
1253
        elif _mod_revision.is_null(revision_id):
2018.5.67 by Wouter van Heyst
Implement RemoteRepository.get_revision_graph (Wouter van Heyst, Robert Collins)
1254
            return {}
1255
1256
        path = self.bzrdir._path_for_remote_call(self._client)
3786.2.3 by Andrew Bennetts
Remove duplicated 'call & translate errors' code in bzrlib.remote.
1257
        response = self._call_expecting_body(
1258
            '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.
1259
        response_tuple, response_handler = response
1260
        if response_tuple[0] != 'ok':
1261
            raise errors.UnexpectedSmartServerResponse(response_tuple)
1262
        coded = response_handler.read_body_bytes()
3245.4.24 by Andrew Bennetts
Consistently raise errors from the server as ErrorFromSmartServer exceptions.
1263
        if coded == '':
1264
            # no revisions in this repository!
1265
            return {}
1266
        lines = coded.split('\n')
1267
        revision_graph = {}
1268
        for line in lines:
1269
            d = tuple(line.split())
1270
            revision_graph[d[0]] = d[1:]
3943.8.1 by Marius Kruger
remove all trailing whitespace from bzr source
1271
3245.4.24 by Andrew Bennetts
Consistently raise errors from the server as ErrorFromSmartServer exceptions.
1272
        return revision_graph
2018.5.67 by Wouter van Heyst
Implement RemoteRepository.get_revision_graph (Wouter van Heyst, Robert Collins)
1273
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)
1274
    def _get_sink(self):
1275
        """See Repository._get_sink()."""
4022.1.6 by Robert Collins
Cherrypick and polish the RemoteSink for streaming push.
1276
        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)
1277
4060.1.3 by Robert Collins
Implement the separate source component for fetch - repository.StreamSource.
1278
    def _get_source(self, to_format):
1279
        """Return a source for streaming from this repository."""
1280
        return RemoteStreamSource(self, to_format)
1281
4307.2.3 by Robert Collins
Change RemoteRepository.has_revision to use get_parent_map to leverage the caching.
1282
    @needs_read_lock
5815.5.8 by Jelmer Vernooij
Use traditional (fileid, revision) entries in file graph.
1283
    def get_file_graph(self):
1284
        return graph.Graph(self.texts)
5815.5.3 by Jelmer Vernooij
Add basic test for per file graph.
1285
1286
    @needs_read_lock
2018.5.40 by Robert Collins
Implement a remote Repository.has_revision method.
1287
    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.
1288
        """True if this repository has a copy of the revision."""
1289
        # Copy of bzrlib.repository.Repository.has_revision
1290
        return revision_id in self.has_revisions((revision_id,))
2018.5.40 by Robert Collins
Implement a remote Repository.has_revision method.
1291
4307.2.3 by Robert Collins
Change RemoteRepository.has_revision to use get_parent_map to leverage the caching.
1292
    @needs_read_lock
3172.3.1 by Robert Collins
Repository has a new method ``has_revisions`` which signals the presence
1293
    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.
1294
        """Probe to find out the presence of multiple revisions.
1295
1296
        :param revision_ids: An iterable of revision_ids.
1297
        :return: A set of the revision_ids that were present.
1298
        """
1299
        # Copy of bzrlib.repository.Repository.has_revisions
1300
        parent_map = self.get_parent_map(revision_ids)
1301
        result = set(parent_map)
1302
        if _mod_revision.NULL_REVISION in revision_ids:
1303
            result.add(_mod_revision.NULL_REVISION)
3172.3.1 by Robert Collins
Repository has a new method ``has_revisions`` which signals the presence
1304
        return result
1305
4509.3.37 by Martin Pool
Remove RepositoryBase; make _has_same_location private
1306
    def _has_same_fallbacks(self, other_repo):
1307
        """Returns true if the repositories have the same fallbacks."""
1308
        # XXX: copied from Repository; it should be unified into a base class
5243.1.2 by Martin
Point launchpad links in comments at production server rather than edge
1309
        # <https://bugs.launchpad.net/bzr/+bug/401622>
4509.3.37 by Martin Pool
Remove RepositoryBase; make _has_same_location private
1310
        my_fb = self._fallback_repositories
1311
        other_fb = other_repo._fallback_repositories
1312
        if len(my_fb) != len(other_fb):
1313
            return False
1314
        for f, g in zip(my_fb, other_fb):
1315
            if not f.has_same_location(g):
1316
                return False
1317
        return True
1318
2617.6.9 by Robert Collins
Merge bzr.dev.
1319
    def has_same_location(self, other):
4509.3.23 by Martin Pool
Comment on has_same_location variation
1320
        # TODO: Move to RepositoryBase and unify with the regular Repository
1321
        # one; unfortunately the tests rely on slightly different behaviour at
1322
        # present -- mbp 20090710
4088.3.1 by Benjamin Peterson
compare types with 'is' not ==
1323
        return (self.__class__ is other.__class__ and
2592.3.162 by Robert Collins
Remove some arbitrary differences from bzr.dev.
1324
                self.bzrdir.transport.base == other.bzrdir.transport.base)
3835.1.1 by Aaron Bentley
Stack get_parent_map on fallback repos
1325
2490.2.21 by Aaron Bentley
Rename graph to deprecated_graph
1326
    def get_graph(self, other_repository=None):
1327
        """Return the graph for this repository format"""
3835.1.17 by Aaron Bentley
Fix stacking bug
1328
        parents_provider = self._make_parents_provider(other_repository)
3441.5.24 by Andrew Bennetts
Remove RemoteGraph experiment.
1329
        return graph.Graph(parents_provider)
2490.2.5 by Aaron Bentley
Use GraphWalker.unique_ancestor to determine merge base
1330
4913.4.2 by Jelmer Vernooij
Add Repository.get_known_graph_ancestry.
1331
    @needs_read_lock
1332
    def get_known_graph_ancestry(self, revision_ids):
1333
        """Return the known graph for a set of revision ids and their ancestors.
1334
        """
1335
        st = static_tuple.StaticTuple
1336
        revision_keys = [st(r_id).intern() for r_id in revision_ids]
1337
        known_graph = self.revisions.get_known_graph_ancestry(revision_keys)
1338
        return graph.GraphThunkIdsToKeys(known_graph)
1339
2018.14.1 by Andrew Bennetts
Update to current hpss branch? Fix lots of test failures.
1340
    def gather_stats(self, revid=None, committers=None):
2018.5.62 by Robert Collins
Stub out RemoteRepository.gather_stats while its implemented in parallel.
1341
        """See Repository.gather_stats()."""
2018.10.3 by v.ladeuil+lp at free
more tests for gather_stats
1342
        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.
1343
        # revid can be None to indicate no revisions, not just NULL_REVISION
5712.3.13 by Jelmer Vernooij
Add Prober.known_formats().
1344
        if revid is None or _mod_revision.is_null(revid):
2018.10.3 by v.ladeuil+lp at free
more tests for gather_stats
1345
            fmt_revid = ''
1346
        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.
1347
            fmt_revid = revid
2018.14.1 by Andrew Bennetts
Update to current hpss branch? Fix lots of test failures.
1348
        if committers is None or not committers:
2018.10.3 by v.ladeuil+lp at free
more tests for gather_stats
1349
            fmt_committers = 'no'
1350
        else:
1351
            fmt_committers = 'yes'
3786.2.3 by Andrew Bennetts
Remove duplicated 'call & translate errors' code in bzrlib.remote.
1352
        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.
1353
            '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.
1354
        if response_tuple[0] != 'ok':
1355
            raise errors.UnexpectedSmartServerResponse(response_tuple)
2018.10.3 by v.ladeuil+lp at free
more tests for gather_stats
1356
3245.4.58 by Andrew Bennetts
Unpack call_expecting_body's return value into variables, to avoid lots of ugly subscripting.
1357
        body = response_handler.read_body_bytes()
2018.10.3 by v.ladeuil+lp at free
more tests for gather_stats
1358
        result = {}
1359
        for line in body.split('\n'):
1360
            if not line:
1361
                continue
1362
            key, val_text = line.split(':')
1363
            if key in ('revisions', 'size', 'committers'):
1364
                result[key] = int(val_text)
1365
            elif key in ('firstrev', 'latestrev'):
1366
                values = val_text.split(' ')[1:]
1367
                result[key] = (float(values[0]), long(values[1]))
1368
1369
        return result
2018.5.62 by Robert Collins
Stub out RemoteRepository.gather_stats while its implemented in parallel.
1370
3140.1.2 by Aaron Bentley
Add ability to find branches inside repositories
1371
    def find_branches(self, using=False):
1372
        """See Repository.find_branches()."""
1373
        # should be an API call to the server.
1374
        self._ensure_real()
1375
        return self._real_repository.find_branches(using=using)
1376
2018.5.60 by Robert Collins
More missing methods from RemoteBranch and RemoteRepository to let 'info' get further.
1377
    def get_physical_lock_status(self):
1378
        """See Repository.get_physical_lock_status()."""
6280.6.1 by Jelmer Vernooij
Implement remote side of {Branch,Repository}.get_physical_lock_status.
1379
        path = self.bzrdir._path_for_remote_call(self._client)
1380
        try:
1381
            response = self._call('Repository.get_physical_lock_status', path)
1382
        except errors.UnknownSmartMethod:
1383
            self._ensure_real()
1384
            return self._real_repository.get_physical_lock_status()
1385
        if response[0] not in ('yes', 'no'):
1386
            raise errors.UnexpectedSmartServerResponse(response)
6280.6.2 by Jelmer Vernooij
Add HPSS calls Repository.get_physical_lock_status and Branch.get_physical_lock_status.
1387
        return (response[0] == 'yes')
2018.5.60 by Robert Collins
More missing methods from RemoteBranch and RemoteRepository to let 'info' get further.
1388
2617.6.1 by Robert Collins
* New method on Repository - ``start_write_group``, ``end_write_group``
1389
    def is_in_write_group(self):
1390
        """Return True if there is an open write group.
1391
1392
        write groups are only applicable locally for the smart server..
1393
        """
6280.7.3 by Jelmer Vernooij
Fix RemoteRepository.is_in_write_group.
1394
        if self._write_group_tokens is not None:
1395
            return True
2617.6.1 by Robert Collins
* New method on Repository - ``start_write_group``, ``end_write_group``
1396
        if self._real_repository:
1397
            return self._real_repository.is_in_write_group()
1398
1399
    def is_locked(self):
1400
        return self._lock_count >= 1
1401
2018.5.57 by Robert Collins
Implement RemoteRepository.is_shared (Robert Collins, Vincent Ladeuil).
1402
    def is_shared(self):
1403
        """See Repository.is_shared()."""
1404
        path = self.bzrdir._path_for_remote_call(self._client)
3786.2.3 by Andrew Bennetts
Remove duplicated 'call & translate errors' code in bzrlib.remote.
1405
        response = self._call('Repository.is_shared', path)
3376.2.4 by Martin Pool
Remove every assert statement from bzrlib!
1406
        if response[0] not in ('yes', 'no'):
1407
            raise SmartProtocolError('unexpected response code %s' % (response,))
2018.5.57 by Robert Collins
Implement RemoteRepository.is_shared (Robert Collins, Vincent Ladeuil).
1408
        return response[0] == 'yes'
1409
2904.1.1 by Robert Collins
* New method ``bzrlib.repository.Repository.is_write_locked`` useful for
1410
    def is_write_locked(self):
1411
        return self._lock_mode == 'w'
1412
5675.2.2 by Jelmer Vernooij
Revert unnecessary bzrlib.remote changes.
1413
    def _warn_if_deprecated(self, branch=None):
1414
        # If we have a real repository, the check will be done there, if we
1415
        # don't the check will be done remotely.
1416
        pass
1417
2018.5.60 by Robert Collins
More missing methods from RemoteBranch and RemoteRepository to let 'info' get further.
1418
    def lock_read(self):
5200.3.3 by Robert Collins
Lock methods on ``Tree``, ``Branch`` and ``Repository`` are now
1419
        """Lock the repository for read operations.
1420
5200.3.6 by Robert Collins
Make all lock methods return Result objects, rather than lock_read returning self, as per John's review.
1421
        :return: A bzrlib.lock.LogicalLockResult.
5200.3.3 by Robert Collins
Lock methods on ``Tree``, ``Branch`` and ``Repository`` are now
1422
        """
2018.5.60 by Robert Collins
More missing methods from RemoteBranch and RemoteRepository to let 'info' get further.
1423
        # wrong eventually - want a local lock cache context
2018.5.75 by Andrew Bennetts
Add Repository.{dont_,}leave_lock_in_place.
1424
        if not self._lock_mode:
4731.1.2 by Andrew Bennetts
Refactor to reduce duplication.
1425
            self._note_lock('r')
2018.5.75 by Andrew Bennetts
Add Repository.{dont_,}leave_lock_in_place.
1426
            self._lock_mode = 'r'
1427
            self._lock_count = 1
4190.1.1 by Robert Collins
Negatively cache misses during read-locks in RemoteRepository.
1428
            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
1429
            if self._real_repository is not None:
1430
                self._real_repository.lock_read()
4379.2.1 by John Arbash Meinel
Change the fallback repository code to only lock/unlock on transition.
1431
            for repo in self._fallback_repositories:
1432
                repo.lock_read()
2018.5.75 by Andrew Bennetts
Add Repository.{dont_,}leave_lock_in_place.
1433
        else:
1434
            self._lock_count += 1
5200.3.6 by Robert Collins
Make all lock methods return Result objects, rather than lock_read returning self, as per John's review.
1435
        return lock.LogicalLockResult(self.unlock)
2018.5.78 by Andrew Bennetts
Implement RemoteRepository.lock_write/unlock to expect and send tokens over the
1436
2018.14.1 by Andrew Bennetts
Update to current hpss branch? Fix lots of test failures.
1437
    def _remote_lock_write(self, token):
2018.5.78 by Andrew Bennetts
Implement RemoteRepository.lock_write/unlock to expect and send tokens over the
1438
        path = self.bzrdir._path_for_remote_call(self._client)
1439
        if token is None:
1440
            token = ''
3786.2.3 by Andrew Bennetts
Remove duplicated 'call & translate errors' code in bzrlib.remote.
1441
        err_context = {'token': token}
1442
        response = self._call('Repository.lock_write', path, token,
1443
                              **err_context)
2018.5.78 by Andrew Bennetts
Implement RemoteRepository.lock_write/unlock to expect and send tokens over the
1444
        if response[0] == 'ok':
1445
            ok, token = response
1446
            return token
1447
        else:
2555.1.1 by Martin Pool
Remove use of 'assert False' to raise an exception unconditionally
1448
            raise errors.UnexpectedSmartServerResponse(response)
2018.5.60 by Robert Collins
More missing methods from RemoteBranch and RemoteRepository to let 'info' get further.
1449
3692.1.1 by Andrew Bennetts
Make RemoteBranch.lock_write lock the repository too.
1450
    def lock_write(self, token=None, _skip_rpc=False):
2018.5.75 by Andrew Bennetts
Add Repository.{dont_,}leave_lock_in_place.
1451
        if not self._lock_mode:
4731.1.2 by Andrew Bennetts
Refactor to reduce duplication.
1452
            self._note_lock('w')
3692.1.1 by Andrew Bennetts
Make RemoteBranch.lock_write lock the repository too.
1453
            if _skip_rpc:
1454
                if self._lock_token is not None:
1455
                    if token != self._lock_token:
3695.1.1 by Andrew Bennetts
Remove some unused imports and fix a couple of trivially broken raise statements.
1456
                        raise errors.TokenMismatch(token, self._lock_token)
3692.1.1 by Andrew Bennetts
Make RemoteBranch.lock_write lock the repository too.
1457
                self._lock_token = token
1458
            else:
1459
                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.
1460
            # if self._lock_token is None, then this is something like packs or
1461
            # svn where we don't get to lock the repo, or a weave style repository
1462
            # where we cannot lock it over the wire and attempts to do so will
1463
            # fail.
2018.5.78 by Andrew Bennetts
Implement RemoteRepository.lock_write/unlock to expect and send tokens over the
1464
            if self._real_repository is not None:
1465
                self._real_repository.lock_write(token=self._lock_token)
1466
            if token is not None:
1467
                self._leave_lock = True
1468
            else:
1469
                self._leave_lock = False
2018.5.75 by Andrew Bennetts
Add Repository.{dont_,}leave_lock_in_place.
1470
            self._lock_mode = 'w'
1471
            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.
1472
            cache_misses = self._real_repository is None
1473
            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.
1474
            for repo in self._fallback_repositories:
1475
                # Writes don't affect fallback repos
1476
                repo.lock_read()
2018.5.75 by Andrew Bennetts
Add Repository.{dont_,}leave_lock_in_place.
1477
        elif self._lock_mode == 'r':
2018.14.1 by Andrew Bennetts
Update to current hpss branch? Fix lots of test failures.
1478
            raise errors.ReadOnlyError(self)
2018.5.75 by Andrew Bennetts
Add Repository.{dont_,}leave_lock_in_place.
1479
        else:
1480
            self._lock_count += 1
5200.3.3 by Robert Collins
Lock methods on ``Tree``, ``Branch`` and ``Repository`` are now
1481
        return RepositoryWriteLockResult(self.unlock, self._lock_token or None)
2018.5.75 by Andrew Bennetts
Add Repository.{dont_,}leave_lock_in_place.
1482
1483
    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.
1484
        if not self._lock_token:
1485
            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
1486
        self._leave_lock = True
2018.5.75 by Andrew Bennetts
Add Repository.{dont_,}leave_lock_in_place.
1487
1488
    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.
1489
        if not self._lock_token:
3015.2.15 by Robert Collins
Review feedback.
1490
            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
1491
        self._leave_lock = False
2018.5.75 by Andrew Bennetts
Add Repository.{dont_,}leave_lock_in_place.
1492
1493
    def _set_real_repository(self, repository):
1494
        """Set the _real_repository for this repository.
1495
1496
        :param repository: The repository to fallback to for non-hpss
1497
            implemented operations.
1498
        """
4053.1.5 by Robert Collins
Review feedback on RemoteRepository._set_real_revision.
1499
        if self._real_repository is not None:
1500
            # Replacing an already set real repository.
1501
            # We cannot do this [currently] if the repository is locked -
1502
            # synchronised state might be lost.
1503
            if self.is_locked():
1504
                raise AssertionError('_real_repository is already set')
3376.2.4 by Martin Pool
Remove every assert statement from bzrlib!
1505
        if isinstance(repository, RemoteRepository):
1506
            raise AssertionError()
2018.5.75 by Andrew Bennetts
Add Repository.{dont_,}leave_lock_in_place.
1507
        self._real_repository = repository
4226.2.5 by Robert Collins
Fix handling of fallback repositories some more.
1508
        # three code paths happen here:
1509
        # 1) old servers, RemoteBranch.open() calls _ensure_real before setting
1510
        # up stacking. In this case self._fallback_repositories is [], and the
1511
        # real repo is already setup. Preserve the real repo and
1512
        # RemoteRepository.add_fallback_repository will avoid adding
1513
        # duplicates.
1514
        # 2) new servers, RemoteBranch.open() sets up stacking, and when
1515
        # ensure_real is triggered from a branch, the real repository to
1516
        # set already has a matching list with separate instances, but
1517
        # as they are also RemoteRepositories we don't worry about making the
1518
        # lists be identical.
1519
        # 3) new servers, RemoteRepository.ensure_real is triggered before
1520
        # RemoteBranch.ensure real, in this case we get a repo with no fallbacks
1521
        # and need to populate it.
1522
        if (self._fallback_repositories and
1523
            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.
1524
            len(self._fallback_repositories)):
1525
            if len(self._real_repository._fallback_repositories):
1526
                raise AssertionError(
1527
                    "cannot cleanly remove existing _fallback_repositories")
3691.2.12 by Martin Pool
Add test for coping without Branch.get_stacked_on_url
1528
        for fb in self._fallback_repositories:
1529
            self._real_repository.add_fallback_repository(fb)
2018.5.75 by Andrew Bennetts
Add Repository.{dont_,}leave_lock_in_place.
1530
        if self._lock_mode == 'w':
1531
            # if we are already locked, the real repository must be able to
1532
            # acquire the lock with our token.
1533
            self._real_repository.lock_write(self._lock_token)
2018.14.1 by Andrew Bennetts
Update to current hpss branch? Fix lots of test failures.
1534
        elif self._lock_mode == 'r':
1535
            self._real_repository.lock_read()
6280.7.5 by Jelmer Vernooij
Bunch of test fixes.
1536
        if self._write_group_tokens is not None:
1537
            # if we are already in a write group, resume it
1538
            self._real_repository.resume_write_group(self._write_group_tokens)
1539
            self._write_group_tokens = None
2018.5.60 by Robert Collins
More missing methods from RemoteBranch and RemoteRepository to let 'info' get further.
1540
2617.6.1 by Robert Collins
* New method on Repository - ``start_write_group``, ``end_write_group``
1541
    def start_write_group(self):
1542
        """Start a write group on the decorated repository.
3943.8.1 by Marius Kruger
remove all trailing whitespace from bzr source
1543
4031.3.3 by Matt Nordhoff
Review tweaks from Ben Finney
1544
        Smart methods perform operations in a single step so this API
2617.6.6 by Robert Collins
Some review feedback.
1545
        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``
1546
        for older plugins that don't use e.g. the CommitBuilder
1547
        facility.
1548
        """
6280.7.5 by Jelmer Vernooij
Bunch of test fixes.
1549
        if self._real_repository:
1550
            self._ensure_real()
1551
            return self._real_repository.start_write_group()
1552
        if not self.is_write_locked():
1553
            raise errors.NotWriteLocked(self)
1554
        if self._write_group_tokens is not None:
1555
            raise errors.BzrError('already in a write group')
6280.7.1 by Jelmer Vernooij
Implement RemoteRepository side of write group HPSS methods.
1556
        path = self.bzrdir._path_for_remote_call(self._client)
1557
        try:
6280.7.2 by Jelmer Vernooij
Add HPSS calls ``Repository.start_write_group``, ``Repository.abort_write_group`` and ``Repository.commit_write_group``.
1558
            response = self._call('Repository.start_write_group', path,
1559
                self._lock_token)
6280.7.8 by Jelmer Vernooij
make sure start_write_group falls back to real_repository if write groups aren't suspendable.
1560
        except (errors.UnknownSmartMethod, errors.UnsuspendableWriteGroup):
6280.7.1 by Jelmer Vernooij
Implement RemoteRepository side of write group HPSS methods.
1561
            self._ensure_real()
1562
            return self._real_repository.start_write_group()
6280.7.2 by Jelmer Vernooij
Add HPSS calls ``Repository.start_write_group``, ``Repository.abort_write_group`` and ``Repository.commit_write_group``.
1563
        if response[0] != 'ok':
6280.7.1 by Jelmer Vernooij
Implement RemoteRepository side of write group HPSS methods.
1564
            raise errors.UnexpectedSmartServerResponse(response)
6280.7.6 by Jelmer Vernooij
Fix remaining tests.
1565
        self._write_group_tokens = response[1]
2617.6.1 by Robert Collins
* New method on Repository - ``start_write_group``, ``end_write_group``
1566
2018.5.78 by Andrew Bennetts
Implement RemoteRepository.lock_write/unlock to expect and send tokens over the
1567
    def _unlock(self, token):
1568
        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.
1569
        if not token:
1570
            # with no token the remote repository is not persistently locked.
1571
            return
3786.2.3 by Andrew Bennetts
Remove duplicated 'call & translate errors' code in bzrlib.remote.
1572
        err_context = {'token': token}
1573
        response = self._call('Repository.unlock', path, token,
1574
                              **err_context)
2018.5.78 by Andrew Bennetts
Implement RemoteRepository.lock_write/unlock to expect and send tokens over the
1575
        if response == ('ok',):
1576
            return
1577
        else:
2555.1.1 by Martin Pool
Remove use of 'assert False' to raise an exception unconditionally
1578
            raise errors.UnexpectedSmartServerResponse(response)
2018.5.78 by Andrew Bennetts
Implement RemoteRepository.lock_write/unlock to expect and send tokens over the
1579
4634.85.9 by Andrew Bennetts
Add some experimental decorators: @only_raises(..) and @cleanup_method.
1580
    @only_raises(errors.LockNotHeld, errors.LockBroken)
2018.5.60 by Robert Collins
More missing methods from RemoteBranch and RemoteRepository to let 'info' get further.
1581
    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.
1582
        if not self._lock_count:
4509.3.25 by Martin Pool
Add an option for unlock errors to be non-fatal
1583
            return lock.cant_unlock_not_held(self)
2018.5.75 by Andrew Bennetts
Add Repository.{dont_,}leave_lock_in_place.
1584
        self._lock_count -= 1
2592.3.244 by Martin Pool
unlock while in a write group now aborts the write group, unlocks, and errors.
1585
        if self._lock_count > 0:
1586
            return
3835.1.8 by Aaron Bentley
Make UnstackedParentsProvider manage the cache
1587
        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.
1588
        old_mode = self._lock_mode
1589
        self._lock_mode = None
1590
        try:
1591
            # The real repository is responsible at present for raising an
1592
            # exception if it's in an unfinished write group.  However, it
1593
            # normally will *not* actually remove the lock from disk - that's
1594
            # done by the server on receiving the Repository.unlock call.
1595
            # 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
1596
            if self._real_repository is not None:
1597
                self._real_repository.unlock()
6280.7.6 by Jelmer Vernooij
Fix remaining tests.
1598
            elif self._write_group_tokens is not None:
1599
                self.abort_write_group()
2592.3.244 by Martin Pool
unlock while in a write group now aborts the write group, unlocks, and errors.
1600
        finally:
1601
            # The rpc-level lock should be released even if there was a
1602
            # problem releasing the vfs-based lock.
1603
            if old_mode == 'w':
2018.5.163 by Andrew Bennetts
Deal with various review comments from Robert.
1604
                # Only write-locked repositories need to make a remote method
4031.3.1 by Frank Aspell
Fixing various typos
1605
                # 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.
1606
                old_token = self._lock_token
1607
                self._lock_token = None
1608
                if not self._leave_lock:
1609
                    self._unlock(old_token)
4379.2.1 by John Arbash Meinel
Change the fallback repository code to only lock/unlock on transition.
1610
        # Fallbacks are always 'lock_read()' so we don't pay attention to
1611
        # self._leave_lock
1612
        for repo in self._fallback_repositories:
1613
            repo.unlock()
2018.5.60 by Robert Collins
More missing methods from RemoteBranch and RemoteRepository to let 'info' get further.
1614
1615
    def break_lock(self):
2018.5.78 by Andrew Bennetts
Implement RemoteRepository.lock_write/unlock to expect and send tokens over the
1616
        # should hand off to the network
6280.4.5 by Jelmer Vernooij
Fix tests.
1617
        path = self.bzrdir._path_for_remote_call(self._client)
6280.4.1 by Jelmer Vernooij
Add remote side of Repository.break_lock.
1618
        try:
6280.4.5 by Jelmer Vernooij
Fix tests.
1619
            response = self._call("Repository.break_lock", path)
6280.4.1 by Jelmer Vernooij
Add remote side of Repository.break_lock.
1620
        except errors.UnknownSmartMethod:
1621
            self._ensure_real()
1622
            return self._real_repository.break_lock()
1623
        if response != ('ok',):
1624
            raise errors.UnexpectedSmartServerResponse(response)
2018.5.60 by Robert Collins
More missing methods from RemoteBranch and RemoteRepository to let 'info' get further.
1625
2018.18.8 by Ian Clatworthy
Tarball proxy code & tests
1626
    def _get_tarball(self, compression):
2814.10.2 by Andrew Bennetts
Make the fallback a little tidier.
1627
        """Return a TemporaryFile containing a repository tarball.
3943.8.1 by Marius Kruger
remove all trailing whitespace from bzr source
1628
2814.10.2 by Andrew Bennetts
Make the fallback a little tidier.
1629
        Returns None if the server does not support sending tarballs.
1630
        """
2018.18.25 by Martin Pool
Repository.tarball fixes for python2.4
1631
        import tempfile
2018.18.8 by Ian Clatworthy
Tarball proxy code & tests
1632
        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.
1633
        try:
3786.2.3 by Andrew Bennetts
Remove duplicated 'call & translate errors' code in bzrlib.remote.
1634
            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.
1635
                'Repository.tarball', path, compression)
1636
        except errors.UnknownSmartMethod:
1637
            protocol.cancel_read_body()
1638
            return None
2018.18.8 by Ian Clatworthy
Tarball proxy code & tests
1639
        if response[0] == 'ok':
1640
            # Extract the tarball and return it
2018.18.25 by Martin Pool
Repository.tarball fixes for python2.4
1641
            t = tempfile.NamedTemporaryFile()
1642
            # TODO: rpc layer should read directly into it...
1643
            t.write(protocol.read_body_bytes())
1644
            t.seek(0)
1645
            return t
2814.10.1 by Andrew Bennetts
Cope gracefully if the server doesn't support the Repository.tarball smart request.
1646
        raise errors.UnexpectedSmartServerResponse(response)
2018.18.8 by Ian Clatworthy
Tarball proxy code & tests
1647
6267.1.2 by Jelmer Vernooij
Avoid _ensure_real in some more calls.
1648
    @needs_read_lock
2440.1.1 by Martin Pool
Add new Repository.sprout,
1649
    def sprout(self, to_bzrdir, revision_id=None):
6267.1.2 by Jelmer Vernooij
Avoid _ensure_real in some more calls.
1650
        """Create a descendent repository for new development.
1651
1652
        Unlike clone, this does not copy the settings of the repository.
1653
        """
1654
        dest_repo = self._create_sprouting_repo(to_bzrdir, shared=False)
2535.3.17 by Andrew Bennetts
[broken] Closer to a working Repository.fetch_revisions smart request.
1655
        dest_repo.fetch(self, revision_id=revision_id)
1656
        return dest_repo
2440.1.1 by Martin Pool
Add new Repository.sprout,
1657
6267.1.2 by Jelmer Vernooij
Avoid _ensure_real in some more calls.
1658
    def _create_sprouting_repo(self, a_bzrdir, shared):
1659
        if not isinstance(a_bzrdir._format, self.bzrdir._format.__class__):
1660
            # use target default format.
1661
            dest_repo = a_bzrdir.create_repository()
1662
        else:
1663
            # Most control formats need the repository to be specifically
1664
            # created, but on some old all-in-one formats it's not needed
1665
            try:
1666
                dest_repo = self._format.initialize(a_bzrdir, shared=shared)
1667
            except errors.UninitializableFormat:
1668
                dest_repo = a_bzrdir.open_repository()
1669
        return dest_repo
1670
2018.14.1 by Andrew Bennetts
Update to current hpss branch? Fix lots of test failures.
1671
    ### These methods are just thin shims to the VFS object for now.
1672
6267.1.3 by Jelmer Vernooij
Fix tests.
1673
    @needs_read_lock
2018.14.1 by Andrew Bennetts
Update to current hpss branch? Fix lots of test failures.
1674
    def revision_tree(self, revision_id):
6267.1.3 by Jelmer Vernooij
Fix tests.
1675
        revision_id = _mod_revision.ensure_null(revision_id)
1676
        if revision_id == _mod_revision.NULL_REVISION:
1677
            return InventoryRevisionTree(self,
1678
                Inventory(root_id=None), _mod_revision.NULL_REVISION)
1679
        else:
1680
            return list(self.revision_trees([revision_id]))[0]
2018.14.1 by Andrew Bennetts
Update to current hpss branch? Fix lots of test failures.
1681
2520.4.113 by Aaron Bentley
Avoid peeking at Repository._serializer
1682
    def get_serializer_format(self):
6280.5.1 by Jelmer Vernooij
Add client side of Repository.get_serializer_format.
1683
        path = self.bzrdir._path_for_remote_call(self._client)
1684
        try:
1685
            response = self._call('VersionedFileRepository.get_serializer_format',
1686
                path)
1687
        except errors.UnknownSmartMethod:
1688
            self._ensure_real()
1689
            return self._real_repository.get_serializer_format()
1690
        if response[0] != 'ok':
1691
            raise errors.UnexpectedSmartServerResponse(response)
6280.5.2 by Jelmer Vernooij
New HPSS call VersionedFileRepository.get_serializer_format.
1692
        return response[1]
2520.4.113 by Aaron Bentley
Avoid peeking at Repository._serializer
1693
2018.14.1 by Andrew Bennetts
Update to current hpss branch? Fix lots of test failures.
1694
    def get_commit_builder(self, branch, parents, config, timestamp=None,
1695
                           timezone=None, committer=None, revprops=None,
5777.6.1 by Jelmer Vernooij
Add --lossy option to 'bzr commit'.
1696
                           revision_id=None, lossy=False):
2018.14.1 by Andrew Bennetts
Update to current hpss branch? Fix lots of test failures.
1697
        # FIXME: It ought to be possible to call this without immediately
1698
        # triggering _ensure_real.  For now it's the easiest thing to do.
1699
        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.
1700
        real_repo = self._real_repository
1701
        builder = real_repo.get_commit_builder(branch, parents,
2018.14.1 by Andrew Bennetts
Update to current hpss branch? Fix lots of test failures.
1702
                config, timestamp=timestamp, timezone=timezone,
5777.6.1 by Jelmer Vernooij
Add --lossy option to 'bzr commit'.
1703
                committer=committer, revprops=revprops,
1704
                revision_id=revision_id, lossy=lossy)
2018.14.1 by Andrew Bennetts
Update to current hpss branch? Fix lots of test failures.
1705
        return builder
1706
3221.12.1 by Robert Collins
Backport development1 format (stackable packs) to before-shallow-branches.
1707
    def add_fallback_repository(self, repository):
1708
        """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
1709
3221.12.1 by Robert Collins
Backport development1 format (stackable packs) to before-shallow-branches.
1710
        :param repository: A repository.
1711
        """
4118.1.1 by Andrew Bennetts
Fix performance regression (many small round-trips) when pushing to a remote pack, and tidy the tests.
1712
        if not self._format.supports_external_lookups:
1713
            raise errors.UnstackableRepositoryFormat(
1714
                self._format.network_name(), self.base)
3221.12.1 by Robert Collins
Backport development1 format (stackable packs) to before-shallow-branches.
1715
        # We need to accumulate additional repositories here, to pass them in
1716
        # on various RPC's.
4035.2.3 by Robert Collins
Fix trailing whitespace.
1717
        #
5609.54.1 by Gary Poster
repositories should not be locked in add_fallback_repository if they will not be used.
1718
        # Make the check before we lock: this raises an exception.
1719
        self._check_fallback_repository(repository)
4379.2.2 by John Arbash Meinel
Change the Repository.add_fallback_repository() contract slightly.
1720
        if self.is_locked():
1721
            # We will call fallback.unlock() when we transition to the unlocked
1722
            # state, so always add a lock here. If a caller passes us a locked
1723
            # repository, they are responsible for unlocking it later.
1724
            repository.lock_read()
3221.12.1 by Robert Collins
Backport development1 format (stackable packs) to before-shallow-branches.
1725
        self._fallback_repositories.append(repository)
4035.2.2 by Robert Collins
Minor tweaks to fix failing tests.
1726
        # If self._real_repository was parameterised already (e.g. because a
1727
        # _real_branch had its get_stacked_on_url method called), then the
1728
        # 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.
1729
        if self._real_repository is not None:
5158.6.7 by Martin Pool
More conversions to using user_url
1730
            fallback_locations = [repo.user_url for repo in
4226.2.5 by Robert Collins
Fix handling of fallback repositories some more.
1731
                self._real_repository._fallback_repositories]
5158.6.7 by Martin Pool
More conversions to using user_url
1732
            if repository.user_url not in fallback_locations:
4035.2.2 by Robert Collins
Minor tweaks to fix failing tests.
1733
                self._real_repository.add_fallback_repository(repository)
3221.12.1 by Robert Collins
Backport development1 format (stackable packs) to before-shallow-branches.
1734
5158.4.1 by Andrew Bennetts
Don't allow RemoteRepository to stack on incompatible formats.
1735
    def _check_fallback_repository(self, repository):
1736
        """Check that this repository can fallback to repository safely.
1737
1738
        Raise an error if not.
1739
1740
        :param repository: A repository to fallback to.
1741
        """
1742
        return _mod_repository.InterRepository._assert_same_model(
1743
            self, repository)
1744
2018.14.1 by Andrew Bennetts
Update to current hpss branch? Fix lots of test failures.
1745
    def add_inventory(self, revid, inv, parents):
1746
        self._ensure_real()
1747
        return self._real_repository.add_inventory(revid, inv, parents)
1748
3879.2.2 by John Arbash Meinel
Rename add_inventory_delta to add_inventory_by_delta.
1749
    def add_inventory_by_delta(self, basis_revision_id, delta, new_revision_id,
5076.1.1 by Jelmer Vernooij
Allow additional arguments to RemoteRepository.add_inventory_by_delta().
1750
            parents, basis_inv=None, propagate_caches=False):
3775.2.1 by Robert Collins
Create bzrlib.repository.Repository.add_inventory_delta for adding inventories via deltas.
1751
        self._ensure_real()
3879.2.2 by John Arbash Meinel
Rename add_inventory_delta to add_inventory_by_delta.
1752
        return self._real_repository.add_inventory_by_delta(basis_revision_id,
5076.1.2 by Jelmer Vernooij
pass the keyword args as keyword args, per Rob's review.
1753
            delta, new_revision_id, parents, basis_inv=basis_inv,
1754
            propagate_caches=propagate_caches)
3775.2.1 by Robert Collins
Create bzrlib.repository.Repository.add_inventory_delta for adding inventories via deltas.
1755
2018.14.1 by Andrew Bennetts
Update to current hpss branch? Fix lots of test failures.
1756
    def add_revision(self, rev_id, rev, inv=None, config=None):
1757
        self._ensure_real()
1758
        return self._real_repository.add_revision(
1759
            rev_id, rev, inv=inv, config=config)
1760
1761
    @needs_read_lock
1762
    def get_inventory(self, revision_id):
1763
        self._ensure_real()
1764
        return self._real_repository.get_inventory(revision_id)
1765
4476.3.86 by Andrew Bennetts
Fix bug in declaration of RemoteRepository.iter_inventories that was causing intermittent failures in test_iter_inventories_is_ordered.
1766
    def iter_inventories(self, revision_ids, ordering=None):
3169.2.1 by Robert Collins
New method ``iter_inventories`` on Repository for access to many
1767
        self._ensure_real()
4476.3.15 by Andrew Bennetts
Partially working fallback for pre-1.17 servers.
1768
        return self._real_repository.iter_inventories(revision_ids, ordering)
3169.2.1 by Robert Collins
New method ``iter_inventories`` on Repository for access to many
1769
2018.14.1 by Andrew Bennetts
Update to current hpss branch? Fix lots of test failures.
1770
    @needs_read_lock
1771
    def get_revision(self, revision_id):
6267.1.1 by Jelmer Vernooij
Avoid _ensure_real in a couple more places.
1772
        return self.get_revisions([revision_id])[0]
2018.14.1 by Andrew Bennetts
Update to current hpss branch? Fix lots of test failures.
1773
1774
    def get_transaction(self):
1775
        self._ensure_real()
1776
        return self._real_repository.get_transaction()
1777
1778
    @needs_read_lock
2018.5.138 by Robert Collins
Merge bzr.dev.
1779
    def clone(self, a_bzrdir, revision_id=None):
6267.1.2 by Jelmer Vernooij
Avoid _ensure_real in some more calls.
1780
        dest_repo = self._create_sprouting_repo(
6267.1.3 by Jelmer Vernooij
Fix tests.
1781
            a_bzrdir, shared=self.is_shared())
6267.1.2 by Jelmer Vernooij
Avoid _ensure_real in some more calls.
1782
        self.copy_content_into(dest_repo, revision_id)
1783
        return dest_repo
2018.14.1 by Andrew Bennetts
Update to current hpss branch? Fix lots of test failures.
1784
1785
    def make_working_trees(self):
3349.1.1 by Aaron Bentley
Enable setting and getting make_working_trees for all repositories
1786
        """See Repository.make_working_trees"""
6263.2.1 by Jelmer Vernooij
Add hpss call ``Repository.make_working_trees``
1787
        path = self.bzrdir._path_for_remote_call(self._client)
1788
        try:
1789
            response = self._call('Repository.make_working_trees', path)
1790
        except errors.UnknownSmartMethod:
1791
            self._ensure_real()
1792
            return self._real_repository.make_working_trees()
1793
        if response[0] not in ('yes', 'no'):
1794
            raise SmartProtocolError('unexpected response code %s' % (response,))
1795
        return response[0] == 'yes'
2018.14.1 by Andrew Bennetts
Update to current hpss branch? Fix lots of test failures.
1796
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.
1797
    def refresh_data(self):
5199.1.3 by Andrew Bennetts
Use Robert's text for the refresh_data docstring.
1798
        """Re-read any data needed to synchronise with disk.
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.
1799
1800
        This method is intended to be called after another repository instance
1801
        (such as one used by a smart server) has inserted data into the
5199.1.3 by Andrew Bennetts
Use Robert's text for the refresh_data docstring.
1802
        repository. On all repositories this will work outside of write groups.
1803
        Some repository formats (pack and newer for bzrlib native formats)
1804
        support refresh_data inside write groups. If called inside a write
1805
        group on a repository that does not support refreshing in a write group
1806
        IsInWriteGroupError will be raised.
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.
1807
        """
1808
        if self._real_repository is not None:
1809
            self._real_repository.refresh_data()
1810
3184.1.9 by Robert Collins
* ``Repository.get_data_stream`` is now deprecated in favour of
1811
    def revision_ids_to_search_result(self, result_set):
1812
        """Convert a set of revision ids to a graph SearchResult."""
1813
        result_parents = set()
1814
        for parents in self.get_graph().get_parent_map(
1815
            result_set).itervalues():
1816
            result_parents.update(parents)
1817
        included_keys = result_set.intersection(result_parents)
1818
        start_keys = result_set.difference(included_keys)
1819
        exclude_keys = result_parents.difference(result_set)
1820
        result = graph.SearchResult(start_keys, exclude_keys,
1821
            len(result_set), result_set)
1822
        return result
1823
1824
    @needs_read_lock
5539.2.10 by Andrew Bennetts
s/NotInOtherForRev/NotInOtherForRevs/, and allow passing multiple revision_ids to search_missing_revision_ids.
1825
    def search_missing_revision_ids(self, other,
1826
            revision_id=symbol_versioning.DEPRECATED_PARAMETER,
5852.1.6 by Jelmer Vernooij
Add extra test for Repository.search_missing_revision_ids.
1827
            find_ghosts=True, revision_ids=None, if_present_ids=None,
1828
            limit=None):
3184.1.9 by Robert Collins
* ``Repository.get_data_stream`` is now deprecated in favour of
1829
        """Return the revision ids that other has that this does not.
3943.8.1 by Marius Kruger
remove all trailing whitespace from bzr source
1830
3184.1.9 by Robert Collins
* ``Repository.get_data_stream`` is now deprecated in favour of
1831
        These are returned in topological order.
1832
1833
        revision_id: only return revision ids included by revision_id.
1834
        """
5539.2.10 by Andrew Bennetts
s/NotInOtherForRev/NotInOtherForRevs/, and allow passing multiple revision_ids to search_missing_revision_ids.
1835
        if symbol_versioning.deprecated_passed(revision_id):
1836
            symbol_versioning.warn(
1837
                'search_missing_revision_ids(revision_id=...) was '
5536.3.3 by Andrew Bennetts
Merge lp:bzr.
1838
                'deprecated in 2.4.  Use revision_ids=[...] instead.',
5539.2.10 by Andrew Bennetts
s/NotInOtherForRev/NotInOtherForRevs/, and allow passing multiple revision_ids to search_missing_revision_ids.
1839
                DeprecationWarning, stacklevel=2)
1840
            if revision_ids is not None:
1841
                raise AssertionError(
1842
                    'revision_ids is mutually exclusive with revision_id')
1843
            if revision_id is not None:
1844
                revision_ids = [revision_id]
5712.3.13 by Jelmer Vernooij
Add Prober.known_formats().
1845
        inter_repo = _mod_repository.InterRepository.get(other, self)
5539.2.10 by Andrew Bennetts
s/NotInOtherForRev/NotInOtherForRevs/, and allow passing multiple revision_ids to search_missing_revision_ids.
1846
        return inter_repo.search_missing_revision_ids(
5535.3.32 by Andrew Bennetts
Implement if_present_ids behaviour in all implementations and code paths of searching_missing_revision_ids
1847
            find_ghosts=find_ghosts, revision_ids=revision_ids,
5852.1.6 by Jelmer Vernooij
Add extra test for Repository.search_missing_revision_ids.
1848
            if_present_ids=if_present_ids, limit=limit)
3184.1.9 by Robert Collins
* ``Repository.get_data_stream`` is now deprecated in favour of
1849
5670.1.1 by Jelmer Vernooij
Remove all methods and arguments that were deprecated before bzr 2.0.0.
1850
    def fetch(self, source, revision_id=None, find_ghosts=False,
4070.9.2 by Andrew Bennetts
Rough prototype of allowing a SearchResult to be passed to fetch, and using that to improve network conversations.
1851
            fetch_spec=None):
4145.1.1 by Robert Collins
Explicitly prevent fetching while the target repository is in a write group.
1852
        # No base implementation to use as RemoteRepository is not a subclass
1853
        # 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.
1854
        if fetch_spec is not None and revision_id is not None:
1855
            raise AssertionError(
1856
                "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.
1857
        if self.is_in_write_group():
4145.1.3 by Robert Collins
NEWS conflicts.
1858
            raise errors.InternalBzrError(
1859
                "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.
1860
        # fast path same-url fetch operations
4509.3.19 by Martin Pool
RemoteRepository.fetch is not a no-op if there's different stacking
1861
        if (self.has_same_location(source)
1862
            and fetch_spec is None
4509.3.37 by Martin Pool
Remove RepositoryBase; make _has_same_location private
1863
            and self._has_same_fallbacks(source)):
2881.4.1 by Robert Collins
Move responsibility for detecting same-repo fetching from the
1864
            # check that last_revision is in 'from' and then return a
1865
            # no-operation.
1866
            if (revision_id is not None and
5712.3.13 by Jelmer Vernooij
Add Prober.known_formats().
1867
                not _mod_revision.is_null(revision_id)):
2881.4.1 by Robert Collins
Move responsibility for detecting same-repo fetching from the
1868
                self.get_revision(revision_id)
2592.4.5 by Martin Pool
Add Repository.base on all repositories.
1869
            return 0, []
4145.1.1 by Robert Collins
Explicitly prevent fetching while the target repository is in a write group.
1870
        # if there is no specific appropriate InterRepository, this will get
1871
        # the InterRepository base class, which raises an
1872
        # IncompatibleRepositories when asked to fetch.
5712.3.13 by Jelmer Vernooij
Add Prober.known_formats().
1873
        inter = _mod_repository.InterRepository.get(source, self)
5670.1.1 by Jelmer Vernooij
Remove all methods and arguments that were deprecated before bzr 2.0.0.
1874
        return inter.fetch(revision_id=revision_id,
4145.1.1 by Robert Collins
Explicitly prevent fetching while the target repository is in a write group.
1875
            find_ghosts=find_ghosts, fetch_spec=fetch_spec)
2018.14.1 by Andrew Bennetts
Update to current hpss branch? Fix lots of test failures.
1876
2520.4.54 by Aaron Bentley
Hang a create_bundle method off repository
1877
    def create_bundle(self, target, base, fileobj, format=None):
1878
        self._ensure_real()
1879
        self._real_repository.create_bundle(target, base, fileobj, format)
1880
2018.14.1 by Andrew Bennetts
Update to current hpss branch? Fix lots of test failures.
1881
    @needs_read_lock
5972.3.10 by Jelmer Vernooij
Deprecate Repository.get_ancestry.
1882
    @symbol_versioning.deprecated_method(
1883
        symbol_versioning.deprecated_in((2, 4, 0)))
2530.1.1 by Aaron Bentley
Make topological sorting optional for get_ancestry
1884
    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.
1885
        self._ensure_real()
2530.1.1 by Aaron Bentley
Make topological sorting optional for get_ancestry
1886
        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.
1887
1888
    def fileids_altered_by_revision_ids(self, revision_ids):
1889
        self._ensure_real()
1890
        return self._real_repository.fileids_altered_by_revision_ids(revision_ids)
1891
3036.1.3 by Robert Collins
Privatise VersionedFileChecker.
1892
    def _get_versioned_file_checker(self, revisions, revision_versions_cache):
2745.6.1 by Aaron Bentley
Initial checking of knit graphs
1893
        self._ensure_real()
3036.1.3 by Robert Collins
Privatise VersionedFileChecker.
1894
        return self._real_repository._get_versioned_file_checker(
2745.6.50 by Andrew Bennetts
Remove find_bad_ancestors; it's not needed anymore.
1895
            revisions, revision_versions_cache)
3943.8.1 by Marius Kruger
remove all trailing whitespace from bzr source
1896
2708.1.7 by Aaron Bentley
Rename extract_files_bytes to iter_files_bytes
1897
    def iter_files_bytes(self, desired_files):
2708.1.9 by Aaron Bentley
Clean-up docs and imports
1898
        """See Repository.iter_file_bytes.
2708.1.3 by Aaron Bentley
Implement extract_files_bytes on Repository
1899
        """
1900
        self._ensure_real()
2708.1.7 by Aaron Bentley
Rename extract_files_bytes to iter_files_bytes
1901
        return self._real_repository.iter_files_bytes(desired_files)
2708.1.3 by Aaron Bentley
Implement extract_files_bytes on Repository
1902
6015.24.4 by John Arbash Meinel
For it to all work properly, we have to expose get_parent_map_cached on RemoteRepository.
1903
    def get_cached_parent_map(self, revision_ids):
1904
        """See bzrlib.CachingParentsProvider.get_cached_parent_map"""
1905
        return self._unstacked_provider.get_cached_parent_map(revision_ids)
1906
3835.1.1 by Aaron Bentley
Stack get_parent_map on fallback repos
1907
    def get_parent_map(self, revision_ids):
3835.1.6 by Aaron Bentley
Reduce inefficiency when doing make_parents_provider frequently
1908
        """See bzrlib.Graph.get_parent_map()."""
3835.1.5 by Aaron Bentley
Fix make_parents_provider
1909
        return self._make_parents_provider().get_parent_map(revision_ids)
3835.1.1 by Aaron Bentley
Stack get_parent_map on fallback repos
1910
1911
    def _get_parent_map_rpc(self, keys):
3172.5.6 by Robert Collins
Create new smart server verb Repository.get_parent_map.
1912
        """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.
1913
        medium = self._client._medium
3453.4.10 by Andrew Bennetts
Change _is_remote_at_least to _is_remote_before.
1914
        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.
1915
            # We already found out that the server can't understand
3213.1.3 by Andrew Bennetts
Fix typo in comment.
1916
            # 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.
1917
            # graph.
3948.3.7 by Martin Pool
Updated tests for RemoteRepository.get_parent_map on old servers.
1918
            #
1919
            # Note that this reads the whole graph, when only some keys are
1920
            # wanted.  On this old server there's no way (?) to get them all
1921
            # in one go, and the user probably will have seen a warning about
1922
            # the server being old anyhow.
1923
            rg = self._get_revision_graph(None)
4031.3.3 by Matt Nordhoff
Review tweaks from Ben Finney
1924
            # 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
1925
            # get_revision_graph. Specifically, a "key:()" pair in
1926
            # get_revision_graph just means a node has no parents. For
1927
            # "get_parent_map" it means the node is a ghost. So fix up the
1928
            # graph to correct this.
1929
            #   https://bugs.launchpad.net/bzr/+bug/214894
1930
            # There is one other "bug" which is that ghosts in
1931
            # get_revision_graph() are not returned at all. But we won't worry
1932
            # about that for now.
1933
            for node_id, parent_ids in rg.iteritems():
1934
                if parent_ids == ():
1935
                    rg[node_id] = (NULL_REVISION,)
1936
            rg[NULL_REVISION] = ()
1937
            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.
1938
3172.5.6 by Robert Collins
Create new smart server verb Repository.get_parent_map.
1939
        keys = set(keys)
3373.5.2 by John Arbash Meinel
Add repository_implementation tests for get_parent_map
1940
        if None in keys:
1941
            raise ValueError('get_parent_map(None) is not valid')
3172.5.6 by Robert Collins
Create new smart server verb Repository.get_parent_map.
1942
        if NULL_REVISION in keys:
1943
            keys.discard(NULL_REVISION)
1944
            found_parents = {NULL_REVISION:()}
1945
            if not keys:
1946
                return found_parents
1947
        else:
1948
            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.
1949
        # TODO(Needs analysis): We could assume that the keys being requested
1950
        # from get_parent_map are in a breadth first search, so typically they
1951
        # will all be depth N from some common parent, and we don't have to
1952
        # have the server iterate from the root parent, but rather from the
1953
        # keys we're searching; and just tell the server the keyspace we
1954
        # already have; but this may be more traffic again.
1955
1956
        # Transform self._parents_map into a search request recipe.
1957
        # TODO: Manage this incrementally to avoid covering the same path
1958
        # repeatedly. (The server will have to on each request, but the less
1959
        # work done the better).
4190.1.3 by Robert Collins
Allow optional inclusion of ghost data in server get_parent_map calls.
1960
        #
1961
        # Negative caching notes:
1962
        # new server sends missing when a request including the revid
1963
        # 'include-missing:' is present in the request.
1964
        # missing keys are serialised as missing:X, and we then call
1965
        # provider.note_missing(X) for-all X
3835.1.8 by Aaron Bentley
Make UnstackedParentsProvider manage the cache
1966
        parents_map = self._unstacked_provider.get_cached_map()
3213.1.8 by Andrew Bennetts
Merge from bzr.dev.
1967
        if parents_map is None:
1968
            # Repository is not locked, so there's no cache.
1969
            parents_map = {}
6015.23.11 by John Arbash Meinel
allow a bit more flexibilty in how we walk the searches.
1970
        if _DEFAULT_SEARCH_DEPTH <= 0:
1971
            (start_set, stop_keys,
1972
             key_count) = graph.search_result_from_parent_map(
1973
                parents_map, self._unstacked_provider.missing_keys)
1974
        else:
6015.23.8 by John Arbash Meinel
Play around with when to activate how much history searching.
1975
            (start_set, stop_keys,
1976
             key_count) = graph.limited_search_result_from_parent_map(
1977
                parents_map, self._unstacked_provider.missing_keys,
6015.23.11 by John Arbash Meinel
allow a bit more flexibilty in how we walk the searches.
1978
                keys, depth=_DEFAULT_SEARCH_DEPTH)
6015.23.3 by John Arbash Meinel
Start refactoring code into graph.py code for easier testing.
1979
        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.
1980
        body = self._serialise_search_recipe(recipe)
3172.5.6 by Robert Collins
Create new smart server verb Repository.get_parent_map.
1981
        path = self.bzrdir._path_for_remote_call(self._client)
1982
        for key in keys:
3360.2.8 by Martin Pool
Change assertion to a plain raise
1983
            if type(key) is not str:
1984
                raise ValueError(
1985
                    "key %r not a plain string" % (key,))
3172.5.8 by Robert Collins
Review feedback.
1986
        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.
1987
        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.
1988
        try:
3786.2.3 by Andrew Bennetts
Remove duplicated 'call & translate errors' code in bzrlib.remote.
1989
            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.
1990
                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.
1991
        except errors.UnknownSmartMethod:
3213.1.2 by Andrew Bennetts
Add test for reconnection if get_parent_map is unknown by the server.
1992
            # 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.
1993
            # Worse, we have to force a disconnection, because the server now
1994
            # doesn't realise it has a body on the wire to consume, so the
1995
            # only way to recover is to abandon the connection.
3213.1.6 by Andrew Bennetts
Emit warnings when forcing a reconnect.
1996
            warning(
1997
                'Server is too old for fast get_parent_map, reconnecting.  '
1998
                '(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.
1999
            medium.disconnect()
2000
            # To avoid having to disconnect repeatedly, we keep track of the
2001
            # 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.
2002
            medium._remember_remote_is_before((1, 2))
3948.3.7 by Martin Pool
Updated tests for RemoteRepository.get_parent_map on old servers.
2003
            # Recurse just once and we should use the fallback code.
2004
            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.
2005
        response_tuple, response_handler = response
2006
        if response_tuple[0] not in ['ok']:
2007
            response_handler.cancel_read_body()
2008
            raise errors.UnexpectedSmartServerResponse(response_tuple)
2009
        if response_tuple[0] == 'ok':
2010
            coded = bz2.decompress(response_handler.read_body_bytes())
3172.5.6 by Robert Collins
Create new smart server verb Repository.get_parent_map.
2011
            if coded == '':
2012
                # no revisions found
2013
                return {}
2014
            lines = coded.split('\n')
2015
            revision_graph = {}
2016
            for line in lines:
2017
                d = tuple(line.split())
2018
                if len(d) > 1:
2019
                    revision_graph[d[0]] = d[1:]
2020
                else:
4190.1.4 by Robert Collins
Cache ghosts when we can get them from a RemoteRepository in get_parent_map.
2021
                    # No parents:
2022
                    if d[0].startswith('missing:'):
2023
                        revid = d[0][8:]
2024
                        self._unstacked_provider.note_missing_key(revid)
2025
                    else:
2026
                        # no parents - so give the Graph result
2027
                        # (NULL_REVISION,).
2028
                        revision_graph[d[0]] = (NULL_REVISION,)
3172.5.6 by Robert Collins
Create new smart server verb Repository.get_parent_map.
2029
            return revision_graph
2030
2018.14.1 by Andrew Bennetts
Update to current hpss branch? Fix lots of test failures.
2031
    @needs_read_lock
2032
    def get_signature_text(self, revision_id):
2033
        self._ensure_real()
2034
        return self._real_repository.get_signature_text(revision_id)
2035
2036
    @needs_read_lock
4988.5.1 by Jelmer Vernooij
Rename Repository.get_inventory_xml -> Repository._get_inventory_xml.
2037
    def _get_inventory_xml(self, revision_id):
2018.14.1 by Andrew Bennetts
Update to current hpss branch? Fix lots of test failures.
2038
        self._ensure_real()
4988.5.1 by Jelmer Vernooij
Rename Repository.get_inventory_xml -> Repository._get_inventory_xml.
2039
        return self._real_repository._get_inventory_xml(revision_id)
2018.14.1 by Andrew Bennetts
Update to current hpss branch? Fix lots of test failures.
2040
2041
    def reconcile(self, other=None, thorough=False):
2042
        self._ensure_real()
2043
        return self._real_repository.reconcile(other=other, thorough=thorough)
3943.8.1 by Marius Kruger
remove all trailing whitespace from bzr source
2044
2018.14.1 by Andrew Bennetts
Update to current hpss branch? Fix lots of test failures.
2045
    def all_revision_ids(self):
6280.3.1 by Jelmer Vernooij
Add remote side of Repository.all_revision_ids.
2046
        path = self.bzrdir._path_for_remote_call(self._client)
2047
        try:
2048
            response_tuple, response_handler = self._call_expecting_body(
2049
                "Repository.all_revision_ids", path)
2050
        except errors.UnknownSmartMethod:
2051
            self._ensure_real()
2052
            return self._real_repository.all_revision_ids()
2053
        if response_tuple != ("ok", ):
2054
            raise errors.UnexpectedSmartServerResponse(response_tuple)
6280.3.3 by Jelmer Vernooij
Cope with fallback repositories.
2055
        revids = set(response_handler.read_body_bytes().splitlines())
2056
        for fallback in self._fallback_repositories:
2057
            revids.update(set(fallback.all_revision_ids()))
2058
        return list(revids)
3943.8.1 by Marius Kruger
remove all trailing whitespace from bzr source
2059
2018.14.1 by Andrew Bennetts
Update to current hpss branch? Fix lots of test failures.
2060
    @needs_read_lock
4137.3.2 by Ian Clatworthy
Repository.get_deltas_for_revisions() now supports file-id filtering
2061
    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.
2062
        self._ensure_real()
4137.3.2 by Ian Clatworthy
Repository.get_deltas_for_revisions() now supports file-id filtering
2063
        return self._real_repository.get_deltas_for_revisions(revisions,
2064
            specific_fileids=specific_fileids)
2018.14.1 by Andrew Bennetts
Update to current hpss branch? Fix lots of test failures.
2065
2066
    @needs_read_lock
4137.3.2 by Ian Clatworthy
Repository.get_deltas_for_revisions() now supports file-id filtering
2067
    def get_revision_delta(self, revision_id, specific_fileids=None):
6267.1.2 by Jelmer Vernooij
Avoid _ensure_real in some more calls.
2068
        r = self.get_revision(revision_id)
2069
        return list(self.get_deltas_for_revisions([r],
2070
            specific_fileids=specific_fileids))[0]
2018.14.1 by Andrew Bennetts
Update to current hpss branch? Fix lots of test failures.
2071
2072
    @needs_read_lock
2073
    def revision_trees(self, revision_ids):
2074
        self._ensure_real()
2075
        return self._real_repository.revision_trees(revision_ids)
2076
2077
    @needs_read_lock
2078
    def get_revision_reconcile(self, revision_id):
2079
        self._ensure_real()
2080
        return self._real_repository.get_revision_reconcile(revision_id)
2081
2082
    @needs_read_lock
4332.3.35 by Robert Collins
Fix failing tests.
2083
    def check(self, revision_ids=None, callback_refs=None, check_repo=True):
2018.14.1 by Andrew Bennetts
Update to current hpss branch? Fix lots of test failures.
2084
        self._ensure_real()
4332.3.11 by Robert Collins
Move tree and back callbacks into the repository check core.
2085
        return self._real_repository.check(revision_ids=revision_ids,
4332.3.35 by Robert Collins
Fix failing tests.
2086
            callback_refs=callback_refs, check_repo=check_repo)
2018.14.1 by Andrew Bennetts
Update to current hpss branch? Fix lots of test failures.
2087
2018.5.138 by Robert Collins
Merge bzr.dev.
2088
    def copy_content_into(self, destination, revision_id=None):
6267.1.1 by Jelmer Vernooij
Avoid _ensure_real in a couple more places.
2089
        """Make a complete copy of the content in self into destination.
2090
2091
        This is a destructive operation! Do not use it on existing
2092
        repositories.
2093
        """
2094
        interrepo = _mod_repository.InterRepository.get(self, destination)
2095
        return interrepo.copy_content(revision_id)
2018.14.1 by Andrew Bennetts
Update to current hpss branch? Fix lots of test failures.
2096
2814.10.2 by Andrew Bennetts
Make the fallback a little tidier.
2097
    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.
2098
        # get a tarball of the remote repository, and copy from that into the
2099
        # destination
2100
        from bzrlib import osutils
2018.18.9 by Martin Pool
remote Repository.tarball builds a temporary directory and tars that
2101
        import tarfile
2018.18.20 by Martin Pool
Route branch operations through remote copy_content_into
2102
        # TODO: Maybe a progress bar while streaming the tarball?
6138.3.4 by Jonathan Riddell
add gettext() to uses of trace.note()
2103
        note(gettext("Copying repository content as tarball..."))
2018.18.25 by Martin Pool
Repository.tarball fixes for python2.4
2104
        tar_file = self._get_tarball('bz2')
2814.10.2 by Andrew Bennetts
Make the fallback a little tidier.
2105
        if tar_file is None:
2106
            return None
2107
        destination = to_bzrdir.create_repository()
2018.18.10 by Martin Pool
copy_content_into from Remote repositories by using temporary directories on both ends.
2108
        try:
2018.18.25 by Martin Pool
Repository.tarball fixes for python2.4
2109
            tar = tarfile.open('repository', fileobj=tar_file,
2110
                mode='r|bz2')
3638.3.2 by Vincent Ladeuil
Fix all calls to tempfile.mkdtemp to osutils.mkdtemp.
2111
            tmpdir = osutils.mkdtemp()
2018.18.25 by Martin Pool
Repository.tarball fixes for python2.4
2112
            try:
2113
                _extract_tar(tar, tmpdir)
5712.3.13 by Jelmer Vernooij
Add Prober.known_formats().
2114
                tmp_bzrdir = _mod_bzrdir.BzrDir.open(tmpdir)
2018.18.25 by Martin Pool
Repository.tarball fixes for python2.4
2115
                tmp_repo = tmp_bzrdir.open_repository()
2116
                tmp_repo.copy_content_into(destination, revision_id)
2117
            finally:
2118
                osutils.rmtree(tmpdir)
2018.18.10 by Martin Pool
copy_content_into from Remote repositories by using temporary directories on both ends.
2119
        finally:
2018.18.25 by Martin Pool
Repository.tarball fixes for python2.4
2120
            tar_file.close()
2814.10.2 by Andrew Bennetts
Make the fallback a little tidier.
2121
        return destination
2018.18.23 by Martin Pool
review cleanups
2122
        # TODO: Suggestion from john: using external tar is much faster than
2123
        # 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.
2124
3842.3.20 by Andrew Bennetts
Re-revert changes from another thread that accidentally got reinstated here.
2125
    @property
2126
    def inventories(self):
2127
        """Decorate the real repository for now.
2128
2129
        In the long term a full blown network facility is needed to
2130
        avoid creating a real repository object locally.
2131
        """
2132
        self._ensure_real()
2133
        return self._real_repository.inventories
2134
2604.2.1 by Robert Collins
(robertc) Introduce a pack command.
2135
    @needs_write_lock
5108.1.1 by Parth Malwankar
initial support for 'pack --clean-obsolete-packs'. tested only manually.
2136
    def pack(self, hint=None, clean_obsolete_packs=False):
2604.2.1 by Robert Collins
(robertc) Introduce a pack command.
2137
        """Compress the data within the repository.
2138
        """
6305.2.3 by Jelmer Vernooij
Store hint in body.
2139
        if hint is None:
2140
            body = ""
2141
        else:
2142
            body = "".join([l+"\n" for l in hint])
6305.2.1 by Jelmer Vernooij
add remote call for Repository.pack.
2143
        path = self.bzrdir._path_for_remote_call(self._client)
2144
        try:
6305.2.3 by Jelmer Vernooij
Store hint in body.
2145
            response, handler = self._call_with_body_bytes_expecting_body(
2146
                'Repository.pack', (path, self._lock_token,
6305.2.4 by Jelmer Vernooij
Fix tests.
2147
                    str(clean_obsolete_packs)), body)
6305.2.1 by Jelmer Vernooij
add remote call for Repository.pack.
2148
        except errors.UnknownSmartMethod:
2149
            self._ensure_real()
2150
            return self._real_repository.pack(hint=hint,
2151
                clean_obsolete_packs=clean_obsolete_packs)
6305.2.3 by Jelmer Vernooij
Store hint in body.
2152
        handler.cancel_read_body()
6305.2.1 by Jelmer Vernooij
add remote call for Repository.pack.
2153
        if response != ('ok', ):
2154
            raise errors.UnexpectedSmartServerResponse(response)
2604.2.1 by Robert Collins
(robertc) Introduce a pack command.
2155
3842.3.20 by Andrew Bennetts
Re-revert changes from another thread that accidentally got reinstated here.
2156
    @property
2157
    def revisions(self):
2158
        """Decorate the real repository for now.
2159
2160
        In the short term this should become a real object to intercept graph
2161
        lookups.
2162
2163
        In the long term a full blown network facility is needed.
2164
        """
2165
        self._ensure_real()
2166
        return self._real_repository.revisions
2167
2018.14.1 by Andrew Bennetts
Update to current hpss branch? Fix lots of test failures.
2168
    def set_make_working_trees(self, new_value):
4017.3.4 by Robert Collins
Create a verb for Repository.set_make_working_trees.
2169
        if new_value:
2170
            new_value_str = "True"
2171
        else:
2172
            new_value_str = "False"
2173
        path = self.bzrdir._path_for_remote_call(self._client)
2174
        try:
2175
            response = self._call(
2176
                'Repository.set_make_working_trees', path, new_value_str)
2177
        except errors.UnknownSmartMethod:
2178
            self._ensure_real()
2179
            self._real_repository.set_make_working_trees(new_value)
2180
        else:
2181
            if response[0] != 'ok':
2182
                raise errors.UnexpectedSmartServerResponse(response)
2018.14.1 by Andrew Bennetts
Update to current hpss branch? Fix lots of test failures.
2183
3842.3.20 by Andrew Bennetts
Re-revert changes from another thread that accidentally got reinstated here.
2184
    @property
2185
    def signatures(self):
2186
        """Decorate the real repository for now.
2187
2188
        In the long term a full blown network facility is needed to avoid
2189
        creating a real repository object locally.
2190
        """
2191
        self._ensure_real()
2192
        return self._real_repository.signatures
2193
2018.14.1 by Andrew Bennetts
Update to current hpss branch? Fix lots of test failures.
2194
    @needs_write_lock
2195
    def sign_revision(self, revision_id, gpg_strategy):
6280.8.1 by Jelmer Vernooij
Avoid _ensure_real in RemoteRepository.verify_revision_signature and RemoteRepository.sign_revision.
2196
        testament = _mod_testament.Testament.from_revision(self, revision_id)
2197
        plaintext = testament.as_short_text()
2198
        self.store_revision_signature(gpg_strategy, plaintext, revision_id)
2018.14.1 by Andrew Bennetts
Update to current hpss branch? Fix lots of test failures.
2199
3842.3.20 by Andrew Bennetts
Re-revert changes from another thread that accidentally got reinstated here.
2200
    @property
2201
    def texts(self):
2202
        """Decorate the real repository for now.
2203
2204
        In the long term a full blown network facility is needed to avoid
2205
        creating a real repository object locally.
2206
        """
2207
        self._ensure_real()
2208
        return self._real_repository.texts
2209
2018.14.1 by Andrew Bennetts
Update to current hpss branch? Fix lots of test failures.
2210
    @needs_read_lock
2211
    def get_revisions(self, revision_ids):
2212
        self._ensure_real()
2213
        return self._real_repository.get_revisions(revision_ids)
2214
2215
    def supports_rich_root(self):
4053.1.4 by Robert Collins
Move the fetch control attributes from Repository to RepositoryFormat.
2216
        return self._format.rich_root_data
2018.14.1 by Andrew Bennetts
Update to current hpss branch? Fix lots of test failures.
2217
5972.2.1 by Jelmer Vernooij
Deprecate Repository.iter_reverse_revision_history.
2218
    @symbol_versioning.deprecated_method(symbol_versioning.deprecated_in((2, 4, 0)))
2018.5.83 by Andrew Bennetts
Fix some test failures caused by the switch from unicode to UTF-8-encoded strs for revision IDs.
2219
    def iter_reverse_revision_history(self, revision_id):
2220
        self._ensure_real()
2221
        return self._real_repository.iter_reverse_revision_history(revision_id)
2222
2018.5.96 by Andrew Bennetts
Merge from bzr.dev, resolving the worst of the semantic conflicts, but there's
2223
    @property
2224
    def _serializer(self):
4053.1.4 by Robert Collins
Move the fetch control attributes from Repository to RepositoryFormat.
2225
        return self._format._serializer
2018.5.96 by Andrew Bennetts
Merge from bzr.dev, resolving the worst of the semantic conflicts, but there's
2226
6267.1.1 by Jelmer Vernooij
Avoid _ensure_real in a couple more places.
2227
    @needs_write_lock
2018.5.97 by Andrew Bennetts
Fix more tests.
2228
    def store_revision_signature(self, gpg_strategy, plaintext, revision_id):
6267.1.1 by Jelmer Vernooij
Avoid _ensure_real in a couple more places.
2229
        signature = gpg_strategy.sign(plaintext)
2230
        self.add_signature_text(revision_id, signature)
2018.5.97 by Andrew Bennetts
Fix more tests.
2231
2996.2.8 by Aaron Bentley
Fix add_signature discrepancies
2232
    def add_signature_text(self, revision_id, signature):
6268.1.10 by Jelmer Vernooij
Use real repository if it is already present.
2233
        if self._real_repository:
2234
            # If there is a real repository the write group will
2235
            # be in the real repository as well, so use that:
6268.1.2 by Jelmer Vernooij
Initial work on Repository.add_signature_text.
2236
            self._ensure_real()
2237
            return self._real_repository.add_signature_text(
2238
                revision_id, signature)
6268.1.10 by Jelmer Vernooij
Use real repository if it is already present.
2239
        path = self.bzrdir._path_for_remote_call(self._client)
2240
        response, response_handler = self._call_with_body_bytes(
2241
            'Repository.add_signature_text', (path, revision_id),
2242
            signature)
6268.1.2 by Jelmer Vernooij
Initial work on Repository.add_signature_text.
2243
        self.refresh_data()
2244
        if response[0] != 'ok':
2245
            raise errors.UnexpectedSmartServerResponse(response)
2996.2.3 by Aaron Bentley
Add tests for install_revisions and add_signature
2246
2018.5.97 by Andrew Bennetts
Fix more tests.
2247
    def has_signature_for_revision_id(self, revision_id):
6265.1.1 by Jelmer Vernooij
Add new HPSS call ``Repository.has_signature_for_revision_id``.
2248
        path = self.bzrdir._path_for_remote_call(self._client)
2249
        try:
2250
            response = self._call('Repository.has_signature_for_revision_id',
2251
                path, revision_id)
2252
        except errors.UnknownSmartMethod:
2253
            self._ensure_real()
2254
            return self._real_repository.has_signature_for_revision_id(
2255
                revision_id)
2256
        if response[0] not in ('yes', 'no'):
2257
            raise SmartProtocolError('unexpected response code %s' % (response,))
2258
        return (response[0] == 'yes')
2018.5.97 by Andrew Bennetts
Fix more tests.
2259
6280.8.5 by Jelmer Vernooij
Add needs_read_lock for verify_revision_signature.
2260
    @needs_read_lock
6257.3.1 by Jelmer Vernooij
Support verifying remote signatures.
2261
    def verify_revision_signature(self, revision_id, gpg_strategy):
6280.8.1 by Jelmer Vernooij
Avoid _ensure_real in RemoteRepository.verify_revision_signature and RemoteRepository.sign_revision.
2262
        if not self.has_signature_for_revision_id(revision_id):
2263
            return gpg.SIGNATURE_NOT_SIGNED, None
2264
        signature = self.get_signature_text(revision_id)
2265
2266
        testament = _mod_testament.Testament.from_revision(self, revision_id)
2267
        plaintext = testament.as_short_text()
2268
2269
        return gpg_strategy.verify(signature, plaintext)
6257.3.1 by Jelmer Vernooij
Support verifying remote signatures.
2270
2535.3.45 by Andrew Bennetts
Add item_keys_introduced_by to RemoteRepository.
2271
    def item_keys_introduced_by(self, revision_ids, _files_pb=None):
2272
        self._ensure_real()
2273
        return self._real_repository.item_keys_introduced_by(revision_ids,
2274
            _files_pb=_files_pb)
2275
4332.3.34 by Robert Collins
Delete obsolete pack tuned find_inconsistent_revisions as the generic code path permits the same optimisation.
2276
    def _find_inconsistent_revision_parents(self, revisions_iterator=None):
2819.2.5 by Andrew Bennetts
Make reconcile abort gracefully if the revision index has bad parents.
2277
        self._ensure_real()
4332.3.34 by Robert Collins
Delete obsolete pack tuned find_inconsistent_revisions as the generic code path permits the same optimisation.
2278
        return self._real_repository._find_inconsistent_revision_parents(
2279
            revisions_iterator)
2819.2.5 by Andrew Bennetts
Make reconcile abort gracefully if the revision index has bad parents.
2280
2281
    def _check_for_inconsistent_revision_parents(self):
2282
        self._ensure_real()
2283
        return self._real_repository._check_for_inconsistent_revision_parents()
2284
3835.1.17 by Aaron Bentley
Fix stacking bug
2285
    def _make_parents_provider(self, other=None):
3835.1.8 by Aaron Bentley
Make UnstackedParentsProvider manage the cache
2286
        providers = [self._unstacked_provider]
3835.1.17 by Aaron Bentley
Fix stacking bug
2287
        if other is not None:
2288
            providers.insert(0, other)
5816.8.3 by Andrew Bennetts
Add test for calling add_fallback_repository after _make_parents_provider, and make it work.
2289
        return graph.StackedParentsProvider(_LazyListJoin(
2290
            providers, self._fallback_repositories))
3172.5.1 by Robert Collins
Create a RemoteRepository get_graph implementation and delegate get_parents_map to the real repository.
2291
3842.3.20 by Andrew Bennetts
Re-revert changes from another thread that accidentally got reinstated here.
2292
    def _serialise_search_recipe(self, recipe):
2293
        """Serialise a graph search recipe.
2294
2295
        :param recipe: A search recipe (start, stop, count).
2296
        :return: Serialised bytes.
2297
        """
4152.1.2 by Robert Collins
Add streaming from a stacked branch when the sort order is compatible with doing so.
2298
        start_keys = ' '.join(recipe[1])
2299
        stop_keys = ' '.join(recipe[2])
2300
        count = str(recipe[3])
3842.3.20 by Andrew Bennetts
Re-revert changes from another thread that accidentally got reinstated here.
2301
        return '\n'.join((start_keys, stop_keys, count))
2302
4070.9.5 by Andrew Bennetts
Better wire protocol: don't shoehorn MiniSearchResult serialisation into previous serialisation format.
2303
    def _serialise_search_result(self, search_result):
5539.2.2 by Andrew Bennetts
Add support for 'everything' fetch spec to RemoteStreamSource.
2304
        parts = search_result.get_network_struct()
4070.9.5 by Andrew Bennetts
Better wire protocol: don't shoehorn MiniSearchResult serialisation into previous serialisation format.
2305
        return '\n'.join(parts)
2306
3842.3.2 by Andrew Bennetts
Revert the RemoteVersionedFiles.get_parent_map implementation, leaving just the skeleton of RemoteVersionedFiles.
2307
    def autopack(self):
2308
        path = self.bzrdir._path_for_remote_call(self._client)
2309
        try:
2310
            response = self._call('PackRepository.autopack', path)
2311
        except errors.UnknownSmartMethod:
2312
            self._ensure_real()
2313
            self._real_repository._pack_collection.autopack()
2314
            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.
2315
        self.refresh_data()
3842.3.2 by Andrew Bennetts
Revert the RemoteVersionedFiles.get_parent_map implementation, leaving just the skeleton of RemoteVersionedFiles.
2316
        if response[0] != 'ok':
2317
            raise errors.UnexpectedSmartServerResponse(response)
2318
2319
5815.4.1 by Jelmer Vernooij
Split versionedfile-specific stuff out into VersionedFileRepository.
2320
class RemoteStreamSink(vf_repository.StreamSink):
4022.1.6 by Robert Collins
Cherrypick and polish the RemoteSink for streaming push.
2321
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.
2322
    def _insert_real(self, stream, src_format, resume_tokens):
4022.1.6 by Robert Collins
Cherrypick and polish the RemoteSink for streaming push.
2323
        self.target_repo._ensure_real()
2324
        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.
2325
        result = sink.insert_stream(stream, src_format, resume_tokens)
4029.2.1 by Robert Collins
Support streaming push to stacked branches.
2326
        if not result:
2327
            self.target_repo.autopack()
2328
        return result
4022.1.6 by Robert Collins
Cherrypick and polish the RemoteSink for streaming push.
2329
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.
2330
    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.
2331
        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.
2332
        target._unstacked_provider.missing_keys.clear()
4476.3.82 by Andrew Bennetts
Mention another bug fix in NEWS, and update verb name, comments, and NEWS additions for landing on 1.19 rather than 1.18.
2333
        candidate_calls = [('Repository.insert_stream_1.19', (1, 19))]
4144.3.2 by Andrew Bennetts
Use Repository.insert_stream_locked if there is a lock_token for the remote repo.
2334
        if target._lock_token:
4476.3.15 by Andrew Bennetts
Partially working fallback for pre-1.17 servers.
2335
            candidate_calls.append(('Repository.insert_stream_locked', (1, 14)))
2336
            lock_args = (target._lock_token or '',)
4144.3.2 by Andrew Bennetts
Use Repository.insert_stream_locked if there is a lock_token for the remote repo.
2337
        else:
4476.3.15 by Andrew Bennetts
Partially working fallback for pre-1.17 servers.
2338
            candidate_calls.append(('Repository.insert_stream', (1, 13)))
2339
            lock_args = ()
4144.3.2 by Andrew Bennetts
Use Repository.insert_stream_locked if there is a lock_token for the remote repo.
2340
        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)
2341
        medium = client._medium
4144.3.2 by Andrew Bennetts
Use Repository.insert_stream_locked if there is a lock_token for the remote repo.
2342
        path = target.bzrdir._path_for_remote_call(client)
4476.3.70 by Andrew Bennetts
Review tweaks.
2343
        # Probe for the verb to use with an empty stream before sending the
2344
        # real stream to it.  We do this both to avoid the risk of sending a
2345
        # large request that is then rejected, and because we don't want to
2346
        # implement a way to buffer, rewind, or restart the stream.
4476.3.15 by Andrew Bennetts
Partially working fallback for pre-1.17 servers.
2347
        found_verb = False
2348
        for verb, required_version in candidate_calls:
2349
            if medium._is_remote_before(required_version):
2350
                continue
4476.3.25 by Andrew Bennetts
Reinstate don't-reprobe-with-resume-tokens optimisation, fixing acceptance test.
2351
            if resume_tokens:
2352
                # We've already done the probing (and set _is_remote_before) on
2353
                # a previous insert.
2354
                found_verb = True
2355
                break
4060.1.4 by Robert Collins
Streaming fetch from remote servers.
2356
            byte_stream = smart_repo._stream_to_byte_stream([], src_format)
4029.2.1 by Robert Collins
Support streaming push to stacked branches.
2357
            try:
2358
                response = client.call_with_body_stream(
4476.3.15 by Andrew Bennetts
Partially working fallback for pre-1.17 servers.
2359
                    (verb, path, '') + lock_args, byte_stream)
4029.2.1 by Robert Collins
Support streaming push to stacked branches.
2360
            except errors.UnknownSmartMethod:
4144.3.2 by Andrew Bennetts
Use Repository.insert_stream_locked if there is a lock_token for the remote repo.
2361
                medium._remember_remote_is_before(required_version)
4476.3.15 by Andrew Bennetts
Partially working fallback for pre-1.17 servers.
2362
            else:
2363
                found_verb = True
2364
                break
2365
        if not found_verb:
2366
            # Have to use VFS.
2367
            return self._insert_real(stream, src_format, resume_tokens)
2368
        self._last_inv_record = None
2369
        self._last_substream = None
4476.3.82 by Andrew Bennetts
Mention another bug fix in NEWS, and update verb name, comments, and NEWS additions for landing on 1.19 rather than 1.18.
2370
        if required_version < (1, 19):
4476.3.35 by Andrew Bennetts
Expand comment.
2371
            # Remote side doesn't support inventory deltas.  Wrap the stream to
2372
            # make sure we don't send any.  If the stream contains inventory
2373
            # deltas we'll interrupt the smart insert_stream request and
2374
            # fallback to VFS.
4476.3.15 by Andrew Bennetts
Partially working fallback for pre-1.17 servers.
2375
            stream = self._stop_stream_if_inventory_delta(stream)
4060.1.4 by Robert Collins
Streaming fetch from remote servers.
2376
        byte_stream = smart_repo._stream_to_byte_stream(
2377
            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.
2378
        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)
2379
        response = client.call_with_body_stream(
4476.3.15 by Andrew Bennetts
Partially working fallback for pre-1.17 servers.
2380
            (verb, path, resume_tokens) + lock_args, byte_stream)
4029.2.1 by Robert Collins
Support streaming push to stacked branches.
2381
        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)
2382
            raise errors.UnexpectedSmartServerResponse(response)
4476.3.54 by Andrew Bennetts
Update fallback-to-VFS in remote.py for the inventory-deltas substream.
2383
        if self._last_substream is not None:
4476.3.21 by Andrew Bennetts
Clarify some code and comments, and s/1.17/1.18/ in a few places.
2384
            # The stream included an inventory-delta record, but the remote
2385
            # side isn't new enough to support them.  So we need to send the
2386
            # rest of the stream via VFS.
4634.35.15 by Andrew Bennetts
Fix 'fallback to vfs if RPC does not support inventory-deltas' case to refresh the vfs pack names before starting the fallback.
2387
            self.target_repo.refresh_data()
4476.3.21 by Andrew Bennetts
Clarify some code and comments, and s/1.17/1.18/ in a few places.
2388
            return self._resume_stream_with_vfs(response, src_format)
4029.2.1 by Robert Collins
Support streaming push to stacked branches.
2389
        if response[0][0] == 'missing-basis':
2390
            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.
2391
            resume_tokens = tokens
4257.3.3 by Andrew Bennetts
missing_keys from sink.insert_stream should be a set, not a tuple.
2392
            return resume_tokens, set(missing_keys)
4029.2.1 by Robert Collins
Support streaming push to stacked branches.
2393
        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.
2394
            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.
2395
            return [], set()
4032.1.1 by John Arbash Meinel
Merge the removal of all trailing whitespace, and resolve conflicts.
2396
4476.3.21 by Andrew Bennetts
Clarify some code and comments, and s/1.17/1.18/ in a few places.
2397
    def _resume_stream_with_vfs(self, response, src_format):
2398
        """Resume sending a stream via VFS, first resending the record and
2399
        substream that couldn't be sent via an insert_stream verb.
2400
        """
4476.3.15 by Andrew Bennetts
Partially working fallback for pre-1.17 servers.
2401
        if response[0][0] == 'missing-basis':
2402
            tokens, missing_keys = bencode.bdecode_as_tuple(response[0][1])
2403
            # Ignore missing_keys, we haven't finished inserting yet
2404
        else:
2405
            tokens = []
4476.3.21 by Andrew Bennetts
Clarify some code and comments, and s/1.17/1.18/ in a few places.
2406
        def resume_substream():
4476.3.54 by Andrew Bennetts
Update fallback-to-VFS in remote.py for the inventory-deltas substream.
2407
            # Yield the substream that was interrupted.
4476.3.21 by Andrew Bennetts
Clarify some code and comments, and s/1.17/1.18/ in a few places.
2408
            for record in self._last_substream:
2409
                yield record
2410
            self._last_substream = None
4476.3.15 by Andrew Bennetts
Partially working fallback for pre-1.17 servers.
2411
        def resume_stream():
4476.3.21 by Andrew Bennetts
Clarify some code and comments, and s/1.17/1.18/ in a few places.
2412
            # Finish sending the interrupted substream
4476.3.54 by Andrew Bennetts
Update fallback-to-VFS in remote.py for the inventory-deltas substream.
2413
            yield ('inventory-deltas', resume_substream())
4476.3.21 by Andrew Bennetts
Clarify some code and comments, and s/1.17/1.18/ in a few places.
2414
            # Then simply continue sending the rest of the stream.
4476.3.15 by Andrew Bennetts
Partially working fallback for pre-1.17 servers.
2415
            for substream_kind, substream in self._last_stream:
2416
                yield substream_kind, substream
2417
        return self._insert_real(resume_stream(), src_format, tokens)
2418
2419
    def _stop_stream_if_inventory_delta(self, stream):
4476.3.21 by Andrew Bennetts
Clarify some code and comments, and s/1.17/1.18/ in a few places.
2420
        """Normally this just lets the original stream pass-through unchanged.
2421
4476.3.54 by Andrew Bennetts
Update fallback-to-VFS in remote.py for the inventory-deltas substream.
2422
        However if any 'inventory-deltas' substream occurs it will stop
2423
        streaming, and store the interrupted substream and stream in
2424
        self._last_substream and self._last_stream so that the stream can be
2425
        resumed by _resume_stream_with_vfs.
4476.3.21 by Andrew Bennetts
Clarify some code and comments, and s/1.17/1.18/ in a few places.
2426
        """
5712.3.13 by Jelmer Vernooij
Add Prober.known_formats().
2427
4476.3.15 by Andrew Bennetts
Partially working fallback for pre-1.17 servers.
2428
        stream_iter = iter(stream)
2429
        for substream_kind, substream in stream_iter:
4476.3.54 by Andrew Bennetts
Update fallback-to-VFS in remote.py for the inventory-deltas substream.
2430
            if substream_kind == 'inventory-deltas':
2431
                self._last_substream = substream
2432
                self._last_stream = stream_iter
2433
                return
4476.3.15 by Andrew Bennetts
Partially working fallback for pre-1.17 servers.
2434
            else:
2435
                yield substream_kind, substream
5712.3.13 by Jelmer Vernooij
Add Prober.known_formats().
2436
2437
5815.4.1 by Jelmer Vernooij
Split versionedfile-specific stuff out into VersionedFileRepository.
2438
class RemoteStreamSource(vf_repository.StreamSource):
4060.1.3 by Robert Collins
Implement the separate source component for fetch - repository.StreamSource.
2439
    """Stream data from a remote server."""
2440
4060.1.4 by Robert Collins
Streaming fetch from remote servers.
2441
    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.
2442
        if (self.from_repository._fallback_repositories and
2443
            self.to_format._fetch_order == 'topological'):
2444
            return self._real_stream(self.from_repository, search)
4577.1.1 by Robert Collins
Fix fetching from smart servers where there is a chain of stacked repositories rather than a single stacking point. (Robert Collins, bug #406597)
2445
        sources = []
2446
        seen = set()
2447
        repos = [self.from_repository]
2448
        while repos:
2449
            repo = repos.pop(0)
2450
            if repo in seen:
2451
                continue
2452
            seen.add(repo)
2453
            repos.extend(repo._fallback_repositories)
2454
            sources.append(repo)
2455
        return self.missing_parents_chain(search, sources)
4152.1.2 by Robert Collins
Add streaming from a stacked branch when the sort order is compatible with doing so.
2456
4476.3.16 by Andrew Bennetts
Only make inv deltas against bases we've already sent, and other tweaks.
2457
    def get_stream_for_missing_keys(self, missing_keys):
2458
        self.from_repository._ensure_real()
2459
        real_repo = self.from_repository._real_repository
2460
        real_source = real_repo._get_source(self.to_format)
2461
        return real_source.get_stream_for_missing_keys(missing_keys)
2462
4152.1.2 by Robert Collins
Add streaming from a stacked branch when the sort order is compatible with doing so.
2463
    def _real_stream(self, repo, search):
2464
        """Get a stream for search from repo.
2465
        
2466
        This never called RemoteStreamSource.get_stream, and is a heler
2467
        for RemoteStreamSource._get_stream to allow getting a stream 
2468
        reliably whether fallback back because of old servers or trying
2469
        to stream from a non-RemoteRepository (which the stacked support
2470
        code will do).
2471
        """
2472
        source = repo._get_source(self.to_format)
2473
        if isinstance(source, RemoteStreamSource):
4600.1.1 by Robert Collins
Fix fetching from 2a branches over bzr-v2.
2474
            repo._ensure_real()
2475
            source = repo._real_repository._get_source(self.to_format)
4152.1.2 by Robert Collins
Add streaming from a stacked branch when the sort order is compatible with doing so.
2476
        return source.get_stream(search)
2477
2478
    def _get_stream(self, repo, search):
2479
        """Core worker to get a stream from repo for search.
2480
2481
        This is used by both get_stream and the stacking support logic. It
2482
        deliberately gets a stream for repo which does not need to be
2483
        self.from_repository. In the event that repo is not Remote, or
2484
        cannot do a smart stream, a fallback is made to the generic
2485
        repository._get_stream() interface, via self._real_stream.
2486
2487
        In the event of stacking, streams from _get_stream will not
2488
        contain all the data for search - this is normal (see get_stream).
2489
2490
        :param repo: A repository.
2491
        :param search: A search.
2492
        """
2493
        # Fallbacks may be non-smart
2494
        if not isinstance(repo, RemoteRepository):
2495
            return self._real_stream(repo, search)
4060.1.4 by Robert Collins
Streaming fetch from remote servers.
2496
        client = repo._client
2497
        medium = client._medium
2498
        path = repo.bzrdir._path_for_remote_call(client)
4476.3.29 by Andrew Bennetts
Add Repository.get_stream_1.18 verb.
2499
        search_bytes = repo._serialise_search_result(search)
2500
        args = (path, self.to_format.network_name())
2501
        candidate_verbs = [
4476.3.82 by Andrew Bennetts
Mention another bug fix in NEWS, and update verb name, comments, and NEWS additions for landing on 1.19 rather than 1.18.
2502
            ('Repository.get_stream_1.19', (1, 19)),
4476.3.29 by Andrew Bennetts
Add Repository.get_stream_1.18 verb.
2503
            ('Repository.get_stream', (1, 13))]
5539.2.2 by Andrew Bennetts
Add support for 'everything' fetch spec to RemoteStreamSource.
2504
4476.3.29 by Andrew Bennetts
Add Repository.get_stream_1.18 verb.
2505
        found_verb = False
2506
        for verb, version in candidate_verbs:
2507
            if medium._is_remote_before(version):
2508
                continue
2509
            try:
2510
                response = repo._call_with_body_bytes_expecting_body(
2511
                    verb, args, search_bytes)
2512
            except errors.UnknownSmartMethod:
2513
                medium._remember_remote_is_before(version)
5539.2.14 by Andrew Bennetts
Don't add a new verb; instead just teach the client to fallback if it gets a BadSearch error.
2514
            except errors.UnknownErrorFromSmartServer, e:
2515
                if isinstance(search, graph.EverythingResult):
2516
                    error_verb = e.error_from_smart_server.error_verb
2517
                    if error_verb == 'BadSearch':
5536.3.3 by Andrew Bennetts
Merge lp:bzr.
2518
                        # Pre-2.4 servers don't support this sort of search.
5539.2.14 by Andrew Bennetts
Don't add a new verb; instead just teach the client to fallback if it gets a BadSearch error.
2519
                        # XXX: perhaps falling back to VFS on BadSearch is a
2520
                        # good idea in general?  It might provide a little bit
2521
                        # of protection against client-side bugs.
5536.3.3 by Andrew Bennetts
Merge lp:bzr.
2522
                        medium._remember_remote_is_before((2, 4))
5539.2.14 by Andrew Bennetts
Don't add a new verb; instead just teach the client to fallback if it gets a BadSearch error.
2523
                        break
2524
                raise
4476.3.29 by Andrew Bennetts
Add Repository.get_stream_1.18 verb.
2525
            else:
2526
                response_tuple, response_handler = response
2527
                found_verb = True
2528
                break
2529
        if not found_verb:
4152.1.2 by Robert Collins
Add streaming from a stacked branch when the sort order is compatible with doing so.
2530
            return self._real_stream(repo, search)
4060.1.4 by Robert Collins
Streaming fetch from remote servers.
2531
        if response_tuple[0] != 'ok':
2532
            raise errors.UnexpectedSmartServerResponse(response_tuple)
2533
        byte_stream = response_handler.read_streamed_body()
5195.3.23 by Parth Malwankar
moved progress bar logic to SourceStream.
2534
        src_format, stream = smart_repo._byte_stream_to_stream(byte_stream,
2535
            self._record_counter)
4060.1.4 by Robert Collins
Streaming fetch from remote servers.
2536
        if src_format.network_name() != repo._format.network_name():
2537
            raise AssertionError(
2538
                "Mismatched RemoteRepository and stream src %r, %r" % (
2539
                src_format.network_name(), repo._format.network_name()))
2540
        return stream
2541
4152.1.2 by Robert Collins
Add streaming from a stacked branch when the sort order is compatible with doing so.
2542
    def missing_parents_chain(self, search, sources):
2543
        """Chain multiple streams together to handle stacking.
2544
2545
        :param search: The overall search to satisfy with streams.
2546
        :param sources: A list of Repository objects to query.
2547
        """
4634.61.2 by Andrew Bennetts
Variable rename suggested by Robert.
2548
        self.from_serialiser = self.from_repository._format._serializer
4152.1.2 by Robert Collins
Add streaming from a stacked branch when the sort order is compatible with doing so.
2549
        self.seen_revs = set()
2550
        self.referenced_revs = set()
2551
        # If there are heads in the search, or the key count is > 0, we are not
2552
        # done.
2553
        while not search.is_empty() and len(sources) > 1:
2554
            source = sources.pop(0)
2555
            stream = self._get_stream(source, search)
2556
            for kind, substream in stream:
2557
                if kind != 'revisions':
2558
                    yield kind, substream
2559
                else:
2560
                    yield kind, self.missing_parents_rev_handler(substream)
2561
            search = search.refine(self.seen_revs, self.referenced_revs)
2562
            self.seen_revs = set()
2563
            self.referenced_revs = set()
2564
        if not search.is_empty():
2565
            for kind, stream in self._get_stream(sources[0], search):
2566
                yield kind, stream
2567
2568
    def missing_parents_rev_handler(self, substream):
2569
        for content in substream:
2570
            revision_bytes = content.get_bytes_as('fulltext')
4634.61.2 by Andrew Bennetts
Variable rename suggested by Robert.
2571
            revision = self.from_serialiser.read_revision_from_string(
2572
                revision_bytes)
4152.1.2 by Robert Collins
Add streaming from a stacked branch when the sort order is compatible with doing so.
2573
            self.seen_revs.add(content.key[-1])
2574
            self.referenced_revs.update(revision.parent_ids)
2575
            yield content
2576
4060.1.3 by Robert Collins
Implement the separate source component for fetch - repository.StreamSource.
2577
2018.5.127 by Andrew Bennetts
Fix most of the lockable_files tests for RemoteBranchLockableFiles.
2578
class RemoteBranchLockableFiles(LockableFiles):
2018.5.59 by Robert Collins
Get BranchConfig working somewhat on RemoteBranches (Robert Collins, Vincent Ladeuil).
2579
    """A 'LockableFiles' implementation that talks to a smart server.
3943.8.1 by Marius Kruger
remove all trailing whitespace from bzr source
2580
2018.5.59 by Robert Collins
Get BranchConfig working somewhat on RemoteBranches (Robert Collins, Vincent Ladeuil).
2581
    This is not a public interface class.
2582
    """
2583
2584
    def __init__(self, bzrdir, _client):
2585
        self.bzrdir = bzrdir
2586
        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.
2587
        self._need_find_modes = True
2018.5.133 by Andrew Bennetts
All TestLockableFiles_RemoteLockDir tests passing.
2588
        LockableFiles.__init__(
2018.5.163 by Andrew Bennetts
Deal with various review comments from Robert.
2589
            self, bzrdir.get_branch_transport(None),
2018.5.133 by Andrew Bennetts
All TestLockableFiles_RemoteLockDir tests passing.
2590
            'lock', lockdir.LockDir)
2018.5.59 by Robert Collins
Get BranchConfig working somewhat on RemoteBranches (Robert Collins, Vincent Ladeuil).
2591
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.
2592
    def _find_modes(self):
2593
        # RemoteBranches don't let the client set the mode of control files.
2594
        self._dir_mode = None
2595
        self._file_mode = None
2596
2018.5.59 by Robert Collins
Get BranchConfig working somewhat on RemoteBranches (Robert Collins, Vincent Ladeuil).
2597
1752.2.31 by Martin Pool
[broken] some support for write operations over hpss
2598
class RemoteBranchFormat(branch.BranchFormat):
2599
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.
2600
    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.
2601
        super(RemoteBranchFormat, self).__init__()
2602
        self._matchingbzrdir = RemoteBzrDirFormat()
2603
        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.
2604
        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.
2605
        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.
2606
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.
2607
    def __eq__(self, other):
3943.8.1 by Marius Kruger
remove all trailing whitespace from bzr source
2608
        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.
2609
            self.__dict__ == other.__dict__)
2610
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.
2611
    def _ensure_real(self):
2612
        if self._custom_format is None:
2613
            self._custom_format = branch.network_format_registry.get(
2614
                self._network_name)
2615
2018.5.60 by Robert Collins
More missing methods from RemoteBranch and RemoteRepository to let 'info' get further.
2616
    def get_format_description(self):
4792.1.1 by Andrew Bennetts
Show real branch/repo format description in 'info -v' over HPSS.
2617
        self._ensure_real()
2618
        return 'Remote: ' + self._custom_format.get_format_description()
2018.5.60 by Robert Collins
More missing methods from RemoteBranch and RemoteRepository to let 'info' get further.
2619
4032.3.1 by Robert Collins
Add a BranchFormat.network_name() method as preparation for creating branches via RPC calls.
2620
    def network_name(self):
2621
        return self._network_name
2622
5051.3.10 by Jelmer Vernooij
Pass colocated branch name around in more places.
2623
    def open(self, a_bzrdir, name=None, ignore_fallbacks=False):
2624
        return a_bzrdir.open_branch(name=name, 
2625
            ignore_fallbacks=ignore_fallbacks)
1752.2.52 by Andrew Bennetts
Flesh out more Remote* methods needed to open and initialise remote branches/trees/repositories.
2626
6123.9.12 by Jelmer Vernooij
Add append_revisions_only argument to BranchFormat.initialize.
2627
    def _vfs_initialize(self, a_bzrdir, name, append_revisions_only):
4032.3.2 by Robert Collins
Create and use a RPC call to create branches on bzr servers rather than using VFS calls.
2628
        # Initialisation when using a local bzrdir object, or a non-vfs init
2629
        # method is not available on the server.
2630
        # self._custom_format is always set - the start of initialize ensures
2631
        # that.
2632
        if isinstance(a_bzrdir, RemoteBzrDir):
2633
            a_bzrdir._ensure_real()
5051.3.10 by Jelmer Vernooij
Pass colocated branch name around in more places.
2634
            result = self._custom_format.initialize(a_bzrdir._real_bzrdir,
6123.9.12 by Jelmer Vernooij
Add append_revisions_only argument to BranchFormat.initialize.
2635
                name, append_revisions_only=append_revisions_only)
4032.3.2 by Robert Collins
Create and use a RPC call to create branches on bzr servers rather than using VFS calls.
2636
        else:
2637
            # We assume the bzrdir is parameterised; it may not be.
6123.9.12 by Jelmer Vernooij
Add append_revisions_only argument to BranchFormat.initialize.
2638
            result = self._custom_format.initialize(a_bzrdir, name,
2639
                append_revisions_only=append_revisions_only)
4032.3.2 by Robert Collins
Create and use a RPC call to create branches on bzr servers rather than using VFS calls.
2640
        if (isinstance(a_bzrdir, RemoteBzrDir) and
2641
            not isinstance(result, RemoteBranch)):
5051.3.10 by Jelmer Vernooij
Pass colocated branch name around in more places.
2642
            result = RemoteBranch(a_bzrdir, a_bzrdir.find_repository(), result,
2643
                                  name=name)
4032.3.2 by Robert Collins
Create and use a RPC call to create branches on bzr servers rather than using VFS calls.
2644
        return result
2645
6123.9.12 by Jelmer Vernooij
Add append_revisions_only argument to BranchFormat.initialize.
2646
    def initialize(self, a_bzrdir, name=None, repository=None,
2647
                   append_revisions_only=None):
4032.3.2 by Robert Collins
Create and use a RPC call to create branches on bzr servers rather than using VFS calls.
2648
        # 1) get the network name to use.
2649
        if self._custom_format:
2650
            network_name = self._custom_format.network_name()
2651
        else:
2652
            # Select the current bzrlib default and ask for that.
5712.3.13 by Jelmer Vernooij
Add Prober.known_formats().
2653
            reference_bzrdir_format = _mod_bzrdir.format_registry.get('default')()
4032.3.2 by Robert Collins
Create and use a RPC call to create branches on bzr servers rather than using VFS calls.
2654
            reference_format = reference_bzrdir_format.get_branch_format()
2655
            self._custom_format = reference_format
2656
            network_name = reference_format.network_name()
2657
        # 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.
2658
        if not isinstance(a_bzrdir, RemoteBzrDir):
6123.9.12 by Jelmer Vernooij
Add append_revisions_only argument to BranchFormat.initialize.
2659
            return self._vfs_initialize(a_bzrdir, name=name,
2660
                append_revisions_only=append_revisions_only)
4032.3.2 by Robert Collins
Create and use a RPC call to create branches on bzr servers rather than using VFS calls.
2661
        medium = a_bzrdir._client._medium
2662
        if medium._is_remote_before((1, 13)):
6123.9.12 by Jelmer Vernooij
Add append_revisions_only argument to BranchFormat.initialize.
2663
            return self._vfs_initialize(a_bzrdir, name=name,
2664
                append_revisions_only=append_revisions_only)
4032.3.2 by Robert Collins
Create and use a RPC call to create branches on bzr servers rather than using VFS calls.
2665
        # Creating on a remote bzr dir.
2666
        # 2) try direct creation via RPC
2667
        path = a_bzrdir._path_for_remote_call(a_bzrdir._client)
5051.3.10 by Jelmer Vernooij
Pass colocated branch name around in more places.
2668
        if name is not None:
5051.3.11 by Jelmer Vernooij
add XXX for creating remote colocated branches.
2669
            # XXX JRV20100304: Support creating colocated branches
5051.3.10 by Jelmer Vernooij
Pass colocated branch name around in more places.
2670
            raise errors.NoColocatedBranchSupport(self)
4032.3.2 by Robert Collins
Create and use a RPC call to create branches on bzr servers rather than using VFS calls.
2671
        verb = 'BzrDir.create_branch'
2672
        try:
2673
            response = a_bzrdir._call(verb, path, network_name)
2674
        except errors.UnknownSmartMethod:
2675
            # Fallback - use vfs methods
4094.1.1 by Andrew Bennetts
Add some medium._remember_is_before((1, 13)) calls.
2676
            medium._remember_remote_is_before((1, 13))
6123.9.12 by Jelmer Vernooij
Add append_revisions_only argument to BranchFormat.initialize.
2677
            return self._vfs_initialize(a_bzrdir, name=name,
2678
                    append_revisions_only=append_revisions_only)
4032.3.2 by Robert Collins
Create and use a RPC call to create branches on bzr servers rather than using VFS calls.
2679
        if response[0] != 'ok':
2680
            raise errors.UnexpectedSmartServerResponse(response)
2681
        # 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.
2682
        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.
2683
        repo_format = response_tuple_to_repo_format(response[3:])
5536.1.1 by Andrew Bennetts
Avoid reopening (and relocking) the same branches/repositories in ControlDir.sprout. Still a few rough edges, but the tests I've run are passing.
2684
        repo_path = response[2]
2685
        if repository is not None:
5609.21.1 by Andrew Bennetts
Possible fix for #726584, plus drive-by docstring fix.
2686
            remote_repo_url = urlutils.join(a_bzrdir.user_url, repo_path)
5535.3.7 by Andrew Bennetts
Allow for trailing-slash differences between local url path vs. remote url path for remote branch's repository.
2687
            url_diff = urlutils.relative_url(repository.user_url,
2688
                    remote_repo_url)
2689
            if url_diff != '.':
5536.1.1 by Andrew Bennetts
Avoid reopening (and relocking) the same branches/repositories in ControlDir.sprout. Still a few rough edges, but the tests I've run are passing.
2690
                raise AssertionError(
5536.1.10 by Andrew Bennetts
Give more helpful message in AssertionErrors, just in case.
2691
                    'repository.user_url %r does not match URL from server '
2692
                    'response (%r + %r)'
5609.21.1 by Andrew Bennetts
Possible fix for #726584, plus drive-by docstring fix.
2693
                    % (repository.user_url, a_bzrdir.user_url, repo_path))
5536.1.1 by Andrew Bennetts
Avoid reopening (and relocking) the same branches/repositories in ControlDir.sprout. Still a few rough edges, but the tests I've run are passing.
2694
            remote_repo = repository
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.
2695
        else:
5536.1.1 by Andrew Bennetts
Avoid reopening (and relocking) the same branches/repositories in ControlDir.sprout. Still a few rough edges, but the tests I've run are passing.
2696
            if repo_path == '':
2697
                repo_bzrdir = a_bzrdir
2698
            else:
2699
                repo_bzrdir = RemoteBzrDir(
2700
                    a_bzrdir.root_transport.clone(repo_path), a_bzrdir._format,
2701
                    a_bzrdir._client)
2702
            remote_repo = RemoteRepository(repo_bzrdir, repo_format)
4032.3.2 by Robert Collins
Create and use a RPC call to create branches on bzr servers rather than using VFS calls.
2703
        remote_branch = RemoteBranch(a_bzrdir, remote_repo,
5051.3.10 by Jelmer Vernooij
Pass colocated branch name around in more places.
2704
            format=format, setup_stacking=False, name=name)
6123.9.12 by Jelmer Vernooij
Add append_revisions_only argument to BranchFormat.initialize.
2705
        if append_revisions_only:
2706
            remote_branch.set_append_revisions_only(append_revisions_only)
4044.1.4 by Robert Collins
Remove a wasted round trip determining the revno and revid of a newly created branch.
2707
        # XXX: We know this is a new branch, so it must have revno 0, revid
2708
        # NULL_REVISION. Creating the branch locked would make this be unable
2709
        # to be wrong; here its simply very unlikely to be wrong. RBC 20090225
2710
        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.
2711
        return remote_branch
1752.2.31 by Martin Pool
[broken] some support for write operations over hpss
2712
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.
2713
    def make_tags(self, branch):
2714
        self._ensure_real()
2715
        return self._custom_format.make_tags(branch)
2716
2696.3.6 by Martin Pool
Mark RemoteBranch as (possibly) supporting tags
2717
    def supports_tags(self):
2718
        # Remote branches might support tags, but we won't know until we
2719
        # 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.
2720
        self._ensure_real()
2721
        return self._custom_format.supports_tags()
2696.3.6 by Martin Pool
Mark RemoteBranch as (possibly) supporting tags
2722
4103.2.2 by Andrew Bennetts
Fix RemoteBranchFormat.supports_stacking()
2723
    def supports_stacking(self):
2724
        self._ensure_real()
2725
        return self._custom_format.supports_stacking()
2726
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.
2727
    def supports_set_append_revisions_only(self):
2728
        self._ensure_real()
2729
        return self._custom_format.supports_set_append_revisions_only()
2730
5672.1.7 by Andrew Bennetts
Use a more explicit method name.
2731
    def _use_default_local_heads_to_fetch(self):
5672.1.4 by Andrew Bennetts
Fix final bzr-loom test by adding RemoteBranch.heads_to_fetch that can ask the remote branch for the heads to fetch (but uses the cheaper default logic if it knows the remote format has an identical heads_to_fetch as Branch.heads_to_fetch).
2732
        # If the branch format is a metadir format *and* its heads_to_fetch
2733
        # implementation is not overridden vs the base class, we can use the
2734
        # base class logic rather than use the heads_to_fetch RPC.  This is
5672.1.5 by Andrew Bennetts
Add some tests for RemoteBranch.heads_to_fetch, and add release-note.
2735
        # usually cheaper in terms of net round trips, as the last-revision and
5672.1.4 by Andrew Bennetts
Fix final bzr-loom test by adding RemoteBranch.heads_to_fetch that can ask the remote branch for the heads to fetch (but uses the cheaper default logic if it knows the remote format has an identical heads_to_fetch as Branch.heads_to_fetch).
2736
        # tags info fetched is cached and would be fetched anyway.
2737
        self._ensure_real()
2738
        if isinstance(self._custom_format, branch.BranchFormatMetadir):
2739
            branch_class = self._custom_format._branch_class()
2740
            heads_to_fetch_impl = branch_class.heads_to_fetch.im_func
2741
            if heads_to_fetch_impl is branch.Branch.heads_to_fetch.im_func:
2742
                return True
2743
        return False
1752.2.31 by Martin Pool
[broken] some support for write operations over hpss
2744
6270.1.4 by Jelmer Vernooij
Add Branch.get_config_stack / BzrDir.get_config_stack.
2745
6270.1.6 by Jelmer Vernooij
Provide RemoteControlStore and RemoteBranchStore.
2746
class RemoteBranchStore(config.IniFileStore):
2747
    """Branch store which attempts to use HPSS calls to retrieve branch store.
2748
2749
    Note that this is specific to bzr-based formats.
2750
    """
2751
2752
    def __init__(self, branch):
2753
        super(RemoteBranchStore, self).__init__()
2754
        self.branch = branch
6270.1.14 by Jelmer Vernooij
Set RemoteBranchStore.id.
2755
        self.id = "branch"
6270.1.7 by Jelmer Vernooij
Use _ensure_real.
2756
        self._real_store = None
6270.1.6 by Jelmer Vernooij
Provide RemoteControlStore and RemoteBranchStore.
2757
2758
    def lock_write(self, token=None):
2759
        return self.branch.lock_write(token)
2760
2761
    def unlock(self):
2762
        return self.branch.unlock()
2763
2764
    @needs_write_lock
2765
    def save(self):
2766
        # We need to be able to override the undecorated implementation
2767
        self.save_without_locking()
2768
2769
    def save_without_locking(self):
2770
        super(RemoteBranchStore, self).save()
2771
2772
    def external_url(self):
6270.1.15 by Jelmer Vernooij
Implement sensible .external_url().
2773
        return self.branch.user_url
6270.1.6 by Jelmer Vernooij
Provide RemoteControlStore and RemoteBranchStore.
2774
2775
    def _load_content(self):
2776
        path = self.branch._remote_path()
2777
        try:
6270.1.10 by Jelmer Vernooij
Fix testing Branch.set_config_file.
2778
            response, handler = self.branch._call_expecting_body(
6270.1.6 by Jelmer Vernooij
Provide RemoteControlStore and RemoteBranchStore.
2779
                'Branch.get_config_file', path)
2780
        except errors.UnknownSmartMethod:
6270.1.7 by Jelmer Vernooij
Use _ensure_real.
2781
            self._ensure_real()
2782
            return self._real_store._load_content()
6270.1.6 by Jelmer Vernooij
Provide RemoteControlStore and RemoteBranchStore.
2783
        if len(response) and response[0] != 'ok':
2784
            raise errors.UnexpectedSmartServerResponse(response)
2785
        return handler.read_body_bytes()
2786
2787
    def _save_content(self, content):
6270.1.7 by Jelmer Vernooij
Use _ensure_real.
2788
        path = self.branch._remote_path()
2789
        try:
6270.1.18 by Jelmer Vernooij
Fix a test.
2790
            response, handler = self.branch._call_with_body_bytes_expecting_body(
6270.1.17 by Jelmer Vernooij
s/set_config_file/put_config_file.
2791
                'Branch.put_config_file', (path,
6270.1.10 by Jelmer Vernooij
Fix testing Branch.set_config_file.
2792
                    self.branch._lock_token, self.branch._repo_lock_token),
2793
                content)
6270.1.7 by Jelmer Vernooij
Use _ensure_real.
2794
        except errors.UnknownSmartMethod:
2795
            self._ensure_real()
2796
            return self._real_store._save_content(content)
6270.1.18 by Jelmer Vernooij
Fix a test.
2797
        handler.cancel_read_body()
6270.1.16 by Jelmer Vernooij
Expect 'ok' response from set_config_file.
2798
        if response != ('ok', ):
6270.1.7 by Jelmer Vernooij
Use _ensure_real.
2799
            raise errors.UnexpectedSmartServerResponse(response)
2800
2801
    def _ensure_real(self):
2802
        self.branch._ensure_real()
6270.1.8 by Jelmer Vernooij
Fix RemoteControlStore.
2803
        if self._real_store is None:
2804
            self._real_store = config.BranchStore(self.branch)
6270.1.6 by Jelmer Vernooij
Provide RemoteControlStore and RemoteBranchStore.
2805
2806
4731.1.2 by Andrew Bennetts
Refactor to reduce duplication.
2807
class RemoteBranch(branch.Branch, _RpcHelper, lock._RelockDebugMixin):
1752.2.31 by Martin Pool
[broken] some support for write operations over hpss
2808
    """Branch stored on a server accessed by HPSS RPC.
2809
2810
    At the moment most operations are mapped down to simple file operations.
2811
    """
1752.2.30 by Martin Pool
Start adding a RemoteBzrDir, etc
2812
2018.5.51 by Wouter van Heyst
Test and implement RemoteBranch.last_revision_info()
2813
    def __init__(self, remote_bzrdir, remote_repository, real_branch=None,
6305.3.6 by Jelmer Vernooij
Pass possible_transports along for remote branches.
2814
        _client=None, format=None, setup_stacking=True, name=None,
2815
        possible_transports=None):
2018.5.34 by Robert Collins
Get test_remote.BasicRemoteObjectTests.test_open_remote_branch passing by implementing a remote method BzrDir.find_repository.
2816
        """Create a RemoteBranch instance.
2817
2818
        :param real_branch: An optional local implementation of the branch
2819
            format, usually accessing the data via the VFS.
2018.5.51 by Wouter van Heyst
Test and implement RemoteBranch.last_revision_info()
2820
        :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.
2821
        :param format: A RemoteBranchFormat object, None to create one
2822
            automatically. If supplied it should have a network_name already
2823
            supplied.
2824
        :param setup_stacking: If True make an RPC call to determine the
2825
            stacked (or not) status of the branch. If False assume the branch
2826
            is not stacked.
5051.3.10 by Jelmer Vernooij
Pass colocated branch name around in more places.
2827
        :param name: Colocated branch name
2018.5.34 by Robert Collins
Get test_remote.BasicRemoteObjectTests.test_open_remote_branch passing by implementing a remote method BzrDir.find_repository.
2828
        """
2018.5.163 by Andrew Bennetts
Deal with various review comments from Robert.
2829
        # We intentionally don't call the parent class's __init__, because it
2830
        # will try to assign to self.tags, which is a property in this subclass.
2831
        # 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.
2832
        self.bzrdir = remote_bzrdir
2018.5.51 by Wouter van Heyst
Test and implement RemoteBranch.last_revision_info()
2833
        if _client is not None:
2834
            self._client = _client
2835
        else:
3313.2.1 by Andrew Bennetts
Change _SmartClient's API to accept a medium and a base, rather than a _SharedConnection.
2836
            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.
2837
        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.
2838
        if real_branch is not None:
2839
            self._real_branch = real_branch
2018.5.79 by Andrew Bennetts
Implement RemoteBranch.lock_write/unlock as smart operations.
2840
            # Give the remote repository the matching real repo.
2018.5.97 by Andrew Bennetts
Fix more tests.
2841
            real_repo = self._real_branch.repository
2842
            if isinstance(real_repo, RemoteRepository):
2843
                real_repo._ensure_real()
2844
                real_repo = real_repo._real_repository
2845
            self.repository._set_real_repository(real_repo)
2018.5.79 by Andrew Bennetts
Implement RemoteBranch.lock_write/unlock as smart operations.
2846
            # Give the branch the remote repository to let fast-pathing happen.
2847
            self._real_branch.repository = self.repository
2018.5.70 by Robert Collins
Only try to get real repositories when an operation requires them.
2848
        else:
2849
            self._real_branch = None
4031.3.3 by Matt Nordhoff
Review tweaks from Ben Finney
2850
        # 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.
2851
        self._clear_cached_state()
5158.6.9 by Martin Pool
Simplify various code to use user_url
2852
        # TODO: deprecate self.base in favor of user_url
2853
        self.base = self.bzrdir.user_url
5051.3.10 by Jelmer Vernooij
Pass colocated branch name around in more places.
2854
        self._name = name
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.
2855
        self._control_files = None
2018.5.79 by Andrew Bennetts
Implement RemoteBranch.lock_write/unlock as smart operations.
2856
        self._lock_mode = None
2857
        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.
2858
        self._repo_lock_token = None
2018.5.79 by Andrew Bennetts
Implement RemoteBranch.lock_write/unlock as smart operations.
2859
        self._lock_count = 0
2860
        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.
2861
        # Setup a format: note that we cannot call _ensure_real until all the
2862
        # attributes above are set: This code cannot be moved higher up in this
2863
        # function.
2864
        if format is None:
2865
            self._format = RemoteBranchFormat()
2866
            if real_branch is not None:
2867
                self._format._network_name = \
2868
                    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.
2869
        else:
4032.3.2 by Robert Collins
Create and use a RPC call to create branches on bzr servers rather than using VFS calls.
2870
            self._format = format
4600.2.1 by Robert Collins
Make RemoteBranch honour ignore_fallbacks when _ensure_real is triggered.
2871
        # when we do _ensure_real we may need to pass ignore_fallbacks to the
2872
        # branch.open_branch method.
2873
        self._real_ignore_fallbacks = not setup_stacking
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.
2874
        if not self._format._network_name:
2875
            # Did not get from open_branchV2 - old server.
2876
            self._ensure_real()
2877
            self._format._network_name = \
2878
                self._real_branch._format.network_name()
2879
        self.tags = self._format.make_tags(self)
3681.1.2 by Robert Collins
Adjust for trunk.
2880
        # 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)
2881
        hooks = branch.Branch.hooks['open']
2882
        for hook in hooks:
2883
            hook(self)
4419.1.3 by Andrew Bennetts
Quick fix by using self._ensure_real.
2884
        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.
2885
        if setup_stacking:
6305.3.6 by Jelmer Vernooij
Pass possible_transports along for remote branches.
2886
            self._setup_stacking(possible_transports)
3691.2.1 by Martin Pool
RemoteBranch must configure stacking into the repository
2887
6305.3.6 by Jelmer Vernooij
Pass possible_transports along for remote branches.
2888
    def _setup_stacking(self, possible_transports):
3691.2.1 by Martin Pool
RemoteBranch must configure stacking into the repository
2889
        # 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
2890
        # the vfs branch.
3691.2.1 by Martin Pool
RemoteBranch must configure stacking into the repository
2891
        try:
2892
            fallback_url = self.get_stacked_on_url()
2893
        except (errors.NotStacked, errors.UnstackableBranchFormat,
2894
            errors.UnstackableRepositoryFormat), e:
3691.2.7 by Martin Pool
FakeClient can know what calls to expect
2895
            return
4419.1.3 by Andrew Bennetts
Quick fix by using self._ensure_real.
2896
        self._is_stacked = True
6305.3.6 by Jelmer Vernooij
Pass possible_transports along for remote branches.
2897
        if possible_transports is None:
2898
            possible_transports = []
2899
        else:
2900
            possible_transports = list(possible_transports)
2901
        possible_transports.append(self.bzrdir.root_transport)
6305.3.3 by Jelmer Vernooij
Fix use of possible_transports.
2902
        self._activate_fallback_location(fallback_url,
6305.3.6 by Jelmer Vernooij
Pass possible_transports along for remote branches.
2903
            possible_transports=possible_transports)
1752.2.64 by Andrew Bennetts
Improve how RemoteBzrDir.open_branch works to handle references and not double-open repositories.
2904
4226.1.5 by Robert Collins
Reinstate the use of the Branch.get_config_file verb.
2905
    def _get_config(self):
2906
        return RemoteBranchConfig(self)
2907
6270.1.19 by Jelmer Vernooij
Some changes discussed with vila on IRC.
2908
    def _get_config_store(self):
2909
        return RemoteBranchStore(self)
6270.1.4 by Jelmer Vernooij
Add Branch.get_config_stack / BzrDir.get_config_stack.
2910
3407.2.17 by Martin Pool
better name: _get_real_transport
2911
    def _get_real_transport(self):
3407.2.16 by Martin Pool
Remove RemoteBranch reliance on control_files._transport
2912
        # if we try vfs access, return the real branch's vfs transport
2913
        self._ensure_real()
2914
        return self._real_branch._transport
2915
3407.2.17 by Martin Pool
better name: _get_real_transport
2916
    _transport = property(_get_real_transport)
3407.2.16 by Martin Pool
Remove RemoteBranch reliance on control_files._transport
2917
2477.1.1 by Martin Pool
Add RemoteBranch repr
2918
    def __str__(self):
2919
        return "%s(%s)" % (self.__class__.__name__, self.base)
2920
2921
    __repr__ = __str__
2922
2018.5.70 by Robert Collins
Only try to get real repositories when an operation requires them.
2923
    def _ensure_real(self):
2924
        """Ensure that there is a _real_branch set.
2925
2018.5.163 by Andrew Bennetts
Deal with various review comments from Robert.
2926
        Used before calls to self._real_branch.
2018.5.70 by Robert Collins
Only try to get real repositories when an operation requires them.
2927
        """
3407.2.16 by Martin Pool
Remove RemoteBranch reliance on control_files._transport
2928
        if self._real_branch is None:
3376.2.4 by Martin Pool
Remove every assert statement from bzrlib!
2929
            if not vfs.vfs_enabled():
2930
                raise AssertionError('smart server vfs must be enabled '
2931
                    'to use vfs implementation')
2018.5.70 by Robert Collins
Only try to get real repositories when an operation requires them.
2932
            self.bzrdir._ensure_real()
4600.2.1 by Robert Collins
Make RemoteBranch honour ignore_fallbacks when _ensure_real is triggered.
2933
            self._real_branch = self.bzrdir._real_bzrdir.open_branch(
5051.3.10 by Jelmer Vernooij
Pass colocated branch name around in more places.
2934
                ignore_fallbacks=self._real_ignore_fallbacks, name=self._name)
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.
2935
            if self.repository._real_repository is None:
2936
                # Give the remote repository the matching real repo.
2937
                real_repo = self._real_branch.repository
2938
                if isinstance(real_repo, RemoteRepository):
2939
                    real_repo._ensure_real()
2940
                    real_repo = real_repo._real_repository
2941
                self.repository._set_real_repository(real_repo)
2942
            # Give the real branch the remote repository to let fast-pathing
2943
            # happen.
2018.5.70 by Robert Collins
Only try to get real repositories when an operation requires them.
2944
            self._real_branch.repository = self.repository
2018.14.1 by Andrew Bennetts
Update to current hpss branch? Fix lots of test failures.
2945
            if self._lock_mode == 'r':
2946
                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.
2947
            elif self._lock_mode == 'w':
2948
                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.
2949
3533.3.1 by Andrew Bennetts
Remove duplication of error translation in bzrlib/remote.py.
2950
    def _translate_error(self, err, **context):
2951
        self.repository._translate_error(err, branch=self, **context)
2952
3441.5.1 by Andrew Bennetts
Avoid necessarily calling get_parent_map when pushing.
2953
    def _clear_cached_state(self):
2954
        super(RemoteBranch, self)._clear_cached_state()
3441.5.5 by Andrew Bennetts
Some small tweaks and comments.
2955
        if self._real_branch is not None:
2956
            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.
2957
2958
    def _clear_cached_state_of_remote_branch_only(self):
2959
        """Like _clear_cached_state, but doesn't clear the cache of
2960
        self._real_branch.
2961
2962
        This is useful when falling back to calling a method of
2963
        self._real_branch that changes state.  In that case the underlying
2964
        branch changes, so we need to invalidate this RemoteBranch's cache of
2965
        it.  However, there's no need to invalidate the _real_branch's cache
2966
        too, in fact doing so might harm performance.
2967
        """
2968
        super(RemoteBranch, self)._clear_cached_state()
3943.8.1 by Marius Kruger
remove all trailing whitespace from bzr source
2969
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.
2970
    @property
2971
    def control_files(self):
2972
        # Defer actually creating RemoteBranchLockableFiles until its needed,
2973
        # because it triggers an _ensure_real that we otherwise might not need.
2974
        if self._control_files is None:
2975
            self._control_files = RemoteBranchLockableFiles(
2976
                self.bzrdir, self._client)
2977
        return self._control_files
2978
6127.1.9 by Jelmer Vernooij
Add lightweight option to _get_checkout_format().
2979
    def _get_checkout_format(self, lightweight=False):
2018.5.166 by Andrew Bennetts
Small changes in response to Aaron's review.
2980
        self._ensure_real()
6127.1.9 by Jelmer Vernooij
Add lightweight option to _get_checkout_format().
2981
        if lightweight:
2982
            format = RemoteBzrDirFormat()
2983
            self.bzrdir._format._supply_sub_formats_to(format)
2984
            format.workingtree_format = self._real_branch._get_checkout_format(
2985
                lightweight=lightweight).workingtree_format
2986
            return format
2987
        else:
2988
            return self._real_branch._get_checkout_format(lightweight=False)
2018.5.166 by Andrew Bennetts
Small changes in response to Aaron's review.
2989
2018.5.60 by Robert Collins
More missing methods from RemoteBranch and RemoteRepository to let 'info' get further.
2990
    def get_physical_lock_status(self):
2991
        """See Branch.get_physical_lock_status()."""
6280.6.1 by Jelmer Vernooij
Implement remote side of {Branch,Repository}.get_physical_lock_status.
2992
        try:
2993
            response = self._client.call('Branch.get_physical_lock_status',
2994
                self._remote_path())
2995
        except errors.UnknownSmartMethod:
2996
            self._ensure_real()
2997
            return self._real_branch.get_physical_lock_status()
2998
        if response[0] not in ('yes', 'no'):
2999
            raise errors.UnexpectedSmartServerResponse(response)
3000
        return (response[0] == 'yes')
2018.5.60 by Robert Collins
More missing methods from RemoteBranch and RemoteRepository to let 'info' get further.
3001
3537.3.1 by Martin Pool
Rename branch.get_stacked_on to get_stacked_on_url
3002
    def get_stacked_on_url(self):
3221.11.2 by Robert Collins
Create basic stackable branch facility.
3003
        """Get the URL this branch is stacked against.
3004
3005
        :raises NotStacked: If the branch is not stacked.
3006
        :raises UnstackableBranchFormat: If the branch does not support
3007
            stacking.
3008
        :raises UnstackableRepositoryFormat: If the repository does not support
3009
            stacking.
3010
        """
3691.2.12 by Martin Pool
Add test for coping without Branch.get_stacked_on_url
3011
        try:
3786.2.3 by Andrew Bennetts
Remove duplicated 'call & translate errors' code in bzrlib.remote.
3012
            # there may not be a repository yet, so we can't use
3013
            # 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
3014
            response = self._client.call('Branch.get_stacked_on_url',
3015
                self._remote_path())
3016
        except errors.ErrorFromSmartServer, err:
3017
            # there may not be a repository yet, so we can't call through
3018
            # its _translate_error
3019
            _translate_error(err, branch=self)
3020
        except errors.UnknownSmartMethod, err:
3021
            self._ensure_real()
3022
            return self._real_branch.get_stacked_on_url()
3786.2.3 by Andrew Bennetts
Remove duplicated 'call & translate errors' code in bzrlib.remote.
3023
        if response[0] != 'ok':
3024
            raise errors.UnexpectedSmartServerResponse(response)
3025
        return response[1]
3221.11.2 by Robert Collins
Create basic stackable branch facility.
3026
4419.1.3 by Andrew Bennetts
Quick fix by using self._ensure_real.
3027
    def set_stacked_on_url(self, url):
3028
        branch.Branch.set_stacked_on_url(self, url)
3029
        if not url:
3030
            self._is_stacked = False
3031
        else:
3032
            self._is_stacked = True
5712.3.13 by Jelmer Vernooij
Add Prober.known_formats().
3033
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.
3034
    def _vfs_get_tags_bytes(self):
3035
        self._ensure_real()
3036
        return self._real_branch._get_tags_bytes()
3037
5535.2.1 by Andrew Bennetts
Cache a branch's tags during a read-lock.
3038
    @needs_read_lock
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.
3039
    def _get_tags_bytes(self):
5535.2.1 by Andrew Bennetts
Cache a branch's tags during a read-lock.
3040
        if self._tags_bytes is None:
3041
            self._tags_bytes = self._get_tags_bytes_via_hpss()
3042
        return self._tags_bytes
3043
3044
    def _get_tags_bytes_via_hpss(self):
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.
3045
        medium = self._client._medium
3046
        if medium._is_remote_before((1, 13)):
3047
            return self._vfs_get_tags_bytes()
3048
        try:
3049
            response = self._call('Branch.get_tags_bytes', self._remote_path())
3050
        except errors.UnknownSmartMethod:
4094.1.1 by Andrew Bennetts
Add some medium._remember_is_before((1, 13)) calls.
3051
            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.
3052
            return self._vfs_get_tags_bytes()
3053
        return response[0]
3054
4556.2.10 by Andrew Bennetts
Fix trivial bug in _vfs_set_tags_bytes.
3055
    def _vfs_set_tags_bytes(self, bytes):
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.
3056
        self._ensure_real()
4556.2.10 by Andrew Bennetts
Fix trivial bug in _vfs_set_tags_bytes.
3057
        return self._real_branch._set_tags_bytes(bytes)
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.
3058
3059
    def _set_tags_bytes(self, bytes):
5535.2.3 by Andrew Bennetts
Reset cached tags when mutating tags.
3060
        if self.is_locked():
3061
            self._tags_bytes = bytes
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.
3062
        medium = self._client._medium
3063
        if medium._is_remote_before((1, 18)):
3064
            self._vfs_set_tags_bytes(bytes)
4634.36.1 by Andrew Bennetts
Fix trivial bug in RemoteBranch._set_tags_bytes, and add some unit tests for it.
3065
            return
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.
3066
        try:
3067
            args = (
3068
                self._remote_path(), self._lock_token, self._repo_lock_token)
3069
            response = self._call_with_body_bytes(
3070
                'Branch.set_tags_bytes', args, bytes)
3071
        except errors.UnknownSmartMethod:
3072
            medium._remember_remote_is_before((1, 18))
3073
            self._vfs_set_tags_bytes(bytes)
3074
1752.2.31 by Martin Pool
[broken] some support for write operations over hpss
3075
    def lock_read(self):
5200.3.3 by Robert Collins
Lock methods on ``Tree``, ``Branch`` and ``Repository`` are now
3076
        """Lock the branch for read operations.
3077
5200.3.6 by Robert Collins
Make all lock methods return Result objects, rather than lock_read returning self, as per John's review.
3078
        :return: A bzrlib.lock.LogicalLockResult.
5200.3.3 by Robert Collins
Lock methods on ``Tree``, ``Branch`` and ``Repository`` are now
3079
        """
3692.1.1 by Andrew Bennetts
Make RemoteBranch.lock_write lock the repository too.
3080
        self.repository.lock_read()
2018.14.1 by Andrew Bennetts
Update to current hpss branch? Fix lots of test failures.
3081
        if not self._lock_mode:
4731.1.2 by Andrew Bennetts
Refactor to reduce duplication.
3082
            self._note_lock('r')
2018.14.1 by Andrew Bennetts
Update to current hpss branch? Fix lots of test failures.
3083
            self._lock_mode = 'r'
3084
            self._lock_count = 1
3085
            if self._real_branch is not None:
3086
                self._real_branch.lock_read()
3087
        else:
3088
            self._lock_count += 1
5200.3.6 by Robert Collins
Make all lock methods return Result objects, rather than lock_read returning self, as per John's review.
3089
        return lock.LogicalLockResult(self.unlock)
1752.2.52 by Andrew Bennetts
Flesh out more Remote* methods needed to open and initialise remote branches/trees/repositories.
3090
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).
3091
    def _remote_lock_write(self, token):
3092
        if token is None:
2018.5.79 by Andrew Bennetts
Implement RemoteBranch.lock_write/unlock as smart operations.
3093
            branch_token = repo_token = ''
3094
        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).
3095
            branch_token = token
5200.3.3 by Robert Collins
Lock methods on ``Tree``, ``Branch`` and ``Repository`` are now
3096
            repo_token = self.repository.lock_write().repository_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).
3097
            self.repository.unlock()
3786.2.3 by Andrew Bennetts
Remove duplicated 'call & translate errors' code in bzrlib.remote.
3098
        err_context = {'token': token}
5284.6.1 by Parth Malwankar
initial implementation for better LockContention message.
3099
        try:
3100
            response = self._call(
3101
                'Branch.lock_write', self._remote_path(), branch_token,
3102
                repo_token or '', **err_context)
3103
        except errors.LockContention, e:
5284.6.3 by Parth Malwankar
fixed tests. closed review comments by mgz.
3104
            # The LockContention from the server doesn't have any
3105
            # information about the lock_url. We re-raise LockContention
3106
            # with valid lock_url.
3107
            raise errors.LockContention('(remote lock)',
3108
                self.repository.base.split('.bzr/')[0])
3245.4.24 by Andrew Bennetts
Consistently raise errors from the server as ErrorFromSmartServer exceptions.
3109
        if response[0] != 'ok':
2555.1.1 by Martin Pool
Remove use of 'assert False' to raise an exception unconditionally
3110
            raise errors.UnexpectedSmartServerResponse(response)
3245.4.24 by Andrew Bennetts
Consistently raise errors from the server as ErrorFromSmartServer exceptions.
3111
        ok, branch_token, repo_token = response
3112
        return branch_token, repo_token
3943.8.1 by Marius Kruger
remove all trailing whitespace from bzr source
3113
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).
3114
    def lock_write(self, token=None):
2018.5.79 by Andrew Bennetts
Implement RemoteBranch.lock_write/unlock as smart operations.
3115
        if not self._lock_mode:
4731.1.2 by Andrew Bennetts
Refactor to reduce duplication.
3116
            self._note_lock('w')
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.
3117
            # 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).
3118
            remote_tokens = self._remote_lock_write(token)
2018.5.79 by Andrew Bennetts
Implement RemoteBranch.lock_write/unlock as smart operations.
3119
            self._lock_token, self._repo_lock_token = remote_tokens
3376.2.4 by Martin Pool
Remove every assert statement from bzrlib!
3120
            if not self._lock_token:
3121
                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.
3122
            # 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.
3123
            self.repository.lock_write(
3124
                self._repo_lock_token, _skip_rpc=True)
3692.1.1 by Andrew Bennetts
Make RemoteBranch.lock_write lock the repository too.
3125
2018.5.79 by Andrew Bennetts
Implement RemoteBranch.lock_write/unlock as smart operations.
3126
            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.
3127
                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).
3128
            if token is not None:
2018.5.79 by Andrew Bennetts
Implement RemoteBranch.lock_write/unlock as smart operations.
3129
                self._leave_lock = True
3130
            else:
3131
                self._leave_lock = False
3132
            self._lock_mode = 'w'
3133
            self._lock_count = 1
3134
        elif self._lock_mode == 'r':
5241.1.1 by Andrew Bennetts
Fix AttributeError in RemoteBranch.lock_write after lock_read.
3135
            raise errors.ReadOnlyError(self)
2018.5.79 by Andrew Bennetts
Implement RemoteBranch.lock_write/unlock as smart operations.
3136
        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).
3137
            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.
3138
                # A token was given to lock_write, and we're relocking, so
3139
                # check that the given token actually matches the one we
3140
                # 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).
3141
                if token != self._lock_token:
3142
                    raise errors.TokenMismatch(token, self._lock_token)
2018.5.79 by Andrew Bennetts
Implement RemoteBranch.lock_write/unlock as smart operations.
3143
            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.
3144
            # Re-lock the repository too.
3692.1.2 by Andrew Bennetts
Fix regression introduced by fix, and add a test for that regression.
3145
            self.repository.lock_write(self._repo_lock_token)
5200.3.3 by Robert Collins
Lock methods on ``Tree``, ``Branch`` and ``Repository`` are now
3146
        return BranchWriteLockResult(self.unlock, self._lock_token or None)
2018.5.79 by Andrew Bennetts
Implement RemoteBranch.lock_write/unlock as smart operations.
3147
3148
    def _unlock(self, branch_token, repo_token):
3786.2.3 by Andrew Bennetts
Remove duplicated 'call & translate errors' code in bzrlib.remote.
3149
        err_context = {'token': str((branch_token, repo_token))}
3150
        response = self._call(
3151
            'Branch.unlock', self._remote_path(), branch_token,
3152
            repo_token or '', **err_context)
2018.5.79 by Andrew Bennetts
Implement RemoteBranch.lock_write/unlock as smart operations.
3153
        if response == ('ok',):
3154
            return
3245.4.24 by Andrew Bennetts
Consistently raise errors from the server as ErrorFromSmartServer exceptions.
3155
        raise errors.UnexpectedSmartServerResponse(response)
1752.2.31 by Martin Pool
[broken] some support for write operations over hpss
3156
4634.85.9 by Andrew Bennetts
Add some experimental decorators: @only_raises(..) and @cleanup_method.
3157
    @only_raises(errors.LockNotHeld, errors.LockBroken)
1752.2.31 by Martin Pool
[broken] some support for write operations over hpss
3158
    def unlock(self):
3692.1.1 by Andrew Bennetts
Make RemoteBranch.lock_write lock the repository too.
3159
        try:
3160
            self._lock_count -= 1
3161
            if not self._lock_count:
3162
                self._clear_cached_state()
3163
                mode = self._lock_mode
3164
                self._lock_mode = None
3165
                if self._real_branch is not None:
3166
                    if (not self._leave_lock and mode == 'w' and
3167
                        self._repo_lock_token):
3168
                        # If this RemoteBranch will remove the physical lock
3169
                        # for the repository, make sure the _real_branch
3170
                        # doesn't do it first.  (Because the _real_branch's
3171
                        # repository is set to be the RemoteRepository.)
3172
                        self._real_branch.repository.leave_lock_in_place()
3173
                    self._real_branch.unlock()
3174
                if mode != 'w':
3175
                    # Only write-locked branched need to make a remote method
4031.3.1 by Frank Aspell
Fixing various typos
3176
                    # call to perform the unlock.
3692.1.1 by Andrew Bennetts
Make RemoteBranch.lock_write lock the repository too.
3177
                    return
3178
                if not self._lock_token:
3179
                    raise AssertionError('Locked, but no token!')
3180
                branch_token = self._lock_token
3181
                repo_token = self._repo_lock_token
3182
                self._lock_token = None
3183
                self._repo_lock_token = None
3184
                if not self._leave_lock:
3185
                    self._unlock(branch_token, repo_token)
3186
        finally:
3187
            self.repository.unlock()
1752.2.52 by Andrew Bennetts
Flesh out more Remote* methods needed to open and initialise remote branches/trees/repositories.
3188
3189
    def break_lock(self):
6280.4.3 by Jelmer Vernooij
add Branch.break_lock.
3190
        try:
3191
            response = self._call(
3192
                'Branch.break_lock', self._remote_path())
3193
        except errors.UnknownSmartMethod:
3194
            self._ensure_real()
3195
            return self._real_branch.break_lock()
3196
        if response != ('ok',):
3197
            raise errors.UnexpectedSmartServerResponse(response)
1752.2.31 by Martin Pool
[broken] some support for write operations over hpss
3198
2018.5.79 by Andrew Bennetts
Implement RemoteBranch.lock_write/unlock as smart operations.
3199
    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.
3200
        if not self._lock_token:
3201
            raise NotImplementedError(self.leave_lock_in_place)
2018.5.79 by Andrew Bennetts
Implement RemoteBranch.lock_write/unlock as smart operations.
3202
        self._leave_lock = True
3203
3204
    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.
3205
        if not self._lock_token:
3015.2.15 by Robert Collins
Review feedback.
3206
            raise NotImplementedError(self.dont_leave_lock_in_place)
2018.5.79 by Andrew Bennetts
Implement RemoteBranch.lock_write/unlock as smart operations.
3207
        self._leave_lock = False
3208
4634.69.1 by Andrew Bennetts
Apply @needs_read_lock to RemoteBranch.get_rev_id.
3209
    @needs_read_lock
4419.2.4 by Andrew Bennetts
Add Repository.get_rev_id_for_revno RPC, removes VFS calls from 'pull -r 123' case.
3210
    def get_rev_id(self, revno, history=None):
4419.2.17 by Andrew Bennetts
Fix test failures in test_lookup_revision_id_by_dotted.
3211
        if revno == 0:
3212
            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.
3213
        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.
3214
        ok, result = self.repository.get_rev_id_for_revno(
3215
            revno, last_revision_info)
3216
        if ok:
3217
            return result
3218
        missing_parent = result[1]
4419.2.17 by Andrew Bennetts
Fix test failures in test_lookup_revision_id_by_dotted.
3219
        # Either the revision named by the server is missing, or its parent
3220
        # is.  Call get_parent_map to determine which, so that we report a
3221
        # useful error.
3222
        parent_map = self.repository.get_parent_map([missing_parent])
3223
        if missing_parent in parent_map:
3224
            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.
3225
        raise errors.RevisionNotPresent(missing_parent, self.repository)
3226
5718.8.3 by Jelmer Vernooij
More branch restructuring.
3227
    def _read_last_revision_info(self):
3786.2.3 by Andrew Bennetts
Remove duplicated 'call & translate errors' code in bzrlib.remote.
3228
        response = self._call('Branch.last_revision_info', self._remote_path())
3376.2.4 by Martin Pool
Remove every assert statement from bzrlib!
3229
        if response[0] != 'ok':
3230
            raise SmartProtocolError('unexpected response code %s' % (response,))
2018.5.51 by Wouter van Heyst
Test and implement RemoteBranch.last_revision_info()
3231
        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.
3232
        last_revision = response[2]
2018.5.51 by Wouter van Heyst
Test and implement RemoteBranch.last_revision_info()
3233
        return (revno, last_revision)
3234
2018.5.105 by Andrew Bennetts
Implement revision_history caching for RemoteBranch.
3235
    def _gen_revision_history(self):
3236
        """See Branch._gen_revision_history()."""
4419.1.3 by Andrew Bennetts
Quick fix by using self._ensure_real.
3237
        if self._is_stacked:
3238
            self._ensure_real()
3239
            return self._real_branch._gen_revision_history()
3786.2.3 by Andrew Bennetts
Remove duplicated 'call & translate errors' code in bzrlib.remote.
3240
        response_tuple, response_handler = self._call_expecting_body(
3691.2.3 by Martin Pool
Factor out RemoteBranch._remote_path() and disable RemoteBranch stacking
3241
            '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.
3242
        if response_tuple[0] != 'ok':
3452.2.2 by Andrew Bennetts
Experimental PackRepository.{check_references,autopack} RPCs.
3243
            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.
3244
        result = response_handler.read_body_bytes().split('\x00')
2018.5.38 by Robert Collins
Implement RemoteBranch.revision_history().
3245
        if result == ['']:
3246
            return []
3247
        return result
1752.2.30 by Martin Pool
Start adding a RemoteBzrDir, etc
3248
3691.2.3 by Martin Pool
Factor out RemoteBranch._remote_path() and disable RemoteBranch stacking
3249
    def _remote_path(self):
3250
        return self.bzrdir._path_for_remote_call(self._client)
3251
3441.5.18 by Andrew Bennetts
Fix some test failures.
3252
    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.
3253
            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.
3254
        # This performs additional work to meet the hook contract; while its
3255
        # undesirable, we have to synthesise the revno to call the hook, and
3256
        # not calling the hook is worse as it means changes can't be prevented.
3257
        # Having calculated this though, we can't just call into
3258
        # set_last_revision_info as a simple call, because there is a set_rh
3259
        # hook that some folk may still be using.
3260
        old_revno, old_revid = self.last_revision_info()
3261
        history = self._lefthand_history(revision_id)
3262
        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.
3263
        err_context = {'other_branch': other_branch}
3264
        response = self._call('Branch.set_last_revision_ex',
3265
            self._remote_path(), self._lock_token, self._repo_lock_token,
3266
            revision_id, int(allow_diverged), int(allow_overwrite_descendant),
3267
            **err_context)
3441.5.6 by Andrew Bennetts
Greatly simplify RemoteBranch.update_revisions. Still needs more tests.
3268
        self._clear_cached_state()
3441.5.18 by Andrew Bennetts
Fix some test failures.
3269
        if len(response) != 3 and response[0] != 'ok':
3441.5.6 by Andrew Bennetts
Greatly simplify RemoteBranch.update_revisions. Still needs more tests.
3270
            raise errors.UnexpectedSmartServerResponse(response)
3441.5.18 by Andrew Bennetts
Fix some test failures.
3271
        new_revno, new_revision_id = response[1:]
3272
        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.
3273
        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.
3274
        if self._real_branch is not None:
3275
            cache = new_revno, new_revision_id
3276
            self._real_branch._last_revision_info_cache = cache
3441.5.6 by Andrew Bennetts
Greatly simplify RemoteBranch.update_revisions. Still needs more tests.
3277
3441.5.1 by Andrew Bennetts
Avoid necessarily calling get_parent_map when pushing.
3278
    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.
3279
        old_revno, old_revid = self.last_revision_info()
3280
        # This performs additional work to meet the hook contract; while its
3281
        # undesirable, we have to synthesise the revno to call the hook, and
3282
        # not calling the hook is worse as it means changes can't be prevented.
3283
        # Having calculated this though, we can't just call into
3284
        # set_last_revision_info as a simple call, because there is a set_rh
3285
        # hook that some folk may still be using.
3286
        history = self._lefthand_history(revision_id)
3287
        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.
3288
        self._clear_cached_state()
3786.2.3 by Andrew Bennetts
Remove duplicated 'call & translate errors' code in bzrlib.remote.
3289
        response = self._call('Branch.set_last_revision',
3290
            self._remote_path(), self._lock_token, self._repo_lock_token,
3291
            revision_id)
3441.5.1 by Andrew Bennetts
Avoid necessarily calling get_parent_map when pushing.
3292
        if response != ('ok',):
3293
            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.
3294
        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.
3295
5718.7.7 by Jelmer Vernooij
Implement stub RemoteBranch.revision_history.
3296
    @symbol_versioning.deprecated_method(symbol_versioning.deprecated_in((2, 4, 0)))
3297
    @needs_write_lock
3298
    def set_revision_history(self, rev_history):
3299
        """See Branch.set_revision_history."""
3300
        self._set_revision_history(rev_history)
3301
2018.14.1 by Andrew Bennetts
Update to current hpss branch? Fix lots of test failures.
3302
    @needs_write_lock
5718.7.4 by Jelmer Vernooij
Branch.set_revision_history.
3303
    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.
3304
        # Send just the tip revision of the history; the server will generate
3305
        # the full history from that.  If the revision doesn't exist in this
3306
        # branch, NoSuchRevision will be raised.
3307
        if rev_history == []:
2018.5.170 by Andrew Bennetts
Use 'null:' instead of '' to mean NULL_REVISION on the wire.
3308
            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.
3309
        else:
3310
            rev_id = rev_history[-1]
3441.5.1 by Andrew Bennetts
Avoid necessarily calling get_parent_map when pushing.
3311
        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.
3312
        for hook in branch.Branch.hooks['set_rh']:
3313
            hook(self, rev_history)
2018.5.105 by Andrew Bennetts
Implement revision_history caching for RemoteBranch.
3314
        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.
3315
4078.2.1 by Robert Collins
Add a Branch.get_parent remote call for RemoteBranch.
3316
    def _get_parent_location(self):
3317
        medium = self._client._medium
3318
        if medium._is_remote_before((1, 13)):
3319
            return self._vfs_get_parent_location()
3320
        try:
4083.1.4 by Andrew Bennetts
Fix trivial bug in get_parent RPC.
3321
            response = self._call('Branch.get_parent', self._remote_path())
4078.2.1 by Robert Collins
Add a Branch.get_parent remote call for RemoteBranch.
3322
        except errors.UnknownSmartMethod:
4094.1.1 by Andrew Bennetts
Add some medium._remember_is_before((1, 13)) calls.
3323
            medium._remember_remote_is_before((1, 13))
4078.2.1 by Robert Collins
Add a Branch.get_parent remote call for RemoteBranch.
3324
            return self._vfs_get_parent_location()
4083.1.4 by Andrew Bennetts
Fix trivial bug in get_parent RPC.
3325
        if len(response) != 1:
4083.1.6 by Andrew Bennetts
Fix trivial bug in my trivial bug fix :)
3326
            raise errors.UnexpectedSmartServerResponse(response)
4083.1.4 by Andrew Bennetts
Fix trivial bug in get_parent RPC.
3327
        parent_location = response[0]
3328
        if parent_location == '':
4078.2.1 by Robert Collins
Add a Branch.get_parent remote call for RemoteBranch.
3329
            return None
4083.1.4 by Andrew Bennetts
Fix trivial bug in get_parent RPC.
3330
        return parent_location
4078.2.1 by Robert Collins
Add a Branch.get_parent remote call for RemoteBranch.
3331
3332
    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.
3333
        self._ensure_real()
4083.1.5 by Andrew Bennetts
Fix trivial bug in get_parent RPC.
3334
        return self._real_branch._get_parent_location()
4032.1.1 by John Arbash Meinel
Merge the removal of all trailing whitespace, and resolve conflicts.
3335
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.
3336
    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.
3337
        medium = self._client._medium
3338
        if medium._is_remote_before((1, 15)):
3339
            return self._vfs_set_parent_location(url)
3340
        try:
3341
            call_url = url or ''
3342
            if type(call_url) is not str:
3343
                raise AssertionError('url must be a str or None (%s)' % url)
3344
            response = self._call('Branch.set_parent_location',
3345
                self._remote_path(), self._lock_token, self._repo_lock_token,
3346
                call_url)
3347
        except errors.UnknownSmartMethod:
3348
            medium._remember_remote_is_before((1, 15))
3349
            return self._vfs_set_parent_location(url)
3350
        if response != ():
3351
            raise errors.UnexpectedSmartServerResponse(response)
3352
3353
    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.
3354
        self._ensure_real()
3355
        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.
3356
2018.14.1 by Andrew Bennetts
Update to current hpss branch? Fix lots of test failures.
3357
    @needs_write_lock
2477.1.2 by Martin Pool
Rename push/pull back to 'run_hooks' (jameinel)
3358
    def pull(self, source, overwrite=False, stop_revision=None,
2477.1.9 by Martin Pool
Review cleanups from John, mostly docs
3359
             **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.
3360
        self._clear_cached_state_of_remote_branch_only()
2018.14.1 by Andrew Bennetts
Update to current hpss branch? Fix lots of test failures.
3361
        self._ensure_real()
3482.1.1 by John Arbash Meinel
Fix bug #238149, RemoteBranch.pull needs to return the _real_branch's pull result.
3362
        return self._real_branch.pull(
2477.1.2 by Martin Pool
Rename push/pull back to 'run_hooks' (jameinel)
3363
            source, overwrite=overwrite, stop_revision=stop_revision,
3489.2.4 by Andrew Bennetts
Fix all tests broken by fixing make_branch_and_tree.
3364
            _override_hook_target=self, **kwargs)
2018.14.1 by Andrew Bennetts
Update to current hpss branch? Fix lots of test failures.
3365
2018.14.3 by Andrew Bennetts
Make a couple more branch_implementations tests pass.
3366
    @needs_read_lock
5853.2.3 by Jelmer Vernooij
Fix lossy tests.
3367
    def push(self, target, overwrite=False, stop_revision=None, lossy=False):
2018.14.3 by Andrew Bennetts
Make a couple more branch_implementations tests pass.
3368
        self._ensure_real()
2018.5.97 by Andrew Bennetts
Fix more tests.
3369
        return self._real_branch.push(
5853.2.3 by Jelmer Vernooij
Fix lossy tests.
3370
            target, overwrite=overwrite, stop_revision=stop_revision, lossy=lossy,
2477.1.5 by Martin Pool
More cleanups of Branch.push to get the right behaviour with RemoteBranches
3371
            _override_hook_source_branch=self)
2018.14.3 by Andrew Bennetts
Make a couple more branch_implementations tests pass.
3372
3373
    def is_locked(self):
3374
        return self._lock_count >= 1
3375
3634.2.1 by John Arbash Meinel
Thunk over to the real branch's revision_id_to_revno.
3376
    @needs_read_lock
6263.1.2 by Jelmer Vernooij
Add ``Branch.revision_id_to_revno`` smart verb.
3377
    def revision_id_to_dotted_revno(self, revision_id):
3378
        """Given a revision id, return its dotted revno.
3379
3380
        :return: a tuple like (1,) or (400,1,3).
3381
        """
3382
        try:
3383
            response = self._call('Branch.revision_id_to_revno',
3384
                self._remote_path(), revision_id)
3385
        except errors.UnknownSmartMethod:
3386
            self._ensure_real()
6305.1.1 by Jelmer Vernooij
Add test for Branch.revision_id_to_dotted_revno fallback.
3387
            return self._real_branch.revision_id_to_dotted_revno(revision_id)
6263.1.2 by Jelmer Vernooij
Add ``Branch.revision_id_to_revno`` smart verb.
3388
        if response[0] == 'ok':
3389
            return tuple([int(x) for x in response[1:]])
3390
        else:
3391
            raise errors.UnexpectedSmartServerResponse(response)
3392
3393
    @needs_read_lock
3634.2.1 by John Arbash Meinel
Thunk over to the real branch's revision_id_to_revno.
3394
    def revision_id_to_revno(self, revision_id):
6263.1.2 by Jelmer Vernooij
Add ``Branch.revision_id_to_revno`` smart verb.
3395
        """Given a revision id on the branch mainline, return its revno.
3396
3397
        :return: an integer
3398
        """
3399
        try:
3400
            response = self._call('Branch.revision_id_to_revno',
3401
                self._remote_path(), revision_id)
3402
        except errors.UnknownSmartMethod:
3403
            self._ensure_real()
3404
            return self._real_branch.revision_id_to_revno(revision_id)
3405
        if response[0] == 'ok':
3406
            if len(response) == 2:
3407
                return int(response[1])
6263.1.6 by Jelmer Vernooij
Fix another test.
3408
            raise NoSuchRevision(self, revision_id)
6263.1.2 by Jelmer Vernooij
Add ``Branch.revision_id_to_revno`` smart verb.
3409
        else:
3410
            raise errors.UnexpectedSmartServerResponse(response)
3634.2.1 by John Arbash Meinel
Thunk over to the real branch's revision_id_to_revno.
3411
2892.2.1 by Andrew Bennetts
Add Branch.set_last_revision_info smart method, and make the RemoteBranch client use it.
3412
    @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.
3413
    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.
3414
        # XXX: These should be returned by the set_last_revision_info verb
3415
        old_revno, old_revid = self.last_revision_info()
3416
        self._run_pre_change_branch_tip_hooks(revno, revision_id)
5803.1.1 by Jelmer Vernooij
Raise InvalidRevisionId on Branch.set_last_revision_info.
3417
        if not revision_id or not isinstance(revision_id, basestring):
3418
            raise errors.InvalidRevisionId(revision_id=revision_id, branch=self)
3297.4.2 by Andrew Bennetts
Add backwards compatibility for servers older than 1.4.
3419
        try:
3786.2.3 by Andrew Bennetts
Remove duplicated 'call & translate errors' code in bzrlib.remote.
3420
            response = self._call('Branch.set_last_revision_info',
3421
                self._remote_path(), self._lock_token, self._repo_lock_token,
3422
                str(revno), revision_id)
3297.4.2 by Andrew Bennetts
Add backwards compatibility for servers older than 1.4.
3423
        except errors.UnknownSmartMethod:
3424
            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.
3425
            self._clear_cached_state_of_remote_branch_only()
3441.5.1 by Andrew Bennetts
Avoid necessarily calling get_parent_map when pushing.
3426
            self._real_branch.set_last_revision_info(revno, revision_id)
3427
            self._last_revision_info_cache = revno, revision_id
3428
            return
2892.2.1 by Andrew Bennetts
Add Branch.set_last_revision_info smart method, and make the RemoteBranch client use it.
3429
        if response == ('ok',):
3430
            self._clear_cached_state()
3441.5.1 by Andrew Bennetts
Avoid necessarily calling get_parent_map when pushing.
3431
            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.
3432
            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.
3433
            # Update the _real_branch's cache too.
3434
            if self._real_branch is not None:
3435
                cache = self._last_revision_info_cache
3436
                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.
3437
        else:
3438
            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.
3439
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.
3440
    @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.
3441
    def generate_revision_history(self, revision_id, last_rev=None,
3442
                                  other_branch=None):
3441.5.6 by Andrew Bennetts
Greatly simplify RemoteBranch.update_revisions. Still needs more tests.
3443
        medium = self._client._medium
3441.5.23 by Andrew Bennetts
Fix test failures.
3444
        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.
3445
            # 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.
3446
            try:
3441.5.18 by Andrew Bennetts
Fix some test failures.
3447
                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.
3448
                    allow_diverged=True, allow_overwrite_descendant=True)
3441.5.6 by Andrew Bennetts
Greatly simplify RemoteBranch.update_revisions. Still needs more tests.
3449
                return
3441.5.18 by Andrew Bennetts
Fix some test failures.
3450
            except errors.UnknownSmartMethod:
3441.5.23 by Andrew Bennetts
Fix test failures.
3451
                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.
3452
        self._clear_cached_state_of_remote_branch_only()
5718.7.4 by Jelmer Vernooij
Branch.set_revision_history.
3453
        self._set_revision_history(self._lefthand_history(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.
3454
            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
3455
2018.5.97 by Andrew Bennetts
Fix more tests.
3456
    def set_push_location(self, location):
3457
        self._ensure_real()
3458
        return self._real_branch.set_push_location(location)
3459
5741.1.11 by Jelmer Vernooij
Don't make heads_to_fetch() take a stop_revision.
3460
    def heads_to_fetch(self):
5672.1.7 by Andrew Bennetts
Use a more explicit method name.
3461
        if self._format._use_default_local_heads_to_fetch():
5672.1.5 by Andrew Bennetts
Add some tests for RemoteBranch.heads_to_fetch, and add release-note.
3462
            # We recognise this format, and its heads-to-fetch implementation
3463
            # is the default one (tip + tags).  In this case it's cheaper to
3464
            # just use the default implementation rather than a special RPC as
3465
            # the tip and tags data is cached.
5741.1.11 by Jelmer Vernooij
Don't make heads_to_fetch() take a stop_revision.
3466
            return branch.Branch.heads_to_fetch(self)
5672.1.4 by Andrew Bennetts
Fix final bzr-loom test by adding RemoteBranch.heads_to_fetch that can ask the remote branch for the heads to fetch (but uses the cheaper default logic if it knows the remote format has an identical heads_to_fetch as Branch.heads_to_fetch).
3467
        medium = self._client._medium
3468
        if medium._is_remote_before((2, 4)):
5741.1.11 by Jelmer Vernooij
Don't make heads_to_fetch() take a stop_revision.
3469
            return self._vfs_heads_to_fetch()
5672.1.4 by Andrew Bennetts
Fix final bzr-loom test by adding RemoteBranch.heads_to_fetch that can ask the remote branch for the heads to fetch (but uses the cheaper default logic if it knows the remote format has an identical heads_to_fetch as Branch.heads_to_fetch).
3470
        try:
5741.1.11 by Jelmer Vernooij
Don't make heads_to_fetch() take a stop_revision.
3471
            return self._rpc_heads_to_fetch()
5672.1.4 by Andrew Bennetts
Fix final bzr-loom test by adding RemoteBranch.heads_to_fetch that can ask the remote branch for the heads to fetch (but uses the cheaper default logic if it knows the remote format has an identical heads_to_fetch as Branch.heads_to_fetch).
3472
        except errors.UnknownSmartMethod:
3473
            medium._remember_remote_is_before((2, 4))
5741.1.11 by Jelmer Vernooij
Don't make heads_to_fetch() take a stop_revision.
3474
            return self._vfs_heads_to_fetch()
5672.1.4 by Andrew Bennetts
Fix final bzr-loom test by adding RemoteBranch.heads_to_fetch that can ask the remote branch for the heads to fetch (but uses the cheaper default logic if it knows the remote format has an identical heads_to_fetch as Branch.heads_to_fetch).
3475
5741.1.11 by Jelmer Vernooij
Don't make heads_to_fetch() take a stop_revision.
3476
    def _rpc_heads_to_fetch(self):
3477
        response = self._call('Branch.heads_to_fetch', self._remote_path())
5672.1.4 by Andrew Bennetts
Fix final bzr-loom test by adding RemoteBranch.heads_to_fetch that can ask the remote branch for the heads to fetch (but uses the cheaper default logic if it knows the remote format has an identical heads_to_fetch as Branch.heads_to_fetch).
3478
        if len(response) != 2:
3479
            raise errors.UnexpectedSmartServerResponse(response)
3480
        must_fetch, if_present_fetch = response
3481
        return set(must_fetch), set(if_present_fetch)
3482
5741.1.11 by Jelmer Vernooij
Don't make heads_to_fetch() take a stop_revision.
3483
    def _vfs_heads_to_fetch(self):
5672.1.4 by Andrew Bennetts
Fix final bzr-loom test by adding RemoteBranch.heads_to_fetch that can ask the remote branch for the heads to fetch (but uses the cheaper default logic if it knows the remote format has an identical heads_to_fetch as Branch.heads_to_fetch).
3484
        self._ensure_real()
5741.1.11 by Jelmer Vernooij
Don't make heads_to_fetch() take a stop_revision.
3485
        return self._real_branch.heads_to_fetch()
5672.1.4 by Andrew Bennetts
Fix final bzr-loom test by adding RemoteBranch.heads_to_fetch that can ask the remote branch for the heads to fetch (but uses the cheaper default logic if it knows the remote format has an identical heads_to_fetch as Branch.heads_to_fetch).
3486
2018.18.25 by Martin Pool
Repository.tarball fixes for python2.4
3487
4288.1.1 by Robert Collins
Add support for a RemoteBzrDirConfig to support optimising push operations which need to look for default stacking locations.
3488
class RemoteConfig(object):
3489
    """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.
3490
3491
    It is a low-level object that considers config data to be name/value pairs
3492
    that may be associated with a section. Assigning meaning to the these
3493
    values is done at higher levels like bzrlib.config.TreeConfig.
3494
    """
3495
3496
    def get_option(self, name, section=None, default=None):
3497
        """Return the value associated with a named option.
3498
3499
        :param name: The name of the value
3500
        :param section: The section the option is in (if any)
3501
        :param default: The value to return if the value is not set
3502
        :return: The value or default value
3503
        """
4288.1.1 by Robert Collins
Add support for a RemoteBzrDirConfig to support optimising push operations which need to look for default stacking locations.
3504
        try:
3505
            configobj = self._get_configobj()
5743.8.17 by Vincent Ladeuil
Add config old_get hook for remote config.
3506
            section_obj = 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.
3507
            if section is None:
3508
                section_obj = configobj
3509
            else:
3510
                try:
3511
                    section_obj = configobj[section]
3512
                except KeyError:
5743.8.17 by Vincent Ladeuil
Add config old_get hook for remote config.
3513
                    pass
3514
            if section_obj is None:
3515
                value = default
3516
            else:
3517
                value = section_obj.get(name, default)
4288.1.1 by Robert Collins
Add support for a RemoteBzrDirConfig to support optimising push operations which need to look for default stacking locations.
3518
        except errors.UnknownSmartMethod:
5743.8.17 by Vincent Ladeuil
Add config old_get hook for remote config.
3519
            value = self._vfs_get_option(name, section, default)
5743.8.24 by Vincent Ladeuil
Clearly seaparate both sets of hooks for the old and new config implementations.
3520
        for hook in config.OldConfigHooks['get']:
5743.8.17 by Vincent Ladeuil
Add config old_get hook for remote config.
3521
            hook(self, name, value)
3522
        return value
4226.1.5 by Robert Collins
Reinstate the use of the Branch.get_config_file verb.
3523
4288.1.1 by Robert Collins
Add support for a RemoteBzrDirConfig to support optimising push operations which need to look for default stacking locations.
3524
    def _response_to_configobj(self, response):
4288.1.2 by Robert Collins
Create a server verb for doing BzrDir.get_config()
3525
        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.
3526
            raise errors.UnexpectedSmartServerResponse(response)
4241.5.1 by Matt Nordhoff
Fix Branch.get_config_file smart verb on multi-line config files. (Bug #354075)
3527
        lines = response[1].read_body_bytes().splitlines()
5743.8.21 by Vincent Ladeuil
Add test for config load hook for remote configs.
3528
        conf = config.ConfigObj(lines, encoding='utf-8')
5743.8.24 by Vincent Ladeuil
Clearly seaparate both sets of hooks for the old and new config implementations.
3529
        for hook in config.OldConfigHooks['load']:
5743.8.21 by Vincent Ladeuil
Add test for config load hook for remote configs.
3530
            hook(self)
3531
        return conf
4226.1.5 by Robert Collins
Reinstate the use of the Branch.get_config_file verb.
3532
4288.1.1 by Robert Collins
Add support for a RemoteBzrDirConfig to support optimising push operations which need to look for default stacking locations.
3533
3534
class RemoteBranchConfig(RemoteConfig):
3535
    """A RemoteConfig for Branches."""
3536
3537
    def __init__(self, branch):
3538
        self._branch = branch
3539
3540
    def _get_configobj(self):
3541
        path = self._branch._remote_path()
3542
        response = self._branch._client.call_expecting_body(
3543
            'Branch.get_config_file', path)
3544
        return self._response_to_configobj(response)
3545
4226.1.5 by Robert Collins
Reinstate the use of the Branch.get_config_file verb.
3546
    def set_option(self, value, name, section=None):
3547
        """Set the value associated with a named option.
3548
3549
        :param value: The value to set
3550
        :param name: The name of the value to set
3551
        :param section: The section the option is in (if any)
3552
        """
4226.2.1 by Robert Collins
Set branch config options via a smart method.
3553
        medium = self._branch._client._medium
3554
        if medium._is_remote_before((1, 14)):
3555
            return self._vfs_set_option(value, name, section)
5227.1.2 by Andrew Bennetts
Add Branch.set_config_option_dict RPC (and VFS fallback), fixes #430382.
3556
        if isinstance(value, dict):
3557
            if medium._is_remote_before((2, 2)):
3558
                return self._vfs_set_option(value, name, section)
3559
            return self._set_config_option_dict(value, name, section)
3560
        else:
3561
            return self._set_config_option(value, name, section)
3562
3563
    def _set_config_option(self, value, name, section):
4226.2.1 by Robert Collins
Set branch config options via a smart method.
3564
        try:
3565
            path = self._branch._remote_path()
3566
            response = self._branch._client.call('Branch.set_config_option',
3567
                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.
3568
                value.encode('utf8'), name, section or '')
4226.2.1 by Robert Collins
Set branch config options via a smart method.
3569
        except errors.UnknownSmartMethod:
5227.1.2 by Andrew Bennetts
Add Branch.set_config_option_dict RPC (and VFS fallback), fixes #430382.
3570
            medium = self._branch._client._medium
4226.2.1 by Robert Collins
Set branch config options via a smart method.
3571
            medium._remember_remote_is_before((1, 14))
3572
            return self._vfs_set_option(value, name, section)
3573
        if response != ():
3574
            raise errors.UnexpectedSmartServerResponse(response)
4226.1.5 by Robert Collins
Reinstate the use of the Branch.get_config_file verb.
3575
5227.1.2 by Andrew Bennetts
Add Branch.set_config_option_dict RPC (and VFS fallback), fixes #430382.
3576
    def _serialize_option_dict(self, option_dict):
3577
        utf8_dict = {}
3578
        for key, value in option_dict.items():
3579
            if isinstance(key, unicode):
3580
                key = key.encode('utf8')
3581
            if isinstance(value, unicode):
3582
                value = value.encode('utf8')
3583
            utf8_dict[key] = value
3584
        return bencode.bencode(utf8_dict)
3585
3586
    def _set_config_option_dict(self, value, name, section):
3587
        try:
3588
            path = self._branch._remote_path()
3589
            serialised_dict = self._serialize_option_dict(value)
3590
            response = self._branch._client.call(
3591
                'Branch.set_config_option_dict',
3592
                path, self._branch._lock_token, self._branch._repo_lock_token,
3593
                serialised_dict, name, section or '')
3594
        except errors.UnknownSmartMethod:
3595
            medium = self._branch._client._medium
3596
            medium._remember_remote_is_before((2, 2))
3597
            return self._vfs_set_option(value, name, section)
3598
        if response != ():
3599
            raise errors.UnexpectedSmartServerResponse(response)
3600
4288.1.1 by Robert Collins
Add support for a RemoteBzrDirConfig to support optimising push operations which need to look for default stacking locations.
3601
    def _real_object(self):
3602
        self._branch._ensure_real()
3603
        return self._branch._real_branch
3604
4226.1.5 by Robert Collins
Reinstate the use of the Branch.get_config_file verb.
3605
    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.
3606
        return self._real_object()._get_config().set_option(
3607
            value, name, section)
3608
3609
3610
class RemoteBzrDirConfig(RemoteConfig):
3611
    """A RemoteConfig for BzrDirs."""
3612
3613
    def __init__(self, bzrdir):
3614
        self._bzrdir = bzrdir
3615
3616
    def _get_configobj(self):
4288.1.4 by Robert Collins
Remove the explicit set_parent method on RemoteBranch in favour of inheriting from Branch.
3617
        medium = self._bzrdir._client._medium
3618
        verb = 'BzrDir.get_config_file'
3619
        if medium._is_remote_before((1, 15)):
3620
            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.
3621
        path = self._bzrdir._path_for_remote_call(self._bzrdir._client)
3622
        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.
3623
            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.
3624
        return self._response_to_configobj(response)
3625
3626
    def _vfs_get_option(self, name, section, default):
3627
        return self._real_object()._get_config().get_option(
3628
            name, section, default)
3629
3630
    def set_option(self, value, name, section=None):
3631
        """Set the value associated with a named option.
3632
3633
        :param value: The value to set
3634
        :param name: The name of the value to set
3635
        :param section: The section the option is in (if any)
3636
        """
3637
        return self._real_object()._get_config().set_option(
3638
            value, name, section)
3639
3640
    def _real_object(self):
3641
        self._bzrdir._ensure_real()
3642
        return self._bzrdir._real_bzrdir
3643
4226.1.5 by Robert Collins
Reinstate the use of the Branch.get_config_file verb.
3644
3645
2018.18.25 by Martin Pool
Repository.tarball fixes for python2.4
3646
def _extract_tar(tar, to_dir):
3647
    """Extract all the contents of a tarfile object.
3648
3649
    A replacement for extractall, which is not present in python2.4
3650
    """
3651
    for tarinfo in tar:
3652
        tar.extract(tarinfo, to_dir)
3533.3.1 by Andrew Bennetts
Remove duplication of error translation in bzrlib/remote.py.
3653
3654
6284.1.1 by Jelmer Vernooij
Allow registering custom error handlers in the HPSS client.
3655
error_translators = registry.Registry()
3656
no_context_error_translators = registry.Registry()
3657
3658
3533.3.1 by Andrew Bennetts
Remove duplication of error translation in bzrlib/remote.py.
3659
def _translate_error(err, **context):
3660
    """Translate an ErrorFromSmartServer into a more useful error.
3661
3662
    Possible context keys:
3663
      - branch
3664
      - repository
3665
      - bzrdir
3666
      - token
3667
      - other_branch
3779.3.2 by Andrew Bennetts
Unify error translation done in bzrlib.remote and bzrlib.transport.remote.
3668
      - path
3690.1.1 by Andrew Bennetts
Unexpected error responses from a smart server no longer cause the client to traceback.
3669
3670
    If the error from the server doesn't match a known pattern, then
3690.1.2 by Andrew Bennetts
Rename UntranslateableErrorFromSmartServer -> UnknownErrorFromSmartServer.
3671
    UnknownErrorFromSmartServer is raised.
3533.3.1 by Andrew Bennetts
Remove duplication of error translation in bzrlib/remote.py.
3672
    """
3673
    def find(name):
3533.3.4 by Andrew Bennetts
Add tests for _translate_error's robustness.
3674
        try:
3675
            return context[name]
3779.3.2 by Andrew Bennetts
Unify error translation done in bzrlib.remote and bzrlib.transport.remote.
3676
        except KeyError, key_err:
3677
            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.
3678
            raise err
3779.3.2 by Andrew Bennetts
Unify error translation done in bzrlib.remote and bzrlib.transport.remote.
3679
    def get_path():
3779.3.3 by Andrew Bennetts
Add a docstring.
3680
        """Get the path from the context if present, otherwise use first error
3681
        arg.
3682
        """
3779.3.2 by Andrew Bennetts
Unify error translation done in bzrlib.remote and bzrlib.transport.remote.
3683
        try:
3684
            return context['path']
3685
        except KeyError, key_err:
3686
            try:
3687
                return err.error_args[0]
3688
            except IndexError, idx_err:
3689
                mutter(
3690
                    'Missing key %r in context %r', key_err.args[0], context)
3691
                raise err
3692
6284.1.1 by Jelmer Vernooij
Allow registering custom error handlers in the HPSS client.
3693
    try:
3694
        translator = error_translators.get(err.error_verb)
3695
    except KeyError:
3696
        pass
3697
    else:
3698
        raise translator(err, find, get_path)
3699
    try:
3700
        translator = no_context_error_translators.get(err.error_verb)
3701
    except KeyError:
3702
        raise errors.UnknownErrorFromSmartServer(err)
3703
    else:
3704
        raise translator(err)
3705
3706
3707
error_translators.register('NoSuchRevision',
3708
    lambda err, find, get_path: NoSuchRevision(
3709
        find('branch'), err.error_args[0]))
3710
error_translators.register('nosuchrevision',
3711
    lambda err, find, get_path: NoSuchRevision(
3712
        find('repository'), err.error_args[0]))
3713
3714
def _translate_nobranch_error(err, find, get_path):
3715
    if len(err.error_args) >= 1:
3716
        extra = err.error_args[0]
3717
    else:
3718
        extra = None
3719
    return errors.NotBranchError(path=find('bzrdir').root_transport.base,
3720
        detail=extra)
3721
3722
error_translators.register('nobranch', _translate_nobranch_error)
3723
error_translators.register('norepository',
3724
    lambda err, find, get_path: errors.NoRepositoryPresent(
3725
        find('bzrdir')))
3726
error_translators.register('UnlockableTransport',
3727
    lambda err, find, get_path: errors.UnlockableTransport(
3728
        find('bzrdir').root_transport))
3729
error_translators.register('TokenMismatch',
3730
    lambda err, find, get_path: errors.TokenMismatch(
3731
        find('token'), '(remote token)'))
3732
error_translators.register('Diverged',
3733
    lambda err, find, get_path: errors.DivergedBranches(
3734
        find('branch'), find('other_branch')))
3735
error_translators.register('NotStacked',
3736
    lambda err, find, get_path: errors.NotStacked(branch=find('branch')))
3737
3738
def _translate_PermissionDenied(err, find, get_path):
3739
    path = get_path()
3740
    if len(err.error_args) >= 2:
3741
        extra = err.error_args[1]
3742
    else:
3743
        extra = None
3744
    return errors.PermissionDenied(path, extra=extra)
3745
3746
error_translators.register('PermissionDenied', _translate_PermissionDenied)
3747
error_translators.register('ReadError',
3748
    lambda err, find, get_path: errors.ReadError(get_path()))
3749
error_translators.register('NoSuchFile',
3750
    lambda err, find, get_path: errors.NoSuchFile(get_path()))
3751
no_context_error_translators.register('IncompatibleRepositories',
3752
    lambda err: errors.IncompatibleRepositories(
3753
        err.error_args[0], err.error_args[1], err.error_args[2]))
3754
no_context_error_translators.register('LockContention',
3755
    lambda err: errors.LockContention('(remote lock)'))
3756
no_context_error_translators.register('LockFailed',
3757
    lambda err: errors.LockFailed(err.error_args[0], err.error_args[1]))
3758
no_context_error_translators.register('TipChangeRejected',
3759
    lambda err: errors.TipChangeRejected(err.error_args[0].decode('utf8')))
3760
no_context_error_translators.register('UnstackableBranchFormat',
3761
    lambda err: errors.UnstackableBranchFormat(*err.error_args))
3762
no_context_error_translators.register('UnstackableRepositoryFormat',
3763
    lambda err: errors.UnstackableRepositoryFormat(*err.error_args))
3764
no_context_error_translators.register('FileExists',
3765
    lambda err: errors.FileExists(err.error_args[0]))
3766
no_context_error_translators.register('DirectoryNotEmpty',
3767
    lambda err: errors.DirectoryNotEmpty(err.error_args[0]))
3768
3769
def _translate_short_readv_error(err):
3770
    args = err.error_args
3771
    return errors.ShortReadvError(args[0], int(args[1]), int(args[2]),
3772
        int(args[3]))
3773
3774
no_context_error_translators.register('ShortReadvError',
3775
    _translate_short_readv_error)
3776
3777
def _translate_unicode_error(err):
3779.3.2 by Andrew Bennetts
Unify error translation done in bzrlib.remote and bzrlib.transport.remote.
3778
        encoding = str(err.error_args[0]) # encoding must always be a string
3779
        val = err.error_args[1]
3780
        start = int(err.error_args[2])
3781
        end = int(err.error_args[3])
3782
        reason = str(err.error_args[4]) # reason must always be a string
3783
        if val.startswith('u:'):
3784
            val = val[2:].decode('utf-8')
3785
        elif val.startswith('s:'):
3786
            val = val[2:].decode('base64')
3786.2.3 by Andrew Bennetts
Remove duplicated 'call & translate errors' code in bzrlib.remote.
3787
        if err.error_verb == 'UnicodeDecodeError':
3779.3.2 by Andrew Bennetts
Unify error translation done in bzrlib.remote and bzrlib.transport.remote.
3788
            raise UnicodeDecodeError(encoding, val, start, end, reason)
3786.2.3 by Andrew Bennetts
Remove duplicated 'call & translate errors' code in bzrlib.remote.
3789
        elif err.error_verb == 'UnicodeEncodeError':
3779.3.2 by Andrew Bennetts
Unify error translation done in bzrlib.remote and bzrlib.transport.remote.
3790
            raise UnicodeEncodeError(encoding, val, start, end, reason)
6284.1.1 by Jelmer Vernooij
Allow registering custom error handlers in the HPSS client.
3791
3792
no_context_error_translators.register('UnicodeEncodeError',
3793
    _translate_unicode_error)
3794
no_context_error_translators.register('UnicodeDecodeError',
3795
    _translate_unicode_error)
3796
no_context_error_translators.register('ReadOnlyError',
3797
    lambda err: errors.TransportNotPossible('readonly transport'))
3798
no_context_error_translators.register('MemoryError',
3799
    lambda err: errors.BzrError("remote server out of memory\n"
3800
        "Retry non-remotely, or contact the server admin for details."))
6280.7.13 by Jelmer Vernooij
Merge bzr.dev.
3801
3802
no_context_error_translators.register('BzrCheckError',
3803
    lambda err: errors.BzrCheckError(msg=err.error_args[0]))
3804
3805
error_translators.register('UnsuspendableWriteGroup',
3806
    lambda err, find, get_path: errors.UnsuspendableWriteGroup(
3807
        repository=find('repository')))
3808
error_translators.register('UnresumableWriteGroup',
3809
    lambda err, find, get_path: errors.UnresumableWriteGroup(
3810
        repository=find('repository'), write_groups=err.error_args[0],
3811
        reason=err.error_args[1]))