279
274
annotated_kind = ''
280
275
self.storage_kind = 'knit-%s%s-gz' % (annotated_kind, kind)
281
276
self._raw_record = raw_record
277
self._network_bytes = network_bytes
282
278
self._build_details = build_details
283
279
self._knit = knit
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,
281
def _create_network_bytes(self):
282
"""Create a fully serialised network version for transmission."""
283
# storage_kind, key, parents, Noeol, raw_record
284
key_bytes = '\x00'.join(self.key)
285
if self.parents is None:
286
parent_bytes = 'None:'
288
parent_bytes = '\t'.join('\x00'.join(key) for key in self.parents)
289
if self._build_details[1]:
293
network_bytes = "%s\n%s\n%s\n%s%s" % (self.storage_kind, key_bytes,
294
parent_bytes, noeol, self._raw_record)
295
self._network_bytes = network_bytes
297
def get_bytes_as(self, storage_kind):
298
if storage_kind == self.storage_kind:
299
if self._network_bytes is None:
300
self._create_network_bytes()
301
return self._network_bytes
302
if ('-ft-' in self.storage_kind and
303
storage_kind in ('chunked', 'fulltext')):
304
adapter_key = (self.storage_kind, 'fulltext')
305
adapter_factory = adapter_registry.get(adapter_key)
306
adapter = adapter_factory(None)
307
bytes = adapter.get_bytes(self)
308
if storage_kind == 'chunked':
312
if self._knit is not None:
313
# Not redundant with direct conversion above - that only handles
315
if storage_kind == 'chunked':
316
return self._knit.get_lines(self.key[0])
317
elif storage_kind == 'fulltext':
318
return self._knit.get_text(self.key[0])
319
raise errors.UnavailableRepresentation(self.key, storage_kind,
323
class LazyKnitContentFactory(ContentFactory):
324
"""A ContentFactory which can either generate full text or a wire form.
326
:seealso ContentFactory:
329
def __init__(self, key, parents, generator, first):
330
"""Create a LazyKnitContentFactory.
332
:param key: The key of the record.
333
:param parents: The parents of the record.
334
:param generator: A _ContentMapGenerator containing the record for this
336
:param first: Is this the first content object returned from generator?
337
if it is, its storage kind is knit-delta-closure, otherwise it is
338
knit-delta-closure-ref
341
self.parents = parents
343
self._generator = generator
344
self.storage_kind = "knit-delta-closure"
346
self.storage_kind = self.storage_kind + "-ref"
349
def get_bytes_as(self, storage_kind):
350
if storage_kind == self.storage_kind:
352
return self._generator._wire_bytes()
354
# all the keys etc are contained in the bytes returned in the
357
if storage_kind in ('chunked', 'fulltext'):
358
chunks = self._generator._get_one_work(self.key).text()
359
if storage_kind == 'chunked':
362
return ''.join(chunks)
363
raise errors.UnavailableRepresentation(self.key, storage_kind,
367
def knit_delta_closure_to_records(storage_kind, bytes, line_end):
368
"""Convert a network record to a iterator over stream records.
370
:param storage_kind: The storage kind of the record.
371
Must be 'knit-delta-closure'.
372
:param bytes: The bytes of the record on the network.
374
generator = _NetworkContentMapGenerator(bytes, line_end)
375
return generator.get_record_stream()
378
def knit_network_to_record(storage_kind, bytes, line_end):
379
"""Convert a network record to a record object.
381
:param storage_kind: The storage kind of the record.
382
:param bytes: The bytes of the record on the network.
385
line_end = bytes.find('\n', start)
386
key = tuple(bytes[start:line_end].split('\x00'))
388
line_end = bytes.find('\n', start)
389
parent_line = bytes[start:line_end]
390
if parent_line == 'None:':
394
[tuple(segment.split('\x00')) for segment in parent_line.split('\t')
397
noeol = bytes[start] == 'N'
398
if 'ft' in storage_kind:
401
method = 'line-delta'
402
build_details = (method, noeol)
404
raw_record = bytes[start:]
405
annotated = 'annotated' in storage_kind
406
return [KnitContentFactory(key, parents, build_details, None, raw_record,
407
annotated, network_bytes=bytes)]
295
410
class KnitContent(object):
296
411
"""Content of a knit version to which deltas can be applied.
298
413
This is always stored in memory as a list of lines with \n at the end,
299
plus a flag saying if the final ending is really there or not, because that
414
plus a flag saying if the final ending is really there or not, because that
300
415
corresponds to the on-disk knit representation.
972
1187
if not self.get_parent_map([key]):
973
1188
raise RevisionNotPresent(key, self)
974
1189
return cached_version
975
text_map, contents_map = self._get_content_maps([key])
976
return contents_map[key]
978
def _get_content_maps(self, keys, nonlocal_keys=None):
979
"""Produce maps of text and KnitContents
981
:param keys: The keys to produce content maps for.
982
:param nonlocal_keys: An iterable of keys(possibly intersecting keys)
983
which are known to not be in this knit, but rather in one of the
985
:return: (text_map, content_map) where text_map contains the texts for
986
the requested versions and content_map contains the KnitContents.
988
# FUTURE: This function could be improved for the 'extract many' case
989
# by tracking each component and only doing the copy when the number of
990
# children than need to apply delta's to it is > 1 or it is part of the
993
multiple_versions = len(keys) != 1
994
record_map = self._get_record_map(keys, allow_missing=True)
999
if nonlocal_keys is None:
1000
nonlocal_keys = set()
1002
nonlocal_keys = frozenset(nonlocal_keys)
1003
missing_keys = set(nonlocal_keys)
1004
for source in self._fallback_vfs:
1190
generator = _VFContentMapGenerator(self, [key])
1191
return generator._get_content(key)
1193
def get_known_graph_ancestry(self, keys):
1194
"""Get a KnownGraph instance with the ancestry of keys."""
1195
parent_map, missing_keys = self._index.find_ancestry(keys)
1196
for fallback in self._fallback_vfs:
1005
1197
if not missing_keys:
1007
for record in source.get_record_stream(missing_keys,
1009
if record.storage_kind == 'absent':
1011
missing_keys.remove(record.key)
1012
lines = split_lines(record.get_bytes_as('fulltext'))
1013
text_map[record.key] = lines
1014
content_map[record.key] = PlainKnitContent(lines, record.key)
1015
if record.key in keys:
1016
final_content[record.key] = content_map[record.key]
1018
if key in nonlocal_keys:
1023
while cursor is not None:
1025
record, record_details, digest, next = record_map[cursor]
1027
raise RevisionNotPresent(cursor, self)
1028
components.append((cursor, record, record_details, digest))
1030
if cursor in content_map:
1031
# no need to plan further back
1032
components.append((cursor, None, None, None))
1036
for (component_id, record, record_details,
1037
digest) in reversed(components):
1038
if component_id in content_map:
1039
content = content_map[component_id]
1041
content, delta = self._factory.parse_record(key[-1],
1042
record, record_details, content,
1043
copy_base_content=multiple_versions)
1044
if multiple_versions:
1045
content_map[component_id] = content
1047
final_content[key] = content
1049
# digest here is the digest from the last applied component.
1050
text = content.text()
1051
actual_sha = sha_strings(text)
1052
if actual_sha != digest:
1053
raise KnitCorrupt(self,
1055
'\n of reconstructed text does not match'
1057
'\n for version %s' %
1058
(actual_sha, digest, key))
1059
text_map[key] = text
1060
return text_map, final_content
1199
(f_parent_map, f_missing_keys) = fallback._index.find_ancestry(
1201
parent_map.update(f_parent_map)
1202
missing_keys = f_missing_keys
1203
kg = _mod_graph.KnownGraph(parent_map)
1062
1206
def get_parent_map(self, keys):
1063
1207
"""Get a map of the graph parents of keys.
1105
1249
build-parent of the version, i.e. the leftmost ancestor.
1106
1250
Will be None if the record is not a delta.
1107
1251
:param keys: The keys to build a map for
1108
:param allow_missing: If some records are missing, rather than
1252
:param allow_missing: If some records are missing, rather than
1109
1253
error, just return the data that could be generated.
1111
position_map = self._get_components_positions(keys,
1255
raw_map = self._get_record_map_unparsed(keys,
1112
1256
allow_missing=allow_missing)
1113
# key = component_id, r = record_details, i_m = index_memo, n = next
1114
records = [(key, i_m) for key, (r, i_m, n)
1115
in position_map.iteritems()]
1117
for key, record, digest in \
1118
self._read_records_iter(records):
1119
(record_details, index_memo, next) = position_map[key]
1120
record_map[key] = record, record_details, digest, next
1257
return self._raw_map_to_record_map(raw_map)
1259
def _raw_map_to_record_map(self, raw_map):
1260
"""Parse the contents of _get_record_map_unparsed.
1262
:return: see _get_record_map.
1266
data, record_details, next = raw_map[key]
1267
content, digest = self._parse_record(key[-1], data)
1268
result[key] = content, record_details, digest, next
1271
def _get_record_map_unparsed(self, keys, allow_missing=False):
1272
"""Get the raw data for reconstructing keys without parsing it.
1274
:return: A dict suitable for parsing via _raw_map_to_record_map.
1275
key-> raw_bytes, (method, noeol), compression_parent
1277
# This retries the whole request if anything fails. Potentially we
1278
# could be a bit more selective. We could track the keys whose records
1279
# we have successfully found, and then only request the new records
1280
# from there. However, _get_components_positions grabs the whole build
1281
# chain, which means we'll likely try to grab the same records again
1282
# anyway. Also, can the build chains change as part of a pack
1283
# operation? We wouldn't want to end up with a broken chain.
1286
position_map = self._get_components_positions(keys,
1287
allow_missing=allow_missing)
1288
# key = component_id, r = record_details, i_m = index_memo,
1290
records = [(key, i_m) for key, (r, i_m, n)
1291
in position_map.iteritems()]
1292
# Sort by the index memo, so that we request records from the
1293
# same pack file together, and in forward-sorted order
1294
records.sort(key=operator.itemgetter(1))
1296
for key, data in self._read_records_iter_unchecked(records):
1297
(record_details, index_memo, next) = position_map[key]
1298
raw_record_map[key] = data, record_details, next
1299
return raw_record_map
1300
except errors.RetryWithNewPacks, e:
1301
self._access.reload_or_raise(e)
1304
def _split_by_prefix(cls, keys):
1305
"""For the given keys, split them up based on their prefix.
1307
To keep memory pressure somewhat under control, split the
1308
requests back into per-file-id requests, otherwise "bzr co"
1309
extracts the full tree into memory before writing it to disk.
1310
This should be revisited if _get_content_maps() can ever cross
1313
The keys for a given file_id are kept in the same relative order.
1314
Ordering between file_ids is not, though prefix_order will return the
1315
order that the key was first seen.
1317
:param keys: An iterable of key tuples
1318
:return: (split_map, prefix_order)
1319
split_map A dictionary mapping prefix => keys
1320
prefix_order The order that we saw the various prefixes
1322
split_by_prefix = {}
1330
if prefix in split_by_prefix:
1331
split_by_prefix[prefix].append(key)
1333
split_by_prefix[prefix] = [key]
1334
prefix_order.append(prefix)
1335
return split_by_prefix, prefix_order
1337
def _group_keys_for_io(self, keys, non_local_keys, positions,
1338
_min_buffer_size=_STREAM_MIN_BUFFER_SIZE):
1339
"""For the given keys, group them into 'best-sized' requests.
1341
The idea is to avoid making 1 request per file, but to never try to
1342
unpack an entire 1.5GB source tree in a single pass. Also when
1343
possible, we should try to group requests to the same pack file
1346
:return: list of (keys, non_local) tuples that indicate what keys
1347
should be fetched next.
1349
# TODO: Ideally we would group on 2 factors. We want to extract texts
1350
# from the same pack file together, and we want to extract all
1351
# the texts for a given build-chain together. Ultimately it
1352
# probably needs a better global view.
1353
total_keys = len(keys)
1354
prefix_split_keys, prefix_order = self._split_by_prefix(keys)
1355
prefix_split_non_local_keys, _ = self._split_by_prefix(non_local_keys)
1357
cur_non_local = set()
1361
for prefix in prefix_order:
1362
keys = prefix_split_keys[prefix]
1363
non_local = prefix_split_non_local_keys.get(prefix, [])
1365
this_size = self._index._get_total_build_size(keys, positions)
1366
cur_size += this_size
1367
cur_keys.extend(keys)
1368
cur_non_local.update(non_local)
1369
if cur_size > _min_buffer_size:
1370
result.append((cur_keys, cur_non_local))
1371
sizes.append(cur_size)
1373
cur_non_local = set()
1376
result.append((cur_keys, cur_non_local))
1377
sizes.append(cur_size)
1123
1380
def get_record_stream(self, keys, ordering, include_delta_closure):
1124
1381
"""Get a stream of records for keys.
1325
1655
access_memo = self._access.add_raw_records(
1326
1656
[(record.key, len(bytes))], bytes)[0]
1327
1657
index_entry = (record.key, options, access_memo, parents)
1329
1658
if 'fulltext' not in options:
1330
basis_parent = parents[0]
1659
# Not a fulltext, so we need to make sure the compression
1660
# parent will also be present.
1331
1661
# Note that pack backed knits don't need to buffer here
1332
1662
# because they buffer all writes to the transaction level,
1333
1663
# but we don't expose that difference at the index level. If
1334
1664
# the query here has sufficient cost to show up in
1335
1665
# profiling we should do that.
1336
if basis_parent not in self.get_parent_map([basis_parent]):
1667
# They're required to be physically in this
1668
# KnitVersionedFiles, not in a fallback.
1669
if not self._index.has_key(compression_parent):
1337
1670
pending = buffered_index_entries.setdefault(
1671
compression_parent, [])
1339
1672
pending.append(index_entry)
1340
1673
buffered = True
1341
1674
if not buffered:
1342
1675
self._index.add_records([index_entry])
1343
elif record.storage_kind == 'fulltext':
1676
elif record.storage_kind == 'chunked':
1344
1677
self.add_lines(record.key, parents,
1345
split_lines(record.get_bytes_as('fulltext')))
1678
osutils.chunks_to_lines(record.get_bytes_as('chunked')))
1347
adapter_key = record.storage_kind, 'fulltext'
1348
adapter = get_adapter(adapter_key)
1349
lines = split_lines(adapter.get_bytes(
1350
record, record.get_bytes_as(record.storage_kind)))
1680
# Not suitable for direct insertion as a
1681
# delta, either because it's not the right format, or this
1682
# KnitVersionedFiles doesn't permit deltas (_max_delta_chain ==
1683
# 0) or because it depends on a base only present in the
1685
self._access.flush()
1687
# Try getting a fulltext directly from the record.
1688
bytes = record.get_bytes_as('fulltext')
1689
except errors.UnavailableRepresentation:
1690
adapter_key = record.storage_kind, 'fulltext'
1691
adapter = get_adapter(adapter_key)
1692
bytes = adapter.get_bytes(record)
1693
lines = split_lines(bytes)
1352
1695
self.add_lines(record.key, parents, lines)
1353
1696
except errors.RevisionAlreadyPresent:
1355
1698
# Add any records whose basis parent is now available.
1356
added_keys = [record.key]
1358
key = added_keys.pop(0)
1359
if key in buffered_index_entries:
1360
index_entries = buffered_index_entries[key]
1361
self._index.add_records(index_entries)
1363
[index_entry[0] for index_entry in index_entries])
1364
del buffered_index_entries[key]
1365
# If there were any deltas which had a missing basis parent, error.
1700
added_keys = [record.key]
1702
key = added_keys.pop(0)
1703
if key in buffered_index_entries:
1704
index_entries = buffered_index_entries[key]
1705
self._index.add_records(index_entries)
1707
[index_entry[0] for index_entry in index_entries])
1708
del buffered_index_entries[key]
1366
1709
if buffered_index_entries:
1367
raise errors.RevisionNotPresent(buffered_index_entries.keys()[0],
1710
# There were index entries buffered at the end of the stream,
1711
# So these need to be added (if the index supports holding such
1712
# entries for later insertion)
1714
for key in buffered_index_entries:
1715
index_entries = buffered_index_entries[key]
1716
all_entries.extend(index_entries)
1717
self._index.add_records(
1718
all_entries, missing_compression_parents=True)
1720
def get_missing_compression_parent_keys(self):
1721
"""Return an iterable of keys of missing compression parents.
1723
Check this after calling insert_record_stream to find out if there are
1724
any missing compression parents. If there are, the records that
1725
depend on them are not able to be inserted safely. For atomic
1726
KnitVersionedFiles built on packs, the transaction should be aborted or
1727
suspended - commit will fail at this point. Nonatomic knits will error
1728
earlier because they have no staging area to put pending entries into.
1730
return self._index.get_missing_compression_parents()
1370
1732
def iter_lines_added_or_present_in_keys(self, keys, pb=None):
1371
1733
"""Iterate over the lines in the versioned files from keys.
2023
class _ContentMapGenerator(object):
2024
"""Generate texts or expose raw deltas for a set of texts."""
2026
def __init__(self, ordering='unordered'):
2027
self._ordering = ordering
2029
def _get_content(self, key):
2030
"""Get the content object for key."""
2031
# Note that _get_content is only called when the _ContentMapGenerator
2032
# has been constructed with just one key requested for reconstruction.
2033
if key in self.nonlocal_keys:
2034
record = self.get_record_stream().next()
2035
# Create a content object on the fly
2036
lines = osutils.chunks_to_lines(record.get_bytes_as('chunked'))
2037
return PlainKnitContent(lines, record.key)
2039
# local keys we can ask for directly
2040
return self._get_one_work(key)
2042
def get_record_stream(self):
2043
"""Get a record stream for the keys requested during __init__."""
2044
for record in self._work():
2048
"""Produce maps of text and KnitContents as dicts.
2050
:return: (text_map, content_map) where text_map contains the texts for
2051
the requested versions and content_map contains the KnitContents.
2053
# NB: By definition we never need to read remote sources unless texts
2054
# are requested from them: we don't delta across stores - and we
2055
# explicitly do not want to to prevent data loss situations.
2056
if self.global_map is None:
2057
self.global_map = self.vf.get_parent_map(self.keys)
2058
nonlocal_keys = self.nonlocal_keys
2060
missing_keys = set(nonlocal_keys)
2061
# Read from remote versioned file instances and provide to our caller.
2062
for source in self.vf._fallback_vfs:
2063
if not missing_keys:
2065
# Loop over fallback repositories asking them for texts - ignore
2066
# any missing from a particular fallback.
2067
for record in source.get_record_stream(missing_keys,
2068
self._ordering, True):
2069
if record.storage_kind == 'absent':
2070
# Not in thie particular stream, may be in one of the
2071
# other fallback vfs objects.
2073
missing_keys.remove(record.key)
2076
if self._raw_record_map is None:
2077
raise AssertionError('_raw_record_map should have been filled')
2079
for key in self.keys:
2080
if key in self.nonlocal_keys:
2082
yield LazyKnitContentFactory(key, self.global_map[key], self, first)
2085
def _get_one_work(self, requested_key):
2086
# Now, if we have calculated everything already, just return the
2088
if requested_key in self._contents_map:
2089
return self._contents_map[requested_key]
2090
# To simplify things, parse everything at once - code that wants one text
2091
# probably wants them all.
2092
# FUTURE: This function could be improved for the 'extract many' case
2093
# by tracking each component and only doing the copy when the number of
2094
# children than need to apply delta's to it is > 1 or it is part of the
2096
multiple_versions = len(self.keys) != 1
2097
if self._record_map is None:
2098
self._record_map = self.vf._raw_map_to_record_map(
2099
self._raw_record_map)
2100
record_map = self._record_map
2101
# raw_record_map is key:
2102
# Have read and parsed records at this point.
2103
for key in self.keys:
2104
if key in self.nonlocal_keys:
2109
while cursor is not None:
2111
record, record_details, digest, next = record_map[cursor]
2113
raise RevisionNotPresent(cursor, self)
2114
components.append((cursor, record, record_details, digest))
2116
if cursor in self._contents_map:
2117
# no need to plan further back
2118
components.append((cursor, None, None, None))
2122
for (component_id, record, record_details,
2123
digest) in reversed(components):
2124
if component_id in self._contents_map:
2125
content = self._contents_map[component_id]
2127
content, delta = self._factory.parse_record(key[-1],
2128
record, record_details, content,
2129
copy_base_content=multiple_versions)
2130
if multiple_versions:
2131
self._contents_map[component_id] = content
2133
# digest here is the digest from the last applied component.
2134
text = content.text()
2135
actual_sha = sha_strings(text)
2136
if actual_sha != digest:
2137
raise SHA1KnitCorrupt(self, actual_sha, digest, key, text)
2138
if multiple_versions:
2139
return self._contents_map[requested_key]
2143
def _wire_bytes(self):
2144
"""Get the bytes to put on the wire for 'key'.
2146
The first collection of bytes asked for returns the serialised
2147
raw_record_map and the additional details (key, parent) for key.
2148
Subsequent calls return just the additional details (key, parent).
2149
The wire storage_kind given for the first key is 'knit-delta-closure',
2150
For subsequent keys it is 'knit-delta-closure-ref'.
2152
:param key: A key from the content generator.
2153
:return: Bytes to put on the wire.
2156
# kind marker for dispatch on the far side,
2157
lines.append('knit-delta-closure')
2159
if self.vf._factory.annotated:
2160
lines.append('annotated')
2163
# then the list of keys
2164
lines.append('\t'.join(['\x00'.join(key) for key in self.keys
2165
if key not in self.nonlocal_keys]))
2166
# then the _raw_record_map in serialised form:
2168
# for each item in the map:
2170
# 1 line with parents if the key is to be yielded (None: for None, '' for ())
2171
# one line with method
2172
# one line with noeol
2173
# one line with next ('' for None)
2174
# one line with byte count of the record bytes
2176
for key, (record_bytes, (method, noeol), next) in \
2177
self._raw_record_map.iteritems():
2178
key_bytes = '\x00'.join(key)
2179
parents = self.global_map.get(key, None)
2181
parent_bytes = 'None:'
2183
parent_bytes = '\t'.join('\x00'.join(key) for key in parents)
2184
method_bytes = method
2190
next_bytes = '\x00'.join(next)
2193
map_byte_list.append('%s\n%s\n%s\n%s\n%s\n%d\n%s' % (
2194
key_bytes, parent_bytes, method_bytes, noeol_bytes, next_bytes,
2195
len(record_bytes), record_bytes))
2196
map_bytes = ''.join(map_byte_list)
2197
lines.append(map_bytes)
2198
bytes = '\n'.join(lines)
2202
class _VFContentMapGenerator(_ContentMapGenerator):
2203
"""Content map generator reading from a VersionedFiles object."""
2205
def __init__(self, versioned_files, keys, nonlocal_keys=None,
2206
global_map=None, raw_record_map=None, ordering='unordered'):
2207
"""Create a _ContentMapGenerator.
2209
:param versioned_files: The versioned files that the texts are being
2211
:param keys: The keys to produce content maps for.
2212
:param nonlocal_keys: An iterable of keys(possibly intersecting keys)
2213
which are known to not be in this knit, but rather in one of the
2215
:param global_map: The result of get_parent_map(keys) (or a supermap).
2216
This is required if get_record_stream() is to be used.
2217
:param raw_record_map: A unparsed raw record map to use for answering
2220
_ContentMapGenerator.__init__(self, ordering=ordering)
2221
# The vf to source data from
2222
self.vf = versioned_files
2224
self.keys = list(keys)
2225
# Keys known to be in fallback vfs objects
2226
if nonlocal_keys is None:
2227
self.nonlocal_keys = set()
2229
self.nonlocal_keys = frozenset(nonlocal_keys)
2230
# Parents data for keys to be returned in get_record_stream
2231
self.global_map = global_map
2232
# The chunked lists for self.keys in text form
2234
# A cache of KnitContent objects used in extracting texts.
2235
self._contents_map = {}
2236
# All the knit records needed to assemble the requested keys as full
2238
self._record_map = None
2239
if raw_record_map is None:
2240
self._raw_record_map = self.vf._get_record_map_unparsed(keys,
2243
self._raw_record_map = raw_record_map
2244
# the factory for parsing records
2245
self._factory = self.vf._factory
2248
class _NetworkContentMapGenerator(_ContentMapGenerator):
2249
"""Content map generator sourced from a network stream."""
2251
def __init__(self, bytes, line_end):
2252
"""Construct a _NetworkContentMapGenerator from a bytes block."""
2254
self.global_map = {}
2255
self._raw_record_map = {}
2256
self._contents_map = {}
2257
self._record_map = None
2258
self.nonlocal_keys = []
2259
# Get access to record parsing facilities
2260
self.vf = KnitVersionedFiles(None, None)
2263
line_end = bytes.find('\n', start)
2264
line = bytes[start:line_end]
2265
start = line_end + 1
2266
if line == 'annotated':
2267
self._factory = KnitAnnotateFactory()
2269
self._factory = KnitPlainFactory()
2270
# list of keys to emit in get_record_stream
2271
line_end = bytes.find('\n', start)
2272
line = bytes[start:line_end]
2273
start = line_end + 1
2275
tuple(segment.split('\x00')) for segment in line.split('\t')
2277
# now a loop until the end. XXX: It would be nice if this was just a
2278
# bunch of the same records as get_record_stream(..., False) gives, but
2279
# there is a decent sized gap stopping that at the moment.
2283
line_end = bytes.find('\n', start)
2284
key = tuple(bytes[start:line_end].split('\x00'))
2285
start = line_end + 1
2286
# 1 line with parents (None: for None, '' for ())
2287
line_end = bytes.find('\n', start)
2288
line = bytes[start:line_end]
2293
[tuple(segment.split('\x00')) for segment in line.split('\t')
2295
self.global_map[key] = parents
2296
start = line_end + 1
2297
# one line with method
2298
line_end = bytes.find('\n', start)
2299
line = bytes[start:line_end]
2301
start = line_end + 1
2302
# one line with noeol
2303
line_end = bytes.find('\n', start)
2304
line = bytes[start:line_end]
2306
start = line_end + 1
2307
# one line with next ('' for None)
2308
line_end = bytes.find('\n', start)
2309
line = bytes[start:line_end]
2313
next = tuple(bytes[start:line_end].split('\x00'))
2314
start = line_end + 1
2315
# one line with byte count of the record bytes
2316
line_end = bytes.find('\n', start)
2317
line = bytes[start:line_end]
2319
start = line_end + 1
2321
record_bytes = bytes[start:start+count]
2322
start = start + count
2324
self._raw_record_map[key] = (record_bytes, (method, noeol), next)
2326
def get_record_stream(self):
2327
"""Get a record stream for for keys requested by the bytestream."""
2329
for key in self.keys:
2330
yield LazyKnitContentFactory(key, self.global_map[key], self, first)
2333
def _wire_bytes(self):
1638
2337
class _KndxIndex(object):
1639
2338
"""Manages knit index files
2428
3424
annotator = _KnitAnnotator(knit)
2429
return iter(annotator.annotate(revision_id))
2432
class _KnitAnnotator(object):
3425
return iter(annotator.annotate_flat(revision_id))
3428
class _KnitAnnotator(annotate.Annotator):
2433
3429
"""Build up the annotations for a text."""
2435
def __init__(self, knit):
2438
# Content objects, differs from fulltexts because of how final newlines
2439
# are treated by knits. the content objects here will always have a
2441
self._fulltext_contents = {}
2443
# Annotated lines of specific revisions
2444
self._annotated_lines = {}
2446
# Track the raw data for nodes that we could not process yet.
2447
# This maps the revision_id of the base to a list of children that will
2448
# annotated from it.
2449
self._pending_children = {}
2451
# Nodes which cannot be extracted
2452
self._ghosts = set()
2454
# Track how many children this node has, so we know if we need to keep
2456
self._annotate_children = {}
2457
self._compression_children = {}
3431
def __init__(self, vf):
3432
annotate.Annotator.__init__(self, vf)
3434
# TODO: handle Nodes which cannot be extracted
3435
# self._ghosts = set()
3437
# Map from (key, parent_key) => matching_blocks, should be 'use once'
3438
self._matching_blocks = {}
3440
# KnitContent objects
3441
self._content_objects = {}
3442
# The number of children that depend on this fulltext content object
3443
self._num_compression_children = {}
3444
# Delta records that need their compression parent before they can be
3446
self._pending_deltas = {}
3447
# Fulltext records that are waiting for their parents fulltexts before
3448
# they can be yielded for annotation
3449
self._pending_annotation = {}
2459
3451
self._all_build_details = {}
2460
# The children => parent revision_id graph
2461
self._revision_id_graph = {}
2463
self._heads_provider = None
2465
self._nodes_to_keep_annotations = set()
2466
self._generations_until_keep = 100
2468
def set_generations_until_keep(self, value):
2469
"""Set the number of generations before caching a node.
2471
Setting this to -1 will cache every merge node, setting this higher
2472
will cache fewer nodes.
2474
self._generations_until_keep = value
2476
def _add_fulltext_content(self, revision_id, content_obj):
2477
self._fulltext_contents[revision_id] = content_obj
2478
# TODO: jam 20080305 It might be good to check the sha1digest here
2479
return content_obj.text()
2481
def _check_parents(self, child, nodes_to_annotate):
2482
"""Check if all parents have been processed.
2484
:param child: A tuple of (rev_id, parents, raw_content)
2485
:param nodes_to_annotate: If child is ready, add it to
2486
nodes_to_annotate, otherwise put it back in self._pending_children
2488
for parent_id in child[1]:
2489
if (parent_id not in self._annotated_lines):
2490
# This parent is present, but another parent is missing
2491
self._pending_children.setdefault(parent_id,
2495
# This one is ready to be processed
2496
nodes_to_annotate.append(child)
2498
def _add_annotation(self, revision_id, fulltext, parent_ids,
2499
left_matching_blocks=None):
2500
"""Add an annotation entry.
2502
All parents should already have been annotated.
2503
:return: A list of children that now have their parents satisfied.
2505
a = self._annotated_lines
2506
annotated_parent_lines = [a[p] for p in parent_ids]
2507
annotated_lines = list(annotate.reannotate(annotated_parent_lines,
2508
fulltext, revision_id, left_matching_blocks,
2509
heads_provider=self._get_heads_provider()))
2510
self._annotated_lines[revision_id] = annotated_lines
2511
for p in parent_ids:
2512
ann_children = self._annotate_children[p]
2513
ann_children.remove(revision_id)
2514
if (not ann_children
2515
and p not in self._nodes_to_keep_annotations):
2516
del self._annotated_lines[p]
2517
del self._all_build_details[p]
2518
if p in self._fulltext_contents:
2519
del self._fulltext_contents[p]
2520
# Now that we've added this one, see if there are any pending
2521
# deltas to be done, certainly this parent is finished
2522
nodes_to_annotate = []
2523
for child in self._pending_children.pop(revision_id, []):
2524
self._check_parents(child, nodes_to_annotate)
2525
return nodes_to_annotate
2527
3453
def _get_build_graph(self, key):
2528
3454
"""Get the graphs for building texts and annotations.
2535
3461
:return: A list of (key, index_memo) records, suitable for
2536
passing to read_records_iter to start reading in the raw data fro/
3462
passing to read_records_iter to start reading in the raw data from
2539
if key in self._annotated_lines:
2542
3465
pending = set([key])
3468
self._num_needed_children[key] = 1
2547
3470
# get all pending nodes
2549
3471
this_iteration = pending
2550
build_details = self._knit._index.get_build_details(this_iteration)
3472
build_details = self._vf._index.get_build_details(this_iteration)
2551
3473
self._all_build_details.update(build_details)
2552
# new_nodes = self._knit._index._get_entries(this_iteration)
3474
# new_nodes = self._vf._index._get_entries(this_iteration)
2553
3475
pending = set()
2554
3476
for key, details in build_details.iteritems():
2555
(index_memo, compression_parent, parents,
3477
(index_memo, compression_parent, parent_keys,
2556
3478
record_details) = details
2557
self._revision_id_graph[key] = parents
3479
self._parent_map[key] = parent_keys
3480
self._heads_provider = None
2558
3481
records.append((key, index_memo))
2559
3482
# Do we actually need to check _annotated_lines?
2560
pending.update(p for p in parents
2561
if p not in self._all_build_details)
3483
pending.update([p for p in parent_keys
3484
if p not in self._all_build_details])
3486
for parent_key in parent_keys:
3487
if parent_key in self._num_needed_children:
3488
self._num_needed_children[parent_key] += 1
3490
self._num_needed_children[parent_key] = 1
2562
3491
if compression_parent:
2563
self._compression_children.setdefault(compression_parent,
2566
for parent in parents:
2567
self._annotate_children.setdefault(parent,
2569
num_gens = generation - kept_generation
2570
if ((num_gens >= self._generations_until_keep)
2571
and len(parents) > 1):
2572
kept_generation = generation
2573
self._nodes_to_keep_annotations.add(key)
3492
if compression_parent in self._num_compression_children:
3493
self._num_compression_children[compression_parent] += 1
3495
self._num_compression_children[compression_parent] = 1
2575
3497
missing_versions = this_iteration.difference(build_details.keys())
2576
self._ghosts.update(missing_versions)
2577
for missing_version in missing_versions:
2578
# add a key, no parents
2579
self._revision_id_graph[missing_version] = ()
2580
pending.discard(missing_version) # don't look for it
2581
if self._ghosts.intersection(self._compression_children):
2583
"We cannot have nodes which have a ghost compression parent:\n"
2585
"compression children: %r"
2586
% (self._ghosts, self._compression_children))
2587
# Cleanout anything that depends on a ghost so that we don't wait for
2588
# the ghost to show up
2589
for node in self._ghosts:
2590
if node in self._annotate_children:
2591
# We won't be building this node
2592
del self._annotate_children[node]
3498
if missing_versions:
3499
for key in missing_versions:
3500
if key in self._parent_map and key in self._text_cache:
3501
# We already have this text ready, we just need to
3502
# yield it later so we get it annotated
3504
parent_keys = self._parent_map[key]
3505
for parent_key in parent_keys:
3506
if parent_key in self._num_needed_children:
3507
self._num_needed_children[parent_key] += 1
3509
self._num_needed_children[parent_key] = 1
3510
pending.update([p for p in parent_keys
3511
if p not in self._all_build_details])
3513
raise errors.RevisionNotPresent(key, self._vf)
2593
3514
# Generally we will want to read the records in reverse order, because
2594
3515
# we find the parent nodes after the children
2595
3516
records.reverse()
2598
def _annotate_records(self, records):
2599
"""Build the annotations for the listed records."""
3517
return records, ann_keys
3519
def _get_needed_texts(self, key, pb=None):
3520
# if True or len(self._vf._fallback_vfs) > 0:
3521
if len(self._vf._fallback_vfs) > 0:
3522
# If we have fallbacks, go to the generic path
3523
for v in annotate.Annotator._get_needed_texts(self, key, pb=pb):
3528
records, ann_keys = self._get_build_graph(key)
3529
for idx, (sub_key, text, num_lines) in enumerate(
3530
self._extract_texts(records)):
3532
pb.update('annotating', idx, len(records))
3533
yield sub_key, text, num_lines
3534
for sub_key in ann_keys:
3535
text = self._text_cache[sub_key]
3536
num_lines = len(text) # bad assumption
3537
yield sub_key, text, num_lines
3539
except errors.RetryWithNewPacks, e:
3540
self._vf._access.reload_or_raise(e)
3541
# The cached build_details are no longer valid
3542
self._all_build_details.clear()
3544
def _cache_delta_blocks(self, key, compression_parent, delta, lines):
3545
parent_lines = self._text_cache[compression_parent]
3546
blocks = list(KnitContent.get_line_delta_blocks(delta, parent_lines, lines))
3547
self._matching_blocks[(key, compression_parent)] = blocks
3549
def _expand_record(self, key, parent_keys, compression_parent, record,
3552
if compression_parent:
3553
if compression_parent not in self._content_objects:
3554
# Waiting for the parent
3555
self._pending_deltas.setdefault(compression_parent, []).append(
3556
(key, parent_keys, record, record_details))
3558
# We have the basis parent, so expand the delta
3559
num = self._num_compression_children[compression_parent]
3562
base_content = self._content_objects.pop(compression_parent)
3563
self._num_compression_children.pop(compression_parent)
3565
self._num_compression_children[compression_parent] = num
3566
base_content = self._content_objects[compression_parent]
3567
# It is tempting to want to copy_base_content=False for the last
3568
# child object. However, whenever noeol=False,
3569
# self._text_cache[parent_key] is content._lines. So mutating it
3570
# gives very bad results.
3571
# The alternative is to copy the lines into text cache, but then we
3572
# are copying anyway, so just do it here.
3573
content, delta = self._vf._factory.parse_record(
3574
key, record, record_details, base_content,
3575
copy_base_content=True)
3578
content, _ = self._vf._factory.parse_record(
3579
key, record, record_details, None)
3580
if self._num_compression_children.get(key, 0) > 0:
3581
self._content_objects[key] = content
3582
lines = content.text()
3583
self._text_cache[key] = lines
3584
if delta is not None:
3585
self._cache_delta_blocks(key, compression_parent, delta, lines)
3588
def _get_parent_annotations_and_matches(self, key, text, parent_key):
3589
"""Get the list of annotations for the parent, and the matching lines.
3591
:param text: The opaque value given by _get_needed_texts
3592
:param parent_key: The key for the parent text
3593
:return: (parent_annotations, matching_blocks)
3594
parent_annotations is a list as long as the number of lines in
3596
matching_blocks is a list of (parent_idx, text_idx, len) tuples
3597
indicating which lines match between the two texts
3599
block_key = (key, parent_key)
3600
if block_key in self._matching_blocks:
3601
blocks = self._matching_blocks.pop(block_key)
3602
parent_annotations = self._annotations_cache[parent_key]
3603
return parent_annotations, blocks
3604
return annotate.Annotator._get_parent_annotations_and_matches(self,
3605
key, text, parent_key)
3607
def _process_pending(self, key):
3608
"""The content for 'key' was just processed.
3610
Determine if there is any more pending work to be processed.
3613
if key in self._pending_deltas:
3614
compression_parent = key
3615
children = self._pending_deltas.pop(key)
3616
for child_key, parent_keys, record, record_details in children:
3617
lines = self._expand_record(child_key, parent_keys,
3619
record, record_details)
3620
if self._check_ready_for_annotations(child_key, parent_keys):
3621
to_return.append(child_key)
3622
# Also check any children that are waiting for this parent to be
3624
if key in self._pending_annotation:
3625
children = self._pending_annotation.pop(key)
3626
to_return.extend([c for c, p_keys in children
3627
if self._check_ready_for_annotations(c, p_keys)])
3630
def _check_ready_for_annotations(self, key, parent_keys):
3631
"""return true if this text is ready to be yielded.
3633
Otherwise, this will return False, and queue the text into
3634
self._pending_annotation
3636
for parent_key in parent_keys:
3637
if parent_key not in self._annotations_cache:
3638
# still waiting on at least one parent text, so queue it up
3639
# Note that if there are multiple parents, we need to wait
3641
self._pending_annotation.setdefault(parent_key,
3642
[]).append((key, parent_keys))
3646
def _extract_texts(self, records):
3647
"""Extract the various texts needed based on records"""
2600
3648
# We iterate in the order read, rather than a strict order requested
2601
3649
# However, process what we can, and put off to the side things that
2602
3650
# still need parents, cleaning them up when those parents are
2604
for (rev_id, record,
2605
digest) in self._knit._read_records_iter(records):
2606
if rev_id in self._annotated_lines:
3653
# 1) As 'records' are read, see if we can expand these records into
3654
# Content objects (and thus lines)
3655
# 2) If a given line-delta is waiting on its compression parent, it
3656
# gets queued up into self._pending_deltas, otherwise we expand
3657
# it, and put it into self._text_cache and self._content_objects
3658
# 3) If we expanded the text, we will then check to see if all
3659
# parents have also been processed. If so, this text gets yielded,
3660
# else this record gets set aside into pending_annotation
3661
# 4) Further, if we expanded the text in (2), we will then check to
3662
# see if there are any children in self._pending_deltas waiting to
3663
# also be processed. If so, we go back to (2) for those
3664
# 5) Further again, if we yielded the text, we can then check if that
3665
# 'unlocks' any of the texts in pending_annotations, which should
3666
# then get yielded as well
3667
# Note that both steps 4 and 5 are 'recursive' in that unlocking one
3668
# compression child could unlock yet another, and yielding a fulltext
3669
# will also 'unlock' the children that are waiting on that annotation.
3670
# (Though also, unlocking 1 parent's fulltext, does not unlock a child
3671
# if other parents are also waiting.)
3672
# We want to yield content before expanding child content objects, so
3673
# that we know when we can re-use the content lines, and the annotation
3674
# code can know when it can stop caching fulltexts, as well.
3676
# Children that are missing their compression parent
3678
for (key, record, digest) in self._vf._read_records_iter(records):
3680
details = self._all_build_details[key]
3681
(_, compression_parent, parent_keys, record_details) = details
3682
lines = self._expand_record(key, parent_keys, compression_parent,
3683
record, record_details)
3685
# Pending delta should be queued up
2608
parent_ids = self._revision_id_graph[rev_id]
2609
parent_ids = [p for p in parent_ids if p not in self._ghosts]
2610
details = self._all_build_details[rev_id]
2611
(index_memo, compression_parent, parents,
2612
record_details) = details
2613
nodes_to_annotate = []
2614
# TODO: Remove the punning between compression parents, and
2615
# parent_ids, we should be able to do this without assuming
2617
if len(parent_ids) == 0:
2618
# There are no parents for this node, so just add it
2619
# TODO: This probably needs to be decoupled
2620
fulltext_content, delta = self._knit._factory.parse_record(
2621
rev_id, record, record_details, None)
2622
fulltext = self._add_fulltext_content(rev_id, fulltext_content)
2623
nodes_to_annotate.extend(self._add_annotation(rev_id, fulltext,
2624
parent_ids, left_matching_blocks=None))
2626
child = (rev_id, parent_ids, record)
2627
# Check if all the parents are present
2628
self._check_parents(child, nodes_to_annotate)
2629
while nodes_to_annotate:
2630
# Should we use a queue here instead of a stack?
2631
(rev_id, parent_ids, record) = nodes_to_annotate.pop()
2632
(index_memo, compression_parent, parents,
2633
record_details) = self._all_build_details[rev_id]
2634
if compression_parent is not None:
2635
comp_children = self._compression_children[compression_parent]
2636
if rev_id not in comp_children:
2637
raise AssertionError("%r not in compression children %r"
2638
% (rev_id, comp_children))
2639
# If there is only 1 child, it is safe to reuse this
2641
reuse_content = (len(comp_children) == 1
2642
and compression_parent not in
2643
self._nodes_to_keep_annotations)
2645
# Remove it from the cache since it will be changing
2646
parent_fulltext_content = self._fulltext_contents.pop(compression_parent)
2647
# Make sure to copy the fulltext since it might be
2649
parent_fulltext = list(parent_fulltext_content.text())
2651
parent_fulltext_content = self._fulltext_contents[compression_parent]
2652
parent_fulltext = parent_fulltext_content.text()
2653
comp_children.remove(rev_id)
2654
fulltext_content, delta = self._knit._factory.parse_record(
2655
rev_id, record, record_details,
2656
parent_fulltext_content,
2657
copy_base_content=(not reuse_content))
2658
fulltext = self._add_fulltext_content(rev_id,
2660
blocks = KnitContent.get_line_delta_blocks(delta,
2661
parent_fulltext, fulltext)
2663
fulltext_content = self._knit._factory.parse_fulltext(
2665
fulltext = self._add_fulltext_content(rev_id,
2668
nodes_to_annotate.extend(
2669
self._add_annotation(rev_id, fulltext, parent_ids,
2670
left_matching_blocks=blocks))
2672
def _get_heads_provider(self):
2673
"""Create a heads provider for resolving ancestry issues."""
2674
if self._heads_provider is not None:
2675
return self._heads_provider
2676
parent_provider = _mod_graph.DictParentsProvider(
2677
self._revision_id_graph)
2678
graph_obj = _mod_graph.Graph(parent_provider)
2679
head_cache = _mod_graph.FrozenHeadsCache(graph_obj)
2680
self._heads_provider = head_cache
2683
def annotate(self, key):
2684
"""Return the annotated fulltext at the given key.
2686
:param key: The key to annotate.
2688
if True or len(self._knit._fallback_vfs) > 0:
2689
# stacked knits can't use the fast path at present.
2690
return self._simple_annotate(key)
2691
records = self._get_build_graph(key)
2692
if key in self._ghosts:
2693
raise errors.RevisionNotPresent(key, self._knit)
2694
self._annotate_records(records)
2695
return self._annotated_lines[key]
2697
def _simple_annotate(self, key):
2698
"""Return annotated fulltext, rediffing from the full texts.
2700
This is slow but makes no assumptions about the repository
2701
being able to produce line deltas.
2703
# TODO: this code generates a parent maps of present ancestors; it
2704
# could be split out into a separate method, and probably should use
2705
# iter_ancestry instead. -- mbp and robertc 20080704
2706
graph = Graph(self._knit)
2707
head_cache = _mod_graph.FrozenHeadsCache(graph)
2708
search = graph._make_breadth_first_searcher([key])
2712
present, ghosts = search.next_with_ghosts()
2713
except StopIteration:
2715
keys.update(present)
2716
parent_map = self._knit.get_parent_map(keys)
2718
reannotate = annotate.reannotate
2719
for record in self._knit.get_record_stream(keys, 'topological', True):
2721
fulltext = split_lines(record.get_bytes_as('fulltext'))
2722
parents = parent_map[key]
2723
if parents is not None:
2724
parent_lines = [parent_cache[parent] for parent in parent_map[key]]
2727
parent_cache[key] = list(
2728
reannotate(parent_lines, fulltext, key, None, head_cache))
2730
return parent_cache[key]
2732
raise errors.RevisionNotPresent(key, self._knit)
3687
# At this point, we may be able to yield this content, if all
3688
# parents are also finished
3689
yield_this_text = self._check_ready_for_annotations(key,
3692
# All parents present
3693
yield key, lines, len(lines)
3694
to_process = self._process_pending(key)
3696
this_process = to_process
3698
for key in this_process:
3699
lines = self._text_cache[key]
3700
yield key, lines, len(lines)
3701
to_process.extend(self._process_pending(key))
2736
from bzrlib._knit_load_data_c import _load_data_c as _load_data
3704
from bzrlib._knit_load_data_pyx import _load_data_c as _load_data
2737
3705
except ImportError:
2738
3706
from bzrlib._knit_load_data_py import _load_data_py as _load_data