configcmd.OneOf for alternative fields; completion.Files for paths
UndocumentedKeys reported the unused alternatives of a struct like SecretRef (env/file/value) as undocumented; a struct implementing the marker configcmd.OneOf now counts as documented with one alternative, and upgrade offers none of the others to a file that chose one. completion.Tree gets the key completion.Files: that level completes file and directory paths besides command names (bash, zsh, fish, PowerShell), for programs started as "<program> [path]" like yamc. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
1 parent
83f4228e66
commit
131d82642c
6 files changed
+244
-13
No files matched your search
@@ -321,7 +321,10 @@ docs/program-conventions.md in the meta-repository):
|
|||||||
|
|
||||||
- `completion.Run(program, tree, args, w)` prints a bash, zsh, fish or
|
- `completion.Run(program, tree, args, w)` prints a bash, zsh, fish or
|
||||||
PowerShell completion script generated from a static `completion.Tree`
|
PowerShell completion script generated from a static `completion.Tree`
|
||||||
of the program's commands.
|
of the program's commands. A level that also takes a path (a program
|
||||||
|
without subcommands, started as `<program> [path]`) adds the key
|
||||||
|
`completion.Files`; the script then completes files and directories
|
||||||
|
there besides the command names.
|
||||||
- `doctor.Report` collects the locations the program resolves
|
- `doctor.Report` collects the locations the program resolves
|
||||||
(`AddPaths(app)` adds the standard `core/paths` ones) and named checks;
|
(`AddPaths(app)` adds the standard `core/paths` ones) and named checks;
|
||||||
`Run(args, stdout, stderr)` prints a table or `--json` and returns the
|
`Run(args, stdout, stderr)` prints a table or `--json` and returns the
|
||||||
@@ -353,6 +356,10 @@ os.Exit(configcmd.Run(spec, configFlag, args, os.Stdout, os.Stderr))
|
|||||||
A program's tests call `configcmd.UndocumentedKeys(FullTemplate,
|
A program's tests call `configcmd.UndocumentedKeys(FullTemplate,
|
||||||
config.Config{})` and expect nothing, so every option stays documented
|
config.Config{})` and expect nothing, so every option stays documented
|
||||||
in the full template -- that is what keeps `config upgrade` useful.
|
in the full template -- that is what keeps `config upgrade` useful.
|
||||||
|
A struct whose fields are alternatives (a secret from `env`, `file` or
|
||||||
|
`value`) implements the marker `configcmd.OneOf` (`func (SecretRef)
|
||||||
|
ConfigOneOf() {}`): one alternative in the template documents it, and
|
||||||
|
`upgrade` offers none of the others to a file that already chose one.
|
||||||
`WarnUnknown` (log at startup) and `UnknownCheck` (a doctor check)
|
`WarnUnknown` (log at startup) and `UnknownCheck` (a doctor check)
|
||||||
report options the program ignores. Taken over from
|
report options the program ignores. Taken over from
|
||||||
`yamase-core/pkg/configcmd`, which now wraps it.
|
`yamase-core/pkg/configcmd`, which now wraps it.
|
||||||
|
|||||||
@@ -32,6 +32,10 @@ speculatively.
|
|||||||
- [x] `manual` (v0.2.0), `completion`, `doctor` (v0.3.0), `secretref`
|
- [x] `manual` (v0.2.0), `completion`, `doctor` (v0.3.0), `secretref`
|
||||||
(v0.4.0), `configcmd` and `version` (v0.5.0) -- see
|
(v0.4.0), `configcmd` and `version` (v0.5.0) -- see
|
||||||
docs/program-conventions.md in the meta-repository.
|
docs/program-conventions.md in the meta-repository.
|
||||||
|
- [x] `configcmd.OneOf`: `UndocumentedKeys` and `upgrade` know structs
|
||||||
|
whose fields are alternatives (SecretRef `env`/`file`/`value`);
|
||||||
|
`completion.Files` completes paths for programs without subcommands
|
||||||
|
(yamc) -- 2026-10-31.
|
||||||
- [x] macOS CLI/Service system-scope `RuntimeDir` is `/var/run/<app>`
|
- [x] macOS CLI/Service system-scope `RuntimeDir` is `/var/run/<app>`
|
||||||
(was `/run/<app>`, which macOS does not have) -- v0.5.0.
|
(was `/run/<app>`, which macOS does not have) -- v0.5.0.
|
||||||
- [x] `core/gui`: the native WebView host from
|
- [x] `core/gui`: the native WebView host from
|
||||||
|
|||||||
@@ -5,7 +5,12 @@
|
|||||||
//
|
//
|
||||||
// The scripts are deliberately simple, word-based completion of command
|
// The scripts are deliberately simple, word-based completion of command
|
||||||
// and subcommand names (not flag-aware): they join the words typed so far
|
// and subcommand names (not flag-aware): they join the words typed so far
|
||||||
// into a prefix and look up what may follow it.
|
// into a prefix and look up what may follow it. A level that also takes a
|
||||||
|
// file or directory path (a program without subcommands that is started
|
||||||
|
// as "<program> [path]") adds the Files key; the shell then completes
|
||||||
|
// paths there too:
|
||||||
|
//
|
||||||
|
// var tree = completion.Tree{completion.Files: nil, "manual": nil, ...}
|
||||||
//
|
//
|
||||||
// var tree = completion.Tree{
|
// var tree = completion.Tree{
|
||||||
// "serve": nil,
|
// "serve": nil,
|
||||||
@@ -41,6 +46,10 @@ func Leaf(names ...string) Tree {
|
|||||||
return t
|
return t
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// Files is a Tree key, not a command: the level it is in also completes
|
||||||
|
// file and directory paths. Its value is ignored.
|
||||||
|
const Files = "<files>"
|
||||||
|
|
||||||
// Shells are the supported shells, in the order help texts list them.
|
// Shells are the supported shells, in the order help texts list them.
|
||||||
var Shells = []string{"bash", "zsh", "fish", "powershell"}
|
var Shells = []string{"bash", "zsh", "fish", "powershell"}
|
||||||
|
|
||||||
@@ -53,6 +62,7 @@ var safeWord = regexp.MustCompile(`^[A-Za-z0-9][A-Za-z0-9._:+-]*$`)
|
|||||||
type entry struct {
|
type entry struct {
|
||||||
prefix string
|
prefix string
|
||||||
words []string
|
words []string
|
||||||
|
files bool // paths complete here too (Files)
|
||||||
}
|
}
|
||||||
|
|
||||||
func flatten(tree Tree) ([]entry, error) {
|
func flatten(tree Tree) ([]entry, error) {
|
||||||
@@ -60,14 +70,19 @@ func flatten(tree Tree) ([]entry, error) {
|
|||||||
var walk func(prefix string, t Tree) error
|
var walk func(prefix string, t Tree) error
|
||||||
walk = func(prefix string, t Tree) error {
|
walk = func(prefix string, t Tree) error {
|
||||||
names := make([]string, 0, len(t))
|
names := make([]string, 0, len(t))
|
||||||
|
files := false
|
||||||
for n := range t {
|
for n := range t {
|
||||||
|
if n == Files {
|
||||||
|
files = true
|
||||||
|
continue
|
||||||
|
}
|
||||||
if !safeWord.MatchString(n) {
|
if !safeWord.MatchString(n) {
|
||||||
return fmt.Errorf("completion: command name %q is not a plain word", n)
|
return fmt.Errorf("completion: command name %q is not a plain word", n)
|
||||||
}
|
}
|
||||||
names = append(names, n)
|
names = append(names, n)
|
||||||
}
|
}
|
||||||
sort.Strings(names)
|
sort.Strings(names)
|
||||||
out = append(out, entry{prefix, names})
|
out = append(out, entry{prefix, names, files})
|
||||||
for _, n := range names {
|
for _, n := range names {
|
||||||
if sub := t[n]; len(sub) > 0 {
|
if sub := t[n]; len(sub) > 0 {
|
||||||
p := n
|
p := n
|
||||||
@@ -84,6 +99,15 @@ func flatten(tree Tree) ([]entry, error) {
|
|||||||
return out, walk("", tree)
|
return out, walk("", tree)
|
||||||
}
|
}
|
||||||
|
|
||||||
|
func anyFiles(entries []entry) bool {
|
||||||
|
for _, e := range entries {
|
||||||
|
if e.files {
|
||||||
|
return true
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return false
|
||||||
|
}
|
||||||
|
|
||||||
// Script returns the completion script for shell.
|
// Script returns the completion script for shell.
|
||||||
func Script(program, shell string, tree Tree) (string, error) {
|
func Script(program, shell string, tree Tree) (string, error) {
|
||||||
if !safeWord.MatchString(program) {
|
if !safeWord.MatchString(program) {
|
||||||
@@ -100,16 +124,30 @@ func Script(program, shell string, tree Tree) (string, error) {
|
|||||||
fmt.Fprintf(&b, "# %s bash completion. Install with:\n# eval \"$(%s completion bash)\" (bash 3.2 on macOS cannot source <(...))\n", program, program)
|
fmt.Fprintf(&b, "# %s bash completion. Install with:\n# eval \"$(%s completion bash)\" (bash 3.2 on macOS cannot source <(...))\n", program, program)
|
||||||
fmt.Fprintf(&b, "%s() {\n local cur prefix\n cur=\"${COMP_WORDS[COMP_CWORD]}\"\n prefix=\"${COMP_WORDS[*]:1:COMP_CWORD-1}\"\n case \"$prefix\" in\n", fn)
|
fmt.Fprintf(&b, "%s() {\n local cur prefix\n cur=\"${COMP_WORDS[COMP_CWORD]}\"\n prefix=\"${COMP_WORDS[*]:1:COMP_CWORD-1}\"\n case \"$prefix\" in\n", fn)
|
||||||
for _, e := range entries {
|
for _, e := range entries {
|
||||||
fmt.Fprintf(&b, " %q) COMPREPLY=($(compgen -W %q -- \"$cur\")); return ;;\n", e.prefix, strings.Join(e.words, " "))
|
fmt.Fprintf(&b, " %q) COMPREPLY=($(compgen -W %q -- \"$cur\"))", e.prefix, strings.Join(e.words, " "))
|
||||||
|
if e.files {
|
||||||
|
// One path per line, so names with spaces stay whole;
|
||||||
|
// compopt (bash 4+) adds the trailing "/" and quoting.
|
||||||
|
b.WriteString("\n local IFS=$'\\n'; COMPREPLY+=($(compgen -f -- \"$cur\")); compopt -o filenames 2>/dev/null")
|
||||||
|
}
|
||||||
|
b.WriteString("; return ;;\n")
|
||||||
}
|
}
|
||||||
fmt.Fprintf(&b, " *) COMPREPLY=() ;;\n esac\n}\ncomplete -F %s %s\n", fn, program)
|
fmt.Fprintf(&b, " *) COMPREPLY=() ;;\n esac\n}\ncomplete -F %s %s\n", fn, program)
|
||||||
case "zsh":
|
case "zsh":
|
||||||
fmt.Fprintf(&b, "#compdef %s\n# %s zsh completion. Install with:\n# source <(%s completion zsh)\n", program, program, program)
|
fmt.Fprintf(&b, "#compdef %s\n# %s zsh completion. Install with:\n# source <(%s completion zsh)\n", program, program, program)
|
||||||
fmt.Fprintf(&b, "%s() {\n local prefix=\"${words[2,CURRENT-1]}\"\n local -a completions\n case \"$prefix\" in\n", fn)
|
fmt.Fprintf(&b, "%s() {\n local prefix=\"${words[2,CURRENT-1]}\" files=0\n local -a completions\n case \"$prefix\" in\n", fn)
|
||||||
for _, e := range entries {
|
for _, e := range entries {
|
||||||
fmt.Fprintf(&b, " %q) completions=(%s) ;;\n", e.prefix, strings.Join(e.words, " "))
|
f := ""
|
||||||
|
if e.files {
|
||||||
|
f = "; files=1"
|
||||||
|
}
|
||||||
|
fmt.Fprintf(&b, " %q) completions=(%s)%s ;;\n", e.prefix, strings.Join(e.words, " "), f)
|
||||||
}
|
}
|
||||||
fmt.Fprintf(&b, " *) completions=() ;;\n esac\n _describe 'command' completions\n}\n")
|
fmt.Fprintf(&b, " *) completions=() ;;\n esac\n _describe 'command' completions\n")
|
||||||
|
if anyFiles(entries) {
|
||||||
|
b.WriteString(" (( files )) && _files\n")
|
||||||
|
}
|
||||||
|
b.WriteString("}\n")
|
||||||
fmt.Fprintf(&b, "if (( $+functions[compdef] )); then\n compdef %s %s\nelse\n echo '%s: zsh completion needs \"autoload -U compinit && compinit\" run first (e.g. in ~/.zshrc)' >&2\nfi\n", fn, program, program)
|
fmt.Fprintf(&b, "if (( $+functions[compdef] )); then\n compdef %s %s\nelse\n echo '%s: zsh completion needs \"autoload -U compinit && compinit\" run first (e.g. in ~/.zshrc)' >&2\nfi\n", fn, program, program)
|
||||||
case "fish":
|
case "fish":
|
||||||
fmt.Fprintf(&b, "# %s fish completion. Install with:\n# %s completion fish | source\n", program, program)
|
fmt.Fprintf(&b, "# %s fish completion. Install with:\n# %s completion fish | source\n", program, program)
|
||||||
@@ -125,6 +163,9 @@ func Script(program, shell string, tree Tree) (string, error) {
|
|||||||
quoted[i] = fmt.Sprintf("%q", w)
|
quoted[i] = fmt.Sprintf("%q", w)
|
||||||
}
|
}
|
||||||
fmt.Fprintf(&b, " printf '%%s\\n' %s\n", strings.Join(quoted, " "))
|
fmt.Fprintf(&b, " printf '%%s\\n' %s\n", strings.Join(quoted, " "))
|
||||||
|
if e.files {
|
||||||
|
b.WriteString(" __fish_complete_path (commandline -ct)\n")
|
||||||
|
}
|
||||||
}
|
}
|
||||||
fmt.Fprintf(&b, " end\nend\ncomplete -c %s -f -a '(%s)'\n", program, fn)
|
fmt.Fprintf(&b, " end\nend\ncomplete -c %s -f -a '(%s)'\n", program, fn)
|
||||||
case "powershell":
|
case "powershell":
|
||||||
@@ -143,7 +184,18 @@ func Script(program, shell string, tree Tree) (string, error) {
|
|||||||
}
|
}
|
||||||
b.WriteString(" default { @() }\n }\n")
|
b.WriteString(" default { @() }\n }\n")
|
||||||
b.WriteString(" $candidates | Where-Object { $_ -like \"$wordToComplete*\" } | ForEach-Object {\n")
|
b.WriteString(" $candidates | Where-Object { $_ -like \"$wordToComplete*\" } | ForEach-Object {\n")
|
||||||
b.WriteString(" [System.Management.Automation.CompletionResult]::new($_, $_, 'ParameterValue', $_)\n }\n}\n")
|
b.WriteString(" [System.Management.Automation.CompletionResult]::new($_, $_, 'ParameterValue', $_)\n }\n")
|
||||||
|
var filePrefixes []string
|
||||||
|
for _, e := range entries {
|
||||||
|
if e.files {
|
||||||
|
filePrefixes = append(filePrefixes, "'"+e.prefix+"'")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if len(filePrefixes) > 0 {
|
||||||
|
fmt.Fprintf(&b, " if (@(%s) -contains $prefix) {\n", strings.Join(filePrefixes, ", "))
|
||||||
|
b.WriteString(" [System.Management.Automation.CompletionCompleters]::CompleteFilename($wordToComplete)\n }\n")
|
||||||
|
}
|
||||||
|
b.WriteString("}\n")
|
||||||
default:
|
default:
|
||||||
return "", fmt.Errorf("%w (unknown shell %q)", ErrUsage, shell)
|
return "", fmt.Errorf("%w (unknown shell %q)", ErrUsage, shell)
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -2,7 +2,10 @@ package completion
|
|||||||
|
|
||||||
import (
|
import (
|
||||||
"errors"
|
"errors"
|
||||||
|
"os"
|
||||||
"os/exec"
|
"os/exec"
|
||||||
|
"path/filepath"
|
||||||
|
"strconv"
|
||||||
"strings"
|
"strings"
|
||||||
"testing"
|
"testing"
|
||||||
)
|
)
|
||||||
@@ -48,3 +51,66 @@ func TestBashCompletes(t *testing.T) {
|
|||||||
t.Fatalf("bash completion: %v %q", err, out)
|
t.Fatalf("bash completion: %v %q", err, out)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// A program without subcommands takes a path as its first argument.
|
||||||
|
var pathTree = Tree{
|
||||||
|
Files: nil,
|
||||||
|
"manual": nil,
|
||||||
|
"config": Leaf("path"),
|
||||||
|
"completion": Leaf(Shells...),
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestScriptsWithFiles(t *testing.T) {
|
||||||
|
want := map[string]string{
|
||||||
|
"bash": "compgen -f",
|
||||||
|
"zsh": "_files",
|
||||||
|
"fish": "__fish_complete_path",
|
||||||
|
"powershell": "CompleteFilename",
|
||||||
|
}
|
||||||
|
for _, shell := range Shells {
|
||||||
|
s, err := Script("tool", shell, pathTree)
|
||||||
|
if err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
if !strings.Contains(s, want[shell]) {
|
||||||
|
t.Errorf("%s script lacks path completion %q", shell, want[shell])
|
||||||
|
}
|
||||||
|
if strings.Contains(s, Files) {
|
||||||
|
t.Errorf("%s script offers the marker %q as a word", shell, Files)
|
||||||
|
}
|
||||||
|
// Without the marker no level completes paths.
|
||||||
|
s, _ = Script("tool", shell, tree)
|
||||||
|
if strings.Contains(s, want[shell]) {
|
||||||
|
t.Errorf("%s script completes paths without Files", shell)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// TestBashCompletesPaths runs the generated bash function in a directory
|
||||||
|
// with a file whose name has a space, when bash is there.
|
||||||
|
func TestBashCompletesPaths(t *testing.T) {
|
||||||
|
if _, err := exec.LookPath("bash"); err != nil {
|
||||||
|
t.Skip("no bash")
|
||||||
|
}
|
||||||
|
dir := t.TempDir()
|
||||||
|
for _, name := range []string{"my notes.txt", "manuscript"} {
|
||||||
|
if err := os.WriteFile(filepath.Join(dir, name), nil, 0o600); err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
s, _ := Script("tool", "bash", pathTree)
|
||||||
|
for cword, want := range map[string]string{
|
||||||
|
"m": "manual|manuscript|my notes.txt", // command names and paths
|
||||||
|
"config p": "path", // a level without Files: no paths
|
||||||
|
} {
|
||||||
|
words := strings.Fields("tool " + cword)
|
||||||
|
script := s + "\nCOMP_WORDS=(" + strings.Join(words, " ") + "); COMP_CWORD=" +
|
||||||
|
strconv.Itoa(len(words)-1) + "; _tool_complete; printf '%s\\n' \"${COMPREPLY[@]}\" | sort | paste -sd '|' -"
|
||||||
|
cmd := exec.Command("bash", "-c", script)
|
||||||
|
cmd.Dir = dir
|
||||||
|
out, err := cmd.CombinedOutput()
|
||||||
|
if err != nil || strings.TrimSpace(string(out)) != want {
|
||||||
|
t.Errorf("bash completion of %q: %v %q, want %q", cword, err, out, want)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -427,3 +427,74 @@ func TestFilenameAndFind(t *testing.T) {
|
|||||||
t.Fatalf("Find: %v, %v", l.Path, err)
|
t.Fatalf("Find: %v, %v", l.Path, err)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
type secretRef struct {
|
||||||
|
Env string `yaml:"env,omitempty"`
|
||||||
|
File string `yaml:"file,omitempty"`
|
||||||
|
Value string `yaml:"value,omitempty"`
|
||||||
|
}
|
||||||
|
|
||||||
|
func (secretRef) ConfigOneOf() {}
|
||||||
|
|
||||||
|
type oneOfSchema struct {
|
||||||
|
Auth struct {
|
||||||
|
Type string `yaml:"type"`
|
||||||
|
Token secretRef `yaml:"token"`
|
||||||
|
Email *secretRef `yaml:"email"`
|
||||||
|
} `yaml:"auth"`
|
||||||
|
}
|
||||||
|
|
||||||
|
const oneOfTemplate = `auth:
|
||||||
|
type: bearer
|
||||||
|
# exactly one of env, file or value
|
||||||
|
token:
|
||||||
|
env: TOKEN
|
||||||
|
email:
|
||||||
|
file: /run/secrets/email
|
||||||
|
`
|
||||||
|
|
||||||
|
func TestUndocumentedKeysOneOf(t *testing.T) {
|
||||||
|
got, err := UndocumentedKeys(oneOfTemplate, oneOfSchema{})
|
||||||
|
if err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
if len(got) != 0 {
|
||||||
|
t.Errorf("UndocumentedKeys(one alternative set) = %v, want none", got)
|
||||||
|
}
|
||||||
|
// No alternative in the template: every one is undocumented.
|
||||||
|
got, _ = UndocumentedKeys("auth:\n type: bearer\n token: {}\n email:\n env: E\n", oneOfSchema{})
|
||||||
|
if want := "auth.token.env auth.token.file auth.token.value"; strings.Join(got, " ") != want {
|
||||||
|
t.Errorf("UndocumentedKeys(empty token) = %v, want %s", got, want)
|
||||||
|
}
|
||||||
|
// A struct without the marker still needs every field.
|
||||||
|
type plain struct {
|
||||||
|
Token struct {
|
||||||
|
Env string `yaml:"env"`
|
||||||
|
File string `yaml:"file"`
|
||||||
|
} `yaml:"token"`
|
||||||
|
}
|
||||||
|
got, _ = UndocumentedKeys("token:\n env: X\n", plain{})
|
||||||
|
if want := "token.file"; strings.Join(got, " ") != want {
|
||||||
|
t.Errorf("UndocumentedKeys(plain) = %v, want %s", got, want)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestMissingOneOfOffersNoOtherAlternative(t *testing.T) {
|
||||||
|
file := "auth:\n type: bearer\n token:\n file: /run/secrets/token\n email:\n value: me@example.org\n"
|
||||||
|
got, err := Missing([]byte(file), []byte(oneOfTemplate), oneOfSchema{})
|
||||||
|
if err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
if len(got) != 0 {
|
||||||
|
t.Errorf("Missing() = %v, want nothing (each secret has its alternative)", got)
|
||||||
|
}
|
||||||
|
// Without the schema the template's alternative is offered as before.
|
||||||
|
got, _ = Missing([]byte(file), []byte(oneOfTemplate), nil)
|
||||||
|
var keys []string
|
||||||
|
for _, a := range got {
|
||||||
|
keys = append(keys, a.Key)
|
||||||
|
}
|
||||||
|
if want := "auth.token.env auth.email.file"; strings.Join(keys, " ") != want {
|
||||||
|
t.Errorf("Missing(no schema) = %v, want %s", keys, want)
|
||||||
|
}
|
||||||
|
}
|
||||||
+36
-5
@@ -82,6 +82,9 @@ func docMapping(doc *yaml.Node) *yaml.Node {
|
|||||||
// of file).
|
// of file).
|
||||||
func compare(path []string, t reflect.Type, fmap, tmap *yaml.Node, childIndent, from, to, afterLine int, lines []string) []Addition {
|
func compare(path []string, t reflect.Type, fmap, tmap *yaml.Node, childIndent, from, to, afterLine int, lines []string) []Addition {
|
||||||
var out []Addition
|
var out []Addition
|
||||||
|
// A file that chose one alternative of a OneOf struct gets none of
|
||||||
|
// the template's others offered.
|
||||||
|
chosen := isOneOf(t) && len(fmap.Content) > 0
|
||||||
for i := 0; i+1 < len(tmap.Content); i += 2 {
|
for i := 0; i+1 < len(tmap.Content); i += 2 {
|
||||||
tkey, tval := tmap.Content[i], tmap.Content[i+1]
|
tkey, tval := tmap.Content[i], tmap.Content[i+1]
|
||||||
sub := append(append([]string(nil), path...), tkey.Value)
|
sub := append(append([]string(nil), path...), tkey.Value)
|
||||||
@@ -105,7 +108,7 @@ func compare(path []string, t reflect.Type, fmap, tmap *yaml.Node, childIndent,
|
|||||||
}
|
}
|
||||||
continue
|
continue
|
||||||
}
|
}
|
||||||
if mentioned(lines, from, to, childIndent, tkey.Value) {
|
if chosen || mentioned(lines, from, to, childIndent, tkey.Value) {
|
||||||
continue
|
continue
|
||||||
}
|
}
|
||||||
out = append(out, Addition{
|
out = append(out, Addition{
|
||||||
@@ -226,12 +229,36 @@ func Apply(raw []byte, adds []Addition) []byte {
|
|||||||
return []byte(out)
|
return []byte(out)
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// OneOf marks a configuration struct whose fields are alternatives, of
|
||||||
|
// which a file sets exactly one -- a secret taken from env, file or
|
||||||
|
// value, say. The method itself does nothing; implementing it is the
|
||||||
|
// marker:
|
||||||
|
//
|
||||||
|
// func (SecretRef) ConfigOneOf() {}
|
||||||
|
//
|
||||||
|
// UndocumentedKeys then accepts a template that sets one alternative
|
||||||
|
// (and explains the others in comments), and Missing offers none of the
|
||||||
|
// others to a file that already chose one.
|
||||||
|
type OneOf interface{ ConfigOneOf() }
|
||||||
|
|
||||||
|
var oneOfType = reflect.TypeOf((*OneOf)(nil)).Elem()
|
||||||
|
|
||||||
|
// isOneOf reports whether t (or a pointer to it) implements OneOf.
|
||||||
|
func isOneOf(t reflect.Type) bool {
|
||||||
|
if t == nil {
|
||||||
|
return false
|
||||||
|
}
|
||||||
|
t = deref(t)
|
||||||
|
return t.Implements(oneOfType) || reflect.PointerTo(t).Implements(oneOfType)
|
||||||
|
}
|
||||||
|
|
||||||
// UndocumentedKeys returns the dotted YAML paths of schema (a struct
|
// UndocumentedKeys returns the dotted YAML paths of schema (a struct
|
||||||
// value, e.g. config.Config{}) that the template does not contain --
|
// 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
|
// 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
|
// item. A struct implementing OneOf counts as documented when the
|
||||||
// option cannot be added without documenting it, which is what keeps
|
// template sets any one of its fields. A program's tests call it with
|
||||||
// "config upgrade" useful.
|
// 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) {
|
func UndocumentedKeys(template string, schema any) ([]string, error) {
|
||||||
var doc yaml.Node
|
var doc yaml.Node
|
||||||
if err := yaml.Unmarshal([]byte(template), &doc); err != nil {
|
if err := yaml.Unmarshal([]byte(template), &doc); err != nil {
|
||||||
@@ -251,6 +278,8 @@ func walkSchema(t reflect.Type, m *yaml.Node, path []string, out *[]string) {
|
|||||||
if t.Kind() != reflect.Struct {
|
if t.Kind() != reflect.Struct {
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
|
// One alternative set: the others are not missing.
|
||||||
|
chosen := isOneOf(t) && len(m.Content) > 0
|
||||||
for i := range t.NumField() {
|
for i := range t.NumField() {
|
||||||
f := t.Field(i)
|
f := t.Field(i)
|
||||||
name, opts, _ := strings.Cut(f.Tag.Get("yaml"), ",")
|
name, opts, _ := strings.Cut(f.Tag.Get("yaml"), ",")
|
||||||
@@ -268,7 +297,9 @@ func walkSchema(t reflect.Type, m *yaml.Node, path []string, out *[]string) {
|
|||||||
sub := append(append([]string(nil), path...), name)
|
sub := append(append([]string(nil), path...), name)
|
||||||
_, val := lookup(m, name)
|
_, val := lookup(m, name)
|
||||||
if val == nil {
|
if val == nil {
|
||||||
*out = append(*out, strings.Join(sub, "."))
|
if !chosen {
|
||||||
|
*out = append(*out, strings.Join(sub, "."))
|
||||||
|
}
|
||||||
continue
|
continue
|
||||||
}
|
}
|
||||||
ft := deref(f.Type)
|
ft := deref(f.Type)
|
||||||
|
|||||||
Reference in new issue
Block a user