/brz/remove-bazaar

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