pruneFlutterTestKernelCache function
Bounds Flutter's generated per-define kernel cache after a suite completes. Keep recent entries warm while preventing unique test options from growing the app's ignored build directory without limit.
Implementation
void pruneFlutterTestKernelCache(
Directory project, {
// A single generated test kernel is typically around 120 MiB. Keeping one
// warm kernel avoids recompiling the common path without allowing distinct
// compile configurations to accumulate into multiple GiB.
int maxBytes = 160 * 1024 * 1024,
}) {
final cache = Directory(
p.join(project.path, 'build', 'test_cache', 'build'),
);
if (!cache.existsSync()) return;
final files = cache
.listSync(followLinks: false)
.whereType<File>()
.where((file) =>
file.path.endsWith('.cache.dill.track.dill') ||
file.path.endsWith('.cache.dill'))
.toList()
..sort((left, right) =>
right.lastModifiedSync().compareTo(left.lastModifiedSync()));
var retainedBytes = 0;
for (final file in files) {
final size = file.lengthSync();
if (size <= maxBytes && retainedBytes + size <= maxBytes) {
retainedBytes += size;
} else {
file.deleteSync();
}
}
}