Skip to content

Commit

Permalink
fix(docs): do not split schemas manually
Browse files Browse the repository at this point in the history
  • Loading branch information
byashimov committed Jan 22, 2025
1 parent a01a94e commit 2dd5741
Showing 1 changed file with 25 additions and 23 deletions.
48 changes: 25 additions & 23 deletions generators/docs/validator.go
Original file line number Diff line number Diff line change
Expand Up @@ -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 {
Expand All @@ -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
Expand Down Expand Up @@ -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)
}
Expand Down

0 comments on commit 2dd5741

Please sign in to comment.