如何在 Java 中编写自定义 Protobuf CodeGenerator
How to write a custom Protobuf CodeGenerator in Java
我正在尝试为内部专有编程语言编写自定义代码生成器。我想我可以使用 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
然而,当我 运行 那样时,我得到了这个错误:
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.
就好像它根本没有在标准输入上传递 CodeGeneratorRequest 一样。我将如何验证?我做错了什么吗?
所以在阅读和重新阅读文档后,我意识到我非常愚蠢的错误:protoc 通过 stdin not 通过 not 通过argv。这意味着如果我将这个:PluginProtos.CodeGeneratorRequest codeGeneratorRequest = PluginProtos.CodeGeneratorRequest.parseFrom(args[0].getBytes());
更改为:PluginProtos.CodeGeneratorRequest codeGeneratorRequest = PluginProtos.CodeGeneratorRequest.parseFrom(System.in);
有效。
我正在尝试为内部专有编程语言编写自定义代码生成器。我想我可以使用 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
然而,当我 运行 那样时,我得到了这个错误:
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.
就好像它根本没有在标准输入上传递 CodeGeneratorRequest 一样。我将如何验证?我做错了什么吗?
所以在阅读和重新阅读文档后,我意识到我非常愚蠢的错误:protoc 通过 stdin not 通过 not 通过argv。这意味着如果我将这个:PluginProtos.CodeGeneratorRequest codeGeneratorRequest = PluginProtos.CodeGeneratorRequest.parseFrom(args[0].getBytes());
更改为:PluginProtos.CodeGeneratorRequest codeGeneratorRequest = PluginProtos.CodeGeneratorRequest.parseFrom(System.in);
有效。