91
# Note: RemoteBzrDirFormat is in bzrdir.py
93
class RemoteBzrDir(BzrDir, _RpcHelper):
105
# Note that RemoteBzrDirProber lives in bzrlib.bzrdir so bzrlib.remote
106
# does not have to be imported unless a remote format is involved.
108
class RemoteBzrDirFormat(_mod_bzrdir.BzrDirMetaFormat1):
109
"""Format representing bzrdirs accessed via a smart server"""
111
supports_workingtrees = False
114
_mod_bzrdir.BzrDirMetaFormat1.__init__(self)
115
# XXX: It's a bit ugly that the network name is here, because we'd
116
# like to believe that format objects are stateless or at least
117
# immutable, However, we do at least avoid mutating the name after
118
# it's returned. See <https://bugs.launchpad.net/bzr/+bug/504102>
119
self._network_name = None
122
return "%s(_network_name=%r)" % (self.__class__.__name__,
125
def get_format_description(self):
126
if self._network_name:
128
real_format = controldir.network_format_registry.get(
133
return 'Remote: ' + real_format.get_format_description()
134
return 'bzr remote bzrdir'
136
def get_format_string(self):
137
raise NotImplementedError(self.get_format_string)
139
def network_name(self):
140
if self._network_name:
141
return self._network_name
143
raise AssertionError("No network name set.")
145
def initialize_on_transport(self, transport):
147
# hand off the request to the smart server
148
client_medium = transport.get_smart_medium()
149
except errors.NoSmartMedium:
150
# TODO: lookup the local format from a server hint.
151
local_dir_format = _mod_bzrdir.BzrDirMetaFormat1()
152
return local_dir_format.initialize_on_transport(transport)
153
client = _SmartClient(client_medium)
154
path = client.remote_path_from_transport(transport)
156
response = client.call('BzrDirFormat.initialize', path)
157
except errors.ErrorFromSmartServer, err:
158
_translate_error(err, path=path)
159
if response[0] != 'ok':
160
raise errors.SmartProtocolError('unexpected response code %s' % (response,))
161
format = RemoteBzrDirFormat()
162
self._supply_sub_formats_to(format)
163
return RemoteBzrDir(transport, format)
165
def parse_NoneTrueFalse(self, arg):
172
raise AssertionError("invalid arg %r" % arg)
174
def _serialize_NoneTrueFalse(self, arg):
181
def _serialize_NoneString(self, arg):
184
def initialize_on_transport_ex(self, transport, use_existing_dir=False,
185
create_prefix=False, force_new_repo=False, stacked_on=None,
186
stack_on_pwd=None, repo_format_name=None, make_working_trees=None,
189
# hand off the request to the smart server
190
client_medium = transport.get_smart_medium()
191
except errors.NoSmartMedium:
194
# Decline to open it if the server doesn't support our required
195
# version (3) so that the VFS-based transport will do it.
196
if client_medium.should_probe():
198
server_version = client_medium.protocol_version()
199
if server_version != '2':
203
except errors.SmartProtocolError:
204
# Apparently there's no usable smart server there, even though
205
# the medium supports the smart protocol.
210
client = _SmartClient(client_medium)
211
path = client.remote_path_from_transport(transport)
212
if client_medium._is_remote_before((1, 16)):
215
# TODO: lookup the local format from a server hint.
216
local_dir_format = _mod_bzrdir.BzrDirMetaFormat1()
217
self._supply_sub_formats_to(local_dir_format)
218
return local_dir_format.initialize_on_transport_ex(transport,
219
use_existing_dir=use_existing_dir, create_prefix=create_prefix,
220
force_new_repo=force_new_repo, stacked_on=stacked_on,
221
stack_on_pwd=stack_on_pwd, repo_format_name=repo_format_name,
222
make_working_trees=make_working_trees, shared_repo=shared_repo,
224
return self._initialize_on_transport_ex_rpc(client, path, transport,
225
use_existing_dir, create_prefix, force_new_repo, stacked_on,
226
stack_on_pwd, repo_format_name, make_working_trees, shared_repo)
228
def _initialize_on_transport_ex_rpc(self, client, path, transport,
229
use_existing_dir, create_prefix, force_new_repo, stacked_on,
230
stack_on_pwd, repo_format_name, make_working_trees, shared_repo):
232
args.append(self._serialize_NoneTrueFalse(use_existing_dir))
233
args.append(self._serialize_NoneTrueFalse(create_prefix))
234
args.append(self._serialize_NoneTrueFalse(force_new_repo))
235
args.append(self._serialize_NoneString(stacked_on))
236
# stack_on_pwd is often/usually our transport
239
stack_on_pwd = transport.relpath(stack_on_pwd)
242
except errors.PathNotChild:
244
args.append(self._serialize_NoneString(stack_on_pwd))
245
args.append(self._serialize_NoneString(repo_format_name))
246
args.append(self._serialize_NoneTrueFalse(make_working_trees))
247
args.append(self._serialize_NoneTrueFalse(shared_repo))
248
request_network_name = self._network_name or \
249
_mod_bzrdir.BzrDirFormat.get_default_format().network_name()
251
response = client.call('BzrDirFormat.initialize_ex_1.16',
252
request_network_name, path, *args)
253
except errors.UnknownSmartMethod:
254
client._medium._remember_remote_is_before((1,16))
255
local_dir_format = _mod_bzrdir.BzrDirMetaFormat1()
256
self._supply_sub_formats_to(local_dir_format)
257
return local_dir_format.initialize_on_transport_ex(transport,
258
use_existing_dir=use_existing_dir, create_prefix=create_prefix,
259
force_new_repo=force_new_repo, stacked_on=stacked_on,
260
stack_on_pwd=stack_on_pwd, repo_format_name=repo_format_name,
261
make_working_trees=make_working_trees, shared_repo=shared_repo,
263
except errors.ErrorFromSmartServer, err:
264
_translate_error(err, path=path)
265
repo_path = response[0]
266
bzrdir_name = response[6]
267
require_stacking = response[7]
268
require_stacking = self.parse_NoneTrueFalse(require_stacking)
269
format = RemoteBzrDirFormat()
270
format._network_name = bzrdir_name
271
self._supply_sub_formats_to(format)
272
bzrdir = RemoteBzrDir(transport, format, _client=client)
274
repo_format = response_tuple_to_repo_format(response[1:])
278
repo_bzrdir_format = RemoteBzrDirFormat()
279
repo_bzrdir_format._network_name = response[5]
280
repo_bzr = RemoteBzrDir(transport.clone(repo_path),
284
final_stack = response[8] or None
285
final_stack_pwd = response[9] or None
287
final_stack_pwd = urlutils.join(
288
transport.base, final_stack_pwd)
289
remote_repo = RemoteRepository(repo_bzr, repo_format)
290
if len(response) > 10:
291
# Updated server verb that locks remotely.
292
repo_lock_token = response[10] or None
293
remote_repo.lock_write(repo_lock_token, _skip_rpc=True)
295
remote_repo.dont_leave_lock_in_place()
297
remote_repo.lock_write()
298
policy = _mod_bzrdir.UseExistingRepository(remote_repo, final_stack,
299
final_stack_pwd, require_stacking)
300
policy.acquire_repository()
304
bzrdir._format.set_branch_format(self.get_branch_format())
306
# The repo has already been created, but we need to make sure that
307
# we'll make a stackable branch.
308
bzrdir._format.require_stacking(_skip_repo=True)
309
return remote_repo, bzrdir, require_stacking, policy
311
def _open(self, transport):
312
return RemoteBzrDir(transport, self)
314
def __eq__(self, other):
315
if not isinstance(other, RemoteBzrDirFormat):
317
return self.get_format_description() == other.get_format_description()
319
def __return_repository_format(self):
320
# Always return a RemoteRepositoryFormat object, but if a specific bzr
321
# repository format has been asked for, tell the RemoteRepositoryFormat
322
# that it should use that for init() etc.
323
result = RemoteRepositoryFormat()
324
custom_format = getattr(self, '_repository_format', None)
326
if isinstance(custom_format, RemoteRepositoryFormat):
329
# We will use the custom format to create repositories over the
330
# wire; expose its details like rich_root_data for code to
332
result._custom_format = custom_format
335
def get_branch_format(self):
336
result = _mod_bzrdir.BzrDirMetaFormat1.get_branch_format(self)
337
if not isinstance(result, RemoteBranchFormat):
338
new_result = RemoteBranchFormat()
339
new_result._custom_format = result
341
self.set_branch_format(new_result)
345
repository_format = property(__return_repository_format,
346
_mod_bzrdir.BzrDirMetaFormat1._set_repository_format) #.im_func)
349
class RemoteControlStore(config.IniFileStore):
350
"""Control store which attempts to use HPSS calls to retrieve control store.
352
Note that this is specific to bzr-based formats.
355
def __init__(self, bzrdir):
356
super(RemoteControlStore, self).__init__()
358
self._real_store = None
360
def lock_write(self, token=None):
362
return self._real_store.lock_write(token)
366
return self._real_store.unlock()
370
# We need to be able to override the undecorated implementation
371
self.save_without_locking()
373
def save_without_locking(self):
374
super(RemoteControlStore, self).save()
376
def _ensure_real(self):
377
self.bzrdir._ensure_real()
378
if self._real_store is None:
379
self._real_store = config.ControlStore(self.bzrdir)
381
def external_url(self):
382
return self.bzrdir.user_url
384
def _load_content(self):
385
medium = self.bzrdir._client._medium
386
path = self.bzrdir._path_for_remote_call(self.bzrdir._client)
388
response, handler = self.bzrdir._call_expecting_body(
389
'BzrDir.get_config_file', path)
390
except errors.UnknownSmartMethod:
392
return self._real_store._load_content()
393
if len(response) and response[0] != 'ok':
394
raise errors.UnexpectedSmartServerResponse(response)
395
return handler.read_body_bytes()
397
def _save_content(self, content):
398
# FIXME JRV 2011-11-22: Ideally this should use a
399
# HPSS call too, but at the moment it is not possible
400
# to write lock control directories.
402
return self._real_store._save_content(content)
405
class RemoteBzrDir(_mod_bzrdir.BzrDir, _RpcHelper):
94
406
"""Control directory on a remote server, accessed via bzr:// or similar."""
96
408
def __init__(self, transport, format, _client=None, _force_probe=False):
1206
1715
raise errors.UnexpectedSmartServerResponse(response)
1208
1718
def sprout(self, to_bzrdir, revision_id=None):
1209
# TODO: Option to control what format is created?
1211
dest_repo = self._real_repository._format.initialize(to_bzrdir,
1719
"""Create a descendent repository for new development.
1721
Unlike clone, this does not copy the settings of the repository.
1723
dest_repo = self._create_sprouting_repo(to_bzrdir, shared=False)
1213
1724
dest_repo.fetch(self, revision_id=revision_id)
1214
1725
return dest_repo
1727
def _create_sprouting_repo(self, a_bzrdir, shared):
1728
if not isinstance(a_bzrdir._format, self.bzrdir._format.__class__):
1729
# use target default format.
1730
dest_repo = a_bzrdir.create_repository()
1732
# Most control formats need the repository to be specifically
1733
# created, but on some old all-in-one formats it's not needed
1735
dest_repo = self._format.initialize(a_bzrdir, shared=shared)
1736
except errors.UninitializableFormat:
1737
dest_repo = a_bzrdir.open_repository()
1216
1740
### These methods are just thin shims to the VFS object for now.
1218
1743
def revision_tree(self, revision_id):
1220
return self._real_repository.revision_tree(revision_id)
1744
revision_id = _mod_revision.ensure_null(revision_id)
1745
if revision_id == _mod_revision.NULL_REVISION:
1746
return InventoryRevisionTree(self,
1747
Inventory(root_id=None), _mod_revision.NULL_REVISION)
1749
return list(self.revision_trees([revision_id]))[0]
1222
1751
def get_serializer_format(self):
1224
return self._real_repository.get_serializer_format()
1752
path = self.bzrdir._path_for_remote_call(self._client)
1754
response = self._call('VersionedFileRepository.get_serializer_format',
1756
except errors.UnknownSmartMethod:
1758
return self._real_repository.get_serializer_format()
1759
if response[0] != 'ok':
1760
raise errors.UnexpectedSmartServerResponse(response)
1226
1763
def get_commit_builder(self, branch, parents, config, timestamp=None,
1227
1764
timezone=None, committer=None, revprops=None,
1765
revision_id=None, lossy=False):
1229
1766
# FIXME: It ought to be possible to call this without immediately
1230
1767
# triggering _ensure_real. For now it's the easiest thing to do.
1231
1768
self._ensure_real()
1232
1769
real_repo = self._real_repository
1233
1770
builder = real_repo.get_commit_builder(branch, parents,
1234
1771
config, timestamp=timestamp, timezone=timezone,
1235
committer=committer, revprops=revprops, revision_id=revision_id)
1772
committer=committer, revprops=revprops,
1773
revision_id=revision_id, lossy=lossy)
1238
1776
def add_fallback_repository(self, repository):
1291
1830
@needs_read_lock
1292
1831
def get_inventory(self, revision_id):
1832
return list(self.iter_inventories([revision_id]))[0]
1834
def _iter_inventories_rpc(self, revision_ids, ordering):
1835
if ordering is None:
1836
ordering = 'unordered'
1837
path = self.bzrdir._path_for_remote_call(self._client)
1838
body = "\n".join(revision_ids)
1839
response_tuple, response_handler = (
1840
self._call_with_body_bytes_expecting_body(
1841
"VersionedFileRepository.get_inventories",
1842
(path, ordering), body))
1843
if response_tuple[0] != "ok":
1844
raise errors.UnexpectedSmartServerResponse(response_tuple)
1845
deserializer = inventory_delta.InventoryDeltaDeserializer()
1846
byte_stream = response_handler.read_streamed_body()
1847
decoded = smart_repo._byte_stream_to_stream(byte_stream)
1849
# no results whatsoever
1851
src_format, stream = decoded
1852
if src_format.network_name() != self._format.network_name():
1853
raise AssertionError(
1854
"Mismatched RemoteRepository and stream src %r, %r" % (
1855
src_format.network_name(), self._format.network_name()))
1856
# ignore the src format, it's not really relevant
1857
prev_inv = Inventory(root_id=None,
1858
revision_id=_mod_revision.NULL_REVISION)
1859
# there should be just one substream, with inventory deltas
1860
substream_kind, substream = stream.next()
1861
if substream_kind != "inventory-deltas":
1862
raise AssertionError(
1863
"Unexpected stream %r received" % substream_kind)
1864
for record in substream:
1865
(parent_id, new_id, versioned_root, tree_references, invdelta) = (
1866
deserializer.parse_text_bytes(record.get_bytes_as("fulltext")))
1867
if parent_id != prev_inv.revision_id:
1868
raise AssertionError("invalid base %r != %r" % (parent_id,
1869
prev_inv.revision_id))
1870
inv = prev_inv.create_by_apply_delta(invdelta, new_id)
1871
yield inv, inv.revision_id
1874
def _iter_inventories_vfs(self, revision_ids, ordering=None):
1293
1875
self._ensure_real()
1294
return self._real_repository.get_inventory(revision_id)
1876
return self._real_repository._iter_inventories(revision_ids, ordering)
1296
1878
def iter_inventories(self, revision_ids, ordering=None):
1298
return self._real_repository.iter_inventories(revision_ids, ordering)
1879
"""Get many inventories by revision_ids.
1881
This will buffer some or all of the texts used in constructing the
1882
inventories in memory, but will only parse a single inventory at a
1885
:param revision_ids: The expected revision ids of the inventories.
1886
:param ordering: optional ordering, e.g. 'topological'. If not
1887
specified, the order of revision_ids will be preserved (by
1888
buffering if necessary).
1889
:return: An iterator of inventories.
1891
if ((None in revision_ids)
1892
or (_mod_revision.NULL_REVISION in revision_ids)):
1893
raise ValueError('cannot get null revision inventory')
1894
for inv, revid in self._iter_inventories(revision_ids, ordering):
1896
raise errors.NoSuchRevision(self, revid)
1899
def _iter_inventories(self, revision_ids, ordering=None):
1900
if len(revision_ids) == 0:
1902
missing = set(revision_ids)
1903
if ordering is None:
1904
order_as_requested = True
1906
order = list(revision_ids)
1908
next_revid = order.pop()
1910
order_as_requested = False
1911
if ordering != 'unordered' and self._fallback_repositories:
1912
raise ValueError('unsupported ordering %r' % ordering)
1913
iter_inv_fns = [self._iter_inventories_rpc] + [
1914
fallback._iter_inventories for fallback in
1915
self._fallback_repositories]
1917
for iter_inv in iter_inv_fns:
1918
request = [revid for revid in revision_ids if revid in missing]
1919
for inv, revid in iter_inv(request, ordering):
1922
missing.remove(inv.revision_id)
1923
if ordering != 'unordered':
1927
if order_as_requested:
1928
# Yield as many results as we can while preserving order.
1929
while next_revid in invs:
1930
inv = invs.pop(next_revid)
1931
yield inv, inv.revision_id
1933
next_revid = order.pop()
1935
# We still want to fully consume the stream, just
1936
# in case it is not actually finished at this point
1939
except errors.UnknownSmartMethod:
1940
for inv, revid in self._iter_inventories_vfs(revision_ids, ordering):
1944
if order_as_requested:
1945
if next_revid is not None:
1946
yield None, next_revid
1949
yield invs.get(revid), revid
1952
yield None, missing.pop()
1300
1954
@needs_read_lock
1301
1955
def get_revision(self, revision_id):
1303
return self._real_repository.get_revision(revision_id)
1956
return self.get_revisions([revision_id])[0]
1305
1958
def get_transaction(self):
1306
1959
self._ensure_real()
1339
2001
included_keys = result_set.intersection(result_parents)
1340
2002
start_keys = result_set.difference(included_keys)
1341
2003
exclude_keys = result_parents.difference(result_set)
1342
result = graph.SearchResult(start_keys, exclude_keys,
2004
result = vf_search.SearchResult(start_keys, exclude_keys,
1343
2005
len(result_set), result_set)
1346
2008
@needs_read_lock
1347
def search_missing_revision_ids(self, other, revision_id=None, find_ghosts=True):
2009
def search_missing_revision_ids(self, other,
2010
revision_id=symbol_versioning.DEPRECATED_PARAMETER,
2011
find_ghosts=True, revision_ids=None, if_present_ids=None,
1348
2013
"""Return the revision ids that other has that this does not.
1350
2015
These are returned in topological order.
1352
2017
revision_id: only return revision ids included by revision_id.
1354
return repository.InterRepository.get(
1355
other, self).search_missing_revision_ids(revision_id, find_ghosts)
2019
if symbol_versioning.deprecated_passed(revision_id):
2020
symbol_versioning.warn(
2021
'search_missing_revision_ids(revision_id=...) was '
2022
'deprecated in 2.4. Use revision_ids=[...] instead.',
2023
DeprecationWarning, stacklevel=2)
2024
if revision_ids is not None:
2025
raise AssertionError(
2026
'revision_ids is mutually exclusive with revision_id')
2027
if revision_id is not None:
2028
revision_ids = [revision_id]
2029
inter_repo = _mod_repository.InterRepository.get(other, self)
2030
return inter_repo.search_missing_revision_ids(
2031
find_ghosts=find_ghosts, revision_ids=revision_ids,
2032
if_present_ids=if_present_ids, limit=limit)
1357
def fetch(self, source, revision_id=None, pb=None, find_ghosts=False,
2034
def fetch(self, source, revision_id=None, find_ghosts=False,
1358
2035
fetch_spec=None):
1359
2036
# No base implementation to use as RemoteRepository is not a subclass
1360
2037
# of Repository; so this is a copy of Repository.fetch().
1399
2082
return self._real_repository._get_versioned_file_checker(
1400
2083
revisions, revision_versions_cache)
2085
def _iter_files_bytes_rpc(self, desired_files, absent):
2086
path = self.bzrdir._path_for_remote_call(self._client)
2089
for (file_id, revid, identifier) in desired_files:
2090
lines.append("%s\0%s" % (
2091
osutils.safe_file_id(file_id),
2092
osutils.safe_revision_id(revid)))
2093
identifiers.append(identifier)
2094
(response_tuple, response_handler) = (
2095
self._call_with_body_bytes_expecting_body(
2096
"Repository.iter_files_bytes", (path, ), "\n".join(lines)))
2097
if response_tuple != ('ok', ):
2098
response_handler.cancel_read_body()
2099
raise errors.UnexpectedSmartServerResponse(response_tuple)
2100
byte_stream = response_handler.read_streamed_body()
2101
def decompress_stream(start, byte_stream, unused):
2102
decompressor = zlib.decompressobj()
2103
yield decompressor.decompress(start)
2104
while decompressor.unused_data == "":
2106
data = byte_stream.next()
2107
except StopIteration:
2109
yield decompressor.decompress(data)
2110
yield decompressor.flush()
2111
unused.append(decompressor.unused_data)
2114
while not "\n" in unused:
2115
unused += byte_stream.next()
2116
header, rest = unused.split("\n", 1)
2117
args = header.split("\0")
2118
if args[0] == "absent":
2119
absent[identifiers[int(args[3])]] = (args[1], args[2])
2122
elif args[0] == "ok":
2125
raise errors.UnexpectedSmartServerResponse(args)
2127
yield (identifiers[idx],
2128
decompress_stream(rest, byte_stream, unused_chunks))
2129
unused = "".join(unused_chunks)
1402
2131
def iter_files_bytes(self, desired_files):
1403
2132
"""See Repository.iter_file_bytes.
1406
return self._real_repository.iter_files_bytes(desired_files)
2136
for (identifier, bytes_iterator) in self._iter_files_bytes_rpc(
2137
desired_files, absent):
2138
yield identifier, bytes_iterator
2139
for fallback in self._fallback_repositories:
2142
desired_files = [(key[0], key[1], identifier) for
2143
(identifier, key) in absent.iteritems()]
2144
for (identifier, bytes_iterator) in fallback.iter_files_bytes(desired_files):
2145
del absent[identifier]
2146
yield identifier, bytes_iterator
2148
# There may be more missing items, but raise an exception
2150
missing_identifier = absent.keys()[0]
2151
missing_key = absent[missing_identifier]
2152
raise errors.RevisionNotPresent(revision_id=missing_key[1],
2153
file_id=missing_key[0])
2154
except errors.UnknownSmartMethod:
2156
for (identifier, bytes_iterator) in (
2157
self._real_repository.iter_files_bytes(desired_files)):
2158
yield identifier, bytes_iterator
2160
def get_cached_parent_map(self, revision_ids):
2161
"""See bzrlib.CachingParentsProvider.get_cached_parent_map"""
2162
return self._unstacked_provider.get_cached_parent_map(revision_ids)
1408
2164
def get_parent_map(self, revision_ids):
1409
2165
"""See bzrlib.Graph.get_parent_map()."""
1543
2288
@needs_read_lock
1544
2289
def get_signature_text(self, revision_id):
1546
return self._real_repository.get_signature_text(revision_id)
2290
path = self.bzrdir._path_for_remote_call(self._client)
2292
response_tuple, response_handler = self._call_expecting_body(
2293
'Repository.get_revision_signature_text', path, revision_id)
2294
except errors.UnknownSmartMethod:
2296
return self._real_repository.get_signature_text(revision_id)
2297
except errors.NoSuchRevision, err:
2298
for fallback in self._fallback_repositories:
2300
return fallback.get_signature_text(revision_id)
2301
except errors.NoSuchRevision:
2305
if response_tuple[0] != 'ok':
2306
raise errors.UnexpectedSmartServerResponse(response_tuple)
2307
return response_handler.read_body_bytes()
1548
2309
@needs_read_lock
1549
2310
def _get_inventory_xml(self, revision_id):
2311
# This call is used by older working tree formats,
2312
# which stored a serialized basis inventory.
1550
2313
self._ensure_real()
1551
2314
return self._real_repository._get_inventory_xml(revision_id)
1553
2317
def reconcile(self, other=None, thorough=False):
1555
return self._real_repository.reconcile(other=other, thorough=thorough)
2318
from bzrlib.reconcile import RepoReconciler
2319
path = self.bzrdir._path_for_remote_call(self._client)
2321
response, handler = self._call_expecting_body(
2322
'Repository.reconcile', path, self._lock_token)
2323
except (errors.UnknownSmartMethod, errors.TokenLockingNotSupported):
2325
return self._real_repository.reconcile(other=other, thorough=thorough)
2326
if response != ('ok', ):
2327
raise errors.UnexpectedSmartServerResponse(response)
2328
body = handler.read_body_bytes()
2329
result = RepoReconciler(self)
2330
for line in body.split('\n'):
2333
key, val_text = line.split(':')
2334
if key == "garbage_inventories":
2335
result.garbage_inventories = int(val_text)
2336
elif key == "inconsistent_parents":
2337
result.inconsistent_parents = int(val_text)
2339
mutter("unknown reconcile key %r" % key)
1557
2342
def all_revision_ids(self):
1559
return self._real_repository.all_revision_ids()
2343
path = self.bzrdir._path_for_remote_call(self._client)
2345
response_tuple, response_handler = self._call_expecting_body(
2346
"Repository.all_revision_ids", path)
2347
except errors.UnknownSmartMethod:
2349
return self._real_repository.all_revision_ids()
2350
if response_tuple != ("ok", ):
2351
raise errors.UnexpectedSmartServerResponse(response_tuple)
2352
revids = set(response_handler.read_body_bytes().splitlines())
2353
for fallback in self._fallback_repositories:
2354
revids.update(set(fallback.all_revision_ids()))
2357
def _filtered_revision_trees(self, revision_ids, file_ids):
2358
"""Return Tree for a revision on this branch with only some files.
2360
:param revision_ids: a sequence of revision-ids;
2361
a revision-id may not be None or 'null:'
2362
:param file_ids: if not None, the result is filtered
2363
so that only those file-ids, their parents and their
2364
children are included.
2366
inventories = self.iter_inventories(revision_ids)
2367
for inv in inventories:
2368
# Should we introduce a FilteredRevisionTree class rather
2369
# than pre-filter the inventory here?
2370
filtered_inv = inv.filter(file_ids)
2371
yield InventoryRevisionTree(self, filtered_inv, filtered_inv.revision_id)
1561
2373
@needs_read_lock
1562
2374
def get_deltas_for_revisions(self, revisions, specific_fileids=None):
1564
return self._real_repository.get_deltas_for_revisions(revisions,
1565
specific_fileids=specific_fileids)
2375
medium = self._client._medium
2376
if medium._is_remote_before((1, 2)):
2378
for delta in self._real_repository.get_deltas_for_revisions(
2379
revisions, specific_fileids):
2382
# Get the revision-ids of interest
2383
required_trees = set()
2384
for revision in revisions:
2385
required_trees.add(revision.revision_id)
2386
required_trees.update(revision.parent_ids[:1])
2388
# Get the matching filtered trees. Note that it's more
2389
# efficient to pass filtered trees to changes_from() rather
2390
# than doing the filtering afterwards. changes_from() could
2391
# arguably do the filtering itself but it's path-based, not
2392
# file-id based, so filtering before or afterwards is
2394
if specific_fileids is None:
2395
trees = dict((t.get_revision_id(), t) for
2396
t in self.revision_trees(required_trees))
2398
trees = dict((t.get_revision_id(), t) for
2399
t in self._filtered_revision_trees(required_trees,
2402
# Calculate the deltas
2403
for revision in revisions:
2404
if not revision.parent_ids:
2405
old_tree = self.revision_tree(_mod_revision.NULL_REVISION)
2407
old_tree = trees[revision.parent_ids[0]]
2408
yield trees[revision.revision_id].changes_from(old_tree)
1567
2410
@needs_read_lock
1568
2411
def get_revision_delta(self, revision_id, specific_fileids=None):
1570
return self._real_repository.get_revision_delta(revision_id,
1571
specific_fileids=specific_fileids)
2412
r = self.get_revision(revision_id)
2413
return list(self.get_deltas_for_revisions([r],
2414
specific_fileids=specific_fileids))[0]
1573
2416
@needs_read_lock
1574
2417
def revision_trees(self, revision_ids):
1576
return self._real_repository.revision_trees(revision_ids)
2418
inventories = self.iter_inventories(revision_ids)
2419
for inv in inventories:
2420
yield InventoryRevisionTree(self, inv, inv.revision_id)
1578
2422
@needs_read_lock
1579
2423
def get_revision_reconcile(self, revision_id):
1691
2548
self._ensure_real()
1692
2549
return self._real_repository.texts
2551
def _iter_revisions_rpc(self, revision_ids):
2552
body = "\n".join(revision_ids)
2553
path = self.bzrdir._path_for_remote_call(self._client)
2554
response_tuple, response_handler = (
2555
self._call_with_body_bytes_expecting_body(
2556
"Repository.iter_revisions", (path, ), body))
2557
if response_tuple[0] != "ok":
2558
raise errors.UnexpectedSmartServerResponse(response_tuple)
2559
serializer_format = response_tuple[1]
2560
serializer = serializer_format_registry.get(serializer_format)
2561
byte_stream = response_handler.read_streamed_body()
2562
decompressor = zlib.decompressobj()
2564
for bytes in byte_stream:
2565
chunks.append(decompressor.decompress(bytes))
2566
if decompressor.unused_data != "":
2567
chunks.append(decompressor.flush())
2568
yield serializer.read_revision_from_string("".join(chunks))
2569
unused = decompressor.unused_data
2570
decompressor = zlib.decompressobj()
2571
chunks = [decompressor.decompress(unused)]
2572
chunks.append(decompressor.flush())
2573
text = "".join(chunks)
2575
yield serializer.read_revision_from_string("".join(chunks))
1694
2577
@needs_read_lock
1695
2578
def get_revisions(self, revision_ids):
1697
return self._real_repository.get_revisions(revision_ids)
2579
if revision_ids is None:
2580
revision_ids = self.all_revision_ids()
2582
for rev_id in revision_ids:
2583
if not rev_id or not isinstance(rev_id, basestring):
2584
raise errors.InvalidRevisionId(
2585
revision_id=rev_id, branch=self)
2587
missing = set(revision_ids)
2589
for rev in self._iter_revisions_rpc(revision_ids):
2590
missing.remove(rev.revision_id)
2591
revs[rev.revision_id] = rev
2592
except errors.UnknownSmartMethod:
2594
return self._real_repository.get_revisions(revision_ids)
2595
for fallback in self._fallback_repositories:
2598
for revid in list(missing):
2599
# XXX JRV 2011-11-20: It would be nice if there was a
2600
# public method on Repository that could be used to query
2601
# for revision objects *without* failing completely if one
2602
# was missing. There is VersionedFileRepository._iter_revisions,
2603
# but unfortunately that's private and not provided by
2604
# all repository implementations.
2606
revs[revid] = fallback.get_revision(revid)
2607
except errors.NoSuchRevision:
2610
missing.remove(revid)
2612
raise errors.NoSuchRevision(self, list(missing)[0])
2613
return [revs[revid] for revid in revision_ids]
1699
2615
def supports_rich_root(self):
1700
2616
return self._format.rich_root_data
2618
@symbol_versioning.deprecated_method(symbol_versioning.deprecated_in((2, 4, 0)))
1702
2619
def iter_reverse_revision_history(self, revision_id):
1703
2620
self._ensure_real()
1704
2621
return self._real_repository.iter_reverse_revision_history(revision_id)
1707
2624
def _serializer(self):
1708
2625
return self._format._serializer
1710
2628
def store_revision_signature(self, gpg_strategy, plaintext, revision_id):
1712
return self._real_repository.store_revision_signature(
1713
gpg_strategy, plaintext, revision_id)
2629
signature = gpg_strategy.sign(plaintext)
2630
self.add_signature_text(revision_id, signature)
1715
2632
def add_signature_text(self, revision_id, signature):
1717
return self._real_repository.add_signature_text(revision_id, signature)
2633
if self._real_repository:
2634
# If there is a real repository the write group will
2635
# be in the real repository as well, so use that:
2637
return self._real_repository.add_signature_text(
2638
revision_id, signature)
2639
path = self.bzrdir._path_for_remote_call(self._client)
2640
response, handler = self._call_with_body_bytes_expecting_body(
2641
'Repository.add_signature_text', (path, self._lock_token,
2642
revision_id) + tuple(self._write_group_tokens), signature)
2643
handler.cancel_read_body()
2645
if response[0] != 'ok':
2646
raise errors.UnexpectedSmartServerResponse(response)
2647
self._write_group_tokens = response[1:]
1719
2649
def has_signature_for_revision_id(self, revision_id):
1721
return self._real_repository.has_signature_for_revision_id(revision_id)
2650
path = self.bzrdir._path_for_remote_call(self._client)
2652
response = self._call('Repository.has_signature_for_revision_id',
2654
except errors.UnknownSmartMethod:
2656
return self._real_repository.has_signature_for_revision_id(
2658
if response[0] not in ('yes', 'no'):
2659
raise SmartProtocolError('unexpected response code %s' % (response,))
2660
if response[0] == 'yes':
2662
for fallback in self._fallback_repositories:
2663
if fallback.has_signature_for_revision_id(revision_id):
2668
def verify_revision_signature(self, revision_id, gpg_strategy):
2669
if not self.has_signature_for_revision_id(revision_id):
2670
return gpg.SIGNATURE_NOT_SIGNED, None
2671
signature = self.get_signature_text(revision_id)
2673
testament = _mod_testament.Testament.from_revision(self, revision_id)
2674
plaintext = testament.as_short_text()
2676
return gpg_strategy.verify(signature, plaintext)
1723
2678
def item_keys_introduced_by(self, revision_ids, _files_pb=None):
1724
2679
self._ensure_real()
1725
2680
return self._real_repository.item_keys_introduced_by(revision_ids,
1726
2681
_files_pb=_files_pb)
1728
def revision_graph_can_have_wrong_parents(self):
1729
# The answer depends on the remote repo format.
1731
return self._real_repository.revision_graph_can_have_wrong_parents()
1733
2683
def _find_inconsistent_revision_parents(self, revisions_iterator=None):
1734
2684
self._ensure_real()
1735
2685
return self._real_repository._find_inconsistent_revision_parents(
2083
3043
if isinstance(a_bzrdir, RemoteBzrDir):
2084
3044
a_bzrdir._ensure_real()
2085
3045
result = self._custom_format.initialize(a_bzrdir._real_bzrdir,
3046
name, append_revisions_only=append_revisions_only)
2088
3048
# We assume the bzrdir is parameterised; it may not be.
2089
result = self._custom_format.initialize(a_bzrdir, name)
3049
result = self._custom_format.initialize(a_bzrdir, name,
3050
append_revisions_only=append_revisions_only)
2090
3051
if (isinstance(a_bzrdir, RemoteBzrDir) and
2091
3052
not isinstance(result, RemoteBranch)):
2092
3053
result = RemoteBranch(a_bzrdir, a_bzrdir.find_repository(), result,
2096
def initialize(self, a_bzrdir, name=None):
3057
def initialize(self, a_bzrdir, name=None, repository=None,
3058
append_revisions_only=None):
2097
3059
# 1) get the network name to use.
2098
3060
if self._custom_format:
2099
3061
network_name = self._custom_format.network_name()
2101
3063
# Select the current bzrlib default and ask for that.
2102
reference_bzrdir_format = bzrdir.format_registry.get('default')()
3064
reference_bzrdir_format = _mod_bzrdir.format_registry.get('default')()
2103
3065
reference_format = reference_bzrdir_format.get_branch_format()
2104
3066
self._custom_format = reference_format
2105
3067
network_name = reference_format.network_name()
2106
3068
# Being asked to create on a non RemoteBzrDir:
2107
3069
if not isinstance(a_bzrdir, RemoteBzrDir):
2108
return self._vfs_initialize(a_bzrdir, name=name)
3070
return self._vfs_initialize(a_bzrdir, name=name,
3071
append_revisions_only=append_revisions_only)
2109
3072
medium = a_bzrdir._client._medium
2110
3073
if medium._is_remote_before((1, 13)):
2111
return self._vfs_initialize(a_bzrdir, name=name)
3074
return self._vfs_initialize(a_bzrdir, name=name,
3075
append_revisions_only=append_revisions_only)
2112
3076
# Creating on a remote bzr dir.
2113
3077
# 2) try direct creation via RPC
2114
3078
path = a_bzrdir._path_for_remote_call(a_bzrdir._client)
2160
3139
self._ensure_real()
2161
3140
return self._custom_format.supports_set_append_revisions_only()
3142
def _use_default_local_heads_to_fetch(self):
3143
# If the branch format is a metadir format *and* its heads_to_fetch
3144
# implementation is not overridden vs the base class, we can use the
3145
# base class logic rather than use the heads_to_fetch RPC. This is
3146
# usually cheaper in terms of net round trips, as the last-revision and
3147
# tags info fetched is cached and would be fetched anyway.
3149
if isinstance(self._custom_format, branch.BranchFormatMetadir):
3150
branch_class = self._custom_format._branch_class()
3151
heads_to_fetch_impl = branch_class.heads_to_fetch.im_func
3152
if heads_to_fetch_impl is branch.Branch.heads_to_fetch.im_func:
3157
class RemoteBranchStore(config.IniFileStore):
3158
"""Branch store which attempts to use HPSS calls to retrieve branch store.
3160
Note that this is specific to bzr-based formats.
3163
def __init__(self, branch):
3164
super(RemoteBranchStore, self).__init__()
3165
self.branch = branch
3167
self._real_store = None
3169
def lock_write(self, token=None):
3170
return self.branch.lock_write(token)
3173
return self.branch.unlock()
3177
# We need to be able to override the undecorated implementation
3178
self.save_without_locking()
3180
def save_without_locking(self):
3181
super(RemoteBranchStore, self).save()
3183
def external_url(self):
3184
return self.branch.user_url
3186
def _load_content(self):
3187
path = self.branch._remote_path()
3189
response, handler = self.branch._call_expecting_body(
3190
'Branch.get_config_file', path)
3191
except errors.UnknownSmartMethod:
3193
return self._real_store._load_content()
3194
if len(response) and response[0] != 'ok':
3195
raise errors.UnexpectedSmartServerResponse(response)
3196
return handler.read_body_bytes()
3198
def _save_content(self, content):
3199
path = self.branch._remote_path()
3201
response, handler = self.branch._call_with_body_bytes_expecting_body(
3202
'Branch.put_config_file', (path,
3203
self.branch._lock_token, self.branch._repo_lock_token),
3205
except errors.UnknownSmartMethod:
3207
return self._real_store._save_content(content)
3208
handler.cancel_read_body()
3209
if response != ('ok', ):
3210
raise errors.UnexpectedSmartServerResponse(response)
3212
def _ensure_real(self):
3213
self.branch._ensure_real()
3214
if self._real_store is None:
3215
self._real_store = config.BranchStore(self.branch)
2164
3218
class RemoteBranch(branch.Branch, _RpcHelper, lock._RelockDebugMixin):
2165
3219
"""Branch stored on a server accessed by HPSS RPC.
2678
3764
_override_hook_target=self, **kwargs)
2680
3766
@needs_read_lock
2681
def push(self, target, overwrite=False, stop_revision=None):
3767
def push(self, target, overwrite=False, stop_revision=None, lossy=False):
2682
3768
self._ensure_real()
2683
3769
return self._real_branch.push(
2684
target, overwrite=overwrite, stop_revision=stop_revision,
3770
target, overwrite=overwrite, stop_revision=stop_revision, lossy=lossy,
2685
3771
_override_hook_source_branch=self)
2687
3773
def is_locked(self):
2688
3774
return self._lock_count >= 1
2690
3776
@needs_read_lock
3777
def revision_id_to_dotted_revno(self, revision_id):
3778
"""Given a revision id, return its dotted revno.
3780
:return: a tuple like (1,) or (400,1,3).
3783
response = self._call('Branch.revision_id_to_revno',
3784
self._remote_path(), revision_id)
3785
except errors.UnknownSmartMethod:
3787
return self._real_branch.revision_id_to_dotted_revno(revision_id)
3788
if response[0] == 'ok':
3789
return tuple([int(x) for x in response[1:]])
3791
raise errors.UnexpectedSmartServerResponse(response)
2691
3794
def revision_id_to_revno(self, revision_id):
2693
return self._real_branch.revision_id_to_revno(revision_id)
3795
"""Given a revision id on the branch mainline, return its revno.
3800
response = self._call('Branch.revision_id_to_revno',
3801
self._remote_path(), revision_id)
3802
except errors.UnknownSmartMethod:
3804
return self._real_branch.revision_id_to_revno(revision_id)
3805
if response[0] == 'ok':
3806
if len(response) == 2:
3807
return int(response[1])
3808
raise NoSuchRevision(self, revision_id)
3810
raise errors.UnexpectedSmartServerResponse(response)
2695
3812
@needs_write_lock
2696
3813
def set_last_revision_info(self, revno, revision_id):
2697
3814
# XXX: These should be returned by the set_last_revision_info verb
2698
3815
old_revno, old_revid = self.last_revision_info()
2699
3816
self._run_pre_change_branch_tip_hooks(revno, revision_id)
2700
revision_id = ensure_null(revision_id)
3817
if not revision_id or not isinstance(revision_id, basestring):
3818
raise errors.InvalidRevisionId(revision_id=revision_id, branch=self)
2702
3820
response = self._call('Branch.set_last_revision_info',
2703
3821
self._remote_path(), self._lock_token, self._repo_lock_token,
2931
4089
'Missing key %r in context %r', key_err.args[0], context)
2934
if err.error_verb == 'IncompatibleRepositories':
2935
raise errors.IncompatibleRepositories(err.error_args[0],
2936
err.error_args[1], err.error_args[2])
2937
elif err.error_verb == 'NoSuchRevision':
2938
raise NoSuchRevision(find('branch'), err.error_args[0])
2939
elif err.error_verb == 'nosuchrevision':
2940
raise NoSuchRevision(find('repository'), err.error_args[0])
2941
elif err.error_verb == 'nobranch':
2942
if len(err.error_args) >= 1:
2943
extra = err.error_args[0]
2946
raise errors.NotBranchError(path=find('bzrdir').root_transport.base,
2948
elif err.error_verb == 'norepository':
2949
raise errors.NoRepositoryPresent(find('bzrdir'))
2950
elif err.error_verb == 'LockContention':
2951
raise errors.LockContention('(remote lock)')
2952
elif err.error_verb == 'UnlockableTransport':
2953
raise errors.UnlockableTransport(find('bzrdir').root_transport)
2954
elif err.error_verb == 'LockFailed':
2955
raise errors.LockFailed(err.error_args[0], err.error_args[1])
2956
elif err.error_verb == 'TokenMismatch':
2957
raise errors.TokenMismatch(find('token'), '(remote token)')
2958
elif err.error_verb == 'Diverged':
2959
raise errors.DivergedBranches(find('branch'), find('other_branch'))
2960
elif err.error_verb == 'TipChangeRejected':
2961
raise errors.TipChangeRejected(err.error_args[0].decode('utf8'))
2962
elif err.error_verb == 'UnstackableBranchFormat':
2963
raise errors.UnstackableBranchFormat(*err.error_args)
2964
elif err.error_verb == 'UnstackableRepositoryFormat':
2965
raise errors.UnstackableRepositoryFormat(*err.error_args)
2966
elif err.error_verb == 'NotStacked':
2967
raise errors.NotStacked(branch=find('branch'))
2968
elif err.error_verb == 'PermissionDenied':
2970
if len(err.error_args) >= 2:
2971
extra = err.error_args[1]
2974
raise errors.PermissionDenied(path, extra=extra)
2975
elif err.error_verb == 'ReadError':
2977
raise errors.ReadError(path)
2978
elif err.error_verb == 'NoSuchFile':
2980
raise errors.NoSuchFile(path)
2981
elif err.error_verb == 'FileExists':
2982
raise errors.FileExists(err.error_args[0])
2983
elif err.error_verb == 'DirectoryNotEmpty':
2984
raise errors.DirectoryNotEmpty(err.error_args[0])
2985
elif err.error_verb == 'ShortReadvError':
2986
args = err.error_args
2987
raise errors.ShortReadvError(
2988
args[0], int(args[1]), int(args[2]), int(args[3]))
2989
elif err.error_verb in ('UnicodeEncodeError', 'UnicodeDecodeError'):
4093
translator = error_translators.get(err.error_verb)
4097
raise translator(err, find, get_path)
4099
translator = no_context_error_translators.get(err.error_verb)
4101
raise errors.UnknownErrorFromSmartServer(err)
4103
raise translator(err)
4106
error_translators.register('NoSuchRevision',
4107
lambda err, find, get_path: NoSuchRevision(
4108
find('branch'), err.error_args[0]))
4109
error_translators.register('nosuchrevision',
4110
lambda err, find, get_path: NoSuchRevision(
4111
find('repository'), err.error_args[0]))
4113
def _translate_nobranch_error(err, find, get_path):
4114
if len(err.error_args) >= 1:
4115
extra = err.error_args[0]
4118
return errors.NotBranchError(path=find('bzrdir').root_transport.base,
4121
error_translators.register('nobranch', _translate_nobranch_error)
4122
error_translators.register('norepository',
4123
lambda err, find, get_path: errors.NoRepositoryPresent(
4125
error_translators.register('UnlockableTransport',
4126
lambda err, find, get_path: errors.UnlockableTransport(
4127
find('bzrdir').root_transport))
4128
error_translators.register('TokenMismatch',
4129
lambda err, find, get_path: errors.TokenMismatch(
4130
find('token'), '(remote token)'))
4131
error_translators.register('Diverged',
4132
lambda err, find, get_path: errors.DivergedBranches(
4133
find('branch'), find('other_branch')))
4134
error_translators.register('NotStacked',
4135
lambda err, find, get_path: errors.NotStacked(branch=find('branch')))
4137
def _translate_PermissionDenied(err, find, get_path):
4139
if len(err.error_args) >= 2:
4140
extra = err.error_args[1]
4143
return errors.PermissionDenied(path, extra=extra)
4145
error_translators.register('PermissionDenied', _translate_PermissionDenied)
4146
error_translators.register('ReadError',
4147
lambda err, find, get_path: errors.ReadError(get_path()))
4148
error_translators.register('NoSuchFile',
4149
lambda err, find, get_path: errors.NoSuchFile(get_path()))
4150
error_translators.register('TokenLockingNotSupported',
4151
lambda err, find, get_path: errors.TokenLockingNotSupported(
4152
find('repository')))
4153
error_translators.register('UnsuspendableWriteGroup',
4154
lambda err, find, get_path: errors.UnsuspendableWriteGroup(
4155
repository=find('repository')))
4156
error_translators.register('UnresumableWriteGroup',
4157
lambda err, find, get_path: errors.UnresumableWriteGroup(
4158
repository=find('repository'), write_groups=err.error_args[0],
4159
reason=err.error_args[1]))
4160
no_context_error_translators.register('IncompatibleRepositories',
4161
lambda err: errors.IncompatibleRepositories(
4162
err.error_args[0], err.error_args[1], err.error_args[2]))
4163
no_context_error_translators.register('LockContention',
4164
lambda err: errors.LockContention('(remote lock)'))
4165
no_context_error_translators.register('LockFailed',
4166
lambda err: errors.LockFailed(err.error_args[0], err.error_args[1]))
4167
no_context_error_translators.register('TipChangeRejected',
4168
lambda err: errors.TipChangeRejected(err.error_args[0].decode('utf8')))
4169
no_context_error_translators.register('UnstackableBranchFormat',
4170
lambda err: errors.UnstackableBranchFormat(*err.error_args))
4171
no_context_error_translators.register('UnstackableRepositoryFormat',
4172
lambda err: errors.UnstackableRepositoryFormat(*err.error_args))
4173
no_context_error_translators.register('FileExists',
4174
lambda err: errors.FileExists(err.error_args[0]))
4175
no_context_error_translators.register('DirectoryNotEmpty',
4176
lambda err: errors.DirectoryNotEmpty(err.error_args[0]))
4178
def _translate_short_readv_error(err):
4179
args = err.error_args
4180
return errors.ShortReadvError(args[0], int(args[1]), int(args[2]),
4183
no_context_error_translators.register('ShortReadvError',
4184
_translate_short_readv_error)
4186
def _translate_unicode_error(err):
2990
4187
encoding = str(err.error_args[0]) # encoding must always be a string
2991
4188
val = err.error_args[1]
2992
4189
start = int(err.error_args[2])