From 185211e3042b4b971cf59e55340cd98ba21855e5 Mon Sep 17 00:00:00 2001 From: Bjoern Kalkbrenner Date: Sun, 25 Oct 2026 14:57:50 +0100 Subject: [PATCH] config: Merge with per-value origins; configcmd: UnknownKeysNode config.Merge(sources...) overlays explicit, ordered sources with the LoadMerged rules (LoadMerged now uses the same code) and returns the origin of every leaf, for a "config show" that says where each value is set. config.ReadFile reads one file as a mapping, Resolver.Paths() exposes the core/paths resolver (e.g. DataDir for defaults). configcmd.UnknownKeysNode checks one section of a parsed document. Needed by the yamase family's layered configuration (yamase ADR-0074). Co-Authored-By: Claude Opus 5.5 --- README.md | 21 ++++++++ config/config.go | 6 +++ config/merge.go | 14 +---- config/origins.go | 101 ++++++++++++++++++++++++++++++++++++ config/origins_test.go | 106 ++++++++++++++++++++++++++++++++++++++ configcmd/unknown.go | 12 +++++ configcmd/unknown_test.go | 15 ++++++ 7 files changed, 262 insertions(+), 13 deletions(-) create mode 100644 config/origins.go create mode 100644 config/origins_test.go diff --git a/README.md b/README.md index 8a9c904..81b1d57 100644 --- a/README.md +++ b/README.md @@ -250,6 +250,27 @@ LOCALAPPDATA/APPDATA/PROGRAMDATA layering `core/paths` already resolves. layer can write `key: null` to intentionally unset a lower layer's value). +### Merging your own layers, with origins + +An application whose layers are not one file name per directory (the +yamase family reads a shared `yamase.yaml`, one section of it, and a +per-program file in every tier) builds its own ordered list and merges +it with the same rules: + +```go +data, err := config.ReadFile(path) // one file as a mapping +merged, origins := config.Merge( + config.Source{Name: "/etc/app/shared.yaml", Data: shared}, + config.Source{Name: "/etc/app/app.yaml", Data: data}, +) +// origins["tls.cert-file"] == the Name of the source that set it +``` + +`Origins` maps every leaf's dotted key to the source it came from (a +list is one leaf), for a "config show" that says where each value is +set. `Resolver.Paths()` returns the underlying `core/paths` resolver, +e.g. for a default derived from `DataDir()`. + ### Environment expansion String values may reference `${VAR}` or `$VAR` (enabled by default, diff --git a/config/config.go b/config/config.go index b8348e8..e4c294d 100644 --- a/config/config.go +++ b/config/config.go @@ -179,3 +179,9 @@ func (r *Resolver) Application() core.Application { return r.app } // Filename returns the configuration file name this Resolver searches // for in every layer. func (r *Resolver) Filename() string { return r.filename } + +// Paths returns the core/paths Resolver this Resolver locates its +// directories with (same application, environment and options), for a +// caller that also needs another category, e.g. DataDir for defaults +// derived from it. +func (r *Resolver) Paths() *paths.Resolver { return r.paths } diff --git a/config/merge.go b/config/merge.go index 8015ad3..ebf20eb 100644 --- a/config/merge.go +++ b/config/merge.go @@ -25,19 +25,7 @@ func mergeMaps(base, over map[string]any) map[string]any { if base == nil { base = map[string]any{} } - for k, v := range over { - if v == nil { - delete(base, k) - continue - } - if overMap, ok := v.(map[string]any); ok { - if baseMap, ok := base[k].(map[string]any); ok { - base[k] = mergeMaps(baseMap, overMap) - continue - } - } - base[k] = v - } + mergeTracked(base, over, "", "", nil) return base } diff --git a/config/origins.go b/config/origins.go new file mode 100644 index 0000000..969fa62 --- /dev/null +++ b/config/origins.go @@ -0,0 +1,101 @@ +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 +} diff --git a/config/origins_test.go b/config/origins_test.go new file mode 100644 index 0000000..bdc57b2 --- /dev/null +++ b/config/origins_test.go @@ -0,0 +1,106 @@ +package config + +import ( + "os" + "path/filepath" + "reflect" + "testing" +) + +func TestMergeTracksOrigins(t *testing.T) { + low := Source{Name: "system", Data: map[string]any{ + "hostname": "mail.example.org", + "tls": map[string]any{"cert-file": "a.crt", "key-file": "a.key"}, + "secrets": []any{"one", "two"}, + "limits": map[string]any{"max": 10}, + "drop": "me", + }} + high := Source{Name: "program", Data: map[string]any{ + "tls": map[string]any{"cert-file": "b.crt"}, + "secrets": []any{"three"}, + "limits": "flat", + "drop": nil, + }} + merged, origins := Merge(low, high) + + want := map[string]any{ + "hostname": "mail.example.org", + "tls": map[string]any{"cert-file": "b.crt", "key-file": "a.key"}, + "secrets": []any{"three"}, + "limits": "flat", + } + if !reflect.DeepEqual(merged, want) { + t.Errorf("merged = %#v\nwant %#v", merged, want) + } + wantOrigins := Origins{ + "hostname": "system", + "tls.cert-file": "program", + "tls.key-file": "system", + "secrets": "program", + "limits": "program", + } + if !reflect.DeepEqual(origins, wantOrigins) { + t.Errorf("origins = %#v\nwant %#v", origins, wantOrigins) + } +} + +func TestMergeMapReplacesScalarAndBack(t *testing.T) { + merged, origins := Merge( + Source{Name: "a", Data: map[string]any{"x": "scalar"}}, + Source{Name: "b", Data: map[string]any{"x": map[string]any{"y": 1}}}, + ) + if !reflect.DeepEqual(merged, map[string]any{"x": map[string]any{"y": 1}}) { + t.Errorf("merged = %#v", merged) + } + if !reflect.DeepEqual(origins, Origins{"x.y": "b"}) { + t.Errorf("origins = %#v", origins) + } + + merged, origins = Merge( + Source{Name: "a", Data: map[string]any{"x": map[string]any{"y": 1, "z": 2}}}, + Source{Name: "b", Data: map[string]any{"x": "scalar"}}, + ) + if !reflect.DeepEqual(merged, map[string]any{"x": "scalar"}) { + t.Errorf("merged = %#v", merged) + } + if !reflect.DeepEqual(origins, Origins{"x": "b"}) { + t.Errorf("origins = %#v", origins) + } +} + +func TestMergeNullRemovesSubtree(t *testing.T) { + merged, origins := Merge( + Source{Name: "a", Data: map[string]any{"x": map[string]any{"y": 1, "z": 2}, "w": 3}}, + Source{Name: "b", Data: map[string]any{"x": nil}}, + ) + if !reflect.DeepEqual(merged, map[string]any{"w": 3}) { + t.Errorf("merged = %#v", merged) + } + if !reflect.DeepEqual(origins, Origins{"w": "a"}) { + t.Errorf("origins = %#v", origins) + } +} + +func TestMergeDoesNotModifySources(t *testing.T) { + inner := map[string]any{"y": 1} + low := Source{Name: "a", Data: map[string]any{"x": inner}} + Merge(low, Source{Name: "b", Data: map[string]any{"x": map[string]any{"z": 2}}}) + if !reflect.DeepEqual(inner, map[string]any{"y": 1}) { + t.Errorf("source map modified: %#v", inner) + } +} + +func TestReadFile(t *testing.T) { + dir := t.TempDir() + if _, err := ReadFile(filepath.Join(dir, "missing.yaml")); err == nil { + t.Error("ReadFile of a missing file succeeded") + } + empty := filepath.Join(dir, "empty.yaml") + if err := os.WriteFile(empty, nil, 0o644); err != nil { + t.Fatal(err) + } + m, err := ReadFile(empty) + if err != nil || m == nil || len(m) != 0 { + t.Errorf("ReadFile(empty) = %#v, %v; want empty map", m, err) + } +} diff --git a/configcmd/unknown.go b/configcmd/unknown.go index 572e32c..147c4d1 100644 --- a/configcmd/unknown.go +++ b/configcmd/unknown.go @@ -43,6 +43,18 @@ func UnknownKeys(raw []byte, schema any) ([]UnknownKey, error) { return out, nil } +// UnknownKeysNode is UnknownKeys for an already parsed mapping node +// (e.g. one section of a larger file): keys are reported relative to n, +// with their line in the original document. +func UnknownKeysNode(n *yaml.Node, schema any) []UnknownKey { + if n == nil || n.Kind != yaml.MappingNode || schema == nil { + return nil + } + var out []UnknownKey + walkUnknown(nil, reflect.TypeOf(schema), n, &out) + return out +} + // UnknownKeysFile is UnknownKeys for the file at path. func UnknownKeysFile(path string, schema any) ([]UnknownKey, error) { raw, err := os.ReadFile(path) diff --git a/configcmd/unknown_test.go b/configcmd/unknown_test.go index 5f3ef12..736863b 100644 --- a/configcmd/unknown_test.go +++ b/configcmd/unknown_test.go @@ -109,3 +109,18 @@ func TestWarnUnknownAndCheck(t *testing.T) { t.Errorf("clean file: %v %q", ok, note) } } + +func TestUnknownKeysNode(t *testing.T) { + var doc yaml.Node + if err := yaml.Unmarshal([]byte("other: 1\nsection:\n log-level: info\n log-levle: debug\n"), &doc); err != nil { + t.Fatal(err) + } + section := doc.Content[0].Content[3] + got := UnknownKeysNode(section, testConfig{}) + if len(got) != 1 || got[0].Key != "log-levle" || got[0].Line != 4 { + t.Errorf("UnknownKeysNode = %v, want log-levle on line 4 (relative key, document line)", got) + } + if got := UnknownKeysNode(nil, testConfig{}); got != nil { + t.Errorf("UnknownKeysNode(nil) = %v", got) + } +}