pflag
pflag copied to clipboard
support traditional single-dash flags
I am facing the following issue: several commands in github.com/kubernetes-csi use the Go flag package for argument parsing. The single-dash flags are part of the API, so we can't just switch to pflag argument parsing without a major version bump.
At the same time we want to use support code from Kubernetes where flags are added to a pflag FlagSet.
What I am therefore looking for is:
- an option in pflag to emulate traditional Go argument parsing or
- a way to copy flags from a pflag FlagSet into a Go FlagSet
I tried copying. It almost works:
pflag.CommandLine.VisitAll(func(f *flag.Flag) {
goflag.CommandLine.Var(f.Value, f.Name, f.Usage)
})
goflag.Parse()
There's just one nuisance that makes this not a full solution: because https://cs.opensource.google/go/go/+/refs/tags/go1.17.1:src/flag/flag.go;l=467-504;drc=refs%2Ftags%2Fgo1.17.1 inspects the type of the values, all flags end up with "value". Before:
-nodeid string
After:
-nodeid value
This could be solved with a pflag.FlagSet.CopyToGoFlagSet
. Such a function can check the type of the values and if it finds pointers to its own string type, use the Go's fs.StringVar
method instead of fs.Var
to copy this particular flag.
I considered doing this via reflection, but I believe reflection cannot access unexported types and can't retrieve a *string
(only string
), so this wouldn't work.
I tried that idea and it works fine.