如何使用protobuf-gradle-plugin指定Protobuf路径

How to specify the Protobuf path using protobuf-gradle-plugin

我正在尝试在另一个 Git 存储库中定义的 Java 项目中生成 Protobuf,我想将其添加为 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)。 Protobufs 依次位于 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 以指定此路径?

我最终解决了这个问题:Java 项目实际上不需要包含相对 Protobuf 导入的包,而需要的包不包含相对导入,所以我修改了 sourceSetsbuild.gradle 就像

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 路径。

我在文档中找到了这个: https://github.com/google/protobuf-gradle-plugin#customizing-source-directories

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'
    }
  }
}