expr icon indicating copy to clipboard operation
expr copied to clipboard

Enhance expr.Env() options on structs

Open andrewbenton opened this issue 2 years ago • 1 comments

When passing structs to the expr.Env() option, it would be nice to have a way to modify the field extraction behavior to be able to:

  • extract or map names based on tags such as the common json tag
  • ignore non-exported fields
  • ignore methods

In my particular case, I'm working with protobuf-generated structs and using the expr library as a way to implement a filtering grammar similar to what is described in https://google.aip.dev/160.

Here's an example struct:

type MyType struct {
    state protoimpl.MessageState
    sizeCache protoimpl.SizeCache
    unknownFields protoimpl.UnknownFields

    Id         string                 `protobuf:"bytes,1,opt,name=id,proto3" json:"id,omitempty"`
    Name       string                 `protobuf:"bytes,2,opt,name=name,proto3" json:"name,omitempty"`
    CreateTime *timestamppb.Timestamp `protobuf:"bytes,3,opt,name=create_time,json=createTime,proto3" json:"
}

func (x *MyType) GetId() string {
    if x != nil {
        return x.Id
    }
    return ""
}

/* other generated functions for exported fields */

The above struct results in both the non-exported fields and duplicate methods being made available to the expression context. It also means that the default names in the expression (prior to patching) don't match the names given in the protobuf.

andrewbenton avatar Apr 27 '22 07:04 andrewbenton

Make sense. I'll add it to my todo list :)

antonmedv avatar Apr 27 '22 07:04 antonmedv

Done!

antonmedv avatar Nov 05 '22 18:11 antonmedv