Skip to content

Commit

Permalink
rpk: add LongFlagValue support for shorthand flags
Browse files Browse the repository at this point in the history
This flag is not used at the moment but it was
missing the shorthand parsing.
  • Loading branch information
r-vasquez committed Sep 6, 2024
1 parent ce624f0 commit 3c75192
Show file tree
Hide file tree
Showing 2 changed files with 27 additions and 16 deletions.
4 changes: 2 additions & 2 deletions src/go/rpk/pkg/cobraext/cobraext.go
Original file line number Diff line number Diff line change
Expand Up @@ -191,13 +191,13 @@ func StripFlags(args []string, fs *pflag.FlagSet, long []string, short []string)
// some flags in args. The flagset should be received from *inside* a cobra
// command, where persistent and non-persistent flags from all parents are
// merged. For repeated flags, only the last value is returned.
func LongFlagValue(args []string, fs *pflag.FlagSet, flag string) string {
func LongFlagValue(args []string, fs *pflag.FlagSet, flag, shorthand string) string {
nop := new(nopValue)
dup := pflag.NewFlagSet("dup", pflag.ContinueOnError)
dup.ParseErrorsWhitelist = pflag.ParseErrorsWhitelist{UnknownFlags: true}

var f string
dup.StringVar(&f, flag, "", "")
dup.StringVarP(&f, flag, shorthand, "", "")
added := dup.Lookup(flag)
fs.VisitAll(func(f *pflag.Flag) {
if f.Name != flag {
Expand Down
39 changes: 25 additions & 14 deletions src/go/rpk/pkg/cobraext/cobraext_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -137,34 +137,45 @@ func TestLongFlagValue(t *testing.T) {
fs.StringP("verbose", "v", "none", "Log level")
fs.Lookup("verbose").NoOptDefVal = "info"

args := []string{"--config", "foo", "--config-opt", "bar", "--config-opt=biz", "-v", "-v=debug", "subcmd", "-f", "foo", "finalarg", "finalarg2", "--unknown", "handled", "--unknown2=handled2"}
args := []string{"--config", "foo", "--config-opt", "bar", "--config-opt=biz", "-v", "-v=debug", "subcmd", "-f", "foo", "finalarg", "finalarg2", "--unknown", "handled", "--unknown2=handled2", "-h"}

for _, test := range []struct {
f string
exp string
flag string
shorthand string
exp string
}{
{
f: "config",
exp: "foo",
flag: "config",
exp: "foo",
},
{
f: "config-opt",
exp: "biz", // we take the last value
flag: "config-opt",
exp: "biz", // we take the last value
},
{
f: "noexist",
exp: "",
flag: "noexist",
exp: "",
},
{
f: "unknown",
exp: "handled",
flag: "unknown",
exp: "handled",
},
{
f: "unknown2",
exp: "handled2",
flag: "unknown2",
exp: "handled2",
},
{
flag: "verbose",
shorthand: "v",
exp: "debug",
},
{
flag: "help",
shorthand: "h",
exp: "true",
},
} {
got := LongFlagValue(args, fs, test.f)
got := LongFlagValue(args, fs, test.flag, test.shorthand)
if got != test.exp {
t.Errorf("got %v != exp %v", got, test.exp)
}
Expand Down

0 comments on commit 3c75192

Please sign in to comment.