89
# Note: RemoteBzrDirFormat is in bzrdir.py
91
class RemoteBzrDir(BzrDir, _RpcHelper):
108
# Note that RemoteBzrDirProber lives in bzrlib.bzrdir so bzrlib.remote
109
# does not have to be imported unless a remote format is involved.
111
class RemoteBzrDirFormat(_mod_bzrdir.BzrDirMetaFormat1):
112
"""Format representing bzrdirs accessed via a smart server"""
114
supports_workingtrees = False
117
_mod_bzrdir.BzrDirMetaFormat1.__init__(self)
118
# XXX: It's a bit ugly that the network name is here, because we'd
119
# like to believe that format objects are stateless or at least
120
# immutable, However, we do at least avoid mutating the name after
121
# it's returned. See <https://bugs.launchpad.net/bzr/+bug/504102>
122
self._network_name = None
125
return "%s(_network_name=%r)" % (self.__class__.__name__,
128
def get_format_description(self):
129
if self._network_name:
131
real_format = controldir.network_format_registry.get(
136
return 'Remote: ' + real_format.get_format_description()
137
return 'bzr remote bzrdir'
139
def get_format_string(self):
140
raise NotImplementedError(self.get_format_string)
142
def network_name(self):
143
if self._network_name:
144
return self._network_name
146
raise AssertionError("No network name set.")
148
def initialize_on_transport(self, transport):
150
# hand off the request to the smart server
151
client_medium = transport.get_smart_medium()
152
except errors.NoSmartMedium:
153
# TODO: lookup the local format from a server hint.
154
local_dir_format = _mod_bzrdir.BzrDirMetaFormat1()
155
return local_dir_format.initialize_on_transport(transport)
156
client = _SmartClient(client_medium)
157
path = client.remote_path_from_transport(transport)
159
response = client.call('BzrDirFormat.initialize', path)
160
except errors.ErrorFromSmartServer, err:
161
_translate_error(err, path=path)
162
if response[0] != 'ok':
163
raise errors.SmartProtocolError('unexpected response code %s' % (response,))
164
format = RemoteBzrDirFormat()
165
self._supply_sub_formats_to(format)
166
return RemoteBzrDir(transport, format)
168
def parse_NoneTrueFalse(self, arg):
175
raise AssertionError("invalid arg %r" % arg)
177
def _serialize_NoneTrueFalse(self, arg):
184
def _serialize_NoneString(self, arg):
187
def initialize_on_transport_ex(self, transport, use_existing_dir=False,
188
create_prefix=False, force_new_repo=False, stacked_on=None,
189
stack_on_pwd=None, repo_format_name=None, make_working_trees=None,
192
# hand off the request to the smart server
193
client_medium = transport.get_smart_medium()
194
except errors.NoSmartMedium:
197
# Decline to open it if the server doesn't support our required
198
# version (3) so that the VFS-based transport will do it.
199
if client_medium.should_probe():
201
server_version = client_medium.protocol_version()
202
if server_version != '2':
206
except errors.SmartProtocolError:
207
# Apparently there's no usable smart server there, even though
208
# the medium supports the smart protocol.
213
client = _SmartClient(client_medium)
214
path = client.remote_path_from_transport(transport)
215
if client_medium._is_remote_before((1, 16)):
218
# TODO: lookup the local format from a server hint.
219
local_dir_format = _mod_bzrdir.BzrDirMetaFormat1()
220
self._supply_sub_formats_to(local_dir_format)
221
return local_dir_format.initialize_on_transport_ex(transport,
222
use_existing_dir=use_existing_dir, create_prefix=create_prefix,
223
force_new_repo=force_new_repo, stacked_on=stacked_on,
224
stack_on_pwd=stack_on_pwd, repo_format_name=repo_format_name,
225
make_working_trees=make_working_trees, shared_repo=shared_repo,
227
return self._initialize_on_transport_ex_rpc(client, path, transport,
228
use_existing_dir, create_prefix, force_new_repo, stacked_on,
229
stack_on_pwd, repo_format_name, make_working_trees, shared_repo)
231
def _initialize_on_transport_ex_rpc(self, client, path, transport,
232
use_existing_dir, create_prefix, force_new_repo, stacked_on,
233
stack_on_pwd, repo_format_name, make_working_trees, shared_repo):
235
args.append(self._serialize_NoneTrueFalse(use_existing_dir))
236
args.append(self._serialize_NoneTrueFalse(create_prefix))
237
args.append(self._serialize_NoneTrueFalse(force_new_repo))
238
args.append(self._serialize_NoneString(stacked_on))
239
# stack_on_pwd is often/usually our transport
242
stack_on_pwd = transport.relpath(stack_on_pwd)
245
except errors.PathNotChild:
247
args.append(self._serialize_NoneString(stack_on_pwd))
248
args.append(self._serialize_NoneString(repo_format_name))
249
args.append(self._serialize_NoneTrueFalse(make_working_trees))
250
args.append(self._serialize_NoneTrueFalse(shared_repo))
251
request_network_name = self._network_name or \
252
_mod_bzrdir.BzrDirFormat.get_default_format().network_name()
254
response = client.call('BzrDirFormat.initialize_ex_1.16',
255
request_network_name, path, *args)
256
except errors.UnknownSmartMethod:
257
client._medium._remember_remote_is_before((1,16))
258
local_dir_format = _mod_bzrdir.BzrDirMetaFormat1()
259
self._supply_sub_formats_to(local_dir_format)
260
return local_dir_format.initialize_on_transport_ex(transport,
261
use_existing_dir=use_existing_dir, create_prefix=create_prefix,
262
force_new_repo=force_new_repo, stacked_on=stacked_on,
263
stack_on_pwd=stack_on_pwd, repo_format_name=repo_format_name,
264
make_working_trees=make_working_trees, shared_repo=shared_repo,
266
except errors.ErrorFromSmartServer, err:
267
_translate_error(err, path=path)
268
repo_path = response[0]
269
bzrdir_name = response[6]
270
require_stacking = response[7]
271
require_stacking = self.parse_NoneTrueFalse(require_stacking)
272
format = RemoteBzrDirFormat()
273
format._network_name = bzrdir_name
274
self._supply_sub_formats_to(format)
275
bzrdir = RemoteBzrDir(transport, format, _client=client)
277
repo_format = response_tuple_to_repo_format(response[1:])
281
repo_bzrdir_format = RemoteBzrDirFormat()
282
repo_bzrdir_format._network_name = response[5]
283
repo_bzr = RemoteBzrDir(transport.clone(repo_path),
287
final_stack = response[8] or None
288
final_stack_pwd = response[9] or None
290
final_stack_pwd = urlutils.join(
291
transport.base, final_stack_pwd)
292
remote_repo = RemoteRepository(repo_bzr, repo_format)
293
if len(response) > 10:
294
# Updated server verb that locks remotely.
295
repo_lock_token = response[10] or None
296
remote_repo.lock_write(repo_lock_token, _skip_rpc=True)
298
remote_repo.dont_leave_lock_in_place()
300
remote_repo.lock_write()
301
policy = _mod_bzrdir.UseExistingRepository(remote_repo, final_stack,
302
final_stack_pwd, require_stacking)
303
policy.acquire_repository()
307
bzrdir._format.set_branch_format(self.get_branch_format())
309
# The repo has already been created, but we need to make sure that
310
# we'll make a stackable branch.
311
bzrdir._format.require_stacking(_skip_repo=True)
312
return remote_repo, bzrdir, require_stacking, policy
314
def _open(self, transport):
315
return RemoteBzrDir(transport, self)
317
def __eq__(self, other):
318
if not isinstance(other, RemoteBzrDirFormat):
320
return self.get_format_description() == other.get_format_description()
322
def __return_repository_format(self):
323
# Always return a RemoteRepositoryFormat object, but if a specific bzr
324
# repository format has been asked for, tell the RemoteRepositoryFormat
325
# that it should use that for init() etc.
326
result = RemoteRepositoryFormat()
327
custom_format = getattr(self, '_repository_format', None)
329
if isinstance(custom_format, RemoteRepositoryFormat):
332
# We will use the custom format to create repositories over the
333
# wire; expose its details like rich_root_data for code to
335
result._custom_format = custom_format
338
def get_branch_format(self):
339
result = _mod_bzrdir.BzrDirMetaFormat1.get_branch_format(self)
340
if not isinstance(result, RemoteBranchFormat):
341
new_result = RemoteBranchFormat()
342
new_result._custom_format = result
344
self.set_branch_format(new_result)
348
repository_format = property(__return_repository_format,
349
_mod_bzrdir.BzrDirMetaFormat1._set_repository_format) #.im_func)
352
class RemoteControlStore(_mod_config.IniFileStore):
353
"""Control store which attempts to use HPSS calls to retrieve control store.
355
Note that this is specific to bzr-based formats.
358
def __init__(self, bzrdir):
359
super(RemoteControlStore, self).__init__()
361
self._real_store = None
363
def lock_write(self, token=None):
365
return self._real_store.lock_write(token)
369
return self._real_store.unlock()
373
# We need to be able to override the undecorated implementation
374
self.save_without_locking()
376
def save_without_locking(self):
377
super(RemoteControlStore, self).save()
379
def _ensure_real(self):
380
self.bzrdir._ensure_real()
381
if self._real_store is None:
382
self._real_store = _mod_config.ControlStore(self.bzrdir)
384
def external_url(self):
385
return self.bzrdir.user_url
387
def _load_content(self):
388
medium = self.bzrdir._client._medium
389
path = self.bzrdir._path_for_remote_call(self.bzrdir._client)
391
response, handler = self.bzrdir._call_expecting_body(
392
'BzrDir.get_config_file', path)
393
except errors.UnknownSmartMethod:
395
return self._real_store._load_content()
396
if len(response) and response[0] != 'ok':
397
raise errors.UnexpectedSmartServerResponse(response)
398
return handler.read_body_bytes()
400
def _save_content(self, content):
401
# FIXME JRV 2011-11-22: Ideally this should use a
402
# HPSS call too, but at the moment it is not possible
403
# to write lock control directories.
405
return self._real_store._save_content(content)
408
class RemoteBzrDir(_mod_bzrdir.BzrDir, _RpcHelper):
92
409
"""Control directory on a remote server, accessed via bzr:// or similar."""
94
411
def __init__(self, transport, format, _client=None, _force_probe=False):
1195
1724
raise errors.UnexpectedSmartServerResponse(response)
1197
1727
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,
1728
"""Create a descendent repository for new development.
1730
Unlike clone, this does not copy the settings of the repository.
1732
dest_repo = self._create_sprouting_repo(to_bzrdir, shared=False)
1202
1733
dest_repo.fetch(self, revision_id=revision_id)
1203
1734
return dest_repo
1736
def _create_sprouting_repo(self, a_bzrdir, shared):
1737
if not isinstance(a_bzrdir._format, self.bzrdir._format.__class__):
1738
# use target default format.
1739
dest_repo = a_bzrdir.create_repository()
1741
# Most control formats need the repository to be specifically
1742
# created, but on some old all-in-one formats it's not needed
1744
dest_repo = self._format.initialize(a_bzrdir, shared=shared)
1745
except errors.UninitializableFormat:
1746
dest_repo = a_bzrdir.open_repository()
1205
1749
### These methods are just thin shims to the VFS object for now.
1207
1752
def revision_tree(self, revision_id):
1209
return self._real_repository.revision_tree(revision_id)
1753
revision_id = _mod_revision.ensure_null(revision_id)
1754
if revision_id == _mod_revision.NULL_REVISION:
1755
return InventoryRevisionTree(self,
1756
Inventory(root_id=None), _mod_revision.NULL_REVISION)
1758
return list(self.revision_trees([revision_id]))[0]
1211
1760
def get_serializer_format(self):
1213
return self._real_repository.get_serializer_format()
1761
path = self.bzrdir._path_for_remote_call(self._client)
1763
response = self._call('VersionedFileRepository.get_serializer_format',
1765
except errors.UnknownSmartMethod:
1767
return self._real_repository.get_serializer_format()
1768
if response[0] != 'ok':
1769
raise errors.UnexpectedSmartServerResponse(response)
1215
1772
def get_commit_builder(self, branch, parents, config, timestamp=None,
1216
1773
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)
1774
revision_id=None, lossy=False):
1775
"""Obtain a CommitBuilder for this repository.
1777
:param branch: Branch to commit to.
1778
:param parents: Revision ids of the parents of the new revision.
1779
:param config: Configuration to use.
1780
:param timestamp: Optional timestamp recorded for commit.
1781
:param timezone: Optional timezone for timestamp.
1782
:param committer: Optional committer to set for commit.
1783
:param revprops: Optional dictionary of revision properties.
1784
:param revision_id: Optional revision id.
1785
:param lossy: Whether to discard data that can not be natively
1786
represented, when pushing to a foreign VCS
1788
if self._fallback_repositories and not self._format.supports_chks:
1789
raise errors.BzrError("Cannot commit directly to a stacked branch"
1790
" in pre-2a formats. See "
1791
"https://bugs.launchpad.net/bzr/+bug/375013 for details.")
1792
if self._format.rich_root_data:
1793
commit_builder_kls = vf_repository.VersionedFileRootCommitBuilder
1795
commit_builder_kls = vf_repository.VersionedFileCommitBuilder
1796
result = commit_builder_kls(self, parents, config,
1797
timestamp, timezone, committer, revprops, revision_id,
1799
self.start_write_group()
1227
1802
def add_fallback_repository(self, repository):
1228
1803
"""Add a repository to use for looking up data not held locally.
1272
1848
delta, new_revision_id, parents, basis_inv=basis_inv,
1273
1849
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)
1851
def add_revision(self, revision_id, rev, inv=None):
1852
_mod_revision.check_not_reserved_id(revision_id)
1853
key = (revision_id,)
1854
# check inventory present
1855
if not self.inventories.get_parent_map([key]):
1857
raise errors.WeaveRevisionNotPresent(revision_id,
1860
# yes, this is not suitable for adding with ghosts.
1861
rev.inventory_sha1 = self.add_inventory(revision_id, inv,
1864
rev.inventory_sha1 = self.inventories.get_sha1s([key])[key]
1865
self._add_revision(rev)
1867
def _add_revision(self, rev):
1868
if self._real_repository is not None:
1869
return self._real_repository._add_revision(rev)
1870
text = self._serializer.write_revision_to_string(rev)
1871
key = (rev.revision_id,)
1872
parents = tuple((parent,) for parent in rev.parent_ids)
1873
self._write_group_tokens, missing_keys = self._get_sink().insert_stream(
1874
[('revisions', [FulltextContentFactory(key, parents, None, text)])],
1875
self._format, self._write_group_tokens)
1280
1877
@needs_read_lock
1281
1878
def get_inventory(self, revision_id):
1879
return list(self.iter_inventories([revision_id]))[0]
1881
def _iter_inventories_rpc(self, revision_ids, ordering):
1882
if ordering is None:
1883
ordering = 'unordered'
1884
path = self.bzrdir._path_for_remote_call(self._client)
1885
body = "\n".join(revision_ids)
1886
response_tuple, response_handler = (
1887
self._call_with_body_bytes_expecting_body(
1888
"VersionedFileRepository.get_inventories",
1889
(path, ordering), body))
1890
if response_tuple[0] != "ok":
1891
raise errors.UnexpectedSmartServerResponse(response_tuple)
1892
deserializer = inventory_delta.InventoryDeltaDeserializer()
1893
byte_stream = response_handler.read_streamed_body()
1894
decoded = smart_repo._byte_stream_to_stream(byte_stream)
1896
# no results whatsoever
1898
src_format, stream = decoded
1899
if src_format.network_name() != self._format.network_name():
1900
raise AssertionError(
1901
"Mismatched RemoteRepository and stream src %r, %r" % (
1902
src_format.network_name(), self._format.network_name()))
1903
# ignore the src format, it's not really relevant
1904
prev_inv = Inventory(root_id=None,
1905
revision_id=_mod_revision.NULL_REVISION)
1906
# there should be just one substream, with inventory deltas
1907
substream_kind, substream = stream.next()
1908
if substream_kind != "inventory-deltas":
1909
raise AssertionError(
1910
"Unexpected stream %r received" % substream_kind)
1911
for record in substream:
1912
(parent_id, new_id, versioned_root, tree_references, invdelta) = (
1913
deserializer.parse_text_bytes(record.get_bytes_as("fulltext")))
1914
if parent_id != prev_inv.revision_id:
1915
raise AssertionError("invalid base %r != %r" % (parent_id,
1916
prev_inv.revision_id))
1917
inv = prev_inv.create_by_apply_delta(invdelta, new_id)
1918
yield inv, inv.revision_id
1921
def _iter_inventories_vfs(self, revision_ids, ordering=None):
1282
1922
self._ensure_real()
1283
return self._real_repository.get_inventory(revision_id)
1923
return self._real_repository._iter_inventories(revision_ids, ordering)
1285
1925
def iter_inventories(self, revision_ids, ordering=None):
1287
return self._real_repository.iter_inventories(revision_ids, ordering)
1926
"""Get many inventories by revision_ids.
1928
This will buffer some or all of the texts used in constructing the
1929
inventories in memory, but will only parse a single inventory at a
1932
:param revision_ids: The expected revision ids of the inventories.
1933
:param ordering: optional ordering, e.g. 'topological'. If not
1934
specified, the order of revision_ids will be preserved (by
1935
buffering if necessary).
1936
:return: An iterator of inventories.
1938
if ((None in revision_ids)
1939
or (_mod_revision.NULL_REVISION in revision_ids)):
1940
raise ValueError('cannot get null revision inventory')
1941
for inv, revid in self._iter_inventories(revision_ids, ordering):
1943
raise errors.NoSuchRevision(self, revid)
1946
def _iter_inventories(self, revision_ids, ordering=None):
1947
if len(revision_ids) == 0:
1949
missing = set(revision_ids)
1950
if ordering is None:
1951
order_as_requested = True
1953
order = list(revision_ids)
1955
next_revid = order.pop()
1957
order_as_requested = False
1958
if ordering != 'unordered' and self._fallback_repositories:
1959
raise ValueError('unsupported ordering %r' % ordering)
1960
iter_inv_fns = [self._iter_inventories_rpc] + [
1961
fallback._iter_inventories for fallback in
1962
self._fallback_repositories]
1964
for iter_inv in iter_inv_fns:
1965
request = [revid for revid in revision_ids if revid in missing]
1966
for inv, revid in iter_inv(request, ordering):
1969
missing.remove(inv.revision_id)
1970
if ordering != 'unordered':
1974
if order_as_requested:
1975
# Yield as many results as we can while preserving order.
1976
while next_revid in invs:
1977
inv = invs.pop(next_revid)
1978
yield inv, inv.revision_id
1980
next_revid = order.pop()
1982
# We still want to fully consume the stream, just
1983
# in case it is not actually finished at this point
1986
except errors.UnknownSmartMethod:
1987
for inv, revid in self._iter_inventories_vfs(revision_ids, ordering):
1991
if order_as_requested:
1992
if next_revid is not None:
1993
yield None, next_revid
1996
yield invs.get(revid), revid
1999
yield None, missing.pop()
1289
2001
@needs_read_lock
1290
2002
def get_revision(self, revision_id):
1292
return self._real_repository.get_revision(revision_id)
2003
return self.get_revisions([revision_id])[0]
1294
2005
def get_transaction(self):
1295
2006
self._ensure_real()
1328
2051
included_keys = result_set.intersection(result_parents)
1329
2052
start_keys = result_set.difference(included_keys)
1330
2053
exclude_keys = result_parents.difference(result_set)
1331
result = graph.SearchResult(start_keys, exclude_keys,
2054
result = vf_search.SearchResult(start_keys, exclude_keys,
1332
2055
len(result_set), result_set)
1335
2058
@needs_read_lock
1336
def search_missing_revision_ids(self, other, revision_id=None, find_ghosts=True):
2059
def search_missing_revision_ids(self, other,
2060
revision_id=symbol_versioning.DEPRECATED_PARAMETER,
2061
find_ghosts=True, revision_ids=None, if_present_ids=None,
1337
2063
"""Return the revision ids that other has that this does not.
1339
2065
These are returned in topological order.
1341
2067
revision_id: only return revision ids included by revision_id.
1343
return repository.InterRepository.get(
1344
other, self).search_missing_revision_ids(revision_id, find_ghosts)
2069
if symbol_versioning.deprecated_passed(revision_id):
2070
symbol_versioning.warn(
2071
'search_missing_revision_ids(revision_id=...) was '
2072
'deprecated in 2.4. Use revision_ids=[...] instead.',
2073
DeprecationWarning, stacklevel=2)
2074
if revision_ids is not None:
2075
raise AssertionError(
2076
'revision_ids is mutually exclusive with revision_id')
2077
if revision_id is not None:
2078
revision_ids = [revision_id]
2079
inter_repo = _mod_repository.InterRepository.get(other, self)
2080
return inter_repo.search_missing_revision_ids(
2081
find_ghosts=find_ghosts, revision_ids=revision_ids,
2082
if_present_ids=if_present_ids, limit=limit)
1346
def fetch(self, source, revision_id=None, pb=None, find_ghosts=False,
2084
def fetch(self, source, revision_id=None, find_ghosts=False,
1347
2085
fetch_spec=None):
1348
2086
# No base implementation to use as RemoteRepository is not a subclass
1349
2087
# of Repository; so this is a copy of Repository.fetch().
1388
2132
return self._real_repository._get_versioned_file_checker(
1389
2133
revisions, revision_versions_cache)
2135
def _iter_files_bytes_rpc(self, desired_files, absent):
2136
path = self.bzrdir._path_for_remote_call(self._client)
2139
for (file_id, revid, identifier) in desired_files:
2140
lines.append("%s\0%s" % (
2141
osutils.safe_file_id(file_id),
2142
osutils.safe_revision_id(revid)))
2143
identifiers.append(identifier)
2144
(response_tuple, response_handler) = (
2145
self._call_with_body_bytes_expecting_body(
2146
"Repository.iter_files_bytes", (path, ), "\n".join(lines)))
2147
if response_tuple != ('ok', ):
2148
response_handler.cancel_read_body()
2149
raise errors.UnexpectedSmartServerResponse(response_tuple)
2150
byte_stream = response_handler.read_streamed_body()
2151
def decompress_stream(start, byte_stream, unused):
2152
decompressor = zlib.decompressobj()
2153
yield decompressor.decompress(start)
2154
while decompressor.unused_data == "":
2156
data = byte_stream.next()
2157
except StopIteration:
2159
yield decompressor.decompress(data)
2160
yield decompressor.flush()
2161
unused.append(decompressor.unused_data)
2164
while not "\n" in unused:
2165
unused += byte_stream.next()
2166
header, rest = unused.split("\n", 1)
2167
args = header.split("\0")
2168
if args[0] == "absent":
2169
absent[identifiers[int(args[3])]] = (args[1], args[2])
2172
elif args[0] == "ok":
2175
raise errors.UnexpectedSmartServerResponse(args)
2177
yield (identifiers[idx],
2178
decompress_stream(rest, byte_stream, unused_chunks))
2179
unused = "".join(unused_chunks)
1391
2181
def iter_files_bytes(self, desired_files):
1392
2182
"""See Repository.iter_file_bytes.
1395
return self._real_repository.iter_files_bytes(desired_files)
2186
for (identifier, bytes_iterator) in self._iter_files_bytes_rpc(
2187
desired_files, absent):
2188
yield identifier, bytes_iterator
2189
for fallback in self._fallback_repositories:
2192
desired_files = [(key[0], key[1], identifier) for
2193
(identifier, key) in absent.iteritems()]
2194
for (identifier, bytes_iterator) in fallback.iter_files_bytes(desired_files):
2195
del absent[identifier]
2196
yield identifier, bytes_iterator
2198
# There may be more missing items, but raise an exception
2200
missing_identifier = absent.keys()[0]
2201
missing_key = absent[missing_identifier]
2202
raise errors.RevisionNotPresent(revision_id=missing_key[1],
2203
file_id=missing_key[0])
2204
except errors.UnknownSmartMethod:
2206
for (identifier, bytes_iterator) in (
2207
self._real_repository.iter_files_bytes(desired_files)):
2208
yield identifier, bytes_iterator
2210
def get_cached_parent_map(self, revision_ids):
2211
"""See bzrlib.CachingParentsProvider.get_cached_parent_map"""
2212
return self._unstacked_provider.get_cached_parent_map(revision_ids)
1397
2214
def get_parent_map(self, revision_ids):
1398
2215
"""See bzrlib.Graph.get_parent_map()."""
1532
2338
@needs_read_lock
1533
2339
def get_signature_text(self, revision_id):
1535
return self._real_repository.get_signature_text(revision_id)
2340
path = self.bzrdir._path_for_remote_call(self._client)
2342
response_tuple, response_handler = self._call_expecting_body(
2343
'Repository.get_revision_signature_text', path, revision_id)
2344
except errors.UnknownSmartMethod:
2346
return self._real_repository.get_signature_text(revision_id)
2347
except errors.NoSuchRevision, err:
2348
for fallback in self._fallback_repositories:
2350
return fallback.get_signature_text(revision_id)
2351
except errors.NoSuchRevision:
2355
if response_tuple[0] != 'ok':
2356
raise errors.UnexpectedSmartServerResponse(response_tuple)
2357
return response_handler.read_body_bytes()
1537
2359
@needs_read_lock
1538
2360
def _get_inventory_xml(self, revision_id):
2361
# This call is used by older working tree formats,
2362
# which stored a serialized basis inventory.
1539
2363
self._ensure_real()
1540
2364
return self._real_repository._get_inventory_xml(revision_id)
1542
2367
def reconcile(self, other=None, thorough=False):
1544
return self._real_repository.reconcile(other=other, thorough=thorough)
2368
from bzrlib.reconcile import RepoReconciler
2369
path = self.bzrdir._path_for_remote_call(self._client)
2371
response, handler = self._call_expecting_body(
2372
'Repository.reconcile', path, self._lock_token)
2373
except (errors.UnknownSmartMethod, errors.TokenLockingNotSupported):
2375
return self._real_repository.reconcile(other=other, thorough=thorough)
2376
if response != ('ok', ):
2377
raise errors.UnexpectedSmartServerResponse(response)
2378
body = handler.read_body_bytes()
2379
result = RepoReconciler(self)
2380
for line in body.split('\n'):
2383
key, val_text = line.split(':')
2384
if key == "garbage_inventories":
2385
result.garbage_inventories = int(val_text)
2386
elif key == "inconsistent_parents":
2387
result.inconsistent_parents = int(val_text)
2389
mutter("unknown reconcile key %r" % key)
1546
2392
def all_revision_ids(self):
1548
return self._real_repository.all_revision_ids()
2393
path = self.bzrdir._path_for_remote_call(self._client)
2395
response_tuple, response_handler = self._call_expecting_body(
2396
"Repository.all_revision_ids", path)
2397
except errors.UnknownSmartMethod:
2399
return self._real_repository.all_revision_ids()
2400
if response_tuple != ("ok", ):
2401
raise errors.UnexpectedSmartServerResponse(response_tuple)
2402
revids = set(response_handler.read_body_bytes().splitlines())
2403
for fallback in self._fallback_repositories:
2404
revids.update(set(fallback.all_revision_ids()))
2407
def _filtered_revision_trees(self, revision_ids, file_ids):
2408
"""Return Tree for a revision on this branch with only some files.
2410
:param revision_ids: a sequence of revision-ids;
2411
a revision-id may not be None or 'null:'
2412
:param file_ids: if not None, the result is filtered
2413
so that only those file-ids, their parents and their
2414
children are included.
2416
inventories = self.iter_inventories(revision_ids)
2417
for inv in inventories:
2418
# Should we introduce a FilteredRevisionTree class rather
2419
# than pre-filter the inventory here?
2420
filtered_inv = inv.filter(file_ids)
2421
yield InventoryRevisionTree(self, filtered_inv, filtered_inv.revision_id)
1550
2423
@needs_read_lock
1551
2424
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)
2425
medium = self._client._medium
2426
if medium._is_remote_before((1, 2)):
2428
for delta in self._real_repository.get_deltas_for_revisions(
2429
revisions, specific_fileids):
2432
# Get the revision-ids of interest
2433
required_trees = set()
2434
for revision in revisions:
2435
required_trees.add(revision.revision_id)
2436
required_trees.update(revision.parent_ids[:1])
2438
# Get the matching filtered trees. Note that it's more
2439
# efficient to pass filtered trees to changes_from() rather
2440
# than doing the filtering afterwards. changes_from() could
2441
# arguably do the filtering itself but it's path-based, not
2442
# file-id based, so filtering before or afterwards is
2444
if specific_fileids is None:
2445
trees = dict((t.get_revision_id(), t) for
2446
t in self.revision_trees(required_trees))
2448
trees = dict((t.get_revision_id(), t) for
2449
t in self._filtered_revision_trees(required_trees,
2452
# Calculate the deltas
2453
for revision in revisions:
2454
if not revision.parent_ids:
2455
old_tree = self.revision_tree(_mod_revision.NULL_REVISION)
2457
old_tree = trees[revision.parent_ids[0]]
2458
yield trees[revision.revision_id].changes_from(old_tree)
1556
2460
@needs_read_lock
1557
2461
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)
2462
r = self.get_revision(revision_id)
2463
return list(self.get_deltas_for_revisions([r],
2464
specific_fileids=specific_fileids))[0]
1562
2466
@needs_read_lock
1563
2467
def revision_trees(self, revision_ids):
1565
return self._real_repository.revision_trees(revision_ids)
2468
inventories = self.iter_inventories(revision_ids)
2469
for inv in inventories:
2470
yield InventoryRevisionTree(self, inv, inv.revision_id)
1567
2472
@needs_read_lock
1568
2473
def get_revision_reconcile(self, revision_id):
1680
2598
self._ensure_real()
1681
2599
return self._real_repository.texts
2601
def _iter_revisions_rpc(self, revision_ids):
2602
body = "\n".join(revision_ids)
2603
path = self.bzrdir._path_for_remote_call(self._client)
2604
response_tuple, response_handler = (
2605
self._call_with_body_bytes_expecting_body(
2606
"Repository.iter_revisions", (path, ), body))
2607
if response_tuple[0] != "ok":
2608
raise errors.UnexpectedSmartServerResponse(response_tuple)
2609
serializer_format = response_tuple[1]
2610
serializer = serializer_format_registry.get(serializer_format)
2611
byte_stream = response_handler.read_streamed_body()
2612
decompressor = zlib.decompressobj()
2614
for bytes in byte_stream:
2615
chunks.append(decompressor.decompress(bytes))
2616
if decompressor.unused_data != "":
2617
chunks.append(decompressor.flush())
2618
yield serializer.read_revision_from_string("".join(chunks))
2619
unused = decompressor.unused_data
2620
decompressor = zlib.decompressobj()
2621
chunks = [decompressor.decompress(unused)]
2622
chunks.append(decompressor.flush())
2623
text = "".join(chunks)
2625
yield serializer.read_revision_from_string("".join(chunks))
1683
2627
@needs_read_lock
1684
2628
def get_revisions(self, revision_ids):
1686
return self._real_repository.get_revisions(revision_ids)
2629
if revision_ids is None:
2630
revision_ids = self.all_revision_ids()
2632
for rev_id in revision_ids:
2633
if not rev_id or not isinstance(rev_id, basestring):
2634
raise errors.InvalidRevisionId(
2635
revision_id=rev_id, branch=self)
2637
missing = set(revision_ids)
2639
for rev in self._iter_revisions_rpc(revision_ids):
2640
missing.remove(rev.revision_id)
2641
revs[rev.revision_id] = rev
2642
except errors.UnknownSmartMethod:
2644
return self._real_repository.get_revisions(revision_ids)
2645
for fallback in self._fallback_repositories:
2648
for revid in list(missing):
2649
# XXX JRV 2011-11-20: It would be nice if there was a
2650
# public method on Repository that could be used to query
2651
# for revision objects *without* failing completely if one
2652
# was missing. There is VersionedFileRepository._iter_revisions,
2653
# but unfortunately that's private and not provided by
2654
# all repository implementations.
2656
revs[revid] = fallback.get_revision(revid)
2657
except errors.NoSuchRevision:
2660
missing.remove(revid)
2662
raise errors.NoSuchRevision(self, list(missing)[0])
2663
return [revs[revid] for revid in revision_ids]
1688
2665
def supports_rich_root(self):
1689
2666
return self._format.rich_root_data
2668
@symbol_versioning.deprecated_method(symbol_versioning.deprecated_in((2, 4, 0)))
1691
2669
def iter_reverse_revision_history(self, revision_id):
1692
2670
self._ensure_real()
1693
2671
return self._real_repository.iter_reverse_revision_history(revision_id)
1696
2674
def _serializer(self):
1697
2675
return self._format._serializer
1699
2678
def store_revision_signature(self, gpg_strategy, plaintext, revision_id):
1701
return self._real_repository.store_revision_signature(
1702
gpg_strategy, plaintext, revision_id)
2679
signature = gpg_strategy.sign(plaintext)
2680
self.add_signature_text(revision_id, signature)
1704
2682
def add_signature_text(self, revision_id, signature):
1706
return self._real_repository.add_signature_text(revision_id, signature)
2683
if self._real_repository:
2684
# If there is a real repository the write group will
2685
# be in the real repository as well, so use that:
2687
return self._real_repository.add_signature_text(
2688
revision_id, signature)
2689
path = self.bzrdir._path_for_remote_call(self._client)
2690
response, handler = self._call_with_body_bytes_expecting_body(
2691
'Repository.add_signature_text', (path, self._lock_token,
2692
revision_id) + tuple(self._write_group_tokens), signature)
2693
handler.cancel_read_body()
2695
if response[0] != 'ok':
2696
raise errors.UnexpectedSmartServerResponse(response)
2697
self._write_group_tokens = response[1:]
1708
2699
def has_signature_for_revision_id(self, revision_id):
1710
return self._real_repository.has_signature_for_revision_id(revision_id)
2700
path = self.bzrdir._path_for_remote_call(self._client)
2702
response = self._call('Repository.has_signature_for_revision_id',
2704
except errors.UnknownSmartMethod:
2706
return self._real_repository.has_signature_for_revision_id(
2708
if response[0] not in ('yes', 'no'):
2709
raise SmartProtocolError('unexpected response code %s' % (response,))
2710
if response[0] == 'yes':
2712
for fallback in self._fallback_repositories:
2713
if fallback.has_signature_for_revision_id(revision_id):
2718
def verify_revision_signature(self, revision_id, gpg_strategy):
2719
if not self.has_signature_for_revision_id(revision_id):
2720
return gpg.SIGNATURE_NOT_SIGNED, None
2721
signature = self.get_signature_text(revision_id)
2723
testament = _mod_testament.Testament.from_revision(self, revision_id)
2724
plaintext = testament.as_short_text()
2726
return gpg_strategy.verify(signature, plaintext)
1712
2728
def item_keys_introduced_by(self, revision_ids, _files_pb=None):
1713
2729
self._ensure_real()
1714
2730
return self._real_repository.item_keys_introduced_by(revision_ids,
1715
2731
_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
2733
def _find_inconsistent_revision_parents(self, revisions_iterator=None):
1723
2734
self._ensure_real()
1724
2735
return self._real_repository._find_inconsistent_revision_parents(
2071
3093
if isinstance(a_bzrdir, RemoteBzrDir):
2072
3094
a_bzrdir._ensure_real()
2073
3095
result = self._custom_format.initialize(a_bzrdir._real_bzrdir,
3096
name, append_revisions_only=append_revisions_only)
2076
3098
# We assume the bzrdir is parameterised; it may not be.
2077
result = self._custom_format.initialize(a_bzrdir, name)
3099
result = self._custom_format.initialize(a_bzrdir, name,
3100
append_revisions_only=append_revisions_only)
2078
3101
if (isinstance(a_bzrdir, RemoteBzrDir) and
2079
3102
not isinstance(result, RemoteBranch)):
2080
3103
result = RemoteBranch(a_bzrdir, a_bzrdir.find_repository(), result,
2084
def initialize(self, a_bzrdir, name=None):
3107
def initialize(self, a_bzrdir, name=None, repository=None,
3108
append_revisions_only=None):
3110
name = a_bzrdir._get_selected_branch()
2085
3111
# 1) get the network name to use.
2086
3112
if self._custom_format:
2087
3113
network_name = self._custom_format.network_name()
2089
3115
# Select the current bzrlib default and ask for that.
2090
reference_bzrdir_format = bzrdir.format_registry.get('default')()
3116
reference_bzrdir_format = _mod_bzrdir.format_registry.get('default')()
2091
3117
reference_format = reference_bzrdir_format.get_branch_format()
2092
3118
self._custom_format = reference_format
2093
3119
network_name = reference_format.network_name()
2094
3120
# Being asked to create on a non RemoteBzrDir:
2095
3121
if not isinstance(a_bzrdir, RemoteBzrDir):
2096
return self._vfs_initialize(a_bzrdir, name=name)
3122
return self._vfs_initialize(a_bzrdir, name=name,
3123
append_revisions_only=append_revisions_only)
2097
3124
medium = a_bzrdir._client._medium
2098
3125
if medium._is_remote_before((1, 13)):
2099
return self._vfs_initialize(a_bzrdir, name=name)
3126
return self._vfs_initialize(a_bzrdir, name=name,
3127
append_revisions_only=append_revisions_only)
2100
3128
# Creating on a remote bzr dir.
2101
3129
# 2) try direct creation via RPC
2102
3130
path = a_bzrdir._path_for_remote_call(a_bzrdir._client)
2103
if name is not None:
2104
3132
# XXX JRV20100304: Support creating colocated branches
2105
3133
raise errors.NoColocatedBranchSupport(self)
2106
3134
verb = 'BzrDir.create_branch'
2148
3191
self._ensure_real()
2149
3192
return self._custom_format.supports_set_append_revisions_only()
3194
def _use_default_local_heads_to_fetch(self):
3195
# If the branch format is a metadir format *and* its heads_to_fetch
3196
# implementation is not overridden vs the base class, we can use the
3197
# base class logic rather than use the heads_to_fetch RPC. This is
3198
# usually cheaper in terms of net round trips, as the last-revision and
3199
# tags info fetched is cached and would be fetched anyway.
3201
if isinstance(self._custom_format, branch.BranchFormatMetadir):
3202
branch_class = self._custom_format._branch_class()
3203
heads_to_fetch_impl = branch_class.heads_to_fetch.im_func
3204
if heads_to_fetch_impl is branch.Branch.heads_to_fetch.im_func:
3209
class RemoteBranchStore(_mod_config.IniFileStore):
3210
"""Branch store which attempts to use HPSS calls to retrieve branch store.
3212
Note that this is specific to bzr-based formats.
3215
def __init__(self, branch):
3216
super(RemoteBranchStore, self).__init__()
3217
self.branch = branch
3219
self._real_store = None
3221
def lock_write(self, token=None):
3222
return self.branch.lock_write(token)
3225
return self.branch.unlock()
3229
# We need to be able to override the undecorated implementation
3230
self.save_without_locking()
3232
def save_without_locking(self):
3233
super(RemoteBranchStore, self).save()
3235
def external_url(self):
3236
return self.branch.user_url
3238
def _load_content(self):
3239
path = self.branch._remote_path()
3241
response, handler = self.branch._call_expecting_body(
3242
'Branch.get_config_file', path)
3243
except errors.UnknownSmartMethod:
3245
return self._real_store._load_content()
3246
if len(response) and response[0] != 'ok':
3247
raise errors.UnexpectedSmartServerResponse(response)
3248
return handler.read_body_bytes()
3250
def _save_content(self, content):
3251
path = self.branch._remote_path()
3253
response, handler = self.branch._call_with_body_bytes_expecting_body(
3254
'Branch.put_config_file', (path,
3255
self.branch._lock_token, self.branch._repo_lock_token),
3257
except errors.UnknownSmartMethod:
3259
return self._real_store._save_content(content)
3260
handler.cancel_read_body()
3261
if response != ('ok', ):
3262
raise errors.UnexpectedSmartServerResponse(response)
3264
def _ensure_real(self):
3265
self.branch._ensure_real()
3266
if self._real_store is None:
3267
self._real_store = _mod_config.BranchStore(self.branch)
2152
3270
class RemoteBranch(branch.Branch, _RpcHelper, lock._RelockDebugMixin):
2153
3271
"""Branch stored on a server accessed by HPSS RPC.
2654
3816
_override_hook_target=self, **kwargs)
2656
3818
@needs_read_lock
2657
def push(self, target, overwrite=False, stop_revision=None):
3819
def push(self, target, overwrite=False, stop_revision=None, lossy=False):
2658
3820
self._ensure_real()
2659
3821
return self._real_branch.push(
2660
target, overwrite=overwrite, stop_revision=stop_revision,
3822
target, overwrite=overwrite, stop_revision=stop_revision, lossy=lossy,
2661
3823
_override_hook_source_branch=self)
2663
3825
def is_locked(self):
2664
3826
return self._lock_count >= 1
2666
3828
@needs_read_lock
3829
def revision_id_to_dotted_revno(self, revision_id):
3830
"""Given a revision id, return its dotted revno.
3832
:return: a tuple like (1,) or (400,1,3).
3835
response = self._call('Branch.revision_id_to_revno',
3836
self._remote_path(), revision_id)
3837
except errors.UnknownSmartMethod:
3839
return self._real_branch.revision_id_to_dotted_revno(revision_id)
3840
if response[0] == 'ok':
3841
return tuple([int(x) for x in response[1:]])
3843
raise errors.UnexpectedSmartServerResponse(response)
2667
3846
def revision_id_to_revno(self, revision_id):
2669
return self._real_branch.revision_id_to_revno(revision_id)
3847
"""Given a revision id on the branch mainline, return its revno.
3852
response = self._call('Branch.revision_id_to_revno',
3853
self._remote_path(), revision_id)
3854
except errors.UnknownSmartMethod:
3856
return self._real_branch.revision_id_to_revno(revision_id)
3857
if response[0] == 'ok':
3858
if len(response) == 2:
3859
return int(response[1])
3860
raise NoSuchRevision(self, revision_id)
3862
raise errors.UnexpectedSmartServerResponse(response)
2671
3864
@needs_write_lock
2672
3865
def set_last_revision_info(self, revno, revision_id):
2673
3866
# XXX: These should be returned by the set_last_revision_info verb
2674
3867
old_revno, old_revid = self.last_revision_info()
2675
3868
self._run_pre_change_branch_tip_hooks(revno, revision_id)
2676
revision_id = ensure_null(revision_id)
3869
if not revision_id or not isinstance(revision_id, basestring):
3870
raise errors.InvalidRevisionId(revision_id=revision_id, branch=self)
2678
3872
response = self._call('Branch.set_last_revision_info',
2679
3873
self._remote_path(), self._lock_token, self._repo_lock_token,
2774
4005
medium = self._branch._client._medium
2775
4006
if medium._is_remote_before((1, 14)):
2776
4007
return self._vfs_set_option(value, name, section)
4008
if isinstance(value, dict):
4009
if medium._is_remote_before((2, 2)):
4010
return self._vfs_set_option(value, name, section)
4011
return self._set_config_option_dict(value, name, section)
4013
return self._set_config_option(value, name, section)
4015
def _set_config_option(self, value, name, section):
2778
4017
path = self._branch._remote_path()
2779
4018
response = self._branch._client.call('Branch.set_config_option',
2780
4019
path, self._branch._lock_token, self._branch._repo_lock_token,
2781
4020
value.encode('utf8'), name, section or '')
2782
4021
except errors.UnknownSmartMethod:
4022
medium = self._branch._client._medium
2783
4023
medium._remember_remote_is_before((1, 14))
2784
4024
return self._vfs_set_option(value, name, section)
2785
4025
if response != ():
2786
4026
raise errors.UnexpectedSmartServerResponse(response)
4028
def _serialize_option_dict(self, option_dict):
4030
for key, value in option_dict.items():
4031
if isinstance(key, unicode):
4032
key = key.encode('utf8')
4033
if isinstance(value, unicode):
4034
value = value.encode('utf8')
4035
utf8_dict[key] = value
4036
return bencode.bencode(utf8_dict)
4038
def _set_config_option_dict(self, value, name, section):
4040
path = self._branch._remote_path()
4041
serialised_dict = self._serialize_option_dict(value)
4042
response = self._branch._client.call(
4043
'Branch.set_config_option_dict',
4044
path, self._branch._lock_token, self._branch._repo_lock_token,
4045
serialised_dict, name, section or '')
4046
except errors.UnknownSmartMethod:
4047
medium = self._branch._client._medium
4048
medium._remember_remote_is_before((2, 2))
4049
return self._vfs_set_option(value, name, section)
4051
raise errors.UnexpectedSmartServerResponse(response)
2788
4053
def _real_object(self):
2789
4054
self._branch._ensure_real()
2790
4055
return self._branch._real_branch
2873
4141
'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'):
4145
translator = error_translators.get(err.error_verb)
4149
raise translator(err, find, get_path)
4151
translator = no_context_error_translators.get(err.error_verb)
4153
raise errors.UnknownErrorFromSmartServer(err)
4155
raise translator(err)
4158
error_translators.register('NoSuchRevision',
4159
lambda err, find, get_path: NoSuchRevision(
4160
find('branch'), err.error_args[0]))
4161
error_translators.register('nosuchrevision',
4162
lambda err, find, get_path: NoSuchRevision(
4163
find('repository'), err.error_args[0]))
4165
def _translate_nobranch_error(err, find, get_path):
4166
if len(err.error_args) >= 1:
4167
extra = err.error_args[0]
4170
return errors.NotBranchError(path=find('bzrdir').root_transport.base,
4173
error_translators.register('nobranch', _translate_nobranch_error)
4174
error_translators.register('norepository',
4175
lambda err, find, get_path: errors.NoRepositoryPresent(
4177
error_translators.register('UnlockableTransport',
4178
lambda err, find, get_path: errors.UnlockableTransport(
4179
find('bzrdir').root_transport))
4180
error_translators.register('TokenMismatch',
4181
lambda err, find, get_path: errors.TokenMismatch(
4182
find('token'), '(remote token)'))
4183
error_translators.register('Diverged',
4184
lambda err, find, get_path: errors.DivergedBranches(
4185
find('branch'), find('other_branch')))
4186
error_translators.register('NotStacked',
4187
lambda err, find, get_path: errors.NotStacked(branch=find('branch')))
4189
def _translate_PermissionDenied(err, find, get_path):
4191
if len(err.error_args) >= 2:
4192
extra = err.error_args[1]
4195
return errors.PermissionDenied(path, extra=extra)
4197
error_translators.register('PermissionDenied', _translate_PermissionDenied)
4198
error_translators.register('ReadError',
4199
lambda err, find, get_path: errors.ReadError(get_path()))
4200
error_translators.register('NoSuchFile',
4201
lambda err, find, get_path: errors.NoSuchFile(get_path()))
4202
error_translators.register('TokenLockingNotSupported',
4203
lambda err, find, get_path: errors.TokenLockingNotSupported(
4204
find('repository')))
4205
error_translators.register('UnsuspendableWriteGroup',
4206
lambda err, find, get_path: errors.UnsuspendableWriteGroup(
4207
repository=find('repository')))
4208
error_translators.register('UnresumableWriteGroup',
4209
lambda err, find, get_path: errors.UnresumableWriteGroup(
4210
repository=find('repository'), write_groups=err.error_args[0],
4211
reason=err.error_args[1]))
4212
no_context_error_translators.register('IncompatibleRepositories',
4213
lambda err: errors.IncompatibleRepositories(
4214
err.error_args[0], err.error_args[1], err.error_args[2]))
4215
no_context_error_translators.register('LockContention',
4216
lambda err: errors.LockContention('(remote lock)'))
4217
no_context_error_translators.register('LockFailed',
4218
lambda err: errors.LockFailed(err.error_args[0], err.error_args[1]))
4219
no_context_error_translators.register('TipChangeRejected',
4220
lambda err: errors.TipChangeRejected(err.error_args[0].decode('utf8')))
4221
no_context_error_translators.register('UnstackableBranchFormat',
4222
lambda err: errors.UnstackableBranchFormat(*err.error_args))
4223
no_context_error_translators.register('UnstackableRepositoryFormat',
4224
lambda err: errors.UnstackableRepositoryFormat(*err.error_args))
4225
no_context_error_translators.register('FileExists',
4226
lambda err: errors.FileExists(err.error_args[0]))
4227
no_context_error_translators.register('DirectoryNotEmpty',
4228
lambda err: errors.DirectoryNotEmpty(err.error_args[0]))
4230
def _translate_short_readv_error(err):
4231
args = err.error_args
4232
return errors.ShortReadvError(args[0], int(args[1]), int(args[2]),
4235
no_context_error_translators.register('ShortReadvError',
4236
_translate_short_readv_error)
4238
def _translate_unicode_error(err):
2932
4239
encoding = str(err.error_args[0]) # encoding must always be a string
2933
4240
val = err.error_args[1]
2934
4241
start = int(err.error_args[2])