forked from bufbuild/protoc-gen-validate
/
msg.go
95 lines (80 loc) · 2.29 KB
/
msg.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
package tpl
const msgTpl = `
{{ if disabled . -}}
{{ cmt "Validate is disabled for " .TypeName.Value ". This method will always return nil." }}
{{- else -}}
{{ cmt "Validate checks the field values on " .TypeName.Value " with the rules defined in the proto definition for this message. If any rules are violated, an error is returned." }}
{{- end -}}
func (m {{ .TypeName.Pointer }}) Validate() error {
{{ if disabled . -}}
return nil
{{ else -}}
if m == nil { return nil }
{{ range .NonOneOfFields }}
{{ render (context .) }}
{{ end }}
{{ range .OneOfs }}
switch m.{{ .Name.PGGUpperCamelCase }}.(type) {
{{ range .Fields }}
case {{ oneof . }}:
{{ render (context .) }}
{{ end }}
{{ if required . }}
default:
return {{ errname .Message }}{
Field: "{{ .Name.PGGUpperCamelCase }}",
Reason: "value is required",
}
{{ end }}
}
{{ end }}
return nil
{{ end -}}
}
{{ if needs . "hostname" }}{{ template "hostname" . }}{{ end }}
{{ if needs . "email" }}{{ template "email" . }}{{ end }}
{{ cmt (errname .) " is the validation error returned by " .TypeName.Value ".Validate if the designated constraints aren't met." -}}
type {{ errname . }} struct {
Field string
Reason string
Cause error
Key bool
}
// Error satisfies the builtin error interface
func (e {{ errname . }}) Error() string {
cause := ""
if e.Cause != nil {
cause = fmt.Sprintf(" | caused by: %v", e.Cause)
}
key := ""
if e.Key {
key = "key for "
}
return fmt.Sprintf(
"invalid %s{{ .TypeName }}.%s: %s%s",
key,
e.Field,
e.Reason,
cause)
}
var _ error = {{ errname . }}{}
{{ range .Fields }}{{ with (context .) }}{{ $f := .Field }}
{{ if has .Rules "In" }}{{ if .Rules.In }}
var {{ lookup .Field "InLookup" }} = map[{{ inType .Field .Rules.In }}]struct{}{
{{- range .Rules.In }}
{{ inKey $f . }}: {},
{{- end }}
}
{{ end }}{{ end }}
{{ if has .Rules "NotIn" }}{{ if .Rules.NotIn }}
var {{ lookup .Field "NotInLookup" }} = map[{{ inType .Field .Rules.In }}]struct{}{
{{- range .Rules.NotIn }}
{{ inKey $f . }}: {},
{{- end }}
}
{{ end }}{{ end }}
{{ if has .Rules "Pattern"}}{{ if .Rules.Pattern }}
var {{ lookup .Field "Pattern" }} = regexp.MustCompile({{ lit .Rules.GetPattern }})
{{ end }}{{ end }}
{{ end }}{{ end }}
`