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

"unknown flag" message prints twice #352

Open
wimglenn opened this issue Jun 16, 2022 · 0 comments · May be fixed by #364
Open

"unknown flag" message prints twice #352

wimglenn opened this issue Jun 16, 2022 · 0 comments · May be fixed by #364

Comments

@wimglenn
Copy link

Reproducer:

package main

import "os"
import flag "github.com/spf13/pflag"

func main() {
	fs := flag.NewFlagSet("myprog", flag.ExitOnError)
	fs.Parse(os.Args[1:])
}

Example:

$ go run main.go --bogus
unknown flag: --bogus
Usage of myprog:
unknown flag: --bogus
exit status 2

Workaround: use flag.ContinueOnError instead of flag.ExitOnError, and then exit yourself after parse.

@vaguecoder vaguecoder linked a pull request Nov 19, 2022 that will close this issue
amterp added a commit to amterp/rad that referenced this issue Dec 21, 2024
We are currently doing this

  pflag.Usage = func() {
    r.RunUsageExit()
  }

That usage gets invoked if pflag fails to parse (e.g. due to an unknown
flag), but then rather than letting pflag exit with a non-0 error code,
the RunUsageExit() func exits with a 0 code, misleading callers into
thinking we had a successful script invocation.

That's a bug. We seem to be able to safely just remove the 'exit' part
to fix it and still have everything else working properly.

I took this opportunity to investigate the 'double unknown error' print
issue a bit. It's a bug in the pflag lib, I'm not the only one to have
found it: spf13/pflag#352

Unfortunately pflag is not maintained anymore (last release >5 years
ago), so very small chance this is ever getting fixed.

The only solution (bar forking pflag, but I don't think this is a
legitimate reason to) is to switch to using our own flagset so that we
can control the error handling to be ContinueOnError instead of
ExitOnError. This way, we can then avoid the double print and handle the
error ourselves. Anyway, that's a future ticket.
amterp added a commit to amterp/rad that referenced this issue Dec 28, 2024
We moved to using our own flagset in the previous commit, which lets us
then instantiate it with 'ContinueOnError', and catch the parsing error
ourselves and print it once, rather than being stuck with the pflag bug
that results in the error being double printed
(spf13/pflag#352).
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging a pull request may close this issue.

1 participant