generate method
Generates Dart code for an input Dart library.
May create additional outputs through the buildStep, but the 'primary'
output is Dart code returned through the Future. If there is nothing to
generate for this library may return null, or a Future that resolves to
null or the empty string.
Implementation
@override
FutureOr<String?> generate(LibraryReader library, BuildStep buildStep) async {
final DartFormatter formatter = DartFormatter();
final assetId = await buildStep.resolver.assetIdForElement(library.element);
final mockId = assetId.changeExtension('.mocks.dart');
final currentPath =
"${Directory.current.path}${Platform.pathSeparator}${assetId.path}";
String currentFileContent = await buildStep.readAsString(assetId);
final RegExp regex = RegExp(r"\/\/\/\#\#\#(.+?)\#\#\#");
final String functionIdentifier =
regex.firstMatch(currentFileContent)?.group(1) ?? '';
//Write Test File
final testFile = File(currentPath.replaceAll(
RegExp(r'\d+\.wt'), functionIdentifier + ".welltested_test"))
..createSync(recursive: true);
await testFile.writeAsString(
formatter.format(currentFileContent.replaceAll(regex, '')));
String? mockFileContent;
try {
mockFileContent = await buildStep.readAsString(mockId);
} catch (_) {}
///Write Mock File If Exists
if (mockFileContent != null && mockFileContent.isNotEmpty) {
final mockFile = File(currentPath.replaceAll(
RegExp(r'\d+\.wt'), functionIdentifier + ".welltested_test.mocks"))
..createSync(recursive: true);
await mockFile.writeAsString(mockFileContent);
}
return null;
}