89
# Note: RemoteBzrDirFormat is in bzrdir.py
91
class RemoteBzrDir(BzrDir, _RpcHelper):
103
# Note that RemoteBzrDirProber lives in bzrlib.bzrdir so bzrlib.remote
104
# does not have to be imported unless a remote format is involved.
106
class RemoteBzrDirFormat(_mod_bzrdir.BzrDirMetaFormat1):
107
"""Format representing bzrdirs accessed via a smart server"""
109
supports_workingtrees = False
112
_mod_bzrdir.BzrDirMetaFormat1.__init__(self)
113
# XXX: It's a bit ugly that the network name is here, because we'd
114
# like to believe that format objects are stateless or at least
115
# immutable, However, we do at least avoid mutating the name after
116
# it's returned. See <https://bugs.launchpad.net/bzr/+bug/504102>
117
self._network_name = None
120
return "%s(_network_name=%r)" % (self.__class__.__name__,
123
def get_format_description(self):
124
if self._network_name:
126
real_format = controldir.network_format_registry.get(
131
return 'Remote: ' + real_format.get_format_description()
132
return 'bzr remote bzrdir'
134
def get_format_string(self):
135
raise NotImplementedError(self.get_format_string)
137
def network_name(self):
138
if self._network_name:
139
return self._network_name
141
raise AssertionError("No network name set.")
143
def initialize_on_transport(self, transport):
145
# hand off the request to the smart server
146
client_medium = transport.get_smart_medium()
147
except errors.NoSmartMedium:
148
# TODO: lookup the local format from a server hint.
149
local_dir_format = _mod_bzrdir.BzrDirMetaFormat1()
150
return local_dir_format.initialize_on_transport(transport)
151
client = _SmartClient(client_medium)
152
path = client.remote_path_from_transport(transport)
154
response = client.call('BzrDirFormat.initialize', path)
155
except errors.ErrorFromSmartServer, err:
156
_translate_error(err, path=path)
157
if response[0] != 'ok':
158
raise errors.SmartProtocolError('unexpected response code %s' % (response,))
159
format = RemoteBzrDirFormat()
160
self._supply_sub_formats_to(format)
161
return RemoteBzrDir(transport, format)
163
def parse_NoneTrueFalse(self, arg):
170
raise AssertionError("invalid arg %r" % arg)
172
def _serialize_NoneTrueFalse(self, arg):
179
def _serialize_NoneString(self, arg):
182
def initialize_on_transport_ex(self, transport, use_existing_dir=False,
183
create_prefix=False, force_new_repo=False, stacked_on=None,
184
stack_on_pwd=None, repo_format_name=None, make_working_trees=None,
187
# hand off the request to the smart server
188
client_medium = transport.get_smart_medium()
189
except errors.NoSmartMedium:
192
# Decline to open it if the server doesn't support our required
193
# version (3) so that the VFS-based transport will do it.
194
if client_medium.should_probe():
196
server_version = client_medium.protocol_version()
197
if server_version != '2':
201
except errors.SmartProtocolError:
202
# Apparently there's no usable smart server there, even though
203
# the medium supports the smart protocol.
208
client = _SmartClient(client_medium)
209
path = client.remote_path_from_transport(transport)
210
if client_medium._is_remote_before((1, 16)):
213
# TODO: lookup the local format from a server hint.
214
local_dir_format = _mod_bzrdir.BzrDirMetaFormat1()
215
self._supply_sub_formats_to(local_dir_format)
216
return local_dir_format.initialize_on_transport_ex(transport,
217
use_existing_dir=use_existing_dir, create_prefix=create_prefix,
218
force_new_repo=force_new_repo, stacked_on=stacked_on,
219
stack_on_pwd=stack_on_pwd, repo_format_name=repo_format_name,
220
make_working_trees=make_working_trees, shared_repo=shared_repo,
222
return self._initialize_on_transport_ex_rpc(client, path, transport,
223
use_existing_dir, create_prefix, force_new_repo, stacked_on,
224
stack_on_pwd, repo_format_name, make_working_trees, shared_repo)
226
def _initialize_on_transport_ex_rpc(self, client, path, transport,
227
use_existing_dir, create_prefix, force_new_repo, stacked_on,
228
stack_on_pwd, repo_format_name, make_working_trees, shared_repo):
230
args.append(self._serialize_NoneTrueFalse(use_existing_dir))
231
args.append(self._serialize_NoneTrueFalse(create_prefix))
232
args.append(self._serialize_NoneTrueFalse(force_new_repo))
233
args.append(self._serialize_NoneString(stacked_on))
234
# stack_on_pwd is often/usually our transport
237
stack_on_pwd = transport.relpath(stack_on_pwd)
240
except errors.PathNotChild:
242
args.append(self._serialize_NoneString(stack_on_pwd))
243
args.append(self._serialize_NoneString(repo_format_name))
244
args.append(self._serialize_NoneTrueFalse(make_working_trees))
245
args.append(self._serialize_NoneTrueFalse(shared_repo))
246
request_network_name = self._network_name or \
247
_mod_bzrdir.BzrDirFormat.get_default_format().network_name()
249
response = client.call('BzrDirFormat.initialize_ex_1.16',
250
request_network_name, path, *args)
251
except errors.UnknownSmartMethod:
252
client._medium._remember_remote_is_before((1,16))
253
local_dir_format = _mod_bzrdir.BzrDirMetaFormat1()
254
self._supply_sub_formats_to(local_dir_format)
255
return local_dir_format.initialize_on_transport_ex(transport,
256
use_existing_dir=use_existing_dir, create_prefix=create_prefix,
257
force_new_repo=force_new_repo, stacked_on=stacked_on,
258
stack_on_pwd=stack_on_pwd, repo_format_name=repo_format_name,
259
make_working_trees=make_working_trees, shared_repo=shared_repo,
261
except errors.ErrorFromSmartServer, err:
262
_translate_error(err, path=path)
263
repo_path = response[0]
264
bzrdir_name = response[6]
265
require_stacking = response[7]
266
require_stacking = self.parse_NoneTrueFalse(require_stacking)
267
format = RemoteBzrDirFormat()
268
format._network_name = bzrdir_name
269
self._supply_sub_formats_to(format)
270
bzrdir = RemoteBzrDir(transport, format, _client=client)
272
repo_format = response_tuple_to_repo_format(response[1:])
276
repo_bzrdir_format = RemoteBzrDirFormat()
277
repo_bzrdir_format._network_name = response[5]
278
repo_bzr = RemoteBzrDir(transport.clone(repo_path),
282
final_stack = response[8] or None
283
final_stack_pwd = response[9] or None
285
final_stack_pwd = urlutils.join(
286
transport.base, final_stack_pwd)
287
remote_repo = RemoteRepository(repo_bzr, repo_format)
288
if len(response) > 10:
289
# Updated server verb that locks remotely.
290
repo_lock_token = response[10] or None
291
remote_repo.lock_write(repo_lock_token, _skip_rpc=True)
293
remote_repo.dont_leave_lock_in_place()
295
remote_repo.lock_write()
296
policy = _mod_bzrdir.UseExistingRepository(remote_repo, final_stack,
297
final_stack_pwd, require_stacking)
298
policy.acquire_repository()
302
bzrdir._format.set_branch_format(self.get_branch_format())
304
# The repo has already been created, but we need to make sure that
305
# we'll make a stackable branch.
306
bzrdir._format.require_stacking(_skip_repo=True)
307
return remote_repo, bzrdir, require_stacking, policy
309
def _open(self, transport):
310
return RemoteBzrDir(transport, self)
312
def __eq__(self, other):
313
if not isinstance(other, RemoteBzrDirFormat):
315
return self.get_format_description() == other.get_format_description()
317
def __return_repository_format(self):
318
# Always return a RemoteRepositoryFormat object, but if a specific bzr
319
# repository format has been asked for, tell the RemoteRepositoryFormat
320
# that it should use that for init() etc.
321
result = RemoteRepositoryFormat()
322
custom_format = getattr(self, '_repository_format', None)
324
if isinstance(custom_format, RemoteRepositoryFormat):
327
# We will use the custom format to create repositories over the
328
# wire; expose its details like rich_root_data for code to
330
result._custom_format = custom_format
333
def get_branch_format(self):
334
result = _mod_bzrdir.BzrDirMetaFormat1.get_branch_format(self)
335
if not isinstance(result, RemoteBranchFormat):
336
new_result = RemoteBranchFormat()
337
new_result._custom_format = result
339
self.set_branch_format(new_result)
343
repository_format = property(__return_repository_format,
344
_mod_bzrdir.BzrDirMetaFormat1._set_repository_format) #.im_func)
347
class RemoteControlStore(config.IniFileStore):
348
"""Control store which attempts to use HPSS calls to retrieve control store.
350
Note that this is specific to bzr-based formats.
353
def __init__(self, bzrdir):
354
super(RemoteControlStore, self).__init__()
356
self._real_store = None
358
def lock_write(self, token=None):
360
return self._real_store.lock_write(token)
364
return self._real_store.unlock()
368
# We need to be able to override the undecorated implementation
369
self.save_without_locking()
371
def save_without_locking(self):
372
super(RemoteControlStore, self).save()
374
def _ensure_real(self):
375
self.bzrdir._ensure_real()
376
if self._real_store is None:
377
self._real_store = config.ControlStore(self.bzrdir)
379
def external_url(self):
380
return self.bzrdir.user_url
382
def _load_content(self):
383
medium = self.bzrdir._client._medium
384
path = self.bzrdir._path_for_remote_call(self.bzrdir._client)
386
response, handler = self.bzrdir._call_expecting_body(
387
'BzrDir.get_config_file', path)
388
except errors.UnknownSmartMethod:
390
return self._real_store._load_content()
391
if len(response) and response[0] != 'ok':
392
raise errors.UnexpectedSmartServerResponse(response)
393
return handler.read_body_bytes()
395
def _save_content(self, content):
396
# FIXME JRV 2011-11-22: Ideally this should use a
397
# HPSS call too, but at the moment it is not possible
398
# to write lock control directories.
400
return self._real_store._save_content(content)
403
class RemoteBzrDir(_mod_bzrdir.BzrDir, _RpcHelper):
92
404
"""Control directory on a remote server, accessed via bzr:// or similar."""
94
406
def __init__(self, transport, format, _client=None, _force_probe=False):
1195
1671
raise errors.UnexpectedSmartServerResponse(response)
1197
1674
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,
1675
"""Create a descendent repository for new development.
1677
Unlike clone, this does not copy the settings of the repository.
1679
dest_repo = self._create_sprouting_repo(to_bzrdir, shared=False)
1202
1680
dest_repo.fetch(self, revision_id=revision_id)
1203
1681
return dest_repo
1683
def _create_sprouting_repo(self, a_bzrdir, shared):
1684
if not isinstance(a_bzrdir._format, self.bzrdir._format.__class__):
1685
# use target default format.
1686
dest_repo = a_bzrdir.create_repository()
1688
# Most control formats need the repository to be specifically
1689
# created, but on some old all-in-one formats it's not needed
1691
dest_repo = self._format.initialize(a_bzrdir, shared=shared)
1692
except errors.UninitializableFormat:
1693
dest_repo = a_bzrdir.open_repository()
1205
1696
### These methods are just thin shims to the VFS object for now.
1207
1699
def revision_tree(self, revision_id):
1209
return self._real_repository.revision_tree(revision_id)
1700
revision_id = _mod_revision.ensure_null(revision_id)
1701
if revision_id == _mod_revision.NULL_REVISION:
1702
return InventoryRevisionTree(self,
1703
Inventory(root_id=None), _mod_revision.NULL_REVISION)
1705
return list(self.revision_trees([revision_id]))[0]
1211
1707
def get_serializer_format(self):
1213
return self._real_repository.get_serializer_format()
1708
path = self.bzrdir._path_for_remote_call(self._client)
1710
response = self._call('VersionedFileRepository.get_serializer_format',
1712
except errors.UnknownSmartMethod:
1714
return self._real_repository.get_serializer_format()
1715
if response[0] != 'ok':
1716
raise errors.UnexpectedSmartServerResponse(response)
1215
1719
def get_commit_builder(self, branch, parents, config, timestamp=None,
1216
1720
timezone=None, committer=None, revprops=None,
1721
revision_id=None, lossy=False):
1218
1722
# FIXME: It ought to be possible to call this without immediately
1219
1723
# triggering _ensure_real. For now it's the easiest thing to do.
1220
1724
self._ensure_real()
1221
1725
real_repo = self._real_repository
1222
1726
builder = real_repo.get_commit_builder(branch, parents,
1223
1727
config, timestamp=timestamp, timezone=timezone,
1224
committer=committer, revprops=revprops, revision_id=revision_id)
1728
committer=committer, revprops=revprops,
1729
revision_id=revision_id, lossy=lossy)
1227
1732
def add_fallback_repository(self, repository):
1388
1918
return self._real_repository._get_versioned_file_checker(
1389
1919
revisions, revision_versions_cache)
1921
def _iter_files_bytes_rpc(self, desired_files, absent):
1922
path = self.bzrdir._path_for_remote_call(self._client)
1925
for (file_id, revid, identifier) in desired_files:
1926
lines.append("%s\0%s" % (
1927
osutils.safe_file_id(file_id),
1928
osutils.safe_revision_id(revid)))
1929
identifiers.append(identifier)
1930
(response_tuple, response_handler) = (
1931
self._call_with_body_bytes_expecting_body(
1932
"Repository.iter_files_bytes", (path, ), "\n".join(lines)))
1933
if response_tuple != ('ok', ):
1934
response_handler.cancel_read_body()
1935
raise errors.UnexpectedSmartServerResponse(response_tuple)
1936
byte_stream = response_handler.read_streamed_body()
1937
def decompress_stream(start, byte_stream, unused):
1938
decompressor = zlib.decompressobj()
1939
yield decompressor.decompress(start)
1940
while decompressor.unused_data == "":
1942
data = byte_stream.next()
1943
except StopIteration:
1945
yield decompressor.decompress(data)
1946
yield decompressor.flush()
1947
unused.append(decompressor.unused_data)
1950
while not "\n" in unused:
1951
unused += byte_stream.next()
1952
header, rest = unused.split("\n", 1)
1953
args = header.split("\0")
1954
if args[0] == "absent":
1955
absent[identifiers[int(args[3])]] = (args[1], args[2])
1958
elif args[0] == "ok":
1961
raise errors.UnexpectedSmartServerResponse(args)
1963
yield (identifiers[idx],
1964
decompress_stream(rest, byte_stream, unused_chunks))
1965
unused = "".join(unused_chunks)
1391
1967
def iter_files_bytes(self, desired_files):
1392
1968
"""See Repository.iter_file_bytes.
1395
return self._real_repository.iter_files_bytes(desired_files)
1972
for (identifier, bytes_iterator) in self._iter_files_bytes_rpc(
1973
desired_files, absent):
1974
yield identifier, bytes_iterator
1975
for fallback in self._fallback_repositories:
1978
desired_files = [(key[0], key[1], identifier) for
1979
(identifier, key) in absent.iteritems()]
1980
for (identifier, bytes_iterator) in fallback.iter_files_bytes(desired_files):
1981
del absent[identifier]
1982
yield identifier, bytes_iterator
1984
# There may be more missing items, but raise an exception
1986
missing_identifier = absent.keys()[0]
1987
missing_key = absent[missing_identifier]
1988
raise errors.RevisionNotPresent(revision_id=missing_key[1],
1989
file_id=missing_key[0])
1990
except errors.UnknownSmartMethod:
1992
for (identifier, bytes_iterator) in (
1993
self._real_repository.iter_files_bytes(desired_files)):
1994
yield identifier, bytes_iterator
1996
def get_cached_parent_map(self, revision_ids):
1997
"""See bzrlib.CachingParentsProvider.get_cached_parent_map"""
1998
return self._unstacked_provider.get_cached_parent_map(revision_ids)
1397
2000
def get_parent_map(self, revision_ids):
1398
2001
"""See bzrlib.Graph.get_parent_map()."""
1680
2313
self._ensure_real()
1681
2314
return self._real_repository.texts
2316
def _iter_revisions_rpc(self, revision_ids):
2317
body = "\n".join(revision_ids)
2318
path = self.bzrdir._path_for_remote_call(self._client)
2319
response_tuple, response_handler = (
2320
self._call_with_body_bytes_expecting_body(
2321
"Repository.iter_revisions", (path, ), body))
2322
if response_tuple[0] != "ok":
2323
raise errors.UnexpectedSmartServerResponse(response_tuple)
2324
serializer_format = response_tuple[1]
2325
serializer = serializer_format_registry.get(serializer_format)
2326
byte_stream = response_handler.read_streamed_body()
2327
decompressor = zlib.decompressobj()
2329
for bytes in byte_stream:
2330
chunks.append(decompressor.decompress(bytes))
2331
if decompressor.unused_data != "":
2332
chunks.append(decompressor.flush())
2333
yield serializer.read_revision_from_string("".join(chunks))
2334
unused = decompressor.unused_data
2335
decompressor = zlib.decompressobj()
2336
chunks = [decompressor.decompress(unused)]
2337
chunks.append(decompressor.flush())
2338
text = "".join(chunks)
2340
yield serializer.read_revision_from_string("".join(chunks))
1683
2342
@needs_read_lock
1684
2343
def get_revisions(self, revision_ids):
1686
return self._real_repository.get_revisions(revision_ids)
2344
if revision_ids is None:
2345
revision_ids = self.all_revision_ids()
2347
for rev_id in revision_ids:
2348
if not rev_id or not isinstance(rev_id, basestring):
2349
raise errors.InvalidRevisionId(
2350
revision_id=rev_id, branch=self)
2352
missing = set(revision_ids)
2354
for rev in self._iter_revisions_rpc(revision_ids):
2355
missing.remove(rev.revision_id)
2356
revs[rev.revision_id] = rev
2357
except errors.UnknownSmartMethod:
2359
return self._real_repository.get_revisions(revision_ids)
2360
for fallback in self._fallback_repositories:
2363
for revid in list(missing):
2364
# XXX JRV 2011-11-20: It would be nice if there was a
2365
# public method on Repository that could be used to query
2366
# for revision objects *without* failing completely if one
2367
# was missing. There is VersionedFileRepository._iter_revisions,
2368
# but unfortunately that's private and not provided by
2369
# all repository implementations.
2371
revs[revid] = fallback.get_revision(revid)
2372
except errors.NoSuchRevision:
2375
missing.remove(revid)
2377
raise errors.NoSuchRevision(self, list(missing)[0])
2378
return [revs[revid] for revid in revision_ids]
1688
2380
def supports_rich_root(self):
1689
2381
return self._format.rich_root_data
2383
@symbol_versioning.deprecated_method(symbol_versioning.deprecated_in((2, 4, 0)))
1691
2384
def iter_reverse_revision_history(self, revision_id):
1692
2385
self._ensure_real()
1693
2386
return self._real_repository.iter_reverse_revision_history(revision_id)
1696
2389
def _serializer(self):
1697
2390
return self._format._serializer
1699
2393
def store_revision_signature(self, gpg_strategy, plaintext, revision_id):
1701
return self._real_repository.store_revision_signature(
1702
gpg_strategy, plaintext, revision_id)
2394
signature = gpg_strategy.sign(plaintext)
2395
self.add_signature_text(revision_id, signature)
1704
2397
def add_signature_text(self, revision_id, signature):
1706
return self._real_repository.add_signature_text(revision_id, signature)
2398
if self._real_repository:
2399
# If there is a real repository the write group will
2400
# be in the real repository as well, so use that:
2402
return self._real_repository.add_signature_text(
2403
revision_id, signature)
2404
path = self.bzrdir._path_for_remote_call(self._client)
2405
response, handler = self._call_with_body_bytes_expecting_body(
2406
'Repository.add_signature_text', (path, self._lock_token,
2407
revision_id) + tuple(self._write_group_tokens), signature)
2408
handler.cancel_read_body()
2410
if response[0] != 'ok':
2411
raise errors.UnexpectedSmartServerResponse(response)
2412
self._write_group_tokens = response[1:]
1708
2414
def has_signature_for_revision_id(self, revision_id):
1710
return self._real_repository.has_signature_for_revision_id(revision_id)
2415
path = self.bzrdir._path_for_remote_call(self._client)
2417
response = self._call('Repository.has_signature_for_revision_id',
2419
except errors.UnknownSmartMethod:
2421
return self._real_repository.has_signature_for_revision_id(
2423
if response[0] not in ('yes', 'no'):
2424
raise SmartProtocolError('unexpected response code %s' % (response,))
2425
if response[0] == 'yes':
2427
for fallback in self._fallback_repositories:
2428
if fallback.has_signature_for_revision_id(revision_id):
2433
def verify_revision_signature(self, revision_id, gpg_strategy):
2434
if not self.has_signature_for_revision_id(revision_id):
2435
return gpg.SIGNATURE_NOT_SIGNED, None
2436
signature = self.get_signature_text(revision_id)
2438
testament = _mod_testament.Testament.from_revision(self, revision_id)
2439
plaintext = testament.as_short_text()
2441
return gpg_strategy.verify(signature, plaintext)
1712
2443
def item_keys_introduced_by(self, revision_ids, _files_pb=None):
1713
2444
self._ensure_real()
1714
2445
return self._real_repository.item_keys_introduced_by(revision_ids,
1715
2446
_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
2448
def _find_inconsistent_revision_parents(self, revisions_iterator=None):
1723
2449
self._ensure_real()
1724
2450
return self._real_repository._find_inconsistent_revision_parents(
2071
2808
if isinstance(a_bzrdir, RemoteBzrDir):
2072
2809
a_bzrdir._ensure_real()
2073
2810
result = self._custom_format.initialize(a_bzrdir._real_bzrdir,
2811
name, append_revisions_only=append_revisions_only)
2076
2813
# We assume the bzrdir is parameterised; it may not be.
2077
result = self._custom_format.initialize(a_bzrdir, name)
2814
result = self._custom_format.initialize(a_bzrdir, name,
2815
append_revisions_only=append_revisions_only)
2078
2816
if (isinstance(a_bzrdir, RemoteBzrDir) and
2079
2817
not isinstance(result, RemoteBranch)):
2080
2818
result = RemoteBranch(a_bzrdir, a_bzrdir.find_repository(), result,
2084
def initialize(self, a_bzrdir, name=None):
2822
def initialize(self, a_bzrdir, name=None, repository=None,
2823
append_revisions_only=None):
2085
2824
# 1) get the network name to use.
2086
2825
if self._custom_format:
2087
2826
network_name = self._custom_format.network_name()
2089
2828
# Select the current bzrlib default and ask for that.
2090
reference_bzrdir_format = bzrdir.format_registry.get('default')()
2829
reference_bzrdir_format = _mod_bzrdir.format_registry.get('default')()
2091
2830
reference_format = reference_bzrdir_format.get_branch_format()
2092
2831
self._custom_format = reference_format
2093
2832
network_name = reference_format.network_name()
2094
2833
# Being asked to create on a non RemoteBzrDir:
2095
2834
if not isinstance(a_bzrdir, RemoteBzrDir):
2096
return self._vfs_initialize(a_bzrdir, name=name)
2835
return self._vfs_initialize(a_bzrdir, name=name,
2836
append_revisions_only=append_revisions_only)
2097
2837
medium = a_bzrdir._client._medium
2098
2838
if medium._is_remote_before((1, 13)):
2099
return self._vfs_initialize(a_bzrdir, name=name)
2839
return self._vfs_initialize(a_bzrdir, name=name,
2840
append_revisions_only=append_revisions_only)
2100
2841
# Creating on a remote bzr dir.
2101
2842
# 2) try direct creation via RPC
2102
2843
path = a_bzrdir._path_for_remote_call(a_bzrdir._client)
2148
2904
self._ensure_real()
2149
2905
return self._custom_format.supports_set_append_revisions_only()
2907
def _use_default_local_heads_to_fetch(self):
2908
# If the branch format is a metadir format *and* its heads_to_fetch
2909
# implementation is not overridden vs the base class, we can use the
2910
# base class logic rather than use the heads_to_fetch RPC. This is
2911
# usually cheaper in terms of net round trips, as the last-revision and
2912
# tags info fetched is cached and would be fetched anyway.
2914
if isinstance(self._custom_format, branch.BranchFormatMetadir):
2915
branch_class = self._custom_format._branch_class()
2916
heads_to_fetch_impl = branch_class.heads_to_fetch.im_func
2917
if heads_to_fetch_impl is branch.Branch.heads_to_fetch.im_func:
2922
class RemoteBranchStore(config.IniFileStore):
2923
"""Branch store which attempts to use HPSS calls to retrieve branch store.
2925
Note that this is specific to bzr-based formats.
2928
def __init__(self, branch):
2929
super(RemoteBranchStore, self).__init__()
2930
self.branch = branch
2932
self._real_store = None
2934
def lock_write(self, token=None):
2935
return self.branch.lock_write(token)
2938
return self.branch.unlock()
2942
# We need to be able to override the undecorated implementation
2943
self.save_without_locking()
2945
def save_without_locking(self):
2946
super(RemoteBranchStore, self).save()
2948
def external_url(self):
2949
return self.branch.user_url
2951
def _load_content(self):
2952
path = self.branch._remote_path()
2954
response, handler = self.branch._call_expecting_body(
2955
'Branch.get_config_file', path)
2956
except errors.UnknownSmartMethod:
2958
return self._real_store._load_content()
2959
if len(response) and response[0] != 'ok':
2960
raise errors.UnexpectedSmartServerResponse(response)
2961
return handler.read_body_bytes()
2963
def _save_content(self, content):
2964
path = self.branch._remote_path()
2966
response, handler = self.branch._call_with_body_bytes_expecting_body(
2967
'Branch.put_config_file', (path,
2968
self.branch._lock_token, self.branch._repo_lock_token),
2970
except errors.UnknownSmartMethod:
2972
return self._real_store._save_content(content)
2973
handler.cancel_read_body()
2974
if response != ('ok', ):
2975
raise errors.UnexpectedSmartServerResponse(response)
2977
def _ensure_real(self):
2978
self.branch._ensure_real()
2979
if self._real_store is None:
2980
self._real_store = config.BranchStore(self.branch)
2152
2983
class RemoteBranch(branch.Branch, _RpcHelper, lock._RelockDebugMixin):
2153
2984
"""Branch stored on a server accessed by HPSS RPC.
2654
3540
_override_hook_target=self, **kwargs)
2656
3542
@needs_read_lock
2657
def push(self, target, overwrite=False, stop_revision=None):
3543
def push(self, target, overwrite=False, stop_revision=None, lossy=False):
2658
3544
self._ensure_real()
2659
3545
return self._real_branch.push(
2660
target, overwrite=overwrite, stop_revision=stop_revision,
3546
target, overwrite=overwrite, stop_revision=stop_revision, lossy=lossy,
2661
3547
_override_hook_source_branch=self)
2663
3549
def is_locked(self):
2664
3550
return self._lock_count >= 1
2666
3552
@needs_read_lock
3553
def revision_id_to_dotted_revno(self, revision_id):
3554
"""Given a revision id, return its dotted revno.
3556
:return: a tuple like (1,) or (400,1,3).
3559
response = self._call('Branch.revision_id_to_revno',
3560
self._remote_path(), revision_id)
3561
except errors.UnknownSmartMethod:
3563
return self._real_branch.revision_id_to_dotted_revno(revision_id)
3564
if response[0] == 'ok':
3565
return tuple([int(x) for x in response[1:]])
3567
raise errors.UnexpectedSmartServerResponse(response)
2667
3570
def revision_id_to_revno(self, revision_id):
2669
return self._real_branch.revision_id_to_revno(revision_id)
3571
"""Given a revision id on the branch mainline, return its revno.
3576
response = self._call('Branch.revision_id_to_revno',
3577
self._remote_path(), revision_id)
3578
except errors.UnknownSmartMethod:
3580
return self._real_branch.revision_id_to_revno(revision_id)
3581
if response[0] == 'ok':
3582
if len(response) == 2:
3583
return int(response[1])
3584
raise NoSuchRevision(self, revision_id)
3586
raise errors.UnexpectedSmartServerResponse(response)
2671
3588
@needs_write_lock
2672
3589
def set_last_revision_info(self, revno, revision_id):
2673
3590
# XXX: These should be returned by the set_last_revision_info verb
2674
3591
old_revno, old_revid = self.last_revision_info()
2675
3592
self._run_pre_change_branch_tip_hooks(revno, revision_id)
2676
revision_id = ensure_null(revision_id)
3593
if not revision_id or not isinstance(revision_id, basestring):
3594
raise errors.InvalidRevisionId(revision_id=revision_id, branch=self)
2678
3596
response = self._call('Branch.set_last_revision_info',
2679
3597
self._remote_path(), self._lock_token, self._repo_lock_token,
2774
3729
medium = self._branch._client._medium
2775
3730
if medium._is_remote_before((1, 14)):
2776
3731
return self._vfs_set_option(value, name, section)
3732
if isinstance(value, dict):
3733
if medium._is_remote_before((2, 2)):
3734
return self._vfs_set_option(value, name, section)
3735
return self._set_config_option_dict(value, name, section)
3737
return self._set_config_option(value, name, section)
3739
def _set_config_option(self, value, name, section):
2778
3741
path = self._branch._remote_path()
2779
3742
response = self._branch._client.call('Branch.set_config_option',
2780
3743
path, self._branch._lock_token, self._branch._repo_lock_token,
2781
3744
value.encode('utf8'), name, section or '')
2782
3745
except errors.UnknownSmartMethod:
3746
medium = self._branch._client._medium
2783
3747
medium._remember_remote_is_before((1, 14))
2784
3748
return self._vfs_set_option(value, name, section)
2785
3749
if response != ():
2786
3750
raise errors.UnexpectedSmartServerResponse(response)
3752
def _serialize_option_dict(self, option_dict):
3754
for key, value in option_dict.items():
3755
if isinstance(key, unicode):
3756
key = key.encode('utf8')
3757
if isinstance(value, unicode):
3758
value = value.encode('utf8')
3759
utf8_dict[key] = value
3760
return bencode.bencode(utf8_dict)
3762
def _set_config_option_dict(self, value, name, section):
3764
path = self._branch._remote_path()
3765
serialised_dict = self._serialize_option_dict(value)
3766
response = self._branch._client.call(
3767
'Branch.set_config_option_dict',
3768
path, self._branch._lock_token, self._branch._repo_lock_token,
3769
serialised_dict, name, section or '')
3770
except errors.UnknownSmartMethod:
3771
medium = self._branch._client._medium
3772
medium._remember_remote_is_before((2, 2))
3773
return self._vfs_set_option(value, name, section)
3775
raise errors.UnexpectedSmartServerResponse(response)
2788
3777
def _real_object(self):
2789
3778
self._branch._ensure_real()
2790
3779
return self._branch._real_branch
2873
3865
'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'):
3869
translator = error_translators.get(err.error_verb)
3873
raise translator(err, find, get_path)
3875
translator = no_context_error_translators.get(err.error_verb)
3877
raise errors.UnknownErrorFromSmartServer(err)
3879
raise translator(err)
3882
error_translators.register('NoSuchRevision',
3883
lambda err, find, get_path: NoSuchRevision(
3884
find('branch'), err.error_args[0]))
3885
error_translators.register('nosuchrevision',
3886
lambda err, find, get_path: NoSuchRevision(
3887
find('repository'), err.error_args[0]))
3889
def _translate_nobranch_error(err, find, get_path):
3890
if len(err.error_args) >= 1:
3891
extra = err.error_args[0]
3894
return errors.NotBranchError(path=find('bzrdir').root_transport.base,
3897
error_translators.register('nobranch', _translate_nobranch_error)
3898
error_translators.register('norepository',
3899
lambda err, find, get_path: errors.NoRepositoryPresent(
3901
error_translators.register('UnlockableTransport',
3902
lambda err, find, get_path: errors.UnlockableTransport(
3903
find('bzrdir').root_transport))
3904
error_translators.register('TokenMismatch',
3905
lambda err, find, get_path: errors.TokenMismatch(
3906
find('token'), '(remote token)'))
3907
error_translators.register('Diverged',
3908
lambda err, find, get_path: errors.DivergedBranches(
3909
find('branch'), find('other_branch')))
3910
error_translators.register('NotStacked',
3911
lambda err, find, get_path: errors.NotStacked(branch=find('branch')))
3913
def _translate_PermissionDenied(err, find, get_path):
3915
if len(err.error_args) >= 2:
3916
extra = err.error_args[1]
3919
return errors.PermissionDenied(path, extra=extra)
3921
error_translators.register('PermissionDenied', _translate_PermissionDenied)
3922
error_translators.register('ReadError',
3923
lambda err, find, get_path: errors.ReadError(get_path()))
3924
error_translators.register('NoSuchFile',
3925
lambda err, find, get_path: errors.NoSuchFile(get_path()))
3926
error_translators.register('UnsuspendableWriteGroup',
3927
lambda err, find, get_path: errors.UnsuspendableWriteGroup(
3928
repository=find('repository')))
3929
error_translators.register('UnresumableWriteGroup',
3930
lambda err, find, get_path: errors.UnresumableWriteGroup(
3931
repository=find('repository'), write_groups=err.error_args[0],
3932
reason=err.error_args[1]))
3933
no_context_error_translators.register('IncompatibleRepositories',
3934
lambda err: errors.IncompatibleRepositories(
3935
err.error_args[0], err.error_args[1], err.error_args[2]))
3936
no_context_error_translators.register('LockContention',
3937
lambda err: errors.LockContention('(remote lock)'))
3938
no_context_error_translators.register('LockFailed',
3939
lambda err: errors.LockFailed(err.error_args[0], err.error_args[1]))
3940
no_context_error_translators.register('TipChangeRejected',
3941
lambda err: errors.TipChangeRejected(err.error_args[0].decode('utf8')))
3942
no_context_error_translators.register('UnstackableBranchFormat',
3943
lambda err: errors.UnstackableBranchFormat(*err.error_args))
3944
no_context_error_translators.register('UnstackableRepositoryFormat',
3945
lambda err: errors.UnstackableRepositoryFormat(*err.error_args))
3946
no_context_error_translators.register('FileExists',
3947
lambda err: errors.FileExists(err.error_args[0]))
3948
no_context_error_translators.register('DirectoryNotEmpty',
3949
lambda err: errors.DirectoryNotEmpty(err.error_args[0]))
3951
def _translate_short_readv_error(err):
3952
args = err.error_args
3953
return errors.ShortReadvError(args[0], int(args[1]), int(args[2]),
3956
no_context_error_translators.register('ShortReadvError',
3957
_translate_short_readv_error)
3959
def _translate_unicode_error(err):
2932
3960
encoding = str(err.error_args[0]) # encoding must always be a string
2933
3961
val = err.error_args[1]
2934
3962
start = int(err.error_args[2])