89
# Note: RemoteBzrDirFormat is in bzrdir.py
91
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):
92
405
"""Control directory on a remote server, accessed via bzr:// or similar."""
94
407
def __init__(self, transport, format, _client=None, _force_probe=False):
1195
1711
raise errors.UnexpectedSmartServerResponse(response)
1197
1714
def sprout(self, to_bzrdir, revision_id=None):
1198
# TODO: Option to control what format is created?
1200
dest_repo = self._real_repository._format.initialize(to_bzrdir,
1715
"""Create a descendent repository for new development.
1717
Unlike clone, this does not copy the settings of the repository.
1719
dest_repo = self._create_sprouting_repo(to_bzrdir, shared=False)
1202
1720
dest_repo.fetch(self, revision_id=revision_id)
1203
1721
return dest_repo
1723
def _create_sprouting_repo(self, a_bzrdir, shared):
1724
if not isinstance(a_bzrdir._format, self.bzrdir._format.__class__):
1725
# use target default format.
1726
dest_repo = a_bzrdir.create_repository()
1728
# Most control formats need the repository to be specifically
1729
# created, but on some old all-in-one formats it's not needed
1731
dest_repo = self._format.initialize(a_bzrdir, shared=shared)
1732
except errors.UninitializableFormat:
1733
dest_repo = a_bzrdir.open_repository()
1205
1736
### These methods are just thin shims to the VFS object for now.
1207
1739
def revision_tree(self, revision_id):
1209
return self._real_repository.revision_tree(revision_id)
1740
revision_id = _mod_revision.ensure_null(revision_id)
1741
if revision_id == _mod_revision.NULL_REVISION:
1742
return InventoryRevisionTree(self,
1743
Inventory(root_id=None), _mod_revision.NULL_REVISION)
1745
return list(self.revision_trees([revision_id]))[0]
1211
1747
def get_serializer_format(self):
1213
return self._real_repository.get_serializer_format()
1748
path = self.bzrdir._path_for_remote_call(self._client)
1750
response = self._call('VersionedFileRepository.get_serializer_format',
1752
except errors.UnknownSmartMethod:
1754
return self._real_repository.get_serializer_format()
1755
if response[0] != 'ok':
1756
raise errors.UnexpectedSmartServerResponse(response)
1215
1759
def get_commit_builder(self, branch, parents, config, timestamp=None,
1216
1760
timezone=None, committer=None, revprops=None,
1761
revision_id=None, lossy=False):
1218
1762
# FIXME: It ought to be possible to call this without immediately
1219
1763
# triggering _ensure_real. For now it's the easiest thing to do.
1220
1764
self._ensure_real()
1221
1765
real_repo = self._real_repository
1222
1766
builder = real_repo.get_commit_builder(branch, parents,
1223
1767
config, timestamp=timestamp, timezone=timezone,
1224
committer=committer, revprops=revprops, revision_id=revision_id)
1768
committer=committer, revprops=revprops,
1769
revision_id=revision_id, lossy=lossy)
1227
1772
def add_fallback_repository(self, repository):
1328
1881
included_keys = result_set.intersection(result_parents)
1329
1882
start_keys = result_set.difference(included_keys)
1330
1883
exclude_keys = result_parents.difference(result_set)
1331
result = graph.SearchResult(start_keys, exclude_keys,
1884
result = vf_search.SearchResult(start_keys, exclude_keys,
1332
1885
len(result_set), result_set)
1335
1888
@needs_read_lock
1336
def search_missing_revision_ids(self, other, revision_id=None, find_ghosts=True):
1889
def search_missing_revision_ids(self, other,
1890
revision_id=symbol_versioning.DEPRECATED_PARAMETER,
1891
find_ghosts=True, revision_ids=None, if_present_ids=None,
1337
1893
"""Return the revision ids that other has that this does not.
1339
1895
These are returned in topological order.
1341
1897
revision_id: only return revision ids included by revision_id.
1343
return repository.InterRepository.get(
1344
other, self).search_missing_revision_ids(revision_id, find_ghosts)
1899
if symbol_versioning.deprecated_passed(revision_id):
1900
symbol_versioning.warn(
1901
'search_missing_revision_ids(revision_id=...) was '
1902
'deprecated in 2.4. Use revision_ids=[...] instead.',
1903
DeprecationWarning, stacklevel=2)
1904
if revision_ids is not None:
1905
raise AssertionError(
1906
'revision_ids is mutually exclusive with revision_id')
1907
if revision_id is not None:
1908
revision_ids = [revision_id]
1909
inter_repo = _mod_repository.InterRepository.get(other, self)
1910
return inter_repo.search_missing_revision_ids(
1911
find_ghosts=find_ghosts, revision_ids=revision_ids,
1912
if_present_ids=if_present_ids, limit=limit)
1346
def fetch(self, source, revision_id=None, pb=None, find_ghosts=False,
1914
def fetch(self, source, revision_id=None, find_ghosts=False,
1347
1915
fetch_spec=None):
1348
1916
# No base implementation to use as RemoteRepository is not a subclass
1349
1917
# of Repository; so this is a copy of Repository.fetch().
1388
1962
return self._real_repository._get_versioned_file_checker(
1389
1963
revisions, revision_versions_cache)
1965
def _iter_files_bytes_rpc(self, desired_files, absent):
1966
path = self.bzrdir._path_for_remote_call(self._client)
1969
for (file_id, revid, identifier) in desired_files:
1970
lines.append("%s\0%s" % (
1971
osutils.safe_file_id(file_id),
1972
osutils.safe_revision_id(revid)))
1973
identifiers.append(identifier)
1974
(response_tuple, response_handler) = (
1975
self._call_with_body_bytes_expecting_body(
1976
"Repository.iter_files_bytes", (path, ), "\n".join(lines)))
1977
if response_tuple != ('ok', ):
1978
response_handler.cancel_read_body()
1979
raise errors.UnexpectedSmartServerResponse(response_tuple)
1980
byte_stream = response_handler.read_streamed_body()
1981
def decompress_stream(start, byte_stream, unused):
1982
decompressor = zlib.decompressobj()
1983
yield decompressor.decompress(start)
1984
while decompressor.unused_data == "":
1986
data = byte_stream.next()
1987
except StopIteration:
1989
yield decompressor.decompress(data)
1990
yield decompressor.flush()
1991
unused.append(decompressor.unused_data)
1994
while not "\n" in unused:
1995
unused += byte_stream.next()
1996
header, rest = unused.split("\n", 1)
1997
args = header.split("\0")
1998
if args[0] == "absent":
1999
absent[identifiers[int(args[3])]] = (args[1], args[2])
2002
elif args[0] == "ok":
2005
raise errors.UnexpectedSmartServerResponse(args)
2007
yield (identifiers[idx],
2008
decompress_stream(rest, byte_stream, unused_chunks))
2009
unused = "".join(unused_chunks)
1391
2011
def iter_files_bytes(self, desired_files):
1392
2012
"""See Repository.iter_file_bytes.
1395
return self._real_repository.iter_files_bytes(desired_files)
2016
for (identifier, bytes_iterator) in self._iter_files_bytes_rpc(
2017
desired_files, absent):
2018
yield identifier, bytes_iterator
2019
for fallback in self._fallback_repositories:
2022
desired_files = [(key[0], key[1], identifier) for
2023
(identifier, key) in absent.iteritems()]
2024
for (identifier, bytes_iterator) in fallback.iter_files_bytes(desired_files):
2025
del absent[identifier]
2026
yield identifier, bytes_iterator
2028
# There may be more missing items, but raise an exception
2030
missing_identifier = absent.keys()[0]
2031
missing_key = absent[missing_identifier]
2032
raise errors.RevisionNotPresent(revision_id=missing_key[1],
2033
file_id=missing_key[0])
2034
except errors.UnknownSmartMethod:
2036
for (identifier, bytes_iterator) in (
2037
self._real_repository.iter_files_bytes(desired_files)):
2038
yield identifier, bytes_iterator
2040
def get_cached_parent_map(self, revision_ids):
2041
"""See bzrlib.CachingParentsProvider.get_cached_parent_map"""
2042
return self._unstacked_provider.get_cached_parent_map(revision_ids)
1397
2044
def get_parent_map(self, revision_ids):
1398
2045
"""See bzrlib.Graph.get_parent_map()."""
1532
2168
@needs_read_lock
1533
2169
def get_signature_text(self, revision_id):
1535
return self._real_repository.get_signature_text(revision_id)
2170
path = self.bzrdir._path_for_remote_call(self._client)
2172
response_tuple, response_handler = self._call_expecting_body(
2173
'Repository.get_revision_signature_text', path, revision_id)
2174
except errors.UnknownSmartMethod:
2176
return self._real_repository.get_signature_text(revision_id)
2177
except errors.NoSuchRevision, err:
2178
for fallback in self._fallback_repositories:
2180
return fallback.get_signature_text(revision_id)
2181
except errors.NoSuchRevision:
2185
if response_tuple[0] != 'ok':
2186
raise errors.UnexpectedSmartServerResponse(response_tuple)
2187
return response_handler.read_body_bytes()
1537
2189
@needs_read_lock
1538
2190
def _get_inventory_xml(self, revision_id):
1539
2191
self._ensure_real()
1540
2192
return self._real_repository._get_inventory_xml(revision_id)
1542
2195
def reconcile(self, other=None, thorough=False):
1544
return self._real_repository.reconcile(other=other, thorough=thorough)
2196
from bzrlib.reconcile import RepoReconciler
2197
path = self.bzrdir._path_for_remote_call(self._client)
2199
response, handler = self._call_expecting_body(
2200
'Repository.reconcile', path, self._lock_token)
2201
except (errors.UnknownSmartMethod, errors.TokenLockingNotSupported):
2203
return self._real_repository.reconcile(other=other, thorough=thorough)
2204
if response != ('ok', ):
2205
raise errors.UnexpectedSmartServerResponse(response)
2206
body = handler.read_body_bytes()
2207
result = RepoReconciler(self)
2208
for line in body.split('\n'):
2211
key, val_text = line.split(':')
2212
if key == "garbage_inventories":
2213
result.garbage_inventories = int(val_text)
2214
elif key == "inconsistent_parents":
2215
result.inconsistent_parents = int(val_text)
2217
mutter("unknown reconcile key %r" % key)
1546
2220
def all_revision_ids(self):
1548
return self._real_repository.all_revision_ids()
2221
path = self.bzrdir._path_for_remote_call(self._client)
2223
response_tuple, response_handler = self._call_expecting_body(
2224
"Repository.all_revision_ids", path)
2225
except errors.UnknownSmartMethod:
2227
return self._real_repository.all_revision_ids()
2228
if response_tuple != ("ok", ):
2229
raise errors.UnexpectedSmartServerResponse(response_tuple)
2230
revids = set(response_handler.read_body_bytes().splitlines())
2231
for fallback in self._fallback_repositories:
2232
revids.update(set(fallback.all_revision_ids()))
1550
2235
@needs_read_lock
1551
2236
def get_deltas_for_revisions(self, revisions, specific_fileids=None):
1680
2379
self._ensure_real()
1681
2380
return self._real_repository.texts
2382
def _iter_revisions_rpc(self, revision_ids):
2383
body = "\n".join(revision_ids)
2384
path = self.bzrdir._path_for_remote_call(self._client)
2385
response_tuple, response_handler = (
2386
self._call_with_body_bytes_expecting_body(
2387
"Repository.iter_revisions", (path, ), body))
2388
if response_tuple[0] != "ok":
2389
raise errors.UnexpectedSmartServerResponse(response_tuple)
2390
serializer_format = response_tuple[1]
2391
serializer = serializer_format_registry.get(serializer_format)
2392
byte_stream = response_handler.read_streamed_body()
2393
decompressor = zlib.decompressobj()
2395
for bytes in byte_stream:
2396
chunks.append(decompressor.decompress(bytes))
2397
if decompressor.unused_data != "":
2398
chunks.append(decompressor.flush())
2399
yield serializer.read_revision_from_string("".join(chunks))
2400
unused = decompressor.unused_data
2401
decompressor = zlib.decompressobj()
2402
chunks = [decompressor.decompress(unused)]
2403
chunks.append(decompressor.flush())
2404
text = "".join(chunks)
2406
yield serializer.read_revision_from_string("".join(chunks))
1683
2408
@needs_read_lock
1684
2409
def get_revisions(self, revision_ids):
1686
return self._real_repository.get_revisions(revision_ids)
2410
if revision_ids is None:
2411
revision_ids = self.all_revision_ids()
2413
for rev_id in revision_ids:
2414
if not rev_id or not isinstance(rev_id, basestring):
2415
raise errors.InvalidRevisionId(
2416
revision_id=rev_id, branch=self)
2418
missing = set(revision_ids)
2420
for rev in self._iter_revisions_rpc(revision_ids):
2421
missing.remove(rev.revision_id)
2422
revs[rev.revision_id] = rev
2423
except errors.UnknownSmartMethod:
2425
return self._real_repository.get_revisions(revision_ids)
2426
for fallback in self._fallback_repositories:
2429
for revid in list(missing):
2430
# XXX JRV 2011-11-20: It would be nice if there was a
2431
# public method on Repository that could be used to query
2432
# for revision objects *without* failing completely if one
2433
# was missing. There is VersionedFileRepository._iter_revisions,
2434
# but unfortunately that's private and not provided by
2435
# all repository implementations.
2437
revs[revid] = fallback.get_revision(revid)
2438
except errors.NoSuchRevision:
2441
missing.remove(revid)
2443
raise errors.NoSuchRevision(self, list(missing)[0])
2444
return [revs[revid] for revid in revision_ids]
1688
2446
def supports_rich_root(self):
1689
2447
return self._format.rich_root_data
2449
@symbol_versioning.deprecated_method(symbol_versioning.deprecated_in((2, 4, 0)))
1691
2450
def iter_reverse_revision_history(self, revision_id):
1692
2451
self._ensure_real()
1693
2452
return self._real_repository.iter_reverse_revision_history(revision_id)
1696
2455
def _serializer(self):
1697
2456
return self._format._serializer
1699
2459
def store_revision_signature(self, gpg_strategy, plaintext, revision_id):
1701
return self._real_repository.store_revision_signature(
1702
gpg_strategy, plaintext, revision_id)
2460
signature = gpg_strategy.sign(plaintext)
2461
self.add_signature_text(revision_id, signature)
1704
2463
def add_signature_text(self, revision_id, signature):
1706
return self._real_repository.add_signature_text(revision_id, signature)
2464
if self._real_repository:
2465
# If there is a real repository the write group will
2466
# be in the real repository as well, so use that:
2468
return self._real_repository.add_signature_text(
2469
revision_id, signature)
2470
path = self.bzrdir._path_for_remote_call(self._client)
2471
response, handler = self._call_with_body_bytes_expecting_body(
2472
'Repository.add_signature_text', (path, self._lock_token,
2473
revision_id) + tuple(self._write_group_tokens), signature)
2474
handler.cancel_read_body()
2476
if response[0] != 'ok':
2477
raise errors.UnexpectedSmartServerResponse(response)
2478
self._write_group_tokens = response[1:]
1708
2480
def has_signature_for_revision_id(self, revision_id):
1710
return self._real_repository.has_signature_for_revision_id(revision_id)
2481
path = self.bzrdir._path_for_remote_call(self._client)
2483
response = self._call('Repository.has_signature_for_revision_id',
2485
except errors.UnknownSmartMethod:
2487
return self._real_repository.has_signature_for_revision_id(
2489
if response[0] not in ('yes', 'no'):
2490
raise SmartProtocolError('unexpected response code %s' % (response,))
2491
if response[0] == 'yes':
2493
for fallback in self._fallback_repositories:
2494
if fallback.has_signature_for_revision_id(revision_id):
2499
def verify_revision_signature(self, revision_id, gpg_strategy):
2500
if not self.has_signature_for_revision_id(revision_id):
2501
return gpg.SIGNATURE_NOT_SIGNED, None
2502
signature = self.get_signature_text(revision_id)
2504
testament = _mod_testament.Testament.from_revision(self, revision_id)
2505
plaintext = testament.as_short_text()
2507
return gpg_strategy.verify(signature, plaintext)
1712
2509
def item_keys_introduced_by(self, revision_ids, _files_pb=None):
1713
2510
self._ensure_real()
1714
2511
return self._real_repository.item_keys_introduced_by(revision_ids,
1715
2512
_files_pb=_files_pb)
1717
def revision_graph_can_have_wrong_parents(self):
1718
# The answer depends on the remote repo format.
1720
return self._real_repository.revision_graph_can_have_wrong_parents()
1722
2514
def _find_inconsistent_revision_parents(self, revisions_iterator=None):
1723
2515
self._ensure_real()
1724
2516
return self._real_repository._find_inconsistent_revision_parents(
2071
2874
if isinstance(a_bzrdir, RemoteBzrDir):
2072
2875
a_bzrdir._ensure_real()
2073
2876
result = self._custom_format.initialize(a_bzrdir._real_bzrdir,
2877
name, append_revisions_only=append_revisions_only)
2076
2879
# We assume the bzrdir is parameterised; it may not be.
2077
result = self._custom_format.initialize(a_bzrdir, name)
2880
result = self._custom_format.initialize(a_bzrdir, name,
2881
append_revisions_only=append_revisions_only)
2078
2882
if (isinstance(a_bzrdir, RemoteBzrDir) and
2079
2883
not isinstance(result, RemoteBranch)):
2080
2884
result = RemoteBranch(a_bzrdir, a_bzrdir.find_repository(), result,
2084
def initialize(self, a_bzrdir, name=None):
2888
def initialize(self, a_bzrdir, name=None, repository=None,
2889
append_revisions_only=None):
2085
2890
# 1) get the network name to use.
2086
2891
if self._custom_format:
2087
2892
network_name = self._custom_format.network_name()
2089
2894
# Select the current bzrlib default and ask for that.
2090
reference_bzrdir_format = bzrdir.format_registry.get('default')()
2895
reference_bzrdir_format = _mod_bzrdir.format_registry.get('default')()
2091
2896
reference_format = reference_bzrdir_format.get_branch_format()
2092
2897
self._custom_format = reference_format
2093
2898
network_name = reference_format.network_name()
2094
2899
# Being asked to create on a non RemoteBzrDir:
2095
2900
if not isinstance(a_bzrdir, RemoteBzrDir):
2096
return self._vfs_initialize(a_bzrdir, name=name)
2901
return self._vfs_initialize(a_bzrdir, name=name,
2902
append_revisions_only=append_revisions_only)
2097
2903
medium = a_bzrdir._client._medium
2098
2904
if medium._is_remote_before((1, 13)):
2099
return self._vfs_initialize(a_bzrdir, name=name)
2905
return self._vfs_initialize(a_bzrdir, name=name,
2906
append_revisions_only=append_revisions_only)
2100
2907
# Creating on a remote bzr dir.
2101
2908
# 2) try direct creation via RPC
2102
2909
path = a_bzrdir._path_for_remote_call(a_bzrdir._client)
2148
2970
self._ensure_real()
2149
2971
return self._custom_format.supports_set_append_revisions_only()
2973
def _use_default_local_heads_to_fetch(self):
2974
# If the branch format is a metadir format *and* its heads_to_fetch
2975
# implementation is not overridden vs the base class, we can use the
2976
# base class logic rather than use the heads_to_fetch RPC. This is
2977
# usually cheaper in terms of net round trips, as the last-revision and
2978
# tags info fetched is cached and would be fetched anyway.
2980
if isinstance(self._custom_format, branch.BranchFormatMetadir):
2981
branch_class = self._custom_format._branch_class()
2982
heads_to_fetch_impl = branch_class.heads_to_fetch.im_func
2983
if heads_to_fetch_impl is branch.Branch.heads_to_fetch.im_func:
2988
class RemoteBranchStore(config.IniFileStore):
2989
"""Branch store which attempts to use HPSS calls to retrieve branch store.
2991
Note that this is specific to bzr-based formats.
2994
def __init__(self, branch):
2995
super(RemoteBranchStore, self).__init__()
2996
self.branch = branch
2998
self._real_store = None
3000
def lock_write(self, token=None):
3001
return self.branch.lock_write(token)
3004
return self.branch.unlock()
3008
# We need to be able to override the undecorated implementation
3009
self.save_without_locking()
3011
def save_without_locking(self):
3012
super(RemoteBranchStore, self).save()
3014
def external_url(self):
3015
return self.branch.user_url
3017
def _load_content(self):
3018
path = self.branch._remote_path()
3020
response, handler = self.branch._call_expecting_body(
3021
'Branch.get_config_file', path)
3022
except errors.UnknownSmartMethod:
3024
return self._real_store._load_content()
3025
if len(response) and response[0] != 'ok':
3026
raise errors.UnexpectedSmartServerResponse(response)
3027
return handler.read_body_bytes()
3029
def _save_content(self, content):
3030
path = self.branch._remote_path()
3032
response, handler = self.branch._call_with_body_bytes_expecting_body(
3033
'Branch.put_config_file', (path,
3034
self.branch._lock_token, self.branch._repo_lock_token),
3036
except errors.UnknownSmartMethod:
3038
return self._real_store._save_content(content)
3039
handler.cancel_read_body()
3040
if response != ('ok', ):
3041
raise errors.UnexpectedSmartServerResponse(response)
3043
def _ensure_real(self):
3044
self.branch._ensure_real()
3045
if self._real_store is None:
3046
self._real_store = config.BranchStore(self.branch)
2152
3049
class RemoteBranch(branch.Branch, _RpcHelper, lock._RelockDebugMixin):
2153
3050
"""Branch stored on a server accessed by HPSS RPC.
2654
3595
_override_hook_target=self, **kwargs)
2656
3597
@needs_read_lock
2657
def push(self, target, overwrite=False, stop_revision=None):
3598
def push(self, target, overwrite=False, stop_revision=None, lossy=False):
2658
3599
self._ensure_real()
2659
3600
return self._real_branch.push(
2660
target, overwrite=overwrite, stop_revision=stop_revision,
3601
target, overwrite=overwrite, stop_revision=stop_revision, lossy=lossy,
2661
3602
_override_hook_source_branch=self)
2663
3604
def is_locked(self):
2664
3605
return self._lock_count >= 1
2666
3607
@needs_read_lock
3608
def revision_id_to_dotted_revno(self, revision_id):
3609
"""Given a revision id, return its dotted revno.
3611
:return: a tuple like (1,) or (400,1,3).
3614
response = self._call('Branch.revision_id_to_revno',
3615
self._remote_path(), revision_id)
3616
except errors.UnknownSmartMethod:
3618
return self._real_branch.revision_id_to_dotted_revno(revision_id)
3619
if response[0] == 'ok':
3620
return tuple([int(x) for x in response[1:]])
3622
raise errors.UnexpectedSmartServerResponse(response)
2667
3625
def revision_id_to_revno(self, revision_id):
2669
return self._real_branch.revision_id_to_revno(revision_id)
3626
"""Given a revision id on the branch mainline, return its revno.
3631
response = self._call('Branch.revision_id_to_revno',
3632
self._remote_path(), revision_id)
3633
except errors.UnknownSmartMethod:
3635
return self._real_branch.revision_id_to_revno(revision_id)
3636
if response[0] == 'ok':
3637
if len(response) == 2:
3638
return int(response[1])
3639
raise NoSuchRevision(self, revision_id)
3641
raise errors.UnexpectedSmartServerResponse(response)
2671
3643
@needs_write_lock
2672
3644
def set_last_revision_info(self, revno, revision_id):
2673
3645
# XXX: These should be returned by the set_last_revision_info verb
2674
3646
old_revno, old_revid = self.last_revision_info()
2675
3647
self._run_pre_change_branch_tip_hooks(revno, revision_id)
2676
revision_id = ensure_null(revision_id)
3648
if not revision_id or not isinstance(revision_id, basestring):
3649
raise errors.InvalidRevisionId(revision_id=revision_id, branch=self)
2678
3651
response = self._call('Branch.set_last_revision_info',
2679
3652
self._remote_path(), self._lock_token, self._repo_lock_token,
2774
3784
medium = self._branch._client._medium
2775
3785
if medium._is_remote_before((1, 14)):
2776
3786
return self._vfs_set_option(value, name, section)
3787
if isinstance(value, dict):
3788
if medium._is_remote_before((2, 2)):
3789
return self._vfs_set_option(value, name, section)
3790
return self._set_config_option_dict(value, name, section)
3792
return self._set_config_option(value, name, section)
3794
def _set_config_option(self, value, name, section):
2778
3796
path = self._branch._remote_path()
2779
3797
response = self._branch._client.call('Branch.set_config_option',
2780
3798
path, self._branch._lock_token, self._branch._repo_lock_token,
2781
3799
value.encode('utf8'), name, section or '')
2782
3800
except errors.UnknownSmartMethod:
3801
medium = self._branch._client._medium
2783
3802
medium._remember_remote_is_before((1, 14))
2784
3803
return self._vfs_set_option(value, name, section)
2785
3804
if response != ():
2786
3805
raise errors.UnexpectedSmartServerResponse(response)
3807
def _serialize_option_dict(self, option_dict):
3809
for key, value in option_dict.items():
3810
if isinstance(key, unicode):
3811
key = key.encode('utf8')
3812
if isinstance(value, unicode):
3813
value = value.encode('utf8')
3814
utf8_dict[key] = value
3815
return bencode.bencode(utf8_dict)
3817
def _set_config_option_dict(self, value, name, section):
3819
path = self._branch._remote_path()
3820
serialised_dict = self._serialize_option_dict(value)
3821
response = self._branch._client.call(
3822
'Branch.set_config_option_dict',
3823
path, self._branch._lock_token, self._branch._repo_lock_token,
3824
serialised_dict, name, section or '')
3825
except errors.UnknownSmartMethod:
3826
medium = self._branch._client._medium
3827
medium._remember_remote_is_before((2, 2))
3828
return self._vfs_set_option(value, name, section)
3830
raise errors.UnexpectedSmartServerResponse(response)
2788
3832
def _real_object(self):
2789
3833
self._branch._ensure_real()
2790
3834
return self._branch._real_branch
2873
3920
'Missing key %r in context %r', key_err.args[0], context)
2876
if err.error_verb == 'IncompatibleRepositories':
2877
raise errors.IncompatibleRepositories(err.error_args[0],
2878
err.error_args[1], err.error_args[2])
2879
elif err.error_verb == 'NoSuchRevision':
2880
raise NoSuchRevision(find('branch'), err.error_args[0])
2881
elif err.error_verb == 'nosuchrevision':
2882
raise NoSuchRevision(find('repository'), err.error_args[0])
2883
elif err.error_verb == 'nobranch':
2884
if len(err.error_args) >= 1:
2885
extra = err.error_args[0]
2888
raise errors.NotBranchError(path=find('bzrdir').root_transport.base,
2890
elif err.error_verb == 'norepository':
2891
raise errors.NoRepositoryPresent(find('bzrdir'))
2892
elif err.error_verb == 'LockContention':
2893
raise errors.LockContention('(remote lock)')
2894
elif err.error_verb == 'UnlockableTransport':
2895
raise errors.UnlockableTransport(find('bzrdir').root_transport)
2896
elif err.error_verb == 'LockFailed':
2897
raise errors.LockFailed(err.error_args[0], err.error_args[1])
2898
elif err.error_verb == 'TokenMismatch':
2899
raise errors.TokenMismatch(find('token'), '(remote token)')
2900
elif err.error_verb == 'Diverged':
2901
raise errors.DivergedBranches(find('branch'), find('other_branch'))
2902
elif err.error_verb == 'TipChangeRejected':
2903
raise errors.TipChangeRejected(err.error_args[0].decode('utf8'))
2904
elif err.error_verb == 'UnstackableBranchFormat':
2905
raise errors.UnstackableBranchFormat(*err.error_args)
2906
elif err.error_verb == 'UnstackableRepositoryFormat':
2907
raise errors.UnstackableRepositoryFormat(*err.error_args)
2908
elif err.error_verb == 'NotStacked':
2909
raise errors.NotStacked(branch=find('branch'))
2910
elif err.error_verb == 'PermissionDenied':
2912
if len(err.error_args) >= 2:
2913
extra = err.error_args[1]
2916
raise errors.PermissionDenied(path, extra=extra)
2917
elif err.error_verb == 'ReadError':
2919
raise errors.ReadError(path)
2920
elif err.error_verb == 'NoSuchFile':
2922
raise errors.NoSuchFile(path)
2923
elif err.error_verb == 'FileExists':
2924
raise errors.FileExists(err.error_args[0])
2925
elif err.error_verb == 'DirectoryNotEmpty':
2926
raise errors.DirectoryNotEmpty(err.error_args[0])
2927
elif err.error_verb == 'ShortReadvError':
2928
args = err.error_args
2929
raise errors.ShortReadvError(
2930
args[0], int(args[1]), int(args[2]), int(args[3]))
2931
elif err.error_verb in ('UnicodeEncodeError', 'UnicodeDecodeError'):
3924
translator = error_translators.get(err.error_verb)
3928
raise translator(err, find, get_path)
3930
translator = no_context_error_translators.get(err.error_verb)
3932
raise errors.UnknownErrorFromSmartServer(err)
3934
raise translator(err)
3937
error_translators.register('NoSuchRevision',
3938
lambda err, find, get_path: NoSuchRevision(
3939
find('branch'), err.error_args[0]))
3940
error_translators.register('nosuchrevision',
3941
lambda err, find, get_path: NoSuchRevision(
3942
find('repository'), err.error_args[0]))
3944
def _translate_nobranch_error(err, find, get_path):
3945
if len(err.error_args) >= 1:
3946
extra = err.error_args[0]
3949
return errors.NotBranchError(path=find('bzrdir').root_transport.base,
3952
error_translators.register('nobranch', _translate_nobranch_error)
3953
error_translators.register('norepository',
3954
lambda err, find, get_path: errors.NoRepositoryPresent(
3956
error_translators.register('UnlockableTransport',
3957
lambda err, find, get_path: errors.UnlockableTransport(
3958
find('bzrdir').root_transport))
3959
error_translators.register('TokenMismatch',
3960
lambda err, find, get_path: errors.TokenMismatch(
3961
find('token'), '(remote token)'))
3962
error_translators.register('Diverged',
3963
lambda err, find, get_path: errors.DivergedBranches(
3964
find('branch'), find('other_branch')))
3965
error_translators.register('NotStacked',
3966
lambda err, find, get_path: errors.NotStacked(branch=find('branch')))
3968
def _translate_PermissionDenied(err, find, get_path):
3970
if len(err.error_args) >= 2:
3971
extra = err.error_args[1]
3974
return errors.PermissionDenied(path, extra=extra)
3976
error_translators.register('PermissionDenied', _translate_PermissionDenied)
3977
error_translators.register('ReadError',
3978
lambda err, find, get_path: errors.ReadError(get_path()))
3979
error_translators.register('NoSuchFile',
3980
lambda err, find, get_path: errors.NoSuchFile(get_path()))
3981
error_translators.register('TokenLockingNotSupported',
3982
lambda err, find, get_path: errors.TokenLockingNotSupported(
3983
find('repository')))
3984
error_translators.register('UnsuspendableWriteGroup',
3985
lambda err, find, get_path: errors.UnsuspendableWriteGroup(
3986
repository=find('repository')))
3987
error_translators.register('UnresumableWriteGroup',
3988
lambda err, find, get_path: errors.UnresumableWriteGroup(
3989
repository=find('repository'), write_groups=err.error_args[0],
3990
reason=err.error_args[1]))
3991
no_context_error_translators.register('IncompatibleRepositories',
3992
lambda err: errors.IncompatibleRepositories(
3993
err.error_args[0], err.error_args[1], err.error_args[2]))
3994
no_context_error_translators.register('LockContention',
3995
lambda err: errors.LockContention('(remote lock)'))
3996
no_context_error_translators.register('LockFailed',
3997
lambda err: errors.LockFailed(err.error_args[0], err.error_args[1]))
3998
no_context_error_translators.register('TipChangeRejected',
3999
lambda err: errors.TipChangeRejected(err.error_args[0].decode('utf8')))
4000
no_context_error_translators.register('UnstackableBranchFormat',
4001
lambda err: errors.UnstackableBranchFormat(*err.error_args))
4002
no_context_error_translators.register('UnstackableRepositoryFormat',
4003
lambda err: errors.UnstackableRepositoryFormat(*err.error_args))
4004
no_context_error_translators.register('FileExists',
4005
lambda err: errors.FileExists(err.error_args[0]))
4006
no_context_error_translators.register('DirectoryNotEmpty',
4007
lambda err: errors.DirectoryNotEmpty(err.error_args[0]))
4009
def _translate_short_readv_error(err):
4010
args = err.error_args
4011
return errors.ShortReadvError(args[0], int(args[1]), int(args[2]),
4014
no_context_error_translators.register('ShortReadvError',
4015
_translate_short_readv_error)
4017
def _translate_unicode_error(err):
2932
4018
encoding = str(err.error_args[0]) # encoding must always be a string
2933
4019
val = err.error_args[1]
2934
4020
start = int(err.error_args[2])