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