protoc-gen-validate icon indicating copy to clipboard operation
protoc-gen-validate copied to clipboard

[bug] wrong code generated for repeated num items

Open martinzhou2015 opened this issue 3 years ago • 3 comments

Issue

When a validation rule below is set for a repeated num item:

repeated int32 x = 1 [(validate.rules).repeated.items.int32 = {in: [0, 1]}];

The code is generated as follows:

	for idx, item := range m.GetX() {
		_, _ = idx, item

		if _, ok := _HelloRequest_X_InLookup[item]; !ok {
			return HelloRequestValidationError{
				field:  fmt.Sprintf("X[%v]", idx),
				reason: "value must be in list [0 1]",
			}
		}

	}

However, the _HelloRequest_X_InLookup is omitted, which leads to a compiler error. For example,

../sudo.pb.validate.go:212:15: undefined: _SudoDetail_ITemplateAllowHours_NotInLookup

Suggestion

The issue resembles the one fixed in: https://github.com/envoyproxy/protoc-gen-validate/commit/478e95eb5ebe9afa11d767b6ce53dec79b6cc8c4

Add template codes in /templates/goshared/msg.go can fix this issue. For instance,

	{{ if has .Rules.Items.GetUint32 "NotIn" }} {{ if .Rules.Items.GetUint32.NotIn }}
		var {{ lookup .Field "NotInLookup" }} = map[uint32]struct{}{
			{{- range .Rules.Items.GetUint32.NotIn }}
				{{ inKey $f . }}: {},
			{{- end }}
		}
	{{ end }}{{ end }}

Any better solutions?

martinzhou2015 avatar May 08 '21 05:05 martinzhou2015

Nope, that sounds like the right way to go. @martinzhou2015 would you be able to send a PR?

akonradi avatar May 27 '21 16:05 akonradi

@complex64 or @jzelinskie (since y'all commented on the PR) would either of you like to tackle this?

akonradi avatar Oct 07 '21 14:10 akonradi

I'd give @jzelinskie first crack at it and offer to pick it up if I haven't heard anything after about a week or so :+1:

complex64 avatar Oct 08 '21 09:10 complex64