checkDecoders function
API services, controllers and models the app uses that
lib/bootstrap/decoders.dart doesn't register.
Implementation
DoctorCheck checkDecoders({String projectRoot = '.'}) {
final _Project p = _Project(projectRoot);
final String? decoders = p.read(_decodersPath);
if (decoders == null) {
return const DoctorCheck(
'Decoders',
DoctorStatus.skipped,
'No $_decodersPath',
);
}
final String registry = withoutComments(decoders);
final Map<String, String> lib = p.dart('lib')..remove(_decodersPath);
// Only the project's own classes can be registered by the project.
final Set<String> declared = {
for (final String source in lib.values)
for (final RegExpMatch match in _classDeclaration.allMatches(source))
match.group(1)!,
};
final Set<String> models = {
for (final MapEntry<String, String> entry in lib.entries)
if (entry.key.startsWith('lib/app/models/'))
for (final RegExpMatch match in _classDeclaration.allMatches(
entry.value,
))
match.group(1)!,
};
// Each missing class, with the map it belongs in and the first file that
// uses it.
final Map<String, (String, String)> missing = {};
void find(RegExp usage, String map, {Set<String>? only}) {
lib.forEach((String path, String source) {
for (final RegExpMatch match in usage.allMatches(source)) {
final String name = match.group(1)!;
if (!declared.contains(name)) continue;
if (only != null && !only.contains(name)) continue;
if (RegExp('\\b$name\\b').hasMatch(registry)) continue;
missing.putIfAbsent(name, () => (map, path));
}
});
}
find(RegExp(r'\bapi\s*<\s*([A-Z]\w*)\s*>\s*\('), 'apiDecoders');
find(RegExp(r'\bNyStatefulWidget\s*<\s*([A-Z]\w*)\s*>'), 'controllers');
find(
RegExp(r'\bnetwork\s*<\s*(?:List\s*<\s*)?([A-Z]\w*)'),
'modelDecoders',
only: models,
);
if (missing.isEmpty) {
return const DoctorCheck(
'Decoders',
DoctorStatus.ok,
'Every API service, controller and model in use is registered',
);
}
final bool decodersList = RegExp(r'modelDecoders\s*=\s*decoders\s*\(')
.hasMatch(registry);
String entry(String name, String map) => switch (map) {
'modelDecoders' when decodersList => 'Decode($name.fromJson),',
'modelDecoders' => '$name: (data) => $name.fromJson(data),',
_ => '$name: () => $name(),',
};
final List<String> names = missing.keys.toList()
..sort((String a, String b) => missing[a]!.$2.compareTo(missing[b]!.$2));
return DoctorCheck(
'Decoders',
DoctorStatus.problem,
names.length == 1
? '${names.single} is used but not in ${missing[names.single]!.$1}'
: '${names.length} classes are used but not registered',
details: [
for (final String name in names)
names.length == 1
? 'used in ${missing[name]!.$2}'
: '$name, not in ${missing[name]!.$1}: used in ${missing[name]!.$2}',
],
fixes: [
for (final String name in names)
'add ${entry(name, missing[name]!.$1)} to '
'${missing[name]!.$1} in $_decodersPath',
],
);
}