add recursive jsonschema loader

This commit is contained in:
Samuel Lorch 2023-10-10 19:56:05 +02:00
parent 80383847de
commit 5483f7f39d

View file

@ -6,35 +6,48 @@ import (
"path/filepath"
"github.com/santhosh-tekuri/jsonschema/v5"
"golang.org/x/exp/slog"
)
//go:embed schemas/*.schema.json
//go:embed schema/*
var schemasFS embed.FS
var schema *jsonschema.Schema
func init() {
all, err := schemasFS.ReadDir("schemas")
if err != nil {
panic(fmt.Errorf("Reading Schemas: %w", err))
}
c := jsonschema.NewCompiler()
for _, f := range all {
data, err := schemasFS.Open(filepath.Join("schemas", f.Name()))
if err != nil {
panic(fmt.Errorf("Reading Schema: %w", err))
}
err = c.AddResource("https://nfsense.net/"+f.Name(), data)
if err != nil {
panic(fmt.Errorf("Adding Schema: %w", err))
}
}
addFolderResources(c, "schema")
s, err := c.Compile("https://nfsense.net/config.schema.json")
s, err := c.Compile("https://nfsense.net/schema/config/config.schema.json")
if err != nil {
panic(fmt.Errorf("Reading Schemas: %w", err))
}
schema = s
}
func addFolderResources(c *jsonschema.Compiler, path string) {
all, err := schemasFS.ReadDir(path)
if err != nil {
panic(fmt.Errorf("Reading Schemas: %w", err))
}
for _, f := range all {
fullpath := filepath.Join(path, f.Name())
slog.Debug("Checking Path", "fullpath", fullpath, "dir", f.IsDir())
if f.IsDir() {
addFolderResources(c, fullpath)
} else {
data, err := schemasFS.Open(fullpath)
if err != nil {
panic(fmt.Errorf("Reading Schema: %w", err))
}
slog.Debug("Adding Resource", "id", "https://nfsense.net/"+fullpath)
err = c.AddResource("https://nfsense.net/"+fullpath, data)
if err != nil {
panic(fmt.Errorf("Adding Schema: %w", err))
}
}
}
}