5

I'm trying to write a custom code generator for an in-house proprietary programming language. I figured I could write the generator in Java, using the protoc plugin guide. My main() does something like this:

public static void main(String[] args) throws IOException {
    CodeGenerator gen = new CodeGenerator();
    PluginProtos.CodeGeneratorRequest codeGeneratorRequest = PluginProtos.CodeGeneratorRequest.parseFrom(args[0].getBytes());
    codeGeneratorRequest.getProtoFileList().forEach(gen::handleFile);
    // get the response and do something with it 
    //PluginProtos.CodeGeneratorResponse response = PluginProtos.CodeGeneratorResponse.newBuilder().build();
    //response.writeTo(System.out);
}

(Obviously I've only just started; wanted to get something stubby working first before actually writing the generation logic)

Problem is: how do I invoke protoc with the --plugin argument to generate code in my custom language, using my plugin? I tried writing a shell script to do it like this:

#!/bin/bash
java -cp ./codegen.jar CodeGeneratorMain "$@"

And I tried invoking protoc like this: protoc --plugin=protoc-gen-code --code_out=./build hello.proto however, when I run that, I get this error:

Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 0 at CodeGeneratorMain.main(CodeGeneratorMain.java:12) --code_out: protoc-gen-code: Plugin failed with status code 1.

As though it's not passing the CodeGeneratorRequest on stdin at all. How would I verify that? Am I doing something obviously wrong?

FreeMemory
  • 8,444
  • 7
  • 37
  • 49
  • Potentially a bit OT: if you're just looking to do Java code generation it might be worth a look at https://github.com/square/javapoet – Mark Elliot Jan 02 '17 at 20:29
  • I'm not looking to generate Java classes. ProtoBufs already can generate Java source. This is a Java plugin to generate non-Java code. – FreeMemory Jan 02 '17 at 20:32
  • how did you get this working. I am doing the same thing. How do you relate the shell script and protoc. I keep getting error saying program not found or is not executable. Can you help me with this please? https://stackoverflow.com/questions/62168625/protoc-custom-plugin-erroring-out-with-program-not-found-or-is-not-executable – User Jun 04 '20 at 03:28

1 Answers1

1

So after reading and re-reading the docs I realized my very silly error: protoc passes the parsed input via stdin not via argv. That means that if I change this: PluginProtos.CodeGeneratorRequest codeGeneratorRequest = PluginProtos.CodeGeneratorRequest.parseFrom(args[0].getBytes()); to this: PluginProtos.CodeGeneratorRequest codeGeneratorRequest = PluginProtos.CodeGeneratorRequest.parseFrom(System.in);

it works.

FreeMemory
  • 8,444
  • 7
  • 37
  • 49