generate method

Future<void> generate({
  1. Map<String, SingleOptionParser>? optionParsers,
  2. OutputConfiguration config = const DefaultOutputConfiguration(),
})

Runs the code generator. The optional optionParsers can be used to change how command line options are parsed (see parseGenerationOptions for details), and config can be used to override where generated files are created and how imports between generated files are constructed (see OutputConfiguration for details).

Implementation

Future<void> generate({
  Map<String, SingleOptionParser>? optionParsers,
  OutputConfiguration config = const DefaultOutputConfiguration(),
}) async {
  final extensions = ExtensionRegistry();

  Dart_options.registerAllExtensions(extensions);
  Client.registerAllExtensions(extensions);

  final builder = await _streamIn.fold(
    BytesBuilder(),
    (builder, data) => builder..add(data),
  );
  final bytes = builder.takeBytes();
  // Suppress CodedBufferReader builtin size limitation when reading the
  // request; protobuf definitions can be larger than default limit of 64Mb.
  final reader = CodedBufferReader(bytes, sizeLimit: bytes.length);
  final request = CodeGeneratorRequest();
  request.mergeFromCodedBufferReader(reader, extensions);
  reader.checkLastTagWas(0);

  request.protoFile.sortBy((desc) => desc.name);

  final response = CodeGeneratorResponse();

  // Parse the options in the request. Return the errors if any.
  final options = parseGenerationOptions(request, response, optionParsers);
  if (options == null) {
    _streamOut.add(response.writeToBuffer());
    return;
  }

  // Create a syntax tree for each .proto file given to us.
  // (We may import it even if we don't generate the .pb.dart file.)
  final generators = <FileGenerator>[];
  for (final file in request.protoFile) {
    generators.add(FileGenerator(file, options));
  }

  // Collect field types and importable files.
  link(options, generators);

  // Generate the .pb.dart file if requested.
  for (final gen in generators) {
    final name = gen.descriptor.name;
    if (request.fileToGenerate.contains(name)) {
      response.file.addAll(gen.generateFiles(config));
    }
  }
  response.supportedFeatures =
      Int64(CodeGeneratorResponse_Feature.FEATURE_PROTO3_OPTIONAL.value);
  _streamOut.add(response.writeToBuffer());
}