fix parser required missing error after check help fun
continuous-integration/drone/push Build is passing Details

This commit is contained in:
Jay 2020-02-13 02:52:14 +00:00
parent b893db5e14
commit ccfa5d3cb0
2 changed files with 22 additions and 13 deletions

View File

@ -99,7 +99,6 @@ func (p *Parser) Parse(a []string) error {
return nil return nil
} }
// in loop func
func (p *Parser) parse(args *[]string) error { func (p *Parser) parse(args *[]string) error {
if p.parsed { if p.parsed {
return nil return nil
@ -118,7 +117,17 @@ func (p *Parser) parse(args *[]string) error {
if p.showHelp == true { if p.showHelp == true {
p.printHelp() p.printHelp()
} }
return nil
return p.checkRequired()
}
func (p *Parser) checkRequired() (err error) {
for _, v := range p.args {
if v.opts != nil && v.opts.Require && !v.parsed {
return fmt.Errorf("[%s] is required", v.name())
}
}
return
} }
func (p *Parser) parseArguemtns(args *[]string) error { func (p *Parser) parseArguemtns(args *[]string) error {
@ -151,9 +160,9 @@ func (p *Parser) parseArguemtns(args *[]string) error {
continue continue
} }
} }
if oarg.opts != nil && oarg.opts.Require && !oarg.parsed { // if oarg.opts != nil && oarg.opts.Require && !oarg.parsed {
return fmt.Errorf("[%s] is required", oarg.name()) // return fmt.Errorf("[%s] is required", oarg.name())
} // }
} }

View File

@ -10,13 +10,13 @@ import (
func main() { func main() {
fmt.Println("argparse example") fmt.Println("argparse example")
opts := []string{ opts := []string{
"-f", "/config.yml", // "-f", "/config.yml",
"-v", // "-v",
"--port", "3000", // "--port", "3000",
"--float", "1.23", // "--float", "1.23",
"-n", "name!!", // "-n", "name!!",
"-i", "item1", // "-i", "item1",
"-i", "item2", // "-i", "item2",
"-h", "-h",
} }
@ -37,7 +37,7 @@ func main() {
p.FloatVar(&floatVal, "ff", "float", nil) p.FloatVar(&floatVal, "ff", "float", nil)
p.StringSliceVar(&sarr, "i", "item", nil) p.StringSliceVar(&sarr, "i", "item", nil)
// uncomment to test required arg missing // uncomment to test required arg missing
// p.IntVar(&missReq, "m", "miss", &argparse.Option{Require: true}) p.IntVar(&missReq, "m", "miss", &argparse.Option{Require: true})
p.Help("h", "help") p.Help("h", "help")
name = p.String("n", "name", nil) name = p.String("n", "name", nil)