Skip to content

Commit

Permalink
fix: update enum+default vars after interpolation
Browse files Browse the repository at this point in the history
This doesn't recursively apply interpolation, as discussed in the issue,
but that's a much bigger change.

Fixes #337
  • Loading branch information
alecthomas committed Nov 3, 2024
1 parent 1b9d57e commit d0beaf7
Show file tree
Hide file tree
Showing 2 changed files with 18 additions and 5 deletions.
10 changes: 5 additions & 5 deletions kong.go
Original file line number Diff line number Diff line change
Expand Up @@ -249,19 +249,19 @@ func (k *Kong) interpolateValue(value *Value, vars Vars) (err error) {
return fmt.Errorf("enum for %s: %s", value.Summary(), err)
}

updatedVars := map[string]string{
"default": value.Default,
"enum": value.Enum,
}
if value.Default, err = interpolate(value.Default, vars, nil); err != nil {
return fmt.Errorf("default value for %s: %s", value.Summary(), err)
}
if value.Enum, err = interpolate(value.Enum, vars, nil); err != nil {
return fmt.Errorf("enum value for %s: %s", value.Summary(), err)
}
updatedVars := map[string]string{
"default": value.Default,
"enum": value.Enum,
}
if value.Flag != nil {
for i, env := range value.Flag.Envs {
if value.Flag.Envs[i], err = interpolate(env, vars, nil); err != nil {
if value.Flag.Envs[i], err = interpolate(env, vars, updatedVars); err != nil {
return fmt.Errorf("env value for %s: %s", value.Summary(), err)
}
}
Expand Down
13 changes: 13 additions & 0 deletions kong_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -2314,3 +2314,16 @@ func TestIntEnum(t *testing.T) {
_, err = k.Parse([]string{"--enum=123"})
assert.EqualError(t, err, `--enum must be one of "1","2","3" but got "123"`)
}

func TestRecursiveVariableExpansion(t *testing.T) {
var cli struct {
Config string `type:"path" default:"${config_file}" help:"Default: ${default}"`
}
k := mustNew(t, &cli, kong.Vars{"config_file": "/etc/config"}, kong.Exit(func(int) {}))
w := &strings.Builder{}
k.Stderr = w
k.Stdout = w
_, err := k.Parse([]string{"--help"})
assert.NoError(t, err)
assert.Contains(t, w.String(), "Default: /etc/config")
}

0 comments on commit d0beaf7

Please sign in to comment.