getImages function
Scans assetsDir for image files and returns a list of image paths
that are not referenced in any .dart, .yaml, .json, or .html
files inside the lib/ folder of the projectRoot.
Implementation
Future<List<String>> getImages(
Directory assetsDir, Directory projectRoot) async {
final allImages = <String>[];
final usedImages = <String>{};
await for (final file in assetsDir.list(recursive: true)) {
if (file is File && _isImage(file.path)) {
// Use package:path to get the relative path from assetsDir
final relativePath = p
.relative(file.path, from: assetsDir.path)
.replaceAll('\\', '/'); // Normalize separators to '/'
allImages.add(relativePath);
}
}
final libDir = Directory(p.join(projectRoot.path, 'lib'));
if (!await libDir.exists()) {
print('⚠️ Warning: lib folder does not exist: ${libDir.path}');
return allImages;
}
final codeFiles = await _getAllCodeFiles(libDir);
for (final file in codeFiles) {
try {
final content = await file.readAsString();
for (final image in allImages) {
if (content.contains(image)) {
usedImages.add(image);
}
}
} catch (e) {
// Ignore unreadable files
}
}
final unusedImages =
allImages.where((img) => !usedImages.contains(img)).toList();
return unusedImages;
}