123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104 |
- package validation
- import (
- "bytes"
- "encoding/json"
- "fmt"
- ejson "github.com/exponent-io/jsonpath"
- utilerrors "k8s.io/apimachinery/pkg/util/errors"
- )
- type Schema interface {
- ValidateBytes(data []byte) error
- }
- type NullSchema struct{}
- func (NullSchema) ValidateBytes(data []byte) error { return nil }
- type NoDoubleKeySchema struct{}
- func (NoDoubleKeySchema) ValidateBytes(data []byte) error {
- var list []error
- if err := validateNoDuplicateKeys(data, "metadata", "labels"); err != nil {
- list = append(list, err)
- }
- if err := validateNoDuplicateKeys(data, "metadata", "annotations"); err != nil {
- list = append(list, err)
- }
- return utilerrors.NewAggregate(list)
- }
- func validateNoDuplicateKeys(data []byte, path ...string) error {
- r := ejson.NewDecoder(bytes.NewReader(data))
-
-
-
- ifacePath := []interface{}{}
- for ix := range path {
- ifacePath = append(ifacePath, path[ix])
- }
- found, err := r.SeekTo(ifacePath...)
- if err != nil {
- return err
- }
- if !found {
- return nil
- }
- seen := map[string]bool{}
- for {
- tok, err := r.Token()
- if err != nil {
- return err
- }
- switch t := tok.(type) {
- case json.Delim:
- if t.String() == "}" {
- return nil
- }
- case ejson.KeyString:
- if seen[string(t)] {
- return fmt.Errorf("duplicate key: %s", string(t))
- }
- seen[string(t)] = true
- }
- }
- }
- type ConjunctiveSchema []Schema
- func (c ConjunctiveSchema) ValidateBytes(data []byte) error {
- var list []error
- schemas := []Schema(c)
- for ix := range schemas {
- if err := schemas[ix].ValidateBytes(data); err != nil {
- list = append(list, err)
- }
- }
- return utilerrors.NewAggregate(list)
- }
|