Skip to content
Advertisement

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

I’m trying to generate Protobufs in a Java project that are defined in another Git repository that I’d like to add as a Git submodule. My build.gradle contains

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

and I’ve included the protobufs repository (called my-protobufs) in the src/main/proto directory. The Protobufs are in turn located in a proto subdirectory of my-protobufs. A partial directory structure looks like this:

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

The foo.proto file has an import statement like this:

import "mypackage/v1/bar.proto";

That is because in that repository, the Protobuf path is the proto directory. The problem is that when I try to ./gradlew build, I get an error like the following:

> 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.

The problem is basically that the --proto_path (in the parlance of protoc) or the directory in which to search for imports is not correctly defined, so protobuf-gradle-plugin doesn’t know where to find them. Is is possible to update the build.gradle to specify this path?

Advertisement

Answer

I found this in die documentation: 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'
    }
  }
}
User contributions licensed under: CC BY-SA
8 People found this is helpful
Advertisement