Home > Software engineering >  Go import scope lookup for protobuf types
Go import scope lookup for protobuf types

Time:05-14

I'm building a transpiler and need to understand the protobuf/go scope lookup system. I've been trying to google the docs and finding no luck.

Q: Is there a shared package scope lookup that you can do when importing Types in Go/protobufs?

Here is the example that I'm questioning:

proto1:

package cosmos.crypto.keyring.v1;
...

message Ledger {
    hd.v1.BIP44Params path = 1;
}

proto2:

package cosmos.crypto.hd.v1;
message BIP44Params {
    ...
}

There are two syntaxes I've seen that do make sense so far:

full scope

message Ledger {
    cosmos.crypto.hd.v1.BIP44Params path = 1;
}

Or I’ve also seen versions like this

completely unscoped

message Ledger {
   BIP44Params path = 1;
}

partially scoped?

But the style I'm seeing is partially scoped

message Ledger {
    hd.v1.BIP44Params path = 1;
}

Is the reason they leave off the cosmos.crypto because these two packages share cosmos.crypto in the root of their package name?

Or is it a more generic scope lookup based on the import?

Any insight or reading links appreciated :)

CodePudding user response:

I'm not sure I fully get the question but I will try to answer. Let me know if you need me to change that.

This is a combination of both. You need to have the package and import the .proto file. Let me explain. If you have two file define like this:

proto1.proto

syntax = "proto3";
package cosmos.crypto.keyring.v1;

message Ledger {
    hd.v1.BIP44Params path = 1;
}

proto2.proto

syntax = "proto3";
package cosmos.crypto.hd.v1;

message BIP44Params {}

trying to compile will tell you that "hd.v1.BIP44Params" is not defined. This is because the proto1.proto is not aware of other definitions. Now, if you import "proto2.proto"; in the proto1.proto, it will be aware of the BIP44Params definition and will notice the package definition.

With this package definition, it will be able to access the following type definition:

  • cosmos.crypto.hd.v1.BIP44Params - which is pretty self explanatory
  • hd.v1.BIP44Params - because the two package matches before the hd part.

but it should be able to access:

  • BIP44Params - because there is no such type defined in cosmos.crypto.keyring.v1 package

Hope that's clear

  • Related