/brz/remove-bazaar

To get this branch, use:
bzr branch http://gegoxaren.bato24.eu/bzr/brz/remove-bazaar
3408.3.1 by Martin Pool
Remove erroneous handling of branch.conf for RemoteBranch
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
2018.5.59 by Robert Collins
Get BranchConfig working somewhat on RemoteBranches (Robert Collins, Vincent Ladeuil).
21
from cStringIO import StringIO
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,
2490.2.5 by Aaron Bentley
Use GraphWalker.unique_ancestor to determine merge base
32
)
2535.4.27 by Andrew Bennetts
Remove some unused imports.
33
from bzrlib.branch import BranchReferenceFormat
2018.5.174 by Andrew Bennetts
Various nits discovered by pyflakes.
34
from bzrlib.bzrdir import BzrDir, RemoteBzrDirFormat
2018.14.2 by Andrew Bennetts
All but one repository_implementation tests for RemoteRepository passing.
35
from bzrlib.config import BranchConfig, TreeConfig
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
2535.4.20 by Andrew Bennetts
Remove unused import.
42
from bzrlib.pack import ContainerPushParser
2018.6.1 by Robert Collins
Implement a BzrDir.open_branch smart server method for opening a branch without VFS.
43
from bzrlib.smart import client, vfs
3297.4.1 by Andrew Bennetts
Merge 'Add Branch.set_last_revision_info smart method'.
44
from bzrlib.revision import ensure_null, NULL_REVISION
3441.5.5 by Andrew Bennetts
Some small tweaks and comments.
45
from bzrlib.trace import mutter, note, warning
1752.2.30 by Martin Pool
Start adding a RemoteBzrDir, etc
46
2018.5.25 by Andrew Bennetts
Make sure RemoteBzrDirFormat is always registered (John Arbash Meinel, Robert Collins, Andrew Bennetts).
47
# Note: RemoteBzrDirFormat is in bzrdir.py
1752.2.30 by Martin Pool
Start adding a RemoteBzrDir, etc
48
49
class RemoteBzrDir(BzrDir):
2018.5.163 by Andrew Bennetts
Deal with various review comments from Robert.
50
    """Control directory on a remote server, accessed via bzr:// or similar."""
1752.2.30 by Martin Pool
Start adding a RemoteBzrDir, etc
51
2018.5.51 by Wouter van Heyst
Test and implement RemoteBranch.last_revision_info()
52
    def __init__(self, transport, _client=None):
53
        """Construct a RemoteBzrDir.
54
55
        :param _client: Private parameter for testing. Disables probing and the
56
            use of a real bzrdir.
57
        """
1752.2.39 by Martin Pool
[broken] implement upgrade apis on remote bzrdirs
58
        BzrDir.__init__(self, transport, RemoteBzrDirFormat())
1752.2.31 by Martin Pool
[broken] some support for write operations over hpss
59
        # this object holds a delegated bzrdir that uses file-level operations
60
        # to talk to the other side
2018.5.70 by Robert Collins
Only try to get real repositories when an operation requires them.
61
        self._real_bzrdir = None
2018.14.1 by Andrew Bennetts
Update to current hpss branch? Fix lots of test failures.
62
63
        if _client is None:
3313.2.3 by Andrew Bennetts
Deprecate Transport.get_shared_medium.
64
            medium = transport.get_smart_medium()
3431.3.2 by Andrew Bennetts
Remove 'base' from _SmartClient entirely, now that the medium has it.
65
            self._client = client._SmartClient(medium)
2018.14.1 by Andrew Bennetts
Update to current hpss branch? Fix lots of test failures.
66
        else:
67
            self._client = _client
68
            return
69
70
        path = self._path_for_remote_call(self._client)
2018.5.163 by Andrew Bennetts
Deal with various review comments from Robert.
71
        response = self._client.call('BzrDir.open', path)
72
        if response not in [('yes',), ('no',)]:
73
            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.
74
        if response == ('no',):
75
            raise errors.NotBranchError(path=transport.base)
1752.2.31 by Martin Pool
[broken] some support for write operations over hpss
76
2018.5.70 by Robert Collins
Only try to get real repositories when an operation requires them.
77
    def _ensure_real(self):
78
        """Ensure that there is a _real_bzrdir set.
79
2018.5.163 by Andrew Bennetts
Deal with various review comments from Robert.
80
        Used before calls to self._real_bzrdir.
2018.5.70 by Robert Collins
Only try to get real repositories when an operation requires them.
81
        """
82
        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.
83
            self._real_bzrdir = BzrDir.open_from_transport(
84
                self.root_transport, _server_formats=False)
2018.5.70 by Robert Collins
Only try to get real repositories when an operation requires them.
85
1752.2.39 by Martin Pool
[broken] implement upgrade apis on remote bzrdirs
86
    def create_repository(self, shared=False):
2018.5.162 by Andrew Bennetts
Add some missing _ensure_real calls, and a missing import.
87
        self._ensure_real()
2018.5.118 by Robert Collins
Fix RemoteRepositoryFormat to have appropriate rich_root_data and support_tree_reference.
88
        self._real_bzrdir.create_repository(shared=shared)
89
        return self.open_repository()
1752.2.50 by Andrew Bennetts
Implement RemoteBzrDir.create_{branch,workingtree}
90
2796.2.19 by Aaron Bentley
Support reconfigure --lightweight-checkout
91
    def destroy_repository(self):
92
        """See BzrDir.destroy_repository"""
93
        self._ensure_real()
94
        self._real_bzrdir.destroy_repository()
95
1752.2.50 by Andrew Bennetts
Implement RemoteBzrDir.create_{branch,workingtree}
96
    def create_branch(self):
2018.5.162 by Andrew Bennetts
Add some missing _ensure_real calls, and a missing import.
97
        self._ensure_real()
1752.2.72 by Andrew Bennetts
Make Remote* classes in remote.py more consistent and remove some dead code.
98
        real_branch = self._real_bzrdir.create_branch()
2018.5.70 by Robert Collins
Only try to get real repositories when an operation requires them.
99
        return RemoteBranch(self, self.find_repository(), real_branch)
1752.2.50 by Andrew Bennetts
Implement RemoteBzrDir.create_{branch,workingtree}
100
2796.2.6 by Aaron Bentley
Implement destroy_branch
101
    def destroy_branch(self):
2796.2.16 by Aaron Bentley
Documentation updates from review
102
        """See BzrDir.destroy_branch"""
2796.2.6 by Aaron Bentley
Implement destroy_branch
103
        self._ensure_real()
104
        self._real_bzrdir.destroy_branch()
105
2955.5.3 by Vincent Ladeuil
Fix second unwanted connection by providing the right branch to create_checkout.
106
    def create_workingtree(self, revision_id=None, from_branch=None):
2018.5.174 by Andrew Bennetts
Various nits discovered by pyflakes.
107
        raise errors.NotLocalUrl(self.transport.base)
1752.2.39 by Martin Pool
[broken] implement upgrade apis on remote bzrdirs
108
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.
109
    def find_branch_format(self):
110
        """Find the branch 'format' for this bzrdir.
111
112
        This might be a synthetic object for e.g. RemoteBranch and SVN.
113
        """
114
        b = self.open_branch()
115
        return b._format
116
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.
117
    def get_branch_reference(self):
118
        """See BzrDir.get_branch_reference()."""
2018.14.1 by Andrew Bennetts
Update to current hpss branch? Fix lots of test failures.
119
        path = self._path_for_remote_call(self._client)
3245.4.24 by Andrew Bennetts
Consistently raise errors from the server as ErrorFromSmartServer exceptions.
120
        try:
121
            response = self._client.call('BzrDir.open_branch', path)
122
        except errors.ErrorFromSmartServer, err:
123
            if err.error_tuple == ('nobranch',):
124
                raise errors.NotBranchError(path=self.root_transport.base)
125
            raise
2018.14.1 by Andrew Bennetts
Update to current hpss branch? Fix lots of test failures.
126
        if response[0] == 'ok':
127
            if response[1] == '':
128
                # 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.
129
                return None
2018.14.1 by Andrew Bennetts
Update to current hpss branch? Fix lots of test failures.
130
            else:
131
                # 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.
132
                return response[1]
2018.6.1 by Robert Collins
Implement a BzrDir.open_branch smart server method for opening a branch without VFS.
133
        else:
2555.1.1 by Martin Pool
Remove use of 'assert False' to raise an exception unconditionally
134
            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.
135
3211.4.1 by Robert Collins
* ``RemoteBzrDir._get_tree_branch`` no longer triggers ``_ensure_real``,
136
    def _get_tree_branch(self):
137
        """See BzrDir._get_tree_branch()."""
138
        return None, self.open_branch()
139
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.
140
    def open_branch(self, _unsupported=False):
3376.2.4 by Martin Pool
Remove every assert statement from bzrlib!
141
        if _unsupported:
142
            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.
143
        reference_url = self.get_branch_reference()
144
        if reference_url is None:
145
            # branch at this location.
146
            return RemoteBranch(self, self.find_repository())
147
        else:
148
            # a branch reference, use the existing BranchReference logic.
149
            format = BranchReferenceFormat()
150
            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.
151
                
1752.2.31 by Martin Pool
[broken] some support for write operations over hpss
152
    def open_repository(self):
2018.14.1 by Andrew Bennetts
Update to current hpss branch? Fix lots of test failures.
153
        path = self._path_for_remote_call(self._client)
3221.3.3 by Robert Collins
* Hook up the new remote method ``RemoteBzrDir.find_repositoryV2`` so
154
        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.
155
        try:
3245.4.24 by Andrew Bennetts
Consistently raise errors from the server as ErrorFromSmartServer exceptions.
156
            try:
157
                response = self._client.call(verb, path)
158
            except errors.UnknownSmartMethod:
159
                verb = 'BzrDir.find_repository'
160
                response = self._client.call(verb, path)
161
        except errors.ErrorFromSmartServer, err:
3245.4.52 by Andrew Bennetts
Add 'error_verb' and 'error_args' attributes to ErrorFromSmartServer.
162
            if err.error_verb == 'norepository':
3245.4.24 by Andrew Bennetts
Consistently raise errors from the server as ErrorFromSmartServer exceptions.
163
                raise errors.NoRepositoryPresent(self)
164
            raise
165
        if response[0] != 'ok':
166
            raise errors.UnexpectedSmartServerResponse(response)
3221.3.3 by Robert Collins
* Hook up the new remote method ``RemoteBzrDir.find_repositoryV2`` so
167
        if verb == 'BzrDir.find_repository':
168
            # servers that don't support the V2 method don't support external
169
            # references either.
170
            response = response + ('no', )
3376.2.4 by Martin Pool
Remove every assert statement from bzrlib!
171
        if not (len(response) == 5):
172
            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.
173
        if response[1] == '':
2018.5.118 by Robert Collins
Fix RemoteRepositoryFormat to have appropriate rich_root_data and support_tree_reference.
174
            format = RemoteRepositoryFormat()
2018.5.166 by Andrew Bennetts
Small changes in response to Aaron's review.
175
            format.rich_root_data = (response[2] == 'yes')
176
            format.supports_tree_reference = (response[3] == 'yes')
3221.3.1 by Robert Collins
* Repository formats have a new supported-feature attribute
177
            # No wire format to check this yet.
3221.3.3 by Robert Collins
* Hook up the new remote method ``RemoteBzrDir.find_repositoryV2`` so
178
            format.supports_external_lookups = (response[4] == 'yes')
2018.5.118 by Robert Collins
Fix RemoteRepositoryFormat to have appropriate rich_root_data and support_tree_reference.
179
            return RemoteRepository(self, format)
2018.5.34 by Robert Collins
Get test_remote.BasicRemoteObjectTests.test_open_remote_branch passing by implementing a remote method BzrDir.find_repository.
180
        else:
181
            raise errors.NoRepositoryPresent(self)
1752.2.30 by Martin Pool
Start adding a RemoteBzrDir, etc
182
2018.5.138 by Robert Collins
Merge bzr.dev.
183
    def open_workingtree(self, recommend_upgrade=True):
2445.1.1 by Andrew Bennetts
Make RemoteBzrDir.open_workingtree raise NoWorkingTree rather than NotLocalUrl
184
        self._ensure_real()
185
        if self._real_bzrdir.has_workingtree():
186
            raise errors.NotLocalUrl(self.root_transport)
187
        else:
188
            raise errors.NoWorkingTree(self.root_transport.base)
1752.2.50 by Andrew Bennetts
Implement RemoteBzrDir.create_{branch,workingtree}
189
2018.5.42 by Robert Collins
Various hopefully improvements, but wsgi is broken, handing over to spiv :).
190
    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.
191
        """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 :).
192
        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.
193
1752.2.31 by Martin Pool
[broken] some support for write operations over hpss
194
    def get_branch_transport(self, branch_format):
2018.5.162 by Andrew Bennetts
Add some missing _ensure_real calls, and a missing import.
195
        self._ensure_real()
1752.2.31 by Martin Pool
[broken] some support for write operations over hpss
196
        return self._real_bzrdir.get_branch_transport(branch_format)
197
1752.2.43 by Andrew Bennetts
Fix get_{branch,repository,workingtree}_transport.
198
    def get_repository_transport(self, repository_format):
2018.5.162 by Andrew Bennetts
Add some missing _ensure_real calls, and a missing import.
199
        self._ensure_real()
1752.2.43 by Andrew Bennetts
Fix get_{branch,repository,workingtree}_transport.
200
        return self._real_bzrdir.get_repository_transport(repository_format)
201
202
    def get_workingtree_transport(self, workingtree_format):
2018.5.162 by Andrew Bennetts
Add some missing _ensure_real calls, and a missing import.
203
        self._ensure_real()
1752.2.43 by Andrew Bennetts
Fix get_{branch,repository,workingtree}_transport.
204
        return self._real_bzrdir.get_workingtree_transport(workingtree_format)
205
1752.2.39 by Martin Pool
[broken] implement upgrade apis on remote bzrdirs
206
    def can_convert_format(self):
207
        """Upgrading of remote bzrdirs is not supported yet."""
208
        return False
209
210
    def needs_format_conversion(self, format=None):
211
        """Upgrading of remote bzrdirs is not supported yet."""
212
        return False
213
2018.5.138 by Robert Collins
Merge bzr.dev.
214
    def clone(self, url, revision_id=None, force_new_repo=False):
2018.5.94 by Andrew Bennetts
Various small changes in aid of making tests pass (including deleting one invalid test).
215
        self._ensure_real()
216
        return self._real_bzrdir.clone(url, revision_id=revision_id,
2018.5.138 by Robert Collins
Merge bzr.dev.
217
            force_new_repo=force_new_repo)
2018.5.94 by Andrew Bennetts
Various small changes in aid of making tests pass (including deleting one invalid test).
218
1752.2.31 by Martin Pool
[broken] some support for write operations over hpss
219
1752.2.52 by Andrew Bennetts
Flesh out more Remote* methods needed to open and initialise remote branches/trees/repositories.
220
class RemoteRepositoryFormat(repository.RepositoryFormat):
2018.5.159 by Andrew Bennetts
Rename SmartClient to _SmartClient.
221
    """Format for repositories accessed over a _SmartClient.
1752.2.31 by Martin Pool
[broken] some support for write operations over hpss
222
1752.2.50 by Andrew Bennetts
Implement RemoteBzrDir.create_{branch,workingtree}
223
    Instances of this repository are represented by RemoteRepository
1752.2.31 by Martin Pool
[broken] some support for write operations over hpss
224
    instances.
2018.5.118 by Robert Collins
Fix RemoteRepositoryFormat to have appropriate rich_root_data and support_tree_reference.
225
3128.1.3 by Vincent Ladeuil
Since we are there s/parameteris.*/parameteriz&/.
226
    The RemoteRepositoryFormat is parameterized during construction
2018.5.118 by Robert Collins
Fix RemoteRepositoryFormat to have appropriate rich_root_data and support_tree_reference.
227
    to reflect the capabilities of the real, remote format. Specifically
2018.5.138 by Robert Collins
Merge bzr.dev.
228
    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.
229
    on a per instance basis, and are not set (and should not be) at
230
    the class level.
1752.2.31 by Martin Pool
[broken] some support for write operations over hpss
231
    """
232
233
    _matchingbzrdir = RemoteBzrDirFormat
234
1752.2.52 by Andrew Bennetts
Flesh out more Remote* methods needed to open and initialise remote branches/trees/repositories.
235
    def initialize(self, a_bzrdir, shared=False):
3376.2.4 by Martin Pool
Remove every assert statement from bzrlib!
236
        if not isinstance(a_bzrdir, RemoteBzrDir):
237
            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.
238
        return a_bzrdir.create_repository(shared=shared)
1752.2.52 by Andrew Bennetts
Flesh out more Remote* methods needed to open and initialise remote branches/trees/repositories.
239
    
240
    def open(self, a_bzrdir):
3376.2.4 by Martin Pool
Remove every assert statement from bzrlib!
241
        if not isinstance(a_bzrdir, RemoteBzrDir):
242
            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.
243
        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.
244
245
    def get_format_description(self):
246
        return 'bzr remote repository'
247
248
    def __eq__(self, other):
1752.2.87 by Andrew Bennetts
Make tests pass.
249
        return self.__class__ == other.__class__
250
2018.5.118 by Robert Collins
Fix RemoteRepositoryFormat to have appropriate rich_root_data and support_tree_reference.
251
    def check_conversion_target(self, target_format):
252
        if self.rich_root_data and not target_format.rich_root_data:
253
            raise errors.BadConversionTarget(
254
                'Does not support rich root data.', target_format)
2018.5.138 by Robert Collins
Merge bzr.dev.
255
        if (self.supports_tree_reference and
256
            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.
257
            raise errors.BadConversionTarget(
258
                '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.
259
1752.2.31 by Martin Pool
[broken] some support for write operations over hpss
260
3441.5.1 by Andrew Bennetts
Avoid necessarily calling get_parent_map when pushing.
261
class RemoteGraph(object):
262
263
    def __init__(self, real_graph, remote_repo):
264
        self._real_graph = real_graph
265
        self._remote_repo = remote_repo
266
267
    def heads(self, keys):
268
        client = self._remote_repo._client
269
        path = self._remote_repo.bzrdir._path_for_remote_call(client)
270
        return set(client.call('Repository.graph_heads', path, *keys))
271
3441.5.4 by Andrew Bennetts
Fix test failures, and add some tests for the remote graph heads RPC.
272
    # All other Graph methods delegate to _real_graph
273
3441.5.1 by Andrew Bennetts
Avoid necessarily calling get_parent_map when pushing.
274
    def find_lca(self, *revisions):
275
        return self._real_graph.find_lca(*revisions)
276
277
    def find_difference(self, left_revision, right_revision):
278
        return self._real_graph.find_difference(left_revision, right_revision)
279
280
    def find_unique_ancestors(self, unique_revision, common_revisions):
281
        return self._real_graph.find_unique_ancestors(
282
            unique_revision, common_revisions)
283
284
    def find_unique_lca(self, left_revision, right_revision,
285
                        count_steps=False):
286
        return self._real_graph.find_unique_lca(
287
            left_revision, right_revision, count_steps=count_steps)
288
        
289
    def get_parents(self, revisions):
290
        return self._real_graph.get_parents(revisions)
291
292
    def get_parent_map(self, revisions):
3441.5.4 by Andrew Bennetts
Fix test failures, and add some tests for the remote graph heads RPC.
293
        return self._remote_repo.get_parent_map(revisions)
3441.5.1 by Andrew Bennetts
Avoid necessarily calling get_parent_map when pushing.
294
295
    def is_ancestor(self, candidate_ancestor, candidate_descendant):
296
        return self._real_graph.is_ancestor(
297
            candidate_ancestor, candidate_descendant)
298
299
    def iter_ancestry(self, revision_ids):
300
        return self._real_graph.iter_ancestry(revision_ids)
301
302
    def iter_topo_order(self, revisions):
303
        return self._real_graph.iter_topo_order(revisions)
304
305
    def _make_breadth_first_searcher(self, revisions):
306
        return self._real_graph._make_breadth_first_searcher(revisions)
307
308
1752.2.50 by Andrew Bennetts
Implement RemoteBzrDir.create_{branch,workingtree}
309
class RemoteRepository(object):
1752.2.31 by Martin Pool
[broken] some support for write operations over hpss
310
    """Repository accessed over rpc.
311
2018.5.163 by Andrew Bennetts
Deal with various review comments from Robert.
312
    For the moment most operations are performed using local transport-backed
313
    Repository objects.
1752.2.31 by Martin Pool
[broken] some support for write operations over hpss
314
    """
315
2018.5.118 by Robert Collins
Fix RemoteRepositoryFormat to have appropriate rich_root_data and support_tree_reference.
316
    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.
317
        """Create a RemoteRepository instance.
318
        
319
        :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.
320
        :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.
321
        :param real_repository: If not None, a local implementation of the
322
            repository logic for the repository, usually accessing the data
323
            via the VFS.
2018.5.57 by Robert Collins
Implement RemoteRepository.is_shared (Robert Collins, Vincent Ladeuil).
324
        :param _client: Private testing parameter - override the smart client
325
            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.
326
        """
327
        if real_repository:
2018.5.36 by Andrew Bennetts
Fix typo, and clean up some ununsed import warnings from pyflakes at the same time.
328
            self._real_repository = real_repository
2018.5.70 by Robert Collins
Only try to get real repositories when an operation requires them.
329
        else:
330
            self._real_repository = None
1752.2.50 by Andrew Bennetts
Implement RemoteBzrDir.create_{branch,workingtree}
331
        self.bzrdir = remote_bzrdir
2018.5.57 by Robert Collins
Implement RemoteRepository.is_shared (Robert Collins, Vincent Ladeuil).
332
        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.
333
            self._client = remote_bzrdir._client
2018.5.57 by Robert Collins
Implement RemoteRepository.is_shared (Robert Collins, Vincent Ladeuil).
334
        else:
335
            self._client = _client
2018.5.118 by Robert Collins
Fix RemoteRepositoryFormat to have appropriate rich_root_data and support_tree_reference.
336
        self._format = format
2018.5.75 by Andrew Bennetts
Add Repository.{dont_,}leave_lock_in_place.
337
        self._lock_mode = None
338
        self._lock_token = None
339
        self._lock_count = 0
2018.5.78 by Andrew Bennetts
Implement RemoteRepository.lock_write/unlock to expect and send tokens over the
340
        self._leave_lock = False
3172.5.4 by Robert Collins
Implement get_parent_map for RemoteRepository with caching, based on get_revision_graph.
341
        # A cache of looked up revision parent data; reset at unlock time.
342
        self._parents_map = None
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.
343
        if 'hpss' in debug.debug_flags:
344
            self._requested_parents = None
2951.1.10 by Robert Collins
Peer review feedback with Ian.
345
        # For tests:
346
        # These depend on the actual remote format, so force them off for
347
        # maximum compatibility. XXX: In future these should depend on the
348
        # remote repository instance, but this is irrelevant until we perform
349
        # 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.
350
        self._reconcile_does_inventory_gc = False
351
        self._reconcile_fixes_text_parents = False
2951.1.3 by Robert Collins
Partial support for native reconcile with packs.
352
        self._reconcile_backsup_inventory = False
2592.4.5 by Martin Pool
Add Repository.base on all repositories.
353
        self.base = self.bzrdir.transport.base
354
355
    def __str__(self):
356
        return "%s(%s)" % (self.__class__.__name__, self.base)
357
358
    __repr__ = __str__
1752.2.52 by Andrew Bennetts
Flesh out more Remote* methods needed to open and initialise remote branches/trees/repositories.
359
2617.6.2 by Robert Collins
Add abort_write_group and wire write_groups into fetch and commit.
360
    def abort_write_group(self):
2617.6.7 by Robert Collins
More review feedback.
361
        """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.
362
        
363
        Smart methods peform operations in a single step so this api
2617.6.6 by Robert Collins
Some review feedback.
364
        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.
365
        for older plugins that don't use e.g. the CommitBuilder
366
        facility.
367
        """
368
        self._ensure_real()
369
        return self._real_repository.abort_write_group()
370
371
    def commit_write_group(self):
2617.6.7 by Robert Collins
More review feedback.
372
        """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.
373
        
374
        Smart methods peform operations in a single step so this api
2617.6.6 by Robert Collins
Some review feedback.
375
        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.
376
        for older plugins that don't use e.g. the CommitBuilder
377
        facility.
378
        """
379
        self._ensure_real()
380
        return self._real_repository.commit_write_group()
2617.6.1 by Robert Collins
* New method on Repository - ``start_write_group``, ``end_write_group``
381
2018.5.70 by Robert Collins
Only try to get real repositories when an operation requires them.
382
    def _ensure_real(self):
383
        """Ensure that there is a _real_repository set.
384
2018.5.163 by Andrew Bennetts
Deal with various review comments from Robert.
385
        Used before calls to self._real_repository.
2018.5.70 by Robert Collins
Only try to get real repositories when an operation requires them.
386
        """
387
        if not self._real_repository:
388
            self.bzrdir._ensure_real()
2018.14.1 by Andrew Bennetts
Update to current hpss branch? Fix lots of test failures.
389
            #self._real_repository = self.bzrdir._real_bzrdir.open_repository()
390
            self._set_real_repository(self.bzrdir._real_bzrdir.open_repository())
2018.5.70 by Robert Collins
Only try to get real repositories when an operation requires them.
391
2988.1.2 by Robert Collins
New Repository API find_text_key_references for use by reconcile and check.
392
    def find_text_key_references(self):
393
        """Find the text key references within the repository.
394
395
        :return: a dictionary mapping (file_id, revision_id) tuples to altered file-ids to an iterable of
396
        revision_ids. Each altered file-ids has the exact revision_ids that
397
        altered it listed explicitly.
398
        :return: A dictionary mapping text keys ((fileid, revision_id) tuples)
399
            to whether they were referred to by the inventory of the
400
            revision_id that they contain. The inventory texts from all present
401
            revision ids are assessed to generate this report.
402
        """
403
        self._ensure_real()
404
        return self._real_repository.find_text_key_references()
405
2988.1.3 by Robert Collins
Add a new repositoy method _generate_text_key_index for use by reconcile/check.
406
    def _generate_text_key_index(self):
407
        """Generate a new text key index for the repository.
408
409
        This is an expensive function that will take considerable time to run.
410
411
        :return: A dict mapping (file_id, revision_id) tuples to a list of
412
            parents, also (file_id, revision_id) tuples.
413
        """
414
        self._ensure_real()
415
        return self._real_repository._generate_text_key_index()
416
3287.6.1 by Robert Collins
* ``VersionedFile.get_graph`` is deprecated, with no replacement method.
417
    @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)
418
    def get_revision_graph(self, revision_id=None):
419
        """See Repository.get_revision_graph()."""
3287.6.4 by Robert Collins
Fix up deprecation warnings for get_revision_graph.
420
        return self._get_revision_graph(revision_id)
421
422
    def _get_revision_graph(self, revision_id):
423
        """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)
424
        if revision_id is None:
425
            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.
426
        elif revision.is_null(revision_id):
2018.5.67 by Wouter van Heyst
Implement RemoteRepository.get_revision_graph (Wouter van Heyst, Robert Collins)
427
            return {}
428
429
        path = self.bzrdir._path_for_remote_call(self._client)
3245.4.24 by Andrew Bennetts
Consistently raise errors from the server as ErrorFromSmartServer exceptions.
430
        try:
431
            response = self._client.call_expecting_body(
432
                'Repository.get_revision_graph', path, revision_id)
433
        except errors.ErrorFromSmartServer, err:
3245.4.52 by Andrew Bennetts
Add 'error_verb' and 'error_args' attributes to ErrorFromSmartServer.
434
            if err.error_verb == 'nosuchrevision':
3245.4.24 by Andrew Bennetts
Consistently raise errors from the server as ErrorFromSmartServer exceptions.
435
                raise NoSuchRevision(self, revision_id)
3245.4.53 by Andrew Bennetts
Add some missing 'raise' statements to test_remote.
436
            raise
3245.4.58 by Andrew Bennetts
Unpack call_expecting_body's return value into variables, to avoid lots of ugly subscripting.
437
        response_tuple, response_handler = response
438
        if response_tuple[0] != 'ok':
439
            raise errors.UnexpectedSmartServerResponse(response_tuple)
440
        coded = response_handler.read_body_bytes()
3245.4.24 by Andrew Bennetts
Consistently raise errors from the server as ErrorFromSmartServer exceptions.
441
        if coded == '':
442
            # no revisions in this repository!
443
            return {}
444
        lines = coded.split('\n')
445
        revision_graph = {}
446
        for line in lines:
447
            d = tuple(line.split())
448
            revision_graph[d[0]] = d[1:]
449
            
450
        return revision_graph
2018.5.67 by Wouter van Heyst
Implement RemoteRepository.get_revision_graph (Wouter van Heyst, Robert Collins)
451
2018.5.40 by Robert Collins
Implement a remote Repository.has_revision method.
452
    def has_revision(self, revision_id):
453
        """See Repository.has_revision()."""
3172.3.1 by Robert Collins
Repository has a new method ``has_revisions`` which signals the presence
454
        if revision_id == NULL_REVISION:
2018.14.1 by Andrew Bennetts
Update to current hpss branch? Fix lots of test failures.
455
            # The null revision is always present.
456
            return True
2018.5.42 by Robert Collins
Various hopefully improvements, but wsgi is broken, handing over to spiv :).
457
        path = self.bzrdir._path_for_remote_call(self._client)
3245.4.58 by Andrew Bennetts
Unpack call_expecting_body's return value into variables, to avoid lots of ugly subscripting.
458
        response = self._client.call(
459
            'Repository.has_revision', path, revision_id)
3376.2.4 by Martin Pool
Remove every assert statement from bzrlib!
460
        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.
461
            raise errors.UnexpectedSmartServerResponse(response)
2018.5.158 by Andrew Bennetts
Return 'yes'/'no' rather than 'ok'/'no' from the Repository.has_revision smart command.
462
        return response[0] == 'yes'
2018.5.40 by Robert Collins
Implement a remote Repository.has_revision method.
463
3172.3.1 by Robert Collins
Repository has a new method ``has_revisions`` which signals the presence
464
    def has_revisions(self, revision_ids):
465
        """See Repository.has_revisions()."""
466
        result = set()
467
        for revision_id in revision_ids:
468
            if self.has_revision(revision_id):
469
                result.add(revision_id)
470
        return result
471
2617.6.9 by Robert Collins
Merge bzr.dev.
472
    def has_same_location(self, other):
2592.3.162 by Robert Collins
Remove some arbitrary differences from bzr.dev.
473
        return (self.__class__ == other.__class__ and
474
                self.bzrdir.transport.base == other.bzrdir.transport.base)
2617.6.9 by Robert Collins
Merge bzr.dev.
475
        
2490.2.21 by Aaron Bentley
Rename graph to deprecated_graph
476
    def get_graph(self, other_repository=None):
477
        """Return the graph for this repository format"""
3172.5.1 by Robert Collins
Create a RemoteRepository get_graph implementation and delegate get_parents_map to the real repository.
478
        parents_provider = self
479
        if (other_repository is not None and
480
            other_repository.bzrdir.transport.base !=
481
            self.bzrdir.transport.base):
482
            parents_provider = graph._StackedParentsProvider(
483
                [parents_provider, other_repository._make_parents_provider()])
3441.5.1 by Andrew Bennetts
Avoid necessarily calling get_parent_map when pushing.
484
        real_graph = graph.Graph(parents_provider)
485
        return RemoteGraph(real_graph, self)
2490.2.5 by Aaron Bentley
Use GraphWalker.unique_ancestor to determine merge base
486
2018.14.1 by Andrew Bennetts
Update to current hpss branch? Fix lots of test failures.
487
    def gather_stats(self, revid=None, committers=None):
2018.5.62 by Robert Collins
Stub out RemoteRepository.gather_stats while its implemented in parallel.
488
        """See Repository.gather_stats()."""
2018.10.3 by v.ladeuil+lp at free
more tests for gather_stats
489
        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.
490
        # revid can be None to indicate no revisions, not just NULL_REVISION
491
        if revid is None or revision.is_null(revid):
2018.10.3 by v.ladeuil+lp at free
more tests for gather_stats
492
            fmt_revid = ''
493
        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.
494
            fmt_revid = revid
2018.14.1 by Andrew Bennetts
Update to current hpss branch? Fix lots of test failures.
495
        if committers is None or not committers:
2018.10.3 by v.ladeuil+lp at free
more tests for gather_stats
496
            fmt_committers = 'no'
497
        else:
498
            fmt_committers = 'yes'
3245.4.58 by Andrew Bennetts
Unpack call_expecting_body's return value into variables, to avoid lots of ugly subscripting.
499
        response_tuple, response_handler = self._client.call_expecting_body(
2018.5.153 by Andrew Bennetts
Rename call2 to call_expecting_body, and other small changes prompted by review.
500
            '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.
501
        if response_tuple[0] != 'ok':
502
            raise errors.UnexpectedSmartServerResponse(response_tuple)
2018.10.3 by v.ladeuil+lp at free
more tests for gather_stats
503
3245.4.58 by Andrew Bennetts
Unpack call_expecting_body's return value into variables, to avoid lots of ugly subscripting.
504
        body = response_handler.read_body_bytes()
2018.10.3 by v.ladeuil+lp at free
more tests for gather_stats
505
        result = {}
506
        for line in body.split('\n'):
507
            if not line:
508
                continue
509
            key, val_text = line.split(':')
510
            if key in ('revisions', 'size', 'committers'):
511
                result[key] = int(val_text)
512
            elif key in ('firstrev', 'latestrev'):
513
                values = val_text.split(' ')[1:]
514
                result[key] = (float(values[0]), long(values[1]))
515
516
        return result
2018.5.62 by Robert Collins
Stub out RemoteRepository.gather_stats while its implemented in parallel.
517
3140.1.2 by Aaron Bentley
Add ability to find branches inside repositories
518
    def find_branches(self, using=False):
519
        """See Repository.find_branches()."""
520
        # should be an API call to the server.
521
        self._ensure_real()
522
        return self._real_repository.find_branches(using=using)
523
2018.5.60 by Robert Collins
More missing methods from RemoteBranch and RemoteRepository to let 'info' get further.
524
    def get_physical_lock_status(self):
525
        """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.
526
        # should be an API call to the server.
527
        self._ensure_real()
528
        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.
529
2617.6.1 by Robert Collins
* New method on Repository - ``start_write_group``, ``end_write_group``
530
    def is_in_write_group(self):
531
        """Return True if there is an open write group.
532
533
        write groups are only applicable locally for the smart server..
534
        """
535
        if self._real_repository:
536
            return self._real_repository.is_in_write_group()
537
538
    def is_locked(self):
539
        return self._lock_count >= 1
540
2018.5.57 by Robert Collins
Implement RemoteRepository.is_shared (Robert Collins, Vincent Ladeuil).
541
    def is_shared(self):
542
        """See Repository.is_shared()."""
543
        path = self.bzrdir._path_for_remote_call(self._client)
544
        response = self._client.call('Repository.is_shared', path)
3376.2.4 by Martin Pool
Remove every assert statement from bzrlib!
545
        if response[0] not in ('yes', 'no'):
546
            raise SmartProtocolError('unexpected response code %s' % (response,))
2018.5.57 by Robert Collins
Implement RemoteRepository.is_shared (Robert Collins, Vincent Ladeuil).
547
        return response[0] == 'yes'
548
2904.1.1 by Robert Collins
* New method ``bzrlib.repository.Repository.is_write_locked`` useful for
549
    def is_write_locked(self):
550
        return self._lock_mode == 'w'
551
2018.5.60 by Robert Collins
More missing methods from RemoteBranch and RemoteRepository to let 'info' get further.
552
    def lock_read(self):
553
        # wrong eventually - want a local lock cache context
2018.5.75 by Andrew Bennetts
Add Repository.{dont_,}leave_lock_in_place.
554
        if not self._lock_mode:
555
            self._lock_mode = 'r'
556
            self._lock_count = 1
3172.5.4 by Robert Collins
Implement get_parent_map for RemoteRepository with caching, based on get_revision_graph.
557
            self._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.
558
            if 'hpss' in debug.debug_flags:
559
                self._requested_parents = set()
2018.5.78 by Andrew Bennetts
Implement RemoteRepository.lock_write/unlock to expect and send tokens over the
560
            if self._real_repository is not None:
561
                self._real_repository.lock_read()
2018.5.75 by Andrew Bennetts
Add Repository.{dont_,}leave_lock_in_place.
562
        else:
563
            self._lock_count += 1
2018.5.78 by Andrew Bennetts
Implement RemoteRepository.lock_write/unlock to expect and send tokens over the
564
2018.14.1 by Andrew Bennetts
Update to current hpss branch? Fix lots of test failures.
565
    def _remote_lock_write(self, token):
2018.5.78 by Andrew Bennetts
Implement RemoteRepository.lock_write/unlock to expect and send tokens over the
566
        path = self.bzrdir._path_for_remote_call(self._client)
567
        if token is None:
568
            token = ''
3245.4.24 by Andrew Bennetts
Consistently raise errors from the server as ErrorFromSmartServer exceptions.
569
        try:
570
            response = self._client.call('Repository.lock_write', path, token)
571
        except errors.ErrorFromSmartServer, err:
3245.4.52 by Andrew Bennetts
Add 'error_verb' and 'error_args' attributes to ErrorFromSmartServer.
572
            if err.error_verb == 'LockContention':
3245.4.24 by Andrew Bennetts
Consistently raise errors from the server as ErrorFromSmartServer exceptions.
573
                raise errors.LockContention('(remote lock)')
3245.4.52 by Andrew Bennetts
Add 'error_verb' and 'error_args' attributes to ErrorFromSmartServer.
574
            elif err.error_verb == 'UnlockableTransport':
3245.4.24 by Andrew Bennetts
Consistently raise errors from the server as ErrorFromSmartServer exceptions.
575
                raise errors.UnlockableTransport(self.bzrdir.root_transport)
3245.4.52 by Andrew Bennetts
Add 'error_verb' and 'error_args' attributes to ErrorFromSmartServer.
576
            elif err.error_verb == 'LockFailed':
577
                raise errors.LockFailed(err.error_args[0], err.error_args[1])
3245.4.24 by Andrew Bennetts
Consistently raise errors from the server as ErrorFromSmartServer exceptions.
578
            raise
579
2018.5.78 by Andrew Bennetts
Implement RemoteRepository.lock_write/unlock to expect and send tokens over the
580
        if response[0] == 'ok':
581
            ok, token = response
582
            return token
583
        else:
2555.1.1 by Martin Pool
Remove use of 'assert False' to raise an exception unconditionally
584
            raise errors.UnexpectedSmartServerResponse(response)
2018.5.60 by Robert Collins
More missing methods from RemoteBranch and RemoteRepository to let 'info' get further.
585
2018.5.75 by Andrew Bennetts
Add Repository.{dont_,}leave_lock_in_place.
586
    def lock_write(self, token=None):
587
        if not self._lock_mode:
2018.14.1 by Andrew Bennetts
Update to current hpss branch? Fix lots of test failures.
588
            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.
589
            # if self._lock_token is None, then this is something like packs or
590
            # svn where we don't get to lock the repo, or a weave style repository
591
            # where we cannot lock it over the wire and attempts to do so will
592
            # fail.
2018.5.78 by Andrew Bennetts
Implement RemoteRepository.lock_write/unlock to expect and send tokens over the
593
            if self._real_repository is not None:
594
                self._real_repository.lock_write(token=self._lock_token)
595
            if token is not None:
596
                self._leave_lock = True
597
            else:
598
                self._leave_lock = False
2018.5.75 by Andrew Bennetts
Add Repository.{dont_,}leave_lock_in_place.
599
            self._lock_mode = 'w'
600
            self._lock_count = 1
3172.5.4 by Robert Collins
Implement get_parent_map for RemoteRepository with caching, based on get_revision_graph.
601
            self._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.
602
            if 'hpss' in debug.debug_flags:
603
                self._requested_parents = set()
2018.5.75 by Andrew Bennetts
Add Repository.{dont_,}leave_lock_in_place.
604
        elif self._lock_mode == 'r':
2018.14.1 by Andrew Bennetts
Update to current hpss branch? Fix lots of test failures.
605
            raise errors.ReadOnlyError(self)
2018.5.75 by Andrew Bennetts
Add Repository.{dont_,}leave_lock_in_place.
606
        else:
607
            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.
608
        return self._lock_token or None
2018.5.75 by Andrew Bennetts
Add Repository.{dont_,}leave_lock_in_place.
609
610
    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.
611
        if not self._lock_token:
612
            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
613
        self._leave_lock = True
2018.5.75 by Andrew Bennetts
Add Repository.{dont_,}leave_lock_in_place.
614
615
    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.
616
        if not self._lock_token:
3015.2.15 by Robert Collins
Review feedback.
617
            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
618
        self._leave_lock = False
2018.5.75 by Andrew Bennetts
Add Repository.{dont_,}leave_lock_in_place.
619
620
    def _set_real_repository(self, repository):
621
        """Set the _real_repository for this repository.
622
623
        :param repository: The repository to fallback to for non-hpss
624
            implemented operations.
625
        """
3376.2.4 by Martin Pool
Remove every assert statement from bzrlib!
626
        if isinstance(repository, RemoteRepository):
627
            raise AssertionError()
2018.5.75 by Andrew Bennetts
Add Repository.{dont_,}leave_lock_in_place.
628
        self._real_repository = repository
629
        if self._lock_mode == 'w':
630
            # if we are already locked, the real repository must be able to
631
            # acquire the lock with our token.
632
            self._real_repository.lock_write(self._lock_token)
2018.14.1 by Andrew Bennetts
Update to current hpss branch? Fix lots of test failures.
633
        elif self._lock_mode == 'r':
634
            self._real_repository.lock_read()
2018.5.60 by Robert Collins
More missing methods from RemoteBranch and RemoteRepository to let 'info' get further.
635
2617.6.1 by Robert Collins
* New method on Repository - ``start_write_group``, ``end_write_group``
636
    def start_write_group(self):
637
        """Start a write group on the decorated repository.
638
        
639
        Smart methods peform operations in a single step so this api
2617.6.6 by Robert Collins
Some review feedback.
640
        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``
641
        for older plugins that don't use e.g. the CommitBuilder
642
        facility.
643
        """
644
        self._ensure_real()
645
        return self._real_repository.start_write_group()
646
2018.5.78 by Andrew Bennetts
Implement RemoteRepository.lock_write/unlock to expect and send tokens over the
647
    def _unlock(self, token):
648
        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.
649
        if not token:
650
            # with no token the remote repository is not persistently locked.
651
            return
3245.4.24 by Andrew Bennetts
Consistently raise errors from the server as ErrorFromSmartServer exceptions.
652
        try:
653
            response = self._client.call('Repository.unlock', path, token)
654
        except errors.ErrorFromSmartServer, err:
3245.4.52 by Andrew Bennetts
Add 'error_verb' and 'error_args' attributes to ErrorFromSmartServer.
655
            if err.error_verb == 'TokenMismatch':
3245.4.24 by Andrew Bennetts
Consistently raise errors from the server as ErrorFromSmartServer exceptions.
656
                raise errors.TokenMismatch(token, '(remote token)')
657
            raise
2018.5.78 by Andrew Bennetts
Implement RemoteRepository.lock_write/unlock to expect and send tokens over the
658
        if response == ('ok',):
659
            return
660
        else:
2555.1.1 by Martin Pool
Remove use of 'assert False' to raise an exception unconditionally
661
            raise errors.UnexpectedSmartServerResponse(response)
2018.5.78 by Andrew Bennetts
Implement RemoteRepository.lock_write/unlock to expect and send tokens over the
662
2018.5.60 by Robert Collins
More missing methods from RemoteBranch and RemoteRepository to let 'info' get further.
663
    def unlock(self):
2018.5.75 by Andrew Bennetts
Add Repository.{dont_,}leave_lock_in_place.
664
        self._lock_count -= 1
2592.3.244 by Martin Pool
unlock while in a write group now aborts the write group, unlocks, and errors.
665
        if self._lock_count > 0:
666
            return
3172.5.4 by Robert Collins
Implement get_parent_map for RemoteRepository with caching, based on get_revision_graph.
667
        self._parents_map = None
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.
668
        if 'hpss' in debug.debug_flags:
669
            self._requested_parents = None
2592.3.244 by Martin Pool
unlock while in a write group now aborts the write group, unlocks, and errors.
670
        old_mode = self._lock_mode
671
        self._lock_mode = None
672
        try:
673
            # The real repository is responsible at present for raising an
674
            # exception if it's in an unfinished write group.  However, it
675
            # normally will *not* actually remove the lock from disk - that's
676
            # done by the server on receiving the Repository.unlock call.
677
            # 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
678
            if self._real_repository is not None:
679
                self._real_repository.unlock()
2592.3.244 by Martin Pool
unlock while in a write group now aborts the write group, unlocks, and errors.
680
        finally:
681
            # The rpc-level lock should be released even if there was a
682
            # problem releasing the vfs-based lock.
683
            if old_mode == 'w':
2018.5.163 by Andrew Bennetts
Deal with various review comments from Robert.
684
                # Only write-locked repositories need to make a remote method
685
                # 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.
686
                old_token = self._lock_token
687
                self._lock_token = None
688
                if not self._leave_lock:
689
                    self._unlock(old_token)
2018.5.60 by Robert Collins
More missing methods from RemoteBranch and RemoteRepository to let 'info' get further.
690
691
    def break_lock(self):
2018.5.78 by Andrew Bennetts
Implement RemoteRepository.lock_write/unlock to expect and send tokens over the
692
        # should hand off to the network
2018.5.70 by Robert Collins
Only try to get real repositories when an operation requires them.
693
        self._ensure_real()
2018.5.60 by Robert Collins
More missing methods from RemoteBranch and RemoteRepository to let 'info' get further.
694
        return self._real_repository.break_lock()
695
2018.18.8 by Ian Clatworthy
Tarball proxy code & tests
696
    def _get_tarball(self, compression):
2814.10.2 by Andrew Bennetts
Make the fallback a little tidier.
697
        """Return a TemporaryFile containing a repository tarball.
698
        
699
        Returns None if the server does not support sending tarballs.
700
        """
2018.18.25 by Martin Pool
Repository.tarball fixes for python2.4
701
        import tempfile
2018.18.8 by Ian Clatworthy
Tarball proxy code & tests
702
        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.
703
        try:
704
            response, protocol = self._client.call_expecting_body(
705
                'Repository.tarball', path, compression)
706
        except errors.UnknownSmartMethod:
707
            protocol.cancel_read_body()
708
            return None
2018.18.8 by Ian Clatworthy
Tarball proxy code & tests
709
        if response[0] == 'ok':
710
            # Extract the tarball and return it
2018.18.25 by Martin Pool
Repository.tarball fixes for python2.4
711
            t = tempfile.NamedTemporaryFile()
712
            # TODO: rpc layer should read directly into it...
713
            t.write(protocol.read_body_bytes())
714
            t.seek(0)
715
            return t
2814.10.1 by Andrew Bennetts
Cope gracefully if the server doesn't support the Repository.tarball smart request.
716
        raise errors.UnexpectedSmartServerResponse(response)
2018.18.8 by Ian Clatworthy
Tarball proxy code & tests
717
2440.1.1 by Martin Pool
Add new Repository.sprout,
718
    def sprout(self, to_bzrdir, revision_id=None):
719
        # 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.
720
        self._ensure_real()
3047.1.4 by Andrew Bennetts
Simplify RemoteRepository.sprout thanks to review comments.
721
        dest_repo = self._real_repository._format.initialize(to_bzrdir,
722
                                                             shared=False)
2535.3.17 by Andrew Bennetts
[broken] Closer to a working Repository.fetch_revisions smart request.
723
        dest_repo.fetch(self, revision_id=revision_id)
724
        return dest_repo
2440.1.1 by Martin Pool
Add new Repository.sprout,
725
2018.14.1 by Andrew Bennetts
Update to current hpss branch? Fix lots of test failures.
726
    ### These methods are just thin shims to the VFS object for now.
727
728
    def revision_tree(self, revision_id):
729
        self._ensure_real()
730
        return self._real_repository.revision_tree(revision_id)
731
2520.4.113 by Aaron Bentley
Avoid peeking at Repository._serializer
732
    def get_serializer_format(self):
733
        self._ensure_real()
734
        return self._real_repository.get_serializer_format()
735
2018.14.1 by Andrew Bennetts
Update to current hpss branch? Fix lots of test failures.
736
    def get_commit_builder(self, branch, parents, config, timestamp=None,
737
                           timezone=None, committer=None, revprops=None,
738
                           revision_id=None):
739
        # FIXME: It ought to be possible to call this without immediately
740
        # triggering _ensure_real.  For now it's the easiest thing to do.
741
        self._ensure_real()
742
        builder = self._real_repository.get_commit_builder(branch, parents,
743
                config, timestamp=timestamp, timezone=timezone,
744
                committer=committer, revprops=revprops, revision_id=revision_id)
745
        return builder
746
747
    def add_inventory(self, revid, inv, parents):
748
        self._ensure_real()
749
        return self._real_repository.add_inventory(revid, inv, parents)
750
751
    def add_revision(self, rev_id, rev, inv=None, config=None):
752
        self._ensure_real()
753
        return self._real_repository.add_revision(
754
            rev_id, rev, inv=inv, config=config)
755
756
    @needs_read_lock
757
    def get_inventory(self, revision_id):
758
        self._ensure_real()
759
        return self._real_repository.get_inventory(revision_id)
760
3169.2.1 by Robert Collins
New method ``iter_inventories`` on Repository for access to many
761
    def iter_inventories(self, revision_ids):
762
        self._ensure_real()
763
        return self._real_repository.iter_inventories(revision_ids)
764
2018.14.1 by Andrew Bennetts
Update to current hpss branch? Fix lots of test failures.
765
    @needs_read_lock
766
    def get_revision(self, revision_id):
767
        self._ensure_real()
768
        return self._real_repository.get_revision(revision_id)
769
770
    @property
771
    def weave_store(self):
772
        self._ensure_real()
773
        return self._real_repository.weave_store
774
775
    def get_transaction(self):
776
        self._ensure_real()
777
        return self._real_repository.get_transaction()
778
779
    @needs_read_lock
2018.5.138 by Robert Collins
Merge bzr.dev.
780
    def clone(self, a_bzrdir, revision_id=None):
2018.14.1 by Andrew Bennetts
Update to current hpss branch? Fix lots of test failures.
781
        self._ensure_real()
2018.5.138 by Robert Collins
Merge bzr.dev.
782
        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.
783
784
    def make_working_trees(self):
3349.1.1 by Aaron Bentley
Enable setting and getting make_working_trees for all repositories
785
        """See Repository.make_working_trees"""
786
        self._ensure_real()
787
        return self._real_repository.make_working_trees()
2018.14.1 by Andrew Bennetts
Update to current hpss branch? Fix lots of test failures.
788
3184.1.9 by Robert Collins
* ``Repository.get_data_stream`` is now deprecated in favour of
789
    def revision_ids_to_search_result(self, result_set):
790
        """Convert a set of revision ids to a graph SearchResult."""
791
        result_parents = set()
792
        for parents in self.get_graph().get_parent_map(
793
            result_set).itervalues():
794
            result_parents.update(parents)
795
        included_keys = result_set.intersection(result_parents)
796
        start_keys = result_set.difference(included_keys)
797
        exclude_keys = result_parents.difference(result_set)
798
        result = graph.SearchResult(start_keys, exclude_keys,
799
            len(result_set), result_set)
800
        return result
801
802
    @needs_read_lock
803
    def search_missing_revision_ids(self, other, revision_id=None, find_ghosts=True):
804
        """Return the revision ids that other has that this does not.
805
        
806
        These are returned in topological order.
807
808
        revision_id: only return revision ids included by revision_id.
809
        """
810
        return repository.InterRepository.get(
811
            other, self).search_missing_revision_ids(revision_id, find_ghosts)
812
2018.14.1 by Andrew Bennetts
Update to current hpss branch? Fix lots of test failures.
813
    def fetch(self, source, revision_id=None, pb=None):
2881.4.1 by Robert Collins
Move responsibility for detecting same-repo fetching from the
814
        if self.has_same_location(source):
815
            # check that last_revision is in 'from' and then return a
816
            # no-operation.
817
            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.
818
                not revision.is_null(revision_id)):
2881.4.1 by Robert Collins
Move responsibility for detecting same-repo fetching from the
819
                self.get_revision(revision_id)
2592.4.5 by Martin Pool
Add Repository.base on all repositories.
820
            return 0, []
2592.3.119 by Robert Collins
Merge some test fixes from Martin.
821
        self._ensure_real()
2018.14.1 by Andrew Bennetts
Update to current hpss branch? Fix lots of test failures.
822
        return self._real_repository.fetch(
823
            source, revision_id=revision_id, pb=pb)
824
2520.4.54 by Aaron Bentley
Hang a create_bundle method off repository
825
    def create_bundle(self, target, base, fileobj, format=None):
826
        self._ensure_real()
827
        self._real_repository.create_bundle(target, base, fileobj, format)
828
2018.14.1 by Andrew Bennetts
Update to current hpss branch? Fix lots of test failures.
829
    @property
830
    def control_weaves(self):
831
        self._ensure_real()
832
        return self._real_repository.control_weaves
833
834
    @needs_read_lock
2530.1.1 by Aaron Bentley
Make topological sorting optional for get_ancestry
835
    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.
836
        self._ensure_real()
2530.1.1 by Aaron Bentley
Make topological sorting optional for get_ancestry
837
        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.
838
839
    @needs_read_lock
840
    def get_inventory_weave(self):
841
        self._ensure_real()
842
        return self._real_repository.get_inventory_weave()
843
844
    def fileids_altered_by_revision_ids(self, revision_ids):
845
        self._ensure_real()
846
        return self._real_repository.fileids_altered_by_revision_ids(revision_ids)
847
3036.1.3 by Robert Collins
Privatise VersionedFileChecker.
848
    def _get_versioned_file_checker(self, revisions, revision_versions_cache):
2745.6.1 by Aaron Bentley
Initial checking of knit graphs
849
        self._ensure_real()
3036.1.3 by Robert Collins
Privatise VersionedFileChecker.
850
        return self._real_repository._get_versioned_file_checker(
2745.6.50 by Andrew Bennetts
Remove find_bad_ancestors; it's not needed anymore.
851
            revisions, revision_versions_cache)
852
        
2708.1.7 by Aaron Bentley
Rename extract_files_bytes to iter_files_bytes
853
    def iter_files_bytes(self, desired_files):
2708.1.9 by Aaron Bentley
Clean-up docs and imports
854
        """See Repository.iter_file_bytes.
2708.1.3 by Aaron Bentley
Implement extract_files_bytes on Repository
855
        """
856
        self._ensure_real()
2708.1.7 by Aaron Bentley
Rename extract_files_bytes to iter_files_bytes
857
        return self._real_repository.iter_files_bytes(desired_files)
2708.1.3 by Aaron Bentley
Implement extract_files_bytes on Repository
858
3172.5.4 by Robert Collins
Implement get_parent_map for RemoteRepository with caching, based on get_revision_graph.
859
    def get_parent_map(self, keys):
860
        """See bzrlib.Graph.get_parent_map()."""
861
        # Hack to build up the caching logic.
862
        ancestry = self._parents_map
3213.1.2 by Andrew Bennetts
Add test for reconnection if get_parent_map is unknown by the server.
863
        if ancestry is None:
864
            # Repository is not locked, so there's no cache.
865
            missing_revisions = set(keys)
866
            ancestry = {}
867
        else:
868
            missing_revisions = set(key for key in keys if key not in ancestry)
3172.5.4 by Robert Collins
Implement get_parent_map for RemoteRepository with caching, based on get_revision_graph.
869
        if missing_revisions:
3192.1.1 by Andrew Bennetts
Add some -Dhpss debugging to get_parent_map.
870
            parent_map = self._get_parent_map(missing_revisions)
871
            if 'hpss' in debug.debug_flags:
872
                mutter('retransmitted revisions: %d of %d',
3213.1.2 by Andrew Bennetts
Add test for reconnection if get_parent_map is unknown by the server.
873
                        len(set(ancestry).intersection(parent_map)),
3192.1.1 by Andrew Bennetts
Add some -Dhpss debugging to get_parent_map.
874
                        len(parent_map))
3213.1.2 by Andrew Bennetts
Add test for reconnection if get_parent_map is unknown by the server.
875
            ancestry.update(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.
876
        present_keys = [k for k in keys if k in ancestry]
3441.5.2 by Andrew Bennetts
Remove various debugging cruft.
877
        if 'hpss' in debug.debug_flags:
3245.4.24 by Andrew Bennetts
Consistently raise errors from the server as ErrorFromSmartServer exceptions.
878
            if self._requested_parents is not None and len(ancestry) != 0:
879
                self._requested_parents.update(present_keys)
880
                mutter('Current RemoteRepository graph hit rate: %d%%',
881
                    100.0 * len(self._requested_parents) / len(ancestry))
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.
882
        return dict((k, ancestry[k]) for k in present_keys)
3172.5.4 by Robert Collins
Implement get_parent_map for RemoteRepository with caching, based on get_revision_graph.
883
3172.5.6 by Robert Collins
Create new smart server verb Repository.get_parent_map.
884
    def _get_parent_map(self, keys):
885
        """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.
886
        medium = self._client._medium
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.
887
        if not medium._remote_is_at_least_1_2:
888
            # We already found out that the server can't understand
3213.1.3 by Andrew Bennetts
Fix typo in comment.
889
            # 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.
890
            # graph.
3287.6.1 by Robert Collins
* ``VersionedFile.get_graph`` is deprecated, with no replacement method.
891
            # XXX: Note that this will issue a deprecation warning. This is ok
892
            # :- its because we're working with a deprecated server anyway, and
893
            # the user will almost certainly have seen a warning about the
894
            # server version already.
3389.1.1 by John Arbash Meinel
Fix bug #214894. Fix RemoteRepository.get_parent_map() when server is <v1.2
895
            rg = self.get_revision_graph()
896
            # There is an api discrepency between get_parent_map and
897
            # get_revision_graph. Specifically, a "key:()" pair in
898
            # get_revision_graph just means a node has no parents. For
899
            # "get_parent_map" it means the node is a ghost. So fix up the
900
            # graph to correct this.
901
            #   https://bugs.launchpad.net/bzr/+bug/214894
902
            # There is one other "bug" which is that ghosts in
903
            # get_revision_graph() are not returned at all. But we won't worry
904
            # about that for now.
905
            for node_id, parent_ids in rg.iteritems():
906
                if parent_ids == ():
907
                    rg[node_id] = (NULL_REVISION,)
908
            rg[NULL_REVISION] = ()
909
            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.
910
3172.5.6 by Robert Collins
Create new smart server verb Repository.get_parent_map.
911
        keys = set(keys)
3373.5.2 by John Arbash Meinel
Add repository_implementation tests for get_parent_map
912
        if None in keys:
913
            raise ValueError('get_parent_map(None) is not valid')
3172.5.6 by Robert Collins
Create new smart server verb Repository.get_parent_map.
914
        if NULL_REVISION in keys:
915
            keys.discard(NULL_REVISION)
916
            found_parents = {NULL_REVISION:()}
917
            if not keys:
918
                return found_parents
919
        else:
920
            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.
921
        # TODO(Needs analysis): We could assume that the keys being requested
922
        # from get_parent_map are in a breadth first search, so typically they
923
        # will all be depth N from some common parent, and we don't have to
924
        # have the server iterate from the root parent, but rather from the
925
        # keys we're searching; and just tell the server the keyspace we
926
        # already have; but this may be more traffic again.
927
928
        # Transform self._parents_map into a search request recipe.
929
        # TODO: Manage this incrementally to avoid covering the same path
930
        # repeatedly. (The server will have to on each request, but the less
931
        # work done the better).
3213.1.8 by Andrew Bennetts
Merge from bzr.dev.
932
        parents_map = self._parents_map
933
        if parents_map is None:
934
            # Repository is not locked, so there's no cache.
935
            parents_map = {}
936
        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.
937
        result_parents = set()
3213.1.8 by Andrew Bennetts
Merge from bzr.dev.
938
        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.
939
            result_parents.update(parents)
940
        stop_keys = result_parents.difference(start_set)
941
        included_keys = start_set.intersection(result_parents)
942
        start_set.difference_update(included_keys)
3213.1.8 by Andrew Bennetts
Merge from bzr.dev.
943
        recipe = (start_set, stop_keys, len(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.
944
        body = self._serialise_search_recipe(recipe)
3172.5.6 by Robert Collins
Create new smart server verb Repository.get_parent_map.
945
        path = self.bzrdir._path_for_remote_call(self._client)
946
        for key in keys:
3360.2.8 by Martin Pool
Change assertion to a plain raise
947
            if type(key) is not str:
948
                raise ValueError(
949
                    "key %r not a plain string" % (key,))
3172.5.8 by Robert Collins
Review feedback.
950
        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.
951
        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.
952
        try:
953
            response = self._client.call_with_body_bytes_expecting_body(
954
                verb, args, self._serialise_search_recipe(recipe))
955
        except errors.UnknownSmartMethod:
3213.1.2 by Andrew Bennetts
Add test for reconnection if get_parent_map is unknown by the server.
956
            # 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.
957
            # Worse, we have to force a disconnection, because the server now
958
            # doesn't realise it has a body on the wire to consume, so the
959
            # only way to recover is to abandon the connection.
3213.1.6 by Andrew Bennetts
Emit warnings when forcing a reconnect.
960
            warning(
961
                'Server is too old for fast get_parent_map, reconnecting.  '
962
                '(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.
963
            medium.disconnect()
964
            # To avoid having to disconnect repeatedly, we keep track of the
965
            # fact the server doesn't understand remote methods added in 1.2.
966
            medium._remote_is_at_least_1_2 = False
3297.3.4 by Andrew Bennetts
Merge from bzr.dev.
967
            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.
968
        response_tuple, response_handler = response
969
        if response_tuple[0] not in ['ok']:
970
            response_handler.cancel_read_body()
971
            raise errors.UnexpectedSmartServerResponse(response_tuple)
972
        if response_tuple[0] == 'ok':
973
            coded = bz2.decompress(response_handler.read_body_bytes())
3172.5.6 by Robert Collins
Create new smart server verb Repository.get_parent_map.
974
            if coded == '':
975
                # no revisions found
976
                return {}
977
            lines = coded.split('\n')
978
            revision_graph = {}
979
            for line in lines:
980
                d = tuple(line.split())
981
                if len(d) > 1:
982
                    revision_graph[d[0]] = d[1:]
983
                else:
984
                    # No parents - so give the Graph result (NULL_REVISION,).
985
                    revision_graph[d[0]] = (NULL_REVISION,)
986
            return revision_graph
987
2018.14.1 by Andrew Bennetts
Update to current hpss branch? Fix lots of test failures.
988
    @needs_read_lock
989
    def get_signature_text(self, revision_id):
990
        self._ensure_real()
991
        return self._real_repository.get_signature_text(revision_id)
992
993
    @needs_read_lock
3228.4.11 by John Arbash Meinel
Deprecations abound.
994
    @symbol_versioning.deprecated_method(symbol_versioning.one_three)
2018.14.1 by Andrew Bennetts
Update to current hpss branch? Fix lots of test failures.
995
    def get_revision_graph_with_ghosts(self, revision_ids=None):
996
        self._ensure_real()
997
        return self._real_repository.get_revision_graph_with_ghosts(
998
            revision_ids=revision_ids)
999
1000
    @needs_read_lock
1001
    def get_inventory_xml(self, revision_id):
1002
        self._ensure_real()
1003
        return self._real_repository.get_inventory_xml(revision_id)
1004
1005
    def deserialise_inventory(self, revision_id, xml):
1006
        self._ensure_real()
1007
        return self._real_repository.deserialise_inventory(revision_id, xml)
1008
1009
    def reconcile(self, other=None, thorough=False):
1010
        self._ensure_real()
1011
        return self._real_repository.reconcile(other=other, thorough=thorough)
1012
        
1013
    def all_revision_ids(self):
1014
        self._ensure_real()
1015
        return self._real_repository.all_revision_ids()
1016
    
1017
    @needs_read_lock
1018
    def get_deltas_for_revisions(self, revisions):
1019
        self._ensure_real()
1020
        return self._real_repository.get_deltas_for_revisions(revisions)
1021
1022
    @needs_read_lock
1023
    def get_revision_delta(self, revision_id):
1024
        self._ensure_real()
1025
        return self._real_repository.get_revision_delta(revision_id)
1026
1027
    @needs_read_lock
1028
    def revision_trees(self, revision_ids):
1029
        self._ensure_real()
1030
        return self._real_repository.revision_trees(revision_ids)
1031
1032
    @needs_read_lock
1033
    def get_revision_reconcile(self, revision_id):
1034
        self._ensure_real()
1035
        return self._real_repository.get_revision_reconcile(revision_id)
1036
1037
    @needs_read_lock
2745.6.36 by Andrew Bennetts
Deprecate revision_ids arg to Repository.check and other tweaks.
1038
    def check(self, revision_ids=None):
2018.14.1 by Andrew Bennetts
Update to current hpss branch? Fix lots of test failures.
1039
        self._ensure_real()
2745.6.36 by Andrew Bennetts
Deprecate revision_ids arg to Repository.check and other tweaks.
1040
        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.
1041
2018.5.138 by Robert Collins
Merge bzr.dev.
1042
    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.
1043
        self._ensure_real()
1044
        return self._real_repository.copy_content_into(
2018.5.138 by Robert Collins
Merge bzr.dev.
1045
            destination, revision_id=revision_id)
2018.14.1 by Andrew Bennetts
Update to current hpss branch? Fix lots of test failures.
1046
2814.10.2 by Andrew Bennetts
Make the fallback a little tidier.
1047
    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.
1048
        # get a tarball of the remote repository, and copy from that into the
1049
        # destination
1050
        from bzrlib import osutils
2018.18.9 by Martin Pool
remote Repository.tarball builds a temporary directory and tars that
1051
        import tarfile
2018.18.10 by Martin Pool
copy_content_into from Remote repositories by using temporary directories on both ends.
1052
        import tempfile
2018.18.20 by Martin Pool
Route branch operations through remote copy_content_into
1053
        # TODO: Maybe a progress bar while streaming the tarball?
1054
        note("Copying repository content as tarball...")
2018.18.25 by Martin Pool
Repository.tarball fixes for python2.4
1055
        tar_file = self._get_tarball('bz2')
2814.10.2 by Andrew Bennetts
Make the fallback a little tidier.
1056
        if tar_file is None:
1057
            return None
1058
        destination = to_bzrdir.create_repository()
2018.18.10 by Martin Pool
copy_content_into from Remote repositories by using temporary directories on both ends.
1059
        try:
2018.18.25 by Martin Pool
Repository.tarball fixes for python2.4
1060
            tar = tarfile.open('repository', fileobj=tar_file,
1061
                mode='r|bz2')
1062
            tmpdir = tempfile.mkdtemp()
1063
            try:
1064
                _extract_tar(tar, tmpdir)
1065
                tmp_bzrdir = BzrDir.open(tmpdir)
1066
                tmp_repo = tmp_bzrdir.open_repository()
1067
                tmp_repo.copy_content_into(destination, revision_id)
1068
            finally:
1069
                osutils.rmtree(tmpdir)
2018.18.10 by Martin Pool
copy_content_into from Remote repositories by using temporary directories on both ends.
1070
        finally:
2018.18.25 by Martin Pool
Repository.tarball fixes for python2.4
1071
            tar_file.close()
2814.10.2 by Andrew Bennetts
Make the fallback a little tidier.
1072
        return destination
2018.18.23 by Martin Pool
review cleanups
1073
        # TODO: Suggestion from john: using external tar is much faster than
1074
        # 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.
1075
2604.2.1 by Robert Collins
(robertc) Introduce a pack command.
1076
    @needs_write_lock
1077
    def pack(self):
1078
        """Compress the data within the repository.
1079
1080
        This is not currently implemented within the smart server.
1081
        """
1082
        self._ensure_real()
1083
        return self._real_repository.pack()
1084
2018.14.1 by Andrew Bennetts
Update to current hpss branch? Fix lots of test failures.
1085
    def set_make_working_trees(self, new_value):
3349.1.1 by Aaron Bentley
Enable setting and getting make_working_trees for all repositories
1086
        self._ensure_real()
1087
        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.
1088
1089
    @needs_write_lock
1090
    def sign_revision(self, revision_id, gpg_strategy):
1091
        self._ensure_real()
1092
        return self._real_repository.sign_revision(revision_id, gpg_strategy)
1093
1094
    @needs_read_lock
1095
    def get_revisions(self, revision_ids):
1096
        self._ensure_real()
1097
        return self._real_repository.get_revisions(revision_ids)
1098
1099
    def supports_rich_root(self):
2018.5.84 by Andrew Bennetts
Merge in supports-rich-root, another test passing.
1100
        self._ensure_real()
1101
        return self._real_repository.supports_rich_root()
2018.14.1 by Andrew Bennetts
Update to current hpss branch? Fix lots of test failures.
1102
2018.5.83 by Andrew Bennetts
Fix some test failures caused by the switch from unicode to UTF-8-encoded strs for revision IDs.
1103
    def iter_reverse_revision_history(self, revision_id):
1104
        self._ensure_real()
1105
        return self._real_repository.iter_reverse_revision_history(revision_id)
1106
2018.5.96 by Andrew Bennetts
Merge from bzr.dev, resolving the worst of the semantic conflicts, but there's
1107
    @property
1108
    def _serializer(self):
1109
        self._ensure_real()
1110
        return self._real_repository._serializer
1111
2018.5.97 by Andrew Bennetts
Fix more tests.
1112
    def store_revision_signature(self, gpg_strategy, plaintext, revision_id):
1113
        self._ensure_real()
1114
        return self._real_repository.store_revision_signature(
1115
            gpg_strategy, plaintext, revision_id)
1116
2996.2.8 by Aaron Bentley
Fix add_signature discrepancies
1117
    def add_signature_text(self, revision_id, signature):
2996.2.3 by Aaron Bentley
Add tests for install_revisions and add_signature
1118
        self._ensure_real()
2996.2.8 by Aaron Bentley
Fix add_signature discrepancies
1119
        return self._real_repository.add_signature_text(revision_id, signature)
2996.2.3 by Aaron Bentley
Add tests for install_revisions and add_signature
1120
2018.5.97 by Andrew Bennetts
Fix more tests.
1121
    def has_signature_for_revision_id(self, revision_id):
1122
        self._ensure_real()
1123
        return self._real_repository.has_signature_for_revision_id(revision_id)
1124
3184.1.9 by Robert Collins
* ``Repository.get_data_stream`` is now deprecated in favour of
1125
    def get_data_stream_for_search(self, search):
3313.2.1 by Andrew Bennetts
Change _SmartClient's API to accept a medium and a base, rather than a _SharedConnection.
1126
        medium = self._client._medium
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.
1127
        if not medium._remote_is_at_least_1_2:
1128
            self._ensure_real()
1129
            return self._real_repository.get_data_stream_for_search(search)
2535.4.29 by Andrew Bennetts
Add a new smart method, Repository.stream_revisions_chunked, rather than changing the behaviour of an existing method.
1130
        REQUEST_NAME = 'Repository.stream_revisions_chunked'
2535.3.15 by Andrew Bennetts
Add KnitVersionedFile.get_stream_as_bytes, start smart implementation of RemoteRepository.get_data_stream.
1131
        path = self.bzrdir._path_for_remote_call(self._client)
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.
1132
        body = self._serialise_search_recipe(search.get_recipe())
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.
1133
        try:
1134
            result = self._client.call_with_body_bytes_expecting_body(
1135
                REQUEST_NAME, (path,), body)
1136
            response, protocol = result
1137
        except errors.UnknownSmartMethod:
3213.1.2 by Andrew Bennetts
Add test for reconnection if get_parent_map is unknown by the server.
1138
            # Server does not support this method, so fall back to VFS.
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.
1139
            # Worse, we have to force a disconnection, because the server now
1140
            # doesn't realise it has a body on the wire to consume, so the
1141
            # only way to recover is to abandon the connection.
3213.1.6 by Andrew Bennetts
Emit warnings when forcing a reconnect.
1142
            warning(
1143
                'Server is too old for streaming pull, reconnecting.  '
1144
                '(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.
1145
            medium.disconnect()
1146
            # To avoid having to disconnect repeatedly, we keep track of the
1147
            # fact the server doesn't understand this remote method.
1148
            medium._remote_is_at_least_1_2 = False
1149
            self._ensure_real()
1150
            return self._real_repository.get_data_stream_for_search(search)
1151
2535.3.39 by Andrew Bennetts
Tidy some XXXs.
1152
        if response == ('ok',):
2535.3.68 by Andrew Bennetts
Backwards compatibility for new smart method.
1153
            return self._deserialise_stream(protocol)
3184.1.10 by Robert Collins
Change the smart server verb for Repository.stream_revisions_chunked to use SearchResults as the request mechanism for downloads.
1154
        if response == ('NoSuchRevision', ):
1155
            # We cannot easily identify the revision that is missing in this
1156
            # situation without doing much more network IO. For now, bail.
1157
            raise NoSuchRevision(self, "unknown")
2535.3.15 by Andrew Bennetts
Add KnitVersionedFile.get_stream_as_bytes, start smart implementation of RemoteRepository.get_data_stream.
1158
        else:
2535.3.17 by Andrew Bennetts
[broken] Closer to a working Repository.fetch_revisions smart request.
1159
            raise errors.UnexpectedSmartServerResponse(response)
2535.3.15 by Andrew Bennetts
Add KnitVersionedFile.get_stream_as_bytes, start smart implementation of RemoteRepository.get_data_stream.
1160
2535.3.68 by Andrew Bennetts
Backwards compatibility for new smart method.
1161
    def _deserialise_stream(self, protocol):
2535.4.11 by Andrew Bennetts
Merge from repo-refactor.
1162
        stream = protocol.read_streamed_body()
2535.4.15 by Andrew Bennetts
Remove 'PackSource' hack by using the ContainerPushParser.
1163
        container_parser = ContainerPushParser()
1164
        for bytes in stream:
1165
            container_parser.accept_bytes(bytes)
1166
            records = container_parser.read_pending_records()
1167
            for record_names, record_bytes in records:
2535.4.31 by Andrew Bennetts
Tweak in response to review comments.
1168
                if len(record_names) != 1:
2535.4.15 by Andrew Bennetts
Remove 'PackSource' hack by using the ContainerPushParser.
1169
                    # These records should have only one name, and that name
1170
                    # should be a one-element tuple.
1171
                    raise errors.SmartProtocolError(
1172
                        'Repository data stream had invalid record name %r'
1173
                        % (record_names,))
2535.4.31 by Andrew Bennetts
Tweak in response to review comments.
1174
                name_tuple = record_names[0]
2535.4.15 by Andrew Bennetts
Remove 'PackSource' hack by using the ContainerPushParser.
1175
                yield name_tuple, record_bytes
2535.3.68 by Andrew Bennetts
Backwards compatibility for new smart method.
1176
2535.3.17 by Andrew Bennetts
[broken] Closer to a working Repository.fetch_revisions smart request.
1177
    def insert_data_stream(self, stream):
1178
        self._ensure_real()
1179
        self._real_repository.insert_data_stream(stream)
2535.3.12 by Andrew Bennetts
Add a first cut of a get_data_stream method to Repository.
1180
2535.3.45 by Andrew Bennetts
Add item_keys_introduced_by to RemoteRepository.
1181
    def item_keys_introduced_by(self, revision_ids, _files_pb=None):
1182
        self._ensure_real()
1183
        return self._real_repository.item_keys_introduced_by(revision_ids,
1184
            _files_pb=_files_pb)
1185
2819.2.4 by Andrew Bennetts
Add a 'revision_graph_can_have_wrong_parents' method to repository.
1186
    def revision_graph_can_have_wrong_parents(self):
1187
        # The answer depends on the remote repo format.
1188
        self._ensure_real()
1189
        return self._real_repository.revision_graph_can_have_wrong_parents()
1190
2819.2.5 by Andrew Bennetts
Make reconcile abort gracefully if the revision index has bad parents.
1191
    def _find_inconsistent_revision_parents(self):
1192
        self._ensure_real()
1193
        return self._real_repository._find_inconsistent_revision_parents()
1194
1195
    def _check_for_inconsistent_revision_parents(self):
1196
        self._ensure_real()
1197
        return self._real_repository._check_for_inconsistent_revision_parents()
1198
3089.2.1 by Andrew Bennetts
Implement RemoteRepository._make_parents_provider.
1199
    def _make_parents_provider(self):
3172.5.1 by Robert Collins
Create a RemoteRepository get_graph implementation and delegate get_parents_map to the real repository.
1200
        return self
1201
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.
1202
    def _serialise_search_recipe(self, recipe):
1203
        """Serialise a graph search recipe.
1204
1205
        :param recipe: A search recipe (start, stop, count).
1206
        :return: Serialised bytes.
1207
        """
1208
        start_keys = ' '.join(recipe[0])
1209
        stop_keys = ' '.join(recipe[1])
1210
        count = str(recipe[2])
1211
        return '\n'.join((start_keys, stop_keys, count))
1212
1752.2.31 by Martin Pool
[broken] some support for write operations over hpss
1213
2018.5.127 by Andrew Bennetts
Fix most of the lockable_files tests for RemoteBranchLockableFiles.
1214
class RemoteBranchLockableFiles(LockableFiles):
2018.5.59 by Robert Collins
Get BranchConfig working somewhat on RemoteBranches (Robert Collins, Vincent Ladeuil).
1215
    """A 'LockableFiles' implementation that talks to a smart server.
1216
    
1217
    This is not a public interface class.
1218
    """
1219
1220
    def __init__(self, bzrdir, _client):
1221
        self.bzrdir = bzrdir
1222
        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.
1223
        self._need_find_modes = True
2018.5.133 by Andrew Bennetts
All TestLockableFiles_RemoteLockDir tests passing.
1224
        LockableFiles.__init__(
2018.5.163 by Andrew Bennetts
Deal with various review comments from Robert.
1225
            self, bzrdir.get_branch_transport(None),
2018.5.133 by Andrew Bennetts
All TestLockableFiles_RemoteLockDir tests passing.
1226
            'lock', lockdir.LockDir)
2018.5.59 by Robert Collins
Get BranchConfig working somewhat on RemoteBranches (Robert Collins, Vincent Ladeuil).
1227
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.
1228
    def _find_modes(self):
1229
        # RemoteBranches don't let the client set the mode of control files.
1230
        self._dir_mode = None
1231
        self._file_mode = None
1232
2018.5.59 by Robert Collins
Get BranchConfig working somewhat on RemoteBranches (Robert Collins, Vincent Ladeuil).
1233
1752.2.31 by Martin Pool
[broken] some support for write operations over hpss
1234
class RemoteBranchFormat(branch.BranchFormat):
1235
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.
1236
    def __eq__(self, other):
1237
        return (isinstance(other, RemoteBranchFormat) and 
1238
            self.__dict__ == other.__dict__)
1239
2018.5.60 by Robert Collins
More missing methods from RemoteBranch and RemoteRepository to let 'info' get further.
1240
    def get_format_description(self):
1241
        return 'Remote BZR Branch'
1242
2018.14.1 by Andrew Bennetts
Update to current hpss branch? Fix lots of test failures.
1243
    def get_format_string(self):
1244
        return 'Remote BZR Branch'
1245
1752.2.31 by Martin Pool
[broken] some support for write operations over hpss
1246
    def open(self, a_bzrdir):
1752.2.72 by Andrew Bennetts
Make Remote* classes in remote.py more consistent and remove some dead code.
1247
        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.
1248
1249
    def initialize(self, a_bzrdir):
1250
        return a_bzrdir.create_branch()
1752.2.31 by Martin Pool
[broken] some support for write operations over hpss
1251
2696.3.6 by Martin Pool
Mark RemoteBranch as (possibly) supporting tags
1252
    def supports_tags(self):
1253
        # Remote branches might support tags, but we won't know until we
1254
        # access the real remote branch.
1255
        return True
1256
1752.2.31 by Martin Pool
[broken] some support for write operations over hpss
1257
1258
class RemoteBranch(branch.Branch):
1259
    """Branch stored on a server accessed by HPSS RPC.
1260
1261
    At the moment most operations are mapped down to simple file operations.
1262
    """
1752.2.30 by Martin Pool
Start adding a RemoteBzrDir, etc
1263
2018.5.51 by Wouter van Heyst
Test and implement RemoteBranch.last_revision_info()
1264
    def __init__(self, remote_bzrdir, remote_repository, real_branch=None,
1265
        _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.
1266
        """Create a RemoteBranch instance.
1267
1268
        :param real_branch: An optional local implementation of the branch
1269
            format, usually accessing the data via the VFS.
2018.5.51 by Wouter van Heyst
Test and implement RemoteBranch.last_revision_info()
1270
        :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.
1271
        """
2018.5.163 by Andrew Bennetts
Deal with various review comments from Robert.
1272
        # We intentionally don't call the parent class's __init__, because it
1273
        # will try to assign to self.tags, which is a property in this subclass.
1274
        # 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.
1275
        self._revision_id_to_revno_cache = None
2018.5.105 by Andrew Bennetts
Implement revision_history caching for RemoteBranch.
1276
        self._revision_history_cache = None
3441.5.1 by Andrew Bennetts
Avoid necessarily calling get_parent_map when pushing.
1277
        self._last_revision_info_cache = None
1752.2.64 by Andrew Bennetts
Improve how RemoteBzrDir.open_branch works to handle references and not double-open repositories.
1278
        self.bzrdir = remote_bzrdir
2018.5.51 by Wouter van Heyst
Test and implement RemoteBranch.last_revision_info()
1279
        if _client is not None:
1280
            self._client = _client
1281
        else:
3313.2.1 by Andrew Bennetts
Change _SmartClient's API to accept a medium and a base, rather than a _SharedConnection.
1282
            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.
1283
        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.
1284
        if real_branch is not None:
1285
            self._real_branch = real_branch
2018.5.79 by Andrew Bennetts
Implement RemoteBranch.lock_write/unlock as smart operations.
1286
            # Give the remote repository the matching real repo.
2018.5.97 by Andrew Bennetts
Fix more tests.
1287
            real_repo = self._real_branch.repository
1288
            if isinstance(real_repo, RemoteRepository):
1289
                real_repo._ensure_real()
1290
                real_repo = real_repo._real_repository
1291
            self.repository._set_real_repository(real_repo)
2018.5.79 by Andrew Bennetts
Implement RemoteBranch.lock_write/unlock as smart operations.
1292
            # Give the branch the remote repository to let fast-pathing happen.
1293
            self._real_branch.repository = self.repository
2018.5.70 by Robert Collins
Only try to get real repositories when an operation requires them.
1294
        else:
1295
            self._real_branch = None
2018.5.59 by Robert Collins
Get BranchConfig working somewhat on RemoteBranches (Robert Collins, Vincent Ladeuil).
1296
        # 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.
1297
        self._format = RemoteBranchFormat()
2018.5.55 by Robert Collins
Give RemoteBranch a base url in line with the Branch protocol.
1298
        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.
1299
        self._control_files = None
2018.5.79 by Andrew Bennetts
Implement RemoteBranch.lock_write/unlock as smart operations.
1300
        self._lock_mode = None
1301
        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.
1302
        self._repo_lock_token = None
2018.5.79 by Andrew Bennetts
Implement RemoteBranch.lock_write/unlock as smart operations.
1303
        self._lock_count = 0
1304
        self._leave_lock = False
1752.2.64 by Andrew Bennetts
Improve how RemoteBzrDir.open_branch works to handle references and not double-open repositories.
1305
2477.1.1 by Martin Pool
Add RemoteBranch repr
1306
    def __str__(self):
1307
        return "%s(%s)" % (self.__class__.__name__, self.base)
1308
1309
    __repr__ = __str__
1310
2018.5.70 by Robert Collins
Only try to get real repositories when an operation requires them.
1311
    def _ensure_real(self):
1312
        """Ensure that there is a _real_branch set.
1313
2018.5.163 by Andrew Bennetts
Deal with various review comments from Robert.
1314
        Used before calls to self._real_branch.
2018.5.70 by Robert Collins
Only try to get real repositories when an operation requires them.
1315
        """
1316
        if not self._real_branch:
3376.2.4 by Martin Pool
Remove every assert statement from bzrlib!
1317
            if not vfs.vfs_enabled():
1318
                raise AssertionError('smart server vfs must be enabled '
1319
                    'to use vfs implementation')
2018.5.70 by Robert Collins
Only try to get real repositories when an operation requires them.
1320
            self.bzrdir._ensure_real()
1321
            self._real_branch = self.bzrdir._real_bzrdir.open_branch()
2018.5.75 by Andrew Bennetts
Add Repository.{dont_,}leave_lock_in_place.
1322
            # Give the remote repository the matching real repo.
2018.5.97 by Andrew Bennetts
Fix more tests.
1323
            real_repo = self._real_branch.repository
1324
            if isinstance(real_repo, RemoteRepository):
1325
                real_repo._ensure_real()
1326
                real_repo = real_repo._real_repository
1327
            self.repository._set_real_repository(real_repo)
2018.5.75 by Andrew Bennetts
Add Repository.{dont_,}leave_lock_in_place.
1328
            # Give the branch the remote repository to let fast-pathing happen.
2018.5.70 by Robert Collins
Only try to get real repositories when an operation requires them.
1329
            self._real_branch.repository = self.repository
2018.14.1 by Andrew Bennetts
Update to current hpss branch? Fix lots of test failures.
1330
            # XXX: deal with _lock_mode == 'w'
1331
            if self._lock_mode == 'r':
1332
                self._real_branch.lock_read()
2018.5.70 by Robert Collins
Only try to get real repositories when an operation requires them.
1333
3441.5.1 by Andrew Bennetts
Avoid necessarily calling get_parent_map when pushing.
1334
    def _clear_cached_state(self):
1335
        super(RemoteBranch, self)._clear_cached_state()
1336
        self._last_revision_info_cache = None
3441.5.5 by Andrew Bennetts
Some small tweaks and comments.
1337
        if self._real_branch is not None:
1338
            self._real_branch._clear_cached_state()
3441.5.1 by Andrew Bennetts
Avoid necessarily calling get_parent_map when pushing.
1339
        
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.
1340
    @property
1341
    def control_files(self):
1342
        # Defer actually creating RemoteBranchLockableFiles until its needed,
1343
        # because it triggers an _ensure_real that we otherwise might not need.
1344
        if self._control_files is None:
1345
            self._control_files = RemoteBranchLockableFiles(
1346
                self.bzrdir, self._client)
1347
        return self._control_files
1348
2018.5.166 by Andrew Bennetts
Small changes in response to Aaron's review.
1349
    def _get_checkout_format(self):
1350
        self._ensure_real()
1351
        return self._real_branch._get_checkout_format()
1352
2018.5.60 by Robert Collins
More missing methods from RemoteBranch and RemoteRepository to let 'info' get further.
1353
    def get_physical_lock_status(self):
1354
        """See Branch.get_physical_lock_status()."""
1355
        # 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.
1356
        self._ensure_real()
2018.5.60 by Robert Collins
More missing methods from RemoteBranch and RemoteRepository to let 'info' get further.
1357
        return self._real_branch.get_physical_lock_status()
1358
1752.2.31 by Martin Pool
[broken] some support for write operations over hpss
1359
    def lock_read(self):
2018.14.1 by Andrew Bennetts
Update to current hpss branch? Fix lots of test failures.
1360
        if not self._lock_mode:
1361
            self._lock_mode = 'r'
1362
            self._lock_count = 1
1363
            if self._real_branch is not None:
1364
                self._real_branch.lock_read()
1365
        else:
1366
            self._lock_count += 1
1752.2.52 by Andrew Bennetts
Flesh out more Remote* methods needed to open and initialise remote branches/trees/repositories.
1367
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).
1368
    def _remote_lock_write(self, token):
1369
        if token is None:
2018.5.79 by Andrew Bennetts
Implement RemoteBranch.lock_write/unlock as smart operations.
1370
            branch_token = repo_token = ''
1371
        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).
1372
            branch_token = token
1373
            repo_token = self.repository.lock_write()
1374
            self.repository.unlock()
2018.5.79 by Andrew Bennetts
Implement RemoteBranch.lock_write/unlock as smart operations.
1375
        path = self.bzrdir._path_for_remote_call(self._client)
3245.4.24 by Andrew Bennetts
Consistently raise errors from the server as ErrorFromSmartServer exceptions.
1376
        try:
1377
            response = self._client.call(
1378
                'Branch.lock_write', path, branch_token, repo_token or '')
1379
        except errors.ErrorFromSmartServer, err:
3245.4.52 by Andrew Bennetts
Add 'error_verb' and 'error_args' attributes to ErrorFromSmartServer.
1380
            if err.error_verb == 'LockContention':
3245.4.24 by Andrew Bennetts
Consistently raise errors from the server as ErrorFromSmartServer exceptions.
1381
                raise errors.LockContention('(remote lock)')
3245.4.52 by Andrew Bennetts
Add 'error_verb' and 'error_args' attributes to ErrorFromSmartServer.
1382
            elif err.error_verb == 'TokenMismatch':
3245.4.24 by Andrew Bennetts
Consistently raise errors from the server as ErrorFromSmartServer exceptions.
1383
                raise errors.TokenMismatch(token, '(remote token)')
3245.4.52 by Andrew Bennetts
Add 'error_verb' and 'error_args' attributes to ErrorFromSmartServer.
1384
            elif err.error_verb == 'UnlockableTransport':
3245.4.24 by Andrew Bennetts
Consistently raise errors from the server as ErrorFromSmartServer exceptions.
1385
                raise errors.UnlockableTransport(self.bzrdir.root_transport)
3245.4.52 by Andrew Bennetts
Add 'error_verb' and 'error_args' attributes to ErrorFromSmartServer.
1386
            elif err.error_verb == 'ReadOnlyError':
3245.4.24 by Andrew Bennetts
Consistently raise errors from the server as ErrorFromSmartServer exceptions.
1387
                raise errors.ReadOnlyError(self)
3245.4.52 by Andrew Bennetts
Add 'error_verb' and 'error_args' attributes to ErrorFromSmartServer.
1388
            elif err.error_verb == 'LockFailed':
1389
                raise errors.LockFailed(err.error_args[0], err.error_args[1])
3245.4.24 by Andrew Bennetts
Consistently raise errors from the server as ErrorFromSmartServer exceptions.
1390
            raise
1391
        if response[0] != 'ok':
2555.1.1 by Martin Pool
Remove use of 'assert False' to raise an exception unconditionally
1392
            raise errors.UnexpectedSmartServerResponse(response)
3245.4.24 by Andrew Bennetts
Consistently raise errors from the server as ErrorFromSmartServer exceptions.
1393
        ok, branch_token, repo_token = response
1394
        return branch_token, repo_token
2018.5.79 by Andrew Bennetts
Implement RemoteBranch.lock_write/unlock as smart operations.
1395
            
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).
1396
    def lock_write(self, token=None):
2018.5.79 by Andrew Bennetts
Implement RemoteBranch.lock_write/unlock as smart operations.
1397
        if not self._lock_mode:
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).
1398
            remote_tokens = self._remote_lock_write(token)
2018.5.79 by Andrew Bennetts
Implement RemoteBranch.lock_write/unlock as smart operations.
1399
            self._lock_token, self._repo_lock_token = remote_tokens
3376.2.4 by Martin Pool
Remove every assert statement from bzrlib!
1400
            if not self._lock_token:
1401
                raise SmartProtocolError('Remote server did not return a token!')
2018.14.1 by Andrew Bennetts
Update to current hpss branch? Fix lots of test failures.
1402
            # TODO: We really, really, really don't want to call _ensure_real
1403
            # here, but it's the easiest way to ensure coherency between the
1404
            # state of the RemoteBranch and RemoteRepository objects and the
1405
            # physical locks.  If we don't materialise the real objects here,
1406
            # then getting everything in the right state later is complex, so
1407
            # for now we just do it the lazy way.
1408
            #   -- Andrew Bennetts, 2007-02-22.
1409
            self._ensure_real()
2018.5.79 by Andrew Bennetts
Implement RemoteBranch.lock_write/unlock as smart operations.
1410
            if self._real_branch is not None:
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).
1411
                self._real_branch.repository.lock_write(
1412
                    token=self._repo_lock_token)
1413
                try:
1414
                    self._real_branch.lock_write(token=self._lock_token)
1415
                finally:
1416
                    self._real_branch.repository.unlock()
1417
            if token is not None:
2018.5.79 by Andrew Bennetts
Implement RemoteBranch.lock_write/unlock as smart operations.
1418
                self._leave_lock = True
1419
            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).
1420
                # XXX: this case seems to be unreachable; token cannot be None.
2018.5.79 by Andrew Bennetts
Implement RemoteBranch.lock_write/unlock as smart operations.
1421
                self._leave_lock = False
1422
            self._lock_mode = 'w'
1423
            self._lock_count = 1
1424
        elif self._lock_mode == 'r':
1425
            raise errors.ReadOnlyTransaction
1426
        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).
1427
            if token is not None:
1428
                # A token was given to lock_write, and we're relocking, so check
1429
                # that the given token actually matches the one we already have.
1430
                if token != self._lock_token:
1431
                    raise errors.TokenMismatch(token, self._lock_token)
2018.5.79 by Andrew Bennetts
Implement RemoteBranch.lock_write/unlock as smart operations.
1432
            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.
1433
        return self._lock_token or None
2018.5.79 by Andrew Bennetts
Implement RemoteBranch.lock_write/unlock as smart operations.
1434
1435
    def _unlock(self, branch_token, repo_token):
1436
        path = self.bzrdir._path_for_remote_call(self._client)
3245.4.24 by Andrew Bennetts
Consistently raise errors from the server as ErrorFromSmartServer exceptions.
1437
        try:
1438
            response = self._client.call('Branch.unlock', path, branch_token,
1439
                                         repo_token or '')
1440
        except errors.ErrorFromSmartServer, err:
3245.4.52 by Andrew Bennetts
Add 'error_verb' and 'error_args' attributes to ErrorFromSmartServer.
1441
            if err.error_verb == 'TokenMismatch':
3245.4.24 by Andrew Bennetts
Consistently raise errors from the server as ErrorFromSmartServer exceptions.
1442
                raise errors.TokenMismatch(
1443
                    str((branch_token, repo_token)), '(remote tokens)')
1444
            raise
2018.5.79 by Andrew Bennetts
Implement RemoteBranch.lock_write/unlock as smart operations.
1445
        if response == ('ok',):
1446
            return
3245.4.24 by Andrew Bennetts
Consistently raise errors from the server as ErrorFromSmartServer exceptions.
1447
        raise errors.UnexpectedSmartServerResponse(response)
1752.2.31 by Martin Pool
[broken] some support for write operations over hpss
1448
1449
    def unlock(self):
2018.5.79 by Andrew Bennetts
Implement RemoteBranch.lock_write/unlock as smart operations.
1450
        self._lock_count -= 1
1451
        if not self._lock_count:
2018.5.105 by Andrew Bennetts
Implement revision_history caching for RemoteBranch.
1452
            self._clear_cached_state()
2018.5.79 by Andrew Bennetts
Implement RemoteBranch.lock_write/unlock as smart operations.
1453
            mode = self._lock_mode
1454
            self._lock_mode = None
1455
            if self._real_branch is not None:
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.
1456
                if (not self._leave_lock and mode == 'w' and
1457
                    self._repo_lock_token):
2018.15.1 by Andrew Bennetts
All branch_implementations/test_locking tests passing.
1458
                    # If this RemoteBranch will remove the physical lock for the
1459
                    # repository, make sure the _real_branch doesn't do it
1460
                    # first.  (Because the _real_branch's repository is set to
1461
                    # be the RemoteRepository.)
1462
                    self._real_branch.repository.leave_lock_in_place()
2018.5.79 by Andrew Bennetts
Implement RemoteBranch.lock_write/unlock as smart operations.
1463
                self._real_branch.unlock()
1464
            if mode != 'w':
2018.5.163 by Andrew Bennetts
Deal with various review comments from Robert.
1465
                # Only write-locked branched need to make a remote method call
1466
                # to perfom the unlock.
2018.5.79 by Andrew Bennetts
Implement RemoteBranch.lock_write/unlock as smart operations.
1467
                return
3376.2.4 by Martin Pool
Remove every assert statement from bzrlib!
1468
            if not self._lock_token:
1469
                raise AssertionError('Locked, but no token!')
2018.5.79 by Andrew Bennetts
Implement RemoteBranch.lock_write/unlock as smart operations.
1470
            branch_token = self._lock_token
1471
            repo_token = self._repo_lock_token
1472
            self._lock_token = None
1473
            self._repo_lock_token = None
1474
            if not self._leave_lock:
1475
                self._unlock(branch_token, repo_token)
1752.2.52 by Andrew Bennetts
Flesh out more Remote* methods needed to open and initialise remote branches/trees/repositories.
1476
1477
    def break_lock(self):
2018.5.70 by Robert Collins
Only try to get real repositories when an operation requires them.
1478
        self._ensure_real()
1752.2.52 by Andrew Bennetts
Flesh out more Remote* methods needed to open and initialise remote branches/trees/repositories.
1479
        return self._real_branch.break_lock()
1752.2.31 by Martin Pool
[broken] some support for write operations over hpss
1480
2018.5.79 by Andrew Bennetts
Implement RemoteBranch.lock_write/unlock as smart operations.
1481
    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.
1482
        if not self._lock_token:
1483
            raise NotImplementedError(self.leave_lock_in_place)
2018.5.79 by Andrew Bennetts
Implement RemoteBranch.lock_write/unlock as smart operations.
1484
        self._leave_lock = True
1485
1486
    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.
1487
        if not self._lock_token:
3015.2.15 by Robert Collins
Review feedback.
1488
            raise NotImplementedError(self.dont_leave_lock_in_place)
2018.5.79 by Andrew Bennetts
Implement RemoteBranch.lock_write/unlock as smart operations.
1489
        self._leave_lock = False
1490
2018.5.51 by Wouter van Heyst
Test and implement RemoteBranch.last_revision_info()
1491
    def last_revision_info(self):
1492
        """See Branch.last_revision_info()."""
3441.5.1 by Andrew Bennetts
Avoid necessarily calling get_parent_map when pushing.
1493
        if self._last_revision_info_cache is None:
1494
            self._last_revision_info_cache = self._last_revision_info()
1495
        return self._last_revision_info_cache
1496
    
1497
    def _last_revision_info(self):
2018.5.51 by Wouter van Heyst
Test and implement RemoteBranch.last_revision_info()
1498
        path = self.bzrdir._path_for_remote_call(self._client)
1499
        response = self._client.call('Branch.last_revision_info', path)
3376.2.4 by Martin Pool
Remove every assert statement from bzrlib!
1500
        if response[0] != 'ok':
1501
            raise SmartProtocolError('unexpected response code %s' % (response,))
2018.5.51 by Wouter van Heyst
Test and implement RemoteBranch.last_revision_info()
1502
        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.
1503
        last_revision = response[2]
2018.5.51 by Wouter van Heyst
Test and implement RemoteBranch.last_revision_info()
1504
        return (revno, last_revision)
1505
2018.5.105 by Andrew Bennetts
Implement revision_history caching for RemoteBranch.
1506
    def _gen_revision_history(self):
1507
        """See Branch._gen_revision_history()."""
2018.5.42 by Robert Collins
Various hopefully improvements, but wsgi is broken, handing over to spiv :).
1508
        path = self.bzrdir._path_for_remote_call(self._client)
3245.4.58 by Andrew Bennetts
Unpack call_expecting_body's return value into variables, to avoid lots of ugly subscripting.
1509
        response_tuple, response_handler = self._client.call_expecting_body(
2018.5.153 by Andrew Bennetts
Rename call2 to call_expecting_body, and other small changes prompted by review.
1510
            'Branch.revision_history', path)
3245.4.58 by Andrew Bennetts
Unpack call_expecting_body's return value into variables, to avoid lots of ugly subscripting.
1511
        if response_tuple[0] != 'ok':
1512
            raise UnexpectedSmartServerResponse(response_tuple)
1513
        result = response_handler.read_body_bytes().split('\x00')
2018.5.38 by Robert Collins
Implement RemoteBranch.revision_history().
1514
        if result == ['']:
1515
            return []
1516
        return result
1752.2.30 by Martin Pool
Start adding a RemoteBzrDir, etc
1517
3441.5.6 by Andrew Bennetts
Greatly simplify RemoteBranch.update_revisions. Still needs more tests.
1518
    def _set_last_revision_descendant(self, revision_id, other_branch):
1519
        path = self.bzrdir._path_for_remote_call(self._client)
1520
        try:
1521
            response = self._client.call('Branch.set_last_revision_descendant',
1522
                path, self._lock_token, self._repo_lock_token, revision_id)
1523
        except errors.ErrorFromSmartServer, err:
1524
            if err.error_verb == 'NoSuchRevision':
1525
                raise NoSuchRevision(self, revision_id)
1526
            elif err.error_verb == 'NotDescendant':
1527
                raise errors.DivergedBranches(self, other_branch)
1528
            raise
1529
        self._clear_cached_state()
1530
        if len(response) != 2 and response[0] != 'ok':
1531
            raise errors.UnexpectedSmartServerResponse(response)
1532
        new_revno = response[1]
1533
        self._last_revision_info_cache = new_revno, revision_id
1534
3441.5.1 by Andrew Bennetts
Avoid necessarily calling get_parent_map when pushing.
1535
    def _set_last_revision(self, revision_id):
1536
        path = self.bzrdir._path_for_remote_call(self._client)
1537
        self._clear_cached_state()
1538
        try:
1539
            response = self._client.call('Branch.set_last_revision',
1540
                path, self._lock_token, self._repo_lock_token, revision_id)
1541
        except errors.ErrorFromSmartServer, err:
1542
            if err.error_verb == 'NoSuchRevision':
1543
                raise NoSuchRevision(self, revision_id)
1544
            raise
1545
        if response != ('ok',):
1546
            raise errors.UnexpectedSmartServerResponse(response)
1547
2018.14.1 by Andrew Bennetts
Update to current hpss branch? Fix lots of test failures.
1548
    @needs_write_lock
1752.2.52 by Andrew Bennetts
Flesh out more Remote* methods needed to open and initialise remote branches/trees/repositories.
1549
    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.
1550
        # Send just the tip revision of the history; the server will generate
1551
        # the full history from that.  If the revision doesn't exist in this
1552
        # branch, NoSuchRevision will be raised.
1553
        if rev_history == []:
2018.5.170 by Andrew Bennetts
Use 'null:' instead of '' to mean NULL_REVISION on the wire.
1554
            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.
1555
        else:
1556
            rev_id = rev_history[-1]
3441.5.1 by Andrew Bennetts
Avoid necessarily calling get_parent_map when pushing.
1557
        self._set_last_revision(rev_id)
2018.5.105 by Andrew Bennetts
Implement revision_history caching for RemoteBranch.
1558
        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.
1559
1560
    def get_parent(self):
2018.5.70 by Robert Collins
Only try to get real repositories when an operation requires them.
1561
        self._ensure_real()
1752.2.52 by Andrew Bennetts
Flesh out more Remote* methods needed to open and initialise remote branches/trees/repositories.
1562
        return self._real_branch.get_parent()
1563
        
1752.2.63 by Andrew Bennetts
Delegate set_parent.
1564
    def set_parent(self, url):
2018.5.70 by Robert Collins
Only try to get real repositories when an operation requires them.
1565
        self._ensure_real()
1752.2.63 by Andrew Bennetts
Delegate set_parent.
1566
        return self._real_branch.set_parent(url)
1567
        
2018.5.94 by Andrew Bennetts
Various small changes in aid of making tests pass (including deleting one invalid test).
1568
    def sprout(self, to_bzrdir, revision_id=None):
1569
        # Like Branch.sprout, except that it sprouts a branch in the default
1570
        # format, because RemoteBranches can't be created at arbitrary URLs.
1571
        # XXX: if to_bzrdir is a RemoteBranch, this should perhaps do
1572
        # to_bzrdir.create_branch...
3047.1.1 by Andrew Bennetts
Fix for bug 164626, add test that Repository.sprout preserves format.
1573
        self._ensure_real()
1574
        result = self._real_branch._format.initialize(to_bzrdir)
2018.18.20 by Martin Pool
Route branch operations through remote copy_content_into
1575
        self.copy_content_into(result, revision_id=revision_id)
2018.5.94 by Andrew Bennetts
Various small changes in aid of making tests pass (including deleting one invalid test).
1576
        result.set_parent(self.bzrdir.root_transport.base)
1577
        return result
1578
2018.14.1 by Andrew Bennetts
Update to current hpss branch? Fix lots of test failures.
1579
    @needs_write_lock
2477.1.2 by Martin Pool
Rename push/pull back to 'run_hooks' (jameinel)
1580
    def pull(self, source, overwrite=False, stop_revision=None,
2477.1.9 by Martin Pool
Review cleanups from John, mostly docs
1581
             **kwargs):
3441.5.4 by Andrew Bennetts
Fix test failures, and add some tests for the remote graph heads RPC.
1582
        self._clear_cached_state()
2477.1.9 by Martin Pool
Review cleanups from John, mostly docs
1583
        # FIXME: This asks the real branch to run the hooks, which means
1584
        # they're called with the wrong target branch parameter. 
1585
        # The test suite specifically allows this at present but it should be
1586
        # fixed.  It should get a _override_hook_target branch,
1587
        # as push does.  -- mbp 20070405
2018.14.1 by Andrew Bennetts
Update to current hpss branch? Fix lots of test failures.
1588
        self._ensure_real()
1589
        self._real_branch.pull(
2477.1.2 by Martin Pool
Rename push/pull back to 'run_hooks' (jameinel)
1590
            source, overwrite=overwrite, stop_revision=stop_revision,
1591
            **kwargs)
2018.14.1 by Andrew Bennetts
Update to current hpss branch? Fix lots of test failures.
1592
2018.14.3 by Andrew Bennetts
Make a couple more branch_implementations tests pass.
1593
    @needs_read_lock
1594
    def push(self, target, overwrite=False, stop_revision=None):
1595
        self._ensure_real()
2018.5.97 by Andrew Bennetts
Fix more tests.
1596
        return self._real_branch.push(
2477.1.5 by Martin Pool
More cleanups of Branch.push to get the right behaviour with RemoteBranches
1597
            target, overwrite=overwrite, stop_revision=stop_revision,
1598
            _override_hook_source_branch=self)
2018.14.3 by Andrew Bennetts
Make a couple more branch_implementations tests pass.
1599
1600
    def is_locked(self):
1601
        return self._lock_count >= 1
1602
2892.2.1 by Andrew Bennetts
Add Branch.set_last_revision_info smart method, and make the RemoteBranch client use it.
1603
    @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.
1604
    def set_last_revision_info(self, revno, revision_id):
2892.2.1 by Andrew Bennetts
Add Branch.set_last_revision_info smart method, and make the RemoteBranch client use it.
1605
        revision_id = ensure_null(revision_id)
1606
        path = self.bzrdir._path_for_remote_call(self._client)
3297.4.2 by Andrew Bennetts
Add backwards compatibility for servers older than 1.4.
1607
        try:
1608
            response = self._client.call('Branch.set_last_revision_info',
1609
                path, self._lock_token, self._repo_lock_token, str(revno), revision_id)
1610
        except errors.UnknownSmartMethod:
1611
            self._ensure_real()
1612
            self._clear_cached_state()
3441.5.1 by Andrew Bennetts
Avoid necessarily calling get_parent_map when pushing.
1613
            self._real_branch.set_last_revision_info(revno, revision_id)
1614
            self._last_revision_info_cache = revno, revision_id
1615
            return
3245.4.24 by Andrew Bennetts
Consistently raise errors from the server as ErrorFromSmartServer exceptions.
1616
        except errors.ErrorFromSmartServer, err:
3245.4.52 by Andrew Bennetts
Add 'error_verb' and 'error_args' attributes to ErrorFromSmartServer.
1617
            if err.error_verb == 'NoSuchRevision':
1618
                raise NoSuchRevision(self, err.error_args[0])
3245.4.53 by Andrew Bennetts
Add some missing 'raise' statements to test_remote.
1619
            raise
2892.2.1 by Andrew Bennetts
Add Branch.set_last_revision_info smart method, and make the RemoteBranch client use it.
1620
        if response == ('ok',):
1621
            self._clear_cached_state()
3441.5.1 by Andrew Bennetts
Avoid necessarily calling get_parent_map when pushing.
1622
            self._last_revision_info_cache = revno, revision_id
2892.2.1 by Andrew Bennetts
Add Branch.set_last_revision_info smart method, and make the RemoteBranch client use it.
1623
        else:
1624
            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.
1625
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.
1626
    def generate_revision_history(self, revision_id, last_rev=None,
1627
                                  other_branch=None):
3441.5.6 by Andrew Bennetts
Greatly simplify RemoteBranch.update_revisions. Still needs more tests.
1628
        medium = self._client._medium
1629
        if medium._remote_is_at_least_1_6:
1630
            try:
1631
                self._set_last_revision_descendant(revision_id, other_branch)
1632
                return
1633
            except UnknownSmartMethod:
1634
                medium._remote_is_at_least_1_6 = False
3441.5.5 by Andrew Bennetts
Some small tweaks and comments.
1635
        self._clear_cached_state()
3441.5.2 by Andrew Bennetts
Remove various debugging cruft.
1636
        self._ensure_real()
3441.5.6 by Andrew Bennetts
Greatly simplify RemoteBranch.update_revisions. Still needs more tests.
1637
        self._real_branch.generate_revision_history(
3441.5.2 by Andrew Bennetts
Remove various debugging cruft.
1638
            revision_id, 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.
1639
2018.5.96 by Andrew Bennetts
Merge from bzr.dev, resolving the worst of the semantic conflicts, but there's
1640
    @property
1641
    def tags(self):
1642
        self._ensure_real()
1643
        return self._real_branch.tags
1644
2018.5.97 by Andrew Bennetts
Fix more tests.
1645
    def set_push_location(self, location):
1646
        self._ensure_real()
1647
        return self._real_branch.set_push_location(location)
1648
3441.5.6 by Andrew Bennetts
Greatly simplify RemoteBranch.update_revisions. Still needs more tests.
1649
    @needs_write_lock
3052.5.4 by John Arbash Meinel
If we are going to overwrite the target, we don't have to do
1650
    def update_revisions(self, other, stop_revision=None, overwrite=False):
3441.5.1 by Andrew Bennetts
Avoid necessarily calling get_parent_map when pushing.
1651
        other.lock_read()
1652
        try:
1653
            if stop_revision is None:
3441.5.6 by Andrew Bennetts
Greatly simplify RemoteBranch.update_revisions. Still needs more tests.
1654
                stop_revision = other.last_revision()
3441.5.5 by Andrew Bennetts
Some small tweaks and comments.
1655
                if revision.is_null(stop_revision):
3441.5.1 by Andrew Bennetts
Avoid necessarily calling get_parent_map when pushing.
1656
                    # if there are no commits, we're done.
1657
                    return
1658
            # whats the current last revision, before we fetch [and change it
1659
            # possibly]
1660
            self.fetch(other, stop_revision)
3441.5.6 by Andrew Bennetts
Greatly simplify RemoteBranch.update_revisions. Still needs more tests.
1661
1662
            if overwrite:
3441.5.1 by Andrew Bennetts
Avoid necessarily calling get_parent_map when pushing.
1663
                self._set_last_revision(stop_revision)
3441.5.6 by Andrew Bennetts
Greatly simplify RemoteBranch.update_revisions. Still needs more tests.
1664
            else:
1665
                medium = self._client._medium
1666
                if medium._remote_is_at_least_1_6:
1667
                    try:
1668
                        self._set_last_revision_descendant(stop_revision, other)
1669
                        return
3441.5.7 by Andrew Bennetts
Fix unbound global.
1670
                    except errors.UnknownSmartMethod:
3441.5.6 by Andrew Bennetts
Greatly simplify RemoteBranch.update_revisions. Still needs more tests.
1671
                        medium._remote_is_at_least_1_6 = False
1672
                last_rev = revision.ensure_null(self.last_revision())
1673
                self.generate_revision_history(
1674
                    stop_revision, last_rev=last_rev, other_branch=other)
3441.5.1 by Andrew Bennetts
Avoid necessarily calling get_parent_map when pushing.
1675
        finally:
1676
            other.unlock()
2018.5.97 by Andrew Bennetts
Fix more tests.
1677
1752.2.30 by Martin Pool
Start adding a RemoteBzrDir, etc
1678
2018.18.25 by Martin Pool
Repository.tarball fixes for python2.4
1679
def _extract_tar(tar, to_dir):
1680
    """Extract all the contents of a tarfile object.
1681
1682
    A replacement for extractall, which is not present in python2.4
1683
    """
1684
    for tarinfo in tar:
1685
        tar.extract(tarinfo, to_dir)