Skip to content

Commit 5aca46c

Browse files
authored
Merge pull request #2221 from malclocke/call-actions-on-env-flags-from-env
Call actions on flags set from env
2 parents 46345bb + 9e5f598 commit 5aca46c

File tree

2 files changed

+27
-0
lines changed

2 files changed

+27
-0
lines changed

command_run.go

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -207,9 +207,14 @@ func (cmd *Command) run(ctx context.Context, osArgs []string) (_ context.Context
207207
}
208208

209209
for _, flag := range cmd.allFlags() {
210+
isSet := flag.IsSet()
210211
if err := flag.PostParse(); err != nil {
211212
return ctx, err
212213
}
214+
// add env set flags here
215+
if !isSet && flag.IsSet() {
216+
cmd.setFlags[flag] = struct{}{}
217+
}
213218
}
214219

215220
if cmd.After != nil && !cmd.Root().shellCompletion {

flag_test.go

Lines changed: 22 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1727,6 +1727,28 @@ func TestParseGenericFromEnv(t *testing.T) {
17271727
assert.NoError(t, cmd.Run(buildTestContext(t), []string{"run"}))
17281728
}
17291729

1730+
func TestFlagActionFromEnv(t *testing.T) {
1731+
t.Setenv("X", "42")
1732+
x := 0
1733+
1734+
cmd := &Command{
1735+
Flags: []Flag{
1736+
&IntFlag{
1737+
Name: "x",
1738+
Sources: EnvVars("X"),
1739+
Action: func(ctx context.Context, cmd *Command, v int) error {
1740+
x = v
1741+
return nil
1742+
},
1743+
},
1744+
},
1745+
}
1746+
1747+
assert.NoError(t, cmd.Run(buildTestContext(t), []string{"run"}))
1748+
assert.Equal(t, cmd.Int("x"), 42)
1749+
assert.Equal(t, x, 42)
1750+
}
1751+
17301752
func TestParseMultiString(t *testing.T) {
17311753
_ = (&Command{
17321754
Flags: []Flag{

0 commit comments

Comments
 (0)