如果您正在寻找示例 gradle protobuf 项目,请查看 here .
我很难使用 gradle 和 protobuf,
我想创建一个简单的 gradle 项目,它将从默认 src/main/proto
、src/test/proto
获取任何 proto 文件并将它们编译为 src/main/java
, src/test/java
相应地,然后将其打包到 jar 中并发布到本地 repo。
不幸的是,我是 gradle 新手,无法弄清楚原始项目是如何组成的。
这是我未完成的 build.gradle 文件
apply plugin: 'java'
apply plugin: "com.google.protobuf"
buildscript {
repositories {
mavenCentral()
}
dependencies {
classpath 'com.google.protobuf:protobuf-gradle-plugin:0.7.0'
}
}
repositories {
mavenCentral()
}
dependencies {
compile 'com.google.protobuf:protobuf-java:3.0.0-beta-1'
}
sourceSets {
main {
proto {
srcDir 'src/main/proto'
}
java {
srcDir 'src/main/java'
}
}
test {
proto {
srcDir 'src/test/proto'
}
proto {
srcDir 'src/test/java'
}
}
}
protobuf {
// Configure the protoc executable
protoc {
// Download from repositories
artifact = 'com.google.protobuf:protoc:3.0.0-alpha-3'
}
generateProtoTasks {
// all() returns the collection of all protoc tasks
all().each { task ->
// Here you can configure the task
}
// In addition to all(), you may get the task collection by various
// criteria:
// (Java only) returns tasks for a sourceSet
ofSourceSet('main')
}
}
运行 jar 任务后,我们有这个:
您可以看到 gradle 将测试和主原型(prototype)构建到同一个类目录(红色箭头),在 jar 中我可以看到包含两个生成的类(而应该跳过测试)。
但主要问题是我想让 将 proto 文件直接编译到适当的源目录(蓝色箭头),之后普通构建会做正确的事情......毕竟我们需要那些src 中的类以在业务逻辑中使用它们...
所以我们只需要一项将 proto 编译到适当 src 目录的任务......仅此而已。
src/main/proto to src/main/java
src/test/proto to src/test/java
当前项目位于 here .请帮忙配置一下,我很确定以后会有很多人需要它...
最佳答案
如果我没有误解您的问题,那么解决起来很简单。如果您不想区分自己的源和生成的源,您只需像这样添加设置 generatedFileBaseDir generateProtoTasks.generatedFilesBaseDir = 'src'
所以整个构建文件看起来像:
// ...
protobuf {
// Configure the protoc executable
protoc {
// Download from repositories
artifact = 'com.google.protobuf:protoc:3.0.0-alpha-3'
}
generateProtoTasks.generatedFilesBaseDir = 'src' // <- that line
generateProtoTasks {
// all() returns the collection of all protoc tasks
all().each { task ->
// Here you can configure the task
}
比你的文件夹看起来像:
但是: 这可能不是将生成与手工源代码混合的最佳主意。所以我的建议是将源代码生成到自己的目录中,如 generatedSources 并将这个目录添加到 java sourceSet。构建文件如下所示:
sourceSets {
main {
proto {
srcDir 'src/main/proto'
}
java {
// include self written and generated code
srcDirs 'src/main/java', 'generated-sources/main/java'
}
}
// remove the test configuration - at least in your example you don't have a special test proto file
}
protobuf {
// Configure the protoc executable
protoc {
// Download from repositories
artifact = 'com.google.protobuf:protoc:3.0.0-alpha-3'
}
generateProtoTasks.generatedFilesBaseDir = 'generated-sources'
generateProtoTasks {
// all() returns the collection of all protoc tasks
all().each { task ->
// Here you can configure the task
}
// In addition to all(), you may get the task collection by various
// criteria:
// (Java only) returns tasks for a sourceSet
ofSourceSet('main')
}
}
您的目录将如下所示
一个很好的副作用是你可以在你的 git 配置中忽略这个 generated-sources 目录。最好不要发布生成的源代码。
https://stackoverflow.com/questions/32820728/