/brz/remove-bazaar

To get this branch, use:
bzr branch http://gegoxaren.bato24.eu/bzr/brz/remove-bazaar
3407.2.2 by Martin Pool
Remove special case in RemoteBranchLockableFiles for branch.conf
1
# Copyright (C) 2006, 2007, 2008 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
15
# Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
16
1752.2.39 by Martin Pool
[broken] implement upgrade apis on remote bzrdirs
17
# TODO: At some point, handle upgrades by just passing the whole request
18
# across to run on the server.
19
3211.5.2 by Robert Collins
Change RemoteRepository.get_parent_map to use bz2 not gzip for compression.
20
import bz2
1752.2.30 by Martin Pool
Start adding a RemoteBzrDir, etc
21
2490.2.5 by Aaron Bentley
Use GraphWalker.unique_ancestor to determine merge base
22
from bzrlib import (
23
    branch,
4017.3.2 by Robert Collins
Reduce the number of round trips required to create a repository over the network.
24
    bzrdir,
3192.1.1 by Andrew Bennetts
Add some -Dhpss debugging to get_parent_map.
25
    debug,
2490.2.5 by Aaron Bentley
Use GraphWalker.unique_ancestor to determine merge base
26
    errors,
3172.5.1 by Robert Collins
Create a RemoteRepository get_graph implementation and delegate get_parents_map to the real repository.
27
    graph,
2490.2.5 by Aaron Bentley
Use GraphWalker.unique_ancestor to determine merge base
28
    lockdir,
4022.1.6 by Robert Collins
Cherrypick and polish the RemoteSink for streaming push.
29
    pack,
2490.2.5 by Aaron Bentley
Use GraphWalker.unique_ancestor to determine merge base
30
    repository,
2948.3.1 by John Arbash Meinel
Fix bug #158333, make sure that Repository.fetch(self) is properly a no-op for all Repository implementations.
31
    revision,
3228.4.11 by John Arbash Meinel
Deprecations abound.
32
    symbol_versioning,
3691.2.2 by Martin Pool
Fix some problems in access to stacked repositories over hpss (#261315)
33
    urlutils,
2490.2.5 by Aaron Bentley
Use GraphWalker.unique_ancestor to determine merge base
34
)
2535.4.27 by Andrew Bennetts
Remove some unused imports.
35
from bzrlib.branch import BranchReferenceFormat
2018.5.174 by Andrew Bennetts
Various nits discovered by pyflakes.
36
from bzrlib.bzrdir import BzrDir, RemoteBzrDirFormat
2018.14.1 by Andrew Bennetts
Update to current hpss branch? Fix lots of test failures.
37
from bzrlib.decorators import needs_read_lock, needs_write_lock
3376.2.4 by Martin Pool
Remove every assert statement from bzrlib!
38
from bzrlib.errors import (
39
    NoSuchRevision,
40
    SmartProtocolError,
41
    )
2018.5.127 by Andrew Bennetts
Fix most of the lockable_files tests for RemoteBranchLockableFiles.
42
from bzrlib.lockable_files import LockableFiles
2018.6.1 by Robert Collins
Implement a BzrDir.open_branch smart server method for opening a branch without VFS.
43
from bzrlib.smart import client, vfs
3297.4.1 by Andrew Bennetts
Merge 'Add Branch.set_last_revision_info smart method'.
44
from bzrlib.revision import ensure_null, NULL_REVISION
3441.5.5 by Andrew Bennetts
Some small tweaks and comments.
45
from bzrlib.trace import mutter, note, warning
4029.2.1 by Robert Collins
Support streaming push to stacked branches.
46
from bzrlib.util import bencode
4022.1.6 by Robert Collins
Cherrypick and polish the RemoteSink for streaming push.
47
from bzrlib.versionedfile import record_to_fulltext_bytes
1752.2.30 by Martin Pool
Start adding a RemoteBzrDir, etc
48
3445.1.5 by John Arbash Meinel
allow passing a 'graph' object into Branch.update_revisions.
49
3786.2.3 by Andrew Bennetts
Remove duplicated 'call & translate errors' code in bzrlib.remote.
50
class _RpcHelper(object):
51
    """Mixin class that helps with issuing RPCs."""
52
53
    def _call(self, method, *args, **err_context):
54
        try:
55
            return self._client.call(method, *args)
56
        except errors.ErrorFromSmartServer, err:
57
            self._translate_error(err, **err_context)
3943.8.1 by Marius Kruger
remove all trailing whitespace from bzr source
58
3786.2.3 by Andrew Bennetts
Remove duplicated 'call & translate errors' code in bzrlib.remote.
59
    def _call_expecting_body(self, method, *args, **err_context):
60
        try:
61
            return self._client.call_expecting_body(method, *args)
62
        except errors.ErrorFromSmartServer, err:
63
            self._translate_error(err, **err_context)
3943.8.1 by Marius Kruger
remove all trailing whitespace from bzr source
64
3786.2.3 by Andrew Bennetts
Remove duplicated 'call & translate errors' code in bzrlib.remote.
65
    def _call_with_body_bytes_expecting_body(self, method, args, body_bytes,
66
                                             **err_context):
67
        try:
68
            return self._client.call_with_body_bytes_expecting_body(
69
                method, args, body_bytes)
70
        except errors.ErrorFromSmartServer, err:
71
            self._translate_error(err, **err_context)
3943.8.1 by Marius Kruger
remove all trailing whitespace from bzr source
72
2018.5.25 by Andrew Bennetts
Make sure RemoteBzrDirFormat is always registered (John Arbash Meinel, Robert Collins, Andrew Bennetts).
73
# Note: RemoteBzrDirFormat is in bzrdir.py
1752.2.30 by Martin Pool
Start adding a RemoteBzrDir, etc
74
3786.2.3 by Andrew Bennetts
Remove duplicated 'call & translate errors' code in bzrlib.remote.
75
class RemoteBzrDir(BzrDir, _RpcHelper):
2018.5.163 by Andrew Bennetts
Deal with various review comments from Robert.
76
    """Control directory on a remote server, accessed via bzr:// or similar."""
1752.2.30 by Martin Pool
Start adding a RemoteBzrDir, etc
77
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.
78
    def __init__(self, transport, format, _client=None):
2018.5.51 by Wouter van Heyst
Test and implement RemoteBranch.last_revision_info()
79
        """Construct a RemoteBzrDir.
80
81
        :param _client: Private parameter for testing. Disables probing and the
82
            use of a real bzrdir.
83
        """
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.
84
        BzrDir.__init__(self, transport, format)
1752.2.31 by Martin Pool
[broken] some support for write operations over hpss
85
        # this object holds a delegated bzrdir that uses file-level operations
86
        # to talk to the other side
2018.5.70 by Robert Collins
Only try to get real repositories when an operation requires them.
87
        self._real_bzrdir = None
2018.14.1 by Andrew Bennetts
Update to current hpss branch? Fix lots of test failures.
88
89
        if _client is None:
3313.2.3 by Andrew Bennetts
Deprecate Transport.get_shared_medium.
90
            medium = transport.get_smart_medium()
3431.3.2 by Andrew Bennetts
Remove 'base' from _SmartClient entirely, now that the medium has it.
91
            self._client = client._SmartClient(medium)
2018.14.1 by Andrew Bennetts
Update to current hpss branch? Fix lots of test failures.
92
        else:
93
            self._client = _client
94
            return
95
96
        path = self._path_for_remote_call(self._client)
3786.2.3 by Andrew Bennetts
Remove duplicated 'call & translate errors' code in bzrlib.remote.
97
        response = self._call('BzrDir.open', path)
2018.5.163 by Andrew Bennetts
Deal with various review comments from Robert.
98
        if response not in [('yes',), ('no',)]:
99
            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.
100
        if response == ('no',):
101
            raise errors.NotBranchError(path=transport.base)
1752.2.31 by Martin Pool
[broken] some support for write operations over hpss
102
2018.5.70 by Robert Collins
Only try to get real repositories when an operation requires them.
103
    def _ensure_real(self):
104
        """Ensure that there is a _real_bzrdir set.
105
2018.5.163 by Andrew Bennetts
Deal with various review comments from Robert.
106
        Used before calls to self._real_bzrdir.
2018.5.70 by Robert Collins
Only try to get real repositories when an operation requires them.
107
        """
108
        if not self._real_bzrdir:
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.
109
            self._real_bzrdir = BzrDir.open_from_transport(
110
                self.root_transport, _server_formats=False)
2018.5.70 by Robert Collins
Only try to get real repositories when an operation requires them.
111
3786.2.3 by Andrew Bennetts
Remove duplicated 'call & translate errors' code in bzrlib.remote.
112
    def _translate_error(self, err, **context):
113
        _translate_error(err, bzrdir=self, **context)
114
3650.3.13 by Aaron Bentley
Make cloning_metadir handle stacking requirements
115
    def cloning_metadir(self, stacked=False):
3242.3.28 by Aaron Bentley
Use repository acquisition policy for sprouting
116
        self._ensure_real()
3650.3.13 by Aaron Bentley
Make cloning_metadir handle stacking requirements
117
        return self._real_bzrdir.cloning_metadir(stacked)
3242.3.28 by Aaron Bentley
Use repository acquisition policy for sprouting
118
1752.2.39 by Martin Pool
[broken] implement upgrade apis on remote bzrdirs
119
    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.
120
        # as per meta1 formats - just delegate to the format object which may
121
        # be parameterised.
122
        result = self._format.repository_format.initialize(self, shared)
123
        if not isinstance(result, RemoteRepository):
124
            return self.open_repository()
125
        else:
126
            return result
1752.2.50 by Andrew Bennetts
Implement RemoteBzrDir.create_{branch,workingtree}
127
2796.2.19 by Aaron Bentley
Support reconfigure --lightweight-checkout
128
    def destroy_repository(self):
129
        """See BzrDir.destroy_repository"""
130
        self._ensure_real()
131
        self._real_bzrdir.destroy_repository()
132
1752.2.50 by Andrew Bennetts
Implement RemoteBzrDir.create_{branch,workingtree}
133
    def create_branch(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.
134
        # as per meta1 formats - just delegate to the format object which may
135
        # be parameterised.
136
        real_branch = self._format.get_branch_format().initialize(self)
137
        if not isinstance(real_branch, RemoteBranch):
138
            return RemoteBranch(self, self.find_repository(), real_branch)
139
        else:
140
            return real_branch
1752.2.50 by Andrew Bennetts
Implement RemoteBzrDir.create_{branch,workingtree}
141
2796.2.6 by Aaron Bentley
Implement destroy_branch
142
    def destroy_branch(self):
2796.2.16 by Aaron Bentley
Documentation updates from review
143
        """See BzrDir.destroy_branch"""
2796.2.6 by Aaron Bentley
Implement destroy_branch
144
        self._ensure_real()
145
        self._real_bzrdir.destroy_branch()
146
2955.5.3 by Vincent Ladeuil
Fix second unwanted connection by providing the right branch to create_checkout.
147
    def create_workingtree(self, revision_id=None, from_branch=None):
2018.5.174 by Andrew Bennetts
Various nits discovered by pyflakes.
148
        raise errors.NotLocalUrl(self.transport.base)
1752.2.39 by Martin Pool
[broken] implement upgrade apis on remote bzrdirs
149
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.
150
    def find_branch_format(self):
151
        """Find the branch 'format' for this bzrdir.
152
153
        This might be a synthetic object for e.g. RemoteBranch and SVN.
154
        """
155
        b = self.open_branch()
156
        return b._format
157
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.
158
    def get_branch_reference(self):
159
        """See BzrDir.get_branch_reference()."""
2018.14.1 by Andrew Bennetts
Update to current hpss branch? Fix lots of test failures.
160
        path = self._path_for_remote_call(self._client)
3786.2.3 by Andrew Bennetts
Remove duplicated 'call & translate errors' code in bzrlib.remote.
161
        response = self._call('BzrDir.open_branch', path)
2018.14.1 by Andrew Bennetts
Update to current hpss branch? Fix lots of test failures.
162
        if response[0] == 'ok':
163
            if response[1] == '':
164
                # branch at this location.
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.
165
                return None
2018.14.1 by Andrew Bennetts
Update to current hpss branch? Fix lots of test failures.
166
            else:
167
                # a branch reference, use the existing BranchReference logic.
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.
168
                return response[1]
2018.6.1 by Robert Collins
Implement a BzrDir.open_branch smart server method for opening a branch without VFS.
169
        else:
2555.1.1 by Martin Pool
Remove use of 'assert False' to raise an exception unconditionally
170
            raise errors.UnexpectedSmartServerResponse(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.
171
3211.4.1 by Robert Collins
* ``RemoteBzrDir._get_tree_branch`` no longer triggers ``_ensure_real``,
172
    def _get_tree_branch(self):
173
        """See BzrDir._get_tree_branch()."""
174
        return None, self.open_branch()
175
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.
176
    def open_branch(self, _unsupported=False):
3376.2.4 by Martin Pool
Remove every assert statement from bzrlib!
177
        if _unsupported:
178
            raise NotImplementedError('unsupported flag support not implemented yet.')
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.
179
        reference_url = self.get_branch_reference()
180
        if reference_url is None:
181
            # branch at this location.
182
            return RemoteBranch(self, self.find_repository())
183
        else:
184
            # a branch reference, use the existing BranchReference logic.
185
            format = BranchReferenceFormat()
186
            return format.open(self, _found=True, location=reference_url)
3943.8.1 by Marius Kruger
remove all trailing whitespace from bzr source
187
1752.2.31 by Martin Pool
[broken] some support for write operations over hpss
188
    def open_repository(self):
2018.14.1 by Andrew Bennetts
Update to current hpss branch? Fix lots of test failures.
189
        path = self._path_for_remote_call(self._client)
3221.3.3 by Robert Collins
* Hook up the new remote method ``RemoteBzrDir.find_repositoryV2`` so
190
        verb = 'BzrDir.find_repositoryV2'
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.
191
        try:
3786.2.3 by Andrew Bennetts
Remove duplicated 'call & translate errors' code in bzrlib.remote.
192
            response = self._call(verb, path)
193
        except errors.UnknownSmartMethod:
194
            verb = 'BzrDir.find_repository'
195
            response = self._call(verb, path)
3245.4.24 by Andrew Bennetts
Consistently raise errors from the server as ErrorFromSmartServer exceptions.
196
        if response[0] != 'ok':
197
            raise errors.UnexpectedSmartServerResponse(response)
3221.3.3 by Robert Collins
* Hook up the new remote method ``RemoteBzrDir.find_repositoryV2`` so
198
        if verb == 'BzrDir.find_repository':
199
            # servers that don't support the V2 method don't support external
200
            # references either.
201
            response = response + ('no', )
3376.2.4 by Martin Pool
Remove every assert statement from bzrlib!
202
        if not (len(response) == 5):
203
            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.
204
        if response[1] == '':
2018.5.118 by Robert Collins
Fix RemoteRepositoryFormat to have appropriate rich_root_data and support_tree_reference.
205
            format = RemoteRepositoryFormat()
2018.5.166 by Andrew Bennetts
Small changes in response to Aaron's review.
206
            format.rich_root_data = (response[2] == 'yes')
207
            format.supports_tree_reference = (response[3] == 'yes')
3221.3.1 by Robert Collins
* Repository formats have a new supported-feature attribute
208
            # No wire format to check this yet.
3221.3.3 by Robert Collins
* Hook up the new remote method ``RemoteBzrDir.find_repositoryV2`` so
209
            format.supports_external_lookups = (response[4] == 'yes')
3221.15.10 by Robert Collins
Add test that we can stack on a smart server from Jonathan Lange.
210
            # Used to support creating a real format instance when needed.
211
            format._creating_bzrdir = self
3990.5.1 by Andrew Bennetts
Add network_name() to RepositoryFormat.
212
            remote_repo = RemoteRepository(self, format)
213
            format._creating_repo = remote_repo
214
            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.
215
        else:
216
            raise errors.NoRepositoryPresent(self)
1752.2.30 by Martin Pool
Start adding a RemoteBzrDir, etc
217
2018.5.138 by Robert Collins
Merge bzr.dev.
218
    def open_workingtree(self, recommend_upgrade=True):
2445.1.1 by Andrew Bennetts
Make RemoteBzrDir.open_workingtree raise NoWorkingTree rather than NotLocalUrl
219
        self._ensure_real()
220
        if self._real_bzrdir.has_workingtree():
221
            raise errors.NotLocalUrl(self.root_transport)
222
        else:
223
            raise errors.NoWorkingTree(self.root_transport.base)
1752.2.50 by Andrew Bennetts
Implement RemoteBzrDir.create_{branch,workingtree}
224
2018.5.42 by Robert Collins
Various hopefully improvements, but wsgi is broken, handing over to spiv :).
225
    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.
226
        """Return the path to be used for this bzrdir in a remote call."""
2018.5.42 by Robert Collins
Various hopefully improvements, but wsgi is broken, handing over to spiv :).
227
        return client.remote_path_from_transport(self.root_transport)
2018.6.1 by Robert Collins
Implement a BzrDir.open_branch smart server method for opening a branch without VFS.
228
1752.2.31 by Martin Pool
[broken] some support for write operations over hpss
229
    def get_branch_transport(self, branch_format):
2018.5.162 by Andrew Bennetts
Add some missing _ensure_real calls, and a missing import.
230
        self._ensure_real()
1752.2.31 by Martin Pool
[broken] some support for write operations over hpss
231
        return self._real_bzrdir.get_branch_transport(branch_format)
232
1752.2.43 by Andrew Bennetts
Fix get_{branch,repository,workingtree}_transport.
233
    def get_repository_transport(self, repository_format):
2018.5.162 by Andrew Bennetts
Add some missing _ensure_real calls, and a missing import.
234
        self._ensure_real()
1752.2.43 by Andrew Bennetts
Fix get_{branch,repository,workingtree}_transport.
235
        return self._real_bzrdir.get_repository_transport(repository_format)
236
237
    def get_workingtree_transport(self, workingtree_format):
2018.5.162 by Andrew Bennetts
Add some missing _ensure_real calls, and a missing import.
238
        self._ensure_real()
1752.2.43 by Andrew Bennetts
Fix get_{branch,repository,workingtree}_transport.
239
        return self._real_bzrdir.get_workingtree_transport(workingtree_format)
240
1752.2.39 by Martin Pool
[broken] implement upgrade apis on remote bzrdirs
241
    def can_convert_format(self):
242
        """Upgrading of remote bzrdirs is not supported yet."""
243
        return False
244
245
    def needs_format_conversion(self, format=None):
246
        """Upgrading of remote bzrdirs is not supported yet."""
3943.2.5 by Martin Pool
deprecate needs_format_conversion(format=None)
247
        if format is None:
248
            symbol_versioning.warn(symbol_versioning.deprecated_in((1, 13, 0))
249
                % 'needs_format_conversion(format=None)')
1752.2.39 by Martin Pool
[broken] implement upgrade apis on remote bzrdirs
250
        return False
251
3242.3.37 by Aaron Bentley
Updates from reviews
252
    def clone(self, url, revision_id=None, force_new_repo=False,
253
              preserve_stacking=False):
2018.5.94 by Andrew Bennetts
Various small changes in aid of making tests pass (including deleting one invalid test).
254
        self._ensure_real()
255
        return self._real_bzrdir.clone(url, revision_id=revision_id,
3242.3.37 by Aaron Bentley
Updates from reviews
256
            force_new_repo=force_new_repo, preserve_stacking=preserve_stacking)
2018.5.94 by Andrew Bennetts
Various small changes in aid of making tests pass (including deleting one invalid test).
257
3567.1.3 by Michael Hudson
fix problem
258
    def get_config(self):
259
        self._ensure_real()
260
        return self._real_bzrdir.get_config()
261
1752.2.31 by Martin Pool
[broken] some support for write operations over hpss
262
1752.2.52 by Andrew Bennetts
Flesh out more Remote* methods needed to open and initialise remote branches/trees/repositories.
263
class RemoteRepositoryFormat(repository.RepositoryFormat):
2018.5.159 by Andrew Bennetts
Rename SmartClient to _SmartClient.
264
    """Format for repositories accessed over a _SmartClient.
1752.2.31 by Martin Pool
[broken] some support for write operations over hpss
265
1752.2.50 by Andrew Bennetts
Implement RemoteBzrDir.create_{branch,workingtree}
266
    Instances of this repository are represented by RemoteRepository
1752.2.31 by Martin Pool
[broken] some support for write operations over hpss
267
    instances.
2018.5.118 by Robert Collins
Fix RemoteRepositoryFormat to have appropriate rich_root_data and support_tree_reference.
268
3128.1.3 by Vincent Ladeuil
Since we are there s/parameteris.*/parameteriz&/.
269
    The RemoteRepositoryFormat is parameterized during construction
2018.5.118 by Robert Collins
Fix RemoteRepositoryFormat to have appropriate rich_root_data and support_tree_reference.
270
    to reflect the capabilities of the real, remote format. Specifically
2018.5.138 by Robert Collins
Merge bzr.dev.
271
    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.
272
    on a per instance basis, and are not set (and should not be) at
273
    the class level.
3990.5.3 by Robert Collins
Docs and polish on RepositoryFormat.network_name.
274
4032.1.1 by John Arbash Meinel
Merge the removal of all trailing whitespace, and resolve conflicts.
275
    :ivar _custom_format: If set, a specific concrete repository format that
3990.5.3 by Robert Collins
Docs and polish on RepositoryFormat.network_name.
276
        will be used when initializing a repository with this
277
        RemoteRepositoryFormat.
278
    :ivar _creating_repo: If set, the repository object that this
279
        RemoteRepositoryFormat was created for: it can be called into
3990.5.4 by Robert Collins
Review feedback.
280
        to obtain data like the network name.
1752.2.31 by Martin Pool
[broken] some support for write operations over hpss
281
    """
282
3543.1.2 by Michael Hudson
the two character fix
283
    _matchingbzrdir = RemoteBzrDirFormat()
1752.2.31 by Martin Pool
[broken] some support for write operations over hpss
284
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.
285
    def __init__(self):
286
        repository.RepositoryFormat.__init__(self)
287
        self._custom_format = None
4017.3.2 by Robert Collins
Reduce the number of round trips required to create a repository over the network.
288
        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.
289
        self._creating_bzrdir = None
290
291
    def _vfs_initialize(self, a_bzrdir, shared):
292
        """Helper for common code in initialize."""
293
        if self._custom_format:
294
            # Custom format requested
295
            result = self._custom_format.initialize(a_bzrdir, shared=shared)
296
        elif self._creating_bzrdir is not None:
297
            # Use the format that the repository we were created to back
298
            # has.
299
            prior_repo = self._creating_bzrdir.open_repository()
300
            prior_repo._ensure_real()
301
            result = prior_repo._real_repository._format.initialize(
302
                a_bzrdir, shared=shared)
303
        else:
304
            # assume that a_bzr is a RemoteBzrDir but the smart server didn't
305
            # support remote initialization.
306
            # We delegate to a real object at this point (as RemoteBzrDir
307
            # delegate to the repository format which would lead to infinite
308
            # recursion if we just called a_bzrdir.create_repository.
309
            a_bzrdir._ensure_real()
310
            result = a_bzrdir._real_bzrdir.create_repository(shared=shared)
311
        if not isinstance(result, RemoteRepository):
312
            return self.open(a_bzrdir)
313
        else:
314
            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.
315
1752.2.52 by Andrew Bennetts
Flesh out more Remote* methods needed to open and initialise remote branches/trees/repositories.
316
    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.
317
        # Being asked to create on a non RemoteBzrDir:
318
        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.
319
            return self._vfs_initialize(a_bzrdir, shared)
320
        medium = a_bzrdir._client._medium
321
        if medium._is_remote_before((1, 13)):
322
            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.
323
        # Creating on a remote bzr dir.
324
        # 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.
325
        if self._custom_format:
4017.3.2 by Robert Collins
Reduce the number of round trips required to create a repository over the network.
326
            network_name = self._custom_format.network_name()
327
        else:
328
            # Select the current bzrlib default and ask for that.
329
            reference_bzrdir_format = bzrdir.format_registry.get('default')()
330
            reference_format = reference_bzrdir_format.repository_format
331
            network_name = reference_format.network_name()
332
        # 2) try direct creation via RPC
333
        path = a_bzrdir._path_for_remote_call(a_bzrdir._client)
334
        verb = 'BzrDir.create_repository'
335
        if shared:
336
            shared_str = 'True'
337
        else:
338
            shared_str = 'False'
339
        try:
340
            response = a_bzrdir._call(verb, path, network_name, shared_str)
341
        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.
342
            # Fallback - use vfs methods
343
            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.
344
        else:
345
            # Turn the response into a RemoteRepository object.
346
            format = RemoteRepositoryFormat()
347
            format.rich_root_data = (response[1] == 'yes')
348
            format.supports_tree_reference = (response[2] == 'yes')
349
            format.supports_external_lookups = (response[3] == 'yes')
350
            format._network_name = response[4]
351
            # Used to support creating a real format instance when needed.
352
            format._creating_bzrdir = a_bzrdir
353
            remote_repo = RemoteRepository(a_bzrdir, format)
354
            format._creating_repo = remote_repo
355
            return remote_repo
3943.8.1 by Marius Kruger
remove all trailing whitespace from bzr source
356
1752.2.52 by Andrew Bennetts
Flesh out more Remote* methods needed to open and initialise remote branches/trees/repositories.
357
    def open(self, a_bzrdir):
3376.2.4 by Martin Pool
Remove every assert statement from bzrlib!
358
        if not isinstance(a_bzrdir, RemoteBzrDir):
359
            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.
360
        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.
361
362
    def get_format_description(self):
363
        return 'bzr remote repository'
364
365
    def __eq__(self, other):
1752.2.87 by Andrew Bennetts
Make tests pass.
366
        return self.__class__ == other.__class__
367
2018.5.118 by Robert Collins
Fix RemoteRepositoryFormat to have appropriate rich_root_data and support_tree_reference.
368
    def check_conversion_target(self, target_format):
369
        if self.rich_root_data and not target_format.rich_root_data:
370
            raise errors.BadConversionTarget(
371
                'Does not support rich root data.', target_format)
2018.5.138 by Robert Collins
Merge bzr.dev.
372
        if (self.supports_tree_reference and
373
            not getattr(target_format, 'supports_tree_reference', False)):
2018.5.118 by Robert Collins
Fix RemoteRepositoryFormat to have appropriate rich_root_data and support_tree_reference.
374
            raise errors.BadConversionTarget(
375
                'Does not support nested trees', target_format)
1752.2.52 by Andrew Bennetts
Flesh out more Remote* methods needed to open and initialise remote branches/trees/repositories.
376
3990.5.1 by Andrew Bennetts
Add network_name() to RepositoryFormat.
377
    def network_name(self):
4017.3.2 by Robert Collins
Reduce the number of round trips required to create a repository over the network.
378
        if self._network_name:
379
            return self._network_name
3990.5.1 by Andrew Bennetts
Add network_name() to RepositoryFormat.
380
        self._creating_repo._ensure_real()
381
        return self._creating_repo._real_repository._format.network_name()
382
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)
383
    @property
384
    def _serializer(self):
385
        # We should only be getting asked for the serializer for
4022.1.3 by Robert Collins
Make a comment easier to read.
386
        # RemoteRepositoryFormat objects when the RemoteRepositoryFormat object
387
        # is a concrete instance for a RemoteRepository. In this case we know
388
        # the creating_repo and can use it to supply the 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)
389
        self._creating_repo._ensure_real()
390
        return self._creating_repo._real_repository._format._serializer
391
1752.2.31 by Martin Pool
[broken] some support for write operations over hpss
392
3786.2.3 by Andrew Bennetts
Remove duplicated 'call & translate errors' code in bzrlib.remote.
393
class RemoteRepository(_RpcHelper):
1752.2.31 by Martin Pool
[broken] some support for write operations over hpss
394
    """Repository accessed over rpc.
395
2018.5.163 by Andrew Bennetts
Deal with various review comments from Robert.
396
    For the moment most operations are performed using local transport-backed
397
    Repository objects.
1752.2.31 by Martin Pool
[broken] some support for write operations over hpss
398
    """
399
2018.5.118 by Robert Collins
Fix RemoteRepositoryFormat to have appropriate rich_root_data and support_tree_reference.
400
    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.
401
        """Create a RemoteRepository instance.
3943.8.1 by Marius Kruger
remove all trailing whitespace from bzr source
402
2018.5.34 by Robert Collins
Get test_remote.BasicRemoteObjectTests.test_open_remote_branch passing by implementing a remote method BzrDir.find_repository.
403
        :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.
404
        :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.
405
        :param real_repository: If not None, a local implementation of the
406
            repository logic for the repository, usually accessing the data
407
            via the VFS.
2018.5.57 by Robert Collins
Implement RemoteRepository.is_shared (Robert Collins, Vincent Ladeuil).
408
        :param _client: Private testing parameter - override the smart client
409
            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.
410
        """
411
        if real_repository:
2018.5.36 by Andrew Bennetts
Fix typo, and clean up some ununsed import warnings from pyflakes at the same time.
412
            self._real_repository = real_repository
2018.5.70 by Robert Collins
Only try to get real repositories when an operation requires them.
413
        else:
414
            self._real_repository = None
1752.2.50 by Andrew Bennetts
Implement RemoteBzrDir.create_{branch,workingtree}
415
        self.bzrdir = remote_bzrdir
2018.5.57 by Robert Collins
Implement RemoteRepository.is_shared (Robert Collins, Vincent Ladeuil).
416
        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.
417
            self._client = remote_bzrdir._client
2018.5.57 by Robert Collins
Implement RemoteRepository.is_shared (Robert Collins, Vincent Ladeuil).
418
        else:
419
            self._client = _client
2018.5.118 by Robert Collins
Fix RemoteRepositoryFormat to have appropriate rich_root_data and support_tree_reference.
420
        self._format = format
2018.5.75 by Andrew Bennetts
Add Repository.{dont_,}leave_lock_in_place.
421
        self._lock_mode = None
422
        self._lock_token = None
423
        self._lock_count = 0
2018.5.78 by Andrew Bennetts
Implement RemoteRepository.lock_write/unlock to expect and send tokens over the
424
        self._leave_lock = False
3835.1.12 by Aaron Bentley
Unify CachingExtraParentsProvider and CachingParentsProvider.
425
        self._unstacked_provider = graph.CachingParentsProvider(
3896.1.1 by Andrew Bennetts
Remove broken debugging cruft, and some unused imports.
426
            get_parent_map=self._get_parent_map_rpc)
3835.1.12 by Aaron Bentley
Unify CachingExtraParentsProvider and CachingParentsProvider.
427
        self._unstacked_provider.disable_cache()
2951.1.10 by Robert Collins
Peer review feedback with Ian.
428
        # For tests:
429
        # These depend on the actual remote format, so force them off for
430
        # maximum compatibility. XXX: In future these should depend on the
431
        # remote repository instance, but this is irrelevant until we perform
432
        # 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.
433
        self._reconcile_does_inventory_gc = False
434
        self._reconcile_fixes_text_parents = False
2951.1.3 by Robert Collins
Partial support for native reconcile with packs.
435
        self._reconcile_backsup_inventory = False
2592.4.5 by Martin Pool
Add Repository.base on all repositories.
436
        self.base = self.bzrdir.transport.base
3221.12.1 by Robert Collins
Backport development1 format (stackable packs) to before-shallow-branches.
437
        # Additional places to query for data.
438
        self._fallback_repositories = []
2592.4.5 by Martin Pool
Add Repository.base on all repositories.
439
440
    def __str__(self):
441
        return "%s(%s)" % (self.__class__.__name__, self.base)
442
443
    __repr__ = __str__
1752.2.52 by Andrew Bennetts
Flesh out more Remote* methods needed to open and initialise remote branches/trees/repositories.
444
3825.4.1 by Andrew Bennetts
Add suppress_errors to abort_write_group.
445
    def abort_write_group(self, suppress_errors=False):
2617.6.7 by Robert Collins
More review feedback.
446
        """Complete a write group on the decorated repository.
3943.8.1 by Marius Kruger
remove all trailing whitespace from bzr source
447
2617.6.2 by Robert Collins
Add abort_write_group and wire write_groups into fetch and commit.
448
        Smart methods peform operations in a single step so this api
2617.6.6 by Robert Collins
Some review feedback.
449
        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.
450
        for older plugins that don't use e.g. the CommitBuilder
451
        facility.
3825.4.6 by Andrew Bennetts
Document the suppress_errors flag in the docstring.
452
453
        :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.
454
        """
455
        self._ensure_real()
3825.4.1 by Andrew Bennetts
Add suppress_errors to abort_write_group.
456
        return self._real_repository.abort_write_group(
457
            suppress_errors=suppress_errors)
2617.6.2 by Robert Collins
Add abort_write_group and wire write_groups into fetch and commit.
458
459
    def commit_write_group(self):
2617.6.7 by Robert Collins
More review feedback.
460
        """Complete a write group on the decorated repository.
3943.8.1 by Marius Kruger
remove all trailing whitespace from bzr source
461
2617.6.2 by Robert Collins
Add abort_write_group and wire write_groups into fetch and commit.
462
        Smart methods peform operations in a single step so this api
2617.6.6 by Robert Collins
Some review feedback.
463
        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.
464
        for older plugins that don't use e.g. the CommitBuilder
465
        facility.
466
        """
467
        self._ensure_real()
468
        return self._real_repository.commit_write_group()
2617.6.1 by Robert Collins
* New method on Repository - ``start_write_group``, ``end_write_group``
469
4002.1.1 by Andrew Bennetts
Implement suspend_write_group/resume_write_group.
470
    def resume_write_group(self, tokens):
471
        self._ensure_real()
472
        return self._real_repository.resume_write_group(tokens)
473
474
    def suspend_write_group(self):
475
        self._ensure_real()
476
        return self._real_repository.suspend_write_group()
477
2018.5.70 by Robert Collins
Only try to get real repositories when an operation requires them.
478
    def _ensure_real(self):
479
        """Ensure that there is a _real_repository set.
480
2018.5.163 by Andrew Bennetts
Deal with various review comments from Robert.
481
        Used before calls to self._real_repository.
2018.5.70 by Robert Collins
Only try to get real repositories when an operation requires them.
482
        """
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.
483
        if self._real_repository is None:
2018.5.70 by Robert Collins
Only try to get real repositories when an operation requires them.
484
            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.
485
            self._set_real_repository(
486
                self.bzrdir._real_bzrdir.open_repository())
2018.5.70 by Robert Collins
Only try to get real repositories when an operation requires them.
487
3533.3.1 by Andrew Bennetts
Remove duplication of error translation in bzrlib/remote.py.
488
    def _translate_error(self, err, **context):
489
        self.bzrdir._translate_error(err, repository=self, **context)
490
2988.1.2 by Robert Collins
New Repository API find_text_key_references for use by reconcile and check.
491
    def find_text_key_references(self):
492
        """Find the text key references within the repository.
493
494
        :return: a dictionary mapping (file_id, revision_id) tuples to altered file-ids to an iterable of
495
        revision_ids. Each altered file-ids has the exact revision_ids that
496
        altered it listed explicitly.
497
        :return: A dictionary mapping text keys ((fileid, revision_id) tuples)
498
            to whether they were referred to by the inventory of the
499
            revision_id that they contain. The inventory texts from all present
500
            revision ids are assessed to generate this report.
501
        """
502
        self._ensure_real()
503
        return self._real_repository.find_text_key_references()
504
2988.1.3 by Robert Collins
Add a new repositoy method _generate_text_key_index for use by reconcile/check.
505
    def _generate_text_key_index(self):
506
        """Generate a new text key index for the repository.
507
508
        This is an expensive function that will take considerable time to run.
509
510
        :return: A dict mapping (file_id, revision_id) tuples to a list of
511
            parents, also (file_id, revision_id) tuples.
512
        """
513
        self._ensure_real()
514
        return self._real_repository._generate_text_key_index()
515
3287.6.1 by Robert Collins
* ``VersionedFile.get_graph`` is deprecated, with no replacement method.
516
    @symbol_versioning.deprecated_method(symbol_versioning.one_four)
2018.5.67 by Wouter van Heyst
Implement RemoteRepository.get_revision_graph (Wouter van Heyst, Robert Collins)
517
    def get_revision_graph(self, revision_id=None):
518
        """See Repository.get_revision_graph()."""
3287.6.4 by Robert Collins
Fix up deprecation warnings for get_revision_graph.
519
        return self._get_revision_graph(revision_id)
520
521
    def _get_revision_graph(self, revision_id):
522
        """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)
523
        if revision_id is None:
524
            revision_id = ''
2948.3.1 by John Arbash Meinel
Fix bug #158333, make sure that Repository.fetch(self) is properly a no-op for all Repository implementations.
525
        elif revision.is_null(revision_id):
2018.5.67 by Wouter van Heyst
Implement RemoteRepository.get_revision_graph (Wouter van Heyst, Robert Collins)
526
            return {}
527
528
        path = self.bzrdir._path_for_remote_call(self._client)
3786.2.3 by Andrew Bennetts
Remove duplicated 'call & translate errors' code in bzrlib.remote.
529
        response = self._call_expecting_body(
530
            '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.
531
        response_tuple, response_handler = response
532
        if response_tuple[0] != 'ok':
533
            raise errors.UnexpectedSmartServerResponse(response_tuple)
534
        coded = response_handler.read_body_bytes()
3245.4.24 by Andrew Bennetts
Consistently raise errors from the server as ErrorFromSmartServer exceptions.
535
        if coded == '':
536
            # no revisions in this repository!
537
            return {}
538
        lines = coded.split('\n')
539
        revision_graph = {}
540
        for line in lines:
541
            d = tuple(line.split())
542
            revision_graph[d[0]] = d[1:]
3943.8.1 by Marius Kruger
remove all trailing whitespace from bzr source
543
3245.4.24 by Andrew Bennetts
Consistently raise errors from the server as ErrorFromSmartServer exceptions.
544
        return revision_graph
2018.5.67 by Wouter van Heyst
Implement RemoteRepository.get_revision_graph (Wouter van Heyst, Robert Collins)
545
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)
546
    def _get_sink(self):
547
        """See Repository._get_sink()."""
4022.1.6 by Robert Collins
Cherrypick and polish the RemoteSink for streaming push.
548
        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)
549
2018.5.40 by Robert Collins
Implement a remote Repository.has_revision method.
550
    def has_revision(self, revision_id):
551
        """See Repository.has_revision()."""
3172.3.1 by Robert Collins
Repository has a new method ``has_revisions`` which signals the presence
552
        if revision_id == NULL_REVISION:
2018.14.1 by Andrew Bennetts
Update to current hpss branch? Fix lots of test failures.
553
            # The null revision is always present.
554
            return True
2018.5.42 by Robert Collins
Various hopefully improvements, but wsgi is broken, handing over to spiv :).
555
        path = self.bzrdir._path_for_remote_call(self._client)
3786.2.3 by Andrew Bennetts
Remove duplicated 'call & translate errors' code in bzrlib.remote.
556
        response = self._call('Repository.has_revision', path, revision_id)
3376.2.4 by Martin Pool
Remove every assert statement from bzrlib!
557
        if response[0] not in ('yes', 'no'):
3245.4.58 by Andrew Bennetts
Unpack call_expecting_body's return value into variables, to avoid lots of ugly subscripting.
558
            raise errors.UnexpectedSmartServerResponse(response)
3691.2.2 by Martin Pool
Fix some problems in access to stacked repositories over hpss (#261315)
559
        if response[0] == 'yes':
560
            return True
561
        for fallback_repo in self._fallback_repositories:
562
            if fallback_repo.has_revision(revision_id):
563
                return True
564
        return False
2018.5.40 by Robert Collins
Implement a remote Repository.has_revision method.
565
3172.3.1 by Robert Collins
Repository has a new method ``has_revisions`` which signals the presence
566
    def has_revisions(self, revision_ids):
567
        """See Repository.has_revisions()."""
3691.2.2 by Martin Pool
Fix some problems in access to stacked repositories over hpss (#261315)
568
        # FIXME: This does many roundtrips, particularly when there are
569
        # fallback repositories.  -- mbp 20080905
3172.3.1 by Robert Collins
Repository has a new method ``has_revisions`` which signals the presence
570
        result = set()
571
        for revision_id in revision_ids:
572
            if self.has_revision(revision_id):
573
                result.add(revision_id)
574
        return result
575
2617.6.9 by Robert Collins
Merge bzr.dev.
576
    def has_same_location(self, other):
2592.3.162 by Robert Collins
Remove some arbitrary differences from bzr.dev.
577
        return (self.__class__ == other.__class__ and
578
                self.bzrdir.transport.base == other.bzrdir.transport.base)
3835.1.1 by Aaron Bentley
Stack get_parent_map on fallback repos
579
2490.2.21 by Aaron Bentley
Rename graph to deprecated_graph
580
    def get_graph(self, other_repository=None):
581
        """Return the graph for this repository format"""
3835.1.17 by Aaron Bentley
Fix stacking bug
582
        parents_provider = self._make_parents_provider(other_repository)
3441.5.24 by Andrew Bennetts
Remove RemoteGraph experiment.
583
        return graph.Graph(parents_provider)
2490.2.5 by Aaron Bentley
Use GraphWalker.unique_ancestor to determine merge base
584
2018.14.1 by Andrew Bennetts
Update to current hpss branch? Fix lots of test failures.
585
    def gather_stats(self, revid=None, committers=None):
2018.5.62 by Robert Collins
Stub out RemoteRepository.gather_stats while its implemented in parallel.
586
        """See Repository.gather_stats()."""
2018.10.3 by v.ladeuil+lp at free
more tests for gather_stats
587
        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.
588
        # revid can be None to indicate no revisions, not just NULL_REVISION
589
        if revid is None or revision.is_null(revid):
2018.10.3 by v.ladeuil+lp at free
more tests for gather_stats
590
            fmt_revid = ''
591
        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.
592
            fmt_revid = revid
2018.14.1 by Andrew Bennetts
Update to current hpss branch? Fix lots of test failures.
593
        if committers is None or not committers:
2018.10.3 by v.ladeuil+lp at free
more tests for gather_stats
594
            fmt_committers = 'no'
595
        else:
596
            fmt_committers = 'yes'
3786.2.3 by Andrew Bennetts
Remove duplicated 'call & translate errors' code in bzrlib.remote.
597
        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.
598
            '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.
599
        if response_tuple[0] != 'ok':
600
            raise errors.UnexpectedSmartServerResponse(response_tuple)
2018.10.3 by v.ladeuil+lp at free
more tests for gather_stats
601
3245.4.58 by Andrew Bennetts
Unpack call_expecting_body's return value into variables, to avoid lots of ugly subscripting.
602
        body = response_handler.read_body_bytes()
2018.10.3 by v.ladeuil+lp at free
more tests for gather_stats
603
        result = {}
604
        for line in body.split('\n'):
605
            if not line:
606
                continue
607
            key, val_text = line.split(':')
608
            if key in ('revisions', 'size', 'committers'):
609
                result[key] = int(val_text)
610
            elif key in ('firstrev', 'latestrev'):
611
                values = val_text.split(' ')[1:]
612
                result[key] = (float(values[0]), long(values[1]))
613
614
        return result
2018.5.62 by Robert Collins
Stub out RemoteRepository.gather_stats while its implemented in parallel.
615
3140.1.2 by Aaron Bentley
Add ability to find branches inside repositories
616
    def find_branches(self, using=False):
617
        """See Repository.find_branches()."""
618
        # should be an API call to the server.
619
        self._ensure_real()
620
        return self._real_repository.find_branches(using=using)
621
2018.5.60 by Robert Collins
More missing methods from RemoteBranch and RemoteRepository to let 'info' get further.
622
    def get_physical_lock_status(self):
623
        """See Repository.get_physical_lock_status()."""
3015.2.10 by Robert Collins
Fix regression due to other pack related fixes in tests with packs not-default.
624
        # should be an API call to the server.
625
        self._ensure_real()
626
        return self._real_repository.get_physical_lock_status()
2018.5.60 by Robert Collins
More missing methods from RemoteBranch and RemoteRepository to let 'info' get further.
627
2617.6.1 by Robert Collins
* New method on Repository - ``start_write_group``, ``end_write_group``
628
    def is_in_write_group(self):
629
        """Return True if there is an open write group.
630
631
        write groups are only applicable locally for the smart server..
632
        """
633
        if self._real_repository:
634
            return self._real_repository.is_in_write_group()
635
636
    def is_locked(self):
637
        return self._lock_count >= 1
638
2018.5.57 by Robert Collins
Implement RemoteRepository.is_shared (Robert Collins, Vincent Ladeuil).
639
    def is_shared(self):
640
        """See Repository.is_shared()."""
641
        path = self.bzrdir._path_for_remote_call(self._client)
3786.2.3 by Andrew Bennetts
Remove duplicated 'call & translate errors' code in bzrlib.remote.
642
        response = self._call('Repository.is_shared', path)
3376.2.4 by Martin Pool
Remove every assert statement from bzrlib!
643
        if response[0] not in ('yes', 'no'):
644
            raise SmartProtocolError('unexpected response code %s' % (response,))
2018.5.57 by Robert Collins
Implement RemoteRepository.is_shared (Robert Collins, Vincent Ladeuil).
645
        return response[0] == 'yes'
646
2904.1.1 by Robert Collins
* New method ``bzrlib.repository.Repository.is_write_locked`` useful for
647
    def is_write_locked(self):
648
        return self._lock_mode == 'w'
649
2018.5.60 by Robert Collins
More missing methods from RemoteBranch and RemoteRepository to let 'info' get further.
650
    def lock_read(self):
651
        # wrong eventually - want a local lock cache context
2018.5.75 by Andrew Bennetts
Add Repository.{dont_,}leave_lock_in_place.
652
        if not self._lock_mode:
653
            self._lock_mode = 'r'
654
            self._lock_count = 1
3835.1.15 by Aaron Bentley
Allow miss caching to be disabled.
655
            self._unstacked_provider.enable_cache(cache_misses=False)
2018.5.78 by Andrew Bennetts
Implement RemoteRepository.lock_write/unlock to expect and send tokens over the
656
            if self._real_repository is not None:
657
                self._real_repository.lock_read()
2018.5.75 by Andrew Bennetts
Add Repository.{dont_,}leave_lock_in_place.
658
        else:
659
            self._lock_count += 1
2018.5.78 by Andrew Bennetts
Implement RemoteRepository.lock_write/unlock to expect and send tokens over the
660
2018.14.1 by Andrew Bennetts
Update to current hpss branch? Fix lots of test failures.
661
    def _remote_lock_write(self, token):
2018.5.78 by Andrew Bennetts
Implement RemoteRepository.lock_write/unlock to expect and send tokens over the
662
        path = self.bzrdir._path_for_remote_call(self._client)
663
        if token is None:
664
            token = ''
3786.2.3 by Andrew Bennetts
Remove duplicated 'call & translate errors' code in bzrlib.remote.
665
        err_context = {'token': token}
666
        response = self._call('Repository.lock_write', path, token,
667
                              **err_context)
2018.5.78 by Andrew Bennetts
Implement RemoteRepository.lock_write/unlock to expect and send tokens over the
668
        if response[0] == 'ok':
669
            ok, token = response
670
            return token
671
        else:
2555.1.1 by Martin Pool
Remove use of 'assert False' to raise an exception unconditionally
672
            raise errors.UnexpectedSmartServerResponse(response)
2018.5.60 by Robert Collins
More missing methods from RemoteBranch and RemoteRepository to let 'info' get further.
673
3692.1.1 by Andrew Bennetts
Make RemoteBranch.lock_write lock the repository too.
674
    def lock_write(self, token=None, _skip_rpc=False):
2018.5.75 by Andrew Bennetts
Add Repository.{dont_,}leave_lock_in_place.
675
        if not self._lock_mode:
3692.1.1 by Andrew Bennetts
Make RemoteBranch.lock_write lock the repository too.
676
            if _skip_rpc:
677
                if self._lock_token is not None:
678
                    if token != self._lock_token:
3695.1.1 by Andrew Bennetts
Remove some unused imports and fix a couple of trivially broken raise statements.
679
                        raise errors.TokenMismatch(token, self._lock_token)
3692.1.1 by Andrew Bennetts
Make RemoteBranch.lock_write lock the repository too.
680
                self._lock_token = token
681
            else:
682
                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.
683
            # if self._lock_token is None, then this is something like packs or
684
            # svn where we don't get to lock the repo, or a weave style repository
685
            # where we cannot lock it over the wire and attempts to do so will
686
            # fail.
2018.5.78 by Andrew Bennetts
Implement RemoteRepository.lock_write/unlock to expect and send tokens over the
687
            if self._real_repository is not None:
688
                self._real_repository.lock_write(token=self._lock_token)
689
            if token is not None:
690
                self._leave_lock = True
691
            else:
692
                self._leave_lock = False
2018.5.75 by Andrew Bennetts
Add Repository.{dont_,}leave_lock_in_place.
693
            self._lock_mode = 'w'
694
            self._lock_count = 1
3835.1.15 by Aaron Bentley
Allow miss caching to be disabled.
695
            self._unstacked_provider.enable_cache(cache_misses=False)
2018.5.75 by Andrew Bennetts
Add Repository.{dont_,}leave_lock_in_place.
696
        elif self._lock_mode == 'r':
2018.14.1 by Andrew Bennetts
Update to current hpss branch? Fix lots of test failures.
697
            raise errors.ReadOnlyError(self)
2018.5.75 by Andrew Bennetts
Add Repository.{dont_,}leave_lock_in_place.
698
        else:
699
            self._lock_count += 1
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.
700
        return self._lock_token or None
2018.5.75 by Andrew Bennetts
Add Repository.{dont_,}leave_lock_in_place.
701
702
    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.
703
        if not self._lock_token:
704
            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
705
        self._leave_lock = True
2018.5.75 by Andrew Bennetts
Add Repository.{dont_,}leave_lock_in_place.
706
707
    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.
708
        if not self._lock_token:
3015.2.15 by Robert Collins
Review feedback.
709
            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
710
        self._leave_lock = False
2018.5.75 by Andrew Bennetts
Add Repository.{dont_,}leave_lock_in_place.
711
712
    def _set_real_repository(self, repository):
713
        """Set the _real_repository for this repository.
714
715
        :param repository: The repository to fallback to for non-hpss
716
            implemented operations.
717
        """
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.
718
        if self._real_repository is not None:
719
            raise AssertionError('_real_repository is already set')
3376.2.4 by Martin Pool
Remove every assert statement from bzrlib!
720
        if isinstance(repository, RemoteRepository):
721
            raise AssertionError()
2018.5.75 by Andrew Bennetts
Add Repository.{dont_,}leave_lock_in_place.
722
        self._real_repository = repository
3691.2.12 by Martin Pool
Add test for coping without Branch.get_stacked_on_url
723
        for fb in self._fallback_repositories:
724
            self._real_repository.add_fallback_repository(fb)
2018.5.75 by Andrew Bennetts
Add Repository.{dont_,}leave_lock_in_place.
725
        if self._lock_mode == 'w':
726
            # if we are already locked, the real repository must be able to
727
            # acquire the lock with our token.
728
            self._real_repository.lock_write(self._lock_token)
2018.14.1 by Andrew Bennetts
Update to current hpss branch? Fix lots of test failures.
729
        elif self._lock_mode == 'r':
730
            self._real_repository.lock_read()
2018.5.60 by Robert Collins
More missing methods from RemoteBranch and RemoteRepository to let 'info' get further.
731
2617.6.1 by Robert Collins
* New method on Repository - ``start_write_group``, ``end_write_group``
732
    def start_write_group(self):
733
        """Start a write group on the decorated repository.
3943.8.1 by Marius Kruger
remove all trailing whitespace from bzr source
734
2617.6.1 by Robert Collins
* New method on Repository - ``start_write_group``, ``end_write_group``
735
        Smart methods peform operations in a single step so this api
2617.6.6 by Robert Collins
Some review feedback.
736
        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``
737
        for older plugins that don't use e.g. the CommitBuilder
738
        facility.
739
        """
740
        self._ensure_real()
741
        return self._real_repository.start_write_group()
742
2018.5.78 by Andrew Bennetts
Implement RemoteRepository.lock_write/unlock to expect and send tokens over the
743
    def _unlock(self, token):
744
        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.
745
        if not token:
746
            # with no token the remote repository is not persistently locked.
747
            return
3786.2.3 by Andrew Bennetts
Remove duplicated 'call & translate errors' code in bzrlib.remote.
748
        err_context = {'token': token}
749
        response = self._call('Repository.unlock', path, token,
750
                              **err_context)
2018.5.78 by Andrew Bennetts
Implement RemoteRepository.lock_write/unlock to expect and send tokens over the
751
        if response == ('ok',):
752
            return
753
        else:
2555.1.1 by Martin Pool
Remove use of 'assert False' to raise an exception unconditionally
754
            raise errors.UnexpectedSmartServerResponse(response)
2018.5.78 by Andrew Bennetts
Implement RemoteRepository.lock_write/unlock to expect and send tokens over the
755
2018.5.60 by Robert Collins
More missing methods from RemoteBranch and RemoteRepository to let 'info' get further.
756
    def unlock(self):
2018.5.75 by Andrew Bennetts
Add Repository.{dont_,}leave_lock_in_place.
757
        self._lock_count -= 1
2592.3.244 by Martin Pool
unlock while in a write group now aborts the write group, unlocks, and errors.
758
        if self._lock_count > 0:
759
            return
3835.1.8 by Aaron Bentley
Make UnstackedParentsProvider manage the cache
760
        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.
761
        old_mode = self._lock_mode
762
        self._lock_mode = None
763
        try:
764
            # The real repository is responsible at present for raising an
765
            # exception if it's in an unfinished write group.  However, it
766
            # normally will *not* actually remove the lock from disk - that's
767
            # done by the server on receiving the Repository.unlock call.
768
            # 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
769
            if self._real_repository is not None:
770
                self._real_repository.unlock()
2592.3.244 by Martin Pool
unlock while in a write group now aborts the write group, unlocks, and errors.
771
        finally:
772
            # The rpc-level lock should be released even if there was a
773
            # problem releasing the vfs-based lock.
774
            if old_mode == 'w':
2018.5.163 by Andrew Bennetts
Deal with various review comments from Robert.
775
                # Only write-locked repositories need to make a remote method
776
                # call to perfom the unlock.
2592.3.244 by Martin Pool
unlock while in a write group now aborts the write group, unlocks, and errors.
777
                old_token = self._lock_token
778
                self._lock_token = None
779
                if not self._leave_lock:
780
                    self._unlock(old_token)
2018.5.60 by Robert Collins
More missing methods from RemoteBranch and RemoteRepository to let 'info' get further.
781
782
    def break_lock(self):
2018.5.78 by Andrew Bennetts
Implement RemoteRepository.lock_write/unlock to expect and send tokens over the
783
        # should hand off to the network
2018.5.70 by Robert Collins
Only try to get real repositories when an operation requires them.
784
        self._ensure_real()
2018.5.60 by Robert Collins
More missing methods from RemoteBranch and RemoteRepository to let 'info' get further.
785
        return self._real_repository.break_lock()
786
2018.18.8 by Ian Clatworthy
Tarball proxy code & tests
787
    def _get_tarball(self, compression):
2814.10.2 by Andrew Bennetts
Make the fallback a little tidier.
788
        """Return a TemporaryFile containing a repository tarball.
3943.8.1 by Marius Kruger
remove all trailing whitespace from bzr source
789
2814.10.2 by Andrew Bennetts
Make the fallback a little tidier.
790
        Returns None if the server does not support sending tarballs.
791
        """
2018.18.25 by Martin Pool
Repository.tarball fixes for python2.4
792
        import tempfile
2018.18.8 by Ian Clatworthy
Tarball proxy code & tests
793
        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.
794
        try:
3786.2.3 by Andrew Bennetts
Remove duplicated 'call & translate errors' code in bzrlib.remote.
795
            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.
796
                'Repository.tarball', path, compression)
797
        except errors.UnknownSmartMethod:
798
            protocol.cancel_read_body()
799
            return None
2018.18.8 by Ian Clatworthy
Tarball proxy code & tests
800
        if response[0] == 'ok':
801
            # Extract the tarball and return it
2018.18.25 by Martin Pool
Repository.tarball fixes for python2.4
802
            t = tempfile.NamedTemporaryFile()
803
            # TODO: rpc layer should read directly into it...
804
            t.write(protocol.read_body_bytes())
805
            t.seek(0)
806
            return t
2814.10.1 by Andrew Bennetts
Cope gracefully if the server doesn't support the Repository.tarball smart request.
807
        raise errors.UnexpectedSmartServerResponse(response)
2018.18.8 by Ian Clatworthy
Tarball proxy code & tests
808
2440.1.1 by Martin Pool
Add new Repository.sprout,
809
    def sprout(self, to_bzrdir, revision_id=None):
810
        # TODO: Option to control what format is created?
3047.1.1 by Andrew Bennetts
Fix for bug 164626, add test that Repository.sprout preserves format.
811
        self._ensure_real()
3047.1.4 by Andrew Bennetts
Simplify RemoteRepository.sprout thanks to review comments.
812
        dest_repo = self._real_repository._format.initialize(to_bzrdir,
813
                                                             shared=False)
2535.3.17 by Andrew Bennetts
[broken] Closer to a working Repository.fetch_revisions smart request.
814
        dest_repo.fetch(self, revision_id=revision_id)
815
        return dest_repo
2440.1.1 by Martin Pool
Add new Repository.sprout,
816
2018.14.1 by Andrew Bennetts
Update to current hpss branch? Fix lots of test failures.
817
    ### These methods are just thin shims to the VFS object for now.
818
819
    def revision_tree(self, revision_id):
820
        self._ensure_real()
821
        return self._real_repository.revision_tree(revision_id)
822
2520.4.113 by Aaron Bentley
Avoid peeking at Repository._serializer
823
    def get_serializer_format(self):
824
        self._ensure_real()
825
        return self._real_repository.get_serializer_format()
826
2018.14.1 by Andrew Bennetts
Update to current hpss branch? Fix lots of test failures.
827
    def get_commit_builder(self, branch, parents, config, timestamp=None,
828
                           timezone=None, committer=None, revprops=None,
829
                           revision_id=None):
830
        # FIXME: It ought to be possible to call this without immediately
831
        # triggering _ensure_real.  For now it's the easiest thing to do.
832
        self._ensure_real()
3692.1.3 by Andrew Bennetts
Delete some cruft (like the _ensure_real call in RemoteBranch.lock_write), improve some comments, and wrap some long lines.
833
        real_repo = self._real_repository
834
        builder = real_repo.get_commit_builder(branch, parents,
2018.14.1 by Andrew Bennetts
Update to current hpss branch? Fix lots of test failures.
835
                config, timestamp=timestamp, timezone=timezone,
836
                committer=committer, revprops=revprops, revision_id=revision_id)
837
        return builder
838
3221.12.1 by Robert Collins
Backport development1 format (stackable packs) to before-shallow-branches.
839
    def add_fallback_repository(self, repository):
840
        """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
841
3221.12.1 by Robert Collins
Backport development1 format (stackable packs) to before-shallow-branches.
842
        :param repository: A repository.
843
        """
3691.2.11 by Martin Pool
More tests around RemoteBranch stacking.
844
        # XXX: At the moment the RemoteRepository will allow fallbacks
845
        # unconditionally - however, a _real_repository will usually exist,
846
        # and may raise an error if it's not accommodated by the underlying
847
        # format.  Eventually we should check when opening the repository
848
        # whether it's willing to allow them or not.
849
        #
3221.12.1 by Robert Collins
Backport development1 format (stackable packs) to before-shallow-branches.
850
        # We need to accumulate additional repositories here, to pass them in
851
        # on various RPC's.
852
        self._fallback_repositories.append(repository)
4035.2.1 by Andrew Bennetts
Fix unnecessary get_parent_map calls after insert_stream during push.
853
        if self._real_repository is not None:
854
            self._real_repository.add_fallback_repository(repository)
855
        else:
856
            # They are also seen by the fallback repository.  If it doesn't
857
            # exist yet they'll be added then.  This implicitly copies them.
858
            self._ensure_real()
3221.12.1 by Robert Collins
Backport development1 format (stackable packs) to before-shallow-branches.
859
2018.14.1 by Andrew Bennetts
Update to current hpss branch? Fix lots of test failures.
860
    def add_inventory(self, revid, inv, parents):
861
        self._ensure_real()
862
        return self._real_repository.add_inventory(revid, inv, parents)
863
3879.2.2 by John Arbash Meinel
Rename add_inventory_delta to add_inventory_by_delta.
864
    def add_inventory_by_delta(self, basis_revision_id, delta, new_revision_id,
865
                               parents):
3775.2.1 by Robert Collins
Create bzrlib.repository.Repository.add_inventory_delta for adding inventories via deltas.
866
        self._ensure_real()
3879.2.2 by John Arbash Meinel
Rename add_inventory_delta to add_inventory_by_delta.
867
        return self._real_repository.add_inventory_by_delta(basis_revision_id,
3775.2.1 by Robert Collins
Create bzrlib.repository.Repository.add_inventory_delta for adding inventories via deltas.
868
            delta, new_revision_id, parents)
869
2018.14.1 by Andrew Bennetts
Update to current hpss branch? Fix lots of test failures.
870
    def add_revision(self, rev_id, rev, inv=None, config=None):
871
        self._ensure_real()
872
        return self._real_repository.add_revision(
873
            rev_id, rev, inv=inv, config=config)
874
875
    @needs_read_lock
876
    def get_inventory(self, revision_id):
877
        self._ensure_real()
878
        return self._real_repository.get_inventory(revision_id)
879
3169.2.1 by Robert Collins
New method ``iter_inventories`` on Repository for access to many
880
    def iter_inventories(self, revision_ids):
881
        self._ensure_real()
882
        return self._real_repository.iter_inventories(revision_ids)
883
2018.14.1 by Andrew Bennetts
Update to current hpss branch? Fix lots of test failures.
884
    @needs_read_lock
885
    def get_revision(self, revision_id):
886
        self._ensure_real()
887
        return self._real_repository.get_revision(revision_id)
888
889
    def get_transaction(self):
890
        self._ensure_real()
891
        return self._real_repository.get_transaction()
892
893
    @needs_read_lock
2018.5.138 by Robert Collins
Merge bzr.dev.
894
    def clone(self, a_bzrdir, revision_id=None):
2018.14.1 by Andrew Bennetts
Update to current hpss branch? Fix lots of test failures.
895
        self._ensure_real()
2018.5.138 by Robert Collins
Merge bzr.dev.
896
        return self._real_repository.clone(a_bzrdir, revision_id=revision_id)
2018.14.1 by Andrew Bennetts
Update to current hpss branch? Fix lots of test failures.
897
898
    def make_working_trees(self):
3349.1.1 by Aaron Bentley
Enable setting and getting make_working_trees for all repositories
899
        """See Repository.make_working_trees"""
900
        self._ensure_real()
901
        return self._real_repository.make_working_trees()
2018.14.1 by Andrew Bennetts
Update to current hpss branch? Fix lots of test failures.
902
3184.1.9 by Robert Collins
* ``Repository.get_data_stream`` is now deprecated in favour of
903
    def revision_ids_to_search_result(self, result_set):
904
        """Convert a set of revision ids to a graph SearchResult."""
905
        result_parents = set()
906
        for parents in self.get_graph().get_parent_map(
907
            result_set).itervalues():
908
            result_parents.update(parents)
909
        included_keys = result_set.intersection(result_parents)
910
        start_keys = result_set.difference(included_keys)
911
        exclude_keys = result_parents.difference(result_set)
912
        result = graph.SearchResult(start_keys, exclude_keys,
913
            len(result_set), result_set)
914
        return result
915
916
    @needs_read_lock
917
    def search_missing_revision_ids(self, other, revision_id=None, find_ghosts=True):
918
        """Return the revision ids that other has that this does not.
3943.8.1 by Marius Kruger
remove all trailing whitespace from bzr source
919
3184.1.9 by Robert Collins
* ``Repository.get_data_stream`` is now deprecated in favour of
920
        These are returned in topological order.
921
922
        revision_id: only return revision ids included by revision_id.
923
        """
924
        return repository.InterRepository.get(
925
            other, self).search_missing_revision_ids(revision_id, find_ghosts)
926
3452.2.1 by Andrew Bennetts
An experimental InterRepo for remote packs.
927
    def fetch(self, source, revision_id=None, pb=None, find_ghosts=False):
928
        # Not delegated to _real_repository so that InterRepository.get has a
929
        # chance to find an InterRepository specialised for RemoteRepository.
2881.4.1 by Robert Collins
Move responsibility for detecting same-repo fetching from the
930
        if self.has_same_location(source):
931
            # check that last_revision is in 'from' and then return a
932
            # no-operation.
933
            if (revision_id is not None and
2948.3.1 by John Arbash Meinel
Fix bug #158333, make sure that Repository.fetch(self) is properly a no-op for all Repository implementations.
934
                not revision.is_null(revision_id)):
2881.4.1 by Robert Collins
Move responsibility for detecting same-repo fetching from the
935
                self.get_revision(revision_id)
2592.4.5 by Martin Pool
Add Repository.base on all repositories.
936
            return 0, []
3709.5.1 by Andrew Bennetts
Allow pushing to a pack repo over HPSS use the get_parent_map RPC, and teach the get_parent_map client to cache missing revisions.
937
        inter = repository.InterRepository.get(source, self)
3452.2.1 by Andrew Bennetts
An experimental InterRepo for remote packs.
938
        try:
939
            return inter.fetch(revision_id=revision_id, pb=pb, find_ghosts=find_ghosts)
940
        except NotImplementedError:
941
            raise errors.IncompatibleRepositories(source, self)
2018.14.1 by Andrew Bennetts
Update to current hpss branch? Fix lots of test failures.
942
2520.4.54 by Aaron Bentley
Hang a create_bundle method off repository
943
    def create_bundle(self, target, base, fileobj, format=None):
944
        self._ensure_real()
945
        self._real_repository.create_bundle(target, base, fileobj, format)
946
2018.14.1 by Andrew Bennetts
Update to current hpss branch? Fix lots of test failures.
947
    @needs_read_lock
2530.1.1 by Aaron Bentley
Make topological sorting optional for get_ancestry
948
    def get_ancestry(self, revision_id, topo_sorted=True):
2018.14.1 by Andrew Bennetts
Update to current hpss branch? Fix lots of test failures.
949
        self._ensure_real()
2530.1.1 by Aaron Bentley
Make topological sorting optional for get_ancestry
950
        return self._real_repository.get_ancestry(revision_id, topo_sorted)
2018.14.1 by Andrew Bennetts
Update to current hpss branch? Fix lots of test failures.
951
952
    def fileids_altered_by_revision_ids(self, revision_ids):
953
        self._ensure_real()
954
        return self._real_repository.fileids_altered_by_revision_ids(revision_ids)
955
3036.1.3 by Robert Collins
Privatise VersionedFileChecker.
956
    def _get_versioned_file_checker(self, revisions, revision_versions_cache):
2745.6.1 by Aaron Bentley
Initial checking of knit graphs
957
        self._ensure_real()
3036.1.3 by Robert Collins
Privatise VersionedFileChecker.
958
        return self._real_repository._get_versioned_file_checker(
2745.6.50 by Andrew Bennetts
Remove find_bad_ancestors; it's not needed anymore.
959
            revisions, revision_versions_cache)
3943.8.1 by Marius Kruger
remove all trailing whitespace from bzr source
960
2708.1.7 by Aaron Bentley
Rename extract_files_bytes to iter_files_bytes
961
    def iter_files_bytes(self, desired_files):
2708.1.9 by Aaron Bentley
Clean-up docs and imports
962
        """See Repository.iter_file_bytes.
2708.1.3 by Aaron Bentley
Implement extract_files_bytes on Repository
963
        """
964
        self._ensure_real()
2708.1.7 by Aaron Bentley
Rename extract_files_bytes to iter_files_bytes
965
        return self._real_repository.iter_files_bytes(desired_files)
2708.1.3 by Aaron Bentley
Implement extract_files_bytes on Repository
966
3565.3.1 by Robert Collins
* The generic fetch code now uses two attributes on Repository objects
967
    @property
968
    def _fetch_order(self):
969
        """Decorate the real repository for now.
970
971
        In the long term getting this back from the remote repository as part
972
        of open would be more efficient.
973
        """
3842.3.20 by Andrew Bennetts
Re-revert changes from another thread that accidentally got reinstated here.
974
        self._ensure_real()
975
        return self._real_repository._fetch_order
3565.3.1 by Robert Collins
* The generic fetch code now uses two attributes on Repository objects
976
977
    @property
978
    def _fetch_uses_deltas(self):
979
        """Decorate the real repository for now.
980
981
        In the long term getting this back from the remote repository as part
982
        of open would be more efficient.
983
        """
984
        self._ensure_real()
985
        return self._real_repository._fetch_uses_deltas
986
3565.3.4 by Robert Collins
Defer decision to reconcile to the repository being fetched into.
987
    @property
988
    def _fetch_reconcile(self):
989
        """Decorate the real repository for now.
990
991
        In the long term getting this back from the remote repository as part
992
        of open would be more efficient.
993
        """
994
        self._ensure_real()
995
        return self._real_repository._fetch_reconcile
996
3835.1.1 by Aaron Bentley
Stack get_parent_map on fallback repos
997
    def get_parent_map(self, revision_ids):
3835.1.6 by Aaron Bentley
Reduce inefficiency when doing make_parents_provider frequently
998
        """See bzrlib.Graph.get_parent_map()."""
3835.1.5 by Aaron Bentley
Fix make_parents_provider
999
        return self._make_parents_provider().get_parent_map(revision_ids)
3835.1.1 by Aaron Bentley
Stack get_parent_map on fallback repos
1000
1001
    def _get_parent_map_rpc(self, keys):
3172.5.6 by Robert Collins
Create new smart server verb Repository.get_parent_map.
1002
        """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.
1003
        medium = self._client._medium
3453.4.10 by Andrew Bennetts
Change _is_remote_at_least to _is_remote_before.
1004
        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.
1005
            # We already found out that the server can't understand
3213.1.3 by Andrew Bennetts
Fix typo in comment.
1006
            # 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.
1007
            # graph.
3287.6.1 by Robert Collins
* ``VersionedFile.get_graph`` is deprecated, with no replacement method.
1008
            # XXX: Note that this will issue a deprecation warning. This is ok
1009
            # :- its because we're working with a deprecated server anyway, and
1010
            # the user will almost certainly have seen a warning about the
1011
            # server version already.
3389.1.1 by John Arbash Meinel
Fix bug #214894. Fix RemoteRepository.get_parent_map() when server is <v1.2
1012
            rg = self.get_revision_graph()
1013
            # There is an api discrepency between get_parent_map and
1014
            # get_revision_graph. Specifically, a "key:()" pair in
1015
            # get_revision_graph just means a node has no parents. For
1016
            # "get_parent_map" it means the node is a ghost. So fix up the
1017
            # graph to correct this.
1018
            #   https://bugs.launchpad.net/bzr/+bug/214894
1019
            # There is one other "bug" which is that ghosts in
1020
            # get_revision_graph() are not returned at all. But we won't worry
1021
            # about that for now.
1022
            for node_id, parent_ids in rg.iteritems():
1023
                if parent_ids == ():
1024
                    rg[node_id] = (NULL_REVISION,)
1025
            rg[NULL_REVISION] = ()
1026
            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.
1027
3172.5.6 by Robert Collins
Create new smart server verb Repository.get_parent_map.
1028
        keys = set(keys)
3373.5.2 by John Arbash Meinel
Add repository_implementation tests for get_parent_map
1029
        if None in keys:
1030
            raise ValueError('get_parent_map(None) is not valid')
3172.5.6 by Robert Collins
Create new smart server verb Repository.get_parent_map.
1031
        if NULL_REVISION in keys:
1032
            keys.discard(NULL_REVISION)
1033
            found_parents = {NULL_REVISION:()}
1034
            if not keys:
1035
                return found_parents
1036
        else:
1037
            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.
1038
        # TODO(Needs analysis): We could assume that the keys being requested
1039
        # from get_parent_map are in a breadth first search, so typically they
1040
        # will all be depth N from some common parent, and we don't have to
1041
        # have the server iterate from the root parent, but rather from the
1042
        # keys we're searching; and just tell the server the keyspace we
1043
        # already have; but this may be more traffic again.
1044
1045
        # Transform self._parents_map into a search request recipe.
1046
        # TODO: Manage this incrementally to avoid covering the same path
1047
        # repeatedly. (The server will have to on each request, but the less
1048
        # work done the better).
3835.1.8 by Aaron Bentley
Make UnstackedParentsProvider manage the cache
1049
        parents_map = self._unstacked_provider.get_cached_map()
3213.1.8 by Andrew Bennetts
Merge from bzr.dev.
1050
        if parents_map is None:
1051
            # Repository is not locked, so there's no cache.
1052
            parents_map = {}
1053
        start_set = set(parents_map)
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.
1054
        result_parents = set()
3213.1.8 by Andrew Bennetts
Merge from bzr.dev.
1055
        for parents in parents_map.itervalues():
3211.5.1 by Robert Collins
Change the smart server get_parents method to take a graph search to exclude already recieved parents from. This prevents history shortcuts causing huge numbers of duplicates.
1056
            result_parents.update(parents)
1057
        stop_keys = result_parents.difference(start_set)
1058
        included_keys = start_set.intersection(result_parents)
1059
        start_set.difference_update(included_keys)
3213.1.8 by Andrew Bennetts
Merge from bzr.dev.
1060
        recipe = (start_set, stop_keys, len(parents_map))
3842.3.20 by Andrew Bennetts
Re-revert changes from another thread that accidentally got reinstated here.
1061
        body = self._serialise_search_recipe(recipe)
3172.5.6 by Robert Collins
Create new smart server verb Repository.get_parent_map.
1062
        path = self.bzrdir._path_for_remote_call(self._client)
1063
        for key in keys:
3360.2.8 by Martin Pool
Change assertion to a plain raise
1064
            if type(key) is not str:
1065
                raise ValueError(
1066
                    "key %r not a plain string" % (key,))
3172.5.8 by Robert Collins
Review feedback.
1067
        verb = 'Repository.get_parent_map'
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.
1068
        args = (path,) + 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.
1069
        try:
3786.2.3 by Andrew Bennetts
Remove duplicated 'call & translate errors' code in bzrlib.remote.
1070
            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.
1071
                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.
1072
        except errors.UnknownSmartMethod:
3213.1.2 by Andrew Bennetts
Add test for reconnection if get_parent_map is unknown by the server.
1073
            # 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.
1074
            # Worse, we have to force a disconnection, because the server now
1075
            # doesn't realise it has a body on the wire to consume, so the
1076
            # only way to recover is to abandon the connection.
3213.1.6 by Andrew Bennetts
Emit warnings when forcing a reconnect.
1077
            warning(
1078
                'Server is too old for fast get_parent_map, reconnecting.  '
1079
                '(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.
1080
            medium.disconnect()
1081
            # To avoid having to disconnect repeatedly, we keep track of the
1082
            # 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.
1083
            medium._remember_remote_is_before((1, 2))
3297.3.4 by Andrew Bennetts
Merge from bzr.dev.
1084
            return self.get_revision_graph(None)
3245.4.58 by Andrew Bennetts
Unpack call_expecting_body's return value into variables, to avoid lots of ugly subscripting.
1085
        response_tuple, response_handler = response
1086
        if response_tuple[0] not in ['ok']:
1087
            response_handler.cancel_read_body()
1088
            raise errors.UnexpectedSmartServerResponse(response_tuple)
1089
        if response_tuple[0] == 'ok':
1090
            coded = bz2.decompress(response_handler.read_body_bytes())
3172.5.6 by Robert Collins
Create new smart server verb Repository.get_parent_map.
1091
            if coded == '':
1092
                # no revisions found
1093
                return {}
1094
            lines = coded.split('\n')
1095
            revision_graph = {}
1096
            for line in lines:
1097
                d = tuple(line.split())
1098
                if len(d) > 1:
1099
                    revision_graph[d[0]] = d[1:]
1100
                else:
1101
                    # No parents - so give the Graph result (NULL_REVISION,).
1102
                    revision_graph[d[0]] = (NULL_REVISION,)
1103
            return revision_graph
1104
2018.14.1 by Andrew Bennetts
Update to current hpss branch? Fix lots of test failures.
1105
    @needs_read_lock
1106
    def get_signature_text(self, revision_id):
1107
        self._ensure_real()
1108
        return self._real_repository.get_signature_text(revision_id)
1109
1110
    @needs_read_lock
3228.4.11 by John Arbash Meinel
Deprecations abound.
1111
    @symbol_versioning.deprecated_method(symbol_versioning.one_three)
2018.14.1 by Andrew Bennetts
Update to current hpss branch? Fix lots of test failures.
1112
    def get_revision_graph_with_ghosts(self, revision_ids=None):
1113
        self._ensure_real()
1114
        return self._real_repository.get_revision_graph_with_ghosts(
1115
            revision_ids=revision_ids)
1116
1117
    @needs_read_lock
1118
    def get_inventory_xml(self, revision_id):
1119
        self._ensure_real()
1120
        return self._real_repository.get_inventory_xml(revision_id)
1121
1122
    def deserialise_inventory(self, revision_id, xml):
1123
        self._ensure_real()
1124
        return self._real_repository.deserialise_inventory(revision_id, xml)
1125
1126
    def reconcile(self, other=None, thorough=False):
1127
        self._ensure_real()
1128
        return self._real_repository.reconcile(other=other, thorough=thorough)
3943.8.1 by Marius Kruger
remove all trailing whitespace from bzr source
1129
2018.14.1 by Andrew Bennetts
Update to current hpss branch? Fix lots of test failures.
1130
    def all_revision_ids(self):
1131
        self._ensure_real()
1132
        return self._real_repository.all_revision_ids()
3943.8.1 by Marius Kruger
remove all trailing whitespace from bzr source
1133
2018.14.1 by Andrew Bennetts
Update to current hpss branch? Fix lots of test failures.
1134
    @needs_read_lock
1135
    def get_deltas_for_revisions(self, revisions):
1136
        self._ensure_real()
1137
        return self._real_repository.get_deltas_for_revisions(revisions)
1138
1139
    @needs_read_lock
1140
    def get_revision_delta(self, revision_id):
1141
        self._ensure_real()
1142
        return self._real_repository.get_revision_delta(revision_id)
1143
1144
    @needs_read_lock
1145
    def revision_trees(self, revision_ids):
1146
        self._ensure_real()
1147
        return self._real_repository.revision_trees(revision_ids)
1148
1149
    @needs_read_lock
1150
    def get_revision_reconcile(self, revision_id):
1151
        self._ensure_real()
1152
        return self._real_repository.get_revision_reconcile(revision_id)
1153
1154
    @needs_read_lock
2745.6.36 by Andrew Bennetts
Deprecate revision_ids arg to Repository.check and other tweaks.
1155
    def check(self, revision_ids=None):
2018.14.1 by Andrew Bennetts
Update to current hpss branch? Fix lots of test failures.
1156
        self._ensure_real()
2745.6.36 by Andrew Bennetts
Deprecate revision_ids arg to Repository.check and other tweaks.
1157
        return self._real_repository.check(revision_ids=revision_ids)
2018.14.1 by Andrew Bennetts
Update to current hpss branch? Fix lots of test failures.
1158
2018.5.138 by Robert Collins
Merge bzr.dev.
1159
    def copy_content_into(self, destination, revision_id=None):
2018.14.1 by Andrew Bennetts
Update to current hpss branch? Fix lots of test failures.
1160
        self._ensure_real()
1161
        return self._real_repository.copy_content_into(
2018.5.138 by Robert Collins
Merge bzr.dev.
1162
            destination, revision_id=revision_id)
2018.14.1 by Andrew Bennetts
Update to current hpss branch? Fix lots of test failures.
1163
2814.10.2 by Andrew Bennetts
Make the fallback a little tidier.
1164
    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.
1165
        # get a tarball of the remote repository, and copy from that into the
1166
        # destination
1167
        from bzrlib import osutils
2018.18.9 by Martin Pool
remote Repository.tarball builds a temporary directory and tars that
1168
        import tarfile
2018.18.20 by Martin Pool
Route branch operations through remote copy_content_into
1169
        # TODO: Maybe a progress bar while streaming the tarball?
1170
        note("Copying repository content as tarball...")
2018.18.25 by Martin Pool
Repository.tarball fixes for python2.4
1171
        tar_file = self._get_tarball('bz2')
2814.10.2 by Andrew Bennetts
Make the fallback a little tidier.
1172
        if tar_file is None:
1173
            return None
1174
        destination = to_bzrdir.create_repository()
2018.18.10 by Martin Pool
copy_content_into from Remote repositories by using temporary directories on both ends.
1175
        try:
2018.18.25 by Martin Pool
Repository.tarball fixes for python2.4
1176
            tar = tarfile.open('repository', fileobj=tar_file,
1177
                mode='r|bz2')
3638.3.2 by Vincent Ladeuil
Fix all calls to tempfile.mkdtemp to osutils.mkdtemp.
1178
            tmpdir = osutils.mkdtemp()
2018.18.25 by Martin Pool
Repository.tarball fixes for python2.4
1179
            try:
1180
                _extract_tar(tar, tmpdir)
1181
                tmp_bzrdir = BzrDir.open(tmpdir)
1182
                tmp_repo = tmp_bzrdir.open_repository()
1183
                tmp_repo.copy_content_into(destination, revision_id)
1184
            finally:
1185
                osutils.rmtree(tmpdir)
2018.18.10 by Martin Pool
copy_content_into from Remote repositories by using temporary directories on both ends.
1186
        finally:
2018.18.25 by Martin Pool
Repository.tarball fixes for python2.4
1187
            tar_file.close()
2814.10.2 by Andrew Bennetts
Make the fallback a little tidier.
1188
        return destination
2018.18.23 by Martin Pool
review cleanups
1189
        # TODO: Suggestion from john: using external tar is much faster than
1190
        # 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.
1191
3842.3.20 by Andrew Bennetts
Re-revert changes from another thread that accidentally got reinstated here.
1192
    @property
1193
    def inventories(self):
1194
        """Decorate the real repository for now.
1195
1196
        In the long term a full blown network facility is needed to
1197
        avoid creating a real repository object locally.
1198
        """
1199
        self._ensure_real()
1200
        return self._real_repository.inventories
1201
2604.2.1 by Robert Collins
(robertc) Introduce a pack command.
1202
    @needs_write_lock
1203
    def pack(self):
1204
        """Compress the data within the repository.
1205
1206
        This is not currently implemented within the smart server.
1207
        """
1208
        self._ensure_real()
1209
        return self._real_repository.pack()
1210
3842.3.20 by Andrew Bennetts
Re-revert changes from another thread that accidentally got reinstated here.
1211
    @property
1212
    def revisions(self):
1213
        """Decorate the real repository for now.
1214
1215
        In the short term this should become a real object to intercept graph
1216
        lookups.
1217
1218
        In the long term a full blown network facility is needed.
1219
        """
1220
        self._ensure_real()
1221
        return self._real_repository.revisions
1222
2018.14.1 by Andrew Bennetts
Update to current hpss branch? Fix lots of test failures.
1223
    def set_make_working_trees(self, new_value):
4017.3.4 by Robert Collins
Create a verb for Repository.set_make_working_trees.
1224
        if new_value:
1225
            new_value_str = "True"
1226
        else:
1227
            new_value_str = "False"
1228
        path = self.bzrdir._path_for_remote_call(self._client)
1229
        try:
1230
            response = self._call(
1231
                'Repository.set_make_working_trees', path, new_value_str)
1232
        except errors.UnknownSmartMethod:
1233
            self._ensure_real()
1234
            self._real_repository.set_make_working_trees(new_value)
1235
        else:
1236
            if response[0] != 'ok':
1237
                raise errors.UnexpectedSmartServerResponse(response)
2018.14.1 by Andrew Bennetts
Update to current hpss branch? Fix lots of test failures.
1238
3842.3.20 by Andrew Bennetts
Re-revert changes from another thread that accidentally got reinstated here.
1239
    @property
1240
    def signatures(self):
1241
        """Decorate the real repository for now.
1242
1243
        In the long term a full blown network facility is needed to avoid
1244
        creating a real repository object locally.
1245
        """
1246
        self._ensure_real()
1247
        return self._real_repository.signatures
1248
2018.14.1 by Andrew Bennetts
Update to current hpss branch? Fix lots of test failures.
1249
    @needs_write_lock
1250
    def sign_revision(self, revision_id, gpg_strategy):
1251
        self._ensure_real()
1252
        return self._real_repository.sign_revision(revision_id, gpg_strategy)
1253
3842.3.20 by Andrew Bennetts
Re-revert changes from another thread that accidentally got reinstated here.
1254
    @property
1255
    def texts(self):
1256
        """Decorate the real repository for now.
1257
1258
        In the long term a full blown network facility is needed to avoid
1259
        creating a real repository object locally.
1260
        """
1261
        self._ensure_real()
1262
        return self._real_repository.texts
1263
2018.14.1 by Andrew Bennetts
Update to current hpss branch? Fix lots of test failures.
1264
    @needs_read_lock
1265
    def get_revisions(self, revision_ids):
1266
        self._ensure_real()
1267
        return self._real_repository.get_revisions(revision_ids)
1268
1269
    def supports_rich_root(self):
2018.5.84 by Andrew Bennetts
Merge in supports-rich-root, another test passing.
1270
        self._ensure_real()
1271
        return self._real_repository.supports_rich_root()
2018.14.1 by Andrew Bennetts
Update to current hpss branch? Fix lots of test failures.
1272
2018.5.83 by Andrew Bennetts
Fix some test failures caused by the switch from unicode to UTF-8-encoded strs for revision IDs.
1273
    def iter_reverse_revision_history(self, revision_id):
1274
        self._ensure_real()
1275
        return self._real_repository.iter_reverse_revision_history(revision_id)
1276
2018.5.96 by Andrew Bennetts
Merge from bzr.dev, resolving the worst of the semantic conflicts, but there's
1277
    @property
1278
    def _serializer(self):
1279
        self._ensure_real()
1280
        return self._real_repository._serializer
1281
2018.5.97 by Andrew Bennetts
Fix more tests.
1282
    def store_revision_signature(self, gpg_strategy, plaintext, revision_id):
1283
        self._ensure_real()
1284
        return self._real_repository.store_revision_signature(
1285
            gpg_strategy, plaintext, revision_id)
1286
2996.2.8 by Aaron Bentley
Fix add_signature discrepancies
1287
    def add_signature_text(self, revision_id, signature):
2996.2.3 by Aaron Bentley
Add tests for install_revisions and add_signature
1288
        self._ensure_real()
2996.2.8 by Aaron Bentley
Fix add_signature discrepancies
1289
        return self._real_repository.add_signature_text(revision_id, signature)
2996.2.3 by Aaron Bentley
Add tests for install_revisions and add_signature
1290
2018.5.97 by Andrew Bennetts
Fix more tests.
1291
    def has_signature_for_revision_id(self, revision_id):
1292
        self._ensure_real()
1293
        return self._real_repository.has_signature_for_revision_id(revision_id)
1294
2535.3.45 by Andrew Bennetts
Add item_keys_introduced_by to RemoteRepository.
1295
    def item_keys_introduced_by(self, revision_ids, _files_pb=None):
1296
        self._ensure_real()
1297
        return self._real_repository.item_keys_introduced_by(revision_ids,
1298
            _files_pb=_files_pb)
1299
2819.2.4 by Andrew Bennetts
Add a 'revision_graph_can_have_wrong_parents' method to repository.
1300
    def revision_graph_can_have_wrong_parents(self):
1301
        # The answer depends on the remote repo format.
1302
        self._ensure_real()
1303
        return self._real_repository.revision_graph_can_have_wrong_parents()
1304
2819.2.5 by Andrew Bennetts
Make reconcile abort gracefully if the revision index has bad parents.
1305
    def _find_inconsistent_revision_parents(self):
1306
        self._ensure_real()
1307
        return self._real_repository._find_inconsistent_revision_parents()
1308
1309
    def _check_for_inconsistent_revision_parents(self):
1310
        self._ensure_real()
1311
        return self._real_repository._check_for_inconsistent_revision_parents()
1312
3835.1.17 by Aaron Bentley
Fix stacking bug
1313
    def _make_parents_provider(self, other=None):
3835.1.8 by Aaron Bentley
Make UnstackedParentsProvider manage the cache
1314
        providers = [self._unstacked_provider]
3835.1.17 by Aaron Bentley
Fix stacking bug
1315
        if other is not None:
1316
            providers.insert(0, other)
3835.1.7 by Aaron Bentley
Updates from review
1317
        providers.extend(r._make_parents_provider() for r in
1318
                         self._fallback_repositories)
1319
        return graph._StackedParentsProvider(providers)
3172.5.1 by Robert Collins
Create a RemoteRepository get_graph implementation and delegate get_parents_map to the real repository.
1320
3842.3.20 by Andrew Bennetts
Re-revert changes from another thread that accidentally got reinstated here.
1321
    def _serialise_search_recipe(self, recipe):
1322
        """Serialise a graph search recipe.
1323
1324
        :param recipe: A search recipe (start, stop, count).
1325
        :return: Serialised bytes.
1326
        """
1327
        start_keys = ' '.join(recipe[0])
1328
        stop_keys = ' '.join(recipe[1])
1329
        count = str(recipe[2])
1330
        return '\n'.join((start_keys, stop_keys, count))
1331
3842.3.2 by Andrew Bennetts
Revert the RemoteVersionedFiles.get_parent_map implementation, leaving just the skeleton of RemoteVersionedFiles.
1332
    def autopack(self):
1333
        path = self.bzrdir._path_for_remote_call(self._client)
1334
        try:
1335
            response = self._call('PackRepository.autopack', path)
1336
        except errors.UnknownSmartMethod:
1337
            self._ensure_real()
1338
            self._real_repository._pack_collection.autopack()
1339
            return
1340
        if self._real_repository is not None:
1341
            # Reset the real repository's cache of pack names.
1342
            # XXX: At some point we may be able to skip this and just rely on
1343
            # the automatic retry logic to do the right thing, but for now we
1344
            # err on the side of being correct rather than being optimal.
1345
            self._real_repository._pack_collection.reload_pack_names()
1346
        if response[0] != 'ok':
1347
            raise errors.UnexpectedSmartServerResponse(response)
1348
1349
4022.1.6 by Robert Collins
Cherrypick and polish the RemoteSink for streaming push.
1350
class RemoteStreamSink(repository.StreamSink):
1351
4029.2.1 by Robert Collins
Support streaming push to stacked branches.
1352
    def __init__(self, target_repo):
1353
        repository.StreamSink.__init__(self, target_repo)
1354
        self._resume_tokens = []
1355
4022.1.6 by Robert Collins
Cherrypick and polish the RemoteSink for streaming push.
1356
    def _insert_real(self, stream, src_format):
1357
        self.target_repo._ensure_real()
1358
        sink = self.target_repo._real_repository._get_sink()
4029.2.1 by Robert Collins
Support streaming push to stacked branches.
1359
        result = sink.insert_stream(stream, src_format)
1360
        if not result:
1361
            self.target_repo.autopack()
1362
        return result
4022.1.6 by Robert Collins
Cherrypick and polish the RemoteSink for streaming push.
1363
1364
    def insert_stream(self, stream, src_format):
1365
        repo = self.target_repo
1366
        client = repo._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)
1367
        medium = client._medium
4029.2.1 by Robert Collins
Support streaming push to stacked branches.
1368
        if medium._is_remote_before((1, 13)):
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)
1369
            # No possible way this can work.
1370
            return self._insert_real(stream, src_format)
4022.1.6 by Robert Collins
Cherrypick and polish the RemoteSink for streaming push.
1371
        path = repo.bzrdir._path_for_remote_call(client)
4029.2.1 by Robert Collins
Support streaming push to stacked branches.
1372
        if not self._resume_tokens:
1373
            # XXX: Ugly but important for correctness, *will* be fixed during
1374
            # 1.13 cycle. Pushing a stream that is interrupted results in a
1375
            # fallback to the _real_repositories sink *with a partial stream*.
1376
            # Thats bad because we insert less data than bzr expected. To avoid
1377
            # this we do a trial push to make sure the verb is accessible, and
1378
            # do not fallback when actually pushing the stream. A cleanup patch
1379
            # is going to look at rewinding/restarting the stream/partial
1380
            # buffering etc.
1381
            byte_stream = self._stream_to_byte_stream([], src_format)
1382
            try:
1383
                resume_tokens = ''
1384
                response = client.call_with_body_stream(
1385
                    ('Repository.insert_stream', path, resume_tokens), byte_stream)
1386
            except errors.UnknownSmartMethod:
1387
                medium._remember_remote_is_before((1,13))
1388
                return self._insert_real(stream, src_format)
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)
1389
        byte_stream = self._stream_to_byte_stream(stream, src_format)
4029.2.1 by Robert Collins
Support streaming push to stacked branches.
1390
        resume_tokens = ' '.join(self._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)
1391
        response = client.call_with_body_stream(
4029.2.1 by Robert Collins
Support streaming push to stacked branches.
1392
            ('Repository.insert_stream', path, resume_tokens), byte_stream)
1393
        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)
1394
            raise errors.UnexpectedSmartServerResponse(response)
4029.2.1 by Robert Collins
Support streaming push to stacked branches.
1395
        if response[0][0] == 'missing-basis':
1396
            tokens, missing_keys = bencode.bdecode_as_tuple(response[0][1])
1397
            self._resume_tokens = tokens
1398
            return missing_keys
1399
        else:
1400
            if self.target_repo._real_repository is not None:
1401
                collection = getattr(self.target_repo._real_repository,
1402
                    '_pack_collection', None)
1403
                if collection is not None:
1404
                    collection.reload_pack_names()
1405
            return []
4032.1.1 by John Arbash Meinel
Merge the removal of all trailing whitespace, and resolve conflicts.
1406
4022.1.6 by Robert Collins
Cherrypick and polish the RemoteSink for streaming push.
1407
    def _stream_to_byte_stream(self, stream, src_format):
1408
        bytes = []
1409
        pack_writer = pack.ContainerWriter(bytes.append)
1410
        pack_writer.begin()
1411
        pack_writer.add_bytes_record(src_format.network_name(), '')
1412
        adapters = {}
1413
        def get_adapter(adapter_key):
1414
            try:
1415
                return adapters[adapter_key]
1416
            except KeyError:
1417
                adapter_factory = adapter_registry.get(adapter_key)
1418
                adapter = adapter_factory(self)
1419
                adapters[adapter_key] = adapter
1420
                return adapter
1421
        for substream_type, substream in stream:
1422
            for record in substream:
1423
                if record.storage_kind in ('chunked', 'fulltext'):
1424
                    serialised = record_to_fulltext_bytes(record)
1425
                else:
1426
                    serialised = record.get_bytes_as(record.storage_kind)
1427
                pack_writer.add_bytes_record(serialised, [(substream_type,)])
1428
                for b in bytes:
1429
                    yield b
1430
                del bytes[:]
1431
        pack_writer.end()
1432
        for b in bytes:
1433
            yield b
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)
1434
1435
2018.5.127 by Andrew Bennetts
Fix most of the lockable_files tests for RemoteBranchLockableFiles.
1436
class RemoteBranchLockableFiles(LockableFiles):
2018.5.59 by Robert Collins
Get BranchConfig working somewhat on RemoteBranches (Robert Collins, Vincent Ladeuil).
1437
    """A 'LockableFiles' implementation that talks to a smart server.
3943.8.1 by Marius Kruger
remove all trailing whitespace from bzr source
1438
2018.5.59 by Robert Collins
Get BranchConfig working somewhat on RemoteBranches (Robert Collins, Vincent Ladeuil).
1439
    This is not a public interface class.
1440
    """
1441
1442
    def __init__(self, bzrdir, _client):
1443
        self.bzrdir = bzrdir
1444
        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.
1445
        self._need_find_modes = True
2018.5.133 by Andrew Bennetts
All TestLockableFiles_RemoteLockDir tests passing.
1446
        LockableFiles.__init__(
2018.5.163 by Andrew Bennetts
Deal with various review comments from Robert.
1447
            self, bzrdir.get_branch_transport(None),
2018.5.133 by Andrew Bennetts
All TestLockableFiles_RemoteLockDir tests passing.
1448
            'lock', lockdir.LockDir)
2018.5.59 by Robert Collins
Get BranchConfig working somewhat on RemoteBranches (Robert Collins, Vincent Ladeuil).
1449
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.
1450
    def _find_modes(self):
1451
        # RemoteBranches don't let the client set the mode of control files.
1452
        self._dir_mode = None
1453
        self._file_mode = None
1454
2018.5.59 by Robert Collins
Get BranchConfig working somewhat on RemoteBranches (Robert Collins, Vincent Ladeuil).
1455
1752.2.31 by Martin Pool
[broken] some support for write operations over hpss
1456
class RemoteBranchFormat(branch.BranchFormat):
1457
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.
1458
    def __init__(self):
1459
        super(RemoteBranchFormat, self).__init__()
1460
        self._matchingbzrdir = RemoteBzrDirFormat()
1461
        self._matchingbzrdir.set_branch_format(self)
1462
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.
1463
    def __eq__(self, other):
3943.8.1 by Marius Kruger
remove all trailing whitespace from bzr source
1464
        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.
1465
            self.__dict__ == other.__dict__)
1466
2018.5.60 by Robert Collins
More missing methods from RemoteBranch and RemoteRepository to let 'info' get further.
1467
    def get_format_description(self):
1468
        return 'Remote BZR Branch'
1469
2018.14.1 by Andrew Bennetts
Update to current hpss branch? Fix lots of test failures.
1470
    def get_format_string(self):
1471
        return 'Remote BZR Branch'
1472
1752.2.31 by Martin Pool
[broken] some support for write operations over hpss
1473
    def open(self, a_bzrdir):
1752.2.72 by Andrew Bennetts
Make Remote* classes in remote.py more consistent and remove some dead code.
1474
        return a_bzrdir.open_branch()
1752.2.52 by Andrew Bennetts
Flesh out more Remote* methods needed to open and initialise remote branches/trees/repositories.
1475
1476
    def initialize(self, a_bzrdir):
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.
1477
        # Delegate to a _real object here - the RemoteBzrDir format now
1478
        # supports delegating to parameterised branch formats and as such
1479
        # this RemoteBranchFormat method is only called when no specific format
1480
        # is selected.
1481
        if not isinstance(a_bzrdir, RemoteBzrDir):
1482
            result = a_bzrdir.create_branch()
1483
        else:
1484
            a_bzrdir._ensure_real()
1485
            result = a_bzrdir._real_bzrdir.create_branch()
1486
        if not isinstance(result, RemoteBranch):
1487
            result = RemoteBranch(a_bzrdir, a_bzrdir.find_repository(), result)
1488
        return result
1752.2.31 by Martin Pool
[broken] some support for write operations over hpss
1489
2696.3.6 by Martin Pool
Mark RemoteBranch as (possibly) supporting tags
1490
    def supports_tags(self):
1491
        # Remote branches might support tags, but we won't know until we
1492
        # access the real remote branch.
1493
        return True
1494
1752.2.31 by Martin Pool
[broken] some support for write operations over hpss
1495
3786.2.3 by Andrew Bennetts
Remove duplicated 'call & translate errors' code in bzrlib.remote.
1496
class RemoteBranch(branch.Branch, _RpcHelper):
1752.2.31 by Martin Pool
[broken] some support for write operations over hpss
1497
    """Branch stored on a server accessed by HPSS RPC.
1498
1499
    At the moment most operations are mapped down to simple file operations.
1500
    """
1752.2.30 by Martin Pool
Start adding a RemoteBzrDir, etc
1501
2018.5.51 by Wouter van Heyst
Test and implement RemoteBranch.last_revision_info()
1502
    def __init__(self, remote_bzrdir, remote_repository, real_branch=None,
1503
        _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.
1504
        """Create a RemoteBranch instance.
1505
1506
        :param real_branch: An optional local implementation of the branch
1507
            format, usually accessing the data via the VFS.
2018.5.51 by Wouter van Heyst
Test and implement RemoteBranch.last_revision_info()
1508
        :param _client: Private parameter for testing.
2018.5.34 by Robert Collins
Get test_remote.BasicRemoteObjectTests.test_open_remote_branch passing by implementing a remote method BzrDir.find_repository.
1509
        """
2018.5.163 by Andrew Bennetts
Deal with various review comments from Robert.
1510
        # We intentionally don't call the parent class's __init__, because it
1511
        # will try to assign to self.tags, which is a property in this subclass.
1512
        # And the parent's __init__ doesn't do much anyway.
2978.7.1 by John Arbash Meinel
Fix bug #162486, by having RemoteBranch properly initialize self._revision_id_to_revno_map.
1513
        self._revision_id_to_revno_cache = None
3949.2.6 by Ian Clatworthy
review feedback from jam
1514
        self._partial_revision_id_to_revno_cache = {}
2018.5.105 by Andrew Bennetts
Implement revision_history caching for RemoteBranch.
1515
        self._revision_history_cache = None
3441.5.1 by Andrew Bennetts
Avoid necessarily calling get_parent_map when pushing.
1516
        self._last_revision_info_cache = None
3949.3.4 by Ian Clatworthy
jam feedback: start & stop limits; simple caching
1517
        self._merge_sorted_revisions_cache = None
1752.2.64 by Andrew Bennetts
Improve how RemoteBzrDir.open_branch works to handle references and not double-open repositories.
1518
        self.bzrdir = remote_bzrdir
2018.5.51 by Wouter van Heyst
Test and implement RemoteBranch.last_revision_info()
1519
        if _client is not None:
1520
            self._client = _client
1521
        else:
3313.2.1 by Andrew Bennetts
Change _SmartClient's API to accept a medium and a base, rather than a _SharedConnection.
1522
            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.
1523
        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.
1524
        if real_branch is not None:
1525
            self._real_branch = real_branch
2018.5.79 by Andrew Bennetts
Implement RemoteBranch.lock_write/unlock as smart operations.
1526
            # Give the remote repository the matching real repo.
2018.5.97 by Andrew Bennetts
Fix more tests.
1527
            real_repo = self._real_branch.repository
1528
            if isinstance(real_repo, RemoteRepository):
1529
                real_repo._ensure_real()
1530
                real_repo = real_repo._real_repository
1531
            self.repository._set_real_repository(real_repo)
2018.5.79 by Andrew Bennetts
Implement RemoteBranch.lock_write/unlock as smart operations.
1532
            # Give the branch the remote repository to let fast-pathing happen.
1533
            self._real_branch.repository = self.repository
2018.5.70 by Robert Collins
Only try to get real repositories when an operation requires them.
1534
        else:
1535
            self._real_branch = None
2018.5.59 by Robert Collins
Get BranchConfig working somewhat on RemoteBranches (Robert Collins, Vincent Ladeuil).
1536
        # Fill out expected attributes of branch for bzrlib api users.
1752.2.64 by Andrew Bennetts
Improve how RemoteBzrDir.open_branch works to handle references and not double-open repositories.
1537
        self._format = RemoteBranchFormat()
2018.5.55 by Robert Collins
Give RemoteBranch a base url in line with the Branch protocol.
1538
        self.base = self.bzrdir.root_transport.base
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.
1539
        self._control_files = None
2018.5.79 by Andrew Bennetts
Implement RemoteBranch.lock_write/unlock as smart operations.
1540
        self._lock_mode = None
1541
        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.
1542
        self._repo_lock_token = None
2018.5.79 by Andrew Bennetts
Implement RemoteBranch.lock_write/unlock as smart operations.
1543
        self._lock_count = 0
1544
        self._leave_lock = False
3681.1.2 by Robert Collins
Adjust for trunk.
1545
        # 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)
1546
        hooks = branch.Branch.hooks['open']
1547
        for hook in hooks:
1548
            hook(self)
3691.2.7 by Martin Pool
FakeClient can know what calls to expect
1549
        self._setup_stacking()
3691.2.1 by Martin Pool
RemoteBranch must configure stacking into the repository
1550
1551
    def _setup_stacking(self):
1552
        # 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
1553
        # the vfs branch.
3691.2.1 by Martin Pool
RemoteBranch must configure stacking into the repository
1554
        try:
1555
            fallback_url = self.get_stacked_on_url()
1556
        except (errors.NotStacked, errors.UnstackableBranchFormat,
1557
            errors.UnstackableRepositoryFormat), e:
3691.2.7 by Martin Pool
FakeClient can know what calls to expect
1558
            return
1559
        # it's relative to this branch...
1560
        fallback_url = urlutils.join(self.base, fallback_url)
1561
        transports = [self.bzrdir.root_transport]
1562
        if self._real_branch is not None:
1563
            transports.append(self._real_branch._transport)
3830.2.1 by Aaron Bentley
Fix HPSS with branch stacked on repository branch
1564
        stacked_on = branch.Branch.open(fallback_url,
1565
                                        possible_transports=transports)
1566
        self.repository.add_fallback_repository(stacked_on.repository)
1752.2.64 by Andrew Bennetts
Improve how RemoteBzrDir.open_branch works to handle references and not double-open repositories.
1567
3468.1.1 by Martin Pool
Update more users of default file modes from control_files to bzrdir
1568
    def _get_real_transport(self):
3407.2.16 by Martin Pool
Remove RemoteBranch reliance on control_files._transport
1569
        # if we try vfs access, return the real branch's vfs transport
1570
        self._ensure_real()
1571
        return self._real_branch._transport
1572
3468.1.1 by Martin Pool
Update more users of default file modes from control_files to bzrdir
1573
    _transport = property(_get_real_transport)
3407.2.16 by Martin Pool
Remove RemoteBranch reliance on control_files._transport
1574
2477.1.1 by Martin Pool
Add RemoteBranch repr
1575
    def __str__(self):
1576
        return "%s(%s)" % (self.__class__.__name__, self.base)
1577
1578
    __repr__ = __str__
1579
2018.5.70 by Robert Collins
Only try to get real repositories when an operation requires them.
1580
    def _ensure_real(self):
1581
        """Ensure that there is a _real_branch set.
1582
2018.5.163 by Andrew Bennetts
Deal with various review comments from Robert.
1583
        Used before calls to self._real_branch.
2018.5.70 by Robert Collins
Only try to get real repositories when an operation requires them.
1584
        """
3407.2.16 by Martin Pool
Remove RemoteBranch reliance on control_files._transport
1585
        if self._real_branch is None:
3376.2.4 by Martin Pool
Remove every assert statement from bzrlib!
1586
            if not vfs.vfs_enabled():
1587
                raise AssertionError('smart server vfs must be enabled '
1588
                    'to use vfs implementation')
2018.5.70 by Robert Collins
Only try to get real repositories when an operation requires them.
1589
            self.bzrdir._ensure_real()
1590
            self._real_branch = self.bzrdir._real_bzrdir.open_branch()
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.
1591
            if self.repository._real_repository is None:
1592
                # Give the remote repository the matching real repo.
1593
                real_repo = self._real_branch.repository
1594
                if isinstance(real_repo, RemoteRepository):
1595
                    real_repo._ensure_real()
1596
                    real_repo = real_repo._real_repository
1597
                self.repository._set_real_repository(real_repo)
1598
            # Give the real branch the remote repository to let fast-pathing
1599
            # happen.
2018.5.70 by Robert Collins
Only try to get real repositories when an operation requires them.
1600
            self._real_branch.repository = self.repository
2018.14.1 by Andrew Bennetts
Update to current hpss branch? Fix lots of test failures.
1601
            if self._lock_mode == 'r':
1602
                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.
1603
            elif self._lock_mode == 'w':
1604
                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.
1605
3533.3.1 by Andrew Bennetts
Remove duplication of error translation in bzrlib/remote.py.
1606
    def _translate_error(self, err, **context):
1607
        self.repository._translate_error(err, branch=self, **context)
1608
3441.5.1 by Andrew Bennetts
Avoid necessarily calling get_parent_map when pushing.
1609
    def _clear_cached_state(self):
1610
        super(RemoteBranch, self)._clear_cached_state()
3441.5.5 by Andrew Bennetts
Some small tweaks and comments.
1611
        if self._real_branch is not None:
1612
            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.
1613
1614
    def _clear_cached_state_of_remote_branch_only(self):
1615
        """Like _clear_cached_state, but doesn't clear the cache of
1616
        self._real_branch.
1617
1618
        This is useful when falling back to calling a method of
1619
        self._real_branch that changes state.  In that case the underlying
1620
        branch changes, so we need to invalidate this RemoteBranch's cache of
1621
        it.  However, there's no need to invalidate the _real_branch's cache
1622
        too, in fact doing so might harm performance.
1623
        """
1624
        super(RemoteBranch, self)._clear_cached_state()
3943.8.1 by Marius Kruger
remove all trailing whitespace from bzr source
1625
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.
1626
    @property
1627
    def control_files(self):
1628
        # Defer actually creating RemoteBranchLockableFiles until its needed,
1629
        # because it triggers an _ensure_real that we otherwise might not need.
1630
        if self._control_files is None:
1631
            self._control_files = RemoteBranchLockableFiles(
1632
                self.bzrdir, self._client)
1633
        return self._control_files
1634
2018.5.166 by Andrew Bennetts
Small changes in response to Aaron's review.
1635
    def _get_checkout_format(self):
1636
        self._ensure_real()
1637
        return self._real_branch._get_checkout_format()
1638
2018.5.60 by Robert Collins
More missing methods from RemoteBranch and RemoteRepository to let 'info' get further.
1639
    def get_physical_lock_status(self):
1640
        """See Branch.get_physical_lock_status()."""
1641
        # should be an API call to the server, as branches must be lockable.
2018.5.70 by Robert Collins
Only try to get real repositories when an operation requires them.
1642
        self._ensure_real()
2018.5.60 by Robert Collins
More missing methods from RemoteBranch and RemoteRepository to let 'info' get further.
1643
        return self._real_branch.get_physical_lock_status()
1644
3537.3.1 by Martin Pool
Rename branch.get_stacked_on to get_stacked_on_url
1645
    def get_stacked_on_url(self):
3221.11.2 by Robert Collins
Create basic stackable branch facility.
1646
        """Get the URL this branch is stacked against.
1647
1648
        :raises NotStacked: If the branch is not stacked.
1649
        :raises UnstackableBranchFormat: If the branch does not support
1650
            stacking.
1651
        :raises UnstackableRepositoryFormat: If the repository does not support
1652
            stacking.
1653
        """
3691.2.12 by Martin Pool
Add test for coping without Branch.get_stacked_on_url
1654
        try:
3786.2.3 by Andrew Bennetts
Remove duplicated 'call & translate errors' code in bzrlib.remote.
1655
            # there may not be a repository yet, so we can't use
1656
            # 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
1657
            response = self._client.call('Branch.get_stacked_on_url',
1658
                self._remote_path())
1659
        except errors.ErrorFromSmartServer, err:
1660
            # there may not be a repository yet, so we can't call through
1661
            # its _translate_error
1662
            _translate_error(err, branch=self)
1663
        except errors.UnknownSmartMethod, err:
1664
            self._ensure_real()
1665
            return self._real_branch.get_stacked_on_url()
3786.2.3 by Andrew Bennetts
Remove duplicated 'call & translate errors' code in bzrlib.remote.
1666
        if response[0] != 'ok':
1667
            raise errors.UnexpectedSmartServerResponse(response)
1668
        return response[1]
3221.11.2 by Robert Collins
Create basic stackable branch facility.
1669
1752.2.31 by Martin Pool
[broken] some support for write operations over hpss
1670
    def lock_read(self):
3692.1.1 by Andrew Bennetts
Make RemoteBranch.lock_write lock the repository too.
1671
        self.repository.lock_read()
2018.14.1 by Andrew Bennetts
Update to current hpss branch? Fix lots of test failures.
1672
        if not self._lock_mode:
1673
            self._lock_mode = 'r'
1674
            self._lock_count = 1
1675
            if self._real_branch is not None:
1676
                self._real_branch.lock_read()
1677
        else:
1678
            self._lock_count += 1
1752.2.52 by Andrew Bennetts
Flesh out more Remote* methods needed to open and initialise remote branches/trees/repositories.
1679
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).
1680
    def _remote_lock_write(self, token):
1681
        if token is None:
2018.5.79 by Andrew Bennetts
Implement RemoteBranch.lock_write/unlock as smart operations.
1682
            branch_token = repo_token = ''
1683
        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).
1684
            branch_token = token
1685
            repo_token = self.repository.lock_write()
1686
            self.repository.unlock()
3786.2.3 by Andrew Bennetts
Remove duplicated 'call & translate errors' code in bzrlib.remote.
1687
        err_context = {'token': token}
1688
        response = self._call(
1689
            'Branch.lock_write', self._remote_path(), branch_token,
1690
            repo_token or '', **err_context)
3245.4.24 by Andrew Bennetts
Consistently raise errors from the server as ErrorFromSmartServer exceptions.
1691
        if response[0] != 'ok':
2555.1.1 by Martin Pool
Remove use of 'assert False' to raise an exception unconditionally
1692
            raise errors.UnexpectedSmartServerResponse(response)
3245.4.24 by Andrew Bennetts
Consistently raise errors from the server as ErrorFromSmartServer exceptions.
1693
        ok, branch_token, repo_token = response
1694
        return branch_token, repo_token
3943.8.1 by Marius Kruger
remove all trailing whitespace from bzr source
1695
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).
1696
    def lock_write(self, token=None):
2018.5.79 by Andrew Bennetts
Implement RemoteBranch.lock_write/unlock as smart operations.
1697
        if not self._lock_mode:
3692.1.3 by Andrew Bennetts
Delete some cruft (like the _ensure_real call in RemoteBranch.lock_write), improve some comments, and wrap some long lines.
1698
            # 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).
1699
            remote_tokens = self._remote_lock_write(token)
2018.5.79 by Andrew Bennetts
Implement RemoteBranch.lock_write/unlock as smart operations.
1700
            self._lock_token, self._repo_lock_token = remote_tokens
3376.2.4 by Martin Pool
Remove every assert statement from bzrlib!
1701
            if not self._lock_token:
1702
                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.
1703
            # 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.
1704
            self.repository.lock_write(
1705
                self._repo_lock_token, _skip_rpc=True)
3692.1.1 by Andrew Bennetts
Make RemoteBranch.lock_write lock the repository too.
1706
2018.5.79 by Andrew Bennetts
Implement RemoteBranch.lock_write/unlock as smart operations.
1707
            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.
1708
                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).
1709
            if token is not None:
2018.5.79 by Andrew Bennetts
Implement RemoteBranch.lock_write/unlock as smart operations.
1710
                self._leave_lock = True
1711
            else:
1712
                self._leave_lock = False
1713
            self._lock_mode = 'w'
1714
            self._lock_count = 1
1715
        elif self._lock_mode == 'r':
1716
            raise errors.ReadOnlyTransaction
1717
        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).
1718
            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.
1719
                # A token was given to lock_write, and we're relocking, so
1720
                # check that the given token actually matches the one we
1721
                # 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).
1722
                if token != self._lock_token:
1723
                    raise errors.TokenMismatch(token, self._lock_token)
2018.5.79 by Andrew Bennetts
Implement RemoteBranch.lock_write/unlock as smart operations.
1724
            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.
1725
            # Re-lock the repository too.
3692.1.2 by Andrew Bennetts
Fix regression introduced by fix, and add a test for that regression.
1726
            self.repository.lock_write(self._repo_lock_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.
1727
        return self._lock_token or None
2018.5.79 by Andrew Bennetts
Implement RemoteBranch.lock_write/unlock as smart operations.
1728
1729
    def _unlock(self, branch_token, repo_token):
3786.2.3 by Andrew Bennetts
Remove duplicated 'call & translate errors' code in bzrlib.remote.
1730
        err_context = {'token': str((branch_token, repo_token))}
1731
        response = self._call(
1732
            'Branch.unlock', self._remote_path(), branch_token,
1733
            repo_token or '', **err_context)
2018.5.79 by Andrew Bennetts
Implement RemoteBranch.lock_write/unlock as smart operations.
1734
        if response == ('ok',):
1735
            return
3245.4.24 by Andrew Bennetts
Consistently raise errors from the server as ErrorFromSmartServer exceptions.
1736
        raise errors.UnexpectedSmartServerResponse(response)
1752.2.31 by Martin Pool
[broken] some support for write operations over hpss
1737
1738
    def unlock(self):
3692.1.1 by Andrew Bennetts
Make RemoteBranch.lock_write lock the repository too.
1739
        try:
1740
            self._lock_count -= 1
1741
            if not self._lock_count:
1742
                self._clear_cached_state()
1743
                mode = self._lock_mode
1744
                self._lock_mode = None
1745
                if self._real_branch is not None:
1746
                    if (not self._leave_lock and mode == 'w' and
1747
                        self._repo_lock_token):
1748
                        # If this RemoteBranch will remove the physical lock
1749
                        # for the repository, make sure the _real_branch
1750
                        # doesn't do it first.  (Because the _real_branch's
1751
                        # repository is set to be the RemoteRepository.)
1752
                        self._real_branch.repository.leave_lock_in_place()
1753
                    self._real_branch.unlock()
1754
                if mode != 'w':
1755
                    # Only write-locked branched need to make a remote method
1756
                    # call to perfom the unlock.
1757
                    return
1758
                if not self._lock_token:
1759
                    raise AssertionError('Locked, but no token!')
1760
                branch_token = self._lock_token
1761
                repo_token = self._repo_lock_token
1762
                self._lock_token = None
1763
                self._repo_lock_token = None
1764
                if not self._leave_lock:
1765
                    self._unlock(branch_token, repo_token)
1766
        finally:
1767
            self.repository.unlock()
1752.2.52 by Andrew Bennetts
Flesh out more Remote* methods needed to open and initialise remote branches/trees/repositories.
1768
1769
    def break_lock(self):
2018.5.70 by Robert Collins
Only try to get real repositories when an operation requires them.
1770
        self._ensure_real()
1752.2.52 by Andrew Bennetts
Flesh out more Remote* methods needed to open and initialise remote branches/trees/repositories.
1771
        return self._real_branch.break_lock()
1752.2.31 by Martin Pool
[broken] some support for write operations over hpss
1772
2018.5.79 by Andrew Bennetts
Implement RemoteBranch.lock_write/unlock as smart operations.
1773
    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.
1774
        if not self._lock_token:
1775
            raise NotImplementedError(self.leave_lock_in_place)
2018.5.79 by Andrew Bennetts
Implement RemoteBranch.lock_write/unlock as smart operations.
1776
        self._leave_lock = True
1777
1778
    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.
1779
        if not self._lock_token:
3015.2.15 by Robert Collins
Review feedback.
1780
            raise NotImplementedError(self.dont_leave_lock_in_place)
2018.5.79 by Andrew Bennetts
Implement RemoteBranch.lock_write/unlock as smart operations.
1781
        self._leave_lock = False
1782
3441.5.1 by Andrew Bennetts
Avoid necessarily calling get_parent_map when pushing.
1783
    def _last_revision_info(self):
3786.2.3 by Andrew Bennetts
Remove duplicated 'call & translate errors' code in bzrlib.remote.
1784
        response = self._call('Branch.last_revision_info', self._remote_path())
3376.2.4 by Martin Pool
Remove every assert statement from bzrlib!
1785
        if response[0] != 'ok':
1786
            raise SmartProtocolError('unexpected response code %s' % (response,))
2018.5.51 by Wouter van Heyst
Test and implement RemoteBranch.last_revision_info()
1787
        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.
1788
        last_revision = response[2]
2018.5.51 by Wouter van Heyst
Test and implement RemoteBranch.last_revision_info()
1789
        return (revno, last_revision)
1790
2018.5.105 by Andrew Bennetts
Implement revision_history caching for RemoteBranch.
1791
    def _gen_revision_history(self):
1792
        """See Branch._gen_revision_history()."""
3786.2.3 by Andrew Bennetts
Remove duplicated 'call & translate errors' code in bzrlib.remote.
1793
        response_tuple, response_handler = self._call_expecting_body(
3691.2.3 by Martin Pool
Factor out RemoteBranch._remote_path() and disable RemoteBranch stacking
1794
            '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.
1795
        if response_tuple[0] != 'ok':
3452.2.2 by Andrew Bennetts
Experimental PackRepository.{check_references,autopack} RPCs.
1796
            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.
1797
        result = response_handler.read_body_bytes().split('\x00')
2018.5.38 by Robert Collins
Implement RemoteBranch.revision_history().
1798
        if result == ['']:
1799
            return []
1800
        return result
1752.2.30 by Martin Pool
Start adding a RemoteBzrDir, etc
1801
3691.2.3 by Martin Pool
Factor out RemoteBranch._remote_path() and disable RemoteBranch stacking
1802
    def _remote_path(self):
1803
        return self.bzrdir._path_for_remote_call(self._client)
1804
3441.5.18 by Andrew Bennetts
Fix some test failures.
1805
    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.
1806
            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.
1807
        # This performs additional work to meet the hook contract; while its
1808
        # undesirable, we have to synthesise the revno to call the hook, and
1809
        # not calling the hook is worse as it means changes can't be prevented.
1810
        # Having calculated this though, we can't just call into
1811
        # set_last_revision_info as a simple call, because there is a set_rh
1812
        # hook that some folk may still be using.
1813
        old_revno, old_revid = self.last_revision_info()
1814
        history = self._lefthand_history(revision_id)
1815
        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.
1816
        err_context = {'other_branch': other_branch}
1817
        response = self._call('Branch.set_last_revision_ex',
1818
            self._remote_path(), self._lock_token, self._repo_lock_token,
1819
            revision_id, int(allow_diverged), int(allow_overwrite_descendant),
1820
            **err_context)
3441.5.6 by Andrew Bennetts
Greatly simplify RemoteBranch.update_revisions. Still needs more tests.
1821
        self._clear_cached_state()
3441.5.18 by Andrew Bennetts
Fix some test failures.
1822
        if len(response) != 3 and response[0] != 'ok':
3441.5.6 by Andrew Bennetts
Greatly simplify RemoteBranch.update_revisions. Still needs more tests.
1823
            raise errors.UnexpectedSmartServerResponse(response)
3441.5.18 by Andrew Bennetts
Fix some test failures.
1824
        new_revno, new_revision_id = response[1:]
1825
        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.
1826
        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.
1827
        if self._real_branch is not None:
1828
            cache = new_revno, new_revision_id
1829
            self._real_branch._last_revision_info_cache = cache
3441.5.6 by Andrew Bennetts
Greatly simplify RemoteBranch.update_revisions. Still needs more tests.
1830
3441.5.1 by Andrew Bennetts
Avoid necessarily calling get_parent_map when pushing.
1831
    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.
1832
        old_revno, old_revid = self.last_revision_info()
1833
        # This performs additional work to meet the hook contract; while its
1834
        # undesirable, we have to synthesise the revno to call the hook, and
1835
        # not calling the hook is worse as it means changes can't be prevented.
1836
        # Having calculated this though, we can't just call into
1837
        # set_last_revision_info as a simple call, because there is a set_rh
1838
        # hook that some folk may still be using.
1839
        history = self._lefthand_history(revision_id)
1840
        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.
1841
        self._clear_cached_state()
3786.2.3 by Andrew Bennetts
Remove duplicated 'call & translate errors' code in bzrlib.remote.
1842
        response = self._call('Branch.set_last_revision',
1843
            self._remote_path(), self._lock_token, self._repo_lock_token,
1844
            revision_id)
3441.5.1 by Andrew Bennetts
Avoid necessarily calling get_parent_map when pushing.
1845
        if response != ('ok',):
1846
            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.
1847
        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.
1848
2018.14.1 by Andrew Bennetts
Update to current hpss branch? Fix lots of test failures.
1849
    @needs_write_lock
1752.2.52 by Andrew Bennetts
Flesh out more Remote* methods needed to open and initialise remote branches/trees/repositories.
1850
    def set_revision_history(self, rev_history):
2018.12.3 by Andrew Bennetts
Add a Branch.set_last_revision smart method, and make RemoteBranch.set_revision_history use it.
1851
        # Send just the tip revision of the history; the server will generate
1852
        # the full history from that.  If the revision doesn't exist in this
1853
        # branch, NoSuchRevision will be raised.
1854
        if rev_history == []:
2018.5.170 by Andrew Bennetts
Use 'null:' instead of '' to mean NULL_REVISION on the wire.
1855
            rev_id = 'null:'
2018.12.3 by Andrew Bennetts
Add a Branch.set_last_revision smart method, and make RemoteBranch.set_revision_history use it.
1856
        else:
1857
            rev_id = rev_history[-1]
3441.5.1 by Andrew Bennetts
Avoid necessarily calling get_parent_map when pushing.
1858
        self._set_last_revision(rev_id)
4005.2.1 by Robert Collins
Fix RemoteBranch to be used correctly in tests using bzr+ssh, to fire off Branch hooks correctly, and improve the branch_implementations tests to check that making a branch gets the right format under test.
1859
        for hook in branch.Branch.hooks['set_rh']:
1860
            hook(self, rev_history)
2018.5.105 by Andrew Bennetts
Implement revision_history caching for RemoteBranch.
1861
        self._cache_revision_history(rev_history)
1752.2.52 by Andrew Bennetts
Flesh out more Remote* methods needed to open and initialise remote branches/trees/repositories.
1862
1863
    def get_parent(self):
2018.5.70 by Robert Collins
Only try to get real repositories when an operation requires them.
1864
        self._ensure_real()
1752.2.52 by Andrew Bennetts
Flesh out more Remote* methods needed to open and initialise remote branches/trees/repositories.
1865
        return self._real_branch.get_parent()
3943.8.1 by Marius Kruger
remove all trailing whitespace from bzr source
1866
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.
1867
    def _get_parent_location(self):
1868
        # Used by tests, when checking normalisation of given vs stored paths.
1869
        self._ensure_real()
1870
        return self._real_branch._get_parent_location()
4032.1.1 by John Arbash Meinel
Merge the removal of all trailing whitespace, and resolve conflicts.
1871
1752.2.63 by Andrew Bennetts
Delegate set_parent.
1872
    def set_parent(self, url):
2018.5.70 by Robert Collins
Only try to get real repositories when an operation requires them.
1873
        self._ensure_real()
1752.2.63 by Andrew Bennetts
Delegate set_parent.
1874
        return self._real_branch.set_parent(url)
3943.8.1 by Marius Kruger
remove all trailing whitespace from bzr source
1875
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.
1876
    def _set_parent_location(self, url):
1877
        # Used by tests, to poke bad urls into branch configurations
1878
        if url is None:
1879
            self.set_parent(url)
1880
        else:
1881
            self._ensure_real()
1882
            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.
1883
3537.3.3 by Martin Pool
Rename Branch.set_stacked_on to set_stacked_on_url
1884
    def set_stacked_on_url(self, stacked_location):
3221.18.1 by Ian Clatworthy
tweaks by ianc during review
1885
        """Set the URL this branch is stacked against.
3221.11.2 by Robert Collins
Create basic stackable branch facility.
1886
1887
        :raises UnstackableBranchFormat: If the branch does not support
1888
            stacking.
1889
        :raises UnstackableRepositoryFormat: If the repository does not support
1890
            stacking.
1891
        """
1892
        self._ensure_real()
3537.3.3 by Martin Pool
Rename Branch.set_stacked_on to set_stacked_on_url
1893
        return self._real_branch.set_stacked_on_url(stacked_location)
3221.11.2 by Robert Collins
Create basic stackable branch facility.
1894
2018.5.94 by Andrew Bennetts
Various small changes in aid of making tests pass (including deleting one invalid test).
1895
    def sprout(self, to_bzrdir, revision_id=None):
3793.1.1 by Andrew Bennetts
Make RemoteBranch.sprout use Branch.sprout when possible.
1896
        branch_format = to_bzrdir._format._branch_format
1897
        if (branch_format is None or
1898
            isinstance(branch_format, RemoteBranchFormat)):
1899
            # The to_bzrdir specifies RemoteBranchFormat (or no format, which
1900
            # implies the same thing), but RemoteBranches can't be created at
1901
            # arbitrary URLs.  So create a branch in the same format as
1902
            # _real_branch instead.
1903
            # XXX: if to_bzrdir is a RemoteBzrDir, this should perhaps do
1904
            # to_bzrdir.create_branch to create a RemoteBranch after all...
1905
            self._ensure_real()
1906
            result = self._real_branch._format.initialize(to_bzrdir)
1907
            self.copy_content_into(result, revision_id=revision_id)
1908
            result.set_parent(self.bzrdir.root_transport.base)
1909
        else:
1910
            result = branch.Branch.sprout(
1911
                self, to_bzrdir, revision_id=revision_id)
2018.5.94 by Andrew Bennetts
Various small changes in aid of making tests pass (including deleting one invalid test).
1912
        return result
1913
2018.14.1 by Andrew Bennetts
Update to current hpss branch? Fix lots of test failures.
1914
    @needs_write_lock
2477.1.2 by Martin Pool
Rename push/pull back to 'run_hooks' (jameinel)
1915
    def pull(self, source, overwrite=False, stop_revision=None,
2477.1.9 by Martin Pool
Review cleanups from John, mostly docs
1916
             **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.
1917
        self._clear_cached_state_of_remote_branch_only()
2018.14.1 by Andrew Bennetts
Update to current hpss branch? Fix lots of test failures.
1918
        self._ensure_real()
3482.1.1 by John Arbash Meinel
Fix bug #238149, RemoteBranch.pull needs to return the _real_branch's pull result.
1919
        return self._real_branch.pull(
2477.1.2 by Martin Pool
Rename push/pull back to 'run_hooks' (jameinel)
1920
            source, overwrite=overwrite, stop_revision=stop_revision,
3489.2.4 by Andrew Bennetts
Fix all tests broken by fixing make_branch_and_tree.
1921
            _override_hook_target=self, **kwargs)
2018.14.1 by Andrew Bennetts
Update to current hpss branch? Fix lots of test failures.
1922
2018.14.3 by Andrew Bennetts
Make a couple more branch_implementations tests pass.
1923
    @needs_read_lock
1924
    def push(self, target, overwrite=False, stop_revision=None):
1925
        self._ensure_real()
2018.5.97 by Andrew Bennetts
Fix more tests.
1926
        return self._real_branch.push(
2477.1.5 by Martin Pool
More cleanups of Branch.push to get the right behaviour with RemoteBranches
1927
            target, overwrite=overwrite, stop_revision=stop_revision,
1928
            _override_hook_source_branch=self)
2018.14.3 by Andrew Bennetts
Make a couple more branch_implementations tests pass.
1929
1930
    def is_locked(self):
1931
        return self._lock_count >= 1
1932
3634.2.1 by John Arbash Meinel
Thunk over to the real branch's revision_id_to_revno.
1933
    @needs_read_lock
1934
    def revision_id_to_revno(self, revision_id):
1935
        self._ensure_real()
1936
        return self._real_branch.revision_id_to_revno(revision_id)
1937
2892.2.1 by Andrew Bennetts
Add Branch.set_last_revision_info smart method, and make the RemoteBranch client use it.
1938
    @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.
1939
    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.
1940
        # XXX: These should be returned by the set_last_revision_info verb
1941
        old_revno, old_revid = self.last_revision_info()
1942
        self._run_pre_change_branch_tip_hooks(revno, revision_id)
2892.2.1 by Andrew Bennetts
Add Branch.set_last_revision_info smart method, and make the RemoteBranch client use it.
1943
        revision_id = ensure_null(revision_id)
3297.4.2 by Andrew Bennetts
Add backwards compatibility for servers older than 1.4.
1944
        try:
3786.2.3 by Andrew Bennetts
Remove duplicated 'call & translate errors' code in bzrlib.remote.
1945
            response = self._call('Branch.set_last_revision_info',
1946
                self._remote_path(), self._lock_token, self._repo_lock_token,
1947
                str(revno), revision_id)
3297.4.2 by Andrew Bennetts
Add backwards compatibility for servers older than 1.4.
1948
        except errors.UnknownSmartMethod:
1949
            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.
1950
            self._clear_cached_state_of_remote_branch_only()
3441.5.1 by Andrew Bennetts
Avoid necessarily calling get_parent_map when pushing.
1951
            self._real_branch.set_last_revision_info(revno, revision_id)
1952
            self._last_revision_info_cache = revno, revision_id
1953
            return
2892.2.1 by Andrew Bennetts
Add Branch.set_last_revision_info smart method, and make the RemoteBranch client use it.
1954
        if response == ('ok',):
1955
            self._clear_cached_state()
3441.5.1 by Andrew Bennetts
Avoid necessarily calling get_parent_map when pushing.
1956
            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.
1957
            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.
1958
            # Update the _real_branch's cache too.
1959
            if self._real_branch is not None:
1960
                cache = self._last_revision_info_cache
1961
                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.
1962
        else:
1963
            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.
1964
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.
1965
    @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.
1966
    def generate_revision_history(self, revision_id, last_rev=None,
1967
                                  other_branch=None):
3441.5.6 by Andrew Bennetts
Greatly simplify RemoteBranch.update_revisions. Still needs more tests.
1968
        medium = self._client._medium
3441.5.23 by Andrew Bennetts
Fix test failures.
1969
        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.
1970
            # 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.
1971
            try:
3441.5.18 by Andrew Bennetts
Fix some test failures.
1972
                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.
1973
                    allow_diverged=True, allow_overwrite_descendant=True)
3441.5.6 by Andrew Bennetts
Greatly simplify RemoteBranch.update_revisions. Still needs more tests.
1974
                return
3441.5.18 by Andrew Bennetts
Fix some test failures.
1975
            except errors.UnknownSmartMethod:
3441.5.23 by Andrew Bennetts
Fix test failures.
1976
                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.
1977
        self._clear_cached_state_of_remote_branch_only()
4005.2.1 by Robert Collins
Fix RemoteBranch to be used correctly in tests using bzr+ssh, to fire off Branch hooks correctly, and improve the branch_implementations tests to check that making a branch gets the right format under test.
1978
        self.set_revision_history(self._lefthand_history(revision_id,
1979
            last_rev=last_rev,other_branch=other_branch))
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.
1980
2018.5.96 by Andrew Bennetts
Merge from bzr.dev, resolving the worst of the semantic conflicts, but there's
1981
    @property
1982
    def tags(self):
1983
        self._ensure_real()
1984
        return self._real_branch.tags
1985
2018.5.97 by Andrew Bennetts
Fix more tests.
1986
    def set_push_location(self, location):
1987
        self._ensure_real()
1988
        return self._real_branch.set_push_location(location)
1989
2018.18.25 by Martin Pool
Repository.tarball fixes for python2.4
1990
1991
def _extract_tar(tar, to_dir):
1992
    """Extract all the contents of a tarfile object.
1993
1994
    A replacement for extractall, which is not present in python2.4
1995
    """
1996
    for tarinfo in tar:
1997
        tar.extract(tarinfo, to_dir)
3533.3.1 by Andrew Bennetts
Remove duplication of error translation in bzrlib/remote.py.
1998
1999
2000
def _translate_error(err, **context):
2001
    """Translate an ErrorFromSmartServer into a more useful error.
2002
2003
    Possible context keys:
2004
      - branch
2005
      - repository
2006
      - bzrdir
2007
      - token
2008
      - other_branch
3779.3.2 by Andrew Bennetts
Unify error translation done in bzrlib.remote and bzrlib.transport.remote.
2009
      - path
3690.1.1 by Andrew Bennetts
Unexpected error responses from a smart server no longer cause the client to traceback.
2010
2011
    If the error from the server doesn't match a known pattern, then
3690.1.2 by Andrew Bennetts
Rename UntranslateableErrorFromSmartServer -> UnknownErrorFromSmartServer.
2012
    UnknownErrorFromSmartServer is raised.
3533.3.1 by Andrew Bennetts
Remove duplication of error translation in bzrlib/remote.py.
2013
    """
2014
    def find(name):
3533.3.4 by Andrew Bennetts
Add tests for _translate_error's robustness.
2015
        try:
2016
            return context[name]
3779.3.2 by Andrew Bennetts
Unify error translation done in bzrlib.remote and bzrlib.transport.remote.
2017
        except KeyError, key_err:
2018
            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.
2019
            raise err
3779.3.2 by Andrew Bennetts
Unify error translation done in bzrlib.remote and bzrlib.transport.remote.
2020
    def get_path():
3779.3.3 by Andrew Bennetts
Add a docstring.
2021
        """Get the path from the context if present, otherwise use first error
2022
        arg.
2023
        """
3779.3.2 by Andrew Bennetts
Unify error translation done in bzrlib.remote and bzrlib.transport.remote.
2024
        try:
2025
            return context['path']
2026
        except KeyError, key_err:
2027
            try:
2028
                return err.error_args[0]
2029
            except IndexError, idx_err:
2030
                mutter(
2031
                    'Missing key %r in context %r', key_err.args[0], context)
2032
                raise err
2033
3533.3.1 by Andrew Bennetts
Remove duplication of error translation in bzrlib/remote.py.
2034
    if err.error_verb == 'NoSuchRevision':
2035
        raise NoSuchRevision(find('branch'), err.error_args[0])
2036
    elif err.error_verb == 'nosuchrevision':
2037
        raise NoSuchRevision(find('repository'), err.error_args[0])
2038
    elif err.error_tuple == ('nobranch',):
3533.3.4 by Andrew Bennetts
Add tests for _translate_error's robustness.
2039
        raise errors.NotBranchError(path=find('bzrdir').root_transport.base)
3533.3.1 by Andrew Bennetts
Remove duplication of error translation in bzrlib/remote.py.
2040
    elif err.error_verb == 'norepository':
2041
        raise errors.NoRepositoryPresent(find('bzrdir'))
2042
    elif err.error_verb == 'LockContention':
2043
        raise errors.LockContention('(remote lock)')
2044
    elif err.error_verb == 'UnlockableTransport':
3533.3.4 by Andrew Bennetts
Add tests for _translate_error's robustness.
2045
        raise errors.UnlockableTransport(find('bzrdir').root_transport)
3533.3.1 by Andrew Bennetts
Remove duplication of error translation in bzrlib/remote.py.
2046
    elif err.error_verb == 'LockFailed':
2047
        raise errors.LockFailed(err.error_args[0], err.error_args[1])
2048
    elif err.error_verb == 'TokenMismatch':
2049
        raise errors.TokenMismatch(find('token'), '(remote token)')
2050
    elif err.error_verb == 'Diverged':
2051
        raise errors.DivergedBranches(find('branch'), find('other_branch'))
3577.1.1 by Andrew Bennetts
Cherry-pick TipChangeRejected changes from pre-branch-tip-changed-hook loom.
2052
    elif err.error_verb == 'TipChangeRejected':
2053
        raise errors.TipChangeRejected(err.error_args[0].decode('utf8'))
3691.2.6 by Martin Pool
Disable RemoteBranch stacking, but get get_stacked_on_url working, and passing back exceptions
2054
    elif err.error_verb == 'UnstackableBranchFormat':
2055
        raise errors.UnstackableBranchFormat(*err.error_args)
2056
    elif err.error_verb == 'UnstackableRepositoryFormat':
2057
        raise errors.UnstackableRepositoryFormat(*err.error_args)
2058
    elif err.error_verb == 'NotStacked':
2059
        raise errors.NotStacked(branch=find('branch'))
3779.3.1 by Andrew Bennetts
Move encoding/decoding logic of PermissionDenied and ReadError so that it happens for all RPCs.
2060
    elif err.error_verb == 'PermissionDenied':
3779.3.2 by Andrew Bennetts
Unify error translation done in bzrlib.remote and bzrlib.transport.remote.
2061
        path = get_path()
3779.3.1 by Andrew Bennetts
Move encoding/decoding logic of PermissionDenied and ReadError so that it happens for all RPCs.
2062
        if len(err.error_args) >= 2:
2063
            extra = err.error_args[1]
3779.3.2 by Andrew Bennetts
Unify error translation done in bzrlib.remote and bzrlib.transport.remote.
2064
        else:
2065
            extra = None
3779.3.1 by Andrew Bennetts
Move encoding/decoding logic of PermissionDenied and ReadError so that it happens for all RPCs.
2066
        raise errors.PermissionDenied(path, extra=extra)
3779.3.2 by Andrew Bennetts
Unify error translation done in bzrlib.remote and bzrlib.transport.remote.
2067
    elif err.error_verb == 'ReadError':
2068
        path = get_path()
2069
        raise errors.ReadError(path)
2070
    elif err.error_verb == 'NoSuchFile':
2071
        path = get_path()
2072
        raise errors.NoSuchFile(path)
2073
    elif err.error_verb == 'FileExists':
2074
        raise errors.FileExists(err.error_args[0])
2075
    elif err.error_verb == 'DirectoryNotEmpty':
2076
        raise errors.DirectoryNotEmpty(err.error_args[0])
2077
    elif err.error_verb == 'ShortReadvError':
2078
        args = err.error_args
2079
        raise errors.ShortReadvError(
2080
            args[0], int(args[1]), int(args[2]), int(args[3]))
2081
    elif err.error_verb in ('UnicodeEncodeError', 'UnicodeDecodeError'):
2082
        encoding = str(err.error_args[0]) # encoding must always be a string
2083
        val = err.error_args[1]
2084
        start = int(err.error_args[2])
2085
        end = int(err.error_args[3])
2086
        reason = str(err.error_args[4]) # reason must always be a string
2087
        if val.startswith('u:'):
2088
            val = val[2:].decode('utf-8')
2089
        elif val.startswith('s:'):
2090
            val = val[2:].decode('base64')
3786.2.3 by Andrew Bennetts
Remove duplicated 'call & translate errors' code in bzrlib.remote.
2091
        if err.error_verb == 'UnicodeDecodeError':
3779.3.2 by Andrew Bennetts
Unify error translation done in bzrlib.remote and bzrlib.transport.remote.
2092
            raise UnicodeDecodeError(encoding, val, start, end, reason)
3786.2.3 by Andrew Bennetts
Remove duplicated 'call & translate errors' code in bzrlib.remote.
2093
        elif err.error_verb == 'UnicodeEncodeError':
3779.3.2 by Andrew Bennetts
Unify error translation done in bzrlib.remote and bzrlib.transport.remote.
2094
            raise UnicodeEncodeError(encoding, val, start, end, reason)
2095
    elif err.error_verb == 'ReadOnlyError':
2096
        raise errors.TransportNotPossible('readonly transport')
3690.1.2 by Andrew Bennetts
Rename UntranslateableErrorFromSmartServer -> UnknownErrorFromSmartServer.
2097
    raise errors.UnknownErrorFromSmartServer(err)