github.com/asifdxtreme/cli@v6.1.3-0.20150123051144-9ead8700b4ae+incompatible/testhelpers/commands/context.go (about) 1 package commands 2 3 import ( 4 "flag" 5 "fmt" 6 "strings" 7 "time" 8 9 "github.com/cloudfoundry/cli/cf/api" 10 "github.com/cloudfoundry/cli/cf/app" 11 "github.com/cloudfoundry/cli/cf/command_factory" 12 "github.com/cloudfoundry/cli/cf/command_runner" 13 testPluginConfig "github.com/cloudfoundry/cli/cf/configuration/plugin_config/fakes" 14 "github.com/cloudfoundry/cli/cf/manifest" 15 "github.com/cloudfoundry/cli/cf/net" 16 testconfig "github.com/cloudfoundry/cli/testhelpers/configuration" 17 testreq "github.com/cloudfoundry/cli/testhelpers/requirements" 18 testterm "github.com/cloudfoundry/cli/testhelpers/terminal" 19 "github.com/codegangsta/cli" 20 ) 21 22 func NewContext(cmdName string, args []string) *cli.Context { 23 targetCommand := findCommand(cmdName) 24 25 flagSet := new(flag.FlagSet) 26 for i, _ := range targetCommand.Flags { 27 targetCommand.Flags[i].Apply(flagSet) 28 } 29 30 // move all flag args to the beginning of the list, go requires them all upfront 31 if targetCommand.SkipFlagParsing == false { 32 firstFlagIndex := -1 33 for index, arg := range args { 34 if strings.HasPrefix(arg, "-") { 35 firstFlagIndex = index 36 break 37 } 38 } 39 if firstFlagIndex > 0 { 40 args := args[0:firstFlagIndex] 41 flags := args[firstFlagIndex:] 42 flagSet.Parse(append(flags, args...)) 43 } else { 44 flagSet.Parse(args[0:]) 45 } 46 } else { 47 flagSet.Parse(args[0:]) 48 } 49 50 return cli.NewContext(cli.NewApp(), flagSet, new(flag.FlagSet)) 51 } 52 53 func findCommand(cmdName string) (cmd cli.Command) { 54 fakeUI := &testterm.FakeUI{} 55 configRepo := testconfig.NewRepository() 56 pluginConfig := &testPluginConfig.FakePluginConfiguration{} 57 manifestRepo := manifest.NewManifestDiskRepository() 58 apiRepoLocator := api.NewRepositoryLocator(configRepo, map[string]net.Gateway{ 59 "auth": net.NewUAAGateway(configRepo, fakeUI), 60 "cloud-controller": net.NewCloudControllerGateway(configRepo, time.Now, fakeUI), 61 "uaa": net.NewUAAGateway(configRepo, fakeUI), 62 }) 63 64 cmdFactory := command_factory.NewFactory(fakeUI, configRepo, manifestRepo, apiRepoLocator, pluginConfig) 65 requirementsFactory := &testreq.FakeReqFactory{} 66 cmdRunner := command_runner.NewRunner(cmdFactory, requirementsFactory, fakeUI) 67 myApp := app.NewApp(cmdRunner, cmdFactory.CommandMetadatas()...) 68 69 for _, cmd := range myApp.Commands { 70 if cmd.Name == cmdName { 71 return cmd 72 } 73 } 74 panic(fmt.Sprintf("command %s does not exist", cmdName)) 75 return 76 }