Files
core/solutions/engine/config.go
T

398 lines
10 KiB
Go
Raw Normal View History

package engine
import (
"bytes"
"fmt"
"regexp"
"sort"
"strconv"
"strings"
"gopkg.in/yaml.v3"
"yetano.dev/yetano/core/solutions/catalog"
)
// placeholder: ${name}, ${name[0]}, ${name.count}, ${name.join}; $${ is a literal "${".
var placeholderRE = regexp.MustCompile(`\$\$\{|\$\{((?:instance|solution)\.[a-z]+|[A-Za-z_][A-Za-z0-9_]*)(?:\[(\d+)\]|\.(count|join))?\}`)
type genFile struct {
path string
pkg string
root *yaml.Node // mapping
origins map[string]Origin
}
func (ev *evaluation) vars() map[string]any {
v := map[string]any{}
for k, a := range ev.answers {
v[k] = a
}
v["instance.name"] = ev.in.Metadata.Name
v["solution.id"] = ev.s.Meta.ID
v["solution.version"] = ev.s.Meta.Version
return v
}
func (ev *evaluation) config() {
files := map[string]*genFile{}
var order []string
get := func(path string) *genFile {
f, ok := files[path]
if !ok {
pkg, _, _ := strings.Cut(path, "/")
f = &genFile{path: path, pkg: pkg, root: &yaml.Node{Kind: yaml.MappingNode, Tag: "!!map"}, origins: map[string]Origin{}}
files[path] = f
order = append(order, path)
}
return f
}
vars := ev.vars()
applyFrag := func(fr catalog.Fragment, origin Origin) {
pkg, _, _ := strings.Cut(fr.File, "/")
if !ev.pkgSelected(pkg) {
return
}
if fr.Module != "" {
mp, mm := pkg, fr.Module
if a, b, ok := strings.Cut(fr.Module, "/"); ok {
mp, mm = a, b
}
if !ev.moduleEnabled(mp, mm) {
return
}
}
node := deepCopy(&fr.Set)
params := map[string]bool{}
if err := interpolate(node, vars, params); err != nil {
ev.msg("error", "config", fmt.Sprintf("%s: %v", origin.Source, err), origin.Source)
return
}
for p := range params {
origin.Params = append(origin.Params, p)
}
sort.Strings(origin.Params)
if node.Kind != yaml.MappingNode {
ev.msg("error", "config", fmt.Sprintf("%s: fragment for %s is not a map", origin.Source, fr.File), origin.Source)
return
}
f := get(fr.File)
mergeMap(f.root, node, "", origin, f.origins)
}
// layer 2: profiles (base first), in package order
ids := append([]string{}, ev.pkgSeen...)
sort.Strings(ids)
for _, id := range ids {
p := ev.pkgs[id]
if !p.Selected || p.Profile == "" {
continue
}
chain, err := ev.e.Cat.ProfileChain(id, p.Profile)
if err != nil {
continue
}
for _, prof := range chain {
for _, fr := range prof.Spec.Config {
applyFrag(fr, Origin{Layer: "profile", Source: "profile:" + prof.Key()})
}
}
}
// layer 3: the solution's fragments
for i, fr := range ev.s.Spec.Config {
if len(fr.When) > 0 && !fr.When.Holds(ev.env) {
continue
}
id := fr.ID
if id == "" {
id = strconv.Itoa(i)
}
applyFrag(fr, Origin{Layer: "solution", Source: "solution:" + ev.s.Meta.ID + "#" + id})
}
// layer 6: explicit overrides
for _, o := range ev.in.Spec.Overrides {
if !catalog.SafeRelPath(o.File) || o.Path == "" {
ev.msg("error", "override", fmt.Sprintf("override %s %s: bad file or path", o.File, o.Path), "override")
continue
}
f, ok := files[o.File]
if !ok {
ev.msg("warning", "override", fmt.Sprintf("override for %s: the solution generates no such file", o.File), "override")
continue
}
var val yaml.Node
if err := val.Encode(o.Value); err != nil {
ev.msg("error", "override", err.Error(), "override")
continue
}
setPath(f.root, strings.Split(o.Path, "."), &val)
f.origins[o.Path] = Origin{Layer: "override", Source: "override"}
ev.msg("info", "override", fmt.Sprintf("%s: %s is set directly, not through a question", o.File, o.Path), "override")
}
sort.Strings(order)
for _, path := range order {
f := files[path]
body, err := render(f.root, ev.s, path)
if err != nil {
ev.msg("error", "config", err.Error(), path)
continue
}
ev.st.Files = append(ev.st.Files, FilePreview{Path: "config/" + path, Package: f.pkg, Content: body, Origins: f.origins})
}
}
func render(root *yaml.Node, s *catalog.Solution, path string) (string, error) {
doc := &yaml.Node{Kind: yaml.DocumentNode, Content: []*yaml.Node{root}}
doc.HeadComment = fmt.Sprintf("Generated by the Yetano Solutions Guide from %s %s.\n"+
"This is a native configuration file: edit it like any other. See\n"+
"solution.lock.yaml before regenerating over hand edits.", s.Meta.ID, s.Meta.Version)
var buf bytes.Buffer
enc := yaml.NewEncoder(&buf)
enc.SetIndent(2)
if err := enc.Encode(doc); err != nil {
return "", fmt.Errorf("%s: %v", path, err)
}
enc.Close()
return buf.String(), nil
}
func deepCopy(n *yaml.Node) *yaml.Node {
if n == nil {
return nil
}
c := *n
if c.Kind == yaml.MappingNode || c.Kind == yaml.SequenceNode {
c.Style = 0 // generated files use block style, whatever the catalog wrote
}
c.Line, c.Column = 0, 0
c.Content = make([]*yaml.Node, len(n.Content))
for i, ch := range n.Content {
c.Content[i] = deepCopy(ch)
}
if n.Kind == yaml.DocumentNode && len(c.Content) == 1 {
return c.Content[0]
}
return &c
}
// interpolate replaces placeholders in scalars (ADR-0005).
func interpolate(n *yaml.Node, vars map[string]any, used map[string]bool) error {
switch n.Kind {
case yaml.MappingNode:
for i := 1; i < len(n.Content); i += 2 {
if err := interpolate(n.Content[i], vars, used); err != nil {
return err
}
}
case yaml.SequenceNode:
for _, ch := range n.Content {
if err := interpolate(ch, vars, used); err != nil {
return err
}
}
case yaml.ScalarNode:
if !strings.Contains(n.Value, "${") {
return nil
}
whole := placeholderRE.FindStringSubmatchIndex(n.Value)
if whole != nil && whole[0] == 0 && whole[1] == len(n.Value) && n.Value != "$${" {
v, err := lookup(n.Value, vars, used)
if err != nil {
return err
}
var repl yaml.Node
if err := repl.Encode(v); err != nil {
return err
}
repl.Style = 0
*n = repl
return nil
}
var firstErr error
out := placeholderRE.ReplaceAllStringFunc(n.Value, func(m string) string {
if m == "$${" {
return "${"
}
v, err := lookup(m, vars, used)
if err != nil && firstErr == nil {
firstErr = err
}
return text(v)
})
if firstErr != nil {
return firstErr
}
n.Value = out
n.Tag = "!!str"
n.Style = 0
}
return nil
}
func lookup(ph string, vars map[string]any, used map[string]bool) (any, error) {
m := placeholderRE.FindStringSubmatch(ph)
name := m[1]
v, ok := vars[name]
if !ok {
return nil, fmt.Errorf("placeholder ${%s}: no answer for %q", name, name)
}
used[name] = true
switch {
case m[2] != "":
i, _ := strconv.Atoi(m[2])
l := listOf(v)
if i >= len(l) {
return nil, fmt.Errorf("placeholder %s: %q has only %d item(s)", ph, name, len(l))
}
return l[i], nil
case m[3] == "count":
return len(listOf(v)), nil
case m[3] == "join":
var parts []string
for _, x := range listOf(v) {
parts = append(parts, catalog.Scalar(x))
}
return strings.Join(parts, ","), nil
}
return v, nil
}
func text(v any) string {
if l, ok := v.([]any); ok {
var parts []string
for _, x := range l {
parts = append(parts, catalog.Scalar(x))
}
return strings.Join(parts, ",")
}
return catalog.Scalar(v)
}
// mergeMap merges src into dst like core/config: maps key by key, lists
// and scalars replace, null removes. Origins are recorded per path.
func mergeMap(dst, src *yaml.Node, prefix string, origin Origin, origins map[string]Origin) {
for i := 0; i+1 < len(src.Content); i += 2 {
k, v := src.Content[i], src.Content[i+1]
path := k.Value
if prefix != "" {
path = prefix + "." + k.Value
}
idx := -1
for j := 0; j+1 < len(dst.Content); j += 2 {
if dst.Content[j].Value == k.Value {
idx = j
break
}
}
if v.Kind == yaml.ScalarNode && v.Tag == "!!null" {
if idx >= 0 {
dst.Content = append(dst.Content[:idx], dst.Content[idx+2:]...)
}
for p := range origins {
if p == path || strings.HasPrefix(p, path+".") {
delete(origins, p)
}
}
continue
}
if idx >= 0 && v.Kind == yaml.MappingNode && dst.Content[idx+1].Kind == yaml.MappingNode {
mergeMap(dst.Content[idx+1], v, path, origin, origins)
continue
}
for p := range origins {
if strings.HasPrefix(p, path+".") {
delete(origins, p)
}
}
if idx >= 0 {
dst.Content[idx+1] = v
} else {
dst.Content = append(dst.Content, &yaml.Node{Kind: yaml.ScalarNode, Tag: "!!str", Value: k.Value}, v)
}
recordLeaves(v, path, origin, origins)
}
}
func recordLeaves(v *yaml.Node, path string, origin Origin, origins map[string]Origin) {
if v.Kind == yaml.MappingNode {
for i := 0; i+1 < len(v.Content); i += 2 {
recordLeaves(v.Content[i+1], path+"."+v.Content[i].Value, origin, origins)
}
return
}
origins[path] = origin
}
func setPath(root *yaml.Node, keys []string, val *yaml.Node) {
cur := root
for i, k := range keys {
idx := -1
for j := 0; j+1 < len(cur.Content); j += 2 {
if cur.Content[j].Value == k {
idx = j
}
}
if i == len(keys)-1 {
if idx >= 0 {
cur.Content[idx+1] = val
} else {
cur.Content = append(cur.Content, &yaml.Node{Kind: yaml.ScalarNode, Tag: "!!str", Value: k}, val)
}
return
}
if idx < 0 || cur.Content[idx+1].Kind != yaml.MappingNode {
m := &yaml.Node{Kind: yaml.MappingNode, Tag: "!!map"}
if idx >= 0 {
cur.Content[idx+1] = m
} else {
cur.Content = append(cur.Content, &yaml.Node{Kind: yaml.ScalarNode, Tag: "!!str", Value: k}, m)
}
cur = m
} else {
cur = cur.Content[idx+1]
}
}
}
// Explanation answers "where does this value come from?" (PROF-05).
type Explanation struct {
File string `json:"file"`
Path string `json:"path"`
Found bool `json:"found"`
Origin Origin `json:"origin"`
Answers map[string]any `json:"answers,omitempty"` // the answers it used, with their origin
Origins map[string]string `json:"answerOrigins,omitempty"`
}
// Explain finds the origin of a value in a generated file. file may omit
// the "config/" prefix; path is dot separated.
func Explain(st *State, file, path string) Explanation {
file = strings.TrimPrefix(file, "config/")
ex := Explanation{File: "config/" + file, Path: path}
for _, f := range st.Files {
if f.Path != "config/"+file {
continue
}
p := path
for p != "" {
if o, ok := f.Origins[p]; ok {
ex.Found, ex.Origin = true, o
break
}
i := strings.LastIndex(p, ".")
if i < 0 {
break
}
p = p[:i]
}
}
if ex.Found && len(ex.Origin.Params) > 0 {
ex.Answers, ex.Origins = map[string]any{}, map[string]string{}
for _, p := range ex.Origin.Params {
if a, ok := st.Answers[p]; ok {
ex.Answers[p] = a.Value
ex.Origins[p] = a.Origin
}
}
}
return ex
}