-
Notifications
You must be signed in to change notification settings - Fork 19
/
Copy patherror_utils.go
171 lines (157 loc) · 5.52 KB
/
error_utils.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
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
// Copyright 2023-2024 Buf Technologies, Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package protovalidate
import (
"errors"
"slices"
"strconv"
"strings"
"buf.build/gen/go/bufbuild/protovalidate/protocolbuffers/go/buf/validate"
"google.golang.org/protobuf/proto"
"google.golang.org/protobuf/reflect/protoreflect"
"google.golang.org/protobuf/types/descriptorpb"
)
// mergeViolations is a utility to resolve and combine errors resulting from
// evaluation. If ok is false, execution of validation should stop (either due
// to failFast or the result is not a ValidationError).
//
//nolint:errorlint
func mergeViolations(dst, src error, failFast bool) (ok bool, err error) {
if src == nil {
return true, dst
}
srcValErrs, ok := src.(*ValidationError)
if !ok {
return false, src
}
if dst == nil {
return !(failFast && len(srcValErrs.Violations) > 0), src
}
dstValErrs, ok := dst.(*ValidationError)
if !ok {
// what should we do here?
return false, dst
}
dstValErrs.Violations = append(dstValErrs.Violations, srcValErrs.Violations...)
return !(failFast && len(dstValErrs.Violations) > 0), dst
}
// fieldPathElement returns a buf.validate.fieldPathElement that corresponds to
// a provided FieldDescriptor. If the provided FieldDescriptor is nil, nil is
// returned.
func fieldPathElement(field protoreflect.FieldDescriptor) *validate.FieldPathElement {
if field == nil {
return nil
}
return &validate.FieldPathElement{
FieldNumber: proto.Int32(int32(field.Number())),
FieldName: proto.String(field.TextName()),
FieldType: descriptorpb.FieldDescriptorProto_Type(field.Kind()).Enum(),
}
}
// fieldPath returns a single-element buf.validate.fieldPath corresponding to
// the provided FieldDescriptor, or nil if the provided FieldDescriptor is nil.
func fieldPath(field protoreflect.FieldDescriptor) *validate.FieldPath {
if field == nil {
return nil
}
return &validate.FieldPath{
Elements: []*validate.FieldPathElement{
fieldPathElement(field),
},
}
}
// updateViolationPaths modifies the field and rule paths of an error, appending
// an element to the end of each field path (if provided) and prepending a list
// of elements to the beginning of each rule path (if provided.)
//
// Note that this function is ordinarily used to append field paths in reverse
// order, as the stack bubbles up through the evaluators. Then, at the end, the
// path is reversed. Rule paths are generally static, so this optimization isn't
// applied for rule paths.
func updateViolationPaths(err error, fieldSuffix *validate.FieldPathElement, rulePrefix []*validate.FieldPathElement) {
if fieldSuffix == nil && len(rulePrefix) == 0 {
return
}
var valErr *ValidationError
if errors.As(err, &valErr) {
for _, violation := range valErr.Violations {
if fieldSuffix != nil {
if violation.Proto.GetField() == nil {
violation.Proto.Field = &validate.FieldPath{}
}
violation.Proto.Field.Elements = append(violation.Proto.Field.Elements, fieldSuffix)
}
if len(rulePrefix) != 0 {
violation.Proto.Rule.Elements = append(
append([]*validate.FieldPathElement{}, rulePrefix...),
violation.Proto.GetRule().GetElements()...,
)
}
}
}
}
// finalizeViolationPaths reverses all field paths in the error and populates
// the deprecated string-based field path.
func finalizeViolationPaths(err error) {
var valErr *ValidationError
if errors.As(err, &valErr) {
for _, violation := range valErr.Violations {
if violation.Proto.GetField() != nil {
slices.Reverse(violation.Proto.GetField().GetElements())
//nolint:staticcheck // Intentional use of deprecated field
violation.Proto.FieldPath = proto.String(fieldPathString(violation.Proto.GetField().GetElements()))
}
}
}
}
// fieldPathString takes a FieldPath and encodes it to a string-based dotted
// field path.
func fieldPathString(path []*validate.FieldPathElement) string {
var result strings.Builder
for i, element := range path {
if i > 0 {
result.WriteByte('.')
}
result.WriteString(element.GetFieldName())
subscript := element.GetSubscript()
if subscript == nil {
continue
}
result.WriteByte('[')
switch value := subscript.(type) {
case *validate.FieldPathElement_Index:
result.WriteString(strconv.FormatUint(value.Index, 10))
case *validate.FieldPathElement_BoolKey:
result.WriteString(strconv.FormatBool(value.BoolKey))
case *validate.FieldPathElement_IntKey:
result.WriteString(strconv.FormatInt(value.IntKey, 10))
case *validate.FieldPathElement_UintKey:
result.WriteString(strconv.FormatUint(value.UintKey, 10))
case *validate.FieldPathElement_StringKey:
result.WriteString(strconv.Quote(value.StringKey))
}
result.WriteByte(']')
}
return result.String()
}
// markViolationForKey marks the provided error as being for a map key, by
// setting the `for_key` flag on each violation within the validation error.
func markViolationForKey(err error) {
var valErr *ValidationError
if errors.As(err, &valErr) {
for _, violation := range valErr.Violations {
violation.Proto.ForKey = proto.Bool(true)
}
}
}