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