checkAssets function

DoctorCheck checkAssets({
  1. String projectRoot = '.',
})

Images in assets/images (or public/images) that nothing refers to.

Implementation

DoctorCheck checkAssets({String projectRoot = '.'}) {
  final _Project p = _Project(projectRoot);
  final String? folder = ['assets/images', 'public/images']
      .where((String path) => Directory('${p.root}/$path').existsSync())
      .firstOrNull;
  if (folder == null) {
    return const DoctorCheck(
      'Assets',
      DoctorStatus.skipped,
      'No assets/images folder',
    );
  }
  final List<String> images = p.files(folder);
  if (images.isEmpty) {
    return DoctorCheck('Assets', DoctorStatus.skipped, 'No images in $folder');
  }

  final String code = [
    ...p.dart('lib').values,
    p.read('pubspec.yaml') ?? '',
  ].join('\n');
  final List<String> unused = [
    for (final String image in images)
      if (!_mentions(code, _assetName(image.substring(folder.length + 1))))
        image,
  ];
  if (unused.isEmpty) {
    return DoctorCheck(
      'Assets',
      DoctorStatus.ok,
      images.length == 1
          ? 'The image in $folder is referenced'
          : 'All ${images.length} images in $folder are referenced',
    );
  }
  return DoctorCheck(
    'Assets',
    DoctorStatus.note,
    unused.length == 1
        ? '1 image in $folder is never referenced: ${unused.single}'
        : '${unused.length} images in $folder are never referenced',
    details: unused.length == 1 ? const [] : unused,
  );
}