/brz/remove-bazaar

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