Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

fix: reset flags' value to default if flags have been parsed #2080

Closed
wants to merge 2 commits into from
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
8 changes: 8 additions & 0 deletions command.go
Original file line number Diff line number Diff line change
Expand Up @@ -1830,6 +1830,14 @@ func (c *Command) ParseFlags(args []string) error {
// do it here after merging all flags and just before parse
c.Flags().ParseErrorsWhitelist = flag.ParseErrorsWhitelist(c.FParseErrWhitelist)

// if flag has been parsed, we should reset flags' value to default
if c.Flags().Parsed() {
c.Flags().Visit(func(f *flag.Flag) {
if err := f.Value.Set(f.DefValue); err != nil {
c.PrintErrf("reset argument[%s] value error %v", f.Name, err)
}
})
}
err := c.Flags().Parse(args)
// Print warnings if they occurred (e.g. deprecated flag messages).
if c.flagErrorBuf.Len()-beforeErrorBufLen > 0 && err == nil {
Expand Down
52 changes: 52 additions & 0 deletions flag_groups_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,7 @@
package cobra

import (
"fmt"
"strings"
"testing"
)
Expand Down Expand Up @@ -193,3 +194,54 @@ func TestValidateFlagGroups(t *testing.T) {
})
}
}

func TestSetArgs(t *testing.T) {
getCMD := func() *Command {
cmd := &Command{
Use: "testcmd",
RunE: func(cmd *Command, args []string) error {
a, _ := cmd.Flags().GetBool("a")
b, _ := cmd.Flags().GetBool("b")
c, _ := cmd.Flags().GetBool("c")
switch {
case a && b, a && c, b && c:
return fmt.Errorf("a,b,c only one could be true")
}
return nil
},
}
f := cmd.Flags()
f.BoolP("a", "a", false, "a,b,c only one could be true")
f.BoolP("b", "b", false, "a,b,c only one could be true")
f.Bool("c", false, "a,b,c only one could be true")
return cmd
}

cmd := getCMD()

// step 1
cmd.SetArgs([]string{
"--a=true",
})
assertNoErr(t, cmd.Execute())
// step 2
cmd.SetArgs([]string{
"--b=true",
})
t.Log(cmd.Flags().Changed("a"))
assertNoErr(t, cmd.Execute())

// step 3
cmd.SetArgs([]string{
"--c=true",
})
assertNoErr(t, cmd.Execute())

// step 4
cmd.SetArgs([]string{
"--a=false",
"--b=false",
"--c=true",
})
assertNoErr(t, cmd.Execute())
}