~bzr-pqm/bzr/bzr.dev

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)
58
        
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)
64
        
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)
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)
2018.14.1 by Andrew Bennetts
Update to current hpss branch? Fix lots of test failures.
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
275
    :ivar _custom_format: If set, a specific concrete repository format that 
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
1752.2.52 by Andrew Bennetts
Flesh out more Remote* methods needed to open and initialise remote branches/trees/repositories.
356
    
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.
402
        
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.
2617.6.2 by Robert Collins
Add abort_write_group and wire write_groups into fetch and commit.
447
        
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.
2617.6.2 by Robert Collins
Add abort_write_group and wire write_groups into fetch and commit.
461
        
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:]
543
            
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.
734
        
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.
789
        
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.
841
        
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)
3691.2.6 by Martin Pool
Disable RemoteBranch stacking, but get get_stacked_on_url working, and passing back exceptions
853
        # They are also seen by the fallback repository.  If it doesn't exist
3691.2.12 by Martin Pool
Add test for coping without Branch.get_stacked_on_url
854
        # yet they'll be added then.  This implicitly copies them.
3691.2.11 by Martin Pool
More tests around RemoteBranch stacking.
855
        self._ensure_real()
3221.12.1 by Robert Collins
Backport development1 format (stackable packs) to before-shallow-branches.
856
2018.14.1 by Andrew Bennetts
Update to current hpss branch? Fix lots of test failures.
857
    def add_inventory(self, revid, inv, parents):
858
        self._ensure_real()
859
        return self._real_repository.add_inventory(revid, inv, parents)
860
3879.2.2 by John Arbash Meinel
Rename add_inventory_delta to add_inventory_by_delta.
861
    def add_inventory_by_delta(self, basis_revision_id, delta, new_revision_id,
862
                               parents):
3775.2.1 by Robert Collins
Create bzrlib.repository.Repository.add_inventory_delta for adding inventories via deltas.
863
        self._ensure_real()
3879.2.2 by John Arbash Meinel
Rename add_inventory_delta to add_inventory_by_delta.
864
        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.
865
            delta, new_revision_id, parents)
866
2018.14.1 by Andrew Bennetts
Update to current hpss branch? Fix lots of test failures.
867
    def add_revision(self, rev_id, rev, inv=None, config=None):
868
        self._ensure_real()
869
        return self._real_repository.add_revision(
870
            rev_id, rev, inv=inv, config=config)
871
872
    @needs_read_lock
873
    def get_inventory(self, revision_id):
874
        self._ensure_real()
875
        return self._real_repository.get_inventory(revision_id)
876
3169.2.1 by Robert Collins
New method ``iter_inventories`` on Repository for access to many
877
    def iter_inventories(self, revision_ids):
878
        self._ensure_real()
879
        return self._real_repository.iter_inventories(revision_ids)
880
2018.14.1 by Andrew Bennetts
Update to current hpss branch? Fix lots of test failures.
881
    @needs_read_lock
882
    def get_revision(self, revision_id):
883
        self._ensure_real()
884
        return self._real_repository.get_revision(revision_id)
885
886
    def get_transaction(self):
887
        self._ensure_real()
888
        return self._real_repository.get_transaction()
889
890
    @needs_read_lock
2018.5.138 by Robert Collins
Merge bzr.dev.
891
    def clone(self, a_bzrdir, revision_id=None):
2018.14.1 by Andrew Bennetts
Update to current hpss branch? Fix lots of test failures.
892
        self._ensure_real()
2018.5.138 by Robert Collins
Merge bzr.dev.
893
        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.
894
895
    def make_working_trees(self):
3349.1.1 by Aaron Bentley
Enable setting and getting make_working_trees for all repositories
896
        """See Repository.make_working_trees"""
897
        self._ensure_real()
898
        return self._real_repository.make_working_trees()
2018.14.1 by Andrew Bennetts
Update to current hpss branch? Fix lots of test failures.
899
3184.1.9 by Robert Collins
* ``Repository.get_data_stream`` is now deprecated in favour of
900
    def revision_ids_to_search_result(self, result_set):
901
        """Convert a set of revision ids to a graph SearchResult."""
902
        result_parents = set()
903
        for parents in self.get_graph().get_parent_map(
904
            result_set).itervalues():
905
            result_parents.update(parents)
906
        included_keys = result_set.intersection(result_parents)
907
        start_keys = result_set.difference(included_keys)
908
        exclude_keys = result_parents.difference(result_set)
909
        result = graph.SearchResult(start_keys, exclude_keys,
910
            len(result_set), result_set)
911
        return result
912
913
    @needs_read_lock
914
    def search_missing_revision_ids(self, other, revision_id=None, find_ghosts=True):
915
        """Return the revision ids that other has that this does not.
916
        
917
        These are returned in topological order.
918
919
        revision_id: only return revision ids included by revision_id.
920
        """
921
        return repository.InterRepository.get(
922
            other, self).search_missing_revision_ids(revision_id, find_ghosts)
923
3452.2.1 by Andrew Bennetts
An experimental InterRepo for remote packs.
924
    def fetch(self, source, revision_id=None, pb=None, find_ghosts=False):
925
        # Not delegated to _real_repository so that InterRepository.get has a
926
        # chance to find an InterRepository specialised for RemoteRepository.
2881.4.1 by Robert Collins
Move responsibility for detecting same-repo fetching from the
927
        if self.has_same_location(source):
928
            # check that last_revision is in 'from' and then return a
929
            # no-operation.
930
            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.
931
                not revision.is_null(revision_id)):
2881.4.1 by Robert Collins
Move responsibility for detecting same-repo fetching from the
932
                self.get_revision(revision_id)
2592.4.5 by Martin Pool
Add Repository.base on all repositories.
933
            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.
934
        inter = repository.InterRepository.get(source, self)
3452.2.1 by Andrew Bennetts
An experimental InterRepo for remote packs.
935
        try:
936
            return inter.fetch(revision_id=revision_id, pb=pb, find_ghosts=find_ghosts)
937
        except NotImplementedError:
938
            raise errors.IncompatibleRepositories(source, self)
2018.14.1 by Andrew Bennetts
Update to current hpss branch? Fix lots of test failures.
939
2520.4.54 by Aaron Bentley
Hang a create_bundle method off repository
940
    def create_bundle(self, target, base, fileobj, format=None):
941
        self._ensure_real()
942
        self._real_repository.create_bundle(target, base, fileobj, format)
943
2018.14.1 by Andrew Bennetts
Update to current hpss branch? Fix lots of test failures.
944
    @needs_read_lock
2530.1.1 by Aaron Bentley
Make topological sorting optional for get_ancestry
945
    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.
946
        self._ensure_real()
2530.1.1 by Aaron Bentley
Make topological sorting optional for get_ancestry
947
        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.
948
949
    def fileids_altered_by_revision_ids(self, revision_ids):
950
        self._ensure_real()
951
        return self._real_repository.fileids_altered_by_revision_ids(revision_ids)
952
3036.1.3 by Robert Collins
Privatise VersionedFileChecker.
953
    def _get_versioned_file_checker(self, revisions, revision_versions_cache):
2745.6.1 by Aaron Bentley
Initial checking of knit graphs
954
        self._ensure_real()
3036.1.3 by Robert Collins
Privatise VersionedFileChecker.
955
        return self._real_repository._get_versioned_file_checker(
2745.6.50 by Andrew Bennetts
Remove find_bad_ancestors; it's not needed anymore.
956
            revisions, revision_versions_cache)
957
        
2708.1.7 by Aaron Bentley
Rename extract_files_bytes to iter_files_bytes
958
    def iter_files_bytes(self, desired_files):
2708.1.9 by Aaron Bentley
Clean-up docs and imports
959
        """See Repository.iter_file_bytes.
2708.1.3 by Aaron Bentley
Implement extract_files_bytes on Repository
960
        """
961
        self._ensure_real()
2708.1.7 by Aaron Bentley
Rename extract_files_bytes to iter_files_bytes
962
        return self._real_repository.iter_files_bytes(desired_files)
2708.1.3 by Aaron Bentley
Implement extract_files_bytes on Repository
963
3565.3.1 by Robert Collins
* The generic fetch code now uses two attributes on Repository objects
964
    @property
965
    def _fetch_order(self):
966
        """Decorate the real repository for now.
967
968
        In the long term getting this back from the remote repository as part
969
        of open would be more efficient.
970
        """
3842.3.20 by Andrew Bennetts
Re-revert changes from another thread that accidentally got reinstated here.
971
        self._ensure_real()
972
        return self._real_repository._fetch_order
3565.3.1 by Robert Collins
* The generic fetch code now uses two attributes on Repository objects
973
974
    @property
975
    def _fetch_uses_deltas(self):
976
        """Decorate the real repository for now.
977
978
        In the long term getting this back from the remote repository as part
979
        of open would be more efficient.
980
        """
981
        self._ensure_real()
982
        return self._real_repository._fetch_uses_deltas
983
3565.3.4 by Robert Collins
Defer decision to reconcile to the repository being fetched into.
984
    @property
985
    def _fetch_reconcile(self):
986
        """Decorate the real repository for now.
987
988
        In the long term getting this back from the remote repository as part
989
        of open would be more efficient.
990
        """
991
        self._ensure_real()
992
        return self._real_repository._fetch_reconcile
993
3835.1.1 by Aaron Bentley
Stack get_parent_map on fallback repos
994
    def get_parent_map(self, revision_ids):
3835.1.6 by Aaron Bentley
Reduce inefficiency when doing make_parents_provider frequently
995
        """See bzrlib.Graph.get_parent_map()."""
3835.1.5 by Aaron Bentley
Fix make_parents_provider
996
        return self._make_parents_provider().get_parent_map(revision_ids)
3835.1.1 by Aaron Bentley
Stack get_parent_map on fallback repos
997
998
    def _get_parent_map_rpc(self, keys):
3172.5.6 by Robert Collins
Create new smart server verb Repository.get_parent_map.
999
        """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.
1000
        medium = self._client._medium
3453.4.10 by Andrew Bennetts
Change _is_remote_at_least to _is_remote_before.
1001
        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.
1002
            # We already found out that the server can't understand
3213.1.3 by Andrew Bennetts
Fix typo in comment.
1003
            # 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.
1004
            # graph.
3287.6.1 by Robert Collins
* ``VersionedFile.get_graph`` is deprecated, with no replacement method.
1005
            # XXX: Note that this will issue a deprecation warning. This is ok
1006
            # :- its because we're working with a deprecated server anyway, and
1007
            # the user will almost certainly have seen a warning about the
1008
            # server version already.
3389.1.1 by John Arbash Meinel
Fix bug #214894. Fix RemoteRepository.get_parent_map() when server is <v1.2
1009
            rg = self.get_revision_graph()
1010
            # There is an api discrepency between get_parent_map and
1011
            # get_revision_graph. Specifically, a "key:()" pair in
1012
            # get_revision_graph just means a node has no parents. For
1013
            # "get_parent_map" it means the node is a ghost. So fix up the
1014
            # graph to correct this.
1015
            #   https://bugs.launchpad.net/bzr/+bug/214894
1016
            # There is one other "bug" which is that ghosts in
1017
            # get_revision_graph() are not returned at all. But we won't worry
1018
            # about that for now.
1019
            for node_id, parent_ids in rg.iteritems():
1020
                if parent_ids == ():
1021
                    rg[node_id] = (NULL_REVISION,)
1022
            rg[NULL_REVISION] = ()
1023
            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.
1024
3172.5.6 by Robert Collins
Create new smart server verb Repository.get_parent_map.
1025
        keys = set(keys)
3373.5.2 by John Arbash Meinel
Add repository_implementation tests for get_parent_map
1026
        if None in keys:
1027
            raise ValueError('get_parent_map(None) is not valid')
3172.5.6 by Robert Collins
Create new smart server verb Repository.get_parent_map.
1028
        if NULL_REVISION in keys:
1029
            keys.discard(NULL_REVISION)
1030
            found_parents = {NULL_REVISION:()}
1031
            if not keys:
1032
                return found_parents
1033
        else:
1034
            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.
1035
        # TODO(Needs analysis): We could assume that the keys being requested
1036
        # from get_parent_map are in a breadth first search, so typically they
1037
        # will all be depth N from some common parent, and we don't have to
1038
        # have the server iterate from the root parent, but rather from the
1039
        # keys we're searching; and just tell the server the keyspace we
1040
        # already have; but this may be more traffic again.
1041
1042
        # Transform self._parents_map into a search request recipe.
1043
        # TODO: Manage this incrementally to avoid covering the same path
1044
        # repeatedly. (The server will have to on each request, but the less
1045
        # work done the better).
3835.1.8 by Aaron Bentley
Make UnstackedParentsProvider manage the cache
1046
        parents_map = self._unstacked_provider.get_cached_map()
3213.1.8 by Andrew Bennetts
Merge from bzr.dev.
1047
        if parents_map is None:
1048
            # Repository is not locked, so there's no cache.
1049
            parents_map = {}
1050
        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.
1051
        result_parents = set()
3213.1.8 by Andrew Bennetts
Merge from bzr.dev.
1052
        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.
1053
            result_parents.update(parents)
1054
        stop_keys = result_parents.difference(start_set)
1055
        included_keys = start_set.intersection(result_parents)
1056
        start_set.difference_update(included_keys)
3213.1.8 by Andrew Bennetts
Merge from bzr.dev.
1057
        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.
1058
        body = self._serialise_search_recipe(recipe)
3172.5.6 by Robert Collins
Create new smart server verb Repository.get_parent_map.
1059
        path = self.bzrdir._path_for_remote_call(self._client)
1060
        for key in keys:
3360.2.8 by Martin Pool
Change assertion to a plain raise
1061
            if type(key) is not str:
1062
                raise ValueError(
1063
                    "key %r not a plain string" % (key,))
3172.5.8 by Robert Collins
Review feedback.
1064
        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.
1065
        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.
1066
        try:
3786.2.3 by Andrew Bennetts
Remove duplicated 'call & translate errors' code in bzrlib.remote.
1067
            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.
1068
                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.
1069
        except errors.UnknownSmartMethod:
3213.1.2 by Andrew Bennetts
Add test for reconnection if get_parent_map is unknown by the server.
1070
            # 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.
1071
            # Worse, we have to force a disconnection, because the server now
1072
            # doesn't realise it has a body on the wire to consume, so the
1073
            # only way to recover is to abandon the connection.
3213.1.6 by Andrew Bennetts
Emit warnings when forcing a reconnect.
1074
            warning(
1075
                'Server is too old for fast get_parent_map, reconnecting.  '
1076
                '(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.
1077
            medium.disconnect()
1078
            # To avoid having to disconnect repeatedly, we keep track of the
1079
            # 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.
1080
            medium._remember_remote_is_before((1, 2))
3297.3.4 by Andrew Bennetts
Merge from bzr.dev.
1081
            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.
1082
        response_tuple, response_handler = response
1083
        if response_tuple[0] not in ['ok']:
1084
            response_handler.cancel_read_body()
1085
            raise errors.UnexpectedSmartServerResponse(response_tuple)
1086
        if response_tuple[0] == 'ok':
1087
            coded = bz2.decompress(response_handler.read_body_bytes())
3172.5.6 by Robert Collins
Create new smart server verb Repository.get_parent_map.
1088
            if coded == '':
1089
                # no revisions found
1090
                return {}
1091
            lines = coded.split('\n')
1092
            revision_graph = {}
1093
            for line in lines:
1094
                d = tuple(line.split())
1095
                if len(d) > 1:
1096
                    revision_graph[d[0]] = d[1:]
1097
                else:
1098
                    # No parents - so give the Graph result (NULL_REVISION,).
1099
                    revision_graph[d[0]] = (NULL_REVISION,)
1100
            return revision_graph
1101
2018.14.1 by Andrew Bennetts
Update to current hpss branch? Fix lots of test failures.
1102
    @needs_read_lock
1103
    def get_signature_text(self, revision_id):
1104
        self._ensure_real()
1105
        return self._real_repository.get_signature_text(revision_id)
1106
1107
    @needs_read_lock
3228.4.11 by John Arbash Meinel
Deprecations abound.
1108
    @symbol_versioning.deprecated_method(symbol_versioning.one_three)
2018.14.1 by Andrew Bennetts
Update to current hpss branch? Fix lots of test failures.
1109
    def get_revision_graph_with_ghosts(self, revision_ids=None):
1110
        self._ensure_real()
1111
        return self._real_repository.get_revision_graph_with_ghosts(
1112
            revision_ids=revision_ids)
1113
1114
    @needs_read_lock
1115
    def get_inventory_xml(self, revision_id):
1116
        self._ensure_real()
1117
        return self._real_repository.get_inventory_xml(revision_id)
1118
1119
    def deserialise_inventory(self, revision_id, xml):
1120
        self._ensure_real()
1121
        return self._real_repository.deserialise_inventory(revision_id, xml)
1122
1123
    def reconcile(self, other=None, thorough=False):
1124
        self._ensure_real()
1125
        return self._real_repository.reconcile(other=other, thorough=thorough)
1126
        
1127
    def all_revision_ids(self):
1128
        self._ensure_real()
1129
        return self._real_repository.all_revision_ids()
1130
    
1131
    @needs_read_lock
1132
    def get_deltas_for_revisions(self, revisions):
1133
        self._ensure_real()
1134
        return self._real_repository.get_deltas_for_revisions(revisions)
1135
1136
    @needs_read_lock
1137
    def get_revision_delta(self, revision_id):
1138
        self._ensure_real()
1139
        return self._real_repository.get_revision_delta(revision_id)
1140
1141
    @needs_read_lock
1142
    def revision_trees(self, revision_ids):
1143
        self._ensure_real()
1144
        return self._real_repository.revision_trees(revision_ids)
1145
1146
    @needs_read_lock
1147
    def get_revision_reconcile(self, revision_id):
1148
        self._ensure_real()
1149
        return self._real_repository.get_revision_reconcile(revision_id)
1150
1151
    @needs_read_lock
2745.6.36 by Andrew Bennetts
Deprecate revision_ids arg to Repository.check and other tweaks.
1152
    def check(self, revision_ids=None):
2018.14.1 by Andrew Bennetts
Update to current hpss branch? Fix lots of test failures.
1153
        self._ensure_real()
2745.6.36 by Andrew Bennetts
Deprecate revision_ids arg to Repository.check and other tweaks.
1154
        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.
1155
2018.5.138 by Robert Collins
Merge bzr.dev.
1156
    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.
1157
        self._ensure_real()
1158
        return self._real_repository.copy_content_into(
2018.5.138 by Robert Collins
Merge bzr.dev.
1159
            destination, revision_id=revision_id)
2018.14.1 by Andrew Bennetts
Update to current hpss branch? Fix lots of test failures.
1160
2814.10.2 by Andrew Bennetts
Make the fallback a little tidier.
1161
    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.
1162
        # get a tarball of the remote repository, and copy from that into the
1163
        # destination
1164
        from bzrlib import osutils
2018.18.9 by Martin Pool
remote Repository.tarball builds a temporary directory and tars that
1165
        import tarfile
2018.18.20 by Martin Pool
Route branch operations through remote copy_content_into
1166
        # TODO: Maybe a progress bar while streaming the tarball?
1167
        note("Copying repository content as tarball...")
2018.18.25 by Martin Pool
Repository.tarball fixes for python2.4
1168
        tar_file = self._get_tarball('bz2')
2814.10.2 by Andrew Bennetts
Make the fallback a little tidier.
1169
        if tar_file is None:
1170
            return None
1171
        destination = to_bzrdir.create_repository()
2018.18.10 by Martin Pool
copy_content_into from Remote repositories by using temporary directories on both ends.
1172
        try:
2018.18.25 by Martin Pool
Repository.tarball fixes for python2.4
1173
            tar = tarfile.open('repository', fileobj=tar_file,
1174
                mode='r|bz2')
3638.3.2 by Vincent Ladeuil
Fix all calls to tempfile.mkdtemp to osutils.mkdtemp.
1175
            tmpdir = osutils.mkdtemp()
2018.18.25 by Martin Pool
Repository.tarball fixes for python2.4
1176
            try:
1177
                _extract_tar(tar, tmpdir)
1178
                tmp_bzrdir = BzrDir.open(tmpdir)
1179
                tmp_repo = tmp_bzrdir.open_repository()
1180
                tmp_repo.copy_content_into(destination, revision_id)
1181
            finally:
1182
                osutils.rmtree(tmpdir)
2018.18.10 by Martin Pool
copy_content_into from Remote repositories by using temporary directories on both ends.
1183
        finally:
2018.18.25 by Martin Pool
Repository.tarball fixes for python2.4
1184
            tar_file.close()
2814.10.2 by Andrew Bennetts
Make the fallback a little tidier.
1185
        return destination
2018.18.23 by Martin Pool
review cleanups
1186
        # TODO: Suggestion from john: using external tar is much faster than
1187
        # 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.
1188
3842.3.20 by Andrew Bennetts
Re-revert changes from another thread that accidentally got reinstated here.
1189
    @property
1190
    def inventories(self):
1191
        """Decorate the real repository for now.
1192
1193
        In the long term a full blown network facility is needed to
1194
        avoid creating a real repository object locally.
1195
        """
1196
        self._ensure_real()
1197
        return self._real_repository.inventories
1198
2604.2.1 by Robert Collins
(robertc) Introduce a pack command.
1199
    @needs_write_lock
1200
    def pack(self):
1201
        """Compress the data within the repository.
1202
1203
        This is not currently implemented within the smart server.
1204
        """
1205
        self._ensure_real()
1206
        return self._real_repository.pack()
1207
3842.3.20 by Andrew Bennetts
Re-revert changes from another thread that accidentally got reinstated here.
1208
    @property
1209
    def revisions(self):
1210
        """Decorate the real repository for now.
1211
1212
        In the short term this should become a real object to intercept graph
1213
        lookups.
1214
1215
        In the long term a full blown network facility is needed.
1216
        """
1217
        self._ensure_real()
1218
        return self._real_repository.revisions
1219
2018.14.1 by Andrew Bennetts
Update to current hpss branch? Fix lots of test failures.
1220
    def set_make_working_trees(self, new_value):
4017.3.4 by Robert Collins
Create a verb for Repository.set_make_working_trees.
1221
        if new_value:
1222
            new_value_str = "True"
1223
        else:
1224
            new_value_str = "False"
1225
        path = self.bzrdir._path_for_remote_call(self._client)
1226
        try:
1227
            response = self._call(
1228
                'Repository.set_make_working_trees', path, new_value_str)
1229
        except errors.UnknownSmartMethod:
1230
            self._ensure_real()
1231
            self._real_repository.set_make_working_trees(new_value)
1232
        else:
1233
            if response[0] != 'ok':
1234
                raise errors.UnexpectedSmartServerResponse(response)
2018.14.1 by Andrew Bennetts
Update to current hpss branch? Fix lots of test failures.
1235
3842.3.20 by Andrew Bennetts
Re-revert changes from another thread that accidentally got reinstated here.
1236
    @property
1237
    def signatures(self):
1238
        """Decorate the real repository for now.
1239
1240
        In the long term a full blown network facility is needed to avoid
1241
        creating a real repository object locally.
1242
        """
1243
        self._ensure_real()
1244
        return self._real_repository.signatures
1245
2018.14.1 by Andrew Bennetts
Update to current hpss branch? Fix lots of test failures.
1246
    @needs_write_lock
1247
    def sign_revision(self, revision_id, gpg_strategy):
1248
        self._ensure_real()
1249
        return self._real_repository.sign_revision(revision_id, gpg_strategy)
1250
3842.3.20 by Andrew Bennetts
Re-revert changes from another thread that accidentally got reinstated here.
1251
    @property
1252
    def texts(self):
1253
        """Decorate the real repository for now.
1254
1255
        In the long term a full blown network facility is needed to avoid
1256
        creating a real repository object locally.
1257
        """
1258
        self._ensure_real()
1259
        return self._real_repository.texts
1260
2018.14.1 by Andrew Bennetts
Update to current hpss branch? Fix lots of test failures.
1261
    @needs_read_lock
1262
    def get_revisions(self, revision_ids):
1263
        self._ensure_real()
1264
        return self._real_repository.get_revisions(revision_ids)
1265
1266
    def supports_rich_root(self):
2018.5.84 by Andrew Bennetts
Merge in supports-rich-root, another test passing.
1267
        self._ensure_real()
1268
        return self._real_repository.supports_rich_root()
2018.14.1 by Andrew Bennetts
Update to current hpss branch? Fix lots of test failures.
1269
2018.5.83 by Andrew Bennetts
Fix some test failures caused by the switch from unicode to UTF-8-encoded strs for revision IDs.
1270
    def iter_reverse_revision_history(self, revision_id):
1271
        self._ensure_real()
1272
        return self._real_repository.iter_reverse_revision_history(revision_id)
1273
2018.5.96 by Andrew Bennetts
Merge from bzr.dev, resolving the worst of the semantic conflicts, but there's
1274
    @property
1275
    def _serializer(self):
1276
        self._ensure_real()
1277
        return self._real_repository._serializer
1278
2018.5.97 by Andrew Bennetts
Fix more tests.
1279
    def store_revision_signature(self, gpg_strategy, plaintext, revision_id):
1280
        self._ensure_real()
1281
        return self._real_repository.store_revision_signature(
1282
            gpg_strategy, plaintext, revision_id)
1283
2996.2.8 by Aaron Bentley
Fix add_signature discrepancies
1284
    def add_signature_text(self, revision_id, signature):
2996.2.3 by Aaron Bentley
Add tests for install_revisions and add_signature
1285
        self._ensure_real()
2996.2.8 by Aaron Bentley
Fix add_signature discrepancies
1286
        return self._real_repository.add_signature_text(revision_id, signature)
2996.2.3 by Aaron Bentley
Add tests for install_revisions and add_signature
1287
2018.5.97 by Andrew Bennetts
Fix more tests.
1288
    def has_signature_for_revision_id(self, revision_id):
1289
        self._ensure_real()
1290
        return self._real_repository.has_signature_for_revision_id(revision_id)
1291
2535.3.45 by Andrew Bennetts
Add item_keys_introduced_by to RemoteRepository.
1292
    def item_keys_introduced_by(self, revision_ids, _files_pb=None):
1293
        self._ensure_real()
1294
        return self._real_repository.item_keys_introduced_by(revision_ids,
1295
            _files_pb=_files_pb)
1296
2819.2.4 by Andrew Bennetts
Add a 'revision_graph_can_have_wrong_parents' method to repository.
1297
    def revision_graph_can_have_wrong_parents(self):
1298
        # The answer depends on the remote repo format.
1299
        self._ensure_real()
1300
        return self._real_repository.revision_graph_can_have_wrong_parents()
1301
2819.2.5 by Andrew Bennetts
Make reconcile abort gracefully if the revision index has bad parents.
1302
    def _find_inconsistent_revision_parents(self):
1303
        self._ensure_real()
1304
        return self._real_repository._find_inconsistent_revision_parents()
1305
1306
    def _check_for_inconsistent_revision_parents(self):
1307
        self._ensure_real()
1308
        return self._real_repository._check_for_inconsistent_revision_parents()
1309
3835.1.17 by Aaron Bentley
Fix stacking bug
1310
    def _make_parents_provider(self, other=None):
3835.1.8 by Aaron Bentley
Make UnstackedParentsProvider manage the cache
1311
        providers = [self._unstacked_provider]
3835.1.17 by Aaron Bentley
Fix stacking bug
1312
        if other is not None:
1313
            providers.insert(0, other)
3835.1.7 by Aaron Bentley
Updates from review
1314
        providers.extend(r._make_parents_provider() for r in
1315
                         self._fallback_repositories)
1316
        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.
1317
3842.3.20 by Andrew Bennetts
Re-revert changes from another thread that accidentally got reinstated here.
1318
    def _serialise_search_recipe(self, recipe):
1319
        """Serialise a graph search recipe.
1320
1321
        :param recipe: A search recipe (start, stop, count).
1322
        :return: Serialised bytes.
1323
        """
1324
        start_keys = ' '.join(recipe[0])
1325
        stop_keys = ' '.join(recipe[1])
1326
        count = str(recipe[2])
1327
        return '\n'.join((start_keys, stop_keys, count))
1328
3842.3.2 by Andrew Bennetts
Revert the RemoteVersionedFiles.get_parent_map implementation, leaving just the skeleton of RemoteVersionedFiles.
1329
    def autopack(self):
1330
        path = self.bzrdir._path_for_remote_call(self._client)
1331
        try:
1332
            response = self._call('PackRepository.autopack', path)
1333
        except errors.UnknownSmartMethod:
1334
            self._ensure_real()
1335
            self._real_repository._pack_collection.autopack()
1336
            return
1337
        if self._real_repository is not None:
1338
            # Reset the real repository's cache of pack names.
1339
            # XXX: At some point we may be able to skip this and just rely on
1340
            # the automatic retry logic to do the right thing, but for now we
1341
            # err on the side of being correct rather than being optimal.
1342
            self._real_repository._pack_collection.reload_pack_names()
1343
        if response[0] != 'ok':
1344
            raise errors.UnexpectedSmartServerResponse(response)
1345
1346
4022.1.6 by Robert Collins
Cherrypick and polish the RemoteSink for streaming push.
1347
class RemoteStreamSink(repository.StreamSink):
1348
4029.2.1 by Robert Collins
Support streaming push to stacked branches.
1349
    def __init__(self, target_repo):
1350
        repository.StreamSink.__init__(self, target_repo)
1351
        self._resume_tokens = []
1352
4022.1.6 by Robert Collins
Cherrypick and polish the RemoteSink for streaming push.
1353
    def _insert_real(self, stream, src_format):
1354
        self.target_repo._ensure_real()
1355
        sink = self.target_repo._real_repository._get_sink()
4029.2.1 by Robert Collins
Support streaming push to stacked branches.
1356
        result = sink.insert_stream(stream, src_format)
1357
        if not result:
1358
            self.target_repo.autopack()
1359
        return result
4022.1.6 by Robert Collins
Cherrypick and polish the RemoteSink for streaming push.
1360
1361
    def insert_stream(self, stream, src_format):
1362
        repo = self.target_repo
1363
        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)
1364
        medium = client._medium
4029.2.1 by Robert Collins
Support streaming push to stacked branches.
1365
        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)
1366
            # No possible way this can work.
1367
            return self._insert_real(stream, src_format)
4022.1.6 by Robert Collins
Cherrypick and polish the RemoteSink for streaming push.
1368
        path = repo.bzrdir._path_for_remote_call(client)
4029.2.1 by Robert Collins
Support streaming push to stacked branches.
1369
        if not self._resume_tokens:
1370
            # XXX: Ugly but important for correctness, *will* be fixed during
1371
            # 1.13 cycle. Pushing a stream that is interrupted results in a
1372
            # fallback to the _real_repositories sink *with a partial stream*.
1373
            # Thats bad because we insert less data than bzr expected. To avoid
1374
            # this we do a trial push to make sure the verb is accessible, and
1375
            # do not fallback when actually pushing the stream. A cleanup patch
1376
            # is going to look at rewinding/restarting the stream/partial
1377
            # buffering etc.
1378
            byte_stream = self._stream_to_byte_stream([], src_format)
1379
            try:
1380
                resume_tokens = ''
1381
                response = client.call_with_body_stream(
1382
                    ('Repository.insert_stream', path, resume_tokens), byte_stream)
1383
            except errors.UnknownSmartMethod:
1384
                medium._remember_remote_is_before((1,13))
1385
                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)
1386
        byte_stream = self._stream_to_byte_stream(stream, src_format)
4029.2.1 by Robert Collins
Support streaming push to stacked branches.
1387
        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)
1388
        response = client.call_with_body_stream(
4029.2.1 by Robert Collins
Support streaming push to stacked branches.
1389
            ('Repository.insert_stream', path, resume_tokens), byte_stream)
1390
        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)
1391
            raise errors.UnexpectedSmartServerResponse(response)
4029.2.1 by Robert Collins
Support streaming push to stacked branches.
1392
        if response[0][0] == 'missing-basis':
1393
            tokens, missing_keys = bencode.bdecode_as_tuple(response[0][1])
1394
            self._resume_tokens = tokens
1395
            return missing_keys
1396
        else:
1397
            if self.target_repo._real_repository is not None:
1398
                collection = getattr(self.target_repo._real_repository,
1399
                    '_pack_collection', None)
1400
                if collection is not None:
1401
                    collection.reload_pack_names()
1402
            return []
4022.1.6 by Robert Collins
Cherrypick and polish the RemoteSink for streaming push.
1403
            
1404
    def _stream_to_byte_stream(self, stream, src_format):
1405
        bytes = []
1406
        pack_writer = pack.ContainerWriter(bytes.append)
1407
        pack_writer.begin()
1408
        pack_writer.add_bytes_record(src_format.network_name(), '')
1409
        adapters = {}
1410
        def get_adapter(adapter_key):
1411
            try:
1412
                return adapters[adapter_key]
1413
            except KeyError:
1414
                adapter_factory = adapter_registry.get(adapter_key)
1415
                adapter = adapter_factory(self)
1416
                adapters[adapter_key] = adapter
1417
                return adapter
1418
        for substream_type, substream in stream:
1419
            for record in substream:
1420
                if record.storage_kind in ('chunked', 'fulltext'):
1421
                    serialised = record_to_fulltext_bytes(record)
1422
                else:
1423
                    serialised = record.get_bytes_as(record.storage_kind)
1424
                pack_writer.add_bytes_record(serialised, [(substream_type,)])
1425
                for b in bytes:
1426
                    yield b
1427
                del bytes[:]
1428
        pack_writer.end()
1429
        for b in bytes:
1430
            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)
1431
1432
2018.5.127 by Andrew Bennetts
Fix most of the lockable_files tests for RemoteBranchLockableFiles.
1433
class RemoteBranchLockableFiles(LockableFiles):
2018.5.59 by Robert Collins
Get BranchConfig working somewhat on RemoteBranches (Robert Collins, Vincent Ladeuil).
1434
    """A 'LockableFiles' implementation that talks to a smart server.
1435
    
1436
    This is not a public interface class.
1437
    """
1438
1439
    def __init__(self, bzrdir, _client):
1440
        self.bzrdir = bzrdir
1441
        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.
1442
        self._need_find_modes = True
2018.5.133 by Andrew Bennetts
All TestLockableFiles_RemoteLockDir tests passing.
1443
        LockableFiles.__init__(
2018.5.163 by Andrew Bennetts
Deal with various review comments from Robert.
1444
            self, bzrdir.get_branch_transport(None),
2018.5.133 by Andrew Bennetts
All TestLockableFiles_RemoteLockDir tests passing.
1445
            'lock', lockdir.LockDir)
2018.5.59 by Robert Collins
Get BranchConfig working somewhat on RemoteBranches (Robert Collins, Vincent Ladeuil).
1446
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.
1447
    def _find_modes(self):
1448
        # RemoteBranches don't let the client set the mode of control files.
1449
        self._dir_mode = None
1450
        self._file_mode = None
1451
2018.5.59 by Robert Collins
Get BranchConfig working somewhat on RemoteBranches (Robert Collins, Vincent Ladeuil).
1452
1752.2.31 by Martin Pool
[broken] some support for write operations over hpss
1453
class RemoteBranchFormat(branch.BranchFormat):
1454
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.
1455
    def __init__(self):
1456
        super(RemoteBranchFormat, self).__init__()
1457
        self._matchingbzrdir = RemoteBzrDirFormat()
1458
        self._matchingbzrdir.set_branch_format(self)
1459
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.
1460
    def __eq__(self, other):
1461
        return (isinstance(other, RemoteBranchFormat) and 
1462
            self.__dict__ == other.__dict__)
1463
2018.5.60 by Robert Collins
More missing methods from RemoteBranch and RemoteRepository to let 'info' get further.
1464
    def get_format_description(self):
1465
        return 'Remote BZR Branch'
1466
2018.14.1 by Andrew Bennetts
Update to current hpss branch? Fix lots of test failures.
1467
    def get_format_string(self):
1468
        return 'Remote BZR Branch'
1469
4032.3.1 by Robert Collins
Add a BranchFormat.network_name() method as preparation for creating branches via RPC calls.
1470
    def network_name(self):
1471
        return self._network_name
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
4032.3.1 by Robert Collins
Add a BranchFormat.network_name() method as preparation for creating branches via RPC calls.
1545
        if real_branch is not None:
1546
            self._format._network_name = \
1547
                self._real_branch._format.network_name()
1548
        else:
1549
            # XXX: Need to get this from BzrDir.open_branch's return value.
1550
            self._ensure_real()
1551
            self._format._network_name = \
1552
                self._real_branch._format.network_name()
3681.1.2 by Robert Collins
Adjust for trunk.
1553
        # 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)
1554
        hooks = branch.Branch.hooks['open']
1555
        for hook in hooks:
1556
            hook(self)
3691.2.7 by Martin Pool
FakeClient can know what calls to expect
1557
        self._setup_stacking()
3691.2.1 by Martin Pool
RemoteBranch must configure stacking into the repository
1558
1559
    def _setup_stacking(self):
1560
        # 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
1561
        # the vfs branch.
3691.2.1 by Martin Pool
RemoteBranch must configure stacking into the repository
1562
        try:
1563
            fallback_url = self.get_stacked_on_url()
1564
        except (errors.NotStacked, errors.UnstackableBranchFormat,
1565
            errors.UnstackableRepositoryFormat), e:
3691.2.7 by Martin Pool
FakeClient can know what calls to expect
1566
            return
1567
        # it's relative to this branch...
1568
        fallback_url = urlutils.join(self.base, fallback_url)
1569
        transports = [self.bzrdir.root_transport]
1570
        if self._real_branch is not None:
1571
            transports.append(self._real_branch._transport)
3830.2.1 by Aaron Bentley
Fix HPSS with branch stacked on repository branch
1572
        stacked_on = branch.Branch.open(fallback_url,
1573
                                        possible_transports=transports)
1574
        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.
1575
3468.1.1 by Martin Pool
Update more users of default file modes from control_files to bzrdir
1576
    def _get_real_transport(self):
3407.2.16 by Martin Pool
Remove RemoteBranch reliance on control_files._transport
1577
        # if we try vfs access, return the real branch's vfs transport
1578
        self._ensure_real()
1579
        return self._real_branch._transport
1580
3468.1.1 by Martin Pool
Update more users of default file modes from control_files to bzrdir
1581
    _transport = property(_get_real_transport)
3407.2.16 by Martin Pool
Remove RemoteBranch reliance on control_files._transport
1582
2477.1.1 by Martin Pool
Add RemoteBranch repr
1583
    def __str__(self):
1584
        return "%s(%s)" % (self.__class__.__name__, self.base)
1585
1586
    __repr__ = __str__
1587
2018.5.70 by Robert Collins
Only try to get real repositories when an operation requires them.
1588
    def _ensure_real(self):
1589
        """Ensure that there is a _real_branch set.
1590
2018.5.163 by Andrew Bennetts
Deal with various review comments from Robert.
1591
        Used before calls to self._real_branch.
2018.5.70 by Robert Collins
Only try to get real repositories when an operation requires them.
1592
        """
3407.2.16 by Martin Pool
Remove RemoteBranch reliance on control_files._transport
1593
        if self._real_branch is None:
3376.2.4 by Martin Pool
Remove every assert statement from bzrlib!
1594
            if not vfs.vfs_enabled():
1595
                raise AssertionError('smart server vfs must be enabled '
1596
                    'to use vfs implementation')
2018.5.70 by Robert Collins
Only try to get real repositories when an operation requires them.
1597
            self.bzrdir._ensure_real()
1598
            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.
1599
            if self.repository._real_repository is None:
1600
                # Give the remote repository the matching real repo.
1601
                real_repo = self._real_branch.repository
1602
                if isinstance(real_repo, RemoteRepository):
1603
                    real_repo._ensure_real()
1604
                    real_repo = real_repo._real_repository
1605
                self.repository._set_real_repository(real_repo)
1606
            # Give the real branch the remote repository to let fast-pathing
1607
            # happen.
2018.5.70 by Robert Collins
Only try to get real repositories when an operation requires them.
1608
            self._real_branch.repository = self.repository
2018.14.1 by Andrew Bennetts
Update to current hpss branch? Fix lots of test failures.
1609
            if self._lock_mode == 'r':
1610
                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.
1611
            elif self._lock_mode == 'w':
1612
                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.
1613
3533.3.1 by Andrew Bennetts
Remove duplication of error translation in bzrlib/remote.py.
1614
    def _translate_error(self, err, **context):
1615
        self.repository._translate_error(err, branch=self, **context)
1616
3441.5.1 by Andrew Bennetts
Avoid necessarily calling get_parent_map when pushing.
1617
    def _clear_cached_state(self):
1618
        super(RemoteBranch, self)._clear_cached_state()
3441.5.5 by Andrew Bennetts
Some small tweaks and comments.
1619
        if self._real_branch is not None:
1620
            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.
1621
1622
    def _clear_cached_state_of_remote_branch_only(self):
1623
        """Like _clear_cached_state, but doesn't clear the cache of
1624
        self._real_branch.
1625
1626
        This is useful when falling back to calling a method of
1627
        self._real_branch that changes state.  In that case the underlying
1628
        branch changes, so we need to invalidate this RemoteBranch's cache of
1629
        it.  However, there's no need to invalidate the _real_branch's cache
1630
        too, in fact doing so might harm performance.
1631
        """
1632
        super(RemoteBranch, self)._clear_cached_state()
3441.5.1 by Andrew Bennetts
Avoid necessarily calling get_parent_map when pushing.
1633
        
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.
1634
    @property
1635
    def control_files(self):
1636
        # Defer actually creating RemoteBranchLockableFiles until its needed,
1637
        # because it triggers an _ensure_real that we otherwise might not need.
1638
        if self._control_files is None:
1639
            self._control_files = RemoteBranchLockableFiles(
1640
                self.bzrdir, self._client)
1641
        return self._control_files
1642
2018.5.166 by Andrew Bennetts
Small changes in response to Aaron's review.
1643
    def _get_checkout_format(self):
1644
        self._ensure_real()
1645
        return self._real_branch._get_checkout_format()
1646
2018.5.60 by Robert Collins
More missing methods from RemoteBranch and RemoteRepository to let 'info' get further.
1647
    def get_physical_lock_status(self):
1648
        """See Branch.get_physical_lock_status()."""
1649
        # 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.
1650
        self._ensure_real()
2018.5.60 by Robert Collins
More missing methods from RemoteBranch and RemoteRepository to let 'info' get further.
1651
        return self._real_branch.get_physical_lock_status()
1652
3537.3.1 by Martin Pool
Rename branch.get_stacked_on to get_stacked_on_url
1653
    def get_stacked_on_url(self):
3221.11.2 by Robert Collins
Create basic stackable branch facility.
1654
        """Get the URL this branch is stacked against.
1655
1656
        :raises NotStacked: If the branch is not stacked.
1657
        :raises UnstackableBranchFormat: If the branch does not support
1658
            stacking.
1659
        :raises UnstackableRepositoryFormat: If the repository does not support
1660
            stacking.
1661
        """
3691.2.12 by Martin Pool
Add test for coping without Branch.get_stacked_on_url
1662
        try:
3786.2.3 by Andrew Bennetts
Remove duplicated 'call & translate errors' code in bzrlib.remote.
1663
            # there may not be a repository yet, so we can't use
1664
            # 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
1665
            response = self._client.call('Branch.get_stacked_on_url',
1666
                self._remote_path())
1667
        except errors.ErrorFromSmartServer, err:
1668
            # there may not be a repository yet, so we can't call through
1669
            # its _translate_error
1670
            _translate_error(err, branch=self)
1671
        except errors.UnknownSmartMethod, err:
1672
            self._ensure_real()
1673
            return self._real_branch.get_stacked_on_url()
3786.2.3 by Andrew Bennetts
Remove duplicated 'call & translate errors' code in bzrlib.remote.
1674
        if response[0] != 'ok':
1675
            raise errors.UnexpectedSmartServerResponse(response)
1676
        return response[1]
3221.11.2 by Robert Collins
Create basic stackable branch facility.
1677
1752.2.31 by Martin Pool
[broken] some support for write operations over hpss
1678
    def lock_read(self):
3692.1.1 by Andrew Bennetts
Make RemoteBranch.lock_write lock the repository too.
1679
        self.repository.lock_read()
2018.14.1 by Andrew Bennetts
Update to current hpss branch? Fix lots of test failures.
1680
        if not self._lock_mode:
1681
            self._lock_mode = 'r'
1682
            self._lock_count = 1
1683
            if self._real_branch is not None:
1684
                self._real_branch.lock_read()
1685
        else:
1686
            self._lock_count += 1
1752.2.52 by Andrew Bennetts
Flesh out more Remote* methods needed to open and initialise remote branches/trees/repositories.
1687
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).
1688
    def _remote_lock_write(self, token):
1689
        if token is None:
2018.5.79 by Andrew Bennetts
Implement RemoteBranch.lock_write/unlock as smart operations.
1690
            branch_token = repo_token = ''
1691
        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).
1692
            branch_token = token
1693
            repo_token = self.repository.lock_write()
1694
            self.repository.unlock()
3786.2.3 by Andrew Bennetts
Remove duplicated 'call & translate errors' code in bzrlib.remote.
1695
        err_context = {'token': token}
1696
        response = self._call(
1697
            'Branch.lock_write', self._remote_path(), branch_token,
1698
            repo_token or '', **err_context)
3245.4.24 by Andrew Bennetts
Consistently raise errors from the server as ErrorFromSmartServer exceptions.
1699
        if response[0] != 'ok':
2555.1.1 by Martin Pool
Remove use of 'assert False' to raise an exception unconditionally
1700
            raise errors.UnexpectedSmartServerResponse(response)
3245.4.24 by Andrew Bennetts
Consistently raise errors from the server as ErrorFromSmartServer exceptions.
1701
        ok, branch_token, repo_token = response
1702
        return branch_token, repo_token
2018.5.79 by Andrew Bennetts
Implement RemoteBranch.lock_write/unlock as smart operations.
1703
            
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).
1704
    def lock_write(self, token=None):
2018.5.79 by Andrew Bennetts
Implement RemoteBranch.lock_write/unlock as smart operations.
1705
        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.
1706
            # 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).
1707
            remote_tokens = self._remote_lock_write(token)
2018.5.79 by Andrew Bennetts
Implement RemoteBranch.lock_write/unlock as smart operations.
1708
            self._lock_token, self._repo_lock_token = remote_tokens
3376.2.4 by Martin Pool
Remove every assert statement from bzrlib!
1709
            if not self._lock_token:
1710
                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.
1711
            # 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.
1712
            self.repository.lock_write(
1713
                self._repo_lock_token, _skip_rpc=True)
3692.1.1 by Andrew Bennetts
Make RemoteBranch.lock_write lock the repository too.
1714
2018.5.79 by Andrew Bennetts
Implement RemoteBranch.lock_write/unlock as smart operations.
1715
            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.
1716
                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).
1717
            if token is not None:
2018.5.79 by Andrew Bennetts
Implement RemoteBranch.lock_write/unlock as smart operations.
1718
                self._leave_lock = True
1719
            else:
1720
                self._leave_lock = False
1721
            self._lock_mode = 'w'
1722
            self._lock_count = 1
1723
        elif self._lock_mode == 'r':
1724
            raise errors.ReadOnlyTransaction
1725
        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).
1726
            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.
1727
                # A token was given to lock_write, and we're relocking, so
1728
                # check that the given token actually matches the one we
1729
                # 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).
1730
                if token != self._lock_token:
1731
                    raise errors.TokenMismatch(token, self._lock_token)
2018.5.79 by Andrew Bennetts
Implement RemoteBranch.lock_write/unlock as smart operations.
1732
            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.
1733
            # Re-lock the repository too.
3692.1.2 by Andrew Bennetts
Fix regression introduced by fix, and add a test for that regression.
1734
            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.
1735
        return self._lock_token or None
2018.5.79 by Andrew Bennetts
Implement RemoteBranch.lock_write/unlock as smart operations.
1736
1737
    def _unlock(self, branch_token, repo_token):
3786.2.3 by Andrew Bennetts
Remove duplicated 'call & translate errors' code in bzrlib.remote.
1738
        err_context = {'token': str((branch_token, repo_token))}
1739
        response = self._call(
1740
            'Branch.unlock', self._remote_path(), branch_token,
1741
            repo_token or '', **err_context)
2018.5.79 by Andrew Bennetts
Implement RemoteBranch.lock_write/unlock as smart operations.
1742
        if response == ('ok',):
1743
            return
3245.4.24 by Andrew Bennetts
Consistently raise errors from the server as ErrorFromSmartServer exceptions.
1744
        raise errors.UnexpectedSmartServerResponse(response)
1752.2.31 by Martin Pool
[broken] some support for write operations over hpss
1745
1746
    def unlock(self):
3692.1.1 by Andrew Bennetts
Make RemoteBranch.lock_write lock the repository too.
1747
        try:
1748
            self._lock_count -= 1
1749
            if not self._lock_count:
1750
                self._clear_cached_state()
1751
                mode = self._lock_mode
1752
                self._lock_mode = None
1753
                if self._real_branch is not None:
1754
                    if (not self._leave_lock and mode == 'w' and
1755
                        self._repo_lock_token):
1756
                        # If this RemoteBranch will remove the physical lock
1757
                        # for the repository, make sure the _real_branch
1758
                        # doesn't do it first.  (Because the _real_branch's
1759
                        # repository is set to be the RemoteRepository.)
1760
                        self._real_branch.repository.leave_lock_in_place()
1761
                    self._real_branch.unlock()
1762
                if mode != 'w':
1763
                    # Only write-locked branched need to make a remote method
1764
                    # call to perfom the unlock.
1765
                    return
1766
                if not self._lock_token:
1767
                    raise AssertionError('Locked, but no token!')
1768
                branch_token = self._lock_token
1769
                repo_token = self._repo_lock_token
1770
                self._lock_token = None
1771
                self._repo_lock_token = None
1772
                if not self._leave_lock:
1773
                    self._unlock(branch_token, repo_token)
1774
        finally:
1775
            self.repository.unlock()
1752.2.52 by Andrew Bennetts
Flesh out more Remote* methods needed to open and initialise remote branches/trees/repositories.
1776
1777
    def break_lock(self):
2018.5.70 by Robert Collins
Only try to get real repositories when an operation requires them.
1778
        self._ensure_real()
1752.2.52 by Andrew Bennetts
Flesh out more Remote* methods needed to open and initialise remote branches/trees/repositories.
1779
        return self._real_branch.break_lock()
1752.2.31 by Martin Pool
[broken] some support for write operations over hpss
1780
2018.5.79 by Andrew Bennetts
Implement RemoteBranch.lock_write/unlock as smart operations.
1781
    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.
1782
        if not self._lock_token:
1783
            raise NotImplementedError(self.leave_lock_in_place)
2018.5.79 by Andrew Bennetts
Implement RemoteBranch.lock_write/unlock as smart operations.
1784
        self._leave_lock = True
1785
1786
    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.
1787
        if not self._lock_token:
3015.2.15 by Robert Collins
Review feedback.
1788
            raise NotImplementedError(self.dont_leave_lock_in_place)
2018.5.79 by Andrew Bennetts
Implement RemoteBranch.lock_write/unlock as smart operations.
1789
        self._leave_lock = False
1790
3441.5.1 by Andrew Bennetts
Avoid necessarily calling get_parent_map when pushing.
1791
    def _last_revision_info(self):
3786.2.3 by Andrew Bennetts
Remove duplicated 'call & translate errors' code in bzrlib.remote.
1792
        response = self._call('Branch.last_revision_info', self._remote_path())
3376.2.4 by Martin Pool
Remove every assert statement from bzrlib!
1793
        if response[0] != 'ok':
1794
            raise SmartProtocolError('unexpected response code %s' % (response,))
2018.5.51 by Wouter van Heyst
Test and implement RemoteBranch.last_revision_info()
1795
        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.
1796
        last_revision = response[2]
2018.5.51 by Wouter van Heyst
Test and implement RemoteBranch.last_revision_info()
1797
        return (revno, last_revision)
1798
2018.5.105 by Andrew Bennetts
Implement revision_history caching for RemoteBranch.
1799
    def _gen_revision_history(self):
1800
        """See Branch._gen_revision_history()."""
3786.2.3 by Andrew Bennetts
Remove duplicated 'call & translate errors' code in bzrlib.remote.
1801
        response_tuple, response_handler = self._call_expecting_body(
3691.2.3 by Martin Pool
Factor out RemoteBranch._remote_path() and disable RemoteBranch stacking
1802
            '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.
1803
        if response_tuple[0] != 'ok':
3452.2.2 by Andrew Bennetts
Experimental PackRepository.{check_references,autopack} RPCs.
1804
            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.
1805
        result = response_handler.read_body_bytes().split('\x00')
2018.5.38 by Robert Collins
Implement RemoteBranch.revision_history().
1806
        if result == ['']:
1807
            return []
1808
        return result
1752.2.30 by Martin Pool
Start adding a RemoteBzrDir, etc
1809
3691.2.3 by Martin Pool
Factor out RemoteBranch._remote_path() and disable RemoteBranch stacking
1810
    def _remote_path(self):
1811
        return self.bzrdir._path_for_remote_call(self._client)
1812
3441.5.18 by Andrew Bennetts
Fix some test failures.
1813
    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.
1814
            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.
1815
        # This performs additional work to meet the hook contract; while its
1816
        # undesirable, we have to synthesise the revno to call the hook, and
1817
        # not calling the hook is worse as it means changes can't be prevented.
1818
        # Having calculated this though, we can't just call into
1819
        # set_last_revision_info as a simple call, because there is a set_rh
1820
        # hook that some folk may still be using.
1821
        old_revno, old_revid = self.last_revision_info()
1822
        history = self._lefthand_history(revision_id)
1823
        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.
1824
        err_context = {'other_branch': other_branch}
1825
        response = self._call('Branch.set_last_revision_ex',
1826
            self._remote_path(), self._lock_token, self._repo_lock_token,
1827
            revision_id, int(allow_diverged), int(allow_overwrite_descendant),
1828
            **err_context)
3441.5.6 by Andrew Bennetts
Greatly simplify RemoteBranch.update_revisions. Still needs more tests.
1829
        self._clear_cached_state()
3441.5.18 by Andrew Bennetts
Fix some test failures.
1830
        if len(response) != 3 and response[0] != 'ok':
3441.5.6 by Andrew Bennetts
Greatly simplify RemoteBranch.update_revisions. Still needs more tests.
1831
            raise errors.UnexpectedSmartServerResponse(response)
3441.5.18 by Andrew Bennetts
Fix some test failures.
1832
        new_revno, new_revision_id = response[1:]
1833
        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.
1834
        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.
1835
        if self._real_branch is not None:
1836
            cache = new_revno, new_revision_id
1837
            self._real_branch._last_revision_info_cache = cache
3441.5.6 by Andrew Bennetts
Greatly simplify RemoteBranch.update_revisions. Still needs more tests.
1838
3441.5.1 by Andrew Bennetts
Avoid necessarily calling get_parent_map when pushing.
1839
    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.
1840
        old_revno, old_revid = self.last_revision_info()
1841
        # This performs additional work to meet the hook contract; while its
1842
        # undesirable, we have to synthesise the revno to call the hook, and
1843
        # not calling the hook is worse as it means changes can't be prevented.
1844
        # Having calculated this though, we can't just call into
1845
        # set_last_revision_info as a simple call, because there is a set_rh
1846
        # hook that some folk may still be using.
1847
        history = self._lefthand_history(revision_id)
1848
        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.
1849
        self._clear_cached_state()
3786.2.3 by Andrew Bennetts
Remove duplicated 'call & translate errors' code in bzrlib.remote.
1850
        response = self._call('Branch.set_last_revision',
1851
            self._remote_path(), self._lock_token, self._repo_lock_token,
1852
            revision_id)
3441.5.1 by Andrew Bennetts
Avoid necessarily calling get_parent_map when pushing.
1853
        if response != ('ok',):
1854
            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.
1855
        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.
1856
2018.14.1 by Andrew Bennetts
Update to current hpss branch? Fix lots of test failures.
1857
    @needs_write_lock
1752.2.52 by Andrew Bennetts
Flesh out more Remote* methods needed to open and initialise remote branches/trees/repositories.
1858
    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.
1859
        # Send just the tip revision of the history; the server will generate
1860
        # the full history from that.  If the revision doesn't exist in this
1861
        # branch, NoSuchRevision will be raised.
1862
        if rev_history == []:
2018.5.170 by Andrew Bennetts
Use 'null:' instead of '' to mean NULL_REVISION on the wire.
1863
            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.
1864
        else:
1865
            rev_id = rev_history[-1]
3441.5.1 by Andrew Bennetts
Avoid necessarily calling get_parent_map when pushing.
1866
        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.
1867
        for hook in branch.Branch.hooks['set_rh']:
1868
            hook(self, rev_history)
2018.5.105 by Andrew Bennetts
Implement revision_history caching for RemoteBranch.
1869
        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.
1870
1871
    def get_parent(self):
2018.5.70 by Robert Collins
Only try to get real repositories when an operation requires them.
1872
        self._ensure_real()
1752.2.52 by Andrew Bennetts
Flesh out more Remote* methods needed to open and initialise remote branches/trees/repositories.
1873
        return self._real_branch.get_parent()
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.
1874
1875
    def _get_parent_location(self):
1876
        # Used by tests, when checking normalisation of given vs stored paths.
1877
        self._ensure_real()
1878
        return self._real_branch._get_parent_location()
1752.2.52 by Andrew Bennetts
Flesh out more Remote* methods needed to open and initialise remote branches/trees/repositories.
1879
        
1752.2.63 by Andrew Bennetts
Delegate set_parent.
1880
    def set_parent(self, url):
2018.5.70 by Robert Collins
Only try to get real repositories when an operation requires them.
1881
        self._ensure_real()
1752.2.63 by Andrew Bennetts
Delegate set_parent.
1882
        return self._real_branch.set_parent(url)
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.
1883
1884
    def _set_parent_location(self, url):
1885
        # Used by tests, to poke bad urls into branch configurations
1886
        if url is None:
1887
            self.set_parent(url)
1888
        else:
1889
            self._ensure_real()
1890
            return self._real_branch._set_parent_location(url)
1752.2.63 by Andrew Bennetts
Delegate set_parent.
1891
        
3537.3.3 by Martin Pool
Rename Branch.set_stacked_on to set_stacked_on_url
1892
    def set_stacked_on_url(self, stacked_location):
3221.18.1 by Ian Clatworthy
tweaks by ianc during review
1893
        """Set the URL this branch is stacked against.
3221.11.2 by Robert Collins
Create basic stackable branch facility.
1894
1895
        :raises UnstackableBranchFormat: If the branch does not support
1896
            stacking.
1897
        :raises UnstackableRepositoryFormat: If the repository does not support
1898
            stacking.
1899
        """
1900
        self._ensure_real()
3537.3.3 by Martin Pool
Rename Branch.set_stacked_on to set_stacked_on_url
1901
        return self._real_branch.set_stacked_on_url(stacked_location)
3221.11.2 by Robert Collins
Create basic stackable branch facility.
1902
2018.5.94 by Andrew Bennetts
Various small changes in aid of making tests pass (including deleting one invalid test).
1903
    def sprout(self, to_bzrdir, revision_id=None):
3793.1.1 by Andrew Bennetts
Make RemoteBranch.sprout use Branch.sprout when possible.
1904
        branch_format = to_bzrdir._format._branch_format
1905
        if (branch_format is None or
1906
            isinstance(branch_format, RemoteBranchFormat)):
1907
            # The to_bzrdir specifies RemoteBranchFormat (or no format, which
1908
            # implies the same thing), but RemoteBranches can't be created at
1909
            # arbitrary URLs.  So create a branch in the same format as
1910
            # _real_branch instead.
1911
            # XXX: if to_bzrdir is a RemoteBzrDir, this should perhaps do
1912
            # to_bzrdir.create_branch to create a RemoteBranch after all...
1913
            self._ensure_real()
1914
            result = self._real_branch._format.initialize(to_bzrdir)
1915
            self.copy_content_into(result, revision_id=revision_id)
1916
            result.set_parent(self.bzrdir.root_transport.base)
1917
        else:
1918
            result = branch.Branch.sprout(
1919
                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).
1920
        return result
1921
2018.14.1 by Andrew Bennetts
Update to current hpss branch? Fix lots of test failures.
1922
    @needs_write_lock
2477.1.2 by Martin Pool
Rename push/pull back to 'run_hooks' (jameinel)
1923
    def pull(self, source, overwrite=False, stop_revision=None,
2477.1.9 by Martin Pool
Review cleanups from John, mostly docs
1924
             **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.
1925
        self._clear_cached_state_of_remote_branch_only()
2018.14.1 by Andrew Bennetts
Update to current hpss branch? Fix lots of test failures.
1926
        self._ensure_real()
3482.1.1 by John Arbash Meinel
Fix bug #238149, RemoteBranch.pull needs to return the _real_branch's pull result.
1927
        return self._real_branch.pull(
2477.1.2 by Martin Pool
Rename push/pull back to 'run_hooks' (jameinel)
1928
            source, overwrite=overwrite, stop_revision=stop_revision,
3489.2.4 by Andrew Bennetts
Fix all tests broken by fixing make_branch_and_tree.
1929
            _override_hook_target=self, **kwargs)
2018.14.1 by Andrew Bennetts
Update to current hpss branch? Fix lots of test failures.
1930
2018.14.3 by Andrew Bennetts
Make a couple more branch_implementations tests pass.
1931
    @needs_read_lock
1932
    def push(self, target, overwrite=False, stop_revision=None):
1933
        self._ensure_real()
2018.5.97 by Andrew Bennetts
Fix more tests.
1934
        return self._real_branch.push(
2477.1.5 by Martin Pool
More cleanups of Branch.push to get the right behaviour with RemoteBranches
1935
            target, overwrite=overwrite, stop_revision=stop_revision,
1936
            _override_hook_source_branch=self)
2018.14.3 by Andrew Bennetts
Make a couple more branch_implementations tests pass.
1937
1938
    def is_locked(self):
1939
        return self._lock_count >= 1
1940
3634.2.1 by John Arbash Meinel
Thunk over to the real branch's revision_id_to_revno.
1941
    @needs_read_lock
1942
    def revision_id_to_revno(self, revision_id):
1943
        self._ensure_real()
1944
        return self._real_branch.revision_id_to_revno(revision_id)
1945
2892.2.1 by Andrew Bennetts
Add Branch.set_last_revision_info smart method, and make the RemoteBranch client use it.
1946
    @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.
1947
    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.
1948
        # XXX: These should be returned by the set_last_revision_info verb
1949
        old_revno, old_revid = self.last_revision_info()
1950
        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.
1951
        revision_id = ensure_null(revision_id)
3297.4.2 by Andrew Bennetts
Add backwards compatibility for servers older than 1.4.
1952
        try:
3786.2.3 by Andrew Bennetts
Remove duplicated 'call & translate errors' code in bzrlib.remote.
1953
            response = self._call('Branch.set_last_revision_info',
1954
                self._remote_path(), self._lock_token, self._repo_lock_token,
1955
                str(revno), revision_id)
3297.4.2 by Andrew Bennetts
Add backwards compatibility for servers older than 1.4.
1956
        except errors.UnknownSmartMethod:
1957
            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.
1958
            self._clear_cached_state_of_remote_branch_only()
3441.5.1 by Andrew Bennetts
Avoid necessarily calling get_parent_map when pushing.
1959
            self._real_branch.set_last_revision_info(revno, revision_id)
1960
            self._last_revision_info_cache = revno, revision_id
1961
            return
2892.2.1 by Andrew Bennetts
Add Branch.set_last_revision_info smart method, and make the RemoteBranch client use it.
1962
        if response == ('ok',):
1963
            self._clear_cached_state()
3441.5.1 by Andrew Bennetts
Avoid necessarily calling get_parent_map when pushing.
1964
            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.
1965
            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.
1966
            # Update the _real_branch's cache too.
1967
            if self._real_branch is not None:
1968
                cache = self._last_revision_info_cache
1969
                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.
1970
        else:
1971
            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.
1972
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.
1973
    @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.
1974
    def generate_revision_history(self, revision_id, last_rev=None,
1975
                                  other_branch=None):
3441.5.6 by Andrew Bennetts
Greatly simplify RemoteBranch.update_revisions. Still needs more tests.
1976
        medium = self._client._medium
3441.5.23 by Andrew Bennetts
Fix test failures.
1977
        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.
1978
            # 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.
1979
            try:
3441.5.18 by Andrew Bennetts
Fix some test failures.
1980
                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.
1981
                    allow_diverged=True, allow_overwrite_descendant=True)
3441.5.6 by Andrew Bennetts
Greatly simplify RemoteBranch.update_revisions. Still needs more tests.
1982
                return
3441.5.18 by Andrew Bennetts
Fix some test failures.
1983
            except errors.UnknownSmartMethod:
3441.5.23 by Andrew Bennetts
Fix test failures.
1984
                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.
1985
        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.
1986
        self.set_revision_history(self._lefthand_history(revision_id,
1987
            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.
1988
2018.5.96 by Andrew Bennetts
Merge from bzr.dev, resolving the worst of the semantic conflicts, but there's
1989
    @property
1990
    def tags(self):
1991
        self._ensure_real()
1992
        return self._real_branch.tags
1993
2018.5.97 by Andrew Bennetts
Fix more tests.
1994
    def set_push_location(self, location):
1995
        self._ensure_real()
1996
        return self._real_branch.set_push_location(location)
1997
3441.5.6 by Andrew Bennetts
Greatly simplify RemoteBranch.update_revisions. Still needs more tests.
1998
    @needs_write_lock
3445.1.8 by John Arbash Meinel
Clarity tweaks recommended by Ian
1999
    def update_revisions(self, other, stop_revision=None, overwrite=False,
2000
                         graph=None):
3441.5.18 by Andrew Bennetts
Fix some test failures.
2001
        """See Branch.update_revisions."""
3441.5.1 by Andrew Bennetts
Avoid necessarily calling get_parent_map when pushing.
2002
        other.lock_read()
2003
        try:
2004
            if stop_revision is None:
3441.5.6 by Andrew Bennetts
Greatly simplify RemoteBranch.update_revisions. Still needs more tests.
2005
                stop_revision = other.last_revision()
3441.5.5 by Andrew Bennetts
Some small tweaks and comments.
2006
                if revision.is_null(stop_revision):
3441.5.1 by Andrew Bennetts
Avoid necessarily calling get_parent_map when pushing.
2007
                    # if there are no commits, we're done.
2008
                    return
2009
            self.fetch(other, stop_revision)
3441.5.6 by Andrew Bennetts
Greatly simplify RemoteBranch.update_revisions. Still needs more tests.
2010
2011
            if overwrite:
3441.5.18 by Andrew Bennetts
Fix some test failures.
2012
                # Just unconditionally set the new revision.  We don't care if
2013
                # the branches have diverged.
3441.5.1 by Andrew Bennetts
Avoid necessarily calling get_parent_map when pushing.
2014
                self._set_last_revision(stop_revision)
3441.5.6 by Andrew Bennetts
Greatly simplify RemoteBranch.update_revisions. Still needs more tests.
2015
            else:
2016
                medium = self._client._medium
3441.5.23 by Andrew Bennetts
Fix test failures.
2017
                if not medium._is_remote_before((1, 6)):
3441.5.6 by Andrew Bennetts
Greatly simplify RemoteBranch.update_revisions. Still needs more tests.
2018
                    try:
2019
                        self._set_last_revision_descendant(stop_revision, other)
2020
                        return
3441.5.7 by Andrew Bennetts
Fix unbound global.
2021
                    except errors.UnknownSmartMethod:
3441.5.23 by Andrew Bennetts
Fix test failures.
2022
                        medium._remember_remote_is_before((1, 6))
3441.5.18 by Andrew Bennetts
Fix some test failures.
2023
                # Fallback for pre-1.6 servers: check for divergence
2024
                # client-side, then do _set_last_revision.
3441.5.6 by Andrew Bennetts
Greatly simplify RemoteBranch.update_revisions. Still needs more tests.
2025
                last_rev = revision.ensure_null(self.last_revision())
3441.5.18 by Andrew Bennetts
Fix some test failures.
2026
                if graph is None:
2027
                    graph = self.repository.get_graph()
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.
2028
                if self._check_if_descendant_or_diverged(
3441.5.18 by Andrew Bennetts
Fix some test failures.
2029
                        stop_revision, last_rev, graph, other):
2030
                    # stop_revision is a descendant of last_rev, but we aren't
2031
                    # overwriting, so we're done.
2032
                    return
2033
                self._set_last_revision(stop_revision)
3441.5.1 by Andrew Bennetts
Avoid necessarily calling get_parent_map when pushing.
2034
        finally:
2035
            other.unlock()
2018.5.97 by Andrew Bennetts
Fix more tests.
2036
2018.18.25 by Martin Pool
Repository.tarball fixes for python2.4
2037
2038
def _extract_tar(tar, to_dir):
2039
    """Extract all the contents of a tarfile object.
2040
2041
    A replacement for extractall, which is not present in python2.4
2042
    """
2043
    for tarinfo in tar:
2044
        tar.extract(tarinfo, to_dir)
3533.3.1 by Andrew Bennetts
Remove duplication of error translation in bzrlib/remote.py.
2045
2046
2047
def _translate_error(err, **context):
2048
    """Translate an ErrorFromSmartServer into a more useful error.
2049
2050
    Possible context keys:
2051
      - branch
2052
      - repository
2053
      - bzrdir
2054
      - token
2055
      - other_branch
3779.3.2 by Andrew Bennetts
Unify error translation done in bzrlib.remote and bzrlib.transport.remote.
2056
      - path
3690.1.1 by Andrew Bennetts
Unexpected error responses from a smart server no longer cause the client to traceback.
2057
2058
    If the error from the server doesn't match a known pattern, then
3690.1.2 by Andrew Bennetts
Rename UntranslateableErrorFromSmartServer -> UnknownErrorFromSmartServer.
2059
    UnknownErrorFromSmartServer is raised.
3533.3.1 by Andrew Bennetts
Remove duplication of error translation in bzrlib/remote.py.
2060
    """
2061
    def find(name):
3533.3.4 by Andrew Bennetts
Add tests for _translate_error's robustness.
2062
        try:
2063
            return context[name]
3779.3.2 by Andrew Bennetts
Unify error translation done in bzrlib.remote and bzrlib.transport.remote.
2064
        except KeyError, key_err:
2065
            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.
2066
            raise err
3779.3.2 by Andrew Bennetts
Unify error translation done in bzrlib.remote and bzrlib.transport.remote.
2067
    def get_path():
3779.3.3 by Andrew Bennetts
Add a docstring.
2068
        """Get the path from the context if present, otherwise use first error
2069
        arg.
2070
        """
3779.3.2 by Andrew Bennetts
Unify error translation done in bzrlib.remote and bzrlib.transport.remote.
2071
        try:
2072
            return context['path']
2073
        except KeyError, key_err:
2074
            try:
2075
                return err.error_args[0]
2076
            except IndexError, idx_err:
2077
                mutter(
2078
                    'Missing key %r in context %r', key_err.args[0], context)
2079
                raise err
2080
3533.3.1 by Andrew Bennetts
Remove duplication of error translation in bzrlib/remote.py.
2081
    if err.error_verb == 'NoSuchRevision':
2082
        raise NoSuchRevision(find('branch'), err.error_args[0])
2083
    elif err.error_verb == 'nosuchrevision':
2084
        raise NoSuchRevision(find('repository'), err.error_args[0])
2085
    elif err.error_tuple == ('nobranch',):
3533.3.4 by Andrew Bennetts
Add tests for _translate_error's robustness.
2086
        raise errors.NotBranchError(path=find('bzrdir').root_transport.base)
3533.3.1 by Andrew Bennetts
Remove duplication of error translation in bzrlib/remote.py.
2087
    elif err.error_verb == 'norepository':
2088
        raise errors.NoRepositoryPresent(find('bzrdir'))
2089
    elif err.error_verb == 'LockContention':
2090
        raise errors.LockContention('(remote lock)')
2091
    elif err.error_verb == 'UnlockableTransport':
3533.3.4 by Andrew Bennetts
Add tests for _translate_error's robustness.
2092
        raise errors.UnlockableTransport(find('bzrdir').root_transport)
3533.3.1 by Andrew Bennetts
Remove duplication of error translation in bzrlib/remote.py.
2093
    elif err.error_verb == 'LockFailed':
2094
        raise errors.LockFailed(err.error_args[0], err.error_args[1])
2095
    elif err.error_verb == 'TokenMismatch':
2096
        raise errors.TokenMismatch(find('token'), '(remote token)')
2097
    elif err.error_verb == 'Diverged':
2098
        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.
2099
    elif err.error_verb == 'TipChangeRejected':
2100
        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
2101
    elif err.error_verb == 'UnstackableBranchFormat':
2102
        raise errors.UnstackableBranchFormat(*err.error_args)
2103
    elif err.error_verb == 'UnstackableRepositoryFormat':
2104
        raise errors.UnstackableRepositoryFormat(*err.error_args)
2105
    elif err.error_verb == 'NotStacked':
2106
        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.
2107
    elif err.error_verb == 'PermissionDenied':
3779.3.2 by Andrew Bennetts
Unify error translation done in bzrlib.remote and bzrlib.transport.remote.
2108
        path = get_path()
3779.3.1 by Andrew Bennetts
Move encoding/decoding logic of PermissionDenied and ReadError so that it happens for all RPCs.
2109
        if len(err.error_args) >= 2:
2110
            extra = err.error_args[1]
3779.3.2 by Andrew Bennetts
Unify error translation done in bzrlib.remote and bzrlib.transport.remote.
2111
        else:
2112
            extra = None
3779.3.1 by Andrew Bennetts
Move encoding/decoding logic of PermissionDenied and ReadError so that it happens for all RPCs.
2113
        raise errors.PermissionDenied(path, extra=extra)
3779.3.2 by Andrew Bennetts
Unify error translation done in bzrlib.remote and bzrlib.transport.remote.
2114
    elif err.error_verb == 'ReadError':
2115
        path = get_path()
2116
        raise errors.ReadError(path)
2117
    elif err.error_verb == 'NoSuchFile':
2118
        path = get_path()
2119
        raise errors.NoSuchFile(path)
2120
    elif err.error_verb == 'FileExists':
2121
        raise errors.FileExists(err.error_args[0])
2122
    elif err.error_verb == 'DirectoryNotEmpty':
2123
        raise errors.DirectoryNotEmpty(err.error_args[0])
2124
    elif err.error_verb == 'ShortReadvError':
2125
        args = err.error_args
2126
        raise errors.ShortReadvError(
2127
            args[0], int(args[1]), int(args[2]), int(args[3]))
2128
    elif err.error_verb in ('UnicodeEncodeError', 'UnicodeDecodeError'):
2129
        encoding = str(err.error_args[0]) # encoding must always be a string
2130
        val = err.error_args[1]
2131
        start = int(err.error_args[2])
2132
        end = int(err.error_args[3])
2133
        reason = str(err.error_args[4]) # reason must always be a string
2134
        if val.startswith('u:'):
2135
            val = val[2:].decode('utf-8')
2136
        elif val.startswith('s:'):
2137
            val = val[2:].decode('base64')
3786.2.3 by Andrew Bennetts
Remove duplicated 'call & translate errors' code in bzrlib.remote.
2138
        if err.error_verb == 'UnicodeDecodeError':
3779.3.2 by Andrew Bennetts
Unify error translation done in bzrlib.remote and bzrlib.transport.remote.
2139
            raise UnicodeDecodeError(encoding, val, start, end, reason)
3786.2.3 by Andrew Bennetts
Remove duplicated 'call & translate errors' code in bzrlib.remote.
2140
        elif err.error_verb == 'UnicodeEncodeError':
3779.3.2 by Andrew Bennetts
Unify error translation done in bzrlib.remote and bzrlib.transport.remote.
2141
            raise UnicodeEncodeError(encoding, val, start, end, reason)
2142
    elif err.error_verb == 'ReadOnlyError':
2143
        raise errors.TransportNotPossible('readonly transport')
3690.1.2 by Andrew Bennetts
Rename UntranslateableErrorFromSmartServer -> UnknownErrorFromSmartServer.
2144
    raise errors.UnknownErrorFromSmartServer(err)