91
# Note: RemoteBzrDirFormat is in bzrdir.py
93
class RemoteBzrDir(BzrDir, _RpcHelper):
104
# Note that RemoteBzrDirProber lives in bzrlib.bzrdir so bzrlib.remote
105
# does not have to be imported unless a remote format is involved.
107
class RemoteBzrDirFormat(_mod_bzrdir.BzrDirMetaFormat1):
108
"""Format representing bzrdirs accessed via a smart server"""
110
supports_workingtrees = False
113
_mod_bzrdir.BzrDirMetaFormat1.__init__(self)
114
# XXX: It's a bit ugly that the network name is here, because we'd
115
# like to believe that format objects are stateless or at least
116
# immutable, However, we do at least avoid mutating the name after
117
# it's returned. See <https://bugs.launchpad.net/bzr/+bug/504102>
118
self._network_name = None
121
return "%s(_network_name=%r)" % (self.__class__.__name__,
124
def get_format_description(self):
125
if self._network_name:
127
real_format = controldir.network_format_registry.get(
132
return 'Remote: ' + real_format.get_format_description()
133
return 'bzr remote bzrdir'
135
def get_format_string(self):
136
raise NotImplementedError(self.get_format_string)
138
def network_name(self):
139
if self._network_name:
140
return self._network_name
142
raise AssertionError("No network name set.")
144
def initialize_on_transport(self, transport):
146
# hand off the request to the smart server
147
client_medium = transport.get_smart_medium()
148
except errors.NoSmartMedium:
149
# TODO: lookup the local format from a server hint.
150
local_dir_format = _mod_bzrdir.BzrDirMetaFormat1()
151
return local_dir_format.initialize_on_transport(transport)
152
client = _SmartClient(client_medium)
153
path = client.remote_path_from_transport(transport)
155
response = client.call('BzrDirFormat.initialize', path)
156
except errors.ErrorFromSmartServer, err:
157
_translate_error(err, path=path)
158
if response[0] != 'ok':
159
raise errors.SmartProtocolError('unexpected response code %s' % (response,))
160
format = RemoteBzrDirFormat()
161
self._supply_sub_formats_to(format)
162
return RemoteBzrDir(transport, format)
164
def parse_NoneTrueFalse(self, arg):
171
raise AssertionError("invalid arg %r" % arg)
173
def _serialize_NoneTrueFalse(self, arg):
180
def _serialize_NoneString(self, arg):
183
def initialize_on_transport_ex(self, transport, use_existing_dir=False,
184
create_prefix=False, force_new_repo=False, stacked_on=None,
185
stack_on_pwd=None, repo_format_name=None, make_working_trees=None,
188
# hand off the request to the smart server
189
client_medium = transport.get_smart_medium()
190
except errors.NoSmartMedium:
193
# Decline to open it if the server doesn't support our required
194
# version (3) so that the VFS-based transport will do it.
195
if client_medium.should_probe():
197
server_version = client_medium.protocol_version()
198
if server_version != '2':
202
except errors.SmartProtocolError:
203
# Apparently there's no usable smart server there, even though
204
# the medium supports the smart protocol.
209
client = _SmartClient(client_medium)
210
path = client.remote_path_from_transport(transport)
211
if client_medium._is_remote_before((1, 16)):
214
# TODO: lookup the local format from a server hint.
215
local_dir_format = _mod_bzrdir.BzrDirMetaFormat1()
216
self._supply_sub_formats_to(local_dir_format)
217
return local_dir_format.initialize_on_transport_ex(transport,
218
use_existing_dir=use_existing_dir, create_prefix=create_prefix,
219
force_new_repo=force_new_repo, stacked_on=stacked_on,
220
stack_on_pwd=stack_on_pwd, repo_format_name=repo_format_name,
221
make_working_trees=make_working_trees, shared_repo=shared_repo,
223
return self._initialize_on_transport_ex_rpc(client, path, transport,
224
use_existing_dir, create_prefix, force_new_repo, stacked_on,
225
stack_on_pwd, repo_format_name, make_working_trees, shared_repo)
227
def _initialize_on_transport_ex_rpc(self, client, path, transport,
228
use_existing_dir, create_prefix, force_new_repo, stacked_on,
229
stack_on_pwd, repo_format_name, make_working_trees, shared_repo):
231
args.append(self._serialize_NoneTrueFalse(use_existing_dir))
232
args.append(self._serialize_NoneTrueFalse(create_prefix))
233
args.append(self._serialize_NoneTrueFalse(force_new_repo))
234
args.append(self._serialize_NoneString(stacked_on))
235
# stack_on_pwd is often/usually our transport
238
stack_on_pwd = transport.relpath(stack_on_pwd)
241
except errors.PathNotChild:
243
args.append(self._serialize_NoneString(stack_on_pwd))
244
args.append(self._serialize_NoneString(repo_format_name))
245
args.append(self._serialize_NoneTrueFalse(make_working_trees))
246
args.append(self._serialize_NoneTrueFalse(shared_repo))
247
request_network_name = self._network_name or \
248
_mod_bzrdir.BzrDirFormat.get_default_format().network_name()
250
response = client.call('BzrDirFormat.initialize_ex_1.16',
251
request_network_name, path, *args)
252
except errors.UnknownSmartMethod:
253
client._medium._remember_remote_is_before((1,16))
254
local_dir_format = _mod_bzrdir.BzrDirMetaFormat1()
255
self._supply_sub_formats_to(local_dir_format)
256
return local_dir_format.initialize_on_transport_ex(transport,
257
use_existing_dir=use_existing_dir, create_prefix=create_prefix,
258
force_new_repo=force_new_repo, stacked_on=stacked_on,
259
stack_on_pwd=stack_on_pwd, repo_format_name=repo_format_name,
260
make_working_trees=make_working_trees, shared_repo=shared_repo,
262
except errors.ErrorFromSmartServer, err:
263
_translate_error(err, path=path)
264
repo_path = response[0]
265
bzrdir_name = response[6]
266
require_stacking = response[7]
267
require_stacking = self.parse_NoneTrueFalse(require_stacking)
268
format = RemoteBzrDirFormat()
269
format._network_name = bzrdir_name
270
self._supply_sub_formats_to(format)
271
bzrdir = RemoteBzrDir(transport, format, _client=client)
273
repo_format = response_tuple_to_repo_format(response[1:])
277
repo_bzrdir_format = RemoteBzrDirFormat()
278
repo_bzrdir_format._network_name = response[5]
279
repo_bzr = RemoteBzrDir(transport.clone(repo_path),
283
final_stack = response[8] or None
284
final_stack_pwd = response[9] or None
286
final_stack_pwd = urlutils.join(
287
transport.base, final_stack_pwd)
288
remote_repo = RemoteRepository(repo_bzr, repo_format)
289
if len(response) > 10:
290
# Updated server verb that locks remotely.
291
repo_lock_token = response[10] or None
292
remote_repo.lock_write(repo_lock_token, _skip_rpc=True)
294
remote_repo.dont_leave_lock_in_place()
296
remote_repo.lock_write()
297
policy = _mod_bzrdir.UseExistingRepository(remote_repo, final_stack,
298
final_stack_pwd, require_stacking)
299
policy.acquire_repository()
303
bzrdir._format.set_branch_format(self.get_branch_format())
305
# The repo has already been created, but we need to make sure that
306
# we'll make a stackable branch.
307
bzrdir._format.require_stacking(_skip_repo=True)
308
return remote_repo, bzrdir, require_stacking, policy
310
def _open(self, transport):
311
return RemoteBzrDir(transport, self)
313
def __eq__(self, other):
314
if not isinstance(other, RemoteBzrDirFormat):
316
return self.get_format_description() == other.get_format_description()
318
def __return_repository_format(self):
319
# Always return a RemoteRepositoryFormat object, but if a specific bzr
320
# repository format has been asked for, tell the RemoteRepositoryFormat
321
# that it should use that for init() etc.
322
result = RemoteRepositoryFormat()
323
custom_format = getattr(self, '_repository_format', None)
325
if isinstance(custom_format, RemoteRepositoryFormat):
328
# We will use the custom format to create repositories over the
329
# wire; expose its details like rich_root_data for code to
331
result._custom_format = custom_format
334
def get_branch_format(self):
335
result = _mod_bzrdir.BzrDirMetaFormat1.get_branch_format(self)
336
if not isinstance(result, RemoteBranchFormat):
337
new_result = RemoteBranchFormat()
338
new_result._custom_format = result
340
self.set_branch_format(new_result)
344
repository_format = property(__return_repository_format,
345
_mod_bzrdir.BzrDirMetaFormat1._set_repository_format) #.im_func)
348
class RemoteControlStore(config.IniFileStore):
349
"""Control store which attempts to use HPSS calls to retrieve control store.
351
Note that this is specific to bzr-based formats.
354
def __init__(self, bzrdir):
355
super(RemoteControlStore, self).__init__()
357
self._real_store = None
359
def lock_write(self, token=None):
361
return self._real_store.lock_write(token)
365
return self._real_store.unlock()
369
# We need to be able to override the undecorated implementation
370
self.save_without_locking()
372
def save_without_locking(self):
373
super(RemoteControlStore, self).save()
375
def _ensure_real(self):
376
self.bzrdir._ensure_real()
377
if self._real_store is None:
378
self._real_store = config.ControlStore(self.bzrdir)
380
def external_url(self):
381
return self.bzrdir.user_url
383
def _load_content(self):
384
medium = self.bzrdir._client._medium
385
path = self.bzrdir._path_for_remote_call(self.bzrdir._client)
387
response, handler = self.bzrdir._call_expecting_body(
388
'BzrDir.get_config_file', path)
389
except errors.UnknownSmartMethod:
391
return self._real_store._load_content()
392
if len(response) and response[0] != 'ok':
393
raise errors.UnexpectedSmartServerResponse(response)
394
return handler.read_body_bytes()
396
def _save_content(self, content):
397
# FIXME JRV 2011-11-22: Ideally this should use a
398
# HPSS call too, but at the moment it is not possible
399
# to write lock control directories.
401
return self._real_store._save_content(content)
404
class RemoteBzrDir(_mod_bzrdir.BzrDir, _RpcHelper):
94
405
"""Control directory on a remote server, accessed via bzr:// or similar."""
96
407
def __init__(self, transport, format, _client=None, _force_probe=False):
1205
1672
raise errors.UnexpectedSmartServerResponse(response)
1207
1675
def sprout(self, to_bzrdir, revision_id=None):
1208
# TODO: Option to control what format is created?
1210
dest_repo = self._real_repository._format.initialize(to_bzrdir,
1676
"""Create a descendent repository for new development.
1678
Unlike clone, this does not copy the settings of the repository.
1680
dest_repo = self._create_sprouting_repo(to_bzrdir, shared=False)
1212
1681
dest_repo.fetch(self, revision_id=revision_id)
1213
1682
return dest_repo
1684
def _create_sprouting_repo(self, a_bzrdir, shared):
1685
if not isinstance(a_bzrdir._format, self.bzrdir._format.__class__):
1686
# use target default format.
1687
dest_repo = a_bzrdir.create_repository()
1689
# Most control formats need the repository to be specifically
1690
# created, but on some old all-in-one formats it's not needed
1692
dest_repo = self._format.initialize(a_bzrdir, shared=shared)
1693
except errors.UninitializableFormat:
1694
dest_repo = a_bzrdir.open_repository()
1215
1697
### These methods are just thin shims to the VFS object for now.
1217
1700
def revision_tree(self, revision_id):
1219
return self._real_repository.revision_tree(revision_id)
1701
revision_id = _mod_revision.ensure_null(revision_id)
1702
if revision_id == _mod_revision.NULL_REVISION:
1703
return InventoryRevisionTree(self,
1704
Inventory(root_id=None), _mod_revision.NULL_REVISION)
1706
return list(self.revision_trees([revision_id]))[0]
1221
1708
def get_serializer_format(self):
1223
return self._real_repository.get_serializer_format()
1709
path = self.bzrdir._path_for_remote_call(self._client)
1711
response = self._call('VersionedFileRepository.get_serializer_format',
1713
except errors.UnknownSmartMethod:
1715
return self._real_repository.get_serializer_format()
1716
if response[0] != 'ok':
1717
raise errors.UnexpectedSmartServerResponse(response)
1225
1720
def get_commit_builder(self, branch, parents, config, timestamp=None,
1226
1721
timezone=None, committer=None, revprops=None,
1722
revision_id=None, lossy=False):
1228
1723
# FIXME: It ought to be possible to call this without immediately
1229
1724
# triggering _ensure_real. For now it's the easiest thing to do.
1230
1725
self._ensure_real()
1231
1726
real_repo = self._real_repository
1232
1727
builder = real_repo.get_commit_builder(branch, parents,
1233
1728
config, timestamp=timestamp, timezone=timezone,
1234
committer=committer, revprops=revprops, revision_id=revision_id)
1729
committer=committer, revprops=revprops,
1730
revision_id=revision_id, lossy=lossy)
1237
1733
def add_fallback_repository(self, repository):
1338
1842
included_keys = result_set.intersection(result_parents)
1339
1843
start_keys = result_set.difference(included_keys)
1340
1844
exclude_keys = result_parents.difference(result_set)
1341
result = graph.SearchResult(start_keys, exclude_keys,
1845
result = vf_search.SearchResult(start_keys, exclude_keys,
1342
1846
len(result_set), result_set)
1345
1849
@needs_read_lock
1346
def search_missing_revision_ids(self, other, revision_id=None, find_ghosts=True):
1850
def search_missing_revision_ids(self, other,
1851
revision_id=symbol_versioning.DEPRECATED_PARAMETER,
1852
find_ghosts=True, revision_ids=None, if_present_ids=None,
1347
1854
"""Return the revision ids that other has that this does not.
1349
1856
These are returned in topological order.
1351
1858
revision_id: only return revision ids included by revision_id.
1353
return repository.InterRepository.get(
1354
other, self).search_missing_revision_ids(revision_id, find_ghosts)
1860
if symbol_versioning.deprecated_passed(revision_id):
1861
symbol_versioning.warn(
1862
'search_missing_revision_ids(revision_id=...) was '
1863
'deprecated in 2.4. Use revision_ids=[...] instead.',
1864
DeprecationWarning, stacklevel=2)
1865
if revision_ids is not None:
1866
raise AssertionError(
1867
'revision_ids is mutually exclusive with revision_id')
1868
if revision_id is not None:
1869
revision_ids = [revision_id]
1870
inter_repo = _mod_repository.InterRepository.get(other, self)
1871
return inter_repo.search_missing_revision_ids(
1872
find_ghosts=find_ghosts, revision_ids=revision_ids,
1873
if_present_ids=if_present_ids, limit=limit)
1356
def fetch(self, source, revision_id=None, pb=None, find_ghosts=False,
1875
def fetch(self, source, revision_id=None, find_ghosts=False,
1357
1876
fetch_spec=None):
1358
1877
# No base implementation to use as RemoteRepository is not a subclass
1359
1878
# of Repository; so this is a copy of Repository.fetch().
1398
1923
return self._real_repository._get_versioned_file_checker(
1399
1924
revisions, revision_versions_cache)
1926
def _iter_files_bytes_rpc(self, desired_files, absent):
1927
path = self.bzrdir._path_for_remote_call(self._client)
1930
for (file_id, revid, identifier) in desired_files:
1931
lines.append("%s\0%s" % (
1932
osutils.safe_file_id(file_id),
1933
osutils.safe_revision_id(revid)))
1934
identifiers.append(identifier)
1935
(response_tuple, response_handler) = (
1936
self._call_with_body_bytes_expecting_body(
1937
"Repository.iter_files_bytes", (path, ), "\n".join(lines)))
1938
if response_tuple != ('ok', ):
1939
response_handler.cancel_read_body()
1940
raise errors.UnexpectedSmartServerResponse(response_tuple)
1941
byte_stream = response_handler.read_streamed_body()
1942
def decompress_stream(start, byte_stream, unused):
1943
decompressor = zlib.decompressobj()
1944
yield decompressor.decompress(start)
1945
while decompressor.unused_data == "":
1947
data = byte_stream.next()
1948
except StopIteration:
1950
yield decompressor.decompress(data)
1951
yield decompressor.flush()
1952
unused.append(decompressor.unused_data)
1955
while not "\n" in unused:
1956
unused += byte_stream.next()
1957
header, rest = unused.split("\n", 1)
1958
args = header.split("\0")
1959
if args[0] == "absent":
1960
absent[identifiers[int(args[3])]] = (args[1], args[2])
1963
elif args[0] == "ok":
1966
raise errors.UnexpectedSmartServerResponse(args)
1968
yield (identifiers[idx],
1969
decompress_stream(rest, byte_stream, unused_chunks))
1970
unused = "".join(unused_chunks)
1401
1972
def iter_files_bytes(self, desired_files):
1402
1973
"""See Repository.iter_file_bytes.
1405
return self._real_repository.iter_files_bytes(desired_files)
1977
for (identifier, bytes_iterator) in self._iter_files_bytes_rpc(
1978
desired_files, absent):
1979
yield identifier, bytes_iterator
1980
for fallback in self._fallback_repositories:
1983
desired_files = [(key[0], key[1], identifier) for
1984
(identifier, key) in absent.iteritems()]
1985
for (identifier, bytes_iterator) in fallback.iter_files_bytes(desired_files):
1986
del absent[identifier]
1987
yield identifier, bytes_iterator
1989
# There may be more missing items, but raise an exception
1991
missing_identifier = absent.keys()[0]
1992
missing_key = absent[missing_identifier]
1993
raise errors.RevisionNotPresent(revision_id=missing_key[1],
1994
file_id=missing_key[0])
1995
except errors.UnknownSmartMethod:
1997
for (identifier, bytes_iterator) in (
1998
self._real_repository.iter_files_bytes(desired_files)):
1999
yield identifier, bytes_iterator
2001
def get_cached_parent_map(self, revision_ids):
2002
"""See bzrlib.CachingParentsProvider.get_cached_parent_map"""
2003
return self._unstacked_provider.get_cached_parent_map(revision_ids)
1407
2005
def get_parent_map(self, revision_ids):
1408
2006
"""See bzrlib.Graph.get_parent_map()."""
1542
2129
@needs_read_lock
1543
2130
def get_signature_text(self, revision_id):
1545
return self._real_repository.get_signature_text(revision_id)
2131
path = self.bzrdir._path_for_remote_call(self._client)
2133
response_tuple, response_handler = self._call_expecting_body(
2134
'Repository.get_revision_signature_text', path, revision_id)
2135
except errors.UnknownSmartMethod:
2137
return self._real_repository.get_signature_text(revision_id)
2138
except errors.NoSuchRevision, err:
2139
for fallback in self._fallback_repositories:
2141
return fallback.get_signature_text(revision_id)
2142
except errors.NoSuchRevision:
2146
if response_tuple[0] != 'ok':
2147
raise errors.UnexpectedSmartServerResponse(response_tuple)
2148
return response_handler.read_body_bytes()
1547
2150
@needs_read_lock
1548
2151
def _get_inventory_xml(self, revision_id):
1549
2152
self._ensure_real()
1550
2153
return self._real_repository._get_inventory_xml(revision_id)
1552
2156
def reconcile(self, other=None, thorough=False):
1554
return self._real_repository.reconcile(other=other, thorough=thorough)
2157
from bzrlib.reconcile import RepoReconciler
2158
path = self.bzrdir._path_for_remote_call(self._client)
2160
response, handler = self._call_expecting_body(
2161
'Repository.reconcile', path, self._lock_token)
2162
except (errors.UnknownSmartMethod, errors.TokenLockingNotSupported):
2164
return self._real_repository.reconcile(other=other, thorough=thorough)
2165
if response != ('ok', ):
2166
raise errors.UnexpectedSmartServerResponse(response)
2167
body = handler.read_body_bytes()
2168
result = RepoReconciler(self)
2169
for line in body.split('\n'):
2172
key, val_text = line.split(':')
2173
if key == "garbage_inventories":
2174
result.garbage_inventories = int(val_text)
2175
elif key == "inconsistent_parents":
2176
result.inconsistent_parents = int(val_text)
2178
mutter("unknown reconcile key %r" % key)
1556
2181
def all_revision_ids(self):
1558
return self._real_repository.all_revision_ids()
2182
path = self.bzrdir._path_for_remote_call(self._client)
2184
response_tuple, response_handler = self._call_expecting_body(
2185
"Repository.all_revision_ids", path)
2186
except errors.UnknownSmartMethod:
2188
return self._real_repository.all_revision_ids()
2189
if response_tuple != ("ok", ):
2190
raise errors.UnexpectedSmartServerResponse(response_tuple)
2191
revids = set(response_handler.read_body_bytes().splitlines())
2192
for fallback in self._fallback_repositories:
2193
revids.update(set(fallback.all_revision_ids()))
1560
2196
@needs_read_lock
1561
2197
def get_deltas_for_revisions(self, revisions, specific_fileids=None):
1690
2340
self._ensure_real()
1691
2341
return self._real_repository.texts
2343
def _iter_revisions_rpc(self, revision_ids):
2344
body = "\n".join(revision_ids)
2345
path = self.bzrdir._path_for_remote_call(self._client)
2346
response_tuple, response_handler = (
2347
self._call_with_body_bytes_expecting_body(
2348
"Repository.iter_revisions", (path, ), body))
2349
if response_tuple[0] != "ok":
2350
raise errors.UnexpectedSmartServerResponse(response_tuple)
2351
serializer_format = response_tuple[1]
2352
serializer = serializer_format_registry.get(serializer_format)
2353
byte_stream = response_handler.read_streamed_body()
2354
decompressor = zlib.decompressobj()
2356
for bytes in byte_stream:
2357
chunks.append(decompressor.decompress(bytes))
2358
if decompressor.unused_data != "":
2359
chunks.append(decompressor.flush())
2360
yield serializer.read_revision_from_string("".join(chunks))
2361
unused = decompressor.unused_data
2362
decompressor = zlib.decompressobj()
2363
chunks = [decompressor.decompress(unused)]
2364
chunks.append(decompressor.flush())
2365
text = "".join(chunks)
2367
yield serializer.read_revision_from_string("".join(chunks))
1693
2369
@needs_read_lock
1694
2370
def get_revisions(self, revision_ids):
1696
return self._real_repository.get_revisions(revision_ids)
2371
if revision_ids is None:
2372
revision_ids = self.all_revision_ids()
2374
for rev_id in revision_ids:
2375
if not rev_id or not isinstance(rev_id, basestring):
2376
raise errors.InvalidRevisionId(
2377
revision_id=rev_id, branch=self)
2379
missing = set(revision_ids)
2381
for rev in self._iter_revisions_rpc(revision_ids):
2382
missing.remove(rev.revision_id)
2383
revs[rev.revision_id] = rev
2384
except errors.UnknownSmartMethod:
2386
return self._real_repository.get_revisions(revision_ids)
2387
for fallback in self._fallback_repositories:
2390
for revid in list(missing):
2391
# XXX JRV 2011-11-20: It would be nice if there was a
2392
# public method on Repository that could be used to query
2393
# for revision objects *without* failing completely if one
2394
# was missing. There is VersionedFileRepository._iter_revisions,
2395
# but unfortunately that's private and not provided by
2396
# all repository implementations.
2398
revs[revid] = fallback.get_revision(revid)
2399
except errors.NoSuchRevision:
2402
missing.remove(revid)
2404
raise errors.NoSuchRevision(self, list(missing)[0])
2405
return [revs[revid] for revid in revision_ids]
1698
2407
def supports_rich_root(self):
1699
2408
return self._format.rich_root_data
2410
@symbol_versioning.deprecated_method(symbol_versioning.deprecated_in((2, 4, 0)))
1701
2411
def iter_reverse_revision_history(self, revision_id):
1702
2412
self._ensure_real()
1703
2413
return self._real_repository.iter_reverse_revision_history(revision_id)
1706
2416
def _serializer(self):
1707
2417
return self._format._serializer
1709
2420
def store_revision_signature(self, gpg_strategy, plaintext, revision_id):
1711
return self._real_repository.store_revision_signature(
1712
gpg_strategy, plaintext, revision_id)
2421
signature = gpg_strategy.sign(plaintext)
2422
self.add_signature_text(revision_id, signature)
1714
2424
def add_signature_text(self, revision_id, signature):
1716
return self._real_repository.add_signature_text(revision_id, signature)
2425
if self._real_repository:
2426
# If there is a real repository the write group will
2427
# be in the real repository as well, so use that:
2429
return self._real_repository.add_signature_text(
2430
revision_id, signature)
2431
path = self.bzrdir._path_for_remote_call(self._client)
2432
response, handler = self._call_with_body_bytes_expecting_body(
2433
'Repository.add_signature_text', (path, self._lock_token,
2434
revision_id) + tuple(self._write_group_tokens), signature)
2435
handler.cancel_read_body()
2437
if response[0] != 'ok':
2438
raise errors.UnexpectedSmartServerResponse(response)
2439
self._write_group_tokens = response[1:]
1718
2441
def has_signature_for_revision_id(self, revision_id):
1720
return self._real_repository.has_signature_for_revision_id(revision_id)
2442
path = self.bzrdir._path_for_remote_call(self._client)
2444
response = self._call('Repository.has_signature_for_revision_id',
2446
except errors.UnknownSmartMethod:
2448
return self._real_repository.has_signature_for_revision_id(
2450
if response[0] not in ('yes', 'no'):
2451
raise SmartProtocolError('unexpected response code %s' % (response,))
2452
if response[0] == 'yes':
2454
for fallback in self._fallback_repositories:
2455
if fallback.has_signature_for_revision_id(revision_id):
2460
def verify_revision_signature(self, revision_id, gpg_strategy):
2461
if not self.has_signature_for_revision_id(revision_id):
2462
return gpg.SIGNATURE_NOT_SIGNED, None
2463
signature = self.get_signature_text(revision_id)
2465
testament = _mod_testament.Testament.from_revision(self, revision_id)
2466
plaintext = testament.as_short_text()
2468
return gpg_strategy.verify(signature, plaintext)
1722
2470
def item_keys_introduced_by(self, revision_ids, _files_pb=None):
1723
2471
self._ensure_real()
1724
2472
return self._real_repository.item_keys_introduced_by(revision_ids,
1725
2473
_files_pb=_files_pb)
1727
def revision_graph_can_have_wrong_parents(self):
1728
# The answer depends on the remote repo format.
1730
return self._real_repository.revision_graph_can_have_wrong_parents()
1732
2475
def _find_inconsistent_revision_parents(self, revisions_iterator=None):
1733
2476
self._ensure_real()
1734
2477
return self._real_repository._find_inconsistent_revision_parents(
2082
2835
if isinstance(a_bzrdir, RemoteBzrDir):
2083
2836
a_bzrdir._ensure_real()
2084
2837
result = self._custom_format.initialize(a_bzrdir._real_bzrdir,
2838
name, append_revisions_only=append_revisions_only)
2087
2840
# We assume the bzrdir is parameterised; it may not be.
2088
result = self._custom_format.initialize(a_bzrdir, name)
2841
result = self._custom_format.initialize(a_bzrdir, name,
2842
append_revisions_only=append_revisions_only)
2089
2843
if (isinstance(a_bzrdir, RemoteBzrDir) and
2090
2844
not isinstance(result, RemoteBranch)):
2091
2845
result = RemoteBranch(a_bzrdir, a_bzrdir.find_repository(), result,
2095
def initialize(self, a_bzrdir, name=None):
2849
def initialize(self, a_bzrdir, name=None, repository=None,
2850
append_revisions_only=None):
2096
2851
# 1) get the network name to use.
2097
2852
if self._custom_format:
2098
2853
network_name = self._custom_format.network_name()
2100
2855
# Select the current bzrlib default and ask for that.
2101
reference_bzrdir_format = bzrdir.format_registry.get('default')()
2856
reference_bzrdir_format = _mod_bzrdir.format_registry.get('default')()
2102
2857
reference_format = reference_bzrdir_format.get_branch_format()
2103
2858
self._custom_format = reference_format
2104
2859
network_name = reference_format.network_name()
2105
2860
# Being asked to create on a non RemoteBzrDir:
2106
2861
if not isinstance(a_bzrdir, RemoteBzrDir):
2107
return self._vfs_initialize(a_bzrdir, name=name)
2862
return self._vfs_initialize(a_bzrdir, name=name,
2863
append_revisions_only=append_revisions_only)
2108
2864
medium = a_bzrdir._client._medium
2109
2865
if medium._is_remote_before((1, 13)):
2110
return self._vfs_initialize(a_bzrdir, name=name)
2866
return self._vfs_initialize(a_bzrdir, name=name,
2867
append_revisions_only=append_revisions_only)
2111
2868
# Creating on a remote bzr dir.
2112
2869
# 2) try direct creation via RPC
2113
2870
path = a_bzrdir._path_for_remote_call(a_bzrdir._client)
2159
2931
self._ensure_real()
2160
2932
return self._custom_format.supports_set_append_revisions_only()
2934
def _use_default_local_heads_to_fetch(self):
2935
# If the branch format is a metadir format *and* its heads_to_fetch
2936
# implementation is not overridden vs the base class, we can use the
2937
# base class logic rather than use the heads_to_fetch RPC. This is
2938
# usually cheaper in terms of net round trips, as the last-revision and
2939
# tags info fetched is cached and would be fetched anyway.
2941
if isinstance(self._custom_format, branch.BranchFormatMetadir):
2942
branch_class = self._custom_format._branch_class()
2943
heads_to_fetch_impl = branch_class.heads_to_fetch.im_func
2944
if heads_to_fetch_impl is branch.Branch.heads_to_fetch.im_func:
2949
class RemoteBranchStore(config.IniFileStore):
2950
"""Branch store which attempts to use HPSS calls to retrieve branch store.
2952
Note that this is specific to bzr-based formats.
2955
def __init__(self, branch):
2956
super(RemoteBranchStore, self).__init__()
2957
self.branch = branch
2959
self._real_store = None
2961
def lock_write(self, token=None):
2962
return self.branch.lock_write(token)
2965
return self.branch.unlock()
2969
# We need to be able to override the undecorated implementation
2970
self.save_without_locking()
2972
def save_without_locking(self):
2973
super(RemoteBranchStore, self).save()
2975
def external_url(self):
2976
return self.branch.user_url
2978
def _load_content(self):
2979
path = self.branch._remote_path()
2981
response, handler = self.branch._call_expecting_body(
2982
'Branch.get_config_file', path)
2983
except errors.UnknownSmartMethod:
2985
return self._real_store._load_content()
2986
if len(response) and response[0] != 'ok':
2987
raise errors.UnexpectedSmartServerResponse(response)
2988
return handler.read_body_bytes()
2990
def _save_content(self, content):
2991
path = self.branch._remote_path()
2993
response, handler = self.branch._call_with_body_bytes_expecting_body(
2994
'Branch.put_config_file', (path,
2995
self.branch._lock_token, self.branch._repo_lock_token),
2997
except errors.UnknownSmartMethod:
2999
return self._real_store._save_content(content)
3000
handler.cancel_read_body()
3001
if response != ('ok', ):
3002
raise errors.UnexpectedSmartServerResponse(response)
3004
def _ensure_real(self):
3005
self.branch._ensure_real()
3006
if self._real_store is None:
3007
self._real_store = config.BranchStore(self.branch)
2163
3010
class RemoteBranch(branch.Branch, _RpcHelper, lock._RelockDebugMixin):
2164
3011
"""Branch stored on a server accessed by HPSS RPC.
2677
3567
_override_hook_target=self, **kwargs)
2679
3569
@needs_read_lock
2680
def push(self, target, overwrite=False, stop_revision=None):
3570
def push(self, target, overwrite=False, stop_revision=None, lossy=False):
2681
3571
self._ensure_real()
2682
3572
return self._real_branch.push(
2683
target, overwrite=overwrite, stop_revision=stop_revision,
3573
target, overwrite=overwrite, stop_revision=stop_revision, lossy=lossy,
2684
3574
_override_hook_source_branch=self)
2686
3576
def is_locked(self):
2687
3577
return self._lock_count >= 1
2689
3579
@needs_read_lock
3580
def revision_id_to_dotted_revno(self, revision_id):
3581
"""Given a revision id, return its dotted revno.
3583
:return: a tuple like (1,) or (400,1,3).
3586
response = self._call('Branch.revision_id_to_revno',
3587
self._remote_path(), revision_id)
3588
except errors.UnknownSmartMethod:
3590
return self._real_branch.revision_id_to_dotted_revno(revision_id)
3591
if response[0] == 'ok':
3592
return tuple([int(x) for x in response[1:]])
3594
raise errors.UnexpectedSmartServerResponse(response)
2690
3597
def revision_id_to_revno(self, revision_id):
2692
return self._real_branch.revision_id_to_revno(revision_id)
3598
"""Given a revision id on the branch mainline, return its revno.
3603
response = self._call('Branch.revision_id_to_revno',
3604
self._remote_path(), revision_id)
3605
except errors.UnknownSmartMethod:
3607
return self._real_branch.revision_id_to_revno(revision_id)
3608
if response[0] == 'ok':
3609
if len(response) == 2:
3610
return int(response[1])
3611
raise NoSuchRevision(self, revision_id)
3613
raise errors.UnexpectedSmartServerResponse(response)
2694
3615
@needs_write_lock
2695
3616
def set_last_revision_info(self, revno, revision_id):
2696
3617
# XXX: These should be returned by the set_last_revision_info verb
2697
3618
old_revno, old_revid = self.last_revision_info()
2698
3619
self._run_pre_change_branch_tip_hooks(revno, revision_id)
2699
revision_id = ensure_null(revision_id)
3620
if not revision_id or not isinstance(revision_id, basestring):
3621
raise errors.InvalidRevisionId(revision_id=revision_id, branch=self)
2701
3623
response = self._call('Branch.set_last_revision_info',
2702
3624
self._remote_path(), self._lock_token, self._repo_lock_token,
2930
3892
'Missing key %r in context %r', key_err.args[0], context)
2933
if err.error_verb == 'IncompatibleRepositories':
2934
raise errors.IncompatibleRepositories(err.error_args[0],
2935
err.error_args[1], err.error_args[2])
2936
elif err.error_verb == 'NoSuchRevision':
2937
raise NoSuchRevision(find('branch'), err.error_args[0])
2938
elif err.error_verb == 'nosuchrevision':
2939
raise NoSuchRevision(find('repository'), err.error_args[0])
2940
elif err.error_verb == 'nobranch':
2941
if len(err.error_args) >= 1:
2942
extra = err.error_args[0]
2945
raise errors.NotBranchError(path=find('bzrdir').root_transport.base,
2947
elif err.error_verb == 'norepository':
2948
raise errors.NoRepositoryPresent(find('bzrdir'))
2949
elif err.error_verb == 'LockContention':
2950
raise errors.LockContention('(remote lock)')
2951
elif err.error_verb == 'UnlockableTransport':
2952
raise errors.UnlockableTransport(find('bzrdir').root_transport)
2953
elif err.error_verb == 'LockFailed':
2954
raise errors.LockFailed(err.error_args[0], err.error_args[1])
2955
elif err.error_verb == 'TokenMismatch':
2956
raise errors.TokenMismatch(find('token'), '(remote token)')
2957
elif err.error_verb == 'Diverged':
2958
raise errors.DivergedBranches(find('branch'), find('other_branch'))
2959
elif err.error_verb == 'TipChangeRejected':
2960
raise errors.TipChangeRejected(err.error_args[0].decode('utf8'))
2961
elif err.error_verb == 'UnstackableBranchFormat':
2962
raise errors.UnstackableBranchFormat(*err.error_args)
2963
elif err.error_verb == 'UnstackableRepositoryFormat':
2964
raise errors.UnstackableRepositoryFormat(*err.error_args)
2965
elif err.error_verb == 'NotStacked':
2966
raise errors.NotStacked(branch=find('branch'))
2967
elif err.error_verb == 'PermissionDenied':
2969
if len(err.error_args) >= 2:
2970
extra = err.error_args[1]
2973
raise errors.PermissionDenied(path, extra=extra)
2974
elif err.error_verb == 'ReadError':
2976
raise errors.ReadError(path)
2977
elif err.error_verb == 'NoSuchFile':
2979
raise errors.NoSuchFile(path)
2980
elif err.error_verb == 'FileExists':
2981
raise errors.FileExists(err.error_args[0])
2982
elif err.error_verb == 'DirectoryNotEmpty':
2983
raise errors.DirectoryNotEmpty(err.error_args[0])
2984
elif err.error_verb == 'ShortReadvError':
2985
args = err.error_args
2986
raise errors.ShortReadvError(
2987
args[0], int(args[1]), int(args[2]), int(args[3]))
2988
elif err.error_verb in ('UnicodeEncodeError', 'UnicodeDecodeError'):
3896
translator = error_translators.get(err.error_verb)
3900
raise translator(err, find, get_path)
3902
translator = no_context_error_translators.get(err.error_verb)
3904
raise errors.UnknownErrorFromSmartServer(err)
3906
raise translator(err)
3909
error_translators.register('NoSuchRevision',
3910
lambda err, find, get_path: NoSuchRevision(
3911
find('branch'), err.error_args[0]))
3912
error_translators.register('nosuchrevision',
3913
lambda err, find, get_path: NoSuchRevision(
3914
find('repository'), err.error_args[0]))
3916
def _translate_nobranch_error(err, find, get_path):
3917
if len(err.error_args) >= 1:
3918
extra = err.error_args[0]
3921
return errors.NotBranchError(path=find('bzrdir').root_transport.base,
3924
error_translators.register('nobranch', _translate_nobranch_error)
3925
error_translators.register('norepository',
3926
lambda err, find, get_path: errors.NoRepositoryPresent(
3928
error_translators.register('UnlockableTransport',
3929
lambda err, find, get_path: errors.UnlockableTransport(
3930
find('bzrdir').root_transport))
3931
error_translators.register('TokenMismatch',
3932
lambda err, find, get_path: errors.TokenMismatch(
3933
find('token'), '(remote token)'))
3934
error_translators.register('Diverged',
3935
lambda err, find, get_path: errors.DivergedBranches(
3936
find('branch'), find('other_branch')))
3937
error_translators.register('NotStacked',
3938
lambda err, find, get_path: errors.NotStacked(branch=find('branch')))
3940
def _translate_PermissionDenied(err, find, get_path):
3942
if len(err.error_args) >= 2:
3943
extra = err.error_args[1]
3946
return errors.PermissionDenied(path, extra=extra)
3948
error_translators.register('PermissionDenied', _translate_PermissionDenied)
3949
error_translators.register('ReadError',
3950
lambda err, find, get_path: errors.ReadError(get_path()))
3951
error_translators.register('NoSuchFile',
3952
lambda err, find, get_path: errors.NoSuchFile(get_path()))
3953
error_translators.register('TokenLockingNotSupported',
3954
lambda err, find, get_path: errors.TokenLockingNotSupported(
3955
find('repository')))
3956
error_translators.register('UnsuspendableWriteGroup',
3957
lambda err, find, get_path: errors.UnsuspendableWriteGroup(
3958
repository=find('repository')))
3959
error_translators.register('UnresumableWriteGroup',
3960
lambda err, find, get_path: errors.UnresumableWriteGroup(
3961
repository=find('repository'), write_groups=err.error_args[0],
3962
reason=err.error_args[1]))
3963
no_context_error_translators.register('IncompatibleRepositories',
3964
lambda err: errors.IncompatibleRepositories(
3965
err.error_args[0], err.error_args[1], err.error_args[2]))
3966
no_context_error_translators.register('LockContention',
3967
lambda err: errors.LockContention('(remote lock)'))
3968
no_context_error_translators.register('LockFailed',
3969
lambda err: errors.LockFailed(err.error_args[0], err.error_args[1]))
3970
no_context_error_translators.register('TipChangeRejected',
3971
lambda err: errors.TipChangeRejected(err.error_args[0].decode('utf8')))
3972
no_context_error_translators.register('UnstackableBranchFormat',
3973
lambda err: errors.UnstackableBranchFormat(*err.error_args))
3974
no_context_error_translators.register('UnstackableRepositoryFormat',
3975
lambda err: errors.UnstackableRepositoryFormat(*err.error_args))
3976
no_context_error_translators.register('FileExists',
3977
lambda err: errors.FileExists(err.error_args[0]))
3978
no_context_error_translators.register('DirectoryNotEmpty',
3979
lambda err: errors.DirectoryNotEmpty(err.error_args[0]))
3981
def _translate_short_readv_error(err):
3982
args = err.error_args
3983
return errors.ShortReadvError(args[0], int(args[1]), int(args[2]),
3986
no_context_error_translators.register('ShortReadvError',
3987
_translate_short_readv_error)
3989
def _translate_unicode_error(err):
2989
3990
encoding = str(err.error_args[0]) # encoding must always be a string
2990
3991
val = err.error_args[1]
2991
3992
start = int(err.error_args[2])