This repository has been archived by the owner on Aug 30, 2023. It is now read-only.
/
webhook_common.go
62 lines (51 loc) · 1.76 KB
/
webhook_common.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
package v1alpha1
import (
"bytes"
"fmt"
apierrors "k8s.io/apimachinery/pkg/api/errors"
"k8s.io/apimachinery/pkg/runtime/schema"
"k8s.io/apimachinery/pkg/util/validation/field"
)
type CacheRule interface {
MarshallSpec() ([]byte, error)
}
func EnsureRuleImmutability(allErrs *field.ErrorList, ruleKind string, a, b CacheRule) error {
// We have to serialize the Proto message as proto.Equals will return false if a field which can't be compared is encountered
aSerialized, err := a.MarshallSpec()
if err != nil {
return fmt.Errorf("unable to serialize first rule: %w", err)
}
bSerialized, err := b.MarshallSpec()
if err != nil {
return fmt.Errorf("unable to serialize second rule: %w", err)
}
if !bytes.Equal(aSerialized, bSerialized) {
detail := fmt.Sprintf("The %s spec is immutable and cannot be updated after initial creation", ruleKind)
*allErrs = append(*allErrs, field.Forbidden(field.NewPath("spec"), detail))
}
return nil
}
func StatusError(allErrs field.ErrorList, name, kind string) error {
if len(allErrs) != 0 {
return apierrors.NewInvalid(
schema.GroupKind{Group: GroupVersion.Group, Kind: kind}, name, allErrs,
)
}
return nil
}
func RequireField(allErrs *field.ErrorList, name, value string, p *field.Path) {
if value == "" {
*allErrs = append(*allErrs, field.Required(p.Child(name), emptyFieldDetail(name)))
}
}
func RequireNonEmptyArray(allErrs *field.ErrorList, name string, value []string, p *field.Path) {
if len(value) == 0 {
*allErrs = append(*allErrs, field.Required(p.Child(name), emptyFieldDetail(name)))
}
}
func FieldMustBeDefined(field string) string {
return fmt.Sprintf("'%s' field must be defined", field)
}
func emptyFieldDetail(field string) string {
return fmt.Sprintf("'%s' field must not be empty", field)
}