89
# Note: RemoteBzrDirFormat is in bzrdir.py
91
class RemoteBzrDir(BzrDir, _RpcHelper):
109
# Note that RemoteBzrDirProber lives in breezy.bzrdir so breezy.remote
110
# does not have to be imported unless a remote format is involved.
112
class RemoteBzrDirFormat(_mod_bzrdir.BzrDirMetaFormat1):
113
"""Format representing bzrdirs accessed via a smart server"""
115
supports_workingtrees = False
117
colocated_branches = False
120
_mod_bzrdir.BzrDirMetaFormat1.__init__(self)
121
# XXX: It's a bit ugly that the network name is here, because we'd
122
# like to believe that format objects are stateless or at least
123
# immutable, However, we do at least avoid mutating the name after
124
# it's returned. See <https://bugs.launchpad.net/bzr/+bug/504102>
125
self._network_name = None
128
return "%s(_network_name=%r)" % (self.__class__.__name__,
131
def get_format_description(self):
132
if self._network_name:
134
real_format = controldir.network_format_registry.get(
139
return 'Remote: ' + real_format.get_format_description()
140
return 'bzr remote bzrdir'
142
def get_format_string(self):
143
raise NotImplementedError(self.get_format_string)
145
def network_name(self):
146
if self._network_name:
147
return self._network_name
149
raise AssertionError("No network name set.")
151
def initialize_on_transport(self, transport):
153
# hand off the request to the smart server
154
client_medium = transport.get_smart_medium()
155
except errors.NoSmartMedium:
156
# TODO: lookup the local format from a server hint.
157
local_dir_format = _mod_bzrdir.BzrDirMetaFormat1()
158
return local_dir_format.initialize_on_transport(transport)
159
client = _SmartClient(client_medium)
160
path = client.remote_path_from_transport(transport)
162
response = client.call('BzrDirFormat.initialize', path)
163
except errors.ErrorFromSmartServer as err:
164
_translate_error(err, path=path)
165
if response[0] != 'ok':
166
raise errors.SmartProtocolError('unexpected response code %s' % (response,))
167
format = RemoteBzrDirFormat()
168
self._supply_sub_formats_to(format)
169
return RemoteBzrDir(transport, format)
171
def parse_NoneTrueFalse(self, arg):
178
raise AssertionError("invalid arg %r" % arg)
180
def _serialize_NoneTrueFalse(self, arg):
187
def _serialize_NoneString(self, arg):
190
def initialize_on_transport_ex(self, transport, use_existing_dir=False,
191
create_prefix=False, force_new_repo=False, stacked_on=None,
192
stack_on_pwd=None, repo_format_name=None, make_working_trees=None,
195
# hand off the request to the smart server
196
client_medium = transport.get_smart_medium()
197
except errors.NoSmartMedium:
200
# Decline to open it if the server doesn't support our required
201
# version (3) so that the VFS-based transport will do it.
202
if client_medium.should_probe():
204
server_version = client_medium.protocol_version()
205
if server_version != '2':
209
except errors.SmartProtocolError:
210
# Apparently there's no usable smart server there, even though
211
# the medium supports the smart protocol.
216
client = _SmartClient(client_medium)
217
path = client.remote_path_from_transport(transport)
218
if client_medium._is_remote_before((1, 16)):
221
# TODO: lookup the local format from a server hint.
222
local_dir_format = _mod_bzrdir.BzrDirMetaFormat1()
223
self._supply_sub_formats_to(local_dir_format)
224
return local_dir_format.initialize_on_transport_ex(transport,
225
use_existing_dir=use_existing_dir, create_prefix=create_prefix,
226
force_new_repo=force_new_repo, stacked_on=stacked_on,
227
stack_on_pwd=stack_on_pwd, repo_format_name=repo_format_name,
228
make_working_trees=make_working_trees, shared_repo=shared_repo,
230
return self._initialize_on_transport_ex_rpc(client, path, transport,
231
use_existing_dir, create_prefix, force_new_repo, stacked_on,
232
stack_on_pwd, repo_format_name, make_working_trees, shared_repo)
234
def _initialize_on_transport_ex_rpc(self, client, path, transport,
235
use_existing_dir, create_prefix, force_new_repo, stacked_on,
236
stack_on_pwd, repo_format_name, make_working_trees, shared_repo):
238
args.append(self._serialize_NoneTrueFalse(use_existing_dir))
239
args.append(self._serialize_NoneTrueFalse(create_prefix))
240
args.append(self._serialize_NoneTrueFalse(force_new_repo))
241
args.append(self._serialize_NoneString(stacked_on))
242
# stack_on_pwd is often/usually our transport
245
stack_on_pwd = transport.relpath(stack_on_pwd)
248
except errors.PathNotChild:
250
args.append(self._serialize_NoneString(stack_on_pwd))
251
args.append(self._serialize_NoneString(repo_format_name))
252
args.append(self._serialize_NoneTrueFalse(make_working_trees))
253
args.append(self._serialize_NoneTrueFalse(shared_repo))
254
request_network_name = self._network_name or \
255
_mod_bzrdir.BzrDirFormat.get_default_format().network_name()
257
response = client.call('BzrDirFormat.initialize_ex_1.16',
258
request_network_name, path, *args)
259
except errors.UnknownSmartMethod:
260
client._medium._remember_remote_is_before((1,16))
261
local_dir_format = _mod_bzrdir.BzrDirMetaFormat1()
262
self._supply_sub_formats_to(local_dir_format)
263
return local_dir_format.initialize_on_transport_ex(transport,
264
use_existing_dir=use_existing_dir, create_prefix=create_prefix,
265
force_new_repo=force_new_repo, stacked_on=stacked_on,
266
stack_on_pwd=stack_on_pwd, repo_format_name=repo_format_name,
267
make_working_trees=make_working_trees, shared_repo=shared_repo,
269
except errors.ErrorFromSmartServer as err:
270
_translate_error(err, path=path)
271
repo_path = response[0]
272
bzrdir_name = response[6]
273
require_stacking = response[7]
274
require_stacking = self.parse_NoneTrueFalse(require_stacking)
275
format = RemoteBzrDirFormat()
276
format._network_name = bzrdir_name
277
self._supply_sub_formats_to(format)
278
bzrdir = RemoteBzrDir(transport, format, _client=client)
280
repo_format = response_tuple_to_repo_format(response[1:])
284
repo_bzrdir_format = RemoteBzrDirFormat()
285
repo_bzrdir_format._network_name = response[5]
286
repo_bzr = RemoteBzrDir(transport.clone(repo_path),
290
final_stack = response[8] or None
291
final_stack_pwd = response[9] or None
293
final_stack_pwd = urlutils.join(
294
transport.base, final_stack_pwd)
295
remote_repo = RemoteRepository(repo_bzr, repo_format)
296
if len(response) > 10:
297
# Updated server verb that locks remotely.
298
repo_lock_token = response[10] or None
299
remote_repo.lock_write(repo_lock_token, _skip_rpc=True)
301
remote_repo.dont_leave_lock_in_place()
303
remote_repo.lock_write()
304
policy = _mod_bzrdir.UseExistingRepository(remote_repo, final_stack,
305
final_stack_pwd, require_stacking)
306
policy.acquire_repository()
310
bzrdir._format.set_branch_format(self.get_branch_format())
312
# The repo has already been created, but we need to make sure that
313
# we'll make a stackable branch.
314
bzrdir._format.require_stacking(_skip_repo=True)
315
return remote_repo, bzrdir, require_stacking, policy
317
def _open(self, transport):
318
return RemoteBzrDir(transport, self)
320
def __eq__(self, other):
321
if not isinstance(other, RemoteBzrDirFormat):
323
return self.get_format_description() == other.get_format_description()
325
def __return_repository_format(self):
326
# Always return a RemoteRepositoryFormat object, but if a specific bzr
327
# repository format has been asked for, tell the RemoteRepositoryFormat
328
# that it should use that for init() etc.
329
result = RemoteRepositoryFormat()
330
custom_format = getattr(self, '_repository_format', None)
332
if isinstance(custom_format, RemoteRepositoryFormat):
335
# We will use the custom format to create repositories over the
336
# wire; expose its details like rich_root_data for code to
338
result._custom_format = custom_format
341
def get_branch_format(self):
342
result = _mod_bzrdir.BzrDirMetaFormat1.get_branch_format(self)
343
if not isinstance(result, RemoteBranchFormat):
344
new_result = RemoteBranchFormat()
345
new_result._custom_format = result
347
self.set_branch_format(new_result)
351
repository_format = property(__return_repository_format,
352
_mod_bzrdir.BzrDirMetaFormat1._set_repository_format) #.im_func)
355
class RemoteControlStore(_mod_config.IniFileStore):
356
"""Control store which attempts to use HPSS calls to retrieve control store.
358
Note that this is specific to bzr-based formats.
361
def __init__(self, bzrdir):
362
super(RemoteControlStore, self).__init__()
364
self._real_store = None
366
def lock_write(self, token=None):
368
return self._real_store.lock_write(token)
372
return self._real_store.unlock()
376
# We need to be able to override the undecorated implementation
377
self.save_without_locking()
379
def save_without_locking(self):
380
super(RemoteControlStore, self).save()
382
def _ensure_real(self):
383
self.bzrdir._ensure_real()
384
if self._real_store is None:
385
self._real_store = _mod_config.ControlStore(self.bzrdir)
387
def external_url(self):
388
return urlutils.join(self.branch.user_url, 'control.conf')
390
def _load_content(self):
391
medium = self.bzrdir._client._medium
392
path = self.bzrdir._path_for_remote_call(self.bzrdir._client)
394
response, handler = self.bzrdir._call_expecting_body(
395
'BzrDir.get_config_file', path)
396
except errors.UnknownSmartMethod:
398
return self._real_store._load_content()
399
if len(response) and response[0] != 'ok':
400
raise errors.UnexpectedSmartServerResponse(response)
401
return handler.read_body_bytes()
403
def _save_content(self, content):
404
# FIXME JRV 2011-11-22: Ideally this should use a
405
# HPSS call too, but at the moment it is not possible
406
# to write lock control directories.
408
return self._real_store._save_content(content)
411
class RemoteBzrDir(_mod_bzrdir.BzrDir, _RpcHelper):
92
412
"""Control directory on a remote server, accessed via bzr:// or similar."""
94
414
def __init__(self, transport, format, _client=None, _force_probe=False):
266
657
def destroy_branch(self, name=None):
267
658
"""See BzrDir.destroy_branch"""
269
self._real_bzrdir.destroy_branch(name=name)
660
name = self._get_selected_branch()
662
raise errors.NoColocatedBranchSupport(self)
663
path = self._path_for_remote_call(self._client)
669
response = self._call('BzrDir.destroy_branch', path, *args)
670
except errors.UnknownSmartMethod:
672
self._real_bzrdir.destroy_branch(name=name)
673
self._next_open_branch_result = None
270
675
self._next_open_branch_result = None
676
if response[0] != 'ok':
677
raise SmartProtocolError('unexpected response code %s' % (response,))
272
def create_workingtree(self, revision_id=None, from_branch=None):
679
def create_workingtree(self, revision_id=None, from_branch=None,
680
accelerator_tree=None, hardlink=False):
273
681
raise errors.NotLocalUrl(self.transport.base)
275
def find_branch_format(self):
683
def find_branch_format(self, name=None):
276
684
"""Find the branch 'format' for this bzrdir.
278
686
This might be a synthetic object for e.g. RemoteBranch and SVN.
280
b = self.open_branch()
688
b = self.open_branch(name=name)
283
def get_branch_reference(self):
691
def get_branches(self, possible_transports=None, ignore_fallbacks=False):
692
path = self._path_for_remote_call(self._client)
694
response, handler = self._call_expecting_body(
695
'BzrDir.get_branches', path)
696
except errors.UnknownSmartMethod:
698
return self._real_bzrdir.get_branches()
699
if response[0] != "success":
700
raise errors.UnexpectedSmartServerResponse(response)
701
body = bencode.bdecode(handler.read_body_bytes())
703
for (name, value) in body.iteritems():
704
ret[name] = self._open_branch(name, value[0], value[1],
705
possible_transports=possible_transports,
706
ignore_fallbacks=ignore_fallbacks)
709
def set_branch_reference(self, target_branch, name=None):
710
"""See BzrDir.set_branch_reference()."""
712
name = self._get_selected_branch()
714
raise errors.NoColocatedBranchSupport(self)
716
return self._real_bzrdir.set_branch_reference(target_branch, name=name)
718
def get_branch_reference(self, name=None):
284
719
"""See BzrDir.get_branch_reference()."""
721
name = self._get_selected_branch()
723
raise errors.NoColocatedBranchSupport(self)
285
724
response = self._get_branch_reference()
286
725
if response[0] == 'ref':
287
726
return response[1]
318
757
raise errors.UnexpectedSmartServerResponse(response)
321
def _get_tree_branch(self):
760
def _get_tree_branch(self, name=None):
322
761
"""See BzrDir._get_tree_branch()."""
323
return None, self.open_branch()
762
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':
764
def _open_branch(self, name, kind, location_or_format,
765
ignore_fallbacks=False, possible_transports=None):
336
767
# a branch reference, use the existing BranchReference logic.
337
768
format = BranchReferenceFormat()
338
769
return format.open(self, name=name, _found=True,
339
location=response[1], ignore_fallbacks=ignore_fallbacks)
340
branch_format_name = response[1]
770
location=location_or_format, ignore_fallbacks=ignore_fallbacks,
771
possible_transports=possible_transports)
772
branch_format_name = location_or_format
341
773
if not branch_format_name:
342
774
branch_format_name = None
343
775
format = RemoteBranchFormat(network_name=branch_format_name)
344
776
return RemoteBranch(self, self.find_repository(), format=format,
345
setup_stacking=not ignore_fallbacks, name=name)
777
setup_stacking=not ignore_fallbacks, name=name,
778
possible_transports=possible_transports)
780
def open_branch(self, name=None, unsupported=False,
781
ignore_fallbacks=False, possible_transports=None):
783
name = self._get_selected_branch()
785
raise errors.NoColocatedBranchSupport(self)
787
raise NotImplementedError('unsupported flag support not implemented yet.')
788
if self._next_open_branch_result is not None:
789
# See create_branch for details.
790
result = self._next_open_branch_result
791
self._next_open_branch_result = None
793
response = self._get_branch_reference()
794
return self._open_branch(name, response[0], response[1],
795
possible_transports=possible_transports,
796
ignore_fallbacks=ignore_fallbacks)
347
798
def _open_repo_v1(self, path):
348
799
verb = 'BzrDir.find_repository'
1195
1769
raise errors.UnexpectedSmartServerResponse(response)
1197
1772
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,
1773
"""Create a descendent repository for new development.
1775
Unlike clone, this does not copy the settings of the repository.
1777
dest_repo = self._create_sprouting_repo(to_bzrdir, shared=False)
1202
1778
dest_repo.fetch(self, revision_id=revision_id)
1203
1779
return dest_repo
1781
def _create_sprouting_repo(self, a_bzrdir, shared):
1782
if not isinstance(a_bzrdir._format, self.bzrdir._format.__class__):
1783
# use target default format.
1784
dest_repo = a_bzrdir.create_repository()
1786
# Most control formats need the repository to be specifically
1787
# created, but on some old all-in-one formats it's not needed
1789
dest_repo = self._format.initialize(a_bzrdir, shared=shared)
1790
except errors.UninitializableFormat:
1791
dest_repo = a_bzrdir.open_repository()
1205
1794
### These methods are just thin shims to the VFS object for now.
1207
1797
def revision_tree(self, revision_id):
1209
return self._real_repository.revision_tree(revision_id)
1798
revision_id = _mod_revision.ensure_null(revision_id)
1799
if revision_id == _mod_revision.NULL_REVISION:
1800
return InventoryRevisionTree(self,
1801
Inventory(root_id=None), _mod_revision.NULL_REVISION)
1803
return list(self.revision_trees([revision_id]))[0]
1211
1805
def get_serializer_format(self):
1213
return self._real_repository.get_serializer_format()
1806
path = self.bzrdir._path_for_remote_call(self._client)
1808
response = self._call('VersionedFileRepository.get_serializer_format',
1810
except errors.UnknownSmartMethod:
1812
return self._real_repository.get_serializer_format()
1813
if response[0] != 'ok':
1814
raise errors.UnexpectedSmartServerResponse(response)
1215
1817
def get_commit_builder(self, branch, parents, config, timestamp=None,
1216
1818
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)
1819
revision_id=None, lossy=False):
1820
"""Obtain a CommitBuilder for this repository.
1822
:param branch: Branch to commit to.
1823
:param parents: Revision ids of the parents of the new revision.
1824
:param config: Configuration to use.
1825
:param timestamp: Optional timestamp recorded for commit.
1826
:param timezone: Optional timezone for timestamp.
1827
:param committer: Optional committer to set for commit.
1828
:param revprops: Optional dictionary of revision properties.
1829
:param revision_id: Optional revision id.
1830
:param lossy: Whether to discard data that can not be natively
1831
represented, when pushing to a foreign VCS
1833
if self._fallback_repositories and not self._format.supports_chks:
1834
raise errors.BzrError("Cannot commit directly to a stacked branch"
1835
" in pre-2a formats. See "
1836
"https://bugs.launchpad.net/bzr/+bug/375013 for details.")
1837
if self._format.rich_root_data:
1838
commit_builder_kls = vf_repository.VersionedFileRootCommitBuilder
1840
commit_builder_kls = vf_repository.VersionedFileCommitBuilder
1841
result = commit_builder_kls(self, parents, config,
1842
timestamp, timezone, committer, revprops, revision_id,
1844
self.start_write_group()
1227
1847
def add_fallback_repository(self, repository):
1228
1848
"""Add a repository to use for looking up data not held locally.
1272
1893
delta, new_revision_id, parents, basis_inv=basis_inv,
1273
1894
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)
1896
def add_revision(self, revision_id, rev, inv=None):
1897
_mod_revision.check_not_reserved_id(revision_id)
1898
key = (revision_id,)
1899
# check inventory present
1900
if not self.inventories.get_parent_map([key]):
1902
raise errors.WeaveRevisionNotPresent(revision_id,
1905
# yes, this is not suitable for adding with ghosts.
1906
rev.inventory_sha1 = self.add_inventory(revision_id, inv,
1909
rev.inventory_sha1 = self.inventories.get_sha1s([key])[key]
1910
self._add_revision(rev)
1912
def _add_revision(self, rev):
1913
if self._real_repository is not None:
1914
return self._real_repository._add_revision(rev)
1915
text = self._serializer.write_revision_to_string(rev)
1916
key = (rev.revision_id,)
1917
parents = tuple((parent,) for parent in rev.parent_ids)
1918
self._write_group_tokens, missing_keys = self._get_sink().insert_stream(
1919
[('revisions', [FulltextContentFactory(key, parents, None, text)])],
1920
self._format, self._write_group_tokens)
1280
1922
@needs_read_lock
1281
1923
def get_inventory(self, revision_id):
1924
return list(self.iter_inventories([revision_id]))[0]
1926
def _iter_inventories_rpc(self, revision_ids, ordering):
1927
if ordering is None:
1928
ordering = 'unordered'
1929
path = self.bzrdir._path_for_remote_call(self._client)
1930
body = "\n".join(revision_ids)
1931
response_tuple, response_handler = (
1932
self._call_with_body_bytes_expecting_body(
1933
"VersionedFileRepository.get_inventories",
1934
(path, ordering), body))
1935
if response_tuple[0] != "ok":
1936
raise errors.UnexpectedSmartServerResponse(response_tuple)
1937
deserializer = inventory_delta.InventoryDeltaDeserializer()
1938
byte_stream = response_handler.read_streamed_body()
1939
decoded = smart_repo._byte_stream_to_stream(byte_stream)
1941
# no results whatsoever
1943
src_format, stream = decoded
1944
if src_format.network_name() != self._format.network_name():
1945
raise AssertionError(
1946
"Mismatched RemoteRepository and stream src %r, %r" % (
1947
src_format.network_name(), self._format.network_name()))
1948
# ignore the src format, it's not really relevant
1949
prev_inv = Inventory(root_id=None,
1950
revision_id=_mod_revision.NULL_REVISION)
1951
# there should be just one substream, with inventory deltas
1952
substream_kind, substream = next(stream)
1953
if substream_kind != "inventory-deltas":
1954
raise AssertionError(
1955
"Unexpected stream %r received" % substream_kind)
1956
for record in substream:
1957
(parent_id, new_id, versioned_root, tree_references, invdelta) = (
1958
deserializer.parse_text_bytes(record.get_bytes_as("fulltext")))
1959
if parent_id != prev_inv.revision_id:
1960
raise AssertionError("invalid base %r != %r" % (parent_id,
1961
prev_inv.revision_id))
1962
inv = prev_inv.create_by_apply_delta(invdelta, new_id)
1963
yield inv, inv.revision_id
1966
def _iter_inventories_vfs(self, revision_ids, ordering=None):
1282
1967
self._ensure_real()
1283
return self._real_repository.get_inventory(revision_id)
1968
return self._real_repository._iter_inventories(revision_ids, ordering)
1285
1970
def iter_inventories(self, revision_ids, ordering=None):
1287
return self._real_repository.iter_inventories(revision_ids, ordering)
1971
"""Get many inventories by revision_ids.
1973
This will buffer some or all of the texts used in constructing the
1974
inventories in memory, but will only parse a single inventory at a
1977
:param revision_ids: The expected revision ids of the inventories.
1978
:param ordering: optional ordering, e.g. 'topological'. If not
1979
specified, the order of revision_ids will be preserved (by
1980
buffering if necessary).
1981
:return: An iterator of inventories.
1983
if ((None in revision_ids)
1984
or (_mod_revision.NULL_REVISION in revision_ids)):
1985
raise ValueError('cannot get null revision inventory')
1986
for inv, revid in self._iter_inventories(revision_ids, ordering):
1988
raise errors.NoSuchRevision(self, revid)
1991
def _iter_inventories(self, revision_ids, ordering=None):
1992
if len(revision_ids) == 0:
1994
missing = set(revision_ids)
1995
if ordering is None:
1996
order_as_requested = True
1998
order = list(revision_ids)
2000
next_revid = order.pop()
2002
order_as_requested = False
2003
if ordering != 'unordered' and self._fallback_repositories:
2004
raise ValueError('unsupported ordering %r' % ordering)
2005
iter_inv_fns = [self._iter_inventories_rpc] + [
2006
fallback._iter_inventories for fallback in
2007
self._fallback_repositories]
2009
for iter_inv in iter_inv_fns:
2010
request = [revid for revid in revision_ids if revid in missing]
2011
for inv, revid in iter_inv(request, ordering):
2014
missing.remove(inv.revision_id)
2015
if ordering != 'unordered':
2019
if order_as_requested:
2020
# Yield as many results as we can while preserving order.
2021
while next_revid in invs:
2022
inv = invs.pop(next_revid)
2023
yield inv, inv.revision_id
2025
next_revid = order.pop()
2027
# We still want to fully consume the stream, just
2028
# in case it is not actually finished at this point
2031
except errors.UnknownSmartMethod:
2032
for inv, revid in self._iter_inventories_vfs(revision_ids, ordering):
2036
if order_as_requested:
2037
if next_revid is not None:
2038
yield None, next_revid
2041
yield invs.get(revid), revid
2044
yield None, missing.pop()
1289
2046
@needs_read_lock
1290
2047
def get_revision(self, revision_id):
1292
return self._real_repository.get_revision(revision_id)
2048
return self.get_revisions([revision_id])[0]
1294
2050
def get_transaction(self):
1295
2051
self._ensure_real()
1388
2159
return self._real_repository._get_versioned_file_checker(
1389
2160
revisions, revision_versions_cache)
2162
def _iter_files_bytes_rpc(self, desired_files, absent):
2163
path = self.bzrdir._path_for_remote_call(self._client)
2166
for (file_id, revid, identifier) in desired_files:
2167
lines.append("%s\0%s" % (
2168
osutils.safe_file_id(file_id),
2169
osutils.safe_revision_id(revid)))
2170
identifiers.append(identifier)
2171
(response_tuple, response_handler) = (
2172
self._call_with_body_bytes_expecting_body(
2173
"Repository.iter_files_bytes", (path, ), "\n".join(lines)))
2174
if response_tuple != ('ok', ):
2175
response_handler.cancel_read_body()
2176
raise errors.UnexpectedSmartServerResponse(response_tuple)
2177
byte_stream = response_handler.read_streamed_body()
2178
def decompress_stream(start, byte_stream, unused):
2179
decompressor = zlib.decompressobj()
2180
yield decompressor.decompress(start)
2181
while decompressor.unused_data == "":
2183
data = next(byte_stream)
2184
except StopIteration:
2186
yield decompressor.decompress(data)
2187
yield decompressor.flush()
2188
unused.append(decompressor.unused_data)
2191
while not "\n" in unused:
2192
unused += next(byte_stream)
2193
header, rest = unused.split("\n", 1)
2194
args = header.split("\0")
2195
if args[0] == "absent":
2196
absent[identifiers[int(args[3])]] = (args[1], args[2])
2199
elif args[0] == "ok":
2202
raise errors.UnexpectedSmartServerResponse(args)
2204
yield (identifiers[idx],
2205
decompress_stream(rest, byte_stream, unused_chunks))
2206
unused = "".join(unused_chunks)
1391
2208
def iter_files_bytes(self, desired_files):
1392
2209
"""See Repository.iter_file_bytes.
1395
return self._real_repository.iter_files_bytes(desired_files)
2213
for (identifier, bytes_iterator) in self._iter_files_bytes_rpc(
2214
desired_files, absent):
2215
yield identifier, bytes_iterator
2216
for fallback in self._fallback_repositories:
2219
desired_files = [(key[0], key[1], identifier) for
2220
(identifier, key) in absent.iteritems()]
2221
for (identifier, bytes_iterator) in fallback.iter_files_bytes(desired_files):
2222
del absent[identifier]
2223
yield identifier, bytes_iterator
2225
# There may be more missing items, but raise an exception
2227
missing_identifier = absent.keys()[0]
2228
missing_key = absent[missing_identifier]
2229
raise errors.RevisionNotPresent(revision_id=missing_key[1],
2230
file_id=missing_key[0])
2231
except errors.UnknownSmartMethod:
2233
for (identifier, bytes_iterator) in (
2234
self._real_repository.iter_files_bytes(desired_files)):
2235
yield identifier, bytes_iterator
2237
def get_cached_parent_map(self, revision_ids):
2238
"""See breezy.CachingParentsProvider.get_cached_parent_map"""
2239
return self._unstacked_provider.get_cached_parent_map(revision_ids)
1397
2241
def get_parent_map(self, revision_ids):
1398
"""See bzrlib.Graph.get_parent_map()."""
2242
"""See breezy.Graph.get_parent_map()."""
1399
2243
return self._make_parents_provider().get_parent_map(revision_ids)
1401
2245
def _get_parent_map_rpc(self, keys):
1532
2365
@needs_read_lock
1533
2366
def get_signature_text(self, revision_id):
1535
return self._real_repository.get_signature_text(revision_id)
2367
path = self.bzrdir._path_for_remote_call(self._client)
2369
response_tuple, response_handler = self._call_expecting_body(
2370
'Repository.get_revision_signature_text', path, revision_id)
2371
except errors.UnknownSmartMethod:
2373
return self._real_repository.get_signature_text(revision_id)
2374
except errors.NoSuchRevision as err:
2375
for fallback in self._fallback_repositories:
2377
return fallback.get_signature_text(revision_id)
2378
except errors.NoSuchRevision:
2382
if response_tuple[0] != 'ok':
2383
raise errors.UnexpectedSmartServerResponse(response_tuple)
2384
return response_handler.read_body_bytes()
1537
2386
@needs_read_lock
1538
2387
def _get_inventory_xml(self, revision_id):
2388
# This call is used by older working tree formats,
2389
# which stored a serialized basis inventory.
1539
2390
self._ensure_real()
1540
2391
return self._real_repository._get_inventory_xml(revision_id)
1542
2394
def reconcile(self, other=None, thorough=False):
1544
return self._real_repository.reconcile(other=other, thorough=thorough)
2395
from .reconcile import RepoReconciler
2396
path = self.bzrdir._path_for_remote_call(self._client)
2398
response, handler = self._call_expecting_body(
2399
'Repository.reconcile', path, self._lock_token)
2400
except (errors.UnknownSmartMethod, errors.TokenLockingNotSupported):
2402
return self._real_repository.reconcile(other=other, thorough=thorough)
2403
if response != ('ok', ):
2404
raise errors.UnexpectedSmartServerResponse(response)
2405
body = handler.read_body_bytes()
2406
result = RepoReconciler(self)
2407
for line in body.split('\n'):
2410
key, val_text = line.split(':')
2411
if key == "garbage_inventories":
2412
result.garbage_inventories = int(val_text)
2413
elif key == "inconsistent_parents":
2414
result.inconsistent_parents = int(val_text)
2416
mutter("unknown reconcile key %r" % key)
1546
2419
def all_revision_ids(self):
1548
return self._real_repository.all_revision_ids()
2420
path = self.bzrdir._path_for_remote_call(self._client)
2422
response_tuple, response_handler = self._call_expecting_body(
2423
"Repository.all_revision_ids", path)
2424
except errors.UnknownSmartMethod:
2426
return self._real_repository.all_revision_ids()
2427
if response_tuple != ("ok", ):
2428
raise errors.UnexpectedSmartServerResponse(response_tuple)
2429
revids = set(response_handler.read_body_bytes().splitlines())
2430
for fallback in self._fallback_repositories:
2431
revids.update(set(fallback.all_revision_ids()))
2434
def _filtered_revision_trees(self, revision_ids, file_ids):
2435
"""Return Tree for a revision on this branch with only some files.
2437
:param revision_ids: a sequence of revision-ids;
2438
a revision-id may not be None or 'null:'
2439
:param file_ids: if not None, the result is filtered
2440
so that only those file-ids, their parents and their
2441
children are included.
2443
inventories = self.iter_inventories(revision_ids)
2444
for inv in inventories:
2445
# Should we introduce a FilteredRevisionTree class rather
2446
# than pre-filter the inventory here?
2447
filtered_inv = inv.filter(file_ids)
2448
yield InventoryRevisionTree(self, filtered_inv, filtered_inv.revision_id)
1550
2450
@needs_read_lock
1551
2451
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)
2452
medium = self._client._medium
2453
if medium._is_remote_before((1, 2)):
2455
for delta in self._real_repository.get_deltas_for_revisions(
2456
revisions, specific_fileids):
2459
# Get the revision-ids of interest
2460
required_trees = set()
2461
for revision in revisions:
2462
required_trees.add(revision.revision_id)
2463
required_trees.update(revision.parent_ids[:1])
2465
# Get the matching filtered trees. Note that it's more
2466
# efficient to pass filtered trees to changes_from() rather
2467
# than doing the filtering afterwards. changes_from() could
2468
# arguably do the filtering itself but it's path-based, not
2469
# file-id based, so filtering before or afterwards is
2471
if specific_fileids is None:
2472
trees = dict((t.get_revision_id(), t) for
2473
t in self.revision_trees(required_trees))
2475
trees = dict((t.get_revision_id(), t) for
2476
t in self._filtered_revision_trees(required_trees,
2479
# Calculate the deltas
2480
for revision in revisions:
2481
if not revision.parent_ids:
2482
old_tree = self.revision_tree(_mod_revision.NULL_REVISION)
2484
old_tree = trees[revision.parent_ids[0]]
2485
yield trees[revision.revision_id].changes_from(old_tree)
1556
2487
@needs_read_lock
1557
2488
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)
2489
r = self.get_revision(revision_id)
2490
return list(self.get_deltas_for_revisions([r],
2491
specific_fileids=specific_fileids))[0]
1562
2493
@needs_read_lock
1563
2494
def revision_trees(self, revision_ids):
1565
return self._real_repository.revision_trees(revision_ids)
2495
inventories = self.iter_inventories(revision_ids)
2496
for inv in inventories:
2497
yield InventoryRevisionTree(self, inv, inv.revision_id)
1567
2499
@needs_read_lock
1568
2500
def get_revision_reconcile(self, revision_id):
1680
2625
self._ensure_real()
1681
2626
return self._real_repository.texts
2628
def _iter_revisions_rpc(self, revision_ids):
2629
body = "\n".join(revision_ids)
2630
path = self.bzrdir._path_for_remote_call(self._client)
2631
response_tuple, response_handler = (
2632
self._call_with_body_bytes_expecting_body(
2633
"Repository.iter_revisions", (path, ), body))
2634
if response_tuple[0] != "ok":
2635
raise errors.UnexpectedSmartServerResponse(response_tuple)
2636
serializer_format = response_tuple[1]
2637
serializer = serializer_format_registry.get(serializer_format)
2638
byte_stream = response_handler.read_streamed_body()
2639
decompressor = zlib.decompressobj()
2641
for bytes in byte_stream:
2642
chunks.append(decompressor.decompress(bytes))
2643
if decompressor.unused_data != "":
2644
chunks.append(decompressor.flush())
2645
yield serializer.read_revision_from_string("".join(chunks))
2646
unused = decompressor.unused_data
2647
decompressor = zlib.decompressobj()
2648
chunks = [decompressor.decompress(unused)]
2649
chunks.append(decompressor.flush())
2650
text = "".join(chunks)
2652
yield serializer.read_revision_from_string("".join(chunks))
1683
2654
@needs_read_lock
1684
2655
def get_revisions(self, revision_ids):
1686
return self._real_repository.get_revisions(revision_ids)
2656
if revision_ids is None:
2657
revision_ids = self.all_revision_ids()
2659
for rev_id in revision_ids:
2660
if not rev_id or not isinstance(rev_id, basestring):
2661
raise errors.InvalidRevisionId(
2662
revision_id=rev_id, branch=self)
2664
missing = set(revision_ids)
2666
for rev in self._iter_revisions_rpc(revision_ids):
2667
missing.remove(rev.revision_id)
2668
revs[rev.revision_id] = rev
2669
except errors.UnknownSmartMethod:
2671
return self._real_repository.get_revisions(revision_ids)
2672
for fallback in self._fallback_repositories:
2675
for revid in list(missing):
2676
# XXX JRV 2011-11-20: It would be nice if there was a
2677
# public method on Repository that could be used to query
2678
# for revision objects *without* failing completely if one
2679
# was missing. There is VersionedFileRepository._iter_revisions,
2680
# but unfortunately that's private and not provided by
2681
# all repository implementations.
2683
revs[revid] = fallback.get_revision(revid)
2684
except errors.NoSuchRevision:
2687
missing.remove(revid)
2689
raise errors.NoSuchRevision(self, list(missing)[0])
2690
return [revs[revid] for revid in revision_ids]
1688
2692
def supports_rich_root(self):
1689
2693
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
2696
def _serializer(self):
1697
2697
return self._format._serializer
1699
2700
def store_revision_signature(self, gpg_strategy, plaintext, revision_id):
1701
return self._real_repository.store_revision_signature(
1702
gpg_strategy, plaintext, revision_id)
2701
signature = gpg_strategy.sign(plaintext)
2702
self.add_signature_text(revision_id, signature)
1704
2704
def add_signature_text(self, revision_id, signature):
1706
return self._real_repository.add_signature_text(revision_id, signature)
2705
if self._real_repository:
2706
# If there is a real repository the write group will
2707
# be in the real repository as well, so use that:
2709
return self._real_repository.add_signature_text(
2710
revision_id, signature)
2711
path = self.bzrdir._path_for_remote_call(self._client)
2712
response, handler = self._call_with_body_bytes_expecting_body(
2713
'Repository.add_signature_text', (path, self._lock_token,
2714
revision_id) + tuple(self._write_group_tokens), signature)
2715
handler.cancel_read_body()
2717
if response[0] != 'ok':
2718
raise errors.UnexpectedSmartServerResponse(response)
2719
self._write_group_tokens = response[1:]
1708
2721
def has_signature_for_revision_id(self, revision_id):
1710
return self._real_repository.has_signature_for_revision_id(revision_id)
2722
path = self.bzrdir._path_for_remote_call(self._client)
2724
response = self._call('Repository.has_signature_for_revision_id',
2726
except errors.UnknownSmartMethod:
2728
return self._real_repository.has_signature_for_revision_id(
2730
if response[0] not in ('yes', 'no'):
2731
raise SmartProtocolError('unexpected response code %s' % (response,))
2732
if response[0] == 'yes':
2734
for fallback in self._fallback_repositories:
2735
if fallback.has_signature_for_revision_id(revision_id):
2740
def verify_revision_signature(self, revision_id, gpg_strategy):
2741
if not self.has_signature_for_revision_id(revision_id):
2742
return gpg.SIGNATURE_NOT_SIGNED, None
2743
signature = self.get_signature_text(revision_id)
2745
testament = _mod_testament.Testament.from_revision(self, revision_id)
2746
plaintext = testament.as_short_text()
2748
return gpg_strategy.verify(signature, plaintext)
1712
2750
def item_keys_introduced_by(self, revision_ids, _files_pb=None):
1713
2751
self._ensure_real()
1714
2752
return self._real_repository.item_keys_introduced_by(revision_ids,
1715
2753
_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
2755
def _find_inconsistent_revision_parents(self, revisions_iterator=None):
1723
2756
self._ensure_real()
1724
2757
return self._real_repository._find_inconsistent_revision_parents(
2071
3116
if isinstance(a_bzrdir, RemoteBzrDir):
2072
3117
a_bzrdir._ensure_real()
2073
3118
result = self._custom_format.initialize(a_bzrdir._real_bzrdir,
3119
name=name, append_revisions_only=append_revisions_only,
3120
repository=repository)
2076
3122
# We assume the bzrdir is parameterised; it may not be.
2077
result = self._custom_format.initialize(a_bzrdir, name)
3123
result = self._custom_format.initialize(a_bzrdir, name=name,
3124
append_revisions_only=append_revisions_only,
3125
repository=repository)
2078
3126
if (isinstance(a_bzrdir, RemoteBzrDir) and
2079
3127
not isinstance(result, RemoteBranch)):
2080
3128
result = RemoteBranch(a_bzrdir, a_bzrdir.find_repository(), result,
2084
def initialize(self, a_bzrdir, name=None):
3132
def initialize(self, a_bzrdir, name=None, repository=None,
3133
append_revisions_only=None):
3135
name = a_bzrdir._get_selected_branch()
2085
3136
# 1) get the network name to use.
2086
3137
if self._custom_format:
2087
3138
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')()
3140
# Select the current breezy default and ask for that.
3141
reference_bzrdir_format = controldir.format_registry.get('default')()
2091
3142
reference_format = reference_bzrdir_format.get_branch_format()
2092
3143
self._custom_format = reference_format
2093
3144
network_name = reference_format.network_name()
2094
3145
# Being asked to create on a non RemoteBzrDir:
2095
3146
if not isinstance(a_bzrdir, RemoteBzrDir):
2096
return self._vfs_initialize(a_bzrdir, name=name)
3147
return self._vfs_initialize(a_bzrdir, name=name,
3148
append_revisions_only=append_revisions_only,
3149
repository=repository)
2097
3150
medium = a_bzrdir._client._medium
2098
3151
if medium._is_remote_before((1, 13)):
2099
return self._vfs_initialize(a_bzrdir, name=name)
3152
return self._vfs_initialize(a_bzrdir, name=name,
3153
append_revisions_only=append_revisions_only,
3154
repository=repository)
2100
3155
# Creating on a remote bzr dir.
2101
3156
# 2) try direct creation via RPC
2102
3157
path = a_bzrdir._path_for_remote_call(a_bzrdir._client)
2103
if name is not None:
2104
3159
# XXX JRV20100304: Support creating colocated branches
2105
3160
raise errors.NoColocatedBranchSupport(self)
2106
3161
verb = 'BzrDir.create_branch'
2148
3219
self._ensure_real()
2149
3220
return self._custom_format.supports_set_append_revisions_only()
3222
def _use_default_local_heads_to_fetch(self):
3223
# If the branch format is a metadir format *and* its heads_to_fetch
3224
# implementation is not overridden vs the base class, we can use the
3225
# base class logic rather than use the heads_to_fetch RPC. This is
3226
# usually cheaper in terms of net round trips, as the last-revision and
3227
# tags info fetched is cached and would be fetched anyway.
3229
if isinstance(self._custom_format, bzrbranch.BranchFormatMetadir):
3230
branch_class = self._custom_format._branch_class()
3231
heads_to_fetch_impl = branch_class.heads_to_fetch.__func__
3232
if heads_to_fetch_impl is branch.Branch.heads_to_fetch.__func__:
3237
class RemoteBranchStore(_mod_config.IniFileStore):
3238
"""Branch store which attempts to use HPSS calls to retrieve branch store.
3240
Note that this is specific to bzr-based formats.
3243
def __init__(self, branch):
3244
super(RemoteBranchStore, self).__init__()
3245
self.branch = branch
3247
self._real_store = None
3249
def external_url(self):
3250
return urlutils.join(self.branch.user_url, 'branch.conf')
3252
def _load_content(self):
3253
path = self.branch._remote_path()
3255
response, handler = self.branch._call_expecting_body(
3256
'Branch.get_config_file', path)
3257
except errors.UnknownSmartMethod:
3259
return self._real_store._load_content()
3260
if len(response) and response[0] != 'ok':
3261
raise errors.UnexpectedSmartServerResponse(response)
3262
return handler.read_body_bytes()
3264
def _save_content(self, content):
3265
path = self.branch._remote_path()
3267
response, handler = self.branch._call_with_body_bytes_expecting_body(
3268
'Branch.put_config_file', (path,
3269
self.branch._lock_token, self.branch._repo_lock_token),
3271
except errors.UnknownSmartMethod:
3273
return self._real_store._save_content(content)
3274
handler.cancel_read_body()
3275
if response != ('ok', ):
3276
raise errors.UnexpectedSmartServerResponse(response)
3278
def _ensure_real(self):
3279
self.branch._ensure_real()
3280
if self._real_store is None:
3281
self._real_store = _mod_config.BranchStore(self.branch)
2152
3284
class RemoteBranch(branch.Branch, _RpcHelper, lock._RelockDebugMixin):
2153
3285
"""Branch stored on a server accessed by HPSS RPC.
2654
3835
_override_hook_target=self, **kwargs)
2656
3837
@needs_read_lock
2657
def push(self, target, overwrite=False, stop_revision=None):
3838
def push(self, target, overwrite=False, stop_revision=None, lossy=False):
2658
3839
self._ensure_real()
2659
3840
return self._real_branch.push(
2660
target, overwrite=overwrite, stop_revision=stop_revision,
3841
target, overwrite=overwrite, stop_revision=stop_revision, lossy=lossy,
2661
3842
_override_hook_source_branch=self)
3844
def peek_lock_mode(self):
3845
return self._lock_mode
2663
3847
def is_locked(self):
2664
3848
return self._lock_count >= 1
2666
3850
@needs_read_lock
3851
def revision_id_to_dotted_revno(self, revision_id):
3852
"""Given a revision id, return its dotted revno.
3854
:return: a tuple like (1,) or (400,1,3).
3857
response = self._call('Branch.revision_id_to_revno',
3858
self._remote_path(), revision_id)
3859
except errors.UnknownSmartMethod:
3861
return self._real_branch.revision_id_to_dotted_revno(revision_id)
3862
if response[0] == 'ok':
3863
return tuple([int(x) for x in response[1:]])
3865
raise errors.UnexpectedSmartServerResponse(response)
2667
3868
def revision_id_to_revno(self, revision_id):
2669
return self._real_branch.revision_id_to_revno(revision_id)
3869
"""Given a revision id on the branch mainline, return its revno.
3874
response = self._call('Branch.revision_id_to_revno',
3875
self._remote_path(), revision_id)
3876
except errors.UnknownSmartMethod:
3878
return self._real_branch.revision_id_to_revno(revision_id)
3879
if response[0] == 'ok':
3880
if len(response) == 2:
3881
return int(response[1])
3882
raise NoSuchRevision(self, revision_id)
3884
raise errors.UnexpectedSmartServerResponse(response)
2671
3886
@needs_write_lock
2672
3887
def set_last_revision_info(self, revno, revision_id):
2673
3888
# XXX: These should be returned by the set_last_revision_info verb
2674
3889
old_revno, old_revid = self.last_revision_info()
2675
3890
self._run_pre_change_branch_tip_hooks(revno, revision_id)
2676
revision_id = ensure_null(revision_id)
3891
if not revision_id or not isinstance(revision_id, basestring):
3892
raise errors.InvalidRevisionId(revision_id=revision_id, branch=self)
2678
3894
response = self._call('Branch.set_last_revision_info',
2679
3895
self._remote_path(), self._lock_token, self._repo_lock_token,
2708
3924
except errors.UnknownSmartMethod:
2709
3925
medium._remember_remote_is_before((1, 6))
2710
3926
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))
3927
graph = self.repository.get_graph()
3928
(last_revno, last_revid) = self.last_revision_info()
3929
known_revision_ids = [
3930
(last_revid, last_revno),
3931
(_mod_revision.NULL_REVISION, 0),
3933
if last_rev is not None:
3934
if not graph.is_ancestor(last_rev, revision_id):
3935
# our previous tip is not merged into stop_revision
3936
raise errors.DivergedBranches(self, other_branch)
3937
revno = graph.find_distance_to_null(revision_id, known_revision_ids)
3938
self.set_last_revision_info(revno, revision_id)
2714
3940
def set_push_location(self, location):
3941
self._set_config_location('push_location', location)
3943
def heads_to_fetch(self):
3944
if self._format._use_default_local_heads_to_fetch():
3945
# We recognise this format, and its heads-to-fetch implementation
3946
# is the default one (tip + tags). In this case it's cheaper to
3947
# just use the default implementation rather than a special RPC as
3948
# the tip and tags data is cached.
3949
return branch.Branch.heads_to_fetch(self)
3950
medium = self._client._medium
3951
if medium._is_remote_before((2, 4)):
3952
return self._vfs_heads_to_fetch()
3954
return self._rpc_heads_to_fetch()
3955
except errors.UnknownSmartMethod:
3956
medium._remember_remote_is_before((2, 4))
3957
return self._vfs_heads_to_fetch()
3959
def _rpc_heads_to_fetch(self):
3960
response = self._call('Branch.heads_to_fetch', self._remote_path())
3961
if len(response) != 2:
3962
raise errors.UnexpectedSmartServerResponse(response)
3963
must_fetch, if_present_fetch = response
3964
return set(must_fetch), set(if_present_fetch)
3966
def _vfs_heads_to_fetch(self):
2715
3967
self._ensure_real()
2716
return self._real_branch.set_push_location(location)
3968
return self._real_branch.heads_to_fetch()
2719
3971
class RemoteConfig(object):
2774
4036
medium = self._branch._client._medium
2775
4037
if medium._is_remote_before((1, 14)):
2776
4038
return self._vfs_set_option(value, name, section)
4039
if isinstance(value, dict):
4040
if medium._is_remote_before((2, 2)):
4041
return self._vfs_set_option(value, name, section)
4042
return self._set_config_option_dict(value, name, section)
4044
return self._set_config_option(value, name, section)
4046
def _set_config_option(self, value, name, section):
2778
4048
path = self._branch._remote_path()
2779
4049
response = self._branch._client.call('Branch.set_config_option',
2780
4050
path, self._branch._lock_token, self._branch._repo_lock_token,
2781
4051
value.encode('utf8'), name, section or '')
2782
4052
except errors.UnknownSmartMethod:
4053
medium = self._branch._client._medium
2783
4054
medium._remember_remote_is_before((1, 14))
2784
4055
return self._vfs_set_option(value, name, section)
2785
4056
if response != ():
2786
4057
raise errors.UnexpectedSmartServerResponse(response)
4059
def _serialize_option_dict(self, option_dict):
4061
for key, value in option_dict.items():
4062
if isinstance(key, unicode):
4063
key = key.encode('utf8')
4064
if isinstance(value, unicode):
4065
value = value.encode('utf8')
4066
utf8_dict[key] = value
4067
return bencode.bencode(utf8_dict)
4069
def _set_config_option_dict(self, value, name, section):
4071
path = self._branch._remote_path()
4072
serialised_dict = self._serialize_option_dict(value)
4073
response = self._branch._client.call(
4074
'Branch.set_config_option_dict',
4075
path, self._branch._lock_token, self._branch._repo_lock_token,
4076
serialised_dict, name, section or '')
4077
except errors.UnknownSmartMethod:
4078
medium = self._branch._client._medium
4079
medium._remember_remote_is_before((2, 2))
4080
return self._vfs_set_option(value, name, section)
4082
raise errors.UnexpectedSmartServerResponse(response)
2788
4084
def _real_object(self):
2789
4085
self._branch._ensure_real()
2790
4086
return self._branch._real_branch
2867
4166
return context['path']
2868
except KeyError, key_err:
4167
except KeyError as key_err:
2870
4169
return err.error_args[0]
2871
except IndexError, idx_err:
4170
except IndexError as idx_err:
2873
4172
'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'):
4176
translator = error_translators.get(err.error_verb)
4180
raise translator(err, find, get_path)
4182
translator = no_context_error_translators.get(err.error_verb)
4184
raise errors.UnknownErrorFromSmartServer(err)
4186
raise translator(err)
4189
error_translators.register('NoSuchRevision',
4190
lambda err, find, get_path: NoSuchRevision(
4191
find('branch'), err.error_args[0]))
4192
error_translators.register('nosuchrevision',
4193
lambda err, find, get_path: NoSuchRevision(
4194
find('repository'), err.error_args[0]))
4196
def _translate_nobranch_error(err, find, get_path):
4197
if len(err.error_args) >= 1:
4198
extra = err.error_args[0]
4201
return errors.NotBranchError(path=find('bzrdir').root_transport.base,
4204
error_translators.register('nobranch', _translate_nobranch_error)
4205
error_translators.register('norepository',
4206
lambda err, find, get_path: errors.NoRepositoryPresent(
4208
error_translators.register('UnlockableTransport',
4209
lambda err, find, get_path: errors.UnlockableTransport(
4210
find('bzrdir').root_transport))
4211
error_translators.register('TokenMismatch',
4212
lambda err, find, get_path: errors.TokenMismatch(
4213
find('token'), '(remote token)'))
4214
error_translators.register('Diverged',
4215
lambda err, find, get_path: errors.DivergedBranches(
4216
find('branch'), find('other_branch')))
4217
error_translators.register('NotStacked',
4218
lambda err, find, get_path: errors.NotStacked(branch=find('branch')))
4220
def _translate_PermissionDenied(err, find, get_path):
4222
if len(err.error_args) >= 2:
4223
extra = err.error_args[1]
4226
return errors.PermissionDenied(path, extra=extra)
4228
error_translators.register('PermissionDenied', _translate_PermissionDenied)
4229
error_translators.register('ReadError',
4230
lambda err, find, get_path: errors.ReadError(get_path()))
4231
error_translators.register('NoSuchFile',
4232
lambda err, find, get_path: errors.NoSuchFile(get_path()))
4233
error_translators.register('TokenLockingNotSupported',
4234
lambda err, find, get_path: errors.TokenLockingNotSupported(
4235
find('repository')))
4236
error_translators.register('UnsuspendableWriteGroup',
4237
lambda err, find, get_path: errors.UnsuspendableWriteGroup(
4238
repository=find('repository')))
4239
error_translators.register('UnresumableWriteGroup',
4240
lambda err, find, get_path: errors.UnresumableWriteGroup(
4241
repository=find('repository'), write_groups=err.error_args[0],
4242
reason=err.error_args[1]))
4243
no_context_error_translators.register('IncompatibleRepositories',
4244
lambda err: errors.IncompatibleRepositories(
4245
err.error_args[0], err.error_args[1], err.error_args[2]))
4246
no_context_error_translators.register('LockContention',
4247
lambda err: errors.LockContention('(remote lock)'))
4248
no_context_error_translators.register('LockFailed',
4249
lambda err: errors.LockFailed(err.error_args[0], err.error_args[1]))
4250
no_context_error_translators.register('TipChangeRejected',
4251
lambda err: errors.TipChangeRejected(err.error_args[0].decode('utf8')))
4252
no_context_error_translators.register('UnstackableBranchFormat',
4253
lambda err: errors.UnstackableBranchFormat(*err.error_args))
4254
no_context_error_translators.register('UnstackableRepositoryFormat',
4255
lambda err: errors.UnstackableRepositoryFormat(*err.error_args))
4256
no_context_error_translators.register('FileExists',
4257
lambda err: errors.FileExists(err.error_args[0]))
4258
no_context_error_translators.register('DirectoryNotEmpty',
4259
lambda err: errors.DirectoryNotEmpty(err.error_args[0]))
4261
def _translate_short_readv_error(err):
4262
args = err.error_args
4263
return errors.ShortReadvError(args[0], int(args[1]), int(args[2]),
4266
no_context_error_translators.register('ShortReadvError',
4267
_translate_short_readv_error)
4269
def _translate_unicode_error(err):
2932
4270
encoding = str(err.error_args[0]) # encoding must always be a string
2933
4271
val = err.error_args[1]
2934
4272
start = int(err.error_args[2])