gonn00b
gonn00b

Reputation: 11

Query about FlagSet usage

I am trying to build a CLI where I expect a group of three arguments to appear together.

command --alpha "value-a" --bravo "value-b" --charlie "value-c"

This is how I am attempting to do it:

import (
    "github.com/spf13/pflag"
)

var (
    alpha         string
    bravo         string
    charlie       string
)

abcFlagSet := pflag.NewFlagSet("alpha", pflag.ContinueOnError)
abcFlagSet.StringVar(&bravo, "bravo", "", "bravo-description")
abcFlagSet.StringVar(&charlie, "charlie", "", "charlie-description")
cmd.Flags().AddFlagSet(abcFlagSet)

This recognizes the bravo and charlie flags correctly. However, I think it treats the alpha as a sub command of command and does not parse the value assigned to it i.e., value-a. Is FlagSet a wrong usage for this use case? How should I parse this scenario where the three arguments can appear all together or none at all?

Upvotes: 0

Views: 753

Answers (1)

whitespace
whitespace

Reputation: 821

https://github.com/spf13/pflag/blob/298182f68c66c05229eb03ac171abe6e309ee79a/flag.go#L1202-L1213, as told here, you are forming a FlagSet with name alpha. Obviously your code does not consider that as a flag. The correct way to define a new flag with name alpha would be

abcFlagSet.StringVar(&alpha, "alpha", "", "alpha-description").

Upvotes: 1

Related Questions