89
# Note: RemoteBzrDirFormat is in bzrdir.py
91
class RemoteBzrDir(BzrDir, _RpcHelper):
107
# Note that RemoteBzrDirProber lives in breezy.bzrdir so breezy.remote
108
# does not have to be imported unless a remote format is involved.
110
class RemoteBzrDirFormat(_mod_bzrdir.BzrDirMetaFormat1):
111
"""Format representing bzrdirs accessed via a smart server"""
113
supports_workingtrees = False
115
colocated_branches = False
118
_mod_bzrdir.BzrDirMetaFormat1.__init__(self)
119
# XXX: It's a bit ugly that the network name is here, because we'd
120
# like to believe that format objects are stateless or at least
121
# immutable, However, we do at least avoid mutating the name after
122
# it's returned. See <https://bugs.launchpad.net/bzr/+bug/504102>
123
self._network_name = None
126
return "%s(_network_name=%r)" % (self.__class__.__name__,
129
def get_format_description(self):
130
if self._network_name:
132
real_format = controldir.network_format_registry.get(
137
return 'Remote: ' + real_format.get_format_description()
138
return 'bzr remote bzrdir'
140
def get_format_string(self):
141
raise NotImplementedError(self.get_format_string)
143
def network_name(self):
144
if self._network_name:
145
return self._network_name
147
raise AssertionError("No network name set.")
149
def initialize_on_transport(self, transport):
151
# hand off the request to the smart server
152
client_medium = transport.get_smart_medium()
153
except errors.NoSmartMedium:
154
# TODO: lookup the local format from a server hint.
155
local_dir_format = _mod_bzrdir.BzrDirMetaFormat1()
156
return local_dir_format.initialize_on_transport(transport)
157
client = _SmartClient(client_medium)
158
path = client.remote_path_from_transport(transport)
160
response = client.call('BzrDirFormat.initialize', path)
161
except errors.ErrorFromSmartServer as err:
162
_translate_error(err, path=path)
163
if response[0] != 'ok':
164
raise errors.SmartProtocolError('unexpected response code %s' % (response,))
165
format = RemoteBzrDirFormat()
166
self._supply_sub_formats_to(format)
167
return RemoteBzrDir(transport, format)
169
def parse_NoneTrueFalse(self, arg):
176
raise AssertionError("invalid arg %r" % arg)
178
def _serialize_NoneTrueFalse(self, arg):
185
def _serialize_NoneString(self, arg):
188
def initialize_on_transport_ex(self, transport, use_existing_dir=False,
189
create_prefix=False, force_new_repo=False, stacked_on=None,
190
stack_on_pwd=None, repo_format_name=None, make_working_trees=None,
193
# hand off the request to the smart server
194
client_medium = transport.get_smart_medium()
195
except errors.NoSmartMedium:
198
# Decline to open it if the server doesn't support our required
199
# version (3) so that the VFS-based transport will do it.
200
if client_medium.should_probe():
202
server_version = client_medium.protocol_version()
203
if server_version != '2':
207
except errors.SmartProtocolError:
208
# Apparently there's no usable smart server there, even though
209
# the medium supports the smart protocol.
214
client = _SmartClient(client_medium)
215
path = client.remote_path_from_transport(transport)
216
if client_medium._is_remote_before((1, 16)):
219
# TODO: lookup the local format from a server hint.
220
local_dir_format = _mod_bzrdir.BzrDirMetaFormat1()
221
self._supply_sub_formats_to(local_dir_format)
222
return local_dir_format.initialize_on_transport_ex(transport,
223
use_existing_dir=use_existing_dir, create_prefix=create_prefix,
224
force_new_repo=force_new_repo, stacked_on=stacked_on,
225
stack_on_pwd=stack_on_pwd, repo_format_name=repo_format_name,
226
make_working_trees=make_working_trees, shared_repo=shared_repo,
228
return self._initialize_on_transport_ex_rpc(client, path, transport,
229
use_existing_dir, create_prefix, force_new_repo, stacked_on,
230
stack_on_pwd, repo_format_name, make_working_trees, shared_repo)
232
def _initialize_on_transport_ex_rpc(self, client, path, transport,
233
use_existing_dir, create_prefix, force_new_repo, stacked_on,
234
stack_on_pwd, repo_format_name, make_working_trees, shared_repo):
236
args.append(self._serialize_NoneTrueFalse(use_existing_dir))
237
args.append(self._serialize_NoneTrueFalse(create_prefix))
238
args.append(self._serialize_NoneTrueFalse(force_new_repo))
239
args.append(self._serialize_NoneString(stacked_on))
240
# stack_on_pwd is often/usually our transport
243
stack_on_pwd = transport.relpath(stack_on_pwd)
246
except errors.PathNotChild:
248
args.append(self._serialize_NoneString(stack_on_pwd))
249
args.append(self._serialize_NoneString(repo_format_name))
250
args.append(self._serialize_NoneTrueFalse(make_working_trees))
251
args.append(self._serialize_NoneTrueFalse(shared_repo))
252
request_network_name = self._network_name or \
253
_mod_bzrdir.BzrDirFormat.get_default_format().network_name()
255
response = client.call('BzrDirFormat.initialize_ex_1.16',
256
request_network_name, path, *args)
257
except errors.UnknownSmartMethod:
258
client._medium._remember_remote_is_before((1,16))
259
local_dir_format = _mod_bzrdir.BzrDirMetaFormat1()
260
self._supply_sub_formats_to(local_dir_format)
261
return local_dir_format.initialize_on_transport_ex(transport,
262
use_existing_dir=use_existing_dir, create_prefix=create_prefix,
263
force_new_repo=force_new_repo, stacked_on=stacked_on,
264
stack_on_pwd=stack_on_pwd, repo_format_name=repo_format_name,
265
make_working_trees=make_working_trees, shared_repo=shared_repo,
267
except errors.ErrorFromSmartServer as err:
268
_translate_error(err, path=path)
269
repo_path = response[0]
270
bzrdir_name = response[6]
271
require_stacking = response[7]
272
require_stacking = self.parse_NoneTrueFalse(require_stacking)
273
format = RemoteBzrDirFormat()
274
format._network_name = bzrdir_name
275
self._supply_sub_formats_to(format)
276
bzrdir = RemoteBzrDir(transport, format, _client=client)
278
repo_format = response_tuple_to_repo_format(response[1:])
282
repo_bzrdir_format = RemoteBzrDirFormat()
283
repo_bzrdir_format._network_name = response[5]
284
repo_bzr = RemoteBzrDir(transport.clone(repo_path),
288
final_stack = response[8] or None
289
final_stack_pwd = response[9] or None
291
final_stack_pwd = urlutils.join(
292
transport.base, final_stack_pwd)
293
remote_repo = RemoteRepository(repo_bzr, repo_format)
294
if len(response) > 10:
295
# Updated server verb that locks remotely.
296
repo_lock_token = response[10] or None
297
remote_repo.lock_write(repo_lock_token, _skip_rpc=True)
299
remote_repo.dont_leave_lock_in_place()
301
remote_repo.lock_write()
302
policy = _mod_bzrdir.UseExistingRepository(remote_repo, final_stack,
303
final_stack_pwd, require_stacking)
304
policy.acquire_repository()
308
bzrdir._format.set_branch_format(self.get_branch_format())
310
# The repo has already been created, but we need to make sure that
311
# we'll make a stackable branch.
312
bzrdir._format.require_stacking(_skip_repo=True)
313
return remote_repo, bzrdir, require_stacking, policy
315
def _open(self, transport):
316
return RemoteBzrDir(transport, self)
318
def __eq__(self, other):
319
if not isinstance(other, RemoteBzrDirFormat):
321
return self.get_format_description() == other.get_format_description()
323
def __return_repository_format(self):
324
# Always return a RemoteRepositoryFormat object, but if a specific bzr
325
# repository format has been asked for, tell the RemoteRepositoryFormat
326
# that it should use that for init() etc.
327
result = RemoteRepositoryFormat()
328
custom_format = getattr(self, '_repository_format', None)
330
if isinstance(custom_format, RemoteRepositoryFormat):
333
# We will use the custom format to create repositories over the
334
# wire; expose its details like rich_root_data for code to
336
result._custom_format = custom_format
339
def get_branch_format(self):
340
result = _mod_bzrdir.BzrDirMetaFormat1.get_branch_format(self)
341
if not isinstance(result, RemoteBranchFormat):
342
new_result = RemoteBranchFormat()
343
new_result._custom_format = result
345
self.set_branch_format(new_result)
349
repository_format = property(__return_repository_format,
350
_mod_bzrdir.BzrDirMetaFormat1._set_repository_format) #.im_func)
353
class RemoteControlStore(_mod_config.IniFileStore):
354
"""Control store which attempts to use HPSS calls to retrieve control store.
356
Note that this is specific to bzr-based formats.
359
def __init__(self, bzrdir):
360
super(RemoteControlStore, self).__init__()
362
self._real_store = None
364
def lock_write(self, token=None):
366
return self._real_store.lock_write(token)
370
return self._real_store.unlock()
374
# We need to be able to override the undecorated implementation
375
self.save_without_locking()
377
def save_without_locking(self):
378
super(RemoteControlStore, self).save()
380
def _ensure_real(self):
381
self.bzrdir._ensure_real()
382
if self._real_store is None:
383
self._real_store = _mod_config.ControlStore(self.bzrdir)
385
def external_url(self):
386
return urlutils.join(self.branch.user_url, 'control.conf')
388
def _load_content(self):
389
medium = self.bzrdir._client._medium
390
path = self.bzrdir._path_for_remote_call(self.bzrdir._client)
392
response, handler = self.bzrdir._call_expecting_body(
393
'BzrDir.get_config_file', path)
394
except errors.UnknownSmartMethod:
396
return self._real_store._load_content()
397
if len(response) and response[0] != 'ok':
398
raise errors.UnexpectedSmartServerResponse(response)
399
return handler.read_body_bytes()
401
def _save_content(self, content):
402
# FIXME JRV 2011-11-22: Ideally this should use a
403
# HPSS call too, but at the moment it is not possible
404
# to write lock control directories.
406
return self._real_store._save_content(content)
409
class RemoteBzrDir(_mod_bzrdir.BzrDir, _RpcHelper):
92
410
"""Control directory on a remote server, accessed via bzr:// or similar."""
94
412
def __init__(self, transport, format, _client=None, _force_probe=False):
266
655
def destroy_branch(self, name=None):
267
656
"""See BzrDir.destroy_branch"""
269
self._real_bzrdir.destroy_branch(name=name)
658
name = self._get_selected_branch()
660
raise errors.NoColocatedBranchSupport(self)
661
path = self._path_for_remote_call(self._client)
667
response = self._call('BzrDir.destroy_branch', path, *args)
668
except errors.UnknownSmartMethod:
670
self._real_bzrdir.destroy_branch(name=name)
671
self._next_open_branch_result = None
270
673
self._next_open_branch_result = None
674
if response[0] != 'ok':
675
raise SmartProtocolError('unexpected response code %s' % (response,))
272
def create_workingtree(self, revision_id=None, from_branch=None):
677
def create_workingtree(self, revision_id=None, from_branch=None,
678
accelerator_tree=None, hardlink=False):
273
679
raise errors.NotLocalUrl(self.transport.base)
275
def find_branch_format(self):
681
def find_branch_format(self, name=None):
276
682
"""Find the branch 'format' for this bzrdir.
278
684
This might be a synthetic object for e.g. RemoteBranch and SVN.
280
b = self.open_branch()
686
b = self.open_branch(name=name)
283
def get_branch_reference(self):
689
def get_branches(self, possible_transports=None, ignore_fallbacks=False):
690
path = self._path_for_remote_call(self._client)
692
response, handler = self._call_expecting_body(
693
'BzrDir.get_branches', path)
694
except errors.UnknownSmartMethod:
696
return self._real_bzrdir.get_branches()
697
if response[0] != "success":
698
raise errors.UnexpectedSmartServerResponse(response)
699
body = bencode.bdecode(handler.read_body_bytes())
701
for (name, value) in body.iteritems():
702
ret[name] = self._open_branch(name, value[0], value[1],
703
possible_transports=possible_transports,
704
ignore_fallbacks=ignore_fallbacks)
707
def set_branch_reference(self, target_branch, name=None):
708
"""See BzrDir.set_branch_reference()."""
710
name = self._get_selected_branch()
712
raise errors.NoColocatedBranchSupport(self)
714
return self._real_bzrdir.set_branch_reference(target_branch, name=name)
716
def get_branch_reference(self, name=None):
284
717
"""See BzrDir.get_branch_reference()."""
719
name = self._get_selected_branch()
721
raise errors.NoColocatedBranchSupport(self)
285
722
response = self._get_branch_reference()
286
723
if response[0] == 'ref':
287
724
return response[1]
318
755
raise errors.UnexpectedSmartServerResponse(response)
321
def _get_tree_branch(self):
758
def _get_tree_branch(self, name=None):
322
759
"""See BzrDir._get_tree_branch()."""
323
return None, self.open_branch()
760
return None, self.open_branch(name=name)
325
def open_branch(self, name=None, unsupported=False,
326
ignore_fallbacks=False):
328
raise NotImplementedError('unsupported flag support not implemented yet.')
329
if self._next_open_branch_result is not None:
330
# See create_branch for details.
331
result = self._next_open_branch_result
332
self._next_open_branch_result = None
334
response = self._get_branch_reference()
335
if response[0] == 'ref':
762
def _open_branch(self, name, kind, location_or_format,
763
ignore_fallbacks=False, possible_transports=None):
336
765
# a branch reference, use the existing BranchReference logic.
337
766
format = BranchReferenceFormat()
338
767
return format.open(self, name=name, _found=True,
339
location=response[1], ignore_fallbacks=ignore_fallbacks)
340
branch_format_name = response[1]
768
location=location_or_format, ignore_fallbacks=ignore_fallbacks,
769
possible_transports=possible_transports)
770
branch_format_name = location_or_format
341
771
if not branch_format_name:
342
772
branch_format_name = None
343
773
format = RemoteBranchFormat(network_name=branch_format_name)
344
774
return RemoteBranch(self, self.find_repository(), format=format,
345
setup_stacking=not ignore_fallbacks, name=name)
775
setup_stacking=not ignore_fallbacks, name=name,
776
possible_transports=possible_transports)
778
def open_branch(self, name=None, unsupported=False,
779
ignore_fallbacks=False, possible_transports=None):
781
name = self._get_selected_branch()
783
raise errors.NoColocatedBranchSupport(self)
785
raise NotImplementedError('unsupported flag support not implemented yet.')
786
if self._next_open_branch_result is not None:
787
# See create_branch for details.
788
result = self._next_open_branch_result
789
self._next_open_branch_result = None
791
response = self._get_branch_reference()
792
return self._open_branch(name, response[0], response[1],
793
possible_transports=possible_transports,
794
ignore_fallbacks=ignore_fallbacks)
347
796
def _open_repo_v1(self, path):
348
797
verb = 'BzrDir.find_repository'
1195
1767
raise errors.UnexpectedSmartServerResponse(response)
1197
1770
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,
1771
"""Create a descendent repository for new development.
1773
Unlike clone, this does not copy the settings of the repository.
1775
dest_repo = self._create_sprouting_repo(to_bzrdir, shared=False)
1202
1776
dest_repo.fetch(self, revision_id=revision_id)
1203
1777
return dest_repo
1779
def _create_sprouting_repo(self, a_bzrdir, shared):
1780
if not isinstance(a_bzrdir._format, self.bzrdir._format.__class__):
1781
# use target default format.
1782
dest_repo = a_bzrdir.create_repository()
1784
# Most control formats need the repository to be specifically
1785
# created, but on some old all-in-one formats it's not needed
1787
dest_repo = self._format.initialize(a_bzrdir, shared=shared)
1788
except errors.UninitializableFormat:
1789
dest_repo = a_bzrdir.open_repository()
1205
1792
### These methods are just thin shims to the VFS object for now.
1207
1795
def revision_tree(self, revision_id):
1209
return self._real_repository.revision_tree(revision_id)
1796
revision_id = _mod_revision.ensure_null(revision_id)
1797
if revision_id == _mod_revision.NULL_REVISION:
1798
return InventoryRevisionTree(self,
1799
Inventory(root_id=None), _mod_revision.NULL_REVISION)
1801
return list(self.revision_trees([revision_id]))[0]
1211
1803
def get_serializer_format(self):
1213
return self._real_repository.get_serializer_format()
1804
path = self.bzrdir._path_for_remote_call(self._client)
1806
response = self._call('VersionedFileRepository.get_serializer_format',
1808
except errors.UnknownSmartMethod:
1810
return self._real_repository.get_serializer_format()
1811
if response[0] != 'ok':
1812
raise errors.UnexpectedSmartServerResponse(response)
1215
1815
def get_commit_builder(self, branch, parents, config, timestamp=None,
1216
1816
timezone=None, committer=None, revprops=None,
1218
# FIXME: It ought to be possible to call this without immediately
1219
# triggering _ensure_real. For now it's the easiest thing to do.
1221
real_repo = self._real_repository
1222
builder = real_repo.get_commit_builder(branch, parents,
1223
config, timestamp=timestamp, timezone=timezone,
1224
committer=committer, revprops=revprops, revision_id=revision_id)
1817
revision_id=None, lossy=False):
1818
"""Obtain a CommitBuilder for this repository.
1820
:param branch: Branch to commit to.
1821
:param parents: Revision ids of the parents of the new revision.
1822
:param config: Configuration to use.
1823
:param timestamp: Optional timestamp recorded for commit.
1824
:param timezone: Optional timezone for timestamp.
1825
:param committer: Optional committer to set for commit.
1826
:param revprops: Optional dictionary of revision properties.
1827
:param revision_id: Optional revision id.
1828
:param lossy: Whether to discard data that can not be natively
1829
represented, when pushing to a foreign VCS
1831
if self._fallback_repositories and not self._format.supports_chks:
1832
raise errors.BzrError("Cannot commit directly to a stacked branch"
1833
" in pre-2a formats. See "
1834
"https://bugs.launchpad.net/bzr/+bug/375013 for details.")
1835
if self._format.rich_root_data:
1836
commit_builder_kls = vf_repository.VersionedFileRootCommitBuilder
1838
commit_builder_kls = vf_repository.VersionedFileCommitBuilder
1839
result = commit_builder_kls(self, parents, config,
1840
timestamp, timezone, committer, revprops, revision_id,
1842
self.start_write_group()
1227
1845
def add_fallback_repository(self, repository):
1228
1846
"""Add a repository to use for looking up data not held locally.
1272
1891
delta, new_revision_id, parents, basis_inv=basis_inv,
1273
1892
propagate_caches=propagate_caches)
1275
def add_revision(self, rev_id, rev, inv=None, config=None):
1277
return self._real_repository.add_revision(
1278
rev_id, rev, inv=inv, config=config)
1894
def add_revision(self, revision_id, rev, inv=None):
1895
_mod_revision.check_not_reserved_id(revision_id)
1896
key = (revision_id,)
1897
# check inventory present
1898
if not self.inventories.get_parent_map([key]):
1900
raise errors.WeaveRevisionNotPresent(revision_id,
1903
# yes, this is not suitable for adding with ghosts.
1904
rev.inventory_sha1 = self.add_inventory(revision_id, inv,
1907
rev.inventory_sha1 = self.inventories.get_sha1s([key])[key]
1908
self._add_revision(rev)
1910
def _add_revision(self, rev):
1911
if self._real_repository is not None:
1912
return self._real_repository._add_revision(rev)
1913
text = self._serializer.write_revision_to_string(rev)
1914
key = (rev.revision_id,)
1915
parents = tuple((parent,) for parent in rev.parent_ids)
1916
self._write_group_tokens, missing_keys = self._get_sink().insert_stream(
1917
[('revisions', [FulltextContentFactory(key, parents, None, text)])],
1918
self._format, self._write_group_tokens)
1280
1920
@needs_read_lock
1281
1921
def get_inventory(self, revision_id):
1922
return list(self.iter_inventories([revision_id]))[0]
1924
def _iter_inventories_rpc(self, revision_ids, ordering):
1925
if ordering is None:
1926
ordering = 'unordered'
1927
path = self.bzrdir._path_for_remote_call(self._client)
1928
body = "\n".join(revision_ids)
1929
response_tuple, response_handler = (
1930
self._call_with_body_bytes_expecting_body(
1931
"VersionedFileRepository.get_inventories",
1932
(path, ordering), body))
1933
if response_tuple[0] != "ok":
1934
raise errors.UnexpectedSmartServerResponse(response_tuple)
1935
deserializer = inventory_delta.InventoryDeltaDeserializer()
1936
byte_stream = response_handler.read_streamed_body()
1937
decoded = smart_repo._byte_stream_to_stream(byte_stream)
1939
# no results whatsoever
1941
src_format, stream = decoded
1942
if src_format.network_name() != self._format.network_name():
1943
raise AssertionError(
1944
"Mismatched RemoteRepository and stream src %r, %r" % (
1945
src_format.network_name(), self._format.network_name()))
1946
# ignore the src format, it's not really relevant
1947
prev_inv = Inventory(root_id=None,
1948
revision_id=_mod_revision.NULL_REVISION)
1949
# there should be just one substream, with inventory deltas
1950
substream_kind, substream = next(stream)
1951
if substream_kind != "inventory-deltas":
1952
raise AssertionError(
1953
"Unexpected stream %r received" % substream_kind)
1954
for record in substream:
1955
(parent_id, new_id, versioned_root, tree_references, invdelta) = (
1956
deserializer.parse_text_bytes(record.get_bytes_as("fulltext")))
1957
if parent_id != prev_inv.revision_id:
1958
raise AssertionError("invalid base %r != %r" % (parent_id,
1959
prev_inv.revision_id))
1960
inv = prev_inv.create_by_apply_delta(invdelta, new_id)
1961
yield inv, inv.revision_id
1964
def _iter_inventories_vfs(self, revision_ids, ordering=None):
1282
1965
self._ensure_real()
1283
return self._real_repository.get_inventory(revision_id)
1966
return self._real_repository._iter_inventories(revision_ids, ordering)
1285
1968
def iter_inventories(self, revision_ids, ordering=None):
1287
return self._real_repository.iter_inventories(revision_ids, ordering)
1969
"""Get many inventories by revision_ids.
1971
This will buffer some or all of the texts used in constructing the
1972
inventories in memory, but will only parse a single inventory at a
1975
:param revision_ids: The expected revision ids of the inventories.
1976
:param ordering: optional ordering, e.g. 'topological'. If not
1977
specified, the order of revision_ids will be preserved (by
1978
buffering if necessary).
1979
:return: An iterator of inventories.
1981
if ((None in revision_ids)
1982
or (_mod_revision.NULL_REVISION in revision_ids)):
1983
raise ValueError('cannot get null revision inventory')
1984
for inv, revid in self._iter_inventories(revision_ids, ordering):
1986
raise errors.NoSuchRevision(self, revid)
1989
def _iter_inventories(self, revision_ids, ordering=None):
1990
if len(revision_ids) == 0:
1992
missing = set(revision_ids)
1993
if ordering is None:
1994
order_as_requested = True
1996
order = list(revision_ids)
1998
next_revid = order.pop()
2000
order_as_requested = False
2001
if ordering != 'unordered' and self._fallback_repositories:
2002
raise ValueError('unsupported ordering %r' % ordering)
2003
iter_inv_fns = [self._iter_inventories_rpc] + [
2004
fallback._iter_inventories for fallback in
2005
self._fallback_repositories]
2007
for iter_inv in iter_inv_fns:
2008
request = [revid for revid in revision_ids if revid in missing]
2009
for inv, revid in iter_inv(request, ordering):
2012
missing.remove(inv.revision_id)
2013
if ordering != 'unordered':
2017
if order_as_requested:
2018
# Yield as many results as we can while preserving order.
2019
while next_revid in invs:
2020
inv = invs.pop(next_revid)
2021
yield inv, inv.revision_id
2023
next_revid = order.pop()
2025
# We still want to fully consume the stream, just
2026
# in case it is not actually finished at this point
2029
except errors.UnknownSmartMethod:
2030
for inv, revid in self._iter_inventories_vfs(revision_ids, ordering):
2034
if order_as_requested:
2035
if next_revid is not None:
2036
yield None, next_revid
2039
yield invs.get(revid), revid
2042
yield None, missing.pop()
1289
2044
@needs_read_lock
1290
2045
def get_revision(self, revision_id):
1292
return self._real_repository.get_revision(revision_id)
2046
return self.get_revisions([revision_id])[0]
1294
2048
def get_transaction(self):
1295
2049
self._ensure_real()
1388
2157
return self._real_repository._get_versioned_file_checker(
1389
2158
revisions, revision_versions_cache)
2160
def _iter_files_bytes_rpc(self, desired_files, absent):
2161
path = self.bzrdir._path_for_remote_call(self._client)
2164
for (file_id, revid, identifier) in desired_files:
2165
lines.append("%s\0%s" % (
2166
osutils.safe_file_id(file_id),
2167
osutils.safe_revision_id(revid)))
2168
identifiers.append(identifier)
2169
(response_tuple, response_handler) = (
2170
self._call_with_body_bytes_expecting_body(
2171
"Repository.iter_files_bytes", (path, ), "\n".join(lines)))
2172
if response_tuple != ('ok', ):
2173
response_handler.cancel_read_body()
2174
raise errors.UnexpectedSmartServerResponse(response_tuple)
2175
byte_stream = response_handler.read_streamed_body()
2176
def decompress_stream(start, byte_stream, unused):
2177
decompressor = zlib.decompressobj()
2178
yield decompressor.decompress(start)
2179
while decompressor.unused_data == "":
2181
data = next(byte_stream)
2182
except StopIteration:
2184
yield decompressor.decompress(data)
2185
yield decompressor.flush()
2186
unused.append(decompressor.unused_data)
2189
while not "\n" in unused:
2190
unused += next(byte_stream)
2191
header, rest = unused.split("\n", 1)
2192
args = header.split("\0")
2193
if args[0] == "absent":
2194
absent[identifiers[int(args[3])]] = (args[1], args[2])
2197
elif args[0] == "ok":
2200
raise errors.UnexpectedSmartServerResponse(args)
2202
yield (identifiers[idx],
2203
decompress_stream(rest, byte_stream, unused_chunks))
2204
unused = "".join(unused_chunks)
1391
2206
def iter_files_bytes(self, desired_files):
1392
2207
"""See Repository.iter_file_bytes.
1395
return self._real_repository.iter_files_bytes(desired_files)
2211
for (identifier, bytes_iterator) in self._iter_files_bytes_rpc(
2212
desired_files, absent):
2213
yield identifier, bytes_iterator
2214
for fallback in self._fallback_repositories:
2217
desired_files = [(key[0], key[1], identifier) for
2218
(identifier, key) in absent.iteritems()]
2219
for (identifier, bytes_iterator) in fallback.iter_files_bytes(desired_files):
2220
del absent[identifier]
2221
yield identifier, bytes_iterator
2223
# There may be more missing items, but raise an exception
2225
missing_identifier = absent.keys()[0]
2226
missing_key = absent[missing_identifier]
2227
raise errors.RevisionNotPresent(revision_id=missing_key[1],
2228
file_id=missing_key[0])
2229
except errors.UnknownSmartMethod:
2231
for (identifier, bytes_iterator) in (
2232
self._real_repository.iter_files_bytes(desired_files)):
2233
yield identifier, bytes_iterator
2235
def get_cached_parent_map(self, revision_ids):
2236
"""See breezy.CachingParentsProvider.get_cached_parent_map"""
2237
return self._unstacked_provider.get_cached_parent_map(revision_ids)
1397
2239
def get_parent_map(self, revision_ids):
1398
"""See bzrlib.Graph.get_parent_map()."""
2240
"""See breezy.Graph.get_parent_map()."""
1399
2241
return self._make_parents_provider().get_parent_map(revision_ids)
1401
2243
def _get_parent_map_rpc(self, keys):
1532
2363
@needs_read_lock
1533
2364
def get_signature_text(self, revision_id):
1535
return self._real_repository.get_signature_text(revision_id)
2365
path = self.bzrdir._path_for_remote_call(self._client)
2367
response_tuple, response_handler = self._call_expecting_body(
2368
'Repository.get_revision_signature_text', path, revision_id)
2369
except errors.UnknownSmartMethod:
2371
return self._real_repository.get_signature_text(revision_id)
2372
except errors.NoSuchRevision as err:
2373
for fallback in self._fallback_repositories:
2375
return fallback.get_signature_text(revision_id)
2376
except errors.NoSuchRevision:
2380
if response_tuple[0] != 'ok':
2381
raise errors.UnexpectedSmartServerResponse(response_tuple)
2382
return response_handler.read_body_bytes()
1537
2384
@needs_read_lock
1538
2385
def _get_inventory_xml(self, revision_id):
2386
# This call is used by older working tree formats,
2387
# which stored a serialized basis inventory.
1539
2388
self._ensure_real()
1540
2389
return self._real_repository._get_inventory_xml(revision_id)
1542
2392
def reconcile(self, other=None, thorough=False):
1544
return self._real_repository.reconcile(other=other, thorough=thorough)
2393
from .reconcile import RepoReconciler
2394
path = self.bzrdir._path_for_remote_call(self._client)
2396
response, handler = self._call_expecting_body(
2397
'Repository.reconcile', path, self._lock_token)
2398
except (errors.UnknownSmartMethod, errors.TokenLockingNotSupported):
2400
return self._real_repository.reconcile(other=other, thorough=thorough)
2401
if response != ('ok', ):
2402
raise errors.UnexpectedSmartServerResponse(response)
2403
body = handler.read_body_bytes()
2404
result = RepoReconciler(self)
2405
for line in body.split('\n'):
2408
key, val_text = line.split(':')
2409
if key == "garbage_inventories":
2410
result.garbage_inventories = int(val_text)
2411
elif key == "inconsistent_parents":
2412
result.inconsistent_parents = int(val_text)
2414
mutter("unknown reconcile key %r" % key)
1546
2417
def all_revision_ids(self):
1548
return self._real_repository.all_revision_ids()
2418
path = self.bzrdir._path_for_remote_call(self._client)
2420
response_tuple, response_handler = self._call_expecting_body(
2421
"Repository.all_revision_ids", path)
2422
except errors.UnknownSmartMethod:
2424
return self._real_repository.all_revision_ids()
2425
if response_tuple != ("ok", ):
2426
raise errors.UnexpectedSmartServerResponse(response_tuple)
2427
revids = set(response_handler.read_body_bytes().splitlines())
2428
for fallback in self._fallback_repositories:
2429
revids.update(set(fallback.all_revision_ids()))
2432
def _filtered_revision_trees(self, revision_ids, file_ids):
2433
"""Return Tree for a revision on this branch with only some files.
2435
:param revision_ids: a sequence of revision-ids;
2436
a revision-id may not be None or 'null:'
2437
:param file_ids: if not None, the result is filtered
2438
so that only those file-ids, their parents and their
2439
children are included.
2441
inventories = self.iter_inventories(revision_ids)
2442
for inv in inventories:
2443
# Should we introduce a FilteredRevisionTree class rather
2444
# than pre-filter the inventory here?
2445
filtered_inv = inv.filter(file_ids)
2446
yield InventoryRevisionTree(self, filtered_inv, filtered_inv.revision_id)
1550
2448
@needs_read_lock
1551
2449
def get_deltas_for_revisions(self, revisions, specific_fileids=None):
1553
return self._real_repository.get_deltas_for_revisions(revisions,
1554
specific_fileids=specific_fileids)
2450
medium = self._client._medium
2451
if medium._is_remote_before((1, 2)):
2453
for delta in self._real_repository.get_deltas_for_revisions(
2454
revisions, specific_fileids):
2457
# Get the revision-ids of interest
2458
required_trees = set()
2459
for revision in revisions:
2460
required_trees.add(revision.revision_id)
2461
required_trees.update(revision.parent_ids[:1])
2463
# Get the matching filtered trees. Note that it's more
2464
# efficient to pass filtered trees to changes_from() rather
2465
# than doing the filtering afterwards. changes_from() could
2466
# arguably do the filtering itself but it's path-based, not
2467
# file-id based, so filtering before or afterwards is
2469
if specific_fileids is None:
2470
trees = dict((t.get_revision_id(), t) for
2471
t in self.revision_trees(required_trees))
2473
trees = dict((t.get_revision_id(), t) for
2474
t in self._filtered_revision_trees(required_trees,
2477
# Calculate the deltas
2478
for revision in revisions:
2479
if not revision.parent_ids:
2480
old_tree = self.revision_tree(_mod_revision.NULL_REVISION)
2482
old_tree = trees[revision.parent_ids[0]]
2483
yield trees[revision.revision_id].changes_from(old_tree)
1556
2485
@needs_read_lock
1557
2486
def get_revision_delta(self, revision_id, specific_fileids=None):
1559
return self._real_repository.get_revision_delta(revision_id,
1560
specific_fileids=specific_fileids)
2487
r = self.get_revision(revision_id)
2488
return list(self.get_deltas_for_revisions([r],
2489
specific_fileids=specific_fileids))[0]
1562
2491
@needs_read_lock
1563
2492
def revision_trees(self, revision_ids):
1565
return self._real_repository.revision_trees(revision_ids)
2493
inventories = self.iter_inventories(revision_ids)
2494
for inv in inventories:
2495
yield InventoryRevisionTree(self, inv, inv.revision_id)
1567
2497
@needs_read_lock
1568
2498
def get_revision_reconcile(self, revision_id):
1680
2623
self._ensure_real()
1681
2624
return self._real_repository.texts
2626
def _iter_revisions_rpc(self, revision_ids):
2627
body = "\n".join(revision_ids)
2628
path = self.bzrdir._path_for_remote_call(self._client)
2629
response_tuple, response_handler = (
2630
self._call_with_body_bytes_expecting_body(
2631
"Repository.iter_revisions", (path, ), body))
2632
if response_tuple[0] != "ok":
2633
raise errors.UnexpectedSmartServerResponse(response_tuple)
2634
serializer_format = response_tuple[1]
2635
serializer = serializer_format_registry.get(serializer_format)
2636
byte_stream = response_handler.read_streamed_body()
2637
decompressor = zlib.decompressobj()
2639
for bytes in byte_stream:
2640
chunks.append(decompressor.decompress(bytes))
2641
if decompressor.unused_data != "":
2642
chunks.append(decompressor.flush())
2643
yield serializer.read_revision_from_string("".join(chunks))
2644
unused = decompressor.unused_data
2645
decompressor = zlib.decompressobj()
2646
chunks = [decompressor.decompress(unused)]
2647
chunks.append(decompressor.flush())
2648
text = "".join(chunks)
2650
yield serializer.read_revision_from_string("".join(chunks))
1683
2652
@needs_read_lock
1684
2653
def get_revisions(self, revision_ids):
1686
return self._real_repository.get_revisions(revision_ids)
2654
if revision_ids is None:
2655
revision_ids = self.all_revision_ids()
2657
for rev_id in revision_ids:
2658
if not rev_id or not isinstance(rev_id, basestring):
2659
raise errors.InvalidRevisionId(
2660
revision_id=rev_id, branch=self)
2662
missing = set(revision_ids)
2664
for rev in self._iter_revisions_rpc(revision_ids):
2665
missing.remove(rev.revision_id)
2666
revs[rev.revision_id] = rev
2667
except errors.UnknownSmartMethod:
2669
return self._real_repository.get_revisions(revision_ids)
2670
for fallback in self._fallback_repositories:
2673
for revid in list(missing):
2674
# XXX JRV 2011-11-20: It would be nice if there was a
2675
# public method on Repository that could be used to query
2676
# for revision objects *without* failing completely if one
2677
# was missing. There is VersionedFileRepository._iter_revisions,
2678
# but unfortunately that's private and not provided by
2679
# all repository implementations.
2681
revs[revid] = fallback.get_revision(revid)
2682
except errors.NoSuchRevision:
2685
missing.remove(revid)
2687
raise errors.NoSuchRevision(self, list(missing)[0])
2688
return [revs[revid] for revid in revision_ids]
1688
2690
def supports_rich_root(self):
1689
2691
return self._format.rich_root_data
1691
def iter_reverse_revision_history(self, revision_id):
1693
return self._real_repository.iter_reverse_revision_history(revision_id)
1696
2694
def _serializer(self):
1697
2695
return self._format._serializer
1699
2698
def store_revision_signature(self, gpg_strategy, plaintext, revision_id):
1701
return self._real_repository.store_revision_signature(
1702
gpg_strategy, plaintext, revision_id)
2699
signature = gpg_strategy.sign(plaintext)
2700
self.add_signature_text(revision_id, signature)
1704
2702
def add_signature_text(self, revision_id, signature):
1706
return self._real_repository.add_signature_text(revision_id, signature)
2703
if self._real_repository:
2704
# If there is a real repository the write group will
2705
# be in the real repository as well, so use that:
2707
return self._real_repository.add_signature_text(
2708
revision_id, signature)
2709
path = self.bzrdir._path_for_remote_call(self._client)
2710
response, handler = self._call_with_body_bytes_expecting_body(
2711
'Repository.add_signature_text', (path, self._lock_token,
2712
revision_id) + tuple(self._write_group_tokens), signature)
2713
handler.cancel_read_body()
2715
if response[0] != 'ok':
2716
raise errors.UnexpectedSmartServerResponse(response)
2717
self._write_group_tokens = response[1:]
1708
2719
def has_signature_for_revision_id(self, revision_id):
1710
return self._real_repository.has_signature_for_revision_id(revision_id)
2720
path = self.bzrdir._path_for_remote_call(self._client)
2722
response = self._call('Repository.has_signature_for_revision_id',
2724
except errors.UnknownSmartMethod:
2726
return self._real_repository.has_signature_for_revision_id(
2728
if response[0] not in ('yes', 'no'):
2729
raise SmartProtocolError('unexpected response code %s' % (response,))
2730
if response[0] == 'yes':
2732
for fallback in self._fallback_repositories:
2733
if fallback.has_signature_for_revision_id(revision_id):
2738
def verify_revision_signature(self, revision_id, gpg_strategy):
2739
if not self.has_signature_for_revision_id(revision_id):
2740
return gpg.SIGNATURE_NOT_SIGNED, None
2741
signature = self.get_signature_text(revision_id)
2743
testament = _mod_testament.Testament.from_revision(self, revision_id)
2744
plaintext = testament.as_short_text()
2746
return gpg_strategy.verify(signature, plaintext)
1712
2748
def item_keys_introduced_by(self, revision_ids, _files_pb=None):
1713
2749
self._ensure_real()
1714
2750
return self._real_repository.item_keys_introduced_by(revision_ids,
1715
2751
_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
2753
def _find_inconsistent_revision_parents(self, revisions_iterator=None):
1723
2754
self._ensure_real()
1724
2755
return self._real_repository._find_inconsistent_revision_parents(
2071
3114
if isinstance(a_bzrdir, RemoteBzrDir):
2072
3115
a_bzrdir._ensure_real()
2073
3116
result = self._custom_format.initialize(a_bzrdir._real_bzrdir,
3117
name=name, append_revisions_only=append_revisions_only,
3118
repository=repository)
2076
3120
# We assume the bzrdir is parameterised; it may not be.
2077
result = self._custom_format.initialize(a_bzrdir, name)
3121
result = self._custom_format.initialize(a_bzrdir, name=name,
3122
append_revisions_only=append_revisions_only,
3123
repository=repository)
2078
3124
if (isinstance(a_bzrdir, RemoteBzrDir) and
2079
3125
not isinstance(result, RemoteBranch)):
2080
3126
result = RemoteBranch(a_bzrdir, a_bzrdir.find_repository(), result,
2084
def initialize(self, a_bzrdir, name=None):
3130
def initialize(self, a_bzrdir, name=None, repository=None,
3131
append_revisions_only=None):
3133
name = a_bzrdir._get_selected_branch()
2085
3134
# 1) get the network name to use.
2086
3135
if self._custom_format:
2087
3136
network_name = self._custom_format.network_name()
2089
# Select the current bzrlib default and ask for that.
2090
reference_bzrdir_format = bzrdir.format_registry.get('default')()
3138
# Select the current breezy default and ask for that.
3139
reference_bzrdir_format = controldir.format_registry.get('default')()
2091
3140
reference_format = reference_bzrdir_format.get_branch_format()
2092
3141
self._custom_format = reference_format
2093
3142
network_name = reference_format.network_name()
2094
3143
# Being asked to create on a non RemoteBzrDir:
2095
3144
if not isinstance(a_bzrdir, RemoteBzrDir):
2096
return self._vfs_initialize(a_bzrdir, name=name)
3145
return self._vfs_initialize(a_bzrdir, name=name,
3146
append_revisions_only=append_revisions_only,
3147
repository=repository)
2097
3148
medium = a_bzrdir._client._medium
2098
3149
if medium._is_remote_before((1, 13)):
2099
return self._vfs_initialize(a_bzrdir, name=name)
3150
return self._vfs_initialize(a_bzrdir, name=name,
3151
append_revisions_only=append_revisions_only,
3152
repository=repository)
2100
3153
# Creating on a remote bzr dir.
2101
3154
# 2) try direct creation via RPC
2102
3155
path = a_bzrdir._path_for_remote_call(a_bzrdir._client)
2103
if name is not None:
2104
3157
# XXX JRV20100304: Support creating colocated branches
2105
3158
raise errors.NoColocatedBranchSupport(self)
2106
3159
verb = 'BzrDir.create_branch'
2148
3217
self._ensure_real()
2149
3218
return self._custom_format.supports_set_append_revisions_only()
3220
def _use_default_local_heads_to_fetch(self):
3221
# If the branch format is a metadir format *and* its heads_to_fetch
3222
# implementation is not overridden vs the base class, we can use the
3223
# base class logic rather than use the heads_to_fetch RPC. This is
3224
# usually cheaper in terms of net round trips, as the last-revision and
3225
# tags info fetched is cached and would be fetched anyway.
3227
if isinstance(self._custom_format, branch.BranchFormatMetadir):
3228
branch_class = self._custom_format._branch_class()
3229
heads_to_fetch_impl = branch_class.heads_to_fetch.__func__
3230
if heads_to_fetch_impl is branch.Branch.heads_to_fetch.__func__:
3235
class RemoteBranchStore(_mod_config.IniFileStore):
3236
"""Branch store which attempts to use HPSS calls to retrieve branch store.
3238
Note that this is specific to bzr-based formats.
3241
def __init__(self, branch):
3242
super(RemoteBranchStore, self).__init__()
3243
self.branch = branch
3245
self._real_store = None
3247
def external_url(self):
3248
return urlutils.join(self.branch.user_url, 'branch.conf')
3250
def _load_content(self):
3251
path = self.branch._remote_path()
3253
response, handler = self.branch._call_expecting_body(
3254
'Branch.get_config_file', path)
3255
except errors.UnknownSmartMethod:
3257
return self._real_store._load_content()
3258
if len(response) and response[0] != 'ok':
3259
raise errors.UnexpectedSmartServerResponse(response)
3260
return handler.read_body_bytes()
3262
def _save_content(self, content):
3263
path = self.branch._remote_path()
3265
response, handler = self.branch._call_with_body_bytes_expecting_body(
3266
'Branch.put_config_file', (path,
3267
self.branch._lock_token, self.branch._repo_lock_token),
3269
except errors.UnknownSmartMethod:
3271
return self._real_store._save_content(content)
3272
handler.cancel_read_body()
3273
if response != ('ok', ):
3274
raise errors.UnexpectedSmartServerResponse(response)
3276
def _ensure_real(self):
3277
self.branch._ensure_real()
3278
if self._real_store is None:
3279
self._real_store = _mod_config.BranchStore(self.branch)
2152
3282
class RemoteBranch(branch.Branch, _RpcHelper, lock._RelockDebugMixin):
2153
3283
"""Branch stored on a server accessed by HPSS RPC.
2654
3833
_override_hook_target=self, **kwargs)
2656
3835
@needs_read_lock
2657
def push(self, target, overwrite=False, stop_revision=None):
3836
def push(self, target, overwrite=False, stop_revision=None, lossy=False):
2658
3837
self._ensure_real()
2659
3838
return self._real_branch.push(
2660
target, overwrite=overwrite, stop_revision=stop_revision,
3839
target, overwrite=overwrite, stop_revision=stop_revision, lossy=lossy,
2661
3840
_override_hook_source_branch=self)
3842
def peek_lock_mode(self):
3843
return self._lock_mode
2663
3845
def is_locked(self):
2664
3846
return self._lock_count >= 1
2666
3848
@needs_read_lock
3849
def revision_id_to_dotted_revno(self, revision_id):
3850
"""Given a revision id, return its dotted revno.
3852
:return: a tuple like (1,) or (400,1,3).
3855
response = self._call('Branch.revision_id_to_revno',
3856
self._remote_path(), revision_id)
3857
except errors.UnknownSmartMethod:
3859
return self._real_branch.revision_id_to_dotted_revno(revision_id)
3860
if response[0] == 'ok':
3861
return tuple([int(x) for x in response[1:]])
3863
raise errors.UnexpectedSmartServerResponse(response)
2667
3866
def revision_id_to_revno(self, revision_id):
2669
return self._real_branch.revision_id_to_revno(revision_id)
3867
"""Given a revision id on the branch mainline, return its revno.
3872
response = self._call('Branch.revision_id_to_revno',
3873
self._remote_path(), revision_id)
3874
except errors.UnknownSmartMethod:
3876
return self._real_branch.revision_id_to_revno(revision_id)
3877
if response[0] == 'ok':
3878
if len(response) == 2:
3879
return int(response[1])
3880
raise NoSuchRevision(self, revision_id)
3882
raise errors.UnexpectedSmartServerResponse(response)
2671
3884
@needs_write_lock
2672
3885
def set_last_revision_info(self, revno, revision_id):
2673
3886
# XXX: These should be returned by the set_last_revision_info verb
2674
3887
old_revno, old_revid = self.last_revision_info()
2675
3888
self._run_pre_change_branch_tip_hooks(revno, revision_id)
2676
revision_id = ensure_null(revision_id)
3889
if not revision_id or not isinstance(revision_id, basestring):
3890
raise errors.InvalidRevisionId(revision_id=revision_id, branch=self)
2678
3892
response = self._call('Branch.set_last_revision_info',
2679
3893
self._remote_path(), self._lock_token, self._repo_lock_token,
2708
3922
except errors.UnknownSmartMethod:
2709
3923
medium._remember_remote_is_before((1, 6))
2710
3924
self._clear_cached_state_of_remote_branch_only()
2711
self.set_revision_history(self._lefthand_history(revision_id,
2712
last_rev=last_rev,other_branch=other_branch))
3925
graph = self.repository.get_graph()
3926
(last_revno, last_revid) = self.last_revision_info()
3927
known_revision_ids = [
3928
(last_revid, last_revno),
3929
(_mod_revision.NULL_REVISION, 0),
3931
if last_rev is not None:
3932
if not graph.is_ancestor(last_rev, revision_id):
3933
# our previous tip is not merged into stop_revision
3934
raise errors.DivergedBranches(self, other_branch)
3935
revno = graph.find_distance_to_null(revision_id, known_revision_ids)
3936
self.set_last_revision_info(revno, revision_id)
2714
3938
def set_push_location(self, location):
3939
self._set_config_location('push_location', location)
3941
def heads_to_fetch(self):
3942
if self._format._use_default_local_heads_to_fetch():
3943
# We recognise this format, and its heads-to-fetch implementation
3944
# is the default one (tip + tags). In this case it's cheaper to
3945
# just use the default implementation rather than a special RPC as
3946
# the tip and tags data is cached.
3947
return branch.Branch.heads_to_fetch(self)
3948
medium = self._client._medium
3949
if medium._is_remote_before((2, 4)):
3950
return self._vfs_heads_to_fetch()
3952
return self._rpc_heads_to_fetch()
3953
except errors.UnknownSmartMethod:
3954
medium._remember_remote_is_before((2, 4))
3955
return self._vfs_heads_to_fetch()
3957
def _rpc_heads_to_fetch(self):
3958
response = self._call('Branch.heads_to_fetch', self._remote_path())
3959
if len(response) != 2:
3960
raise errors.UnexpectedSmartServerResponse(response)
3961
must_fetch, if_present_fetch = response
3962
return set(must_fetch), set(if_present_fetch)
3964
def _vfs_heads_to_fetch(self):
2715
3965
self._ensure_real()
2716
return self._real_branch.set_push_location(location)
3966
return self._real_branch.heads_to_fetch()
2719
3969
class RemoteConfig(object):
2774
4034
medium = self._branch._client._medium
2775
4035
if medium._is_remote_before((1, 14)):
2776
4036
return self._vfs_set_option(value, name, section)
4037
if isinstance(value, dict):
4038
if medium._is_remote_before((2, 2)):
4039
return self._vfs_set_option(value, name, section)
4040
return self._set_config_option_dict(value, name, section)
4042
return self._set_config_option(value, name, section)
4044
def _set_config_option(self, value, name, section):
2778
4046
path = self._branch._remote_path()
2779
4047
response = self._branch._client.call('Branch.set_config_option',
2780
4048
path, self._branch._lock_token, self._branch._repo_lock_token,
2781
4049
value.encode('utf8'), name, section or '')
2782
4050
except errors.UnknownSmartMethod:
4051
medium = self._branch._client._medium
2783
4052
medium._remember_remote_is_before((1, 14))
2784
4053
return self._vfs_set_option(value, name, section)
2785
4054
if response != ():
2786
4055
raise errors.UnexpectedSmartServerResponse(response)
4057
def _serialize_option_dict(self, option_dict):
4059
for key, value in option_dict.items():
4060
if isinstance(key, unicode):
4061
key = key.encode('utf8')
4062
if isinstance(value, unicode):
4063
value = value.encode('utf8')
4064
utf8_dict[key] = value
4065
return bencode.bencode(utf8_dict)
4067
def _set_config_option_dict(self, value, name, section):
4069
path = self._branch._remote_path()
4070
serialised_dict = self._serialize_option_dict(value)
4071
response = self._branch._client.call(
4072
'Branch.set_config_option_dict',
4073
path, self._branch._lock_token, self._branch._repo_lock_token,
4074
serialised_dict, name, section or '')
4075
except errors.UnknownSmartMethod:
4076
medium = self._branch._client._medium
4077
medium._remember_remote_is_before((2, 2))
4078
return self._vfs_set_option(value, name, section)
4080
raise errors.UnexpectedSmartServerResponse(response)
2788
4082
def _real_object(self):
2789
4083
self._branch._ensure_real()
2790
4084
return self._branch._real_branch
2867
4164
return context['path']
2868
except KeyError, key_err:
4165
except KeyError as key_err:
2870
4167
return err.error_args[0]
2871
except IndexError, idx_err:
4168
except IndexError as idx_err:
2873
4170
'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'):
4174
translator = error_translators.get(err.error_verb)
4178
raise translator(err, find, get_path)
4180
translator = no_context_error_translators.get(err.error_verb)
4182
raise errors.UnknownErrorFromSmartServer(err)
4184
raise translator(err)
4187
error_translators.register('NoSuchRevision',
4188
lambda err, find, get_path: NoSuchRevision(
4189
find('branch'), err.error_args[0]))
4190
error_translators.register('nosuchrevision',
4191
lambda err, find, get_path: NoSuchRevision(
4192
find('repository'), err.error_args[0]))
4194
def _translate_nobranch_error(err, find, get_path):
4195
if len(err.error_args) >= 1:
4196
extra = err.error_args[0]
4199
return errors.NotBranchError(path=find('bzrdir').root_transport.base,
4202
error_translators.register('nobranch', _translate_nobranch_error)
4203
error_translators.register('norepository',
4204
lambda err, find, get_path: errors.NoRepositoryPresent(
4206
error_translators.register('UnlockableTransport',
4207
lambda err, find, get_path: errors.UnlockableTransport(
4208
find('bzrdir').root_transport))
4209
error_translators.register('TokenMismatch',
4210
lambda err, find, get_path: errors.TokenMismatch(
4211
find('token'), '(remote token)'))
4212
error_translators.register('Diverged',
4213
lambda err, find, get_path: errors.DivergedBranches(
4214
find('branch'), find('other_branch')))
4215
error_translators.register('NotStacked',
4216
lambda err, find, get_path: errors.NotStacked(branch=find('branch')))
4218
def _translate_PermissionDenied(err, find, get_path):
4220
if len(err.error_args) >= 2:
4221
extra = err.error_args[1]
4224
return errors.PermissionDenied(path, extra=extra)
4226
error_translators.register('PermissionDenied', _translate_PermissionDenied)
4227
error_translators.register('ReadError',
4228
lambda err, find, get_path: errors.ReadError(get_path()))
4229
error_translators.register('NoSuchFile',
4230
lambda err, find, get_path: errors.NoSuchFile(get_path()))
4231
error_translators.register('TokenLockingNotSupported',
4232
lambda err, find, get_path: errors.TokenLockingNotSupported(
4233
find('repository')))
4234
error_translators.register('UnsuspendableWriteGroup',
4235
lambda err, find, get_path: errors.UnsuspendableWriteGroup(
4236
repository=find('repository')))
4237
error_translators.register('UnresumableWriteGroup',
4238
lambda err, find, get_path: errors.UnresumableWriteGroup(
4239
repository=find('repository'), write_groups=err.error_args[0],
4240
reason=err.error_args[1]))
4241
no_context_error_translators.register('IncompatibleRepositories',
4242
lambda err: errors.IncompatibleRepositories(
4243
err.error_args[0], err.error_args[1], err.error_args[2]))
4244
no_context_error_translators.register('LockContention',
4245
lambda err: errors.LockContention('(remote lock)'))
4246
no_context_error_translators.register('LockFailed',
4247
lambda err: errors.LockFailed(err.error_args[0], err.error_args[1]))
4248
no_context_error_translators.register('TipChangeRejected',
4249
lambda err: errors.TipChangeRejected(err.error_args[0].decode('utf8')))
4250
no_context_error_translators.register('UnstackableBranchFormat',
4251
lambda err: errors.UnstackableBranchFormat(*err.error_args))
4252
no_context_error_translators.register('UnstackableRepositoryFormat',
4253
lambda err: errors.UnstackableRepositoryFormat(*err.error_args))
4254
no_context_error_translators.register('FileExists',
4255
lambda err: errors.FileExists(err.error_args[0]))
4256
no_context_error_translators.register('DirectoryNotEmpty',
4257
lambda err: errors.DirectoryNotEmpty(err.error_args[0]))
4259
def _translate_short_readv_error(err):
4260
args = err.error_args
4261
return errors.ShortReadvError(args[0], int(args[1]), int(args[2]),
4264
no_context_error_translators.register('ShortReadvError',
4265
_translate_short_readv_error)
4267
def _translate_unicode_error(err):
2932
4268
encoding = str(err.error_args[0]) # encoding must always be a string
2933
4269
val = err.error_args[1]
2934
4270
start = int(err.error_args[2])