196 lines
5.3 KiB
Go
196 lines
5.3 KiB
Go
// Package validation supports this repository's contract checks. It is not a
|
|
// consumer SDK: consumers may use their own conforming YAML and schema tools.
|
|
package validation
|
|
|
|
import (
|
|
"encoding/json"
|
|
"fmt"
|
|
"math/big"
|
|
"strings"
|
|
|
|
"go.yaml.in/yaml/v4"
|
|
)
|
|
|
|
// Decode uses go-yaml's parser and scalar resolution, adapting its node graph to
|
|
// the documented JSON data model. Numbers retain their precision as json.Number.
|
|
func Decode(data []byte) (any, error) {
|
|
var document yaml.Node
|
|
if err := yaml.Load(data, &document, yaml.WithUniqueKeys()); err != nil {
|
|
return nil, fmt.Errorf("decode: %w", err)
|
|
}
|
|
d := decoder{active: make(map[*yaml.Node]bool), values: make(map[*yaml.Node]any)}
|
|
value, err := d.value(&document, "")
|
|
if err != nil {
|
|
return nil, fmt.Errorf("decode: %w", err)
|
|
}
|
|
return value, nil
|
|
}
|
|
|
|
type decoder struct {
|
|
active map[*yaml.Node]bool
|
|
values map[*yaml.Node]any
|
|
}
|
|
|
|
func (d *decoder) value(n *yaml.Node, path string) (any, error) {
|
|
if n == nil {
|
|
return nil, fmt.Errorf("%s: unresolved alias", pointer(path))
|
|
}
|
|
if d.active[n] {
|
|
return nil, nodeError(n, path, "cyclic alias")
|
|
}
|
|
if value, found := d.values[n]; found {
|
|
return value, nil
|
|
}
|
|
d.active[n] = true
|
|
defer delete(d.active, n)
|
|
var value any
|
|
var err error
|
|
switch n.Kind {
|
|
case yaml.DocumentNode:
|
|
if len(n.Content) != 1 {
|
|
return nil, nodeError(n, path, "expected one document")
|
|
}
|
|
value, err = d.value(n.Content[0], path)
|
|
case yaml.AliasNode:
|
|
value, err = d.value(n.Alias, path)
|
|
case yaml.MappingNode:
|
|
if n.ShortTag() != "!!map" {
|
|
return nil, nodeError(n, path, "unsupported mapping tag %q", n.Tag)
|
|
}
|
|
mapping := make(map[string]any, len(n.Content)/2)
|
|
for i := 0; i < len(n.Content); i += 2 {
|
|
keyValue, keyErr := d.value(n.Content[i], path)
|
|
if keyErr != nil {
|
|
return nil, keyErr
|
|
}
|
|
key, ok := keyValue.(string)
|
|
if !ok {
|
|
return nil, nodeError(n.Content[i], path, "mapping key must be a string")
|
|
}
|
|
childPath := path + "/" + escape(key)
|
|
if _, exists := mapping[key]; exists {
|
|
return nil, nodeError(n.Content[i], childPath, "duplicate mapping key %q", key)
|
|
}
|
|
mapping[key], err = d.value(n.Content[i+1], childPath)
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
}
|
|
value = mapping
|
|
case yaml.SequenceNode:
|
|
if n.ShortTag() != "!!seq" {
|
|
return nil, nodeError(n, path, "unsupported sequence tag %q", n.Tag)
|
|
}
|
|
sequence := make([]any, len(n.Content))
|
|
for i, child := range n.Content {
|
|
sequence[i], err = d.value(child, fmt.Sprintf("%s/%d", path, i))
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
}
|
|
value = sequence
|
|
case yaml.ScalarNode:
|
|
value, err = scalar(n)
|
|
if err != nil {
|
|
return nil, nodeError(n, path, "%v", err)
|
|
}
|
|
default:
|
|
return nil, nodeError(n, path, "expected a document value")
|
|
}
|
|
if err == nil {
|
|
d.values[n] = value
|
|
}
|
|
return value, err
|
|
}
|
|
|
|
func scalar(n *yaml.Node) (any, error) {
|
|
switch n.ShortTag() {
|
|
case "!!str":
|
|
// go-yaml resolves decimal numbers outside machine-float range as
|
|
// strings. Plain JSON numbers still retain numeric meaning in this
|
|
// profile, including when the source serialization is JSON.
|
|
if n.Style == 0 {
|
|
if number, ok := jsonNumber(n.Value); ok {
|
|
return number, nil
|
|
}
|
|
}
|
|
return n.Value, nil
|
|
case "!!timestamp":
|
|
// Date-like scalars are text in the shared data model, not time.Time.
|
|
return n.Value, nil
|
|
case "!!bool", "!!null":
|
|
var value any
|
|
err := n.Decode(&value)
|
|
return value, err
|
|
case "!!int":
|
|
text := strings.ReplaceAll(n.Value, "_", "")
|
|
integer, ok := new(big.Int).SetString(text, 0)
|
|
if !ok {
|
|
integer, ok = new(big.Int).SetString(text, 10)
|
|
}
|
|
if !ok {
|
|
return nil, fmt.Errorf("invalid integer %q", n.Value)
|
|
}
|
|
return json.Number(integer.String()), nil
|
|
case "!!float":
|
|
// Normalize YAML's leading '+', '.5', and '5.' spellings, retaining the
|
|
// decimal digits instead of converting through float64.
|
|
text := strings.TrimPrefix(strings.ReplaceAll(n.Value, "_", ""), "+")
|
|
mantissa, exponent, hasExponent := strings.Cut(strings.ToLower(text), "e")
|
|
sign := ""
|
|
if strings.HasPrefix(mantissa, "-") {
|
|
sign, mantissa = "-", strings.TrimPrefix(mantissa, "-")
|
|
}
|
|
whole, fraction, hasPoint := strings.Cut(mantissa, ".")
|
|
whole = strings.TrimLeft(whole, "0")
|
|
if whole == "" {
|
|
whole = "0"
|
|
}
|
|
text = sign + whole
|
|
if hasPoint {
|
|
if fraction == "" {
|
|
fraction = "0"
|
|
}
|
|
text += "." + fraction
|
|
}
|
|
if hasExponent {
|
|
text += "e" + exponent
|
|
}
|
|
if number, ok := jsonNumber(text); ok {
|
|
return number, nil
|
|
}
|
|
return nil, fmt.Errorf("number %q is not a finite JSON number", n.Value)
|
|
default:
|
|
return nil, fmt.Errorf("tag %q has no shared JSON representation", n.Tag)
|
|
}
|
|
}
|
|
|
|
func jsonNumber(text string) (json.Number, bool) {
|
|
if !json.Valid([]byte(text)) {
|
|
return "", false
|
|
}
|
|
var value any
|
|
decoder := json.NewDecoder(strings.NewReader(text))
|
|
decoder.UseNumber()
|
|
if err := decoder.Decode(&value); err != nil {
|
|
return "", false
|
|
}
|
|
number, ok := value.(json.Number)
|
|
return number, ok
|
|
}
|
|
|
|
func nodeError(n *yaml.Node, path, format string, args ...any) error {
|
|
return fmt.Errorf("%s (line %d, column %d): %s", pointer(path), n.Line, n.Column, fmt.Sprintf(format, args...))
|
|
}
|
|
|
|
func pointer(path string) string {
|
|
if path == "" {
|
|
return "/"
|
|
}
|
|
return path
|
|
}
|
|
|
|
func escape(value string) string {
|
|
return strings.ReplaceAll(strings.ReplaceAll(value, "~", "~0"), "/", "~1")
|
|
}
|