generate method

  1. @override
Future<String?> generate(
  1. LibraryReader library,
  2. BuildStep buildStep
)

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
Future<String?> generate(LibraryReader library, BuildStep buildStep) async {
  var parsedLibraryResults = ParsedLibraryResults();

  // Workaround for https://github.com/google/built_value.dart/issues/941.
  LibraryElement libraryElement;
  var attempts = 0;
  while (true) {
    try {
      libraryElement = await buildStep.resolver.libraryFor(
          await buildStep.resolver.assetIdForElement(library.element));
      parsedLibraryResults.parsedLibraryResultOrThrowingMock(libraryElement);
      break;
    } catch (_) {
      ++attempts;
      if (attempts == 10) {
        log.severe('Analysis session did not stabilize after ten tries!');
        return null;
      }
    }
  }

  var result = StringBuffer();
  try {
    final enumCode = EnumSourceLibrary(parsedLibraryResults, libraryElement)
        .generateCode();
    if (enumCode != null) result.writeln(enumCode);
    final serializerSourceLibrary =
        SerializerSourceLibrary(parsedLibraryResults, libraryElement);
    if (serializerSourceLibrary.needsBuiltJson ||
        serializerSourceLibrary.hasSerializers) {
      result.writeln(serializerSourceLibrary.generateCode());
    }
  } on InvalidGenerationSourceError catch (e, st) {
    result.writeln(_error(e.message));
    log.severe(
        'Error in BuiltValueGenerator for '
        '${libraryElement.source.fullName}.',
        e,
        st);
  } catch (e, st) {
    result.writeln(_error(e.toString()));
    log.severe(
        'Unknown error in BuiltValueGenerator for '
        '${libraryElement.source.fullName}.',
        e,
        st);
  }

  for (var element in libraryElement.units.expand((unit) => unit.classes)) {
    if (ValueSourceClass.needsBuiltValue(element)) {
      try {
        result.writeln(
            ValueSourceClass(parsedLibraryResults, element).generateCode());
      } catch (e, st) {
        result.writeln(_error(e));
        log.severe('Error in BuiltValueGenerator for $element.', e, st);
      }
    }
  }

  if (result.isNotEmpty) {
    return '$result'
        '\n'
        '// ignore_for_file: '
        'deprecated_member_use_from_same_package,'
        'type=lint';
  } else {
    return null;
  }
}