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 {
  if (_fileToProcess == null) {
    _fileToProcess = Completer();
    try {
      final files = await _collectDartFiles();
      final finder = PragmaAnnotatedLibraryFinder(
          filePaths: files,
          test: (String name) {
            return name == PragmaAnnotations.build;
          });
      final found = finder.find();
      _fileToProcess!.complete(found.toSet());
      final result = <String>[];
      final resolver = buildStep.resolver;
      for (var file in found) {
        file = p.normalize(file);
        result.add(file);
        final base = Directory.current.path;
        final package = p.split(base).last;
        final path = PathHelper.pathToFileUri(p.relative(file, from: base));
        final assetId = AssetId.parse('$package|$path');
        final library = await resolver.libraryFor(assetId);
        final session = library.session;
        final libraryResult = await session
            .getResolvedLibrary('/$package/$path') as ResolvedLibraryResult;
        _libraryResults.add(libraryResult);
      }

      _readyForBuild.complete();
    } catch (e, s) {
      _fileToProcess!.completeError(e, s);
    }
  }

  final filesToProcess = await _fileToProcess!.future;
  final inputId = buildStep.inputId;
  var path = inputId.path;
  final base = Directory.current.path;
  path = p.join(base, path);
  path = p.normalize(path);
  if (!filesToProcess.contains(path)) {
    return '';
  }

  await _readyForBuild.future;
  await buildStep.fetchResource(_reflection);
  final filePath = '/${inputId.package}/${inputId.path}';
  final source = await _build(library.element, buildStep, filePath);
  return source;
}