saveStatsCache method
Save the stats cache to disk atomically. Uses a temp file + rename pattern to prevent corruption.
Implementation
Future<void> saveStatsCache(PersistedStatsCache cache) async {
final cachePath = getStatsCachePath();
final tempPath = '$cachePath.${DateTime.now().microsecondsSinceEpoch}.tmp';
try {
final configDir = Directory(_configHomeDir);
if (!await configDir.exists()) {
await configDir.create(recursive: true);
}
final content = const JsonEncoder.withIndent(
' ',
).convert(cache.toJson());
final tempFile = File(tempPath);
await tempFile.writeAsString(content, flush: true);
// Atomic rename.
await tempFile.rename(cachePath);
} catch (_) {
// Clean up temp file.
try {
await File(tempPath).delete();
} catch (_) {
// Ignore cleanup errors.
}
}
}