如何使用Protobuf-gradle插件指定Protobuf路径



我正在尝试在Java项目中生成Protobuf,这些项目在另一个Git存储库中定义,我想将其添加为Git子模块。我的build.gradle包含

protobuf {
protoc {
artifact = "com.google.protobuf:protoc:4.0.0-rc-2"
}
plugins {
grpc {
artifact = "io.grpc:protoc-gen-grpc-java:${grpcVersion}"
}
}
generateProtoTasks {
all()*.plugins {
grpc {}
}
}
}
// Inform IDEs like IntelliJ IDEA, Eclipse or NetBeans about the generated code.
sourceSets {
main {
java {
srcDirs 'build/generated/source/proto/main/grpc'
srcDirs 'build/generated/source/proto/main/java'
}
}
}

我已经在src/main/proto目录中包含了protobufs存储库(称为my-protobufs(。Protobuf依次位于my-protobufsproto子目录中。部分目录结构如下所示:

src/main/proto/edm-grpc-protobufs/proto
├── mypackage
│   └── v1
│       ├── bar.proto
│       └── foo.proto

foo.proto文件有一个import语句,如下所示:

import "mypackage/v1/bar.proto";

这是因为在该存储库中,Protobuf路径是proto目录。问题是,当我尝试./gradlew build时,我会得到如下错误:

> Task :generateProto FAILED
FAILURE: Build failed with an exception.
* What went wrong:
Execution failed for task ':generateProto'.
> protoc: stdout: . stderr: mypackage/v1/bar.proto: File not found.
my-protobufs/proto/mypackage/v1/foo.proto:5:1: Import "axmorg/v1/bar.proto" was not found or had errors.
my-protobufs/proto/mypackage/v1/foo.proto:10:5: "SourceType" is not defined.

问题基本上是--proto_path(用protoc的说法(或搜索导入的目录没有正确定义,所以protobuf-gradle-plugin不知道在哪里可以找到它们。是否可以更新build.gradle以指定此路径?

我在模具文档中发现了这一点:https://github.com/google/protobuf-gradle-plugin#customizing-源目录

sourceSets {
main {
proto {
// In addition to the default 'src/main/proto'
srcDir 'src/main/protobuf'
srcDir 'src/main/protocolbuffers'
// In addition to the default '**/*.proto' (use with caution).
// Using an extension other than 'proto' is NOT recommended,
// because when proto files are published along with class files, we can
// only tell the type of a file from its extension.
include '**/*.protodevel'
}
java {
...
}
}
test {
proto {
// In addition to the default 'src/test/proto'
srcDir 'src/test/protocolbuffers'
}
}
}

我最终解决了这个问题:Java项目实际上不需要包含相对Protobuf导入的包,而需要的包不包含相对导入,所以我将build.gradle中的sourceSets修改为类似

sourceSets {
main {
java {
srcDirs 'build/generated/source/proto/main/grpc'
srcDirs 'build/generated/source/proto/main/java'
}
proto {
exclude '**/*.proto'
include 'my-protobufs/proto/mypackage/**/*.proto'
}
}
}

它绕过了Protobuf路径的问题,因为不再有任何导入。不过,我仍然很好奇如何指定Protobuf路径。

最新更新