github.com/olli-ai/jx/v2@v2.0.400-0.20210921045218-14731b4dd448/pkg/util/validation.go (about)

     1  package util
     2  
     3  import (
     4  	schemagen "github.com/alecthomas/jsonschema"
     5  	"github.com/xeipuuv/gojsonschema"
     6  	corev1 "k8s.io/api/core/v1"
     7  	"sigs.k8s.io/yaml"
     8  )
     9  
    10  // GenerateSchema generates a JSON schema for the given struct type and returns it.
    11  func GenerateSchema(target interface{}) *schemagen.Schema {
    12  	reflector := schemagen.Reflector{
    13  		IgnoredTypes: []interface{}{
    14  			corev1.Container{},
    15  		},
    16  		RequiredFromJSONSchemaTags: true,
    17  	}
    18  	return reflector.Reflect(target)
    19  }
    20  
    21  // ValidateYaml generates a JSON schema for the given struct type, and then validates the given YAML against that
    22  // schema, ignoring Containers and missing fields.
    23  func ValidateYaml(target interface{}, data []byte) ([]string, error) {
    24  	schema := GenerateSchema(target)
    25  
    26  	dataAsJSON, err := yaml.YAMLToJSON(data)
    27  	if err != nil {
    28  		return nil, err
    29  	}
    30  	schemaLoader := gojsonschema.NewGoLoader(schema)
    31  	documentLoader := gojsonschema.NewBytesLoader(dataAsJSON)
    32  
    33  	result, err := gojsonschema.Validate(schemaLoader, documentLoader)
    34  	if err != nil {
    35  		return nil, err
    36  	}
    37  	if !result.Valid() {
    38  		errMsgs := []string{}
    39  		for _, e := range result.Errors() {
    40  			errMsgs = append(errMsgs, e.String())
    41  		}
    42  		return errMsgs, nil
    43  	}
    44  
    45  	return nil, nil
    46  }