Files

101 lines
2.7 KiB
Go
Raw Permalink Normal View History

package config
import (
"fmt"
"os"
"strings"
"gopkg.in/yaml.v3"
)
// Source is one input of Merge: a parsed YAML mapping and the name of
// where it came from (a file path, "path [section]", "default", ...),
// which Merge records as the origin of every value it contributes.
type Source struct {
Name string
Data map[string]any
}
// Origins maps the dotted path of every leaf of a merged configuration
// ("storage.inbound.root") to the Name of the Source that set it. A
// leaf is any value that is not a mapping: scalars and lists alike,
// since a list is replaced as a whole, never merged element by element.
type Origins map[string]string
// Merge overlays sources lowest priority first, with the same semantics
// as LoadMerged (see mergeMaps: maps merge key by key, scalars and lists
// are replaced, an explicit null removes the key), and returns the
// merged mapping together with the origin of each of its leaves. The
// sources' maps are not modified.
func Merge(sources ...Source) (map[string]any, Origins) {
merged := map[string]any{}
origins := Origins{}
for _, s := range sources {
mergeTracked(merged, s.Data, "", s.Name, origins)
}
return merged, origins
}
// ReadFile reads path and parses it as a YAML mapping (an empty file is
// an empty mapping). Unlike LoadMerged's layers, a missing file is an
// error: the caller asked for this file.
func ReadFile(path string) (map[string]any, error) {
data, err := os.ReadFile(path)
if err != nil {
return nil, fmt.Errorf("config: read %s: %w", path, err)
}
var m map[string]any
if err := yaml.Unmarshal(data, &m); err != nil {
return nil, fmt.Errorf("config: parse %s: %w", path, err)
}
if m == nil {
m = map[string]any{}
}
return m, nil
}
// mergeTracked overlays over onto base in place, recording the origin
// of every leaf it sets in origins (nil: not tracked).
func mergeTracked(base, over map[string]any, prefix, name string, origins Origins) {
for k, v := range over {
key := joinKey(prefix, k)
if v == nil {
delete(base, k)
origins.drop(key)
continue
}
if overMap, ok := v.(map[string]any); ok {
baseMap, ok := base[k].(map[string]any)
if !ok {
origins.drop(key)
baseMap = map[string]any{}
base[k] = baseMap
}
mergeTracked(baseMap, overMap, key, name, origins)
continue
}
origins.drop(key)
base[k] = v
if origins != nil {
origins[key] = name
}
}
}
// drop forgets the origin of key and of everything below it.
func (o Origins) drop(key string) {
delete(o, key)
prefix := key + "."
for k := range o {
if strings.HasPrefix(k, prefix) {
delete(o, k)
}
}
}
func joinKey(prefix, k string) string {
if prefix == "" {
return k
}
return prefix + "." + k
}