5

我正在尝试为内部专有编程语言编写自定义代码生成器。我想我可以使用 protoc 插件指南用 Java 编写生成器。我的 main() 做这样的事情:

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);
}

(显然我才刚刚开始;想要在实际编写生成逻辑之前先让一些粗短的东西工作)

问题是:如何使用我的插件调用带有 --plugin 参数的 protoc 以我的自定义语言生成代码?我尝试编写一个 shell 脚本来做到这一点:

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

我尝试像这样调用 protoc:protoc --plugin=protoc-gen-code --code_out=./build hello.proto但是,当我运行它时,我收到了这个错误:

线程“主”java.lang.ArrayIndexOutOfBoundsException 中的异常:CodeGeneratorMain.main 中的 0(CodeGeneratorMain.java:12)--code_out:protoc-gen-code:插件失败,状态码为 1。

好像它根本没有在标准输入上传递 CodeGeneratorRequest。我将如何验证?我在做一些明显错误的事情吗?

4

1 回答 1

1

因此,在阅读和重新阅读文档后,我意识到我的非常愚蠢的错误:protoc 通过stdin 而不是通过 argv 传递解析的输入。这意味着如果我将其更改PluginProtos.CodeGeneratorRequest codeGeneratorRequest = PluginProtos.CodeGeneratorRequest.parseFrom(args[0].getBytes());为:PluginProtos.CodeGeneratorRequest codeGeneratorRequest = PluginProtos.CodeGeneratorRequest.parseFrom(System.in);

有用。

于 2017-01-03T16:47:56.797 回答