Allow for flags being passed in after arguments
This commit is contained in:
parent
e3ea5e29b0
commit
5d511c7a8b
22
app_test.go
22
app_test.go
@ -62,3 +62,25 @@ func TestApp_Command(t *testing.T) {
|
|||||||
expect(t, app.Command(test.name) != nil, test.expected)
|
expect(t, app.Command(test.name) != nil, test.expected)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
func TestApp_CommandWithArgBeforeFlags(t *testing.T) {
|
||||||
|
var parsedOption, firstArg string
|
||||||
|
|
||||||
|
app := cli.NewApp()
|
||||||
|
command := cli.Command{
|
||||||
|
Name: "cmd",
|
||||||
|
Flags: []cli.Flag{
|
||||||
|
cli.StringFlag{"option", "", "some option"},
|
||||||
|
},
|
||||||
|
Action: func(c *cli.Context) {
|
||||||
|
parsedOption = c.String("option")
|
||||||
|
firstArg = c.Args()[0]
|
||||||
|
},
|
||||||
|
}
|
||||||
|
app.Commands = []cli.Command{command}
|
||||||
|
|
||||||
|
app.Run([]string{"", "cmd", "my-arg", "--option", "my-option"})
|
||||||
|
|
||||||
|
expect(t, parsedOption, "my-option")
|
||||||
|
expect(t, firstArg, "my-arg")
|
||||||
|
}
|
||||||
|
21
command.go
21
command.go
@ -1,9 +1,10 @@
|
|||||||
package cli
|
package cli
|
||||||
|
|
||||||
import (
|
import (
|
||||||
"io/ioutil"
|
|
||||||
"os"
|
"os"
|
||||||
"fmt"
|
"fmt"
|
||||||
|
"io/ioutil"
|
||||||
|
"strings"
|
||||||
)
|
)
|
||||||
|
|
||||||
type Command struct {
|
type Command struct {
|
||||||
@ -24,7 +25,23 @@ func (c Command) Run(ctx *Context) {
|
|||||||
|
|
||||||
set := flagSet(c.Name, c.Flags)
|
set := flagSet(c.Name, c.Flags)
|
||||||
set.SetOutput(ioutil.Discard)
|
set.SetOutput(ioutil.Discard)
|
||||||
err := set.Parse(ctx.Args()[1:])
|
|
||||||
|
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:])
|
||||||
|
}
|
||||||
|
|
||||||
if err != nil {
|
if err != nil {
|
||||||
fmt.Println("Incorrect Usage.\n")
|
fmt.Println("Incorrect Usage.\n")
|
||||||
|
Loading…
Reference in New Issue
Block a user