/brz/remove-bazaar

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