urfave-cli/app.go

73 lines
1.3 KiB
Go
Raw Normal View History

package cli
import (
"os"
"io/ioutil"
"fmt"
)
type App struct {
// The name of the program. Defaults to os.Args[0]
Name string
// Description of the program.
Usage string
// Version of the program
Version string
// List of commands to execute
Commands []Command
2013-07-20 22:50:13 +00:00
// List of flags to parse
Flags []Flag
// The action to execute when no subcommands are specified
2013-07-20 22:50:13 +00:00
Action func(context *Context)
}
func NewApp() *App {
return &App{
Name: os.Args[0],
Usage: "A new cli application",
Version: "0.0.0",
2013-07-19 22:23:42 +00:00
Action: helpCommand.Action,
}
}
func (a *App) Run(arguments []string) {
2013-07-20 15:44:09 +00:00
// append help to commands
a.Commands = append(a.Commands, helpCommand)
// append version to flags
2013-07-24 14:35:45 +00:00
a.Flags = append(
a.Flags,
BoolFlag{"version", "print the version"},
helpFlag{"show help"},
)
2013-07-20 15:44:09 +00:00
// parse flags
2013-07-20 15:21:20 +00:00
set := flagSet(a.Name, a.Flags)
set.SetOutput(ioutil.Discard)
2013-07-24 14:35:45 +00:00
err := set.Parse(arguments[1:])
context := NewContext(a, set, set)
2013-07-24 14:35:45 +00:00
if err != nil {
fmt.Println("Incorrect Usage.\n")
ShowAppHelp(context)
fmt.Println("")
2013-07-24 14:35:45 +00:00
os.Exit(1)
}
2013-07-24 14:35:45 +00:00
checkHelp(context)
checkVersion(context)
2013-07-20 15:44:09 +00:00
args := context.Args()
if len(args) > 0 {
name := args[0]
for _, c := range a.Commands {
if c.HasName(name) {
c.Run(context)
return
}
}
}
// Run default Action
a.Action(context)
}