build method Null safety

  1. @override
Future<void> build(
  1. BuildStep buildStep
)
inherited

Generates the outputs for a given BuildStep.

Implementation

@override
Future<void> build(BuildStep buildStep) async {
  var resolver = buildStep.resolver;
  var library = await buildStep.inputLibrary;
  var originalLib =
      buildStep.inputId.path.replaceFirst(_inputExtension, '.gen.dart');
  var buffer = StringBuffer('''
// GENERATED FILE - DO NOT EDIT
//
// This file was generated by applying the following macros to the
// `${buildStep.inputId.path}` file:
//
''');
  for (var macro in macros.values) {
    buffer.writeln('//   - ${macro}');
  }
  buffer.writeln('''
//
// To make changes you should edit the `$originalLib` file;
''');
  var ast = await resolver.compilationUnitFor(buildStep.inputId);
  for (var directive in ast.directives) {
    // MEGA HACK: Replace earlier phase imports with next phase ones.
    var directiveSrc =
        directive.toSource().replaceAll(_inputExtension, _outputExtension);
    buffer.writeln(directiveSrc);
  }

  for (var topLevel in library.topLevelElements) {
    await _applyMacros(topLevel, buffer, buffer, resolver,
        await buildStep.readAsString(buildStep.inputId));
  }
  var inputPath = buildStep.inputId.path;
  var outputId = AssetId(
      buildStep.inputId.package,
      inputPath.replaceRange(inputPath.length - _inputExtension.length,
          inputPath.length, _outputExtension));
  try {
    var formatted =
        DartFormatter().format(buffer.toString(), uri: outputId.uri);
    await buildStep.writeAsString(outputId, formatted);
  } catch (e, s) {
    log.severe('Failed to format file $buffer', e, s);
  }
}