generateForAnnotatedElement method

  1. @override
Future<String> generateForAnnotatedElement(
  1. Element classElement,
  2. ConstantReader annotation,
  3. BuildStep buildStep
)

Implement to return source code to generate for element.

This method is invoked based on finding elements annotated with an instance of T. The annotation is provided as a ConstantReader.

Supported return values include a single String or multiple String instances within an Iterable or Stream. It is also valid to return a Future of String, Iterable, or Stream.

Implementations should return null when no content is generated. Empty or whitespace-only String instances are also ignored.

Implementation

@override
Future<String> generateForAnnotatedElement(Element classElement,
    ConstantReader annotation, BuildStep buildStep) async {
  if (classElement is! ClassElement) {
    throw 'This annotation can only be used on classes. Offending Element: $classElement';
  }

  final configList = annotation.read('configFiles').listValue;

  if (configList.isEmpty) {
    throw 'configFiles list cannot be empty!  Offending Element: $classElement';
  }

  final buffer = StringBuffer();

  for (final configFile in configList) {
    final filePath = configFile.getField('path')?.toStringValue();
    if (filePath == null) {
      throw "error: path was null in ${configFile} from at annotation ${annotation}";
    }
    final assets = await buildStep
        .findAssets(Glob(filePath, caseSensitive: true))
        .toList();
    if (assets.isEmpty) {
      throw "no file found for argument $filePath";
    }
    if (assets.length > 1) {
      throw "error: multiple files found that match $filePath!";
    }
    final assetId = assets.first;
    final jsonString = await buildStep.readAsString(assetId);
    final configName = configFile.getField('configName')?.toStringValue();
    final code =
        generateCodeForFile(filePath, classElement, jsonString, configName);
    buffer.write(code);
  }
  return buffer.toString();
}