Home

tmpl @07ccb515849ca1a50462bf2e5059af23c14a516a - refs - log -
-
https://git.jolheiser.com/tmpl.git
Template automation
tmpl / schema / schema.go
- raw
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
package schema

import (
	_ "embed"
	"fmt"
	"io"
	"strings"

	"github.com/xeipuuv/gojsonschema"
)

var (
	//go:embed tmpl.json
	schema       []byte
	schemaLoader = gojsonschema.NewBytesLoader(schema)
)

// Lint is for linting a recipe against the schema
func Lint(r io.Reader) error {
	data, err := io.ReadAll(r)
	if err != nil {
		return err
	}
	var m any
	if err := Unmarshal(data, &m); err != nil {
		return err
	}
	sourceLoader := gojsonschema.NewGoLoader(m)
	result, err := gojsonschema.Validate(schemaLoader, sourceLoader)
	if err != nil {
		return err
	}
	if len(result.Errors()) > 0 {
		return ResultErrors(result.Errors())
	}
	return nil
}

// ResultErrors is a slice of gojsonschema.ResultError that implements error
type ResultErrors []gojsonschema.ResultError

// Error implements error
func (r ResultErrors) Error() string {
	errs := make([]string, 0, len(r))
	for _, re := range r {
		errs = append(errs, fmt.Sprintf("%s: %s", re.Field(), re.Description()))
	}
	return strings.Join(errs, " | ")
}