Added simple man page support

main
Alexander Rødseth 11 years ago
parent f93652a890
commit 7050f048d1

@ -4,6 +4,7 @@ import (
"fmt"
"io/ioutil"
"os"
"time"
)
// App is the main structure of a cli application. It is recomended that
@ -21,15 +22,34 @@ type App struct {
Flags []Flag
// The action to execute when no subcommands are specified
Action func(context *Context)
// Compilation date
Compiled time.Time
// Author
Author string
// Author e-mail
Email string
}
// Tries to find out when this binary was compiled.
// Returns the current time if it fails to find it.
func compileTime() time.Time {
info, err := os.Stat(os.Args[0])
if err != nil {
return time.Now()
}
return info.ModTime()
}
// Creates a new cli Application with some reasonable defaults for Name, Usage, Version and Action.
func NewApp() *App {
return &App{
Name: os.Args[0],
Usage: "A new cli application",
Version: "0.0.0",
Action: helpCommand.Action,
Name: os.Args[0],
Usage: "A new cli application",
Version: "0.0.0",
Action: helpCommand.Action,
Compiled: compileTime(),
Author: "Author",
Email: "unknown@email",
}
}

@ -44,6 +44,32 @@ OPTIONS:
{{end}}
`
var ManPageTemplate = `.\" -*-Nroff-*-
.\"
.TH "{{.Name}}" 1 "{{.Compiled.Day}} {{.Compiled.Month}} {{.Compiled.Year}}" "" ""
.SH NAME
{{.Name}} \- {{.Usage}}
.SH SYNOPSIS
.B {{.Name}}
.nf
command {{.Name}} [command options] [arguments...]
.fi
.SH COMMANDS
.nf
{{range .Commands}}{{.Name}}{{with .ShortName}}, {{.}}{{end}}{{ "\t" }}{{.Usage}}
{{end}}
.fi
.SH OPTIONS
.nf
{{range .Flags}}{{.}}
{{end}}
.fi
.SH VERSION
.B {{.Version}}
.SH AUTHOR
.B {{.Name}} was written by {{.Author}} <{{.Email}}>
`
var helpCommand = Command{
Name: "help",
ShortName: "h",
@ -63,6 +89,11 @@ func ShowAppHelp(c *Context) {
printHelp(AppHelpTemplate, c.App)
}
// Generates (prints) man page for the App
func GenerateManPage(c *Context) {
printHelp(ManPageTemplate, c.App)
}
// Prints help for the given command
func ShowCommandHelp(c *Context, command string) {
for _, c := range c.App.Commands {
@ -83,7 +114,10 @@ func ShowVersion(c *Context) {
func printHelp(templ string, data interface{}) {
w := tabwriter.NewWriter(os.Stdout, 0, 8, 1, '\t', 0)
t := template.Must(template.New("help").Parse(templ))
t.Execute(w, data)
err := t.Execute(w, data)
if err != nil {
panic(err)
}
w.Flush()
}

Loading…
Cancel
Save