generateForAnnotatedElement method

  1. @override
dynamic generateForAnnotatedElement(
  1. Element element,
  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
dynamic generateForAnnotatedElement(
    Element element, ConstantReader annotation, BuildStep buildStep) {
  try {
    assert(element is ClassElement, "@grunt must only be applied to class");
    final cls = element as ClassElement;
    final logLevel = annotation.read("logLevel").stringValue;
    final logOutput = annotation.read("logOutput").stringValue;
    var mixin = <String>[];
    mixin += [
      "",
      "import 'package:logging/logging.dart';",
      "import 'package:logging_config/logging_config.dart';",
      "import 'package:worker_service/work_in_ww.dart';",
      "import '${buildStep.inputId.uri}';",
      "",
      "final _log = Logger(\"grunt${cls.name}\");",
      "void main() async {",
      "  await configureLogging(LogConfig.root(Level.$logLevel, handler: LoggingHandler.$logOutput()));",
      "  _log.info('Configured logging: $logLevel, $logOutput');",
      "  var channel = GruntChannel.create(${cls.name}());",
      "  await channel.done;",
      '  _log.info("Job ${cls.name} is done");',
      "}",
    ];
    return mixin.join("\n");
  } catch (e) {
    print(e);
  }
}