build method

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

Generates the outputs for a given BuildStep.

Implementation

@override
Future<void> build(BuildStep buildStep) async {
  final inputId = buildStep.inputId;
  if (!inputId.path.endsWith('.graphql') && !inputId.path.endsWith('.gql')) {
    return;
  }
  final content = await buildStep.readAsString(inputId);
  final schemaPath = config.schemaPath;
  final sharedDir = config.sharedDir;

  String? schemaContent;
  if (schemaPath != null &&
      p.normalize(schemaPath) != p.normalize(inputId.path)) {
    final schemaAssetId = AssetId(inputId.package, schemaPath);
    if (await buildStep.canRead(schemaAssetId)) {
      schemaContent = await buildStep.readAsString(schemaAssetId);
    } else {
      try {
        schemaContent = File(schemaPath).readAsStringSync();
      } catch (e, st) {
        log.warning(
          'mk_graphql_generator: could not read schema file $schemaPath '
          'for ${inputId.path} — generating without schema-derived types '
          '(utility selection sets, enums, custom scalars) for this file.',
          e,
          st,
        );
      }
    }
  }

  final cachedParse = _parsedCache[inputId.path];
  final preParsed = cachedParse != null && cachedParse.content == content
      ? cachedParse.parsed
      : null;

  final bundle = await GeneratorOrchestrator.generateForGraphQLFile(
    content: content,
    inputPath: inputId.path,
    schemaPath: schemaPath,
    sharedDir: sharedDir,
    schemaContent: schemaContent,
    packageName: inputId.package,
    customScalars: config.scalars,
    useCache: config.cache,
    preParsed: preParsed,
  );

  final baseDir = p.dirname(inputId.path);

  for (final entry in bundle.files.entries) {
    final targetPath = p.normalize(p.join(baseDir, entry.key));
    final outputId = AssetId(inputId.package, targetPath);
    await buildStep.writeAsString(outputId, entry.value);
  }
}