321 lines
10 KiB
Go
321 lines
10 KiB
Go
package configcmd
|
|||
|
|
|
||
|
|
import (
|
||
|
|
"bytes"
|
||
|
|
"fmt"
|
||
|
|
"reflect"
|
||
|
|
"regexp"
|
||
|
|
"sort"
|
||
|
|
"strings"
|
||
|
|
|
||
|
|
"gopkg.in/yaml.v3"
|
||
|
|
)
|
||
|
|
|
||
|
|
// Addition is one option a configuration file does not mention yet,
|
||
|
|
// rendered from the full template as a commented YAML block.
|
||
|
|
type Addition struct {
|
||
|
|
// Key is the option's dotted path, e.g. "limits.connection-rate-per-source".
|
||
|
|
Key string
|
||
|
|
// Text is the commented block, indented for where it goes, ending
|
||
|
|
// in a newline.
|
||
|
|
Text string
|
||
|
|
// AfterLine is the 1-based line of the file the block goes after;
|
||
|
|
// 0 means the end of the file (a top-level option).
|
||
|
|
AfterLine int
|
||
|
|
}
|
||
|
|
|
||
|
|
// Missing compares a configuration file with the full template and
|
||
|
|
// returns, in template order, every option the template documents that
|
||
|
|
// the file neither sets nor mentions as a "# key:" comment -- the same
|
||
|
|
// shape the blocks themselves are added in, so running it again on the
|
||
|
|
// upgraded file finds nothing.
|
||
|
|
//
|
||
|
|
// The comparison descends into mappings the file and the template both
|
||
|
|
// have; a list (listeners, blocklists, ...) is the operator's data and
|
||
|
|
// is never descended into, and neither is an option the file sets to a
|
||
|
|
// non-mapping value (e.g. "tls:" left empty on purpose).
|
||
|
|
//
|
||
|
|
// schema is the program's configuration struct (e.g. config.Config{}).
|
||
|
|
// With it, a mapping whose Go type is a map (keys the operator names,
|
||
|
|
// like a map of named backends) is operator data too: only its presence
|
||
|
|
// counts, the template's example entries are never offered inside it.
|
||
|
|
// nil compares by the template alone.
|
||
|
|
func Missing(raw, full []byte, schema any) ([]Addition, error) {
|
||
|
|
var file, tmpl yaml.Node
|
||
|
|
if err := yaml.Unmarshal(raw, &file); err != nil {
|
||
|
|
return nil, fmt.Errorf("parsing: %w", err)
|
||
|
|
}
|
||
|
|
if err := yaml.Unmarshal(full, &tmpl); err != nil {
|
||
|
|
return nil, fmt.Errorf("parsing the full template: %w", err)
|
||
|
|
}
|
||
|
|
troot := docMapping(&tmpl)
|
||
|
|
if troot == nil {
|
||
|
|
return nil, nil
|
||
|
|
}
|
||
|
|
lines := strings.Split(string(raw), "\n")
|
||
|
|
froot := docMapping(&file)
|
||
|
|
if froot == nil {
|
||
|
|
if len(file.Content) > 0 {
|
||
|
|
return nil, fmt.Errorf("top level is not a mapping")
|
||
|
|
}
|
||
|
|
// empty (or comments only): every top-level option is missing
|
||
|
|
froot = &yaml.Node{Kind: yaml.MappingNode}
|
||
|
|
}
|
||
|
|
var t reflect.Type
|
||
|
|
if schema != nil {
|
||
|
|
t = reflect.TypeOf(schema)
|
||
|
|
}
|
||
|
|
return compare(nil, t, froot, troot, 0, 1, len(lines), 0, lines), nil
|
||
|
|
}
|
||
|
|
|
||
|
|
func docMapping(doc *yaml.Node) *yaml.Node {
|
||
|
|
if doc.Kind != yaml.DocumentNode || len(doc.Content) == 0 || doc.Content[0].Kind != yaml.MappingNode {
|
||
|
|
return nil
|
||
|
|
}
|
||
|
|
return doc.Content[0]
|
||
|
|
}
|
||
|
|
|
||
|
|
// compare collects the template keys missing in fmap. t is the Go type
|
||
|
|
// of the mapping (nil: unknown, compare by the template alone), from..to
|
||
|
|
// (1-based) are the file lines fmap spans, childIndent the column its
|
||
|
|
// keys start at, and afterLine where a missing key's block goes (0: end
|
||
|
|
// of file).
|
||
|
|
func compare(path []string, t reflect.Type, fmap, tmap *yaml.Node, childIndent, from, to, afterLine int, lines []string) []Addition {
|
||
|
|
var out []Addition
|
||
|
|
for i := 0; i+1 < len(tmap.Content); i += 2 {
|
||
|
|
tkey, tval := tmap.Content[i], tmap.Content[i+1]
|
||
|
|
sub := append(append([]string(nil), path...), tkey.Value)
|
||
|
|
var ft reflect.Type
|
||
|
|
if t != nil {
|
||
|
|
var ok bool
|
||
|
|
if ft, ok = fieldType(t, tkey.Value); !ok {
|
||
|
|
continue // not an option of this program
|
||
|
|
}
|
||
|
|
}
|
||
|
|
fkey, fval := lookup(fmap, tkey.Value)
|
||
|
|
if fval != nil {
|
||
|
|
if fval.Kind == yaml.MappingNode && tval.Kind == yaml.MappingNode && fval.Style&yaml.FlowStyle == 0 &&
|
||
|
|
(ft == nil || deref(ft).Kind() == reflect.Struct) {
|
||
|
|
indent := childIndent + 2
|
||
|
|
if len(fval.Content) > 0 {
|
||
|
|
indent = fval.Content[0].Column - 1
|
||
|
|
}
|
||
|
|
end := blockEnd(lines, lastLine(fval), indent)
|
||
|
|
out = append(out, compare(sub, ft, fval, tval, indent, fkey.Line, end, end, lines)...)
|
||
|
|
}
|
||
|
|
continue
|
||
|
|
}
|
||
|
|
if mentioned(lines, from, to, childIndent, tkey.Value) {
|
||
|
|
continue
|
||
|
|
}
|
||
|
|
out = append(out, Addition{
|
||
|
|
Key: strings.Join(sub, "."),
|
||
|
|
Text: render(tkey, tval, childIndent),
|
||
|
|
AfterLine: afterLine,
|
||
|
|
})
|
||
|
|
}
|
||
|
|
return out
|
||
|
|
}
|
||
|
|
|
||
|
|
func lookup(m *yaml.Node, key string) (*yaml.Node, *yaml.Node) {
|
||
|
|
for i := 0; i+1 < len(m.Content); i += 2 {
|
||
|
|
if m.Content[i].Value == key {
|
||
|
|
return m.Content[i], m.Content[i+1]
|
||
|
|
}
|
||
|
|
}
|
||
|
|
return nil, nil
|
||
|
|
}
|
||
|
|
|
||
|
|
// lastLine is the last file line a node's value occupies.
|
||
|
|
func lastLine(n *yaml.Node) int {
|
||
|
|
last := n.Line
|
||
|
|
if n.Kind == yaml.ScalarNode && n.Style&(yaml.LiteralStyle|yaml.FoldedStyle) != 0 {
|
||
|
|
last += strings.Count(strings.TrimRight(n.Value, "\n"), "\n") + 1
|
||
|
|
}
|
||
|
|
for _, c := range n.Content {
|
||
|
|
last = max(last, lastLine(c))
|
||
|
|
}
|
||
|
|
return last
|
||
|
|
}
|
||
|
|
|
||
|
|
func indentOf(l string) int { return len(l) - len(strings.TrimLeft(l, " ")) }
|
||
|
|
|
||
|
|
// blockEnd extends a block's last line over the comment lines right
|
||
|
|
// after it that are indented as its children -- blocks an earlier
|
||
|
|
// upgrade added there still belong to it.
|
||
|
|
func blockEnd(lines []string, last, minIndent int) int {
|
||
|
|
for last < len(lines) {
|
||
|
|
l := lines[last] // the line after "last" (1-based)
|
||
|
|
if !strings.HasPrefix(strings.TrimSpace(l), "#") || indentOf(l) < minIndent {
|
||
|
|
break
|
||
|
|
}
|
||
|
|
last++
|
||
|
|
}
|
||
|
|
return last
|
||
|
|
}
|
||
|
|
|
||
|
|
// mentioned reports whether lines from..to (1-based) set key or carry it
|
||
|
|
// as a "# key:" comment at the given indent. Only "#" followed by at
|
||
|
|
// most one space counts, so the deeper lines of a commented block
|
||
|
|
// ("# driver: ...") are not taken for a sibling option.
|
||
|
|
func mentioned(lines []string, from, to, indent int, key string) bool {
|
||
|
|
re := regexp.MustCompile(`^#\s?` + regexp.QuoteMeta(key) + `:`)
|
||
|
|
for i := max(from, 1) - 1; i < to && i < len(lines); i++ {
|
||
|
|
if indentOf(lines[i]) == indent && re.MatchString(lines[i][indent:]) {
|
||
|
|
return true
|
||
|
|
}
|
||
|
|
}
|
||
|
|
return false
|
||
|
|
}
|
||
|
|
|
||
|
|
// render returns one template option as a commented block at indent:
|
||
|
|
// the template's comment lines stay as they are, every YAML line gets
|
||
|
|
// "# " in front, so adding it changes nothing until the operator
|
||
|
|
// removes the "#".
|
||
|
|
func render(key, val *yaml.Node, indent int) string {
|
||
|
|
k := *key
|
||
|
|
k.FootComment = ""
|
||
|
|
var buf bytes.Buffer
|
||
|
|
enc := yaml.NewEncoder(&buf)
|
||
|
|
enc.SetIndent(2)
|
||
|
|
_ = enc.Encode(&yaml.Node{Kind: yaml.MappingNode, Content: []*yaml.Node{&k, val}})
|
||
|
|
_ = enc.Close()
|
||
|
|
|
||
|
|
pad := strings.Repeat(" ", indent)
|
||
|
|
var b strings.Builder
|
||
|
|
for _, l := range strings.Split(strings.TrimRight(buf.String(), "\n"), "\n") {
|
||
|
|
switch {
|
||
|
|
case strings.TrimSpace(l) == "":
|
||
|
|
case strings.HasPrefix(l, "#"):
|
||
|
|
b.WriteString(pad + l + "\n")
|
||
|
|
default:
|
||
|
|
b.WriteString(pad + "# " + l + "\n")
|
||
|
|
}
|
||
|
|
}
|
||
|
|
return b.String()
|
||
|
|
}
|
||
|
|
|
||
|
|
// Apply inserts the additions Missing returned into raw: nested ones
|
||
|
|
// after their line (bottom-up, so earlier line numbers stay valid),
|
||
|
|
// top-level ones at the end of the file.
|
||
|
|
func Apply(raw []byte, adds []Addition) []byte {
|
||
|
|
lines := strings.Split(string(raw), "\n")
|
||
|
|
byLine := map[int]string{}
|
||
|
|
var at []int
|
||
|
|
var tail strings.Builder
|
||
|
|
for _, a := range adds {
|
||
|
|
if a.AfterLine == 0 {
|
||
|
|
tail.WriteString("\n" + a.Text)
|
||
|
|
continue
|
||
|
|
}
|
||
|
|
if _, ok := byLine[a.AfterLine]; !ok {
|
||
|
|
at = append(at, a.AfterLine)
|
||
|
|
}
|
||
|
|
byLine[a.AfterLine] += a.Text
|
||
|
|
}
|
||
|
|
sort.Sort(sort.Reverse(sort.IntSlice(at)))
|
||
|
|
for _, n := range at {
|
||
|
|
n = min(n, len(lines))
|
||
|
|
ins := strings.Split(strings.TrimRight(byLine[n], "\n"), "\n")
|
||
|
|
lines = append(lines[:n], append(ins, lines[n:]...)...)
|
||
|
|
}
|
||
|
|
out := strings.Join(lines, "\n")
|
||
|
|
if tail.Len() > 0 {
|
||
|
|
out = strings.TrimRight(out, "\n") + "\n" + tail.String()
|
||
|
|
}
|
||
|
|
return []byte(out)
|
||
|
|
}
|
||
|
|
|
||
|
|
// UndocumentedKeys returns the dotted YAML paths of schema (a struct
|
||
|
|
// value, e.g. config.Config{}) that the template does not contain --
|
||
|
|
// neither as a key nor, for a list of structs, in the list's first
|
||
|
|
// item. A program's tests call it with its full template so that a new
|
||
|
|
// option cannot be added without documenting it, which is what keeps
|
||
|
|
// "config upgrade" useful.
|
||
|
|
func UndocumentedKeys(template string, schema any) ([]string, error) {
|
||
|
|
var doc yaml.Node
|
||
|
|
if err := yaml.Unmarshal([]byte(template), &doc); err != nil {
|
||
|
|
return nil, fmt.Errorf("parsing the template: %w", err)
|
||
|
|
}
|
||
|
|
root := docMapping(&doc)
|
||
|
|
if root == nil {
|
||
|
|
return nil, fmt.Errorf("template top level is not a mapping")
|
||
|
|
}
|
||
|
|
var out []string
|
||
|
|
walkSchema(reflect.TypeOf(schema), root, nil, &out)
|
||
|
|
return out, nil
|
||
|
|
}
|
||
|
|
|
||
|
|
func walkSchema(t reflect.Type, m *yaml.Node, path []string, out *[]string) {
|
||
|
|
t = deref(t)
|
||
|
|
if t.Kind() != reflect.Struct {
|
||
|
|
return
|
||
|
|
}
|
||
|
|
for i := range t.NumField() {
|
||
|
|
f := t.Field(i)
|
||
|
|
name, opts, _ := strings.Cut(f.Tag.Get("yaml"), ",")
|
||
|
|
if name == "-" || !f.IsExported() {
|
||
|
|
continue
|
||
|
|
}
|
||
|
|
// An inline (embedded) struct's fields are keys of this mapping.
|
||
|
|
if f.Anonymous && strings.Contains(","+opts+",", ",inline,") {
|
||
|
|
walkSchema(f.Type, m, path, out)
|
||
|
|
continue
|
||
|
|
}
|
||
|
|
if name == "" {
|
||
|
|
name = strings.ToLower(f.Name)
|
||
|
|
}
|
||
|
|
sub := append(append([]string(nil), path...), name)
|
||
|
|
_, val := lookup(m, name)
|
||
|
|
if val == nil {
|
||
|
|
*out = append(*out, strings.Join(sub, "."))
|
||
|
|
continue
|
||
|
|
}
|
||
|
|
ft := deref(f.Type)
|
||
|
|
switch {
|
||
|
|
case ft.Kind() == reflect.Struct && val.Kind == yaml.MappingNode:
|
||
|
|
walkSchema(ft, val, sub, out)
|
||
|
|
case ft.Kind() == reflect.Slice && deref(ft.Elem()).Kind() == reflect.Struct &&
|
||
|
|
val.Kind == yaml.SequenceNode && len(val.Content) > 0 && val.Content[0].Kind == yaml.MappingNode:
|
||
|
|
walkSchema(ft.Elem(), val.Content[0], append(sub[:len(sub)-1:len(sub)-1], name+"[]"), out)
|
||
|
|
}
|
||
|
|
}
|
||
|
|
}
|
||
|
|
|
||
|
|
// fieldType returns the type of the field of struct t (or a pointer to
|
||
|
|
// one) whose YAML name is key.
|
||
|
|
func fieldType(t reflect.Type, key string) (reflect.Type, bool) {
|
||
|
|
t = deref(t)
|
||
|
|
if t.Kind() != reflect.Struct {
|
||
|
|
return nil, false
|
||
|
|
}
|
||
|
|
for i := range t.NumField() {
|
||
|
|
f := t.Field(i)
|
||
|
|
name, opts, _ := strings.Cut(f.Tag.Get("yaml"), ",")
|
||
|
|
if strings.Contains(","+opts+",", ",inline,") {
|
||
|
|
// An inline struct's keys are its parent's (named or
|
||
|
|
// embedded); an inline map takes every other key.
|
||
|
|
if deref(f.Type).Kind() == reflect.Map {
|
||
|
|
return deref(f.Type).Elem(), true
|
||
|
|
}
|
||
|
|
if ft, ok := fieldType(f.Type, key); ok {
|
||
|
|
return ft, true
|
||
|
|
}
|
||
|
|
continue
|
||
|
|
}
|
||
|
|
if name == "" {
|
||
|
|
name = strings.ToLower(f.Name)
|
||
|
|
}
|
||
|
|
if name == key && name != "-" && f.IsExported() {
|
||
|
|
return f.Type, true
|
||
|
|
}
|
||
|
|
}
|
||
|
|
return nil, false
|
||
|
|
}
|
||
|
|
|
||
|
|
func deref(t reflect.Type) reflect.Type {
|
||
|
|
for t.Kind() == reflect.Pointer {
|
||
|
|
t = t.Elem()
|
||
|
|
}
|
||
|
|
return t
|
||
|
|
}
|