From 165c69543bb37c64b6dca975cbfda8a4d5116ee1 Mon Sep 17 00:00:00 2001 From: Matt Bell Date: Sat, 8 Nov 2014 03:18:58 -0800 Subject: [PATCH] cmd/ipfs2: Output generated help text on error or help flag --- cmd/ipfs2/main.go | 58 ++++++++++++++++++++++++++++++++++++----------- 1 file changed, 45 insertions(+), 13 deletions(-) diff --git a/cmd/ipfs2/main.go b/cmd/ipfs2/main.go index f56094685..2660b5b49 100644 --- a/cmd/ipfs2/main.go +++ b/cmd/ipfs2/main.go @@ -41,22 +41,49 @@ func main() { } func createRequest(args []string) (cmds.Request, *cmds.Command) { - req, root, cmd, err := cmdsCli.Parse(args, Root, commands.Root) - if err != nil { - fmt.Println(err) - if cmd != nil { - if cmd.Help != "" { - fmt.Println(cmd.Help) - } - } else { - fmt.Println(Root.Help) + req, root, cmd, path, err := cmdsCli.Parse(args, Root, commands.Root) + + var options cmds.Request + if req != nil && root != nil { + var err2 error + options, err2 = getOptions(req, root) + if err2 != nil { + fmt.Println(err2) + os.Exit(1) } - os.Exit(1) } - options, err := getOptions(req, root) + // handle parse error (which means the commandline input was wrong, + // e.g. incorrect number of args, or nonexistent subcommand) if err != nil { - fmt.Println(err) + // if the -help flag wasn't specified, show the error message + if options != nil { + opt, _ := options.Option("help") + help, _ := opt.(bool) + if !help { + fmt.Println(err) + } + + } else if path != nil && len(path) > 0 { + // if a path was returned (user specified a valid subcommand), show the error message + // (this means there was an option or argument error) + fmt.Println(err) + } + + // when generating help for the root command, we don't want the autogenerated subcommand text + // (since we have better hand-made subcommand list in the root Help field) + if cmd == nil { + root = &*commands.Root + root.Subcommands = nil + } + + // generate the help text for the command the user was trying to call (or root) + helpText, err := cmdsCli.HelpText("ipfs", root, path) + if err != nil { + fmt.Println(err) + } else { + fmt.Println(helpText) + } os.Exit(1) } @@ -96,7 +123,12 @@ func handleOptions(req cmds.Request, root *cmds.Command) { if help, found := options.Option("help"); found { if helpBool, ok := help.(bool); helpBool && ok { - fmt.Println(req.Command().Help) + helpText, err := cmdsCli.HelpText("ipfs", root, req.Path()) + if err != nil { + fmt.Println(err.Error()) + } else { + fmt.Println(helpText) + } os.Exit(0) } else if !ok { fmt.Println("error: expected 'help' option to be a bool")