Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
22 changes: 22 additions & 0 deletions app_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -62,3 +62,25 @@ func TestApp_Command(t *testing.T) {
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")
}
33 changes: 25 additions & 8 deletions command.go
Original file line number Diff line number Diff line change
@@ -1,18 +1,19 @@
package cli

import (
"io/ioutil"
"os"
"fmt"
"io/ioutil"
"strings"
)

type Command struct {
Name string
ShortName string
Usage string
Description string
Action func(context *Context)
Flags []Flag
Name string
ShortName string
Usage string
Description string
Action func (context *Context)
Flags []Flag
}

func (c Command) Run(ctx *Context) {
Expand All @@ -24,7 +25,23 @@ func (c Command) Run(ctx *Context) {

set := flagSet(c.Name, c.Flags)
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 {
fmt.Println("Incorrect Usage.\n")
Expand Down