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