276
279
annotated_kind = ''
277
280
self.storage_kind = 'knit-%s%s-gz' % (annotated_kind, kind)
278
281
self._raw_record = raw_record
279
self._network_bytes = network_bytes
280
282
self._build_details = build_details
281
283
self._knit = knit
283
def _create_network_bytes(self):
284
"""Create a fully serialised network version for transmission."""
285
# storage_kind, key, parents, Noeol, raw_record
286
key_bytes = '\x00'.join(self.key)
287
if self.parents is None:
288
parent_bytes = 'None:'
290
parent_bytes = '\t'.join('\x00'.join(key) for key in self.parents)
291
if self._build_details[1]:
295
network_bytes = "%s\n%s\n%s\n%s%s" % (self.storage_kind, key_bytes,
296
parent_bytes, noeol, self._raw_record)
297
self._network_bytes = network_bytes
299
def get_bytes_as(self, storage_kind):
300
if storage_kind == self.storage_kind:
301
if self._network_bytes is None:
302
self._create_network_bytes()
303
return self._network_bytes
304
if ('-ft-' in self.storage_kind and
305
storage_kind in ('chunked', 'fulltext')):
306
adapter_key = (self.storage_kind, 'fulltext')
307
adapter_factory = adapter_registry.get(adapter_key)
308
adapter = adapter_factory(None)
309
bytes = adapter.get_bytes(self)
310
if storage_kind == 'chunked':
314
if self._knit is not None:
315
# Not redundant with direct conversion above - that only handles
317
if storage_kind == 'chunked':
318
return self._knit.get_lines(self.key[0])
319
elif storage_kind == 'fulltext':
320
return self._knit.get_text(self.key[0])
321
raise errors.UnavailableRepresentation(self.key, storage_kind,
325
class LazyKnitContentFactory(ContentFactory):
326
"""A ContentFactory which can either generate full text or a wire form.
328
:seealso ContentFactory:
331
def __init__(self, key, parents, generator, first):
332
"""Create a LazyKnitContentFactory.
334
:param key: The key of the record.
335
:param parents: The parents of the record.
336
:param generator: A _ContentMapGenerator containing the record for this
338
:param first: Is this the first content object returned from generator?
339
if it is, its storage kind is knit-delta-closure, otherwise it is
340
knit-delta-closure-ref
343
self.parents = parents
345
self._generator = generator
346
self.storage_kind = "knit-delta-closure"
348
self.storage_kind = self.storage_kind + "-ref"
351
def get_bytes_as(self, storage_kind):
352
if storage_kind == self.storage_kind:
354
return self._generator._wire_bytes()
356
# all the keys etc are contained in the bytes returned in the
359
if storage_kind in ('chunked', 'fulltext'):
360
chunks = self._generator._get_one_work(self.key).text()
361
if storage_kind == 'chunked':
364
return ''.join(chunks)
365
raise errors.UnavailableRepresentation(self.key, storage_kind,
369
def knit_delta_closure_to_records(storage_kind, bytes, line_end):
370
"""Convert a network record to a iterator over stream records.
372
:param storage_kind: The storage kind of the record.
373
Must be 'knit-delta-closure'.
374
:param bytes: The bytes of the record on the network.
376
generator = _NetworkContentMapGenerator(bytes, line_end)
377
return generator.get_record_stream()
380
def knit_network_to_record(storage_kind, bytes, line_end):
381
"""Convert a network record to a record object.
383
:param storage_kind: The storage kind of the record.
384
:param bytes: The bytes of the record on the network.
387
line_end = bytes.find('\n', start)
388
key = tuple(bytes[start:line_end].split('\x00'))
390
line_end = bytes.find('\n', start)
391
parent_line = bytes[start:line_end]
392
if parent_line == 'None:':
396
[tuple(segment.split('\x00')) for segment in parent_line.split('\t')
399
noeol = bytes[start] == 'N'
400
if 'ft' in storage_kind:
403
method = 'line-delta'
404
build_details = (method, noeol)
406
raw_record = bytes[start:]
407
annotated = 'annotated' in storage_kind
408
return [KnitContentFactory(key, parents, build_details, None, raw_record,
409
annotated, network_bytes=bytes)]
285
def get_bytes_as(self, storage_kind):
286
if storage_kind == self.storage_kind:
287
return self._raw_record
288
if storage_kind == 'fulltext' and self._knit is not None:
289
return self._knit.get_text(self.key[0])
291
raise errors.UnavailableRepresentation(self.key, storage_kind,
412
295
class KnitContent(object):
413
296
"""Content of a knit version to which deltas can be applied.
415
298
This is always stored in memory as a list of lines with \n at the end,
416
plus a flag saying if the final ending is really there or not, because that
299
plus a flag saying if the final ending is really there or not, because that
417
300
corresponds to the on-disk knit representation.
1189
958
if not self.get_parent_map([key]):
1190
959
raise RevisionNotPresent(key, self)
1191
960
return cached_version
1192
generator = _VFContentMapGenerator(self, [key])
1193
return generator._get_content(key)
1195
def get_known_graph_ancestry(self, keys):
1196
"""Get a KnownGraph instance with the ancestry of keys."""
1197
parent_map, missing_keys = self._index.find_ancestry(keys)
1198
for fallback in self._fallback_vfs:
1199
if not missing_keys:
1201
(f_parent_map, f_missing_keys) = fallback._index.find_ancestry(
1203
parent_map.update(f_parent_map)
1204
missing_keys = f_missing_keys
1205
kg = _mod_graph.KnownGraph(parent_map)
961
text_map, contents_map = self._get_content_maps([key])
962
return contents_map[key]
964
def _get_content_maps(self, keys):
965
"""Produce maps of text and KnitContents
967
:return: (text_map, content_map) where text_map contains the texts for
968
the requested versions and content_map contains the KnitContents.
970
# FUTURE: This function could be improved for the 'extract many' case
971
# by tracking each component and only doing the copy when the number of
972
# children than need to apply delta's to it is > 1 or it is part of the
975
multiple_versions = len(keys) != 1
976
record_map = self._get_record_map(keys)
984
while cursor is not None:
985
record, record_details, digest, next = record_map[cursor]
986
components.append((cursor, record, record_details, digest))
987
if cursor in content_map:
992
for (component_id, record, record_details,
993
digest) in reversed(components):
994
if component_id in content_map:
995
content = content_map[component_id]
997
content, delta = self._factory.parse_record(key[-1],
998
record, record_details, content,
999
copy_base_content=multiple_versions)
1000
if multiple_versions:
1001
content_map[component_id] = content
1003
final_content[key] = content
1005
# digest here is the digest from the last applied component.
1006
text = content.text()
1007
actual_sha = sha_strings(text)
1008
if actual_sha != digest:
1009
raise KnitCorrupt(self,
1011
'\n of reconstructed text does not match'
1013
'\n for version %s' %
1014
(actual_sha, digest, key))
1015
text_map[key] = text
1016
return text_map, final_content
1208
1018
def get_parent_map(self, keys):
1209
"""Get a map of the graph parents of keys.
1019
"""Get a map of the parents of keys.
1211
1021
:param keys: The keys to look up parents for.
1212
1022
:return: A mapping from keys to parents. Absent keys are absent from
1215
return self._get_parent_map_with_sources(keys)[0]
1217
def _get_parent_map_with_sources(self, keys):
1218
"""Get a map of the parents of keys.
1220
:param keys: The keys to look up parents for.
1221
:return: A tuple. The first element is a mapping from keys to parents.
1222
Absent keys are absent from the mapping. The second element is a
1223
list with the locations each key was found in. The first element
1224
is the in-this-knit parents, the second the first fallback source,
1228
sources = [self._index] + self._fallback_vfs
1231
for source in sources:
1234
new_result = source.get_parent_map(missing)
1235
source_results.append(new_result)
1236
result.update(new_result)
1237
missing.difference_update(set(new_result))
1238
return result, source_results
1240
def _get_record_map(self, keys, allow_missing=False):
1025
return self._index.get_parent_map(keys)
1027
def _get_record_map(self, keys):
1241
1028
"""Produce a dictionary of knit records.
1243
1030
:return: {key:(record, record_details, digest, next)}
1245
data returned from read_records (a KnitContentobject)
1032
data returned from read_records
1247
1034
opaque information to pass to parse_record
1251
1038
build-parent of the version, i.e. the leftmost ancestor.
1252
1039
Will be None if the record is not a delta.
1253
:param keys: The keys to build a map for
1254
:param allow_missing: If some records are missing, rather than
1255
error, just return the data that could be generated.
1257
raw_map = self._get_record_map_unparsed(keys,
1258
allow_missing=allow_missing)
1259
return self._raw_map_to_record_map(raw_map)
1261
def _raw_map_to_record_map(self, raw_map):
1262
"""Parse the contents of _get_record_map_unparsed.
1264
:return: see _get_record_map.
1268
data, record_details, next = raw_map[key]
1269
content, digest = self._parse_record(key[-1], data)
1270
result[key] = content, record_details, digest, next
1273
def _get_record_map_unparsed(self, keys, allow_missing=False):
1274
"""Get the raw data for reconstructing keys without parsing it.
1276
:return: A dict suitable for parsing via _raw_map_to_record_map.
1277
key-> raw_bytes, (method, noeol), compression_parent
1279
# This retries the whole request if anything fails. Potentially we
1280
# could be a bit more selective. We could track the keys whose records
1281
# we have successfully found, and then only request the new records
1282
# from there. However, _get_components_positions grabs the whole build
1283
# chain, which means we'll likely try to grab the same records again
1284
# anyway. Also, can the build chains change as part of a pack
1285
# operation? We wouldn't want to end up with a broken chain.
1288
position_map = self._get_components_positions(keys,
1289
allow_missing=allow_missing)
1290
# key = component_id, r = record_details, i_m = index_memo,
1292
records = [(key, i_m) for key, (r, i_m, n)
1293
in position_map.iteritems()]
1294
# Sort by the index memo, so that we request records from the
1295
# same pack file together, and in forward-sorted order
1296
records.sort(key=operator.itemgetter(1))
1298
for key, data in self._read_records_iter_unchecked(records):
1299
(record_details, index_memo, next) = position_map[key]
1300
raw_record_map[key] = data, record_details, next
1301
return raw_record_map
1302
except errors.RetryWithNewPacks, e:
1303
self._access.reload_or_raise(e)
1306
def _split_by_prefix(cls, keys):
1307
"""For the given keys, split them up based on their prefix.
1309
To keep memory pressure somewhat under control, split the
1310
requests back into per-file-id requests, otherwise "bzr co"
1311
extracts the full tree into memory before writing it to disk.
1312
This should be revisited if _get_content_maps() can ever cross
1315
The keys for a given file_id are kept in the same relative order.
1316
Ordering between file_ids is not, though prefix_order will return the
1317
order that the key was first seen.
1319
:param keys: An iterable of key tuples
1320
:return: (split_map, prefix_order)
1321
split_map A dictionary mapping prefix => keys
1322
prefix_order The order that we saw the various prefixes
1324
split_by_prefix = {}
1332
if prefix in split_by_prefix:
1333
split_by_prefix[prefix].append(key)
1335
split_by_prefix[prefix] = [key]
1336
prefix_order.append(prefix)
1337
return split_by_prefix, prefix_order
1339
def _group_keys_for_io(self, keys, non_local_keys, positions,
1340
_min_buffer_size=_STREAM_MIN_BUFFER_SIZE):
1341
"""For the given keys, group them into 'best-sized' requests.
1343
The idea is to avoid making 1 request per file, but to never try to
1344
unpack an entire 1.5GB source tree in a single pass. Also when
1345
possible, we should try to group requests to the same pack file
1348
:return: list of (keys, non_local) tuples that indicate what keys
1349
should be fetched next.
1351
# TODO: Ideally we would group on 2 factors. We want to extract texts
1352
# from the same pack file together, and we want to extract all
1353
# the texts for a given build-chain together. Ultimately it
1354
# probably needs a better global view.
1355
total_keys = len(keys)
1356
prefix_split_keys, prefix_order = self._split_by_prefix(keys)
1357
prefix_split_non_local_keys, _ = self._split_by_prefix(non_local_keys)
1359
cur_non_local = set()
1363
for prefix in prefix_order:
1364
keys = prefix_split_keys[prefix]
1365
non_local = prefix_split_non_local_keys.get(prefix, [])
1367
this_size = self._index._get_total_build_size(keys, positions)
1368
cur_size += this_size
1369
cur_keys.extend(keys)
1370
cur_non_local.update(non_local)
1371
if cur_size > _min_buffer_size:
1372
result.append((cur_keys, cur_non_local))
1373
sizes.append(cur_size)
1375
cur_non_local = set()
1378
result.append((cur_keys, cur_non_local))
1379
sizes.append(cur_size)
1041
position_map = self._get_components_positions(keys)
1042
# key = component_id, r = record_details, i_m = index_memo, n = next
1043
records = [(key, i_m) for key, (r, i_m, n)
1044
in position_map.iteritems()]
1046
for key, record, digest in \
1047
self._read_records_iter(records):
1048
(record_details, index_memo, next) = position_map[key]
1049
record_map[key] = record, record_details, digest, next
1382
1052
def get_record_stream(self, keys, ordering, include_delta_closure):
1383
1053
"""Get a stream of records for keys.
1449
1098
chain.append(positions[chain[-1]][2])
1450
1099
except KeyError:
1451
1100
# missing basis component
1452
needed_from_fallback.add(chain[-1])
1455
1103
for chain_key in chain[:-1]:
1456
1104
reconstructable_keys[chain_key] = result
1458
needed_from_fallback.add(key)
1459
# Double index lookups here : need a unified api ?
1460
global_map, parent_maps = self._get_parent_map_with_sources(keys)
1461
if ordering in ('topological', 'groupcompress'):
1462
if ordering == 'topological':
1463
# Global topological sort
1464
present_keys = tsort.topo_sort(global_map)
1466
present_keys = sort_groupcompress(global_map)
1467
# Now group by source:
1469
current_source = None
1470
for key in present_keys:
1471
for parent_map in parent_maps:
1472
if key in parent_map:
1473
key_source = parent_map
1475
if current_source is not key_source:
1476
source_keys.append((key_source, []))
1477
current_source = key_source
1478
source_keys[-1][1].append(key)
1480
if ordering != 'unordered':
1481
raise AssertionError('valid values for ordering are:'
1482
' "unordered", "groupcompress" or "topological" not: %r'
1484
# Just group by source; remote sources first.
1487
for parent_map in reversed(parent_maps):
1488
source_keys.append((parent_map, []))
1489
for key in parent_map:
1490
present_keys.append(key)
1491
source_keys[-1][1].append(key)
1492
# We have been requested to return these records in an order that
1493
# suits us. So we ask the index to give us an optimally sorted
1495
for source, sub_keys in source_keys:
1496
if source is parent_maps[0]:
1497
# Only sort the keys for this VF
1498
self._index._sort_keys_by_io(sub_keys, positions)
1499
absent_keys = keys - set(global_map)
1106
absent_keys.add(key)
1500
1107
for key in absent_keys:
1501
1108
yield AbsentContentFactory(key)
1502
1109
# restrict our view to the keys we can answer.
1110
keys = keys - absent_keys
1111
# Double index lookups here : need a unified api ?
1112
parent_map = self.get_parent_map(keys)
1113
if ordering == 'topological':
1114
present_keys = topo_sort(parent_map)
1503
1117
# XXX: Memory: TODO: batch data here to cap buffered data at (say) 1MB.
1504
# XXX: At that point we need to consider the impact of double reads by
1505
# utilising components multiple times.
1118
# XXX: At that point we need to consider double reads by utilising
1119
# components multiple times.
1506
1120
if include_delta_closure:
1507
1121
# XXX: get_content_maps performs its own index queries; allow state
1508
1122
# to be passed in.
1509
non_local_keys = needed_from_fallback - absent_keys
1510
for keys, non_local_keys in self._group_keys_for_io(present_keys,
1513
generator = _VFContentMapGenerator(self, keys, non_local_keys,
1516
for record in generator.get_record_stream():
1123
text_map, _ = self._get_content_maps(present_keys)
1124
for key in present_keys:
1125
yield FulltextContentFactory(key, parent_map[key], None,
1126
''.join(text_map[key]))
1519
for source, keys in source_keys:
1520
if source is parent_maps[0]:
1521
# this KnitVersionedFiles
1522
records = [(key, positions[key][1]) for key in keys]
1523
for key, raw_data in self._read_records_iter_unchecked(records):
1524
(record_details, index_memo, _) = positions[key]
1525
yield KnitContentFactory(key, global_map[key],
1526
record_details, None, raw_data, self._factory.annotated, None)
1528
vf = self._fallback_vfs[parent_maps.index(source) - 1]
1529
for record in vf.get_record_stream(keys, ordering,
1530
include_delta_closure):
1128
records = [(key, positions[key][1]) for key in present_keys]
1129
for key, raw_data, sha1 in self._read_records_iter_raw(records):
1130
(record_details, index_memo, _) = positions[key]
1131
yield KnitContentFactory(key, parent_map[key],
1132
record_details, sha1, raw_data, self._factory.annotated, None)
1533
1134
def get_sha1s(self, keys):
1534
1135
"""See VersionedFiles.get_sha1s()."""
1536
record_map = self._get_record_map(missing, allow_missing=True)
1538
for key, details in record_map.iteritems():
1539
if key not in missing:
1541
# record entry 2 is the 'digest'.
1542
result[key] = details[2]
1543
missing.difference_update(set(result))
1544
for source in self._fallback_vfs:
1547
new_result = source.get_sha1s(missing)
1548
result.update(new_result)
1549
missing.difference_update(set(new_result))
1136
record_map = self._get_record_map(keys)
1137
# record entry 2 is the 'digest'.
1138
return [record_map[key][2] for key in keys]
1552
1140
def insert_record_stream(self, stream):
1553
1141
"""Insert a record stream into this container.
1555
:param stream: A stream of records to insert.
1143
:param stream: A stream of records to insert.
1557
1145
:seealso VersionedFiles.get_record_stream:
1657
1208
access_memo = self._access.add_raw_records(
1658
1209
[(record.key, len(bytes))], bytes)[0]
1659
1210
index_entry = (record.key, options, access_memo, parents)
1660
1212
if 'fulltext' not in options:
1661
# Not a fulltext, so we need to make sure the compression
1662
# parent will also be present.
1213
basis_parent = parents[0]
1663
1214
# Note that pack backed knits don't need to buffer here
1664
1215
# because they buffer all writes to the transaction level,
1665
1216
# but we don't expose that difference at the index level. If
1666
1217
# the query here has sufficient cost to show up in
1667
1218
# profiling we should do that.
1669
# They're required to be physically in this
1670
# KnitVersionedFiles, not in a fallback.
1671
if not self._index.has_key(compression_parent):
1219
if basis_parent not in self.get_parent_map([basis_parent]):
1672
1220
pending = buffered_index_entries.setdefault(
1673
compression_parent, [])
1674
1222
pending.append(index_entry)
1675
1223
buffered = True
1676
1224
if not buffered:
1677
1225
self._index.add_records([index_entry])
1678
elif record.storage_kind == 'chunked':
1226
elif record.storage_kind == 'fulltext':
1679
1227
self.add_lines(record.key, parents,
1680
osutils.chunks_to_lines(record.get_bytes_as('chunked')))
1228
split_lines(record.get_bytes_as('fulltext')))
1682
# Not suitable for direct insertion as a
1683
# delta, either because it's not the right format, or this
1684
# KnitVersionedFiles doesn't permit deltas (_max_delta_chain ==
1685
# 0) or because it depends on a base only present in the
1687
self._access.flush()
1689
# Try getting a fulltext directly from the record.
1690
bytes = record.get_bytes_as('fulltext')
1691
except errors.UnavailableRepresentation:
1692
adapter_key = record.storage_kind, 'fulltext'
1693
adapter = get_adapter(adapter_key)
1694
bytes = adapter.get_bytes(record)
1695
lines = split_lines(bytes)
1230
adapter_key = record.storage_kind, 'fulltext'
1231
adapter = get_adapter(adapter_key)
1232
lines = split_lines(adapter.get_bytes(
1233
record, record.get_bytes_as(record.storage_kind)))
1697
1235
self.add_lines(record.key, parents, lines)
1698
1236
except errors.RevisionAlreadyPresent:
1700
1238
# Add any records whose basis parent is now available.
1702
added_keys = [record.key]
1704
key = added_keys.pop(0)
1705
if key in buffered_index_entries:
1706
index_entries = buffered_index_entries[key]
1707
self._index.add_records(index_entries)
1709
[index_entry[0] for index_entry in index_entries])
1710
del buffered_index_entries[key]
1239
added_keys = [record.key]
1241
key = added_keys.pop(0)
1242
if key in buffered_index_entries:
1243
index_entries = buffered_index_entries[key]
1244
self._index.add_records(index_entries)
1246
[index_entry[0] for index_entry in index_entries])
1247
del buffered_index_entries[key]
1248
# If there were any deltas which had a missing basis parent, error.
1711
1249
if buffered_index_entries:
1712
# There were index entries buffered at the end of the stream,
1713
# So these need to be added (if the index supports holding such
1714
# entries for later insertion)
1716
for key in buffered_index_entries:
1717
index_entries = buffered_index_entries[key]
1718
all_entries.extend(index_entries)
1719
self._index.add_records(
1720
all_entries, missing_compression_parents=True)
1722
def get_missing_compression_parent_keys(self):
1723
"""Return an iterable of keys of missing compression parents.
1725
Check this after calling insert_record_stream to find out if there are
1726
any missing compression parents. If there are, the records that
1727
depend on them are not able to be inserted safely. For atomic
1728
KnitVersionedFiles built on packs, the transaction should be aborted or
1729
suspended - commit will fail at this point. Nonatomic knits will error
1730
earlier because they have no staging area to put pending entries into.
1732
return self._index.get_missing_compression_parents()
1250
raise errors.RevisionNotPresent(buffered_index_entries.keys()[0],
1734
1253
def iter_lines_added_or_present_in_keys(self, keys, pb=None):
1735
1254
"""Iterate over the lines in the versioned files from keys.
1746
1265
is an iterator).
1749
* Lines are normalised by the underlying store: they will all have \\n
1268
* Lines are normalised by the underlying store: they will all have \n
1751
1270
* Lines are returned in arbitrary order.
1752
* If a requested key did not change any lines (or didn't have any
1753
lines), it may not be mentioned at all in the result.
1755
:param pb: Progress bar supplied by caller.
1756
1272
:return: An iterator over (line, key).
1759
pb = ui.ui_factory.nested_progress_bar()
1275
pb = progress.DummyProgress()
1760
1276
keys = set(keys)
1765
# we don't care about inclusions, the caller cares.
1766
# but we need to setup a list of records to visit.
1767
# we need key, position, length
1769
build_details = self._index.get_build_details(keys)
1770
for key, details in build_details.iteritems():
1772
key_records.append((key, details[0]))
1773
records_iter = enumerate(self._read_records_iter(key_records))
1774
for (key_idx, (key, data, sha_value)) in records_iter:
1775
pb.update('Walking content', key_idx, total)
1776
compression_parent = build_details[key][1]
1777
if compression_parent is None:
1779
line_iterator = self._factory.get_fulltext_content(data)
1782
line_iterator = self._factory.get_linedelta_content(data)
1783
# Now that we are yielding the data for this key, remove it
1786
# XXX: It might be more efficient to yield (key,
1787
# line_iterator) in the future. However for now, this is a
1788
# simpler change to integrate into the rest of the
1789
# codebase. RBC 20071110
1790
for line in line_iterator:
1793
except errors.RetryWithNewPacks, e:
1794
self._access.reload_or_raise(e)
1795
# If there are still keys we've not yet found, we look in the fallback
1796
# vfs, and hope to find them there. Note that if the keys are found
1797
# but had no changes or no content, the fallback may not return
1799
if keys and not self._fallback_vfs:
1800
# XXX: strictly the second parameter is meant to be the file id
1801
# but it's not easily accessible here.
1802
raise RevisionNotPresent(keys, repr(self))
1803
for source in self._fallback_vfs:
1807
for line, key in source.iter_lines_added_or_present_in_keys(keys):
1808
source_keys.add(key)
1277
# filter for available keys
1278
parent_map = self.get_parent_map(keys)
1279
if len(parent_map) != len(keys):
1280
missing = set(parent_map) - requested_keys
1281
raise RevisionNotPresent(key, self.filename)
1282
# we don't care about inclusions, the caller cares.
1283
# but we need to setup a list of records to visit.
1284
# we need key, position, length
1286
build_details = self._index.get_build_details(keys)
1289
key_records.append((key, build_details[key][0]))
1290
total = len(key_records)
1291
records_iter = enumerate(self._read_records_iter(key_records))
1292
for (key_idx, (key, data, sha_value)) in records_iter:
1293
pb.update('Walking content.', key_idx, total)
1294
compression_parent = build_details[key][1]
1295
if compression_parent is None:
1297
line_iterator = self._factory.get_fulltext_content(data)
1300
line_iterator = self._factory.get_linedelta_content(data)
1301
# XXX: It might be more efficient to yield (key,
1302
# line_iterator) in the future. However for now, this is a simpler
1303
# change to integrate into the rest of the codebase. RBC 20071110
1304
for line in line_iterator:
1809
1305
yield line, key
1810
keys.difference_update(source_keys)
1811
pb.update('Walking content', total, total)
1306
pb.update('Walking content.', total, total)
1813
1308
def _make_line_delta(self, delta_seq, new_content):
1814
1309
"""Generate a line delta from delta_seq and new_content."""
2015
1504
"""See VersionedFiles.keys."""
2016
1505
if 'evil' in debug.debug_flags:
2017
1506
trace.mutter_callsite(2, "keys scales with size of history")
2018
sources = [self._index] + self._fallback_vfs
2020
for source in sources:
2021
result.update(source.keys())
2025
class _ContentMapGenerator(object):
2026
"""Generate texts or expose raw deltas for a set of texts."""
2028
def __init__(self, ordering='unordered'):
2029
self._ordering = ordering
2031
def _get_content(self, key):
2032
"""Get the content object for key."""
2033
# Note that _get_content is only called when the _ContentMapGenerator
2034
# has been constructed with just one key requested for reconstruction.
2035
if key in self.nonlocal_keys:
2036
record = self.get_record_stream().next()
2037
# Create a content object on the fly
2038
lines = osutils.chunks_to_lines(record.get_bytes_as('chunked'))
2039
return PlainKnitContent(lines, record.key)
2041
# local keys we can ask for directly
2042
return self._get_one_work(key)
2044
def get_record_stream(self):
2045
"""Get a record stream for the keys requested during __init__."""
2046
for record in self._work():
2050
"""Produce maps of text and KnitContents as dicts.
2052
:return: (text_map, content_map) where text_map contains the texts for
2053
the requested versions and content_map contains the KnitContents.
2055
# NB: By definition we never need to read remote sources unless texts
2056
# are requested from them: we don't delta across stores - and we
2057
# explicitly do not want to to prevent data loss situations.
2058
if self.global_map is None:
2059
self.global_map = self.vf.get_parent_map(self.keys)
2060
nonlocal_keys = self.nonlocal_keys
2062
missing_keys = set(nonlocal_keys)
2063
# Read from remote versioned file instances and provide to our caller.
2064
for source in self.vf._fallback_vfs:
2065
if not missing_keys:
2067
# Loop over fallback repositories asking them for texts - ignore
2068
# any missing from a particular fallback.
2069
for record in source.get_record_stream(missing_keys,
2070
self._ordering, True):
2071
if record.storage_kind == 'absent':
2072
# Not in thie particular stream, may be in one of the
2073
# other fallback vfs objects.
2075
missing_keys.remove(record.key)
2078
if self._raw_record_map is None:
2079
raise AssertionError('_raw_record_map should have been filled')
2081
for key in self.keys:
2082
if key in self.nonlocal_keys:
2084
yield LazyKnitContentFactory(key, self.global_map[key], self, first)
2087
def _get_one_work(self, requested_key):
2088
# Now, if we have calculated everything already, just return the
2090
if requested_key in self._contents_map:
2091
return self._contents_map[requested_key]
2092
# To simplify things, parse everything at once - code that wants one text
2093
# probably wants them all.
2094
# FUTURE: This function could be improved for the 'extract many' case
2095
# by tracking each component and only doing the copy when the number of
2096
# children than need to apply delta's to it is > 1 or it is part of the
2098
multiple_versions = len(self.keys) != 1
2099
if self._record_map is None:
2100
self._record_map = self.vf._raw_map_to_record_map(
2101
self._raw_record_map)
2102
record_map = self._record_map
2103
# raw_record_map is key:
2104
# Have read and parsed records at this point.
2105
for key in self.keys:
2106
if key in self.nonlocal_keys:
2111
while cursor is not None:
2113
record, record_details, digest, next = record_map[cursor]
2115
raise RevisionNotPresent(cursor, self)
2116
components.append((cursor, record, record_details, digest))
2118
if cursor in self._contents_map:
2119
# no need to plan further back
2120
components.append((cursor, None, None, None))
2124
for (component_id, record, record_details,
2125
digest) in reversed(components):
2126
if component_id in self._contents_map:
2127
content = self._contents_map[component_id]
2129
content, delta = self._factory.parse_record(key[-1],
2130
record, record_details, content,
2131
copy_base_content=multiple_versions)
2132
if multiple_versions:
2133
self._contents_map[component_id] = content
2135
# digest here is the digest from the last applied component.
2136
text = content.text()
2137
actual_sha = sha_strings(text)
2138
if actual_sha != digest:
2139
raise SHA1KnitCorrupt(self, actual_sha, digest, key, text)
2140
if multiple_versions:
2141
return self._contents_map[requested_key]
2145
def _wire_bytes(self):
2146
"""Get the bytes to put on the wire for 'key'.
2148
The first collection of bytes asked for returns the serialised
2149
raw_record_map and the additional details (key, parent) for key.
2150
Subsequent calls return just the additional details (key, parent).
2151
The wire storage_kind given for the first key is 'knit-delta-closure',
2152
For subsequent keys it is 'knit-delta-closure-ref'.
2154
:param key: A key from the content generator.
2155
:return: Bytes to put on the wire.
2158
# kind marker for dispatch on the far side,
2159
lines.append('knit-delta-closure')
2161
if self.vf._factory.annotated:
2162
lines.append('annotated')
2165
# then the list of keys
2166
lines.append('\t'.join(['\x00'.join(key) for key in self.keys
2167
if key not in self.nonlocal_keys]))
2168
# then the _raw_record_map in serialised form:
2170
# for each item in the map:
2172
# 1 line with parents if the key is to be yielded (None: for None, '' for ())
2173
# one line with method
2174
# one line with noeol
2175
# one line with next ('' for None)
2176
# one line with byte count of the record bytes
2178
for key, (record_bytes, (method, noeol), next) in \
2179
self._raw_record_map.iteritems():
2180
key_bytes = '\x00'.join(key)
2181
parents = self.global_map.get(key, None)
2183
parent_bytes = 'None:'
2185
parent_bytes = '\t'.join('\x00'.join(key) for key in parents)
2186
method_bytes = method
2192
next_bytes = '\x00'.join(next)
2195
map_byte_list.append('%s\n%s\n%s\n%s\n%s\n%d\n%s' % (
2196
key_bytes, parent_bytes, method_bytes, noeol_bytes, next_bytes,
2197
len(record_bytes), record_bytes))
2198
map_bytes = ''.join(map_byte_list)
2199
lines.append(map_bytes)
2200
bytes = '\n'.join(lines)
2204
class _VFContentMapGenerator(_ContentMapGenerator):
2205
"""Content map generator reading from a VersionedFiles object."""
2207
def __init__(self, versioned_files, keys, nonlocal_keys=None,
2208
global_map=None, raw_record_map=None, ordering='unordered'):
2209
"""Create a _ContentMapGenerator.
2211
:param versioned_files: The versioned files that the texts are being
2213
:param keys: The keys to produce content maps for.
2214
:param nonlocal_keys: An iterable of keys(possibly intersecting keys)
2215
which are known to not be in this knit, but rather in one of the
2217
:param global_map: The result of get_parent_map(keys) (or a supermap).
2218
This is required if get_record_stream() is to be used.
2219
:param raw_record_map: A unparsed raw record map to use for answering
2222
_ContentMapGenerator.__init__(self, ordering=ordering)
2223
# The vf to source data from
2224
self.vf = versioned_files
2226
self.keys = list(keys)
2227
# Keys known to be in fallback vfs objects
2228
if nonlocal_keys is None:
2229
self.nonlocal_keys = set()
2231
self.nonlocal_keys = frozenset(nonlocal_keys)
2232
# Parents data for keys to be returned in get_record_stream
2233
self.global_map = global_map
2234
# The chunked lists for self.keys in text form
2236
# A cache of KnitContent objects used in extracting texts.
2237
self._contents_map = {}
2238
# All the knit records needed to assemble the requested keys as full
2240
self._record_map = None
2241
if raw_record_map is None:
2242
self._raw_record_map = self.vf._get_record_map_unparsed(keys,
2245
self._raw_record_map = raw_record_map
2246
# the factory for parsing records
2247
self._factory = self.vf._factory
2250
class _NetworkContentMapGenerator(_ContentMapGenerator):
2251
"""Content map generator sourced from a network stream."""
2253
def __init__(self, bytes, line_end):
2254
"""Construct a _NetworkContentMapGenerator from a bytes block."""
2256
self.global_map = {}
2257
self._raw_record_map = {}
2258
self._contents_map = {}
2259
self._record_map = None
2260
self.nonlocal_keys = []
2261
# Get access to record parsing facilities
2262
self.vf = KnitVersionedFiles(None, None)
2265
line_end = bytes.find('\n', start)
2266
line = bytes[start:line_end]
2267
start = line_end + 1
2268
if line == 'annotated':
2269
self._factory = KnitAnnotateFactory()
2271
self._factory = KnitPlainFactory()
2272
# list of keys to emit in get_record_stream
2273
line_end = bytes.find('\n', start)
2274
line = bytes[start:line_end]
2275
start = line_end + 1
2277
tuple(segment.split('\x00')) for segment in line.split('\t')
2279
# now a loop until the end. XXX: It would be nice if this was just a
2280
# bunch of the same records as get_record_stream(..., False) gives, but
2281
# there is a decent sized gap stopping that at the moment.
2285
line_end = bytes.find('\n', start)
2286
key = tuple(bytes[start:line_end].split('\x00'))
2287
start = line_end + 1
2288
# 1 line with parents (None: for None, '' for ())
2289
line_end = bytes.find('\n', start)
2290
line = bytes[start:line_end]
2295
[tuple(segment.split('\x00')) for segment in line.split('\t')
2297
self.global_map[key] = parents
2298
start = line_end + 1
2299
# one line with method
2300
line_end = bytes.find('\n', start)
2301
line = bytes[start:line_end]
2303
start = line_end + 1
2304
# one line with noeol
2305
line_end = bytes.find('\n', start)
2306
line = bytes[start:line_end]
2308
start = line_end + 1
2309
# one line with next ('' for None)
2310
line_end = bytes.find('\n', start)
2311
line = bytes[start:line_end]
2315
next = tuple(bytes[start:line_end].split('\x00'))
2316
start = line_end + 1
2317
# one line with byte count of the record bytes
2318
line_end = bytes.find('\n', start)
2319
line = bytes[start:line_end]
2321
start = line_end + 1
2323
record_bytes = bytes[start:start+count]
2324
start = start + count
2326
self._raw_record_map[key] = (record_bytes, (method, noeol), next)
2328
def get_record_stream(self):
2329
"""Get a record stream for for keys requested by the bytestream."""
2331
for key in self.keys:
2332
yield LazyKnitContentFactory(key, self.global_map[key], self, first)
2335
def _wire_bytes(self):
1507
return self._index.keys()
2339
1510
class _KndxIndex(object):
2760
1877
self._mode = 'r'
2762
def _sort_keys_by_io(self, keys, positions):
2763
"""Figure out an optimal order to read the records for the given keys.
2765
Sort keys, grouped by index and sorted by position.
2767
:param keys: A list of keys whose records we want to read. This will be
2769
:param positions: A dict, such as the one returned by
2770
_get_components_positions()
2773
def get_sort_key(key):
2774
index_memo = positions[key][1]
2775
# Group by prefix and position. index_memo[0] is the key, so it is
2776
# (file_id, revision_id) and we don't want to sort on revision_id,
2777
# index_memo[1] is the position, and index_memo[2] is the size,
2778
# which doesn't matter for the sort
2779
return index_memo[0][:-1], index_memo[1]
2780
return keys.sort(key=get_sort_key)
2782
_get_total_build_size = _get_total_build_size
2784
1879
def _split_key(self, key):
2785
1880
"""Split key into a prefix and suffix."""
2786
1881
return key[:-1], key[-1]
2789
class _KeyRefs(object):
2791
def __init__(self, track_new_keys=False):
2792
# dict mapping 'key' to 'set of keys referring to that key'
2795
# set remembering all new keys
2796
self.new_keys = set()
2798
self.new_keys = None
2804
self.new_keys.clear()
2806
def add_references(self, key, refs):
2807
# Record the new references
2808
for referenced in refs:
2810
needed_by = self.refs[referenced]
2812
needed_by = self.refs[referenced] = set()
2814
# Discard references satisfied by the new key
2817
def get_new_keys(self):
2818
return self.new_keys
2820
def get_unsatisfied_refs(self):
2821
return self.refs.iterkeys()
2823
def _satisfy_refs_for_key(self, key):
2827
# No keys depended on this key. That's ok.
2830
def add_key(self, key):
2831
# satisfy refs for key, and remember that we've seen this key.
2832
self._satisfy_refs_for_key(key)
2833
if self.new_keys is not None:
2834
self.new_keys.add(key)
2836
def satisfy_refs_for_keys(self, keys):
2838
self._satisfy_refs_for_key(key)
2840
def get_referrers(self):
2842
for referrers in self.refs.itervalues():
2843
result.update(referrers)
2847
1884
class _KnitGraphIndex(object):
2848
1885
"""A KnitVersionedFiles index layered on GraphIndex."""
2850
1887
def __init__(self, graph_index, is_locked, deltas=False, parents=True,
2851
add_callback=None, track_external_parent_refs=False):
2852
1889
"""Construct a KnitGraphIndex on a graph_index.
2854
1891
:param graph_index: An implementation of bzrlib.index.GraphIndex.
2855
1892
:param is_locked: A callback to check whether the object should answer
2857
1894
:param deltas: Allow delta-compressed records.
2858
:param parents: If True, record knits parents, if not do not record
1895
:param parents: If True, record knits parents, if not do not record
2860
1897
:param add_callback: If not None, allow additions to the index and call
2861
1898
this callback with a list of added GraphIndex nodes:
2862
1899
[(node, value, node_refs), ...]
2863
1900
:param is_locked: A callback, returns True if the index is locked and
2865
:param track_external_parent_refs: If True, record all external parent
2866
references parents from added records. These can be retrieved
2867
later by calling get_missing_parents().
2869
1903
self._add_callback = add_callback
2870
1904
self._graph_index = graph_index
3431
2294
annotator = _KnitAnnotator(knit)
3432
return iter(annotator.annotate_flat(revision_id))
3435
class _KnitAnnotator(annotate.Annotator):
2295
return iter(annotator.annotate(revision_id))
2298
class _KnitAnnotator(object):
3436
2299
"""Build up the annotations for a text."""
3438
def __init__(self, vf):
3439
annotate.Annotator.__init__(self, vf)
3441
# TODO: handle Nodes which cannot be extracted
3442
# self._ghosts = set()
3444
# Map from (key, parent_key) => matching_blocks, should be 'use once'
3445
self._matching_blocks = {}
3447
# KnitContent objects
3448
self._content_objects = {}
3449
# The number of children that depend on this fulltext content object
3450
self._num_compression_children = {}
3451
# Delta records that need their compression parent before they can be
3453
self._pending_deltas = {}
3454
# Fulltext records that are waiting for their parents fulltexts before
3455
# they can be yielded for annotation
3456
self._pending_annotation = {}
2301
def __init__(self, knit):
2304
# Content objects, differs from fulltexts because of how final newlines
2305
# are treated by knits. the content objects here will always have a
2307
self._fulltext_contents = {}
2309
# Annotated lines of specific revisions
2310
self._annotated_lines = {}
2312
# Track the raw data for nodes that we could not process yet.
2313
# This maps the revision_id of the base to a list of children that will
2314
# annotated from it.
2315
self._pending_children = {}
2317
# Nodes which cannot be extracted
2318
self._ghosts = set()
2320
# Track how many children this node has, so we know if we need to keep
2322
self._annotate_children = {}
2323
self._compression_children = {}
3458
2325
self._all_build_details = {}
2326
# The children => parent revision_id graph
2327
self._revision_id_graph = {}
2329
self._heads_provider = None
2331
self._nodes_to_keep_annotations = set()
2332
self._generations_until_keep = 100
2334
def set_generations_until_keep(self, value):
2335
"""Set the number of generations before caching a node.
2337
Setting this to -1 will cache every merge node, setting this higher
2338
will cache fewer nodes.
2340
self._generations_until_keep = value
2342
def _add_fulltext_content(self, revision_id, content_obj):
2343
self._fulltext_contents[revision_id] = content_obj
2344
# TODO: jam 20080305 It might be good to check the sha1digest here
2345
return content_obj.text()
2347
def _check_parents(self, child, nodes_to_annotate):
2348
"""Check if all parents have been processed.
2350
:param child: A tuple of (rev_id, parents, raw_content)
2351
:param nodes_to_annotate: If child is ready, add it to
2352
nodes_to_annotate, otherwise put it back in self._pending_children
2354
for parent_id in child[1]:
2355
if (parent_id not in self._annotated_lines):
2356
# This parent is present, but another parent is missing
2357
self._pending_children.setdefault(parent_id,
2361
# This one is ready to be processed
2362
nodes_to_annotate.append(child)
2364
def _add_annotation(self, revision_id, fulltext, parent_ids,
2365
left_matching_blocks=None):
2366
"""Add an annotation entry.
2368
All parents should already have been annotated.
2369
:return: A list of children that now have their parents satisfied.
2371
a = self._annotated_lines
2372
annotated_parent_lines = [a[p] for p in parent_ids]
2373
annotated_lines = list(annotate.reannotate(annotated_parent_lines,
2374
fulltext, revision_id, left_matching_blocks,
2375
heads_provider=self._get_heads_provider()))
2376
self._annotated_lines[revision_id] = annotated_lines
2377
for p in parent_ids:
2378
ann_children = self._annotate_children[p]
2379
ann_children.remove(revision_id)
2380
if (not ann_children
2381
and p not in self._nodes_to_keep_annotations):
2382
del self._annotated_lines[p]
2383
del self._all_build_details[p]
2384
if p in self._fulltext_contents:
2385
del self._fulltext_contents[p]
2386
# Now that we've added this one, see if there are any pending
2387
# deltas to be done, certainly this parent is finished
2388
nodes_to_annotate = []
2389
for child in self._pending_children.pop(revision_id, []):
2390
self._check_parents(child, nodes_to_annotate)
2391
return nodes_to_annotate
3460
2393
def _get_build_graph(self, key):
3461
2394
"""Get the graphs for building texts and annotations.
3468
2401
:return: A list of (key, index_memo) records, suitable for
3469
passing to read_records_iter to start reading in the raw data from
2402
passing to read_records_iter to start reading in the raw data fro/
2405
if key in self._annotated_lines:
3472
2408
pending = set([key])
3475
self._num_needed_children[key] = 1
3477
2413
# get all pending nodes
3478
2415
this_iteration = pending
3479
build_details = self._vf._index.get_build_details(this_iteration)
2416
build_details = self._knit._index.get_build_details(this_iteration)
3480
2417
self._all_build_details.update(build_details)
3481
# new_nodes = self._vf._index._get_entries(this_iteration)
2418
# new_nodes = self._knit._index._get_entries(this_iteration)
3482
2419
pending = set()
3483
2420
for key, details in build_details.iteritems():
3484
(index_memo, compression_parent, parent_keys,
2421
(index_memo, compression_parent, parents,
3485
2422
record_details) = details
3486
self._parent_map[key] = parent_keys
3487
self._heads_provider = None
2423
self._revision_id_graph[key] = parents
3488
2424
records.append((key, index_memo))
3489
2425
# Do we actually need to check _annotated_lines?
3490
pending.update([p for p in parent_keys
3491
if p not in self._all_build_details])
3493
for parent_key in parent_keys:
3494
if parent_key in self._num_needed_children:
3495
self._num_needed_children[parent_key] += 1
3497
self._num_needed_children[parent_key] = 1
2426
pending.update(p for p in parents
2427
if p not in self._all_build_details)
3498
2428
if compression_parent:
3499
if compression_parent in self._num_compression_children:
3500
self._num_compression_children[compression_parent] += 1
3502
self._num_compression_children[compression_parent] = 1
2429
self._compression_children.setdefault(compression_parent,
2432
for parent in parents:
2433
self._annotate_children.setdefault(parent,
2435
num_gens = generation - kept_generation
2436
if ((num_gens >= self._generations_until_keep)
2437
and len(parents) > 1):
2438
kept_generation = generation
2439
self._nodes_to_keep_annotations.add(key)
3504
2441
missing_versions = this_iteration.difference(build_details.keys())
3505
if missing_versions:
3506
for key in missing_versions:
3507
if key in self._parent_map and key in self._text_cache:
3508
# We already have this text ready, we just need to
3509
# yield it later so we get it annotated
3511
parent_keys = self._parent_map[key]
3512
for parent_key in parent_keys:
3513
if parent_key in self._num_needed_children:
3514
self._num_needed_children[parent_key] += 1
3516
self._num_needed_children[parent_key] = 1
3517
pending.update([p for p in parent_keys
3518
if p not in self._all_build_details])
3520
raise errors.RevisionNotPresent(key, self._vf)
2442
self._ghosts.update(missing_versions)
2443
for missing_version in missing_versions:
2444
# add a key, no parents
2445
self._revision_id_graph[missing_version] = ()
2446
pending.discard(missing_version) # don't look for it
2447
if self._ghosts.intersection(self._compression_children):
2449
"We cannot have nodes which have a ghost compression parent:\n"
2451
"compression children: %r"
2452
% (self._ghosts, self._compression_children))
2453
# Cleanout anything that depends on a ghost so that we don't wait for
2454
# the ghost to show up
2455
for node in self._ghosts:
2456
if node in self._annotate_children:
2457
# We won't be building this node
2458
del self._annotate_children[node]
3521
2459
# Generally we will want to read the records in reverse order, because
3522
2460
# we find the parent nodes after the children
3523
2461
records.reverse()
3524
return records, ann_keys
3526
def _get_needed_texts(self, key, pb=None):
3527
# if True or len(self._vf._fallback_vfs) > 0:
3528
if len(self._vf._fallback_vfs) > 0:
3529
# If we have fallbacks, go to the generic path
3530
for v in annotate.Annotator._get_needed_texts(self, key, pb=pb):
3535
records, ann_keys = self._get_build_graph(key)
3536
for idx, (sub_key, text, num_lines) in enumerate(
3537
self._extract_texts(records)):
3539
pb.update('annotating', idx, len(records))
3540
yield sub_key, text, num_lines
3541
for sub_key in ann_keys:
3542
text = self._text_cache[sub_key]
3543
num_lines = len(text) # bad assumption
3544
yield sub_key, text, num_lines
3546
except errors.RetryWithNewPacks, e:
3547
self._vf._access.reload_or_raise(e)
3548
# The cached build_details are no longer valid
3549
self._all_build_details.clear()
3551
def _cache_delta_blocks(self, key, compression_parent, delta, lines):
3552
parent_lines = self._text_cache[compression_parent]
3553
blocks = list(KnitContent.get_line_delta_blocks(delta, parent_lines, lines))
3554
self._matching_blocks[(key, compression_parent)] = blocks
3556
def _expand_record(self, key, parent_keys, compression_parent, record,
3559
if compression_parent:
3560
if compression_parent not in self._content_objects:
3561
# Waiting for the parent
3562
self._pending_deltas.setdefault(compression_parent, []).append(
3563
(key, parent_keys, record, record_details))
3565
# We have the basis parent, so expand the delta
3566
num = self._num_compression_children[compression_parent]
3569
base_content = self._content_objects.pop(compression_parent)
3570
self._num_compression_children.pop(compression_parent)
3572
self._num_compression_children[compression_parent] = num
3573
base_content = self._content_objects[compression_parent]
3574
# It is tempting to want to copy_base_content=False for the last
3575
# child object. However, whenever noeol=False,
3576
# self._text_cache[parent_key] is content._lines. So mutating it
3577
# gives very bad results.
3578
# The alternative is to copy the lines into text cache, but then we
3579
# are copying anyway, so just do it here.
3580
content, delta = self._vf._factory.parse_record(
3581
key, record, record_details, base_content,
3582
copy_base_content=True)
3585
content, _ = self._vf._factory.parse_record(
3586
key, record, record_details, None)
3587
if self._num_compression_children.get(key, 0) > 0:
3588
self._content_objects[key] = content
3589
lines = content.text()
3590
self._text_cache[key] = lines
3591
if delta is not None:
3592
self._cache_delta_blocks(key, compression_parent, delta, lines)
3595
def _get_parent_annotations_and_matches(self, key, text, parent_key):
3596
"""Get the list of annotations for the parent, and the matching lines.
3598
:param text: The opaque value given by _get_needed_texts
3599
:param parent_key: The key for the parent text
3600
:return: (parent_annotations, matching_blocks)
3601
parent_annotations is a list as long as the number of lines in
3603
matching_blocks is a list of (parent_idx, text_idx, len) tuples
3604
indicating which lines match between the two texts
3606
block_key = (key, parent_key)
3607
if block_key in self._matching_blocks:
3608
blocks = self._matching_blocks.pop(block_key)
3609
parent_annotations = self._annotations_cache[parent_key]
3610
return parent_annotations, blocks
3611
return annotate.Annotator._get_parent_annotations_and_matches(self,
3612
key, text, parent_key)
3614
def _process_pending(self, key):
3615
"""The content for 'key' was just processed.
3617
Determine if there is any more pending work to be processed.
3620
if key in self._pending_deltas:
3621
compression_parent = key
3622
children = self._pending_deltas.pop(key)
3623
for child_key, parent_keys, record, record_details in children:
3624
lines = self._expand_record(child_key, parent_keys,
3626
record, record_details)
3627
if self._check_ready_for_annotations(child_key, parent_keys):
3628
to_return.append(child_key)
3629
# Also check any children that are waiting for this parent to be
3631
if key in self._pending_annotation:
3632
children = self._pending_annotation.pop(key)
3633
to_return.extend([c for c, p_keys in children
3634
if self._check_ready_for_annotations(c, p_keys)])
3637
def _check_ready_for_annotations(self, key, parent_keys):
3638
"""return true if this text is ready to be yielded.
3640
Otherwise, this will return False, and queue the text into
3641
self._pending_annotation
3643
for parent_key in parent_keys:
3644
if parent_key not in self._annotations_cache:
3645
# still waiting on at least one parent text, so queue it up
3646
# Note that if there are multiple parents, we need to wait
3648
self._pending_annotation.setdefault(parent_key,
3649
[]).append((key, parent_keys))
3653
def _extract_texts(self, records):
3654
"""Extract the various texts needed based on records"""
2464
def _annotate_records(self, records):
2465
"""Build the annotations for the listed records."""
3655
2466
# We iterate in the order read, rather than a strict order requested
3656
2467
# However, process what we can, and put off to the side things that
3657
2468
# still need parents, cleaning them up when those parents are
3660
# 1) As 'records' are read, see if we can expand these records into
3661
# Content objects (and thus lines)
3662
# 2) If a given line-delta is waiting on its compression parent, it
3663
# gets queued up into self._pending_deltas, otherwise we expand
3664
# it, and put it into self._text_cache and self._content_objects
3665
# 3) If we expanded the text, we will then check to see if all
3666
# parents have also been processed. If so, this text gets yielded,
3667
# else this record gets set aside into pending_annotation
3668
# 4) Further, if we expanded the text in (2), we will then check to
3669
# see if there are any children in self._pending_deltas waiting to
3670
# also be processed. If so, we go back to (2) for those
3671
# 5) Further again, if we yielded the text, we can then check if that
3672
# 'unlocks' any of the texts in pending_annotations, which should
3673
# then get yielded as well
3674
# Note that both steps 4 and 5 are 'recursive' in that unlocking one
3675
# compression child could unlock yet another, and yielding a fulltext
3676
# will also 'unlock' the children that are waiting on that annotation.
3677
# (Though also, unlocking 1 parent's fulltext, does not unlock a child
3678
# if other parents are also waiting.)
3679
# We want to yield content before expanding child content objects, so
3680
# that we know when we can re-use the content lines, and the annotation
3681
# code can know when it can stop caching fulltexts, as well.
3683
# Children that are missing their compression parent
3685
for (key, record, digest) in self._vf._read_records_iter(records):
3687
details = self._all_build_details[key]
3688
(_, compression_parent, parent_keys, record_details) = details
3689
lines = self._expand_record(key, parent_keys, compression_parent,
3690
record, record_details)
3692
# Pending delta should be queued up
2470
for (rev_id, record,
2471
digest) in self._knit._read_records_iter(records):
2472
if rev_id in self._annotated_lines:
3694
# At this point, we may be able to yield this content, if all
3695
# parents are also finished
3696
yield_this_text = self._check_ready_for_annotations(key,
3699
# All parents present
3700
yield key, lines, len(lines)
3701
to_process = self._process_pending(key)
3703
this_process = to_process
3705
for key in this_process:
3706
lines = self._text_cache[key]
3707
yield key, lines, len(lines)
3708
to_process.extend(self._process_pending(key))
2474
parent_ids = self._revision_id_graph[rev_id]
2475
parent_ids = [p for p in parent_ids if p not in self._ghosts]
2476
details = self._all_build_details[rev_id]
2477
(index_memo, compression_parent, parents,
2478
record_details) = details
2479
nodes_to_annotate = []
2480
# TODO: Remove the punning between compression parents, and
2481
# parent_ids, we should be able to do this without assuming
2483
if len(parent_ids) == 0:
2484
# There are no parents for this node, so just add it
2485
# TODO: This probably needs to be decoupled
2486
fulltext_content, delta = self._knit._factory.parse_record(
2487
rev_id, record, record_details, None)
2488
fulltext = self._add_fulltext_content(rev_id, fulltext_content)
2489
nodes_to_annotate.extend(self._add_annotation(rev_id, fulltext,
2490
parent_ids, left_matching_blocks=None))
2492
child = (rev_id, parent_ids, record)
2493
# Check if all the parents are present
2494
self._check_parents(child, nodes_to_annotate)
2495
while nodes_to_annotate:
2496
# Should we use a queue here instead of a stack?
2497
(rev_id, parent_ids, record) = nodes_to_annotate.pop()
2498
(index_memo, compression_parent, parents,
2499
record_details) = self._all_build_details[rev_id]
2500
if compression_parent is not None:
2501
comp_children = self._compression_children[compression_parent]
2502
if rev_id not in comp_children:
2503
raise AssertionError("%r not in compression children %r"
2504
% (rev_id, comp_children))
2505
# If there is only 1 child, it is safe to reuse this
2507
reuse_content = (len(comp_children) == 1
2508
and compression_parent not in
2509
self._nodes_to_keep_annotations)
2511
# Remove it from the cache since it will be changing
2512
parent_fulltext_content = self._fulltext_contents.pop(compression_parent)
2513
# Make sure to copy the fulltext since it might be
2515
parent_fulltext = list(parent_fulltext_content.text())
2517
parent_fulltext_content = self._fulltext_contents[compression_parent]
2518
parent_fulltext = parent_fulltext_content.text()
2519
comp_children.remove(rev_id)
2520
fulltext_content, delta = self._knit._factory.parse_record(
2521
rev_id, record, record_details,
2522
parent_fulltext_content,
2523
copy_base_content=(not reuse_content))
2524
fulltext = self._add_fulltext_content(rev_id,
2526
blocks = KnitContent.get_line_delta_blocks(delta,
2527
parent_fulltext, fulltext)
2529
fulltext_content = self._knit._factory.parse_fulltext(
2531
fulltext = self._add_fulltext_content(rev_id,
2534
nodes_to_annotate.extend(
2535
self._add_annotation(rev_id, fulltext, parent_ids,
2536
left_matching_blocks=blocks))
2538
def _get_heads_provider(self):
2539
"""Create a heads provider for resolving ancestry issues."""
2540
if self._heads_provider is not None:
2541
return self._heads_provider
2542
parent_provider = _mod_graph.DictParentsProvider(
2543
self._revision_id_graph)
2544
graph_obj = _mod_graph.Graph(parent_provider)
2545
head_cache = _mod_graph.FrozenHeadsCache(graph_obj)
2546
self._heads_provider = head_cache
2549
def annotate(self, key):
2550
"""Return the annotated fulltext at the given key.
2552
:param key: The key to annotate.
2554
records = self._get_build_graph(key)
2555
if key in self._ghosts:
2556
raise errors.RevisionNotPresent(key, self._knit)
2557
self._annotate_records(records)
2558
return self._annotated_lines[key]
3711
from bzrlib._knit_load_data_pyx import _load_data_c as _load_data
3712
except ImportError, e:
3713
osutils.failed_to_load_extension(e)
2562
from bzrlib._knit_load_data_c import _load_data_c as _load_data
3714
2564
from bzrlib._knit_load_data_py import _load_data_py as _load_data