Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

lib/proto: add support for instantiating proto map fields #491

Merged
merged 1 commit into from
Jul 26, 2023
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
40 changes: 39 additions & 1 deletion lib/proto/proto.go
Original file line number Diff line number Diff line change
Expand Up @@ -395,7 +395,6 @@ func setField(msg protoreflect.Message, fdesc protoreflect.FieldDescriptor, valu
}
defer iter.Done()

// TODO(adonovan): handle maps
list := msg.Mutable(fdesc).List()
list.Truncate(0)
var x starlark.Value
Expand All @@ -409,6 +408,45 @@ func setField(msg protoreflect.Message, fdesc protoreflect.FieldDescriptor, valu
return nil
}

if fdesc.IsMap() {
mapping, ok := value.(starlark.IterableMapping)
if !ok {
return fmt.Errorf("in map field %s: expected mappable type, but got %s", fdesc.Name(), value.Type())
}

iter := mapping.Iterate()
defer iter.Done()

// Each value is converted using toProto as usual, passing the key/value
// field descriptors to check their types.
mutMap := msg.Mutable(fdesc).Map()
var k starlark.Value
for iter.Next(&k) {
adonovan marked this conversation as resolved.
Show resolved Hide resolved
kproto, err := toProto(fdesc.MapKey(), k)
if err != nil {
return fmt.Errorf("in key of map field %s: %w", fdesc.Name(), err)
}

// `found` is discarded, as the presence of the key in the
// iterator guarantees the presence of some value (even if it is
// starlark.None). Mismatching values will be caught in toProto
// below.
v, _, err := mapping.Get(k)
if err != nil {
return fmt.Errorf("in map field %s, at key %s: %w", fdesc.Name(), k.String(), err)
}

vproto, err := toProto(fdesc.MapValue(), v)
if err != nil {
return fmt.Errorf("in map field %s, at key %s: %w", fdesc.Name(), k.String(), err)
}

mutMap.Set(kproto.MapKey(), vproto)
}

return nil
}

v, err := toProto(fdesc, value)
if err != nil {
return fmt.Errorf("in field %s: %v", fdesc.Name(), err)
Expand Down
Loading