-
Notifications
You must be signed in to change notification settings - Fork 23
/
validate.go
66 lines (60 loc) · 1.85 KB
/
validate.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
// SPDX-FileCopyrightText: 2022 SAP SE or an SAP affiliate company and Open Component Model contributors.
//
// SPDX-License-Identifier: Apache-2.0
package utils
import (
"k8s.io/apimachinery/pkg/util/validation/field"
)
func CheckForUnknownFields(fldPath *field.Path, orig, accepted map[string]interface{}) field.ErrorList {
allErrs := field.ErrorList{}
for k, o := range orig {
child := fldPath.Child(k)
if a, ok := accepted[k]; ok {
allErrs = append(allErrs, CheckForUnknown(child, o, a)...)
} else {
// this is a hack, empty lists or maps are not covered with omitempty in json annotation
switch v := o.(type) {
case map[string]interface{}:
if len(v) == 0 {
continue
}
case []interface{}:
if len(v) == 0 {
continue
}
}
allErrs = append(allErrs, field.Forbidden(child, "unknown field"))
}
}
return allErrs
}
func CheckForUnknownElements(fldPath *field.Path, orig, accepted []interface{}) field.ErrorList {
allErrs := field.ErrorList{}
for i, o := range orig {
if i >= len(accepted) {
allErrs = append(allErrs, field.Forbidden(fldPath, "unexpected list entry"))
} else {
allErrs = append(allErrs, CheckForUnknown(fldPath.Index(i), o, accepted[i])...)
}
}
return allErrs
}
func CheckForUnknown(fldPath *field.Path, orig, accepted interface{}) field.ErrorList {
allErrs := field.ErrorList{}
switch a := accepted.(type) {
case map[string]interface{}:
if o, ok := orig.(map[string]interface{}); ok {
allErrs = append(allErrs, CheckForUnknownFields(fldPath, o, a)...)
} else {
allErrs = append(allErrs, field.Forbidden(fldPath, "map expected"))
}
case []interface{}:
if o, ok := orig.([]interface{}); ok {
allErrs = append(allErrs, CheckForUnknownElements(fldPath, o, a)...)
} else {
allErrs = append(allErrs, field.Forbidden(fldPath, "list expected"))
}
default:
}
return allErrs
}