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