From cb87159237140871657be69f75fef6e6db050ba0 Mon Sep 17 00:00:00 2001 From: Ryan Cavicchioni Date: Fri, 7 Aug 2020 22:11:33 -0500 Subject: [PATCH] add help command --- cmd/help.go | 60 +++++++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 60 insertions(+) create mode 100644 cmd/help.go diff --git a/cmd/help.go b/cmd/help.go new file mode 100644 index 0000000..bdf2cc9 --- /dev/null +++ b/cmd/help.go @@ -0,0 +1,60 @@ +package lumecmd + +import ( + "flag" + "fmt" +) + +func init() { + var cmdName string = "help" + fs := flag.NewFlagSet(cmdName, flag.ExitOnError) + + RegisterCommand(cmdName, Command{ + Func: HelpCmd, + Flags: fs, + Use: "", + Short: "Show help for a command", + }) +} + +func HelpCmd(args CmdArgs) (int, error) { + argv := args.Flags.Args() + + if len(argv) == 0 { + printHelp(commandRegistry) + } else if len(argv) >= 1 { + subCmd, ok := commandRegistry[argv[0]] + if !ok { + fmt.Printf("unknown command: %s\n", argv[0]) + return 1, nil + } + + if subCmd.Use != "" { + fmt.Printf("usage:\n lume %s %s\n", subCmd.Name, subCmd.Use) + fmt.Println() + } + + fmt.Print("flags:\n") + subCmd.Flags.PrintDefaults() + } + + return 0, nil +} + +func printHelp(commands map[string]Command) { + var maxLen, cmdLen int + for _, c := range commands { + cmdLen = len(c.Name) + if cmdLen > maxLen { + maxLen = cmdLen + } + } + + fmt.Printf("usage:\n lume []") + fmt.Println() + + fmt.Println("\ncommands:") + for _, c := range commands { + fmt.Printf(" %-*s %s\n", maxLen, c.Name, c.Short) + } +}