/brz/remove-bazaar

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