Skip to content

Commit a05d798

Browse files
committed
argparse: create basic argument parser
Add a basic argument parser for arbitrary series of string arguments. For now, it is little more than a wrapper of 'flag.FlagSet' (a builtin structure that handles parsing of flags preceded by a '-'). In future patches, the arg parser will be extended to handle subcommands and positional arguments to simplify 'git-bundle-server' command setup. Signed-off-by: Victoria Dye <[email protected]>
1 parent 0b0917d commit a05d798

File tree

1 file changed

+41
-0
lines changed

1 file changed

+41
-0
lines changed

internal/argparse/argparse.go

Lines changed: 41 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,41 @@
1+
package argparse
2+
3+
import (
4+
"flag"
5+
"fmt"
6+
"os"
7+
)
8+
9+
type argParser struct {
10+
flag.FlagSet
11+
}
12+
13+
func NewArgParser(usageString string) *argParser {
14+
flagSet := flag.NewFlagSet("", flag.ExitOnError)
15+
16+
a := &argParser{
17+
FlagSet: *flagSet,
18+
}
19+
20+
a.FlagSet.Usage = func() {
21+
out := a.FlagSet.Output()
22+
fmt.Fprintf(out, "usage: %s\n\n", usageString)
23+
}
24+
25+
return a
26+
}
27+
28+
func (a *argParser) Parse(args []string) {
29+
err := a.FlagSet.Parse(args)
30+
if err != nil {
31+
panic("argParser FlagSet error handling should be 'ExitOnError', but error encountered")
32+
}
33+
}
34+
35+
func (a *argParser) Usage(errFmt string, args ...any) {
36+
fmt.Fprintf(a.FlagSet.Output(), errFmt+"\n", args...)
37+
a.FlagSet.Usage()
38+
39+
// Exit with error code 2 to match flag.Parse() behavior
40+
os.Exit(2)
41+
}

0 commit comments

Comments
 (0)