/brz/remove-bazaar

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