Files
core/configfamily/unknown.go
T

89 lines
2.6 KiB
Go
Raw Normal View History

package configfamily
import (
"fmt"
"os"
"gopkg.in/yaml.v3"
"yetano.dev/yetano/core/configcmd"
)
// Unknown returns the unknown options of every layer that contributed,
// checked against schema (the program's configuration struct). The
// program starts anyway with the default for them.
//
// - the program's own file, --config and its section of the family
// file: every key schema does not have, except an option of the
// family's shared schema, which is valid in every layer;
// - the family file's top level: a key neither the shared schema nor
// schema has -- an option some other program reads is not unknown,
// and neither are the other programs' sections.
func (l *Loaded) Unknown(schema any) ([]configcmd.UnknownKey, error) {
f := l.Program.Family
var out []configcmd.UnknownKey
for i := len(l.Layers) - 1; i >= 0; i-- {
layer := l.Layers[i]
if !layer.Exists {
continue
}
root, err := parseMapping(layer.Path)
if err != nil {
return nil, err
}
var keys []configcmd.UnknownKey
switch layer.Kind {
case SharedLayer:
shared := &yaml.Node{Kind: yaml.MappingNode}
for j := 0; j+1 < len(root.Content); j += 2 {
if !f.IsProgramSection(root.Content[j].Value) {
shared.Content = append(shared.Content, root.Content[j], root.Content[j+1])
}
}
keys = configcmd.UnknownKeysNode(shared, schema)
case SectionLayer:
keys = configcmd.UnknownKeysNode(mappingValue(root, layer.Section), schema)
default:
keys = configcmd.UnknownKeysNode(root, schema)
}
for _, k := range keys {
if f.IsSharedKey(k.Key) {
continue // a family option, valid in every layer
}
if layer.Kind == SectionLayer {
k.Key = layer.Section + "." + k.Key
}
k.Layer = layer.Name()
out = append(out, k)
}
}
return out, nil
}
// parseMapping parses path and returns its top-level mapping node (an
// empty one for an empty file).
func parseMapping(path string) (*yaml.Node, error) {
raw, err := os.ReadFile(path)
if err != nil {
return nil, fmt.Errorf("config: read %s: %w", path, err)
}
var doc yaml.Node
if err := yaml.Unmarshal(raw, &doc); err != nil {
return nil, fmt.Errorf("config: parse %s: %w", path, err)
}
if doc.Kind == yaml.DocumentNode && len(doc.Content) == 1 && doc.Content[0].Kind == yaml.MappingNode {
return doc.Content[0], nil
}
return &yaml.Node{Kind: yaml.MappingNode}, nil
}
// mappingValue returns the value node of key in mapping n (an empty
// mapping if absent).
func mappingValue(n *yaml.Node, key string) *yaml.Node {
for i := 0; i+1 < len(n.Content); i += 2 {
if n.Content[i].Value == key {
return n.Content[i+1]
}
}
return &yaml.Node{Kind: yaml.MappingNode}
}