forked from cloudfoundry/cli
-
Notifications
You must be signed in to change notification settings - Fork 0
/
context.go
55 lines (47 loc) · 1.21 KB
/
context.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
package commands
import (
"cf/app"
"cf/commands"
"flag"
"fmt"
"github.com/codegangsta/cli"
"strings"
testreq "testhelpers/requirements"
)
func NewContext(cmdName string, args []string) *cli.Context {
targetCommand := findCommand(cmdName)
flagSet := new(flag.FlagSet)
for i, _ := range targetCommand.Flags {
targetCommand.Flags[i].Apply(flagSet)
}
// move all flag args to the beginning of the list, go requires them all upfront
firstFlagIndex := -1
for index, arg := range args {
if strings.HasPrefix(arg, "-") {
firstFlagIndex = index
break
}
}
if firstFlagIndex > 0 {
args := args[0:firstFlagIndex]
flags := args[firstFlagIndex:]
flagSet.Parse(append(flags, args...))
} else {
flagSet.Parse(args[0:])
}
globalSet := new(flag.FlagSet)
return cli.NewContext(cli.NewApp(), flagSet, globalSet)
}
func findCommand(cmdName string) (cmd cli.Command) {
cmdFactory := commands.ConcreteFactory{}
requirementsFactory := &testreq.FakeReqFactory{}
cmdRunner := commands.NewRunner(cmdFactory, requirementsFactory)
myApp, _ := app.NewApp(cmdRunner)
for _, cmd := range myApp.Commands {
if cmd.Name == cmdName {
return cmd
}
}
panic(fmt.Sprintf("command %s does not exist", cmdName))
return
}