golang / protobuf

Go support for Google's protocol buffers
BSD 3-Clause "New" or "Revised" License
9.81k stars 1.58k forks source link

[protobuf-go] How to access field extensions. #1528

Open marwan-at-work opened 1 year ago

marwan-at-work commented 1 year ago

Hi there, I have the following protobuf file:

syntax = "proto3";
package example;
option go_package = "...";
import "options.proto";

message MyMessage {
  string ID = 1 [(optionspkg.name) = "id"];
}

And I am writing a plugin in protobuf-go using protogen.

My question is: how can I access options.pkg.name and its value "id" from *protogen.Field?

It seems that I can call field.Desc.Options() which does return *descriptorpb.FieldOptions which has the options in an unexported field : extensionFields protoimpl.ExtensionFields so I'm unable to access it.

Thanks!

marwan-at-work commented 1 year ago

Ah, it looks like I can use this function: https://pkg.go.dev/google.golang.org/protobuf/proto#GetExtension

It might be worth documenting it here?: https://github.com/protocolbuffers/protobuf-go/blob/eba8b0975f4efc219baabc1e0e13df28a6e1ad28/reflect/protoreflect/type.go#L109

emicklei commented 1 month ago

One hint that could have helped me is that the protoreflect.ExtensionType argument instance can be found in the generated proto definition of your extension.

For example in my protocheck package, I have this code line:

ext, ok := proto.GetExtension(fops, protocheck.E_Field).(*protocheck.Check)