Formatted help text via templates

This commit is contained in:
Jeremy Saenz 2013-07-14 17:37:43 -07:00
parent 6016cafda3
commit 5b788be8a6
2 changed files with 59 additions and 21 deletions

24
cli.go
View File

@ -6,7 +6,7 @@ import "os"
var Name = os.Args[0] var Name = os.Args[0]
// Description of the program. // Description of the program.
var Usage = "" var Usage = "<No Description>"
// Version of the program // Version of the program
var Version = "0.0.0" var Version = "0.0.0"
@ -17,19 +17,19 @@ var Commands []Command = nil
var DefaultAction = ShowHelp var DefaultAction = ShowHelp
func Run(args []string) { func Run(args []string) {
if len(args) > 1 { if len(args) > 1 {
command := args[1] command := args[1]
commands := CommandsWithDefaults() commands := CommandsWithDefaults()
for _, c := range commands { for _, c := range commands {
if c.Name == command { if c.Name == command {
c.Action(command) c.Action(command)
return return
} }
} }
} }
// Run default Action // Run default Action
DefaultAction("") DefaultAction("")
} }
func CommandsWithDefaults() []Command { func CommandsWithDefaults() []Command {

56
help.go
View File

@ -1,8 +1,17 @@
package cli package cli
import "fmt"
import "os" import "os"
import "log"
import "text/tabwriter" import "text/tabwriter"
import "text/template"
type HelpData struct {
Name string
Usage string
Commands []Command
Version string
}
var HelpCommand = Command{ var HelpCommand = Command{
Name: "help", Name: "help",
@ -11,14 +20,43 @@ var HelpCommand = Command{
Action: ShowHelp, Action: ShowHelp,
} }
var helpTemplate = `NAME:
{{.Name}} - {{.Usage}}
USAGE:
{{.Name}} [global-options] COMMAND [command-options]
VERSION:
{{.Version}}
COMMANDS:
{{range .Commands}}{{.Name}}{{ "\t" }}{{.Usage}}
{{end}}
`
var ShowHelp = func(name string) { var ShowHelp = func(name string) {
w := tabwriter.NewWriter(os.Stdout, 0, 8, 1, '\t', 0)
fmt.Printf("Usage: %v [global-options] COMMAND [command-options]\n\n", Name) data := HelpData{
if Commands != nil { Name,
fmt.Printf("The most commonly used %v commands are:\n", Name) Usage,
for _, c := range Commands { Commands,
fmt.Fprintln(w, " "+c.Name+"\t"+c.Usage) Version,
}
w.Flush()
} }
w := tabwriter.NewWriter(os.Stdout, 0, 8, 1, '\t', 0)
t := template.Must(template.New("help").Parse(helpTemplate))
err := t.Execute(w, data)
w.Flush()
if err != nil {
log.Println("executing template:", err)
}
// fmt.Printf("Usage: %v [global-options] COMMAND [command-options]\n\n", Name)
// if Commands != nil {
// fmt.Printf("The most commonly used %v commands are:\n", Name)
// for _, c := range Commands {
// fmt.Fprintln(w, " "+c.Name+"\t"+c.Usage)
// }
// w.Flush()
// }
} }