urfave-cli/app.go

117 lines
2.3 KiB
Go
Raw Normal View History

package cli
import (
"fmt"
"io/ioutil"
"os"
)
2013-11-01 14:31:37 +00:00
// App is the main structure of a cli application. It is recomended that
// and app be created with the cli.NewApp() function
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)
}
2013-11-01 14:31:37 +00:00
// 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",
2013-07-19 22:23:42 +00:00
Action: helpCommand.Action,
}
}
2013-11-01 14:31:37 +00:00
// Entry point to the cli app. Parses the arguments slice and routes to the proper flag/args combination
2013-11-01 13:23:19 +00:00
func (a *App) Run(arguments []string) error {
2013-07-20 15:44:09 +00:00
// append help to commands
if a.Command(helpCommand.Name) == nil {
a.Commands = append(a.Commands, helpCommand)
}
//append version/help flags
a.appendFlag(BoolFlag{"version", "print the version"})
a.appendFlag(BoolFlag{"help, h", "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:])
2013-11-20 08:05:18 +00:00
nerr := normalizeFlags(a.Flags, set)
if nerr != nil {
fmt.Println(nerr)
context := NewContext(a, set, set)
ShowAppHelp(context)
fmt.Println("")
return nerr
}
context := NewContext(a, set, set)
2013-07-24 14:35:45 +00:00
if err != nil {
fmt.Println("Incorrect Usage.\n")
2013-11-20 08:05:18 +00:00
fmt.Println("")
ShowAppHelp(context)
fmt.Println("")
2013-11-01 13:23:19 +00:00
return err
2013-07-24 14:35:45 +00:00
}
if checkHelp(context) {
return nil
}
if checkVersion(context) {
return nil
}
2013-07-20 15:44:09 +00:00
args := context.Args()
if len(args) > 0 {
name := args[0]
c := a.Command(name)
if c != nil {
return c.Run(context)
}
}
// Run default Action
a.Action(context)
2013-11-01 13:23:19 +00:00
return nil
}
2013-11-01 14:31:37 +00:00
// Returns the named command on App. Returns nil if the command does not exist
func (a *App) Command(name string) *Command {
for _, c := range a.Commands {
if c.HasName(name) {
return &c
}
}
return nil
}
func (a *App) hasFlag(flag Flag) bool {
for _, f := range a.Flags {
if flag == f {
return true
}
}
return false
}
func (a *App) appendFlag(flag Flag) {
if !a.hasFlag(flag) {
a.Flags = append(a.Flags, flag)
}
}