urfave-cli/command.go

94 lines
2.1 KiB
Go
Raw Normal View History

package cli
import (
"fmt"
"io/ioutil"
"strings"
)
2013-11-01 14:31:37 +00:00
// Command is a subcommand for a cli.App.
type Command struct {
2013-11-01 14:31:37 +00:00
// The name of the command
Name string
// short name of the command. Typically one character
ShortName string
// A short description of the usage of this command
Usage string
// A longer explaination of how the command works
2013-09-24 01:41:31 +00:00
Description string
2014-04-10 17:14:13 +00:00
// The function to call when checking for bash command completions
BashComplete func(context *Context)
2013-11-01 14:31:37 +00:00
// The function to call when this command is invoked
Action func(context *Context)
// List of flags to parse
Flags []Flag
2014-04-14 21:44:32 +00:00
// Treat all flags as normal arguments if true
SkipFlagParsing bool
}
2013-07-19 02:23:00 +00:00
2013-11-01 14:31:37 +00:00
// Invokes the command given the context, parses ctx.Args() to generate command-specific flags
func (c Command) Run(ctx *Context) error {
2013-08-14 04:40:39 +00:00
// append help to flags
c.Flags = append(
c.Flags,
2013-11-21 01:25:13 +00:00
BoolFlag{"help, h", "show help"},
2013-08-14 04:40:39 +00:00
)
if ctx.App.EnableBashCompletion {
c.Flags = append(c.Flags, BashCompletionFlag)
}
2013-07-20 15:21:20 +00:00
set := flagSet(c.Name, c.Flags)
set.SetOutput(ioutil.Discard)
firstFlagIndex := -1
for index, arg := range ctx.Args() {
if strings.HasPrefix(arg, "-") {
firstFlagIndex = index
break
}
}
var err error
2014-04-14 21:44:32 +00:00
if firstFlagIndex > -1 && !c.SkipFlagParsing{
2013-11-24 13:40:21 +00:00
args := ctx.Args()
regularArgs := args[1:firstFlagIndex]
flagArgs := args[firstFlagIndex:]
err = set.Parse(append(flagArgs, regularArgs...))
} else {
2013-11-24 13:40:21 +00:00
err = set.Parse(ctx.Args().Tail())
}
if err != nil {
fmt.Printf("Incorrect Usage.\n\n")
ShowCommandHelp(ctx, c.Name)
fmt.Println("")
return err
}
2013-08-14 04:40:39 +00:00
2013-11-20 08:05:18 +00:00
nerr := normalizeFlags(c.Flags, set)
if nerr != nil {
fmt.Println(nerr)
fmt.Println("")
ShowCommandHelp(ctx, c.Name)
fmt.Println("")
return nerr
}
2013-08-14 04:40:39 +00:00
context := NewContext(ctx.App, set, ctx.globalSet)
2014-04-10 17:14:13 +00:00
if checkCommandCompletions(context, c.Name) {
return nil
}
if checkCommandHelp(context, c.Name) {
return nil
}
2013-08-14 04:40:39 +00:00
c.Action(context)
return nil
2013-07-19 02:23:00 +00:00
}
2013-07-19 02:30:18 +00:00
2013-11-01 14:31:37 +00:00
// Returns true if Command.Name or Command.ShortName matches given name
2013-07-20 15:21:20 +00:00
func (c Command) HasName(name string) bool {
return c.Name == name || c.ShortName == name
2013-07-19 02:30:18 +00:00
}