From 2dd57412f6fb21aa3719cb91855bd18396b2530c Mon Sep 17 00:00:00 2001 From: Murad Biashimov Date: Wed, 22 Jan 2025 13:40:46 +0100 Subject: [PATCH] fix(docs): do not split schemas manually --- generators/docs/validator.go | 48 +++++++++++++++++++----------------- 1 file changed, 25 insertions(+), 23 deletions(-) diff --git a/generators/docs/validator.go b/generators/docs/validator.go index 9e330a2f..953af609 100644 --- a/generators/docs/validator.go +++ b/generators/docs/validator.go @@ -3,20 +3,18 @@ package main import ( "bytes" "encoding/json" + "errors" "fmt" + "io" "os" "path/filepath" "strings" - "github.com/ghodss/yaml" "github.com/xeipuuv/gojsonschema" + "gopkg.in/yaml.v3" + yaml2 "sigs.k8s.io/yaml" ) -// exampleKind gets example's kind to validate with kind's schema -type exampleKind struct { - Kind string `yaml:"kind"` -} - // crdSchema schema type crdSchema struct { Spec struct { @@ -29,37 +27,41 @@ type crdSchema struct { } // validateYAML validates yaml document -// Converts yaml to json, because there is no yaml validator func validateYAML(validators map[string]schemaValidator, document []byte) error { - for _, d := range bytes.Split(document, []byte("---")) { - if len(bytes.TrimSpace(d)) == 0 { - continue + deco := yaml.NewDecoder(bytes.NewReader(document)) + for { + // A yaml document can contain multiple documents + example := make(map[string]any) + err := deco.Decode(&example) + if errors.Is(err, io.EOF) { + return nil } - example := new(exampleKind) - err := yaml.Unmarshal(d, example) if err != nil { - return err + return fmt.Errorf("can't unmarshal example: %w", err) } - // Validates given document - jsonDocument, err := yaml.YAMLToJSON(d) - if err != nil { - return fmt.Errorf("can't convert yaml to json: %w", err) + // Every example must have "kind", e.g.: `kind: KafkaTopic` + kind, ok := example["kind"].(string) + if !ok { + return fmt.Errorf("the example doesn't have kind") } - validate, ok := validators[example.Kind] + validate, ok := validators[kind] if !ok { - return fmt.Errorf("validator for kind %q not found", example.Kind) + return fmt.Errorf("validator for kind %q not found", kind) } - err = validate(jsonDocument) + b, err := json.Marshal(example) if err != nil { return err } - } - return nil + err = validate(b) + if err != nil { + return err + } + } } type schemaValidator func([]byte) error @@ -88,7 +90,7 @@ func newSchemaValidator(kind string, crd []byte) (schemaValidator, error) { return func(document []byte) error { // Validates given document - jsonDocument, err := yaml.YAMLToJSON(document) + jsonDocument, err := yaml2.YAMLToJSON(document) if err != nil { return fmt.Errorf("can't convert yaml to json: %w", err) }