Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I Import a .proto file from a dependency jar using gradle

I have a project that creates a set of protobuf objects and GRPC stubs.

I have a dependency on a jar with other .proto files in it, that I would like to use in my project.

ie:

project-abc-0.0.1.jar contains a file: /some-types.proto It contains these pieces:

package foo_companyname;
message StatusItem {
    string status = 1;
    string statusDescription = 2;
}

my project has a build.gradle file where I am trying to import it like so:

buildscript {
    dependencies {
        classpath 'com.google.protobuf:protobuf-gradle-plugin:0.8.3'
    }
}

dependencies {
    compile(group: 'com.companyname', name: 'project-abc', version: '0.0.1')
}

Then, inside my new "enhanced-status.proto" I'm doing this:

import "foo_companyname/some-types.proto";

message EnhancedStatus{
    string author = 1;
    repeated StatusItem status = 2;
}

If I don't reference the other .proto, everything works fine - I'm able to generate all the correct java any python classes. As soon as I add it, I'm getting this:

Execution failed for task ':generateProto'.
> protoc: stdout: . stderr: foo_companyname/some-types.proto: File not found.
  enhanced-status.proto: Import "foo_companyname/some-types.proto" was not found or had errors.
  enhanced-status.proto:26:19: "StatusItem" is not defined.

I'm assuming there's some trick to getting gradle or protoc to find .proto sources that are in a jar file? Or do I need to extract the jar file's .proto into my own /proto dir? That would cause a conflict, since the jar has a compiled version of some-types.proto already, and I don't want to compile it again.

like image 565
Kylar Avatar asked Feb 08 '18 17:02

Kylar


3 Answers

Using the google protobuf gradle plugin

plugins {
   id 'com.google.protobuf' version "0.8.5"
}

You should just need to specify your dependent jar in the dependencies block (i.e, as a 'protobuf' dependency, not 'compile'):

dependencies {           
    protobuf "com.companyname:project-abc:0.0.1"
}
like image 120
scottsue Avatar answered Nov 18 '22 18:11

scottsue


The Protobuf Plugin for Gradle supports protobuf files in dependencies:

If a compile configuration has a dependency on a project or library jar that contains proto files, they will be added to the --proto_path flag of the protoc command line, so that they can be imported in the proto files of the dependent project. The imported proto files will not be compiled since they have already been compiled in their own projects.

like image 3
Lukas Körfer Avatar answered Nov 18 '22 17:11

Lukas Körfer


You need to add the package name foo_companyname for using StatusItem message, try in this way:

import "foo_companyname/some-types.proto";

message EnhancedStatus{
    string author = 1;
    repeated foo_companyname.StatusItem status = 2;
}
like image 2
Enrico La Sala Avatar answered Nov 18 '22 17:11

Enrico La Sala