Skip to content

Commit c22c05e

Browse files
committed
argparse: do not rely on os.Exit() inside FlagSet.Parse()
When the internal 'FlagSet.Parse()' of an 'argparser' encounters an invalid flag, the current 'ExitOnError' error handling causes it to invoke the 'os.Exit(2)' syscall and exit the program abruptly. In later patches, we're going to want to "catch" that exit status in our logs, so change the error handling to 'ContinueOnError' and explicitly call 'os.Exit(2)' in 'argparse.Parse()' if 'FlagSet.Parse()' returns an error. Signed-off-by: Victoria Dye <[email protected]>
1 parent 725df38 commit c22c05e

File tree

1 file changed

+8
-4
lines changed

1 file changed

+8
-4
lines changed

internal/argparse/argparse.go

Lines changed: 8 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -7,6 +7,9 @@ import (
77
"strings"
88
)
99

10+
// For consistency with 'flag', use 2 as the usage-related error code
11+
const usageExitCode int = 2
12+
1013
type positionalArg struct {
1114
name string
1215
description string
@@ -30,7 +33,7 @@ type argParser struct {
3033
}
3134

3235
func NewArgParser(usageString string) *argParser {
33-
flagSet := flag.NewFlagSet("", flag.ExitOnError)
36+
flagSet := flag.NewFlagSet("", flag.ContinueOnError)
3437

3538
a := &argParser{
3639
isTopLevel: false,
@@ -136,7 +139,9 @@ func (a *argParser) Parse(args []string) {
136139

137140
err := a.FlagSet.Parse(args)
138141
if err != nil {
139-
panic("argParser FlagSet error handling should be 'ExitOnError', but error encountered")
142+
// The error was already printed (via a.FlagSet.Usage()), so we
143+
// just need to exit
144+
os.Exit(usageExitCode)
140145
}
141146

142147
if len(a.subcommands) > 0 {
@@ -212,6 +217,5 @@ func (a *argParser) Usage(errFmt string, args ...any) {
212217
fmt.Fprintf(a.FlagSet.Output(), errFmt+"\n", args...)
213218
a.FlagSet.Usage()
214219

215-
// Exit with error code 2 to match flag.Parse() behavior
216-
os.Exit(2)
220+
os.Exit(usageExitCode)
217221
}

0 commit comments

Comments
 (0)