Search code examples
protocol-buffers

importing proto from different files


I maintain all my proto files in one folder. An overview:

protos
|
|__auth
|
|__some_other

Inside auth directory I have auth_service.proto user.proto etc.

But I am having issues with importing definitions form user.proto

In auth_service.proto:

syntax="proto3";

package auth;

import "auth/user.proto"; // Import "auth/user.proto" was not found or had errors.

message SomeMessage {
  User user = 1; // user is not defined
}

user.proto has the same package name:

syntax="proto3";

package auth;

message User{}

Protoc version: libprotoc : 3.19.4


Solution

  • This can be tricky.

    One way to think about it is that you need to determine the root of the import path and then proto imports are relative to it.

    Assuming ${PWD} is the parent of protos.

    Example #1:

    If you use ${PWD} as the proto_path:

    protoc \
    --proto_path=${PWD} \
    --go_out=${PWD} \
      ${PWD}/protos/auth/auth_service.proto \
      ${PWD}/protos/auth/user.proto
    

    Then the import should be import "protos/auth/user.proto";

    Example #2:

    If you use protos as the proto_path:

    protoc \
    --proto_path=${PWD}/protos \
    --go_out=${PWD} \
      ${PWD}/protos/auth/auth_service.proto \
      ${PWD}/protos/auth/user.proto
    

    Then the import should be import "auth/user.proto";.

    NOTE In all cases, the proto file references must be prefixed by (one of) a proto_path.

    settings.json:

    "protoc": {
        "path": "${workspaceRoot}/protoc-21.2-linux-x86_64/bin/protoc",
        "compile_on_save": true,
        "options": [
            "--proto_path=${workspaceRoot}/protoc-21.2-linux-x86_64/include",
            "--proto_path=${workspaceRoot}/protos",
            "--go_out=${workspaceRoot}"
        ]
    }