How to write a custom Protobuf CodeGenerator in Java

时光怂恿深爱的人放手 提交于 2019-12-10 14:25:01

问题


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?


回答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.



来源:https://stackoverflow.com/questions/41432876/how-to-write-a-custom-protobuf-codegenerator-in-java

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!