mirror of
https://github.com/yannh/kubeconform.git
synced 2026-04-24 12:24:42 +00:00
better errors
This commit is contained in:
parent
96e35cb926
commit
79c9197f38
5 changed files with 59 additions and 30 deletions
|
|
@ -3,8 +3,14 @@ package validator
|
|||
import (
|
||||
"fmt"
|
||||
"github.com/xeipuuv/gojsonschema"
|
||||
"sigs.k8s.io/yaml"
|
||||
)
|
||||
|
||||
type InvalidResourceError struct { err string }
|
||||
func (r InvalidResourceError) Error() string{
|
||||
return r.err
|
||||
}
|
||||
|
||||
// ValidFormat is a type for quickly forcing
|
||||
// new formats on the gojsonschema loader
|
||||
type ValidFormat struct{}
|
||||
|
|
@ -19,22 +25,27 @@ func init () {
|
|||
gojsonschema.FormatCheckers.Add("int-or-string", ValidFormat{})
|
||||
}
|
||||
|
||||
func Validate(resource interface{}, rawSchema []byte) error {
|
||||
func Validate(rawResource []byte, rawSchema []byte) error {
|
||||
schemaLoader := gojsonschema.NewBytesLoader(rawSchema)
|
||||
schema, err := gojsonschema.NewSchema(schemaLoader)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
documentLoader := gojsonschema.NewGoLoader(resource)
|
||||
results, err := schema.Validate(documentLoader)
|
||||
var resource map[string]interface{}
|
||||
if err = yaml.Unmarshal(rawResource, &resource); err != nil {
|
||||
return fmt.Errorf("error unmarshalling resource: %s", err)
|
||||
}
|
||||
resourceLoader := gojsonschema.NewGoLoader(resource)
|
||||
|
||||
results, err := schema.Validate(resourceLoader)
|
||||
if err != nil {
|
||||
// This error can only happen if the Object to validate is poorly formed. There's no hope of saving this one
|
||||
return fmt.Errorf("problem validating schema. Check JSON formatting: %s", err)
|
||||
}
|
||||
|
||||
if !results.Valid() {
|
||||
return fmt.Errorf("resource does not conform to schema")
|
||||
return InvalidResourceError{err: fmt.Sprintf("resource does not conform to schema: %+v", results) }
|
||||
}
|
||||
|
||||
return nil
|
||||
|
|
|
|||
Loading…
Add table
Add a link
Reference in a new issue