268
274
annotated_kind = ''
269
275
self.storage_kind = 'knit-%s%s-gz' % (annotated_kind, kind)
270
276
self._raw_record = raw_record
277
self._network_bytes = network_bytes
271
278
self._build_details = build_details
272
279
self._knit = knit
274
def get_bytes_as(self, storage_kind):
275
if storage_kind == self.storage_kind:
276
return self._raw_record
277
if storage_kind == 'fulltext' and self._knit is not None:
278
return self._knit.get_text(self.key[0])
280
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)]
284
410
class KnitContent(object):
285
411
"""Content of a knit version to which deltas can be applied.
287
413
This is always stored in memory as a list of lines with \n at the end,
288
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
289
415
corresponds to the on-disk knit representation.
970
1187
if not self.get_parent_map([key]):
971
1188
raise RevisionNotPresent(key, self)
972
1189
return cached_version
973
text_map, contents_map = self._get_content_maps([key])
974
return contents_map[key]
976
def _get_content_maps(self, keys, nonlocal_keys=None):
977
"""Produce maps of text and KnitContents
979
:param keys: The keys to produce content maps for.
980
:param nonlocal_keys: An iterable of keys(possibly intersecting keys)
981
which are known to not be in this knit, but rather in one of the
983
:return: (text_map, content_map) where text_map contains the texts for
984
the requested versions and content_map contains the KnitContents.
986
# FUTURE: This function could be improved for the 'extract many' case
987
# by tracking each component and only doing the copy when the number of
988
# children than need to apply delta's to it is > 1 or it is part of the
991
multiple_versions = len(keys) != 1
992
record_map = self._get_record_map(keys, allow_missing=True)
997
if nonlocal_keys is None:
998
nonlocal_keys = set()
1000
nonlocal_keys = frozenset(nonlocal_keys)
1001
missing_keys = set(nonlocal_keys)
1002
for source in self._fallback_vfs:
1003
if not missing_keys:
1005
for record in source.get_record_stream(missing_keys,
1007
if record.storage_kind == 'absent':
1009
missing_keys.remove(record.key)
1010
lines = split_lines(record.get_bytes_as('fulltext'))
1011
text_map[record.key] = lines
1012
content_map[record.key] = PlainKnitContent(lines, record.key)
1013
if record.key in keys:
1014
final_content[record.key] = content_map[record.key]
1016
if key in nonlocal_keys:
1021
while cursor is not None:
1023
record, record_details, digest, next = record_map[cursor]
1025
raise RevisionNotPresent(cursor, self)
1026
components.append((cursor, record, record_details, digest))
1028
if cursor in content_map:
1029
# no need to plan further back
1030
components.append((cursor, None, None, None))
1034
for (component_id, record, record_details,
1035
digest) in reversed(components):
1036
if component_id in content_map:
1037
content = content_map[component_id]
1039
content, delta = self._factory.parse_record(key[-1],
1040
record, record_details, content,
1041
copy_base_content=multiple_versions)
1042
if multiple_versions:
1043
content_map[component_id] = content
1045
final_content[key] = content
1047
# digest here is the digest from the last applied component.
1048
text = content.text()
1049
actual_sha = sha_strings(text)
1050
if actual_sha != digest:
1051
raise KnitCorrupt(self,
1053
'\n of reconstructed text does not match'
1055
'\n for version %s' %
1056
(actual_sha, digest, key))
1057
text_map[key] = text
1058
return text_map, final_content
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
kg = _mod_graph.KnownGraph(parent_map)
1060
1199
def get_parent_map(self, keys):
1061
1200
"""Get a map of the graph parents of keys.
1103
1242
build-parent of the version, i.e. the leftmost ancestor.
1104
1243
Will be None if the record is not a delta.
1105
1244
:param keys: The keys to build a map for
1106
:param allow_missing: If some records are missing, rather than
1245
:param allow_missing: If some records are missing, rather than
1107
1246
error, just return the data that could be generated.
1109
position_map = self._get_components_positions(keys,
1248
raw_map = self._get_record_map_unparsed(keys,
1110
1249
allow_missing=allow_missing)
1111
# key = component_id, r = record_details, i_m = index_memo, n = next
1112
records = [(key, i_m) for key, (r, i_m, n)
1113
in position_map.iteritems()]
1115
for key, record, digest in \
1116
self._read_records_iter(records):
1117
(record_details, index_memo, next) = position_map[key]
1118
record_map[key] = record, record_details, digest, next
1250
return self._raw_map_to_record_map(raw_map)
1252
def _raw_map_to_record_map(self, raw_map):
1253
"""Parse the contents of _get_record_map_unparsed.
1255
:return: see _get_record_map.
1259
data, record_details, next = raw_map[key]
1260
content, digest = self._parse_record(key[-1], data)
1261
result[key] = content, record_details, digest, next
1264
def _get_record_map_unparsed(self, keys, allow_missing=False):
1265
"""Get the raw data for reconstructing keys without parsing it.
1267
:return: A dict suitable for parsing via _raw_map_to_record_map.
1268
key-> raw_bytes, (method, noeol), compression_parent
1270
# This retries the whole request if anything fails. Potentially we
1271
# could be a bit more selective. We could track the keys whose records
1272
# we have successfully found, and then only request the new records
1273
# from there. However, _get_components_positions grabs the whole build
1274
# chain, which means we'll likely try to grab the same records again
1275
# anyway. Also, can the build chains change as part of a pack
1276
# operation? We wouldn't want to end up with a broken chain.
1279
position_map = self._get_components_positions(keys,
1280
allow_missing=allow_missing)
1281
# key = component_id, r = record_details, i_m = index_memo,
1283
records = [(key, i_m) for key, (r, i_m, n)
1284
in position_map.iteritems()]
1285
# Sort by the index memo, so that we request records from the
1286
# same pack file together, and in forward-sorted order
1287
records.sort(key=operator.itemgetter(1))
1289
for key, data in self._read_records_iter_unchecked(records):
1290
(record_details, index_memo, next) = position_map[key]
1291
raw_record_map[key] = data, record_details, next
1292
return raw_record_map
1293
except errors.RetryWithNewPacks, e:
1294
self._access.reload_or_raise(e)
1297
def _split_by_prefix(cls, keys):
1298
"""For the given keys, split them up based on their prefix.
1300
To keep memory pressure somewhat under control, split the
1301
requests back into per-file-id requests, otherwise "bzr co"
1302
extracts the full tree into memory before writing it to disk.
1303
This should be revisited if _get_content_maps() can ever cross
1306
The keys for a given file_id are kept in the same relative order.
1307
Ordering between file_ids is not, though prefix_order will return the
1308
order that the key was first seen.
1310
:param keys: An iterable of key tuples
1311
:return: (split_map, prefix_order)
1312
split_map A dictionary mapping prefix => keys
1313
prefix_order The order that we saw the various prefixes
1315
split_by_prefix = {}
1323
if prefix in split_by_prefix:
1324
split_by_prefix[prefix].append(key)
1326
split_by_prefix[prefix] = [key]
1327
prefix_order.append(prefix)
1328
return split_by_prefix, prefix_order
1330
def _group_keys_for_io(self, keys, non_local_keys, positions,
1331
_min_buffer_size=_STREAM_MIN_BUFFER_SIZE):
1332
"""For the given keys, group them into 'best-sized' requests.
1334
The idea is to avoid making 1 request per file, but to never try to
1335
unpack an entire 1.5GB source tree in a single pass. Also when
1336
possible, we should try to group requests to the same pack file
1339
:return: list of (keys, non_local) tuples that indicate what keys
1340
should be fetched next.
1342
# TODO: Ideally we would group on 2 factors. We want to extract texts
1343
# from the same pack file together, and we want to extract all
1344
# the texts for a given build-chain together. Ultimately it
1345
# probably needs a better global view.
1346
total_keys = len(keys)
1347
prefix_split_keys, prefix_order = self._split_by_prefix(keys)
1348
prefix_split_non_local_keys, _ = self._split_by_prefix(non_local_keys)
1350
cur_non_local = set()
1354
for prefix in prefix_order:
1355
keys = prefix_split_keys[prefix]
1356
non_local = prefix_split_non_local_keys.get(prefix, [])
1358
this_size = self._index._get_total_build_size(keys, positions)
1359
cur_size += this_size
1360
cur_keys.extend(keys)
1361
cur_non_local.update(non_local)
1362
if cur_size > _min_buffer_size:
1363
result.append((cur_keys, cur_non_local))
1364
sizes.append(cur_size)
1366
cur_non_local = set()
1369
result.append((cur_keys, cur_non_local))
1370
sizes.append(cur_size)
1121
1373
def get_record_stream(self, keys, ordering, include_delta_closure):
1122
1374
"""Get a stream of records for keys.
1327
1641
access_memo = self._access.add_raw_records(
1328
1642
[(record.key, len(bytes))], bytes)[0]
1329
1643
index_entry = (record.key, options, access_memo, parents)
1331
1644
if 'fulltext' not in options:
1332
basis_parent = parents[0]
1645
# Not a fulltext, so we need to make sure the compression
1646
# parent will also be present.
1333
1647
# Note that pack backed knits don't need to buffer here
1334
1648
# because they buffer all writes to the transaction level,
1335
1649
# but we don't expose that difference at the index level. If
1336
1650
# the query here has sufficient cost to show up in
1337
1651
# profiling we should do that.
1338
if basis_parent not in self.get_parent_map([basis_parent]):
1653
# They're required to be physically in this
1654
# KnitVersionedFiles, not in a fallback.
1655
if not self._index.has_key(compression_parent):
1339
1656
pending = buffered_index_entries.setdefault(
1657
compression_parent, [])
1341
1658
pending.append(index_entry)
1342
1659
buffered = True
1343
1660
if not buffered:
1344
1661
self._index.add_records([index_entry])
1345
elif record.storage_kind == 'fulltext':
1662
elif record.storage_kind == 'chunked':
1346
1663
self.add_lines(record.key, parents,
1347
split_lines(record.get_bytes_as('fulltext')))
1664
osutils.chunks_to_lines(record.get_bytes_as('chunked')))
1349
adapter_key = record.storage_kind, 'fulltext'
1350
adapter = get_adapter(adapter_key)
1351
lines = split_lines(adapter.get_bytes(
1352
record, record.get_bytes_as(record.storage_kind)))
1666
# Not suitable for direct insertion as a
1667
# delta, either because it's not the right format, or this
1668
# KnitVersionedFiles doesn't permit deltas (_max_delta_chain ==
1669
# 0) or because it depends on a base only present in the
1671
self._access.flush()
1673
# Try getting a fulltext directly from the record.
1674
bytes = record.get_bytes_as('fulltext')
1675
except errors.UnavailableRepresentation:
1676
adapter_key = record.storage_kind, 'fulltext'
1677
adapter = get_adapter(adapter_key)
1678
bytes = adapter.get_bytes(record)
1679
lines = split_lines(bytes)
1354
1681
self.add_lines(record.key, parents, lines)
1355
1682
except errors.RevisionAlreadyPresent:
1357
1684
# Add any records whose basis parent is now available.
1358
added_keys = [record.key]
1360
key = added_keys.pop(0)
1361
if key in buffered_index_entries:
1362
index_entries = buffered_index_entries[key]
1363
self._index.add_records(index_entries)
1365
[index_entry[0] for index_entry in index_entries])
1366
del buffered_index_entries[key]
1367
# If there were any deltas which had a missing basis parent, error.
1686
added_keys = [record.key]
1688
key = added_keys.pop(0)
1689
if key in buffered_index_entries:
1690
index_entries = buffered_index_entries[key]
1691
self._index.add_records(index_entries)
1693
[index_entry[0] for index_entry in index_entries])
1694
del buffered_index_entries[key]
1368
1695
if buffered_index_entries:
1369
raise errors.RevisionNotPresent(buffered_index_entries.keys()[0],
1696
# There were index entries buffered at the end of the stream,
1697
# So these need to be added (if the index supports holding such
1698
# entries for later insertion)
1699
for key in buffered_index_entries:
1700
index_entries = buffered_index_entries[key]
1701
self._index.add_records(index_entries,
1702
missing_compression_parents=True)
1704
def get_missing_compression_parent_keys(self):
1705
"""Return an iterable of keys of missing compression parents.
1707
Check this after calling insert_record_stream to find out if there are
1708
any missing compression parents. If there are, the records that
1709
depend on them are not able to be inserted safely. For atomic
1710
KnitVersionedFiles built on packs, the transaction should be aborted or
1711
suspended - commit will fail at this point. Nonatomic knits will error
1712
earlier because they have no staging area to put pending entries into.
1714
return self._index.get_missing_compression_parents()
1372
1716
def iter_lines_added_or_present_in_keys(self, keys, pb=None):
1373
1717
"""Iterate over the lines in the versioned files from keys.
2007
class _ContentMapGenerator(object):
2008
"""Generate texts or expose raw deltas for a set of texts."""
2010
def __init__(self, ordering='unordered'):
2011
self._ordering = ordering
2013
def _get_content(self, key):
2014
"""Get the content object for key."""
2015
# Note that _get_content is only called when the _ContentMapGenerator
2016
# has been constructed with just one key requested for reconstruction.
2017
if key in self.nonlocal_keys:
2018
record = self.get_record_stream().next()
2019
# Create a content object on the fly
2020
lines = osutils.chunks_to_lines(record.get_bytes_as('chunked'))
2021
return PlainKnitContent(lines, record.key)
2023
# local keys we can ask for directly
2024
return self._get_one_work(key)
2026
def get_record_stream(self):
2027
"""Get a record stream for the keys requested during __init__."""
2028
for record in self._work():
2032
"""Produce maps of text and KnitContents as dicts.
2034
:return: (text_map, content_map) where text_map contains the texts for
2035
the requested versions and content_map contains the KnitContents.
2037
# NB: By definition we never need to read remote sources unless texts
2038
# are requested from them: we don't delta across stores - and we
2039
# explicitly do not want to to prevent data loss situations.
2040
if self.global_map is None:
2041
self.global_map = self.vf.get_parent_map(self.keys)
2042
nonlocal_keys = self.nonlocal_keys
2044
missing_keys = set(nonlocal_keys)
2045
# Read from remote versioned file instances and provide to our caller.
2046
for source in self.vf._fallback_vfs:
2047
if not missing_keys:
2049
# Loop over fallback repositories asking them for texts - ignore
2050
# any missing from a particular fallback.
2051
for record in source.get_record_stream(missing_keys,
2052
self._ordering, True):
2053
if record.storage_kind == 'absent':
2054
# Not in thie particular stream, may be in one of the
2055
# other fallback vfs objects.
2057
missing_keys.remove(record.key)
2060
if self._raw_record_map is None:
2061
raise AssertionError('_raw_record_map should have been filled')
2063
for key in self.keys:
2064
if key in self.nonlocal_keys:
2066
yield LazyKnitContentFactory(key, self.global_map[key], self, first)
2069
def _get_one_work(self, requested_key):
2070
# Now, if we have calculated everything already, just return the
2072
if requested_key in self._contents_map:
2073
return self._contents_map[requested_key]
2074
# To simplify things, parse everything at once - code that wants one text
2075
# probably wants them all.
2076
# FUTURE: This function could be improved for the 'extract many' case
2077
# by tracking each component and only doing the copy when the number of
2078
# children than need to apply delta's to it is > 1 or it is part of the
2080
multiple_versions = len(self.keys) != 1
2081
if self._record_map is None:
2082
self._record_map = self.vf._raw_map_to_record_map(
2083
self._raw_record_map)
2084
record_map = self._record_map
2085
# raw_record_map is key:
2086
# Have read and parsed records at this point.
2087
for key in self.keys:
2088
if key in self.nonlocal_keys:
2093
while cursor is not None:
2095
record, record_details, digest, next = record_map[cursor]
2097
raise RevisionNotPresent(cursor, self)
2098
components.append((cursor, record, record_details, digest))
2100
if cursor in self._contents_map:
2101
# no need to plan further back
2102
components.append((cursor, None, None, None))
2106
for (component_id, record, record_details,
2107
digest) in reversed(components):
2108
if component_id in self._contents_map:
2109
content = self._contents_map[component_id]
2111
content, delta = self._factory.parse_record(key[-1],
2112
record, record_details, content,
2113
copy_base_content=multiple_versions)
2114
if multiple_versions:
2115
self._contents_map[component_id] = content
2117
# digest here is the digest from the last applied component.
2118
text = content.text()
2119
actual_sha = sha_strings(text)
2120
if actual_sha != digest:
2121
raise SHA1KnitCorrupt(self, actual_sha, digest, key, text)
2122
if multiple_versions:
2123
return self._contents_map[requested_key]
2127
def _wire_bytes(self):
2128
"""Get the bytes to put on the wire for 'key'.
2130
The first collection of bytes asked for returns the serialised
2131
raw_record_map and the additional details (key, parent) for key.
2132
Subsequent calls return just the additional details (key, parent).
2133
The wire storage_kind given for the first key is 'knit-delta-closure',
2134
For subsequent keys it is 'knit-delta-closure-ref'.
2136
:param key: A key from the content generator.
2137
:return: Bytes to put on the wire.
2140
# kind marker for dispatch on the far side,
2141
lines.append('knit-delta-closure')
2143
if self.vf._factory.annotated:
2144
lines.append('annotated')
2147
# then the list of keys
2148
lines.append('\t'.join(['\x00'.join(key) for key in self.keys
2149
if key not in self.nonlocal_keys]))
2150
# then the _raw_record_map in serialised form:
2152
# for each item in the map:
2154
# 1 line with parents if the key is to be yielded (None: for None, '' for ())
2155
# one line with method
2156
# one line with noeol
2157
# one line with next ('' for None)
2158
# one line with byte count of the record bytes
2160
for key, (record_bytes, (method, noeol), next) in \
2161
self._raw_record_map.iteritems():
2162
key_bytes = '\x00'.join(key)
2163
parents = self.global_map.get(key, None)
2165
parent_bytes = 'None:'
2167
parent_bytes = '\t'.join('\x00'.join(key) for key in parents)
2168
method_bytes = method
2174
next_bytes = '\x00'.join(next)
2177
map_byte_list.append('%s\n%s\n%s\n%s\n%s\n%d\n%s' % (
2178
key_bytes, parent_bytes, method_bytes, noeol_bytes, next_bytes,
2179
len(record_bytes), record_bytes))
2180
map_bytes = ''.join(map_byte_list)
2181
lines.append(map_bytes)
2182
bytes = '\n'.join(lines)
2186
class _VFContentMapGenerator(_ContentMapGenerator):
2187
"""Content map generator reading from a VersionedFiles object."""
2189
def __init__(self, versioned_files, keys, nonlocal_keys=None,
2190
global_map=None, raw_record_map=None, ordering='unordered'):
2191
"""Create a _ContentMapGenerator.
2193
:param versioned_files: The versioned files that the texts are being
2195
:param keys: The keys to produce content maps for.
2196
:param nonlocal_keys: An iterable of keys(possibly intersecting keys)
2197
which are known to not be in this knit, but rather in one of the
2199
:param global_map: The result of get_parent_map(keys) (or a supermap).
2200
This is required if get_record_stream() is to be used.
2201
:param raw_record_map: A unparsed raw record map to use for answering
2204
_ContentMapGenerator.__init__(self, ordering=ordering)
2205
# The vf to source data from
2206
self.vf = versioned_files
2208
self.keys = list(keys)
2209
# Keys known to be in fallback vfs objects
2210
if nonlocal_keys is None:
2211
self.nonlocal_keys = set()
2213
self.nonlocal_keys = frozenset(nonlocal_keys)
2214
# Parents data for keys to be returned in get_record_stream
2215
self.global_map = global_map
2216
# The chunked lists for self.keys in text form
2218
# A cache of KnitContent objects used in extracting texts.
2219
self._contents_map = {}
2220
# All the knit records needed to assemble the requested keys as full
2222
self._record_map = None
2223
if raw_record_map is None:
2224
self._raw_record_map = self.vf._get_record_map_unparsed(keys,
2227
self._raw_record_map = raw_record_map
2228
# the factory for parsing records
2229
self._factory = self.vf._factory
2232
class _NetworkContentMapGenerator(_ContentMapGenerator):
2233
"""Content map generator sourced from a network stream."""
2235
def __init__(self, bytes, line_end):
2236
"""Construct a _NetworkContentMapGenerator from a bytes block."""
2238
self.global_map = {}
2239
self._raw_record_map = {}
2240
self._contents_map = {}
2241
self._record_map = None
2242
self.nonlocal_keys = []
2243
# Get access to record parsing facilities
2244
self.vf = KnitVersionedFiles(None, None)
2247
line_end = bytes.find('\n', start)
2248
line = bytes[start:line_end]
2249
start = line_end + 1
2250
if line == 'annotated':
2251
self._factory = KnitAnnotateFactory()
2253
self._factory = KnitPlainFactory()
2254
# list of keys to emit in get_record_stream
2255
line_end = bytes.find('\n', start)
2256
line = bytes[start:line_end]
2257
start = line_end + 1
2259
tuple(segment.split('\x00')) for segment in line.split('\t')
2261
# now a loop until the end. XXX: It would be nice if this was just a
2262
# bunch of the same records as get_record_stream(..., False) gives, but
2263
# there is a decent sized gap stopping that at the moment.
2267
line_end = bytes.find('\n', start)
2268
key = tuple(bytes[start:line_end].split('\x00'))
2269
start = line_end + 1
2270
# 1 line with parents (None: for None, '' for ())
2271
line_end = bytes.find('\n', start)
2272
line = bytes[start:line_end]
2277
[tuple(segment.split('\x00')) for segment in line.split('\t')
2279
self.global_map[key] = parents
2280
start = line_end + 1
2281
# one line with method
2282
line_end = bytes.find('\n', start)
2283
line = bytes[start:line_end]
2285
start = line_end + 1
2286
# one line with noeol
2287
line_end = bytes.find('\n', start)
2288
line = bytes[start:line_end]
2290
start = line_end + 1
2291
# one line with next ('' for None)
2292
line_end = bytes.find('\n', start)
2293
line = bytes[start:line_end]
2297
next = tuple(bytes[start:line_end].split('\x00'))
2298
start = line_end + 1
2299
# one line with byte count of the record bytes
2300
line_end = bytes.find('\n', start)
2301
line = bytes[start:line_end]
2303
start = line_end + 1
2305
record_bytes = bytes[start:start+count]
2306
start = start + count
2308
self._raw_record_map[key] = (record_bytes, (method, noeol), next)
2310
def get_record_stream(self):
2311
"""Get a record stream for for keys requested by the bytestream."""
2313
for key in self.keys:
2314
yield LazyKnitContentFactory(key, self.global_map[key], self, first)
2317
def _wire_bytes(self):
1640
2321
class _KndxIndex(object):
1641
2322
"""Manages knit index files
2430
3388
annotator = _KnitAnnotator(knit)
2431
return iter(annotator.annotate(revision_id))
2434
class _KnitAnnotator(object):
3389
return iter(annotator.annotate_flat(revision_id))
3392
class _KnitAnnotator(annotate.Annotator):
2435
3393
"""Build up the annotations for a text."""
2437
def __init__(self, knit):
2440
# Content objects, differs from fulltexts because of how final newlines
2441
# are treated by knits. the content objects here will always have a
2443
self._fulltext_contents = {}
2445
# Annotated lines of specific revisions
2446
self._annotated_lines = {}
2448
# Track the raw data for nodes that we could not process yet.
2449
# This maps the revision_id of the base to a list of children that will
2450
# annotated from it.
2451
self._pending_children = {}
2453
# Nodes which cannot be extracted
2454
self._ghosts = set()
2456
# Track how many children this node has, so we know if we need to keep
2458
self._annotate_children = {}
2459
self._compression_children = {}
3395
def __init__(self, vf):
3396
annotate.Annotator.__init__(self, vf)
3398
# TODO: handle Nodes which cannot be extracted
3399
# self._ghosts = set()
3401
# Map from (key, parent_key) => matching_blocks, should be 'use once'
3402
self._matching_blocks = {}
3404
# KnitContent objects
3405
self._content_objects = {}
3406
# The number of children that depend on this fulltext content object
3407
self._num_compression_children = {}
3408
# Delta records that need their compression parent before they can be
3410
self._pending_deltas = {}
3411
# Fulltext records that are waiting for their parents fulltexts before
3412
# they can be yielded for annotation
3413
self._pending_annotation = {}
2461
3415
self._all_build_details = {}
2462
# The children => parent revision_id graph
2463
self._revision_id_graph = {}
2465
self._heads_provider = None
2467
self._nodes_to_keep_annotations = set()
2468
self._generations_until_keep = 100
2470
def set_generations_until_keep(self, value):
2471
"""Set the number of generations before caching a node.
2473
Setting this to -1 will cache every merge node, setting this higher
2474
will cache fewer nodes.
2476
self._generations_until_keep = value
2478
def _add_fulltext_content(self, revision_id, content_obj):
2479
self._fulltext_contents[revision_id] = content_obj
2480
# TODO: jam 20080305 It might be good to check the sha1digest here
2481
return content_obj.text()
2483
def _check_parents(self, child, nodes_to_annotate):
2484
"""Check if all parents have been processed.
2486
:param child: A tuple of (rev_id, parents, raw_content)
2487
:param nodes_to_annotate: If child is ready, add it to
2488
nodes_to_annotate, otherwise put it back in self._pending_children
2490
for parent_id in child[1]:
2491
if (parent_id not in self._annotated_lines):
2492
# This parent is present, but another parent is missing
2493
self._pending_children.setdefault(parent_id,
2497
# This one is ready to be processed
2498
nodes_to_annotate.append(child)
2500
def _add_annotation(self, revision_id, fulltext, parent_ids,
2501
left_matching_blocks=None):
2502
"""Add an annotation entry.
2504
All parents should already have been annotated.
2505
:return: A list of children that now have their parents satisfied.
2507
a = self._annotated_lines
2508
annotated_parent_lines = [a[p] for p in parent_ids]
2509
annotated_lines = list(annotate.reannotate(annotated_parent_lines,
2510
fulltext, revision_id, left_matching_blocks,
2511
heads_provider=self._get_heads_provider()))
2512
self._annotated_lines[revision_id] = annotated_lines
2513
for p in parent_ids:
2514
ann_children = self._annotate_children[p]
2515
ann_children.remove(revision_id)
2516
if (not ann_children
2517
and p not in self._nodes_to_keep_annotations):
2518
del self._annotated_lines[p]
2519
del self._all_build_details[p]
2520
if p in self._fulltext_contents:
2521
del self._fulltext_contents[p]
2522
# Now that we've added this one, see if there are any pending
2523
# deltas to be done, certainly this parent is finished
2524
nodes_to_annotate = []
2525
for child in self._pending_children.pop(revision_id, []):
2526
self._check_parents(child, nodes_to_annotate)
2527
return nodes_to_annotate
2529
3417
def _get_build_graph(self, key):
2530
3418
"""Get the graphs for building texts and annotations.
2537
3425
:return: A list of (key, index_memo) records, suitable for
2538
passing to read_records_iter to start reading in the raw data fro/
3426
passing to read_records_iter to start reading in the raw data from
2541
if key in self._annotated_lines:
2544
3429
pending = set([key])
3432
self._num_needed_children[key] = 1
2549
3434
# get all pending nodes
2551
3435
this_iteration = pending
2552
build_details = self._knit._index.get_build_details(this_iteration)
3436
build_details = self._vf._index.get_build_details(this_iteration)
2553
3437
self._all_build_details.update(build_details)
2554
# new_nodes = self._knit._index._get_entries(this_iteration)
3438
# new_nodes = self._vf._index._get_entries(this_iteration)
2555
3439
pending = set()
2556
3440
for key, details in build_details.iteritems():
2557
(index_memo, compression_parent, parents,
3441
(index_memo, compression_parent, parent_keys,
2558
3442
record_details) = details
2559
self._revision_id_graph[key] = parents
3443
self._parent_map[key] = parent_keys
3444
self._heads_provider = None
2560
3445
records.append((key, index_memo))
2561
3446
# Do we actually need to check _annotated_lines?
2562
pending.update(p for p in parents
2563
if p not in self._all_build_details)
3447
pending.update([p for p in parent_keys
3448
if p not in self._all_build_details])
3450
for parent_key in parent_keys:
3451
if parent_key in self._num_needed_children:
3452
self._num_needed_children[parent_key] += 1
3454
self._num_needed_children[parent_key] = 1
2564
3455
if compression_parent:
2565
self._compression_children.setdefault(compression_parent,
2568
for parent in parents:
2569
self._annotate_children.setdefault(parent,
2571
num_gens = generation - kept_generation
2572
if ((num_gens >= self._generations_until_keep)
2573
and len(parents) > 1):
2574
kept_generation = generation
2575
self._nodes_to_keep_annotations.add(key)
3456
if compression_parent in self._num_compression_children:
3457
self._num_compression_children[compression_parent] += 1
3459
self._num_compression_children[compression_parent] = 1
2577
3461
missing_versions = this_iteration.difference(build_details.keys())
2578
self._ghosts.update(missing_versions)
2579
for missing_version in missing_versions:
2580
# add a key, no parents
2581
self._revision_id_graph[missing_version] = ()
2582
pending.discard(missing_version) # don't look for it
2583
if self._ghosts.intersection(self._compression_children):
2585
"We cannot have nodes which have a ghost compression parent:\n"
2587
"compression children: %r"
2588
% (self._ghosts, self._compression_children))
2589
# Cleanout anything that depends on a ghost so that we don't wait for
2590
# the ghost to show up
2591
for node in self._ghosts:
2592
if node in self._annotate_children:
2593
# We won't be building this node
2594
del self._annotate_children[node]
3462
if missing_versions:
3463
for key in missing_versions:
3464
if key in self._parent_map and key in self._text_cache:
3465
# We already have this text ready, we just need to
3466
# yield it later so we get it annotated
3468
parent_keys = self._parent_map[key]
3469
for parent_key in parent_keys:
3470
if parent_key in self._num_needed_children:
3471
self._num_needed_children[parent_key] += 1
3473
self._num_needed_children[parent_key] = 1
3474
pending.update([p for p in parent_keys
3475
if p not in self._all_build_details])
3477
raise errors.RevisionNotPresent(key, self._vf)
2595
3478
# Generally we will want to read the records in reverse order, because
2596
3479
# we find the parent nodes after the children
2597
3480
records.reverse()
2600
def _annotate_records(self, records):
2601
"""Build the annotations for the listed records."""
3481
return records, ann_keys
3483
def _get_needed_texts(self, key, pb=None):
3484
# if True or len(self._vf._fallback_vfs) > 0:
3485
if len(self._vf._fallback_vfs) > 0:
3486
# If we have fallbacks, go to the generic path
3487
for v in annotate.Annotator._get_needed_texts(self, key, pb=pb):
3492
records, ann_keys = self._get_build_graph(key)
3493
for idx, (sub_key, text, num_lines) in enumerate(
3494
self._extract_texts(records)):
3496
pb.update('annotating', idx, len(records))
3497
yield sub_key, text, num_lines
3498
for sub_key in ann_keys:
3499
text = self._text_cache[sub_key]
3500
num_lines = len(text) # bad assumption
3501
yield sub_key, text, num_lines
3503
except errors.RetryWithNewPacks, e:
3504
self._vf._access.reload_or_raise(e)
3505
# The cached build_details are no longer valid
3506
self._all_build_details.clear()
3508
def _cache_delta_blocks(self, key, compression_parent, delta, lines):
3509
parent_lines = self._text_cache[compression_parent]
3510
blocks = list(KnitContent.get_line_delta_blocks(delta, parent_lines, lines))
3511
self._matching_blocks[(key, compression_parent)] = blocks
3513
def _expand_record(self, key, parent_keys, compression_parent, record,
3516
if compression_parent:
3517
if compression_parent not in self._content_objects:
3518
# Waiting for the parent
3519
self._pending_deltas.setdefault(compression_parent, []).append(
3520
(key, parent_keys, record, record_details))
3522
# We have the basis parent, so expand the delta
3523
num = self._num_compression_children[compression_parent]
3526
base_content = self._content_objects.pop(compression_parent)
3527
self._num_compression_children.pop(compression_parent)
3529
self._num_compression_children[compression_parent] = num
3530
base_content = self._content_objects[compression_parent]
3531
# It is tempting to want to copy_base_content=False for the last
3532
# child object. However, whenever noeol=False,
3533
# self._text_cache[parent_key] is content._lines. So mutating it
3534
# gives very bad results.
3535
# The alternative is to copy the lines into text cache, but then we
3536
# are copying anyway, so just do it here.
3537
content, delta = self._vf._factory.parse_record(
3538
key, record, record_details, base_content,
3539
copy_base_content=True)
3542
content, _ = self._vf._factory.parse_record(
3543
key, record, record_details, None)
3544
if self._num_compression_children.get(key, 0) > 0:
3545
self._content_objects[key] = content
3546
lines = content.text()
3547
self._text_cache[key] = lines
3548
if delta is not None:
3549
self._cache_delta_blocks(key, compression_parent, delta, lines)
3552
def _get_parent_annotations_and_matches(self, key, text, parent_key):
3553
"""Get the list of annotations for the parent, and the matching lines.
3555
:param text: The opaque value given by _get_needed_texts
3556
:param parent_key: The key for the parent text
3557
:return: (parent_annotations, matching_blocks)
3558
parent_annotations is a list as long as the number of lines in
3560
matching_blocks is a list of (parent_idx, text_idx, len) tuples
3561
indicating which lines match between the two texts
3563
block_key = (key, parent_key)
3564
if block_key in self._matching_blocks:
3565
blocks = self._matching_blocks.pop(block_key)
3566
parent_annotations = self._annotations_cache[parent_key]
3567
return parent_annotations, blocks
3568
return annotate.Annotator._get_parent_annotations_and_matches(self,
3569
key, text, parent_key)
3571
def _process_pending(self, key):
3572
"""The content for 'key' was just processed.
3574
Determine if there is any more pending work to be processed.
3577
if key in self._pending_deltas:
3578
compression_parent = key
3579
children = self._pending_deltas.pop(key)
3580
for child_key, parent_keys, record, record_details in children:
3581
lines = self._expand_record(child_key, parent_keys,
3583
record, record_details)
3584
if self._check_ready_for_annotations(child_key, parent_keys):
3585
to_return.append(child_key)
3586
# Also check any children that are waiting for this parent to be
3588
if key in self._pending_annotation:
3589
children = self._pending_annotation.pop(key)
3590
to_return.extend([c for c, p_keys in children
3591
if self._check_ready_for_annotations(c, p_keys)])
3594
def _check_ready_for_annotations(self, key, parent_keys):
3595
"""return true if this text is ready to be yielded.
3597
Otherwise, this will return False, and queue the text into
3598
self._pending_annotation
3600
for parent_key in parent_keys:
3601
if parent_key not in self._annotations_cache:
3602
# still waiting on at least one parent text, so queue it up
3603
# Note that if there are multiple parents, we need to wait
3605
self._pending_annotation.setdefault(parent_key,
3606
[]).append((key, parent_keys))
3610
def _extract_texts(self, records):
3611
"""Extract the various texts needed based on records"""
2602
3612
# We iterate in the order read, rather than a strict order requested
2603
3613
# However, process what we can, and put off to the side things that
2604
3614
# still need parents, cleaning them up when those parents are
2606
for (rev_id, record,
2607
digest) in self._knit._read_records_iter(records):
2608
if rev_id in self._annotated_lines:
3617
# 1) As 'records' are read, see if we can expand these records into
3618
# Content objects (and thus lines)
3619
# 2) If a given line-delta is waiting on its compression parent, it
3620
# gets queued up into self._pending_deltas, otherwise we expand
3621
# it, and put it into self._text_cache and self._content_objects
3622
# 3) If we expanded the text, we will then check to see if all
3623
# parents have also been processed. If so, this text gets yielded,
3624
# else this record gets set aside into pending_annotation
3625
# 4) Further, if we expanded the text in (2), we will then check to
3626
# see if there are any children in self._pending_deltas waiting to
3627
# also be processed. If so, we go back to (2) for those
3628
# 5) Further again, if we yielded the text, we can then check if that
3629
# 'unlocks' any of the texts in pending_annotations, which should
3630
# then get yielded as well
3631
# Note that both steps 4 and 5 are 'recursive' in that unlocking one
3632
# compression child could unlock yet another, and yielding a fulltext
3633
# will also 'unlock' the children that are waiting on that annotation.
3634
# (Though also, unlocking 1 parent's fulltext, does not unlock a child
3635
# if other parents are also waiting.)
3636
# We want to yield content before expanding child content objects, so
3637
# that we know when we can re-use the content lines, and the annotation
3638
# code can know when it can stop caching fulltexts, as well.
3640
# Children that are missing their compression parent
3642
for (key, record, digest) in self._vf._read_records_iter(records):
3644
details = self._all_build_details[key]
3645
(_, compression_parent, parent_keys, record_details) = details
3646
lines = self._expand_record(key, parent_keys, compression_parent,
3647
record, record_details)
3649
# Pending delta should be queued up
2610
parent_ids = self._revision_id_graph[rev_id]
2611
parent_ids = [p for p in parent_ids if p not in self._ghosts]
2612
details = self._all_build_details[rev_id]
2613
(index_memo, compression_parent, parents,
2614
record_details) = details
2615
nodes_to_annotate = []
2616
# TODO: Remove the punning between compression parents, and
2617
# parent_ids, we should be able to do this without assuming
2619
if len(parent_ids) == 0:
2620
# There are no parents for this node, so just add it
2621
# TODO: This probably needs to be decoupled
2622
fulltext_content, delta = self._knit._factory.parse_record(
2623
rev_id, record, record_details, None)
2624
fulltext = self._add_fulltext_content(rev_id, fulltext_content)
2625
nodes_to_annotate.extend(self._add_annotation(rev_id, fulltext,
2626
parent_ids, left_matching_blocks=None))
2628
child = (rev_id, parent_ids, record)
2629
# Check if all the parents are present
2630
self._check_parents(child, nodes_to_annotate)
2631
while nodes_to_annotate:
2632
# Should we use a queue here instead of a stack?
2633
(rev_id, parent_ids, record) = nodes_to_annotate.pop()
2634
(index_memo, compression_parent, parents,
2635
record_details) = self._all_build_details[rev_id]
2636
if compression_parent is not None:
2637
comp_children = self._compression_children[compression_parent]
2638
if rev_id not in comp_children:
2639
raise AssertionError("%r not in compression children %r"
2640
% (rev_id, comp_children))
2641
# If there is only 1 child, it is safe to reuse this
2643
reuse_content = (len(comp_children) == 1
2644
and compression_parent not in
2645
self._nodes_to_keep_annotations)
2647
# Remove it from the cache since it will be changing
2648
parent_fulltext_content = self._fulltext_contents.pop(compression_parent)
2649
# Make sure to copy the fulltext since it might be
2651
parent_fulltext = list(parent_fulltext_content.text())
2653
parent_fulltext_content = self._fulltext_contents[compression_parent]
2654
parent_fulltext = parent_fulltext_content.text()
2655
comp_children.remove(rev_id)
2656
fulltext_content, delta = self._knit._factory.parse_record(
2657
rev_id, record, record_details,
2658
parent_fulltext_content,
2659
copy_base_content=(not reuse_content))
2660
fulltext = self._add_fulltext_content(rev_id,
2662
blocks = KnitContent.get_line_delta_blocks(delta,
2663
parent_fulltext, fulltext)
2665
fulltext_content = self._knit._factory.parse_fulltext(
2667
fulltext = self._add_fulltext_content(rev_id,
2670
nodes_to_annotate.extend(
2671
self._add_annotation(rev_id, fulltext, parent_ids,
2672
left_matching_blocks=blocks))
2674
def _get_heads_provider(self):
2675
"""Create a heads provider for resolving ancestry issues."""
2676
if self._heads_provider is not None:
2677
return self._heads_provider
2678
parent_provider = _mod_graph.DictParentsProvider(
2679
self._revision_id_graph)
2680
graph_obj = _mod_graph.Graph(parent_provider)
2681
head_cache = _mod_graph.FrozenHeadsCache(graph_obj)
2682
self._heads_provider = head_cache
2685
def annotate(self, key):
2686
"""Return the annotated fulltext at the given key.
2688
:param key: The key to annotate.
2690
if True or len(self._knit._fallback_vfs) > 0:
2691
# stacked knits can't use the fast path at present.
2692
return self._simple_annotate(key)
2693
records = self._get_build_graph(key)
2694
if key in self._ghosts:
2695
raise errors.RevisionNotPresent(key, self._knit)
2696
self._annotate_records(records)
2697
return self._annotated_lines[key]
2699
def _simple_annotate(self, key):
2700
"""Return annotated fulltext, rediffing from the full texts.
2702
This is slow but makes no assumptions about the repository
2703
being able to produce line deltas.
2705
# TODO: this code generates a parent maps of present ancestors; it
2706
# could be split out into a separate method, and probably should use
2707
# iter_ancestry instead. -- mbp and robertc 20080704
2708
graph = _mod_graph.Graph(self._knit)
2709
head_cache = _mod_graph.FrozenHeadsCache(graph)
2710
search = graph._make_breadth_first_searcher([key])
2714
present, ghosts = search.next_with_ghosts()
2715
except StopIteration:
2717
keys.update(present)
2718
parent_map = self._knit.get_parent_map(keys)
2720
reannotate = annotate.reannotate
2721
for record in self._knit.get_record_stream(keys, 'topological', True):
2723
fulltext = split_lines(record.get_bytes_as('fulltext'))
2724
parents = parent_map[key]
2725
if parents is not None:
2726
parent_lines = [parent_cache[parent] for parent in parent_map[key]]
2729
parent_cache[key] = list(
2730
reannotate(parent_lines, fulltext, key, None, head_cache))
2732
return parent_cache[key]
2734
raise errors.RevisionNotPresent(key, self._knit)
3651
# At this point, we may be able to yield this content, if all
3652
# parents are also finished
3653
yield_this_text = self._check_ready_for_annotations(key,
3656
# All parents present
3657
yield key, lines, len(lines)
3658
to_process = self._process_pending(key)
3660
this_process = to_process
3662
for key in this_process:
3663
lines = self._text_cache[key]
3664
yield key, lines, len(lines)
3665
to_process.extend(self._process_pending(key))
2738
from bzrlib._knit_load_data_c import _load_data_c as _load_data
3668
from bzrlib._knit_load_data_pyx import _load_data_c as _load_data
2739
3669
except ImportError:
2740
3670
from bzrlib._knit_load_data_py import _load_data_py as _load_data