2013-07-19 00:29:06 +00:00
|
|
|
package cli
|
|
|
|
|
2013-09-04 19:58:31 +00:00
|
|
|
import (
|
|
|
|
"fmt"
|
2013-09-18 16:24:20 +00:00
|
|
|
"io/ioutil"
|
2013-09-24 01:41:31 +00:00
|
|
|
"os"
|
2013-09-18 16:24:20 +00:00
|
|
|
"strings"
|
2013-09-04 19:58:31 +00:00
|
|
|
)
|
|
|
|
|
2013-07-19 00:29:06 +00:00
|
|
|
type Command struct {
|
2013-09-24 01:41:31 +00:00
|
|
|
Name string
|
|
|
|
ShortName string
|
|
|
|
Usage string
|
|
|
|
Description string
|
|
|
|
Action func(context *Context)
|
|
|
|
Flags []Flag
|
2013-07-19 00:29:06 +00:00
|
|
|
}
|
2013-07-19 02:23:00 +00:00
|
|
|
|
2013-07-20 15:21:20 +00:00
|
|
|
func (c Command) Run(ctx *Context) {
|
2013-08-14 04:40:39 +00:00
|
|
|
// append help to flags
|
|
|
|
c.Flags = append(
|
|
|
|
c.Flags,
|
|
|
|
helpFlag{"show help"},
|
|
|
|
)
|
|
|
|
|
2013-07-20 15:21:20 +00:00
|
|
|
set := flagSet(c.Name, c.Flags)
|
2013-09-04 19:58:31 +00:00
|
|
|
set.SetOutput(ioutil.Discard)
|
2013-09-18 16:24:20 +00:00
|
|
|
|
|
|
|
firstFlagIndex := -1
|
|
|
|
for index, arg := range ctx.Args() {
|
|
|
|
if strings.HasPrefix(arg, "-") {
|
|
|
|
firstFlagIndex = index
|
|
|
|
break
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
var err error
|
|
|
|
if firstFlagIndex > -1 {
|
|
|
|
args := ctx.Args()[1:firstFlagIndex]
|
|
|
|
flags := ctx.Args()[firstFlagIndex:]
|
|
|
|
err = set.Parse(append(flags, args...))
|
|
|
|
} else {
|
|
|
|
err = set.Parse(ctx.Args()[1:])
|
|
|
|
}
|
2013-09-04 19:58:31 +00:00
|
|
|
|
|
|
|
if err != nil {
|
|
|
|
fmt.Println("Incorrect Usage.\n")
|
|
|
|
ShowCommandHelp(ctx, c.Name)
|
|
|
|
fmt.Println("")
|
|
|
|
os.Exit(1)
|
|
|
|
}
|
2013-08-14 04:40:39 +00:00
|
|
|
|
|
|
|
context := NewContext(ctx.App, set, ctx.globalSet)
|
|
|
|
checkCommandHelp(context, c.Name)
|
|
|
|
c.Action(context)
|
2013-07-19 02:23:00 +00:00
|
|
|
}
|
2013-07-19 02:30:18 +00:00
|
|
|
|
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
|
|
|
}
|