From df1af564443778a63ccdbe38a0a7ae4eb97d2df5 Mon Sep 17 00:00:00 2001 From: budougumi0617 Date: Mon, 12 Oct 2020 02:12:01 +0900 Subject: [PATCH] :recycle: change stream by args --- cmd/leetgode/main.go | 55 +++++++++++++++++++++++++++++--------------- 1 file changed, 36 insertions(+), 19 deletions(-) diff --git a/cmd/leetgode/main.go b/cmd/leetgode/main.go index 908fc56..5e298f6 100644 --- a/cmd/leetgode/main.go +++ b/cmd/leetgode/main.go @@ -4,6 +4,7 @@ import ( "context" "flag" "fmt" + "io" "io/ioutil" "log" "os" @@ -12,35 +13,51 @@ import ( ) func main() { - flag.Usage = func() { - if err := leetgode.ShowUsage(os.Stdout); err != nil { - panic(err) + os.Exit(run(os.Stdout, os.Stderr, os.Args)) +} + +func run(stdout, stderr io.Writer, args []string) int { + if len(args) < 2 { + cmd := &leetgode.HelpCmd{} + if err := cmd.Run(context.Background(), []string{}); err != nil { + fmt.Fprintf(stderr, "help comamnd is faield: %v", err) } + return 1 } - flag.Parse() - sub := flag.Arg(0) - if len(sub) == 0 { - cmd := &leetgode.HelpCmd{} - if err := cmd.Run(context.Background(), []string{}); err !=nil{ - fmt.Printf("help comamnd is faield: %v", err) + sub := args[1] + f := flag.NewFlagSet(sub, flag.ContinueOnError) + f.Usage = func() { + if err := leetgode.ShowUsage(stdout); err != nil { + fmt.Fprintf(stderr, "failed show useage: %v\n", err) } - return } - // TODO: set os.Stderr if set debug mode - log.SetOutput(ioutil.Discard) + var v bool + f.BoolVar(&v, "v", false, "show debug print") + if err := f.Parse(args[2:]); err == flag.ErrHelp { + return 1 + } else if err != nil { + fmt.Fprintf(stderr, "%s with invalid args: %v\n", sub, err) + return 1 + } + + log.SetOutput(stderr) + if !v { + log.SetOutput(ioutil.Discard) + } if cmd, ok := leetgode.CmdMap[leetgode.CmdName(sub)]; ok { - args := flag.Args()[1:] + args := f.Args() if len(args) != cmd.MaxArg() { - fmt.Printf("%s expects %d options, but %d options\n", cmd.Name(), cmd.MaxArg(), len(args)) - os.Exit(1) + fmt.Fprintf(stderr, "%s expects %d options, but %d options\n", cmd.Name(), cmd.MaxArg(), len(args)) + return 1 } if err := cmd.Run(context.Background(), args); err != nil { - log.Printf("main: err %v", err) - os.Exit(1) + fmt.Fprintf(stderr, "main: err %v", err) + return 1 } } else { - log.Printf("unknown command %q", sub) - os.Exit(1) + fmt.Fprintf(stderr, "unknown command %q", sub) + return 1 } + return 0 }