78 lines
2.3 KiB
Go
78 lines
2.3 KiB
Go
package sharedglossary
|
|
|
|
import (
|
|
"context"
|
|
"errors"
|
|
"strings"
|
|
|
|
"github.com/santhosh-tekuri/jsonschema/v6"
|
|
|
|
"gitea.maximumdirect.net/eric/audita/v4/internal/core/config"
|
|
ck "go.maximumdirect.net/configkit"
|
|
)
|
|
|
|
// Load composes ordered shared documents and validates the completed envelope.
|
|
// A nil result means no documents were supplied.
|
|
func Load(ctx context.Context, inputs []ck.Input) (*ck.Result[map[string]any], error) {
|
|
if err := ctx.Err(); err != nil {
|
|
return nil, err
|
|
}
|
|
if len(inputs) == 0 {
|
|
return nil, nil
|
|
}
|
|
validator, err := NewValidator()
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
underlays := make([]ck.Underlay, 0, len(inputs)-1)
|
|
for _, input := range inputs[:len(inputs)-1] {
|
|
input.Imports = true
|
|
underlays = append(underlays, ck.Underlay{Inputs: []ck.Input{input}})
|
|
}
|
|
main := inputs[len(inputs)-1]
|
|
main.Imports = true
|
|
result, err := ck.LoadLayered(main, ck.LayeredOptions[map[string]any]{
|
|
Definition: ck.Definition[map[string]any]{
|
|
SequenceIdentities: []ck.SequenceIdentity{config.GlossaryEntryIdentity(ck.SequenceSelector{ck.SequenceLiteralKey("collections")})},
|
|
Validate: func(document *map[string]any, validation *ck.Validation) {
|
|
if err := validator.Validate(*document, "input"); err != nil {
|
|
var schemaError *jsonschema.ValidationError
|
|
if errors.As(err, &schemaError) {
|
|
reportSchemaError(validation, schemaError)
|
|
} else {
|
|
validation.Error(ck.Keys(), err.Error())
|
|
}
|
|
}
|
|
},
|
|
},
|
|
Underlays: underlays,
|
|
})
|
|
if canceled := ctx.Err(); canceled != nil {
|
|
return nil, errors.Join(err, canceled)
|
|
}
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
return result, nil
|
|
}
|
|
|
|
func reportSchemaError(validation *ck.Validation, err *jsonschema.ValidationError) {
|
|
if len(err.Causes) > 0 {
|
|
for _, cause := range err.Causes {
|
|
reportSchemaError(validation, cause)
|
|
}
|
|
return
|
|
}
|
|
path := ck.Keys()
|
|
if len(err.InstanceLocation) > 0 {
|
|
segments := make([]string, len(err.InstanceLocation))
|
|
for i, segment := range err.InstanceLocation {
|
|
segments[i] = strings.ReplaceAll(strings.ReplaceAll(segment, "~", "~0"), "/", "~1")
|
|
}
|
|
// Escaped instance segments always form a valid JSON Pointer. Parsing
|
|
// leaves numeric keys/indexes for ConfigKit to resolve against the data.
|
|
path, _ = ck.ParsePath("/" + strings.Join(segments, "/"))
|
|
}
|
|
validation.Error(path, err.Error())
|
|
}
|