configcmd: config show, Doctor, KnownKey and a Layered hook

"config show [--json] [--show-secrets]" prints the configuration with
the origin of every value (secrets redacted), for every program.
Spec.Layered lets a program whose configuration is merged from several
inputs (family file, a section of it, its own file -- the yamase
family) run path, validate and show over all layers, with its own
unknown-option rules; unknown options are warnings there. Doctor(report,
spec, explicit) is the config part of a doctor command. UnknownKey
carries the layer it is in; KnownKey tells whether a dotted key is an
option of a config struct.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
terminarandClaude Opus 5.5 committed 2026-10-25 17:29:19 +01:00
1 parent 185211e304
commit fa52990e3e
7 files changed
+758 -11

No files matched your search

+37 -4
View File
@@ -6,6 +6,7 @@
// <program> config validate
// <program> config upgrade [--write]
// <program> config path
// <program> config show [--json] [--show-secrets]
//
// The command behaves the same in every program; what differs is only
// the program's own part, passed in as a Spec: its name and
@@ -33,6 +34,11 @@
// Exit codes: 0 success, 1 the command ran and found a problem (invalid
// configuration, no file found, refusing to overwrite), 2 usage error.
//
// "config show" prints the configuration with the origin of every value.
// A program merged from several inputs (a family-wide file, a section
// of it, its own file) sets Spec.Layered so that path, validate and show
// work on all of them (see Layered).
//
// The package does not depend on cobra: a cobra program wires Run into
// a command with flag parsing disabled, taking --config out of the
// arguments itself, the same way it wires core/doctor.
@@ -113,6 +119,12 @@ type Spec struct {
// Options are passed through to core/config; tests use them to
// inject a platform, environment, root and working directory.
Options []coreconfig.Option
// Layered, when set, makes path, validate and show work on a
// configuration merged from several inputs (see Layered); create
// and upgrade still work on Filename. nil: the program reads the
// single file Find selects.
Layered *Layered
}
func (s Spec) filename() string {
@@ -131,7 +143,7 @@ func Run(s Spec, explicit string, args []string, stdout, stderr io.Writer) int {
}
sub, rest := args[0], args[1:]
switch sub {
case "create", "validate", "upgrade", "path":
case "create", "validate", "upgrade", "path", "show":
if s.None {
fmt.Fprintf(stdout, "%s has no configuration file\n", s.Name)
return ExitOK
@@ -141,11 +153,25 @@ func Run(s Spec, explicit string, args []string, stdout, stderr io.Writer) int {
case "create":
return s.create(explicit, rest, stdout, stderr)
case "validate":
if s.Layered != nil {
if code := parse(s.newFlagSet("validate", stderr), rest); code >= 0 {
return code
}
return s.layeredValidate(explicit, stdout, stderr)
}
return s.validate(explicit, rest, stdout, stderr)
case "upgrade":
return s.upgrade(explicit, rest, stdout, stderr)
case "path":
if s.Layered != nil {
if code := parse(s.newFlagSet("path", stderr), rest); code >= 0 {
return code
}
return s.layeredPath(explicit, stdout, stderr)
}
return s.path(explicit, rest, stdout, stderr)
case "show":
return s.show(explicit, rest, stdout, stderr)
case "help", "-h", "-help", "--help":
usage(s, stdout)
return ExitOK
@@ -158,9 +184,13 @@ func Run(s Spec, explicit string, args []string, stdout, stderr io.Writer) int {
// Subcommands are the config subcommands, for a program's completion
// tree and help text.
var Subcommands = []string{"create", "validate", "upgrade", "path"}
var Subcommands = []string{"create", "validate", "upgrade", "path", "show"}
func usage(s Spec, w io.Writer) {
pathHelp := "list the locations searched for " + s.filename() + ", highest priority first"
if s.Layered != nil {
pathHelp = "list every configuration layer, highest priority first"
}
fmt.Fprintf(w, `usage: %[1]s config <subcommand> [--config <file>]
create [--minimal|--full] [--force] [--output <file>]
@@ -169,8 +199,11 @@ func usage(s Spec, w io.Writer) {
upgrade [--write]
show the options of "create --full" the file does not mention
yet, as commented blocks; --write adds them to the file
path list the locations searched for %[2]s, highest priority first
`, s.Name, s.filename())
path %[3]s
show [--json] [--show-secrets]
print the configuration with the file every value comes from;
secrets are redacted unless --show-secrets
`, s.Name, s.filename(), pathHelp)
}
// newFlagSet returns a flag set for one subcommand whose usage errors go
+301
View File
@@ -0,0 +1,301 @@
package configcmd
import (
"errors"
"fmt"
"io"
"strings"
"gopkg.in/yaml.v3"
coreconfig "yetano.dev/yetano/core/config"
"yetano.dev/yetano/core/doctor"
"yetano.dev/yetano/core/paths"
)
// Layered describes a program whose configuration is merged from
// several inputs that are not one file name per directory -- e.g. a
// family-wide file, one section of it and a per-program file in every
// tier (the yamase family, yamase ADR-0074). With Spec.Layered set,
// "config path", "config validate" and "config show" work on all
// layers; "config create" and "config upgrade" keep working on the
// program's own file (Spec.Filename).
//
// Unknown options are warnings for a layered program, not problems:
// files shared between programs (of different versions) legitimately
// carry options one program does not read.
type Layered struct {
// Layers lists every input, highest priority first, whether it
// exists or not (for "config path" and doctor). explicit is the
// --config value.
Layers func(explicit string) ([]LayerInfo, error)
// Load merges the existing layers. With none at all it returns an
// error wrapping ErrNotFound.
Load func(explicit string) (*Effective, error)
// Unknown reports the unknown options of e's layers. nil: every
// existing layer's file is checked against Spec.Schema.
Unknown func(e *Effective) ([]UnknownKey, error)
// Validate parses and validates the merged configuration (YAML) the
// way the program does at startup, including files it names.
Validate func(merged []byte) error
// Used reports whether the program reads the option key, for "config
// show". nil: KnownKey(Spec.Schema, key).
Used func(key string) bool
}
// LayerInfo is one input of a layered configuration.
type LayerInfo struct {
// Name is how the layer is shown and recorded as an origin: the
// path, plus e.g. " [section]" for a part of a file.
Name string
// Path is the file that holds it.
Path string
// Source names the tier ("system-directory", "--config", ...).
Source string
// Exists reports whether the layer contributes anything.
Exists bool
}
// Effective is a merged configuration: its layers, the merged mapping
// and the origin (LayerInfo.Name, or a default's name) of every leaf.
type Effective struct {
// Name is the program's name, for "config show"'s header.
Name string
// Layers are all layers, highest priority first.
Layers []LayerInfo
Merged map[string]any
Origins coreconfig.Origins
// Loader is the Layered loader's own value for this configuration
// (e.g. its richer layer list), for its Unknown hook; nil otherwise.
Loader any
}
// Used returns the layers that contributed, highest priority first.
func (e *Effective) Used() []LayerInfo {
var out []LayerInfo
for _, l := range e.Layers {
if l.Exists {
out = append(out, l)
}
}
return out
}
// Describe names the layers that contributed, lowest priority first
// ("a.yaml + b.yaml [section]"), for log lines and messages.
func (e *Effective) Describe() string {
used := e.Used()
names := make([]string, len(used))
for i, l := range used {
names[len(used)-1-i] = l.Name
}
return strings.Join(names, " + ")
}
// YAML returns the merged configuration as YAML, for the program's own
// parser.
func (e *Effective) YAML() ([]byte, error) {
data, err := yaml.Marshal(e.Merged)
if err != nil {
return nil, fmt.Errorf("config: marshal merged configuration: %w", err)
}
return data, nil
}
// effective loads the configuration "config show" and Doctor report:
// Layered.Load, or else the single file Find selects as the only layer.
func (s Spec) effective(explicit string) (*Effective, error) {
if s.Layered != nil {
return s.Layered.Load(explicit)
}
file, err := s.Find(explicit)
if err != nil {
return nil, err
}
data, err := coreconfig.ReadFile(file.Path)
if err != nil {
return nil, err
}
merged, origins := coreconfig.Merge(coreconfig.Source{Name: file.Path, Data: data})
src := file.Source.String()
return &Effective{
Name: s.Name,
Layers: []LayerInfo{{Name: file.Path, Path: file.Path, Source: src, Exists: true}},
Merged: merged,
Origins: origins,
}, nil
}
// UnknownIn returns the unknown options of e's layers: Layered.Unknown
// if set, else every existing layer's file against s.Schema.
func (s Spec) UnknownIn(e *Effective) ([]UnknownKey, error) {
if s.Layered != nil && s.Layered.Unknown != nil {
return s.Layered.Unknown(e)
}
if s.Schema == nil {
return nil, nil
}
var out []UnknownKey
for i := len(e.Layers) - 1; i >= 0; i-- {
l := e.Layers[i]
if !l.Exists {
continue
}
keys, err := UnknownKeysFile(l.Path, s.Schema)
if err != nil {
return nil, err
}
for _, k := range keys {
k.Layer = l.Name
out = append(out, k)
}
}
return out, nil
}
func (s Spec) layeredPath(explicit string, stdout, stderr io.Writer) int {
layers, err := s.Layered.Layers(explicit)
if err != nil {
fmt.Fprintf(stderr, "%s config path: %v\n", s.Name, err)
return ExitProblem
}
found := false
for _, l := range layers {
mark, state := " ", "missing"
if l.Exists {
mark, state, found = "*", "used", true
}
fmt.Fprintf(stdout, "%s %s (%s, %s)\n", mark, l.Name, l.Source, state)
}
if !found {
fmt.Fprintf(stdout, "no configuration file found -- \"%s config create\" writes one\n", s.Name)
}
return ExitOK
}
func (s Spec) layeredValidate(explicit string, stdout, stderr io.Writer) int {
e, err := s.Layered.Load(explicit)
if err != nil {
fmt.Fprintf(stderr, "%s config validate: %v\n", s.Name, err)
return ExitProblem
}
unknown, err := s.UnknownIn(e)
if err != nil {
fmt.Fprintf(stderr, "%s config validate: %v\n", s.Name, err)
return ExitProblem
}
for _, k := range unknown {
fmt.Fprintf(stdout, "warning: unknown option %s (%s, line %d), ignored -- the default applies\n", k.Key, k.Layer, k.Line)
}
if s.Layered.Validate != nil {
data, err := e.YAML()
if err == nil {
err = s.Layered.Validate(data)
}
if err != nil {
fmt.Fprintf(stderr, "%s config validate: %s: %v\n", s.Name, e.Describe(), err)
return ExitProblem
}
}
fmt.Fprintf(stdout, "%s: valid\n", e.Describe())
return ExitOK
}
func (s Spec) show(explicit string, args []string, stdout, stderr io.Writer) int {
fs := s.newFlagSet("show", stderr)
asJSON := fs.Bool("json", false, "print a JSON array of {key, value, source, used}")
secrets := fs.Bool("show-secrets", false, "print secret values instead of <redacted>")
if code := parse(fs, args); code >= 0 {
return code
}
e, err := s.effective(explicit)
if err != nil {
if s.Optional && explicit == "" && errors.Is(err, ErrNotFound) {
fmt.Fprintf(stdout, "no configuration file found -- %s runs on its built-in defaults\n", s.Name)
return ExitOK
}
fmt.Fprintf(stderr, "%s config show: %v\n", s.Name, err)
return ExitProblem
}
used := s.usedFunc()
if err := e.Show(stdout, used, *asJSON, *secrets); err != nil {
fmt.Fprintf(stderr, "%s config show: %v\n", s.Name, err)
return ExitProblem
}
return ExitOK
}
// usedFunc is Layered.Used, else KnownKey against the schema (every key
// counts as used without one).
func (s Spec) usedFunc() func(string) bool {
if s.Layered != nil && s.Layered.Used != nil {
return s.Layered.Used
}
if s.Schema == nil {
return nil
}
return func(key string) bool { return KnownKey(s.Schema, key) }
}
// Doctor records the program's core/paths locations and every
// configuration layer in r, checks that the configuration loads and has
// no unknown options, and returns it (nil when it does not load).
// Nothing is created. A layered program's unknown options are reported
// as a failed check like any program's: doctor is where an operator
// looks for them.
func Doctor(r *doctor.Report, s Spec, explicit string) *Effective {
r.AddPaths(s.App)
if s.Layered != nil {
layers, err := s.Layered.Layers(explicit)
if err != nil {
r.AddPath("config search", "", err)
}
for _, l := range layers {
name := "config search (" + l.Source + ")"
if l.Exists {
name = "config file (" + l.Source + ")"
}
r.AddPath(name, l.Name, nil)
}
} else if layers, err := s.Layers(explicit); err != nil {
r.AddPath("config search", "", err)
} else {
for _, l := range layers {
src := l.Source.String()
if l.Source == paths.APIOverride {
src = "--config"
}
r.AddPath("config search ("+src+")", l.Path, nil)
}
}
e, err := s.effective(explicit)
if err != nil {
note := err.Error()
if errors.Is(err, ErrNotFound) {
note = "none of the searched files exists; pass --config <file> or run \"" + s.Name + " config create\""
}
r.Check("config file found", false, note)
return nil
}
r.Check("config file found", true, e.Describe())
if s.Schema != nil || (s.Layered != nil && s.Layered.Unknown != nil) {
unknown, err := s.UnknownIn(e)
switch {
case err != nil:
r.Check("config has no unknown options", false, err.Error())
case len(unknown) == 0:
r.Check("config has no unknown options", true, "")
default:
parts := make([]string, len(unknown))
for i, k := range unknown {
parts[i] = k.String()
}
r.Check("config has no unknown options", false, "ignored, the defaults apply: "+strings.Join(parts, ", "))
}
}
return e
}
+213
View File
@@ -0,0 +1,213 @@
package configcmd
import (
"bytes"
"encoding/json"
"os"
"path/filepath"
"reflect"
"strings"
"testing"
"gopkg.in/yaml.v3"
coreconfig "yetano.dev/yetano/core/config"
"yetano.dev/yetano/core/doctor"
)
func TestShowSingleFile(t *testing.T) {
root := t.TempDir()
s := testSpec(root)
file := filepath.Join(root, "etc", "yamase", "yamase-test.yaml")
writeFile(t, file, minimalTemplate+"log-level: debug\nunread: 1\n")
code, out, errOut := run(t, s, "", "show")
if code != ExitOK {
t.Fatalf("show: exit %d: %s", code, errOut)
}
for _, want := range []string{
`log-level: "debug"`,
"# " + file,
`root: "/var/lib/yamase/queue"`,
"unread: 1",
"not used by yamase-test",
} {
if !strings.Contains(out, want) {
t.Errorf("show output lacks %q:\n%s", want, out)
}
}
code, out, _ = run(t, s, "", "show", "--json")
var values []Value
if code != ExitOK || json.Unmarshal([]byte(out), &values) != nil || len(values) == 0 {
t.Errorf("show --json: exit %d, output %q", code, out)
}
}
// fakeLayered serves two layers of one directory, as a family-wide file
// plus a program file.
func fakeLayered(dir string) *Layered {
shared := filepath.Join(dir, "family.yaml")
own := filepath.Join(dir, "own.yaml")
layers := func(string) ([]LayerInfo, error) {
return []LayerInfo{
{Name: own, Path: own, Source: "test", Exists: statOK(own)},
{Name: shared, Path: shared, Source: "test", Exists: statOK(shared)},
}, nil
}
return &Layered{
Layers: layers,
Load: func(explicit string) (*Effective, error) {
ls, _ := layers(explicit)
var sources []coreconfig.Source
for i := len(ls) - 1; i >= 0; i-- {
if !ls[i].Exists {
continue
}
data, err := coreconfig.ReadFile(ls[i].Path)
if err != nil {
return nil, err
}
sources = append(sources, coreconfig.Source{Name: ls[i].Name, Data: data})
}
if len(sources) == 0 {
return nil, ErrNotFound
}
merged, origins := coreconfig.Merge(sources...)
return &Effective{Name: "yamase-test", Layers: ls, Merged: merged, Origins: origins}, nil
},
Validate: func(merged []byte) error {
var s schema
if err := yaml.Unmarshal(merged, &s); err != nil {
return err
}
if len(s.Listen) == 0 {
return errNoListener
}
return nil
},
}
}
type testErr string
func (e testErr) Error() string { return string(e) }
const errNoListener = testErr("listen: at least one listener is required")
func statOK(path string) bool { return statExistsForTest(path) }
func TestLayered(t *testing.T) {
root := t.TempDir()
dir := filepath.Join(root, "cfg")
s := testSpec(root)
s.Layered = fakeLayered(dir)
if code, out, _ := run(t, s, "", "path"); code != ExitOK || !strings.Contains(out, "no configuration file found") {
t.Errorf("path without files: exit %d, %q", code, out)
}
if code, _, errOut := run(t, s, "", "validate"); code != ExitProblem || !strings.Contains(errOut, ErrNotFound.Error()) {
t.Errorf("validate without files: exit %d, %q", code, errOut)
}
writeFile(t, filepath.Join(dir, "family.yaml"), "log-level: info\nlisten:\n - address: \":25\"\n")
writeFile(t, filepath.Join(dir, "own.yaml"), "log-level: debug\nlog-levle: x\n")
code, out, _ := run(t, s, "", "path")
if code != ExitOK || strings.Count(out, "(test, used)") != 2 {
t.Errorf("path: exit %d, %q", code, out)
}
// Unknown options are warnings for a layered program.
code, out, errOut := run(t, s, "", "validate")
if code != ExitOK || !strings.Contains(out, "warning: unknown option log-levle ("+filepath.Join(dir, "own.yaml")+", line 2)") || !strings.Contains(out, ": valid") {
t.Errorf("validate: exit %d, stdout %q, stderr %q", code, out, errOut)
}
code, out, _ = run(t, s, "", "show")
if code != ExitOK || !strings.Contains(out, `log-level: "debug"`) || !strings.Contains(out, "# "+filepath.Join(dir, "family.yaml")) {
t.Errorf("show: exit %d:\n%s", code, out)
}
if !strings.Contains(out, "layers, lowest priority first: "+filepath.Join(dir, "family.yaml")+" + "+filepath.Join(dir, "own.yaml")) {
t.Errorf("show header:\n%s", out)
}
writeFile(t, filepath.Join(dir, "family.yaml"), "log-level: info\n")
if code, _, errOut := run(t, s, "", "validate"); code != ExitProblem || !strings.Contains(errOut, "listen") {
t.Errorf("validate of an invalid merge: exit %d, %q", code, errOut)
}
}
func TestDoctor(t *testing.T) {
root := t.TempDir()
s := testSpec(root)
r := doctor.Report{Program: "yamase-test"}
if e := Doctor(&r, s, ""); e != nil {
t.Error("Doctor without a file returned a configuration")
}
writeFile(t, filepath.Join(root, "etc", "yamase", "yamase-test.yaml"), minimalTemplate+"log-levle: x\n")
r = doctor.Report{Program: "yamase-test"}
e := Doctor(&r, s, "")
if e == nil {
t.Fatal("Doctor with a file returned nil")
}
var out bytes.Buffer
r.Run([]string{"--json"}, &out, &out)
if !strings.Contains(out.String(), "log-levle (") || !strings.Contains(out.String(), "config file found") {
t.Errorf("doctor report = %s", out.String())
}
}
func TestValuesRedaction(t *testing.T) {
merged, origins := coreconfig.Merge(coreconfig.Source{Name: "f", Data: map[string]any{
"srs": map[string]any{"secrets": []any{"plain", "env:X", "base64:abc"}},
"yaais": map[string]any{"token": "file:/run/t", "password": "hunter2"},
}})
e := &Effective{Name: "p", Merged: merged, Origins: origins}
got := map[string]any{}
for _, v := range e.Values(nil, false) {
got[v.Key] = v.Value
}
want := map[string]any{
"srs.secrets": []any{"<redacted>", "env:X", "<redacted>"},
"yaais.token": "file:/run/t",
"yaais.password": "<redacted>",
}
if !reflect.DeepEqual(got, want) {
t.Errorf("Values = %v, want %v", got, want)
}
}
type inlineBase struct {
Enabled bool `yaml:"enabled"`
}
func TestKnownKey(t *testing.T) {
type cfg struct {
Throttle struct {
inlineBase `yaml:",inline"`
Window string `yaml:"window"`
} `yaml:"throttle"`
Listen []struct {
Address string `yaml:"address"`
} `yaml:"listen"`
Backends map[string]struct{ Root string } `yaml:"backends"`
Custom selfDecoding `yaml:"custom"`
}
for key, want := range map[string]bool{
"throttle.enabled": true,
"throttle.window": true,
"throttle.nope": false,
"listen[0].address": true,
"listen[].address": true,
"backends.any.root": true,
"backends.any.nope": false,
"custom.anything": true,
"missing": false,
} {
if got := KnownKey(cfg{}, key); got != want {
t.Errorf("KnownKey(%q) = %v, want %v", key, got, want)
}
}
}
func statExistsForTest(path string) bool {
_, err := os.Stat(path)
return err == nil
}
+174
View File
@@ -0,0 +1,174 @@
package configcmd
import (
"encoding/json"
"fmt"
"io"
"reflect"
"regexp"
"sort"
"strings"
)
// Value is one leaf of a merged configuration, as "config show" reports
// it.
type Value struct {
Key string `json:"key"`
Value any `json:"value"`
Source string `json:"source"`
// Used reports whether the program reads this option; an option in a
// shared file that only other programs read has Used false.
Used bool `json:"used"`
}
// DefaultOrigin is the origin of a leaf no layer set (a value a loader
// filled in).
const DefaultOrigin = "default"
// Values returns every leaf of e, sorted by key, with its origin.
// used reports whether the program reads a key (nil: every key); a
// default it does not read is left out. Secret values (keys secrets,
// secret, token, password) are replaced by "<redacted>" unless
// showSecrets; a reference that only says where a secret is (env:,
// file:, secret://) is shown.
func (e *Effective) Values(used func(string) bool, showSecrets bool) []Value {
var out []Value
walkLeaves("", e.Merged, func(key string, v any) {
source := e.Origins[key]
if source == "" {
source = DefaultOrigin
}
u := used == nil || used(key)
if !u && source == DefaultOrigin {
return
}
if !showSecrets && isSecretKey(key) {
v = redact(v)
}
out = append(out, Value{Key: key, Value: v, Source: source, Used: u})
})
return out
}
// Show writes the merged configuration: indented YAML with every
// value's origin as a comment, or with asJSON a JSON array of Values.
func (e *Effective) Show(w io.Writer, used func(string) bool, asJSON, showSecrets bool) error {
values := e.Values(used, showSecrets)
if asJSON {
enc := json.NewEncoder(w)
enc.SetEscapeHTML(false)
enc.SetIndent("", " ")
return enc.Encode(values)
}
fmt.Fprintf(w, "# %s: effective configuration\n# layers, lowest priority first: %s\n", e.Name, e.Describe())
var printed []string // the parent path last printed, by depth
for _, v := range values {
parts := strings.Split(v.Key, ".")
for depth, name := range parts[:len(parts)-1] {
if depth < len(printed) && printed[depth] == name {
continue
}
printed = append(printed[:depth], name)
fmt.Fprintf(w, "%s%s:\n", strings.Repeat(" ", depth), name)
}
printed = printed[:len(parts)-1]
line := fmt.Sprintf("%s%s: %s", strings.Repeat(" ", len(parts)-1), parts[len(parts)-1], renderValue(v.Value))
note := v.Source
if !v.Used {
note += ", not used by " + e.Name
}
fmt.Fprintf(w, "%s%s# %s\n", line, strings.Repeat(" ", max(44-len(line), 1)), note)
}
return nil
}
func walkLeaves(prefix string, m map[string]any, fn func(string, any)) {
keys := make([]string, 0, len(m))
for k := range m {
keys = append(keys, k)
}
sort.Strings(keys)
for _, k := range keys {
key := k
if prefix != "" {
key = prefix + "." + k
}
if sub, ok := m[k].(map[string]any); ok && len(sub) > 0 {
walkLeaves(key, sub, fn)
continue
}
fn(key, m[k])
}
}
// renderValue formats a leaf as a single-line YAML value (JSON is a subset
// of YAML's flow style).
func renderValue(v any) string {
var b strings.Builder
enc := json.NewEncoder(&b)
enc.SetEscapeHTML(false)
if err := enc.Encode(v); err != nil {
return fmt.Sprint(v)
}
return strings.TrimSuffix(b.String(), "\n")
}
var secretKeys = map[string]bool{"secrets": true, "secret": true, "token": true, "password": true}
func isSecretKey(key string) bool { return secretKeys[key[strings.LastIndex(key, ".")+1:]] }
// redact replaces secret values, keeping references that only say where
// the secret is.
func redact(v any) any {
switch x := v.(type) {
case string:
for _, ref := range []string{"env:", "file:", "secret://"} {
if strings.HasPrefix(x, ref) {
return x
}
}
return "<redacted>"
case []any:
out := make([]any, len(x))
for i, e := range x {
out[i] = redact(e)
}
return out
}
return "<redacted>"
}
// listIndex matches the "[n]" (or "[]") of a list entry in a dotted key.
var listIndex = regexp.MustCompile(`\[\d*\]`)
// KnownKey reports whether the dotted option key ("storage.inbound.root",
// "listen[0].address") exists in schema (a configuration struct) by its
// yaml tags. A map accepts any key; a list, an interface or a type that
// decodes itself accepts everything below it; an embedded ",inline"
// struct contributes its fields.
func KnownKey(schema any, key string) bool {
if schema == nil {
return false
}
return knownPath(reflect.TypeOf(schema), strings.Split(listIndex.ReplaceAllString(key, ""), "."))
}
func knownPath(t reflect.Type, path []string) bool {
t = deref(t)
if len(path) == 0 {
return true
}
if t.Implements(unmarshalerType) || reflect.PointerTo(t).Implements(unmarshalerType) {
return true
}
switch t.Kind() {
case reflect.Struct:
ft, ok := fieldType(t, path[0])
return ok && knownPath(ft, path[1:])
case reflect.Map:
return knownPath(t.Elem(), path[1:])
case reflect.Interface, reflect.Slice, reflect.Array:
return true
}
return false
}
+9 -1
View File
@@ -19,9 +19,17 @@ type UnknownKey struct {
// entries of a list are "listen[1].tls".
Key string
Line int
// Layer names the layer the key is in, for a layered configuration
// (LayerInfo.Name); "" for a single file.
Layer string
}
func (k UnknownKey) String() string { return fmt.Sprintf("%s (line %d)", k.Key, k.Line) }
func (k UnknownKey) String() string {
if k.Layer != "" {
return fmt.Sprintf("%s (%s, line %d)", k.Key, k.Layer, k.Line)
}
return fmt.Sprintf("%s (line %d)", k.Key, k.Line)
}
// UnknownKeys lists the keys of raw that schema (the program's
// configuration struct, e.g. config.Config{}) has no field for, by its
+6 -6
View File
@@ -74,12 +74,12 @@ Ignored: x
t.Fatal(err)
}
want := []UnknownKey{
{"log-levle", 2},
{"listen[0].tsl", 5},
{"storage.mailstore.rot", 9},
{"backends.inbound.extra", 11},
{"throttle.enabeld", 15},
{"Ignored", 18},
{Key: "log-levle", Line: 2},
{Key: "listen[0].tsl", Line: 5},
{Key: "storage.mailstore.rot", Line: 9},
{Key: "backends.inbound.extra", Line: 11},
{Key: "throttle.enabeld", Line: 15},
{Key: "Ignored", Line: 18},
}
if !reflect.DeepEqual(got, want) {
t.Fatalf("UnknownKeys =\n%v\nwant\n%v", got, want)