CLI argument parser code generator
package options
//go:generate go run github.com/gqgs/argsgen@latest
type options struct {
i, input string `arg:"input filename,positional"`
o, output string `arg:"output filename,positional"`
db, database string `arg:"database name"`
folder string `arg:"target folder,required"`
parallel uint `arg:"number of process in parallel"`
limit int `arg:"limit of something,required"`
real float64 `arg:"float of something"`
profile bool `arg:"should it profile?"`
}
👇
// Code generated by argsgen.
// DO NOT EDIT!
package options
import (
"errors"
"flag"
"fmt"
"os"
)
func (o *options) flagSet() *flag.FlagSet {
flagSet := flag.NewFlagSet(os.Args[0], flag.ExitOnError)
flagSet.StringVar(&o.i, "i", o.i, "input filename")
flagSet.StringVar(&o.i, "input", o.i, "input filename")
flagSet.StringVar(&o.o, "o", o.o, "output filename")
flagSet.StringVar(&o.o, "output", o.o, "output filename")
flagSet.StringVar(&o.db, "db", o.db, "database name")
flagSet.StringVar(&o.db, "database", o.db, "database name")
flagSet.StringVar(&o.folder, "folder", o.folder, "target folder")
flagSet.UintVar(&o.parallel, "parallel", o.parallel, "number of process in parallel")
flagSet.IntVar(&o.limit, "limit", o.limit, "limit of something")
flagSet.Float64Var(&o.real, "real", o.real, "float of something")
flagSet.BoolVar(&o.profile, "profile", o.profile, "should it profile?")
return flagSet
}
// Parse parses the arguments in os.Args
func (o *options) Parse() error {
flagSet := o.flagSet()
var positional []string
args := os.Args[1:]
for len(args) > 0 {
if err := flagSet.Parse(args); err != nil {
return err
}
if remaining := flagSet.NArg(); remaining > 0 {
posIndex := len(args) - remaining
positional = append(positional, args[posIndex])
args = args[posIndex+1:]
continue
}
break
}
o.database = o.db
o.input = o.i
o.output = o.o
if len(positional) == 0 {
if o.folder == "" {
return errors.New("argument 'folder' is required")
}
if o.limit == 0 {
return errors.New("argument 'limit' is required")
}
return nil
}
if len(positional) > 0 {
o.i = positional[0]
}
if len(positional) > 0 {
o.input = positional[0]
}
if len(positional) > 1 {
o.o = positional[1]
}
if len(positional) > 1 {
o.output = positional[1]
}
if o.folder == "" {
return errors.New("argument 'folder' is required")
}
if o.limit == 0 {
return errors.New("argument 'limit' is required")
}
return nil
}
// MustParse parses the arguments in os.Args or exists on error
func (o *options) MustParse() {
if err := o.Parse(); err != nil {
o.flagSet().PrintDefaults()
fmt.Fprintln(os.Stderr)
fmt.Fprintln(os.Stderr, err)
os.Exit(1)
}
}