From ccfa5d3cb07728a837672b7210c562ea2bf71329 Mon Sep 17 00:00:00 2001 From: Jay Date: Thu, 13 Feb 2020 02:52:14 +0000 Subject: [PATCH] fix parser required missing error after check help fun --- argparse.go | 19 ++++++++++++++----- example/main.go | 16 ++++++++-------- 2 files changed, 22 insertions(+), 13 deletions(-) diff --git a/argparse.go b/argparse.go index 7877494..bb203b1 100644 --- a/argparse.go +++ b/argparse.go @@ -99,7 +99,6 @@ func (p *Parser) Parse(a []string) error { return nil } -// in loop func func (p *Parser) parse(args *[]string) error { if p.parsed { return nil @@ -118,7 +117,17 @@ func (p *Parser) parse(args *[]string) error { if p.showHelp == true { 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 { @@ -151,9 +160,9 @@ func (p *Parser) parseArguemtns(args *[]string) error { continue } } - if oarg.opts != nil && oarg.opts.Require && !oarg.parsed { - return fmt.Errorf("[%s] is required", oarg.name()) - } + // if oarg.opts != nil && oarg.opts.Require && !oarg.parsed { + // return fmt.Errorf("[%s] is required", oarg.name()) + // } } diff --git a/example/main.go b/example/main.go index 4f200f6..5ccbda4 100644 --- a/example/main.go +++ b/example/main.go @@ -10,13 +10,13 @@ import ( func main() { fmt.Println("argparse example") opts := []string{ - "-f", "/config.yml", - "-v", - "--port", "3000", - "--float", "1.23", - "-n", "name!!", - "-i", "item1", - "-i", "item2", + // "-f", "/config.yml", + // "-v", + // "--port", "3000", + // "--float", "1.23", + // "-n", "name!!", + // "-i", "item1", + // "-i", "item2", "-h", } @@ -37,7 +37,7 @@ func main() { p.FloatVar(&floatVal, "ff", "float", nil) p.StringSliceVar(&sarr, "i", "item", nil) // 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") name = p.String("n", "name", nil)