268
275
annotated_kind = ''
269
276
self.storage_kind = 'knit-%s%s-gz' % (annotated_kind, kind)
270
277
self._raw_record = raw_record
278
self._network_bytes = network_bytes
271
279
self._build_details = build_details
272
280
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,
282
def _create_network_bytes(self):
283
"""Create a fully serialised network version for transmission."""
284
# storage_kind, key, parents, Noeol, raw_record
285
key_bytes = '\x00'.join(self.key)
286
if self.parents is None:
287
parent_bytes = 'None:'
289
parent_bytes = '\t'.join('\x00'.join(key) for key in self.parents)
290
if self._build_details[1]:
294
network_bytes = "%s\n%s\n%s\n%s%s" % (self.storage_kind, key_bytes,
295
parent_bytes, noeol, self._raw_record)
296
self._network_bytes = network_bytes
298
def get_bytes_as(self, storage_kind):
299
if storage_kind == self.storage_kind:
300
if self._network_bytes is None:
301
self._create_network_bytes()
302
return self._network_bytes
303
if ('-ft-' in self.storage_kind and
304
storage_kind in ('chunked', 'fulltext')):
305
adapter_key = (self.storage_kind, 'fulltext')
306
adapter_factory = adapter_registry.get(adapter_key)
307
adapter = adapter_factory(None)
308
bytes = adapter.get_bytes(self)
309
if storage_kind == 'chunked':
313
if self._knit is not None:
314
# Not redundant with direct conversion above - that only handles
316
if storage_kind == 'chunked':
317
return self._knit.get_lines(self.key[0])
318
elif storage_kind == 'fulltext':
319
return self._knit.get_text(self.key[0])
320
raise errors.UnavailableRepresentation(self.key, storage_kind,
324
class LazyKnitContentFactory(ContentFactory):
325
"""A ContentFactory which can either generate full text or a wire form.
327
:seealso ContentFactory:
330
def __init__(self, key, parents, generator, first):
331
"""Create a LazyKnitContentFactory.
333
:param key: The key of the record.
334
:param parents: The parents of the record.
335
:param generator: A _ContentMapGenerator containing the record for this
337
:param first: Is this the first content object returned from generator?
338
if it is, its storage kind is knit-delta-closure, otherwise it is
339
knit-delta-closure-ref
342
self.parents = parents
344
self._generator = generator
345
self.storage_kind = "knit-delta-closure"
347
self.storage_kind = self.storage_kind + "-ref"
350
def get_bytes_as(self, storage_kind):
351
if storage_kind == self.storage_kind:
353
return self._generator._wire_bytes()
355
# all the keys etc are contained in the bytes returned in the
358
if storage_kind in ('chunked', 'fulltext'):
359
chunks = self._generator._get_one_work(self.key).text()
360
if storage_kind == 'chunked':
363
return ''.join(chunks)
364
raise errors.UnavailableRepresentation(self.key, storage_kind,
368
def knit_delta_closure_to_records(storage_kind, bytes, line_end):
369
"""Convert a network record to a iterator over stream records.
371
:param storage_kind: The storage kind of the record.
372
Must be 'knit-delta-closure'.
373
:param bytes: The bytes of the record on the network.
375
generator = _NetworkContentMapGenerator(bytes, line_end)
376
return generator.get_record_stream()
379
def knit_network_to_record(storage_kind, bytes, line_end):
380
"""Convert a network record to a record object.
382
:param storage_kind: The storage kind of the record.
383
:param bytes: The bytes of the record on the network.
386
line_end = bytes.find('\n', start)
387
key = tuple(bytes[start:line_end].split('\x00'))
389
line_end = bytes.find('\n', start)
390
parent_line = bytes[start:line_end]
391
if parent_line == 'None:':
395
[tuple(segment.split('\x00')) for segment in parent_line.split('\t')
398
noeol = bytes[start] == 'N'
399
if 'ft' in storage_kind:
402
method = 'line-delta'
403
build_details = (method, noeol)
405
raw_record = bytes[start:]
406
annotated = 'annotated' in storage_kind
407
return [KnitContentFactory(key, parents, build_details, None, raw_record,
408
annotated, network_bytes=bytes)]
284
411
class KnitContent(object):
285
412
"""Content of a knit version to which deltas can be applied.
287
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
This is always stored in memory as a list of lines with \\n at the end,
415
plus a flag saying if the final ending is really there or not, because that
289
416
corresponds to the on-disk knit representation.
1098
1233
def _get_record_map(self, keys, allow_missing=False):
1099
1234
"""Produce a dictionary of knit records.
1101
1236
:return: {key:(record, record_details, digest, next)}
1103
data returned from read_records
1105
opaque information to pass to parse_record
1107
SHA1 digest of the full text after all steps are done
1109
build-parent of the version, i.e. the leftmost ancestor.
1238
* record: data returned from read_records (a KnitContentobject)
1239
* record_details: opaque information to pass to parse_record
1240
* digest: SHA1 digest of the full text after all steps are done
1241
* next: build-parent of the version, i.e. the leftmost ancestor.
1110
1242
Will be None if the record is not a delta.
1111
1244
:param keys: The keys to build a map for
1112
:param allow_missing: If some records are missing, rather than
1245
:param allow_missing: If some records are missing, rather than
1113
1246
error, just return the data that could be generated.
1115
position_map = self._get_components_positions(keys,
1248
raw_map = self._get_record_map_unparsed(keys,
1116
1249
allow_missing=allow_missing)
1117
# key = component_id, r = record_details, i_m = index_memo, n = next
1118
records = [(key, i_m) for key, (r, i_m, n)
1119
in position_map.iteritems()]
1121
for key, record, digest in \
1122
self._read_records_iter(records):
1123
(record_details, index_memo, next) = position_map[key]
1124
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)
1127
1373
def get_record_stream(self, keys, ordering, include_delta_closure):
1128
1374
"""Get a stream of records for keys.
1333
1648
access_memo = self._access.add_raw_records(
1334
1649
[(record.key, len(bytes))], bytes)[0]
1335
1650
index_entry = (record.key, options, access_memo, parents)
1337
1651
if 'fulltext' not in options:
1338
basis_parent = parents[0]
1652
# Not a fulltext, so we need to make sure the compression
1653
# parent will also be present.
1339
1654
# Note that pack backed knits don't need to buffer here
1340
1655
# because they buffer all writes to the transaction level,
1341
1656
# but we don't expose that difference at the index level. If
1342
1657
# the query here has sufficient cost to show up in
1343
1658
# profiling we should do that.
1344
if basis_parent not in self.get_parent_map([basis_parent]):
1660
# They're required to be physically in this
1661
# KnitVersionedFiles, not in a fallback.
1662
if not self._index.has_key(compression_parent):
1345
1663
pending = buffered_index_entries.setdefault(
1664
compression_parent, [])
1347
1665
pending.append(index_entry)
1348
1666
buffered = True
1349
1667
if not buffered:
1350
1668
self._index.add_records([index_entry])
1351
elif record.storage_kind == 'fulltext':
1669
elif record.storage_kind == 'chunked':
1352
1670
self.add_lines(record.key, parents,
1353
split_lines(record.get_bytes_as('fulltext')))
1671
osutils.chunks_to_lines(record.get_bytes_as('chunked')))
1355
adapter_key = record.storage_kind, 'fulltext'
1356
adapter = get_adapter(adapter_key)
1357
lines = split_lines(adapter.get_bytes(
1358
record, record.get_bytes_as(record.storage_kind)))
1673
# Not suitable for direct insertion as a
1674
# delta, either because it's not the right format, or this
1675
# KnitVersionedFiles doesn't permit deltas (_max_delta_chain ==
1676
# 0) or because it depends on a base only present in the
1678
self._access.flush()
1680
# Try getting a fulltext directly from the record.
1681
bytes = record.get_bytes_as('fulltext')
1682
except errors.UnavailableRepresentation:
1683
adapter_key = record.storage_kind, 'fulltext'
1684
adapter = get_adapter(adapter_key)
1685
bytes = adapter.get_bytes(record)
1686
lines = split_lines(bytes)
1360
1688
self.add_lines(record.key, parents, lines)
1361
1689
except errors.RevisionAlreadyPresent:
1363
1691
# Add any records whose basis parent is now available.
1364
added_keys = [record.key]
1366
key = added_keys.pop(0)
1367
if key in buffered_index_entries:
1368
index_entries = buffered_index_entries[key]
1369
self._index.add_records(index_entries)
1371
[index_entry[0] for index_entry in index_entries])
1372
del buffered_index_entries[key]
1373
# If there were any deltas which had a missing basis parent, error.
1693
added_keys = [record.key]
1695
key = added_keys.pop(0)
1696
if key in buffered_index_entries:
1697
index_entries = buffered_index_entries[key]
1698
self._index.add_records(index_entries)
1700
[index_entry[0] for index_entry in index_entries])
1701
del buffered_index_entries[key]
1374
1702
if buffered_index_entries:
1375
raise errors.RevisionNotPresent(buffered_index_entries.keys()[0],
1703
# There were index entries buffered at the end of the stream,
1704
# So these need to be added (if the index supports holding such
1705
# entries for later insertion)
1707
for key in buffered_index_entries:
1708
index_entries = buffered_index_entries[key]
1709
all_entries.extend(index_entries)
1710
self._index.add_records(
1711
all_entries, missing_compression_parents=True)
1713
def get_missing_compression_parent_keys(self):
1714
"""Return an iterable of keys of missing compression parents.
1716
Check this after calling insert_record_stream to find out if there are
1717
any missing compression parents. If there are, the records that
1718
depend on them are not able to be inserted safely. For atomic
1719
KnitVersionedFiles built on packs, the transaction should be aborted or
1720
suspended - commit will fail at this point. Nonatomic knits will error
1721
earlier because they have no staging area to put pending entries into.
1723
return self._index.get_missing_compression_parents()
1378
1725
def iter_lines_added_or_present_in_keys(self, keys, pb=None):
1379
1726
"""Iterate over the lines in the versioned files from keys.
1390
1737
is an iterator).
1393
* Lines are normalised by the underlying store: they will all have \n
1740
* Lines are normalised by the underlying store: they will all have \\n
1395
1742
* Lines are returned in arbitrary order.
1743
* If a requested key did not change any lines (or didn't have any
1744
lines), it may not be mentioned at all in the result.
1746
:param pb: Progress bar supplied by caller.
1397
1747
:return: An iterator over (line, key).
1400
pb = progress.DummyProgress()
1750
pb = ui.ui_factory.nested_progress_bar()
1401
1751
keys = set(keys)
1402
1752
total = len(keys)
1403
# we don't care about inclusions, the caller cares.
1404
# but we need to setup a list of records to visit.
1405
# we need key, position, length
1407
build_details = self._index.get_build_details(keys)
1408
for key, details in build_details.iteritems():
1410
key_records.append((key, details[0]))
1412
records_iter = enumerate(self._read_records_iter(key_records))
1413
for (key_idx, (key, data, sha_value)) in records_iter:
1414
pb.update('Walking content.', key_idx, total)
1415
compression_parent = build_details[key][1]
1416
if compression_parent is None:
1418
line_iterator = self._factory.get_fulltext_content(data)
1421
line_iterator = self._factory.get_linedelta_content(data)
1422
# XXX: It might be more efficient to yield (key,
1423
# line_iterator) in the future. However for now, this is a simpler
1424
# change to integrate into the rest of the codebase. RBC 20071110
1425
for line in line_iterator:
1427
for source in self._fallback_vfs:
1756
# we don't care about inclusions, the caller cares.
1757
# but we need to setup a list of records to visit.
1758
# we need key, position, length
1760
build_details = self._index.get_build_details(keys)
1761
for key, details in build_details.iteritems():
1763
key_records.append((key, details[0]))
1764
records_iter = enumerate(self._read_records_iter(key_records))
1765
for (key_idx, (key, data, sha_value)) in records_iter:
1766
pb.update(gettext('Walking content'), key_idx, total)
1767
compression_parent = build_details[key][1]
1768
if compression_parent is None:
1770
line_iterator = self._factory.get_fulltext_content(data)
1773
line_iterator = self._factory.get_linedelta_content(data)
1774
# Now that we are yielding the data for this key, remove it
1777
# XXX: It might be more efficient to yield (key,
1778
# line_iterator) in the future. However for now, this is a
1779
# simpler change to integrate into the rest of the
1780
# codebase. RBC 20071110
1781
for line in line_iterator:
1784
except errors.RetryWithNewPacks, e:
1785
self._access.reload_or_raise(e)
1786
# If there are still keys we've not yet found, we look in the fallback
1787
# vfs, and hope to find them there. Note that if the keys are found
1788
# but had no changes or no content, the fallback may not return
1790
if keys and not self._immediate_fallback_vfs:
1791
# XXX: strictly the second parameter is meant to be the file id
1792
# but it's not easily accessible here.
1793
raise RevisionNotPresent(keys, repr(self))
1794
for source in self._immediate_fallback_vfs:
1430
1797
source_keys = set()
1635
2007
"""See VersionedFiles.keys."""
1636
2008
if 'evil' in debug.debug_flags:
1637
2009
trace.mutter_callsite(2, "keys scales with size of history")
1638
sources = [self._index] + self._fallback_vfs
2010
sources = [self._index] + self._immediate_fallback_vfs
1640
2012
for source in sources:
1641
2013
result.update(source.keys())
2017
class _ContentMapGenerator(object):
2018
"""Generate texts or expose raw deltas for a set of texts."""
2020
def __init__(self, ordering='unordered'):
2021
self._ordering = ordering
2023
def _get_content(self, key):
2024
"""Get the content object for key."""
2025
# Note that _get_content is only called when the _ContentMapGenerator
2026
# has been constructed with just one key requested for reconstruction.
2027
if key in self.nonlocal_keys:
2028
record = self.get_record_stream().next()
2029
# Create a content object on the fly
2030
lines = osutils.chunks_to_lines(record.get_bytes_as('chunked'))
2031
return PlainKnitContent(lines, record.key)
2033
# local keys we can ask for directly
2034
return self._get_one_work(key)
2036
def get_record_stream(self):
2037
"""Get a record stream for the keys requested during __init__."""
2038
for record in self._work():
2042
"""Produce maps of text and KnitContents as dicts.
2044
:return: (text_map, content_map) where text_map contains the texts for
2045
the requested versions and content_map contains the KnitContents.
2047
# NB: By definition we never need to read remote sources unless texts
2048
# are requested from them: we don't delta across stores - and we
2049
# explicitly do not want to to prevent data loss situations.
2050
if self.global_map is None:
2051
self.global_map = self.vf.get_parent_map(self.keys)
2052
nonlocal_keys = self.nonlocal_keys
2054
missing_keys = set(nonlocal_keys)
2055
# Read from remote versioned file instances and provide to our caller.
2056
for source in self.vf._immediate_fallback_vfs:
2057
if not missing_keys:
2059
# Loop over fallback repositories asking them for texts - ignore
2060
# any missing from a particular fallback.
2061
for record in source.get_record_stream(missing_keys,
2062
self._ordering, True):
2063
if record.storage_kind == 'absent':
2064
# Not in thie particular stream, may be in one of the
2065
# other fallback vfs objects.
2067
missing_keys.remove(record.key)
2070
if self._raw_record_map is None:
2071
raise AssertionError('_raw_record_map should have been filled')
2073
for key in self.keys:
2074
if key in self.nonlocal_keys:
2076
yield LazyKnitContentFactory(key, self.global_map[key], self, first)
2079
def _get_one_work(self, requested_key):
2080
# Now, if we have calculated everything already, just return the
2082
if requested_key in self._contents_map:
2083
return self._contents_map[requested_key]
2084
# To simplify things, parse everything at once - code that wants one text
2085
# probably wants them all.
2086
# FUTURE: This function could be improved for the 'extract many' case
2087
# by tracking each component and only doing the copy when the number of
2088
# children than need to apply delta's to it is > 1 or it is part of the
2090
multiple_versions = len(self.keys) != 1
2091
if self._record_map is None:
2092
self._record_map = self.vf._raw_map_to_record_map(
2093
self._raw_record_map)
2094
record_map = self._record_map
2095
# raw_record_map is key:
2096
# Have read and parsed records at this point.
2097
for key in self.keys:
2098
if key in self.nonlocal_keys:
2103
while cursor is not None:
2105
record, record_details, digest, next = record_map[cursor]
2107
raise RevisionNotPresent(cursor, self)
2108
components.append((cursor, record, record_details, digest))
2110
if cursor in self._contents_map:
2111
# no need to plan further back
2112
components.append((cursor, None, None, None))
2116
for (component_id, record, record_details,
2117
digest) in reversed(components):
2118
if component_id in self._contents_map:
2119
content = self._contents_map[component_id]
2121
content, delta = self._factory.parse_record(key[-1],
2122
record, record_details, content,
2123
copy_base_content=multiple_versions)
2124
if multiple_versions:
2125
self._contents_map[component_id] = content
2127
# digest here is the digest from the last applied component.
2128
text = content.text()
2129
actual_sha = sha_strings(text)
2130
if actual_sha != digest:
2131
raise SHA1KnitCorrupt(self, actual_sha, digest, key, text)
2132
if multiple_versions:
2133
return self._contents_map[requested_key]
2137
def _wire_bytes(self):
2138
"""Get the bytes to put on the wire for 'key'.
2140
The first collection of bytes asked for returns the serialised
2141
raw_record_map and the additional details (key, parent) for key.
2142
Subsequent calls return just the additional details (key, parent).
2143
The wire storage_kind given for the first key is 'knit-delta-closure',
2144
For subsequent keys it is 'knit-delta-closure-ref'.
2146
:param key: A key from the content generator.
2147
:return: Bytes to put on the wire.
2150
# kind marker for dispatch on the far side,
2151
lines.append('knit-delta-closure')
2153
if self.vf._factory.annotated:
2154
lines.append('annotated')
2157
# then the list of keys
2158
lines.append('\t'.join(['\x00'.join(key) for key in self.keys
2159
if key not in self.nonlocal_keys]))
2160
# then the _raw_record_map in serialised form:
2162
# for each item in the map:
2164
# 1 line with parents if the key is to be yielded (None: for None, '' for ())
2165
# one line with method
2166
# one line with noeol
2167
# one line with next ('' for None)
2168
# one line with byte count of the record bytes
2170
for key, (record_bytes, (method, noeol), next) in \
2171
self._raw_record_map.iteritems():
2172
key_bytes = '\x00'.join(key)
2173
parents = self.global_map.get(key, None)
2175
parent_bytes = 'None:'
2177
parent_bytes = '\t'.join('\x00'.join(key) for key in parents)
2178
method_bytes = method
2184
next_bytes = '\x00'.join(next)
2187
map_byte_list.append('%s\n%s\n%s\n%s\n%s\n%d\n%s' % (
2188
key_bytes, parent_bytes, method_bytes, noeol_bytes, next_bytes,
2189
len(record_bytes), record_bytes))
2190
map_bytes = ''.join(map_byte_list)
2191
lines.append(map_bytes)
2192
bytes = '\n'.join(lines)
2196
class _VFContentMapGenerator(_ContentMapGenerator):
2197
"""Content map generator reading from a VersionedFiles object."""
2199
def __init__(self, versioned_files, keys, nonlocal_keys=None,
2200
global_map=None, raw_record_map=None, ordering='unordered'):
2201
"""Create a _ContentMapGenerator.
2203
:param versioned_files: The versioned files that the texts are being
2205
:param keys: The keys to produce content maps for.
2206
:param nonlocal_keys: An iterable of keys(possibly intersecting keys)
2207
which are known to not be in this knit, but rather in one of the
2209
:param global_map: The result of get_parent_map(keys) (or a supermap).
2210
This is required if get_record_stream() is to be used.
2211
:param raw_record_map: A unparsed raw record map to use for answering
2214
_ContentMapGenerator.__init__(self, ordering=ordering)
2215
# The vf to source data from
2216
self.vf = versioned_files
2218
self.keys = list(keys)
2219
# Keys known to be in fallback vfs objects
2220
if nonlocal_keys is None:
2221
self.nonlocal_keys = set()
2223
self.nonlocal_keys = frozenset(nonlocal_keys)
2224
# Parents data for keys to be returned in get_record_stream
2225
self.global_map = global_map
2226
# The chunked lists for self.keys in text form
2228
# A cache of KnitContent objects used in extracting texts.
2229
self._contents_map = {}
2230
# All the knit records needed to assemble the requested keys as full
2232
self._record_map = None
2233
if raw_record_map is None:
2234
self._raw_record_map = self.vf._get_record_map_unparsed(keys,
2237
self._raw_record_map = raw_record_map
2238
# the factory for parsing records
2239
self._factory = self.vf._factory
2242
class _NetworkContentMapGenerator(_ContentMapGenerator):
2243
"""Content map generator sourced from a network stream."""
2245
def __init__(self, bytes, line_end):
2246
"""Construct a _NetworkContentMapGenerator from a bytes block."""
2248
self.global_map = {}
2249
self._raw_record_map = {}
2250
self._contents_map = {}
2251
self._record_map = None
2252
self.nonlocal_keys = []
2253
# Get access to record parsing facilities
2254
self.vf = KnitVersionedFiles(None, None)
2257
line_end = bytes.find('\n', start)
2258
line = bytes[start:line_end]
2259
start = line_end + 1
2260
if line == 'annotated':
2261
self._factory = KnitAnnotateFactory()
2263
self._factory = KnitPlainFactory()
2264
# list of keys to emit in get_record_stream
2265
line_end = bytes.find('\n', start)
2266
line = bytes[start:line_end]
2267
start = line_end + 1
2269
tuple(segment.split('\x00')) for segment in line.split('\t')
2271
# now a loop until the end. XXX: It would be nice if this was just a
2272
# bunch of the same records as get_record_stream(..., False) gives, but
2273
# there is a decent sized gap stopping that at the moment.
2277
line_end = bytes.find('\n', start)
2278
key = tuple(bytes[start:line_end].split('\x00'))
2279
start = line_end + 1
2280
# 1 line with parents (None: for None, '' for ())
2281
line_end = bytes.find('\n', start)
2282
line = bytes[start:line_end]
2287
[tuple(segment.split('\x00')) for segment in line.split('\t')
2289
self.global_map[key] = parents
2290
start = line_end + 1
2291
# one line with method
2292
line_end = bytes.find('\n', start)
2293
line = bytes[start:line_end]
2295
start = line_end + 1
2296
# one line with noeol
2297
line_end = bytes.find('\n', start)
2298
line = bytes[start:line_end]
2300
start = line_end + 1
2301
# one line with next ('' for None)
2302
line_end = bytes.find('\n', start)
2303
line = bytes[start:line_end]
2307
next = tuple(bytes[start:line_end].split('\x00'))
2308
start = line_end + 1
2309
# one line with byte count of the record bytes
2310
line_end = bytes.find('\n', start)
2311
line = bytes[start:line_end]
2313
start = line_end + 1
2315
record_bytes = bytes[start:start+count]
2316
start = start + count
2318
self._raw_record_map[key] = (record_bytes, (method, noeol), next)
2320
def get_record_stream(self):
2321
"""Get a record stream for for keys requested by the bytestream."""
2323
for key in self.keys:
2324
yield LazyKnitContentFactory(key, self.global_map[key], self, first)
2327
def _wire_bytes(self):
1646
2331
class _KndxIndex(object):
1647
2332
"""Manages knit index files
2436
3222
annotator = _KnitAnnotator(knit)
2437
return iter(annotator.annotate(revision_id))
2440
class _KnitAnnotator(object):
3223
return iter(annotator.annotate_flat(revision_id))
3226
class _KnitAnnotator(annotate.Annotator):
2441
3227
"""Build up the annotations for a text."""
2443
def __init__(self, knit):
2446
# Content objects, differs from fulltexts because of how final newlines
2447
# are treated by knits. the content objects here will always have a
2449
self._fulltext_contents = {}
2451
# Annotated lines of specific revisions
2452
self._annotated_lines = {}
2454
# Track the raw data for nodes that we could not process yet.
2455
# This maps the revision_id of the base to a list of children that will
2456
# annotated from it.
2457
self._pending_children = {}
2459
# Nodes which cannot be extracted
2460
self._ghosts = set()
2462
# Track how many children this node has, so we know if we need to keep
2464
self._annotate_children = {}
2465
self._compression_children = {}
3229
def __init__(self, vf):
3230
annotate.Annotator.__init__(self, vf)
3232
# TODO: handle Nodes which cannot be extracted
3233
# self._ghosts = set()
3235
# Map from (key, parent_key) => matching_blocks, should be 'use once'
3236
self._matching_blocks = {}
3238
# KnitContent objects
3239
self._content_objects = {}
3240
# The number of children that depend on this fulltext content object
3241
self._num_compression_children = {}
3242
# Delta records that need their compression parent before they can be
3244
self._pending_deltas = {}
3245
# Fulltext records that are waiting for their parents fulltexts before
3246
# they can be yielded for annotation
3247
self._pending_annotation = {}
2467
3249
self._all_build_details = {}
2468
# The children => parent revision_id graph
2469
self._revision_id_graph = {}
2471
self._heads_provider = None
2473
self._nodes_to_keep_annotations = set()
2474
self._generations_until_keep = 100
2476
def set_generations_until_keep(self, value):
2477
"""Set the number of generations before caching a node.
2479
Setting this to -1 will cache every merge node, setting this higher
2480
will cache fewer nodes.
2482
self._generations_until_keep = value
2484
def _add_fulltext_content(self, revision_id, content_obj):
2485
self._fulltext_contents[revision_id] = content_obj
2486
# TODO: jam 20080305 It might be good to check the sha1digest here
2487
return content_obj.text()
2489
def _check_parents(self, child, nodes_to_annotate):
2490
"""Check if all parents have been processed.
2492
:param child: A tuple of (rev_id, parents, raw_content)
2493
:param nodes_to_annotate: If child is ready, add it to
2494
nodes_to_annotate, otherwise put it back in self._pending_children
2496
for parent_id in child[1]:
2497
if (parent_id not in self._annotated_lines):
2498
# This parent is present, but another parent is missing
2499
self._pending_children.setdefault(parent_id,
2503
# This one is ready to be processed
2504
nodes_to_annotate.append(child)
2506
def _add_annotation(self, revision_id, fulltext, parent_ids,
2507
left_matching_blocks=None):
2508
"""Add an annotation entry.
2510
All parents should already have been annotated.
2511
:return: A list of children that now have their parents satisfied.
2513
a = self._annotated_lines
2514
annotated_parent_lines = [a[p] for p in parent_ids]
2515
annotated_lines = list(annotate.reannotate(annotated_parent_lines,
2516
fulltext, revision_id, left_matching_blocks,
2517
heads_provider=self._get_heads_provider()))
2518
self._annotated_lines[revision_id] = annotated_lines
2519
for p in parent_ids:
2520
ann_children = self._annotate_children[p]
2521
ann_children.remove(revision_id)
2522
if (not ann_children
2523
and p not in self._nodes_to_keep_annotations):
2524
del self._annotated_lines[p]
2525
del self._all_build_details[p]
2526
if p in self._fulltext_contents:
2527
del self._fulltext_contents[p]
2528
# Now that we've added this one, see if there are any pending
2529
# deltas to be done, certainly this parent is finished
2530
nodes_to_annotate = []
2531
for child in self._pending_children.pop(revision_id, []):
2532
self._check_parents(child, nodes_to_annotate)
2533
return nodes_to_annotate
2535
3251
def _get_build_graph(self, key):
2536
3252
"""Get the graphs for building texts and annotations.
2543
3259
:return: A list of (key, index_memo) records, suitable for
2544
passing to read_records_iter to start reading in the raw data fro/
3260
passing to read_records_iter to start reading in the raw data from
2547
if key in self._annotated_lines:
2550
3263
pending = set([key])
3266
self._num_needed_children[key] = 1
2555
3268
# get all pending nodes
2557
3269
this_iteration = pending
2558
build_details = self._knit._index.get_build_details(this_iteration)
3270
build_details = self._vf._index.get_build_details(this_iteration)
2559
3271
self._all_build_details.update(build_details)
2560
# new_nodes = self._knit._index._get_entries(this_iteration)
3272
# new_nodes = self._vf._index._get_entries(this_iteration)
2561
3273
pending = set()
2562
3274
for key, details in build_details.iteritems():
2563
(index_memo, compression_parent, parents,
3275
(index_memo, compression_parent, parent_keys,
2564
3276
record_details) = details
2565
self._revision_id_graph[key] = parents
3277
self._parent_map[key] = parent_keys
3278
self._heads_provider = None
2566
3279
records.append((key, index_memo))
2567
3280
# Do we actually need to check _annotated_lines?
2568
pending.update(p for p in parents
2569
if p not in self._all_build_details)
3281
pending.update([p for p in parent_keys
3282
if p not in self._all_build_details])
3284
for parent_key in parent_keys:
3285
if parent_key in self._num_needed_children:
3286
self._num_needed_children[parent_key] += 1
3288
self._num_needed_children[parent_key] = 1
2570
3289
if compression_parent:
2571
self._compression_children.setdefault(compression_parent,
2574
for parent in parents:
2575
self._annotate_children.setdefault(parent,
2577
num_gens = generation - kept_generation
2578
if ((num_gens >= self._generations_until_keep)
2579
and len(parents) > 1):
2580
kept_generation = generation
2581
self._nodes_to_keep_annotations.add(key)
3290
if compression_parent in self._num_compression_children:
3291
self._num_compression_children[compression_parent] += 1
3293
self._num_compression_children[compression_parent] = 1
2583
3295
missing_versions = this_iteration.difference(build_details.keys())
2584
self._ghosts.update(missing_versions)
2585
for missing_version in missing_versions:
2586
# add a key, no parents
2587
self._revision_id_graph[missing_version] = ()
2588
pending.discard(missing_version) # don't look for it
2589
if self._ghosts.intersection(self._compression_children):
2591
"We cannot have nodes which have a ghost compression parent:\n"
2593
"compression children: %r"
2594
% (self._ghosts, self._compression_children))
2595
# Cleanout anything that depends on a ghost so that we don't wait for
2596
# the ghost to show up
2597
for node in self._ghosts:
2598
if node in self._annotate_children:
2599
# We won't be building this node
2600
del self._annotate_children[node]
3296
if missing_versions:
3297
for key in missing_versions:
3298
if key in self._parent_map and key in self._text_cache:
3299
# We already have this text ready, we just need to
3300
# yield it later so we get it annotated
3302
parent_keys = self._parent_map[key]
3303
for parent_key in parent_keys:
3304
if parent_key in self._num_needed_children:
3305
self._num_needed_children[parent_key] += 1
3307
self._num_needed_children[parent_key] = 1
3308
pending.update([p for p in parent_keys
3309
if p not in self._all_build_details])
3311
raise errors.RevisionNotPresent(key, self._vf)
2601
3312
# Generally we will want to read the records in reverse order, because
2602
3313
# we find the parent nodes after the children
2603
3314
records.reverse()
2606
def _annotate_records(self, records):
2607
"""Build the annotations for the listed records."""
3315
return records, ann_keys
3317
def _get_needed_texts(self, key, pb=None):
3318
# if True or len(self._vf._immediate_fallback_vfs) > 0:
3319
if len(self._vf._immediate_fallback_vfs) > 0:
3320
# If we have fallbacks, go to the generic path
3321
for v in annotate.Annotator._get_needed_texts(self, key, pb=pb):
3326
records, ann_keys = self._get_build_graph(key)
3327
for idx, (sub_key, text, num_lines) in enumerate(
3328
self._extract_texts(records)):
3330
pb.update(gettext('annotating'), idx, len(records))
3331
yield sub_key, text, num_lines
3332
for sub_key in ann_keys:
3333
text = self._text_cache[sub_key]
3334
num_lines = len(text) # bad assumption
3335
yield sub_key, text, num_lines
3337
except errors.RetryWithNewPacks, e:
3338
self._vf._access.reload_or_raise(e)
3339
# The cached build_details are no longer valid
3340
self._all_build_details.clear()
3342
def _cache_delta_blocks(self, key, compression_parent, delta, lines):
3343
parent_lines = self._text_cache[compression_parent]
3344
blocks = list(KnitContent.get_line_delta_blocks(delta, parent_lines, lines))
3345
self._matching_blocks[(key, compression_parent)] = blocks
3347
def _expand_record(self, key, parent_keys, compression_parent, record,
3350
if compression_parent:
3351
if compression_parent not in self._content_objects:
3352
# Waiting for the parent
3353
self._pending_deltas.setdefault(compression_parent, []).append(
3354
(key, parent_keys, record, record_details))
3356
# We have the basis parent, so expand the delta
3357
num = self._num_compression_children[compression_parent]
3360
base_content = self._content_objects.pop(compression_parent)
3361
self._num_compression_children.pop(compression_parent)
3363
self._num_compression_children[compression_parent] = num
3364
base_content = self._content_objects[compression_parent]
3365
# It is tempting to want to copy_base_content=False for the last
3366
# child object. However, whenever noeol=False,
3367
# self._text_cache[parent_key] is content._lines. So mutating it
3368
# gives very bad results.
3369
# The alternative is to copy the lines into text cache, but then we
3370
# are copying anyway, so just do it here.
3371
content, delta = self._vf._factory.parse_record(
3372
key, record, record_details, base_content,
3373
copy_base_content=True)
3376
content, _ = self._vf._factory.parse_record(
3377
key, record, record_details, None)
3378
if self._num_compression_children.get(key, 0) > 0:
3379
self._content_objects[key] = content
3380
lines = content.text()
3381
self._text_cache[key] = lines
3382
if delta is not None:
3383
self._cache_delta_blocks(key, compression_parent, delta, lines)
3386
def _get_parent_annotations_and_matches(self, key, text, parent_key):
3387
"""Get the list of annotations for the parent, and the matching lines.
3389
:param text: The opaque value given by _get_needed_texts
3390
:param parent_key: The key for the parent text
3391
:return: (parent_annotations, matching_blocks)
3392
parent_annotations is a list as long as the number of lines in
3394
matching_blocks is a list of (parent_idx, text_idx, len) tuples
3395
indicating which lines match between the two texts
3397
block_key = (key, parent_key)
3398
if block_key in self._matching_blocks:
3399
blocks = self._matching_blocks.pop(block_key)
3400
parent_annotations = self._annotations_cache[parent_key]
3401
return parent_annotations, blocks
3402
return annotate.Annotator._get_parent_annotations_and_matches(self,
3403
key, text, parent_key)
3405
def _process_pending(self, key):
3406
"""The content for 'key' was just processed.
3408
Determine if there is any more pending work to be processed.
3411
if key in self._pending_deltas:
3412
compression_parent = key
3413
children = self._pending_deltas.pop(key)
3414
for child_key, parent_keys, record, record_details in children:
3415
lines = self._expand_record(child_key, parent_keys,
3417
record, record_details)
3418
if self._check_ready_for_annotations(child_key, parent_keys):
3419
to_return.append(child_key)
3420
# Also check any children that are waiting for this parent to be
3422
if key in self._pending_annotation:
3423
children = self._pending_annotation.pop(key)
3424
to_return.extend([c for c, p_keys in children
3425
if self._check_ready_for_annotations(c, p_keys)])
3428
def _check_ready_for_annotations(self, key, parent_keys):
3429
"""return true if this text is ready to be yielded.
3431
Otherwise, this will return False, and queue the text into
3432
self._pending_annotation
3434
for parent_key in parent_keys:
3435
if parent_key not in self._annotations_cache:
3436
# still waiting on at least one parent text, so queue it up
3437
# Note that if there are multiple parents, we need to wait
3439
self._pending_annotation.setdefault(parent_key,
3440
[]).append((key, parent_keys))
3444
def _extract_texts(self, records):
3445
"""Extract the various texts needed based on records"""
2608
3446
# We iterate in the order read, rather than a strict order requested
2609
3447
# However, process what we can, and put off to the side things that
2610
3448
# still need parents, cleaning them up when those parents are
2612
for (rev_id, record,
2613
digest) in self._knit._read_records_iter(records):
2614
if rev_id in self._annotated_lines:
3451
# 1) As 'records' are read, see if we can expand these records into
3452
# Content objects (and thus lines)
3453
# 2) If a given line-delta is waiting on its compression parent, it
3454
# gets queued up into self._pending_deltas, otherwise we expand
3455
# it, and put it into self._text_cache and self._content_objects
3456
# 3) If we expanded the text, we will then check to see if all
3457
# parents have also been processed. If so, this text gets yielded,
3458
# else this record gets set aside into pending_annotation
3459
# 4) Further, if we expanded the text in (2), we will then check to
3460
# see if there are any children in self._pending_deltas waiting to
3461
# also be processed. If so, we go back to (2) for those
3462
# 5) Further again, if we yielded the text, we can then check if that
3463
# 'unlocks' any of the texts in pending_annotations, which should
3464
# then get yielded as well
3465
# Note that both steps 4 and 5 are 'recursive' in that unlocking one
3466
# compression child could unlock yet another, and yielding a fulltext
3467
# will also 'unlock' the children that are waiting on that annotation.
3468
# (Though also, unlocking 1 parent's fulltext, does not unlock a child
3469
# if other parents are also waiting.)
3470
# We want to yield content before expanding child content objects, so
3471
# that we know when we can re-use the content lines, and the annotation
3472
# code can know when it can stop caching fulltexts, as well.
3474
# Children that are missing their compression parent
3476
for (key, record, digest) in self._vf._read_records_iter(records):
3478
details = self._all_build_details[key]
3479
(_, compression_parent, parent_keys, record_details) = details
3480
lines = self._expand_record(key, parent_keys, compression_parent,
3481
record, record_details)
3483
# Pending delta should be queued up
2616
parent_ids = self._revision_id_graph[rev_id]
2617
parent_ids = [p for p in parent_ids if p not in self._ghosts]
2618
details = self._all_build_details[rev_id]
2619
(index_memo, compression_parent, parents,
2620
record_details) = details
2621
nodes_to_annotate = []
2622
# TODO: Remove the punning between compression parents, and
2623
# parent_ids, we should be able to do this without assuming
2625
if len(parent_ids) == 0:
2626
# There are no parents for this node, so just add it
2627
# TODO: This probably needs to be decoupled
2628
fulltext_content, delta = self._knit._factory.parse_record(
2629
rev_id, record, record_details, None)
2630
fulltext = self._add_fulltext_content(rev_id, fulltext_content)
2631
nodes_to_annotate.extend(self._add_annotation(rev_id, fulltext,
2632
parent_ids, left_matching_blocks=None))
2634
child = (rev_id, parent_ids, record)
2635
# Check if all the parents are present
2636
self._check_parents(child, nodes_to_annotate)
2637
while nodes_to_annotate:
2638
# Should we use a queue here instead of a stack?
2639
(rev_id, parent_ids, record) = nodes_to_annotate.pop()
2640
(index_memo, compression_parent, parents,
2641
record_details) = self._all_build_details[rev_id]
2642
if compression_parent is not None:
2643
comp_children = self._compression_children[compression_parent]
2644
if rev_id not in comp_children:
2645
raise AssertionError("%r not in compression children %r"
2646
% (rev_id, comp_children))
2647
# If there is only 1 child, it is safe to reuse this
2649
reuse_content = (len(comp_children) == 1
2650
and compression_parent not in
2651
self._nodes_to_keep_annotations)
2653
# Remove it from the cache since it will be changing
2654
parent_fulltext_content = self._fulltext_contents.pop(compression_parent)
2655
# Make sure to copy the fulltext since it might be
2657
parent_fulltext = list(parent_fulltext_content.text())
2659
parent_fulltext_content = self._fulltext_contents[compression_parent]
2660
parent_fulltext = parent_fulltext_content.text()
2661
comp_children.remove(rev_id)
2662
fulltext_content, delta = self._knit._factory.parse_record(
2663
rev_id, record, record_details,
2664
parent_fulltext_content,
2665
copy_base_content=(not reuse_content))
2666
fulltext = self._add_fulltext_content(rev_id,
2668
blocks = KnitContent.get_line_delta_blocks(delta,
2669
parent_fulltext, fulltext)
2671
fulltext_content = self._knit._factory.parse_fulltext(
2673
fulltext = self._add_fulltext_content(rev_id,
2676
nodes_to_annotate.extend(
2677
self._add_annotation(rev_id, fulltext, parent_ids,
2678
left_matching_blocks=blocks))
2680
def _get_heads_provider(self):
2681
"""Create a heads provider for resolving ancestry issues."""
2682
if self._heads_provider is not None:
2683
return self._heads_provider
2684
parent_provider = _mod_graph.DictParentsProvider(
2685
self._revision_id_graph)
2686
graph_obj = _mod_graph.Graph(parent_provider)
2687
head_cache = _mod_graph.FrozenHeadsCache(graph_obj)
2688
self._heads_provider = head_cache
2691
def annotate(self, key):
2692
"""Return the annotated fulltext at the given key.
2694
:param key: The key to annotate.
2696
if True or len(self._knit._fallback_vfs) > 0:
2697
# stacked knits can't use the fast path at present.
2698
return self._simple_annotate(key)
2699
records = self._get_build_graph(key)
2700
if key in self._ghosts:
2701
raise errors.RevisionNotPresent(key, self._knit)
2702
self._annotate_records(records)
2703
return self._annotated_lines[key]
2705
def _simple_annotate(self, key):
2706
"""Return annotated fulltext, rediffing from the full texts.
2708
This is slow but makes no assumptions about the repository
2709
being able to produce line deltas.
2711
# TODO: this code generates a parent maps of present ancestors; it
2712
# could be split out into a separate method, and probably should use
2713
# iter_ancestry instead. -- mbp and robertc 20080704
2714
graph = _mod_graph.Graph(self._knit)
2715
head_cache = _mod_graph.FrozenHeadsCache(graph)
2716
search = graph._make_breadth_first_searcher([key])
2720
present, ghosts = search.next_with_ghosts()
2721
except StopIteration:
2723
keys.update(present)
2724
parent_map = self._knit.get_parent_map(keys)
2726
reannotate = annotate.reannotate
2727
for record in self._knit.get_record_stream(keys, 'topological', True):
2729
fulltext = split_lines(record.get_bytes_as('fulltext'))
2730
parents = parent_map[key]
2731
if parents is not None:
2732
parent_lines = [parent_cache[parent] for parent in parent_map[key]]
2735
parent_cache[key] = list(
2736
reannotate(parent_lines, fulltext, key, None, head_cache))
2738
return parent_cache[key]
2740
raise errors.RevisionNotPresent(key, self._knit)
3485
# At this point, we may be able to yield this content, if all
3486
# parents are also finished
3487
yield_this_text = self._check_ready_for_annotations(key,
3490
# All parents present
3491
yield key, lines, len(lines)
3492
to_process = self._process_pending(key)
3494
this_process = to_process
3496
for key in this_process:
3497
lines = self._text_cache[key]
3498
yield key, lines, len(lines)
3499
to_process.extend(self._process_pending(key))
2744
from bzrlib._knit_load_data_c import _load_data_c as _load_data
3502
from bzrlib._knit_load_data_pyx import _load_data_c as _load_data
3503
except ImportError, e:
3504
osutils.failed_to_load_extension(e)
2746
3505
from bzrlib._knit_load_data_py import _load_data_py as _load_data