func parseArguments(args []string) (flags.FlagContext, error) { fc := flags.New() fc.NewStringFlag("organization", "o", "The organization to target for when listing apps") err := fc.Parse(args...) return fc, err }
func parseArguments(args []string) (flags.FlagContext, error) { fc := flags.New() fc.NewBoolFlag("started", "s", "Shows only apps that are started") fc.NewBoolFlag("stopped", "o", "Shows only apps that are stopped") err := fc.Parse(args...) return fc, err }
func BindService(cliConnection plugin.CliConnection, args []string) { customParameters := "{}" fc := flags.New() fc.NewStringFlag("parameters", "c", "Valid JSON object containing service-specific configuration parameters, provided either in-line or in a file. For a list of supported configuration parameters, see documentation for the particular service offering.") fc.Parse(args...) if fc.IsSet("c") { customParameters = fc.String("c") } appName := fc.Args()[1] serviceInstanceName := fc.Args()[2] rawOutput, _ := cliConnection.CliCommandWithoutTerminalOutput("curl", fmt.Sprintf("/v3/apps?names=%s", appName)) apps := V3AppsModel{} output := strings.Join(rawOutput, "") json.Unmarshal([]byte(output), &apps) if len(apps.Apps) == 0 { fmt.Printf("App %s not found\n", appName) return } appGuid := apps.Apps[0].Guid serviceInstance, err := cliConnection.GetService(serviceInstanceName) FreakOut(err) serviceInstanceGuid := serviceInstance.Guid body := fmt.Sprintf(`{ "type": "app", "relationships": { "app": {"guid" : "%s"}, "service_instance": {"guid": "%s"} }, "data": { "parameters": %s } }`, appGuid, serviceInstanceGuid, customParameters) if _, err := cliConnection.CliCommandWithoutTerminalOutput("curl", fmt.Sprintf("/v3/service_bindings"), "-X", "POST", "-d", body); err != nil { fmt.Printf("Failed to bind app %s to service instance %s\n", appName, serviceInstanceName) return } fmt.Println("OK") }
/* * This function must be implemented by any plugin because it is part of the * plugin interface defined by the core CLI. * * Run(....) is the entry point when the core CLI is invoking a command defined * by a plugin. The first parameter, plugin.CliConnection, is a struct that can * be used to invoke cli commands. The second paramter, args, is a slice of * strings. args[0] will be the name of the command, and will be followed by * any additional arguments a cli user typed in. * * Any error handling should be handled with the plugin itself (this means printing * user facing errors). The CLI will exit 0 if the plugin exits 0 and will exit * 1 should the plugin exits nonzero. */ func (c *FastPushPlugin) Run(cliConnection plugin.CliConnection, args []string) { // Ensure that the user called the command fast-push // alias fp is auto mapped var dryRun bool c.ui = terminal.NewUI(os.Stdin, terminal.NewTeePrinter()) cliLogged, err := cliConnection.IsLoggedIn() if err != nil { c.ui.Failed(err.Error()) } if cliLogged == false { panic("cannot perform fast-push without being logged in to CF") } if args[0] == "fast-push" || args[0] == "fp" { if len(args) == 1 { c.showUsage(args) return } // set flag for dry run fc := flags.New() fc.NewBoolFlag("dry", "d", "bool dry run flag") err := fc.Parse(args[1:]...) if err != nil { c.ui.Failed(err.Error()) } // check if the user asked for a dry run or not if fc.IsSet("dry") { dryRun = fc.Bool("dry") } else { c.ui.Warn("warning: dry run not set, commencing fast push") } c.ui.Say("Running the fast-push command") c.ui.Say("Target app: %s \n", args[1]) c.FastPush(cliConnection, args[1], dryRun) } else if args[0] == "fast-push-status" || args[0] == "fps" { c.FastPushStatus(cliConnection, args[1]) } else { return } }
func (c *NozzlerCmd) buildClientOptions(args []string) *firehose.ClientOptions { var debug bool var noFilter bool var filter string var subscriptionId string fc := flags.New() fc.NewBoolFlag("debug", "d", "used for debugging") fc.NewBoolFlag("no-filter", "n", "no firehose filter. Display all messages") fc.NewStringFlag("filter", "f", "specify message filter such as LogMessage, ValueMetric, CounterEvent, HttpStartStop") fc.NewStringFlag("subscription-id", "s", "specify subscription id for distributing firehose output between clients") err := fc.Parse(args[1:]...) if err != nil { c.ui.Failed(err.Error()) } if fc.IsSet("debug") { debug = fc.Bool("debug") } if fc.IsSet("no-filter") { noFilter = fc.Bool("no-filter") } if fc.IsSet("filter") { filter = fc.String("filter") } if fc.IsSet("subscription-id") { subscriptionId = fc.String("subscription-id") } return &firehose.ClientOptions{ Debug: debug, NoFilter: noFilter, Filter: filter, SubscriptionID: subscriptionId, } }
import ( "github.com/simonleung8/flags" . "github.com/onsi/ginkgo" . "github.com/onsi/gomega" "github.com/onsi/gomega/gbytes" ) var _ = Describe("Showing Flags Usage", func() { var ( fc flags.FlagContext ) BeforeEach(func() { fc = flags.New() fc.NewIntFlag("intFlag", "i", "Usage for intFlag") fc.NewIntFlag("m", "", "Usage for intFlag") fc.NewBoolFlag("boolFlag", "b", "Usage for boolFlag") fc.NewBoolFlag("f", "", "Usage for f") }) It("prints both the full and short flag name", func() { outputs := fc.ShowUsage(0) Ω(outputs).To(ContainSubstring("-intFlag, -i")) Ω(outputs).To(ContainSubstring("-f")) Ω(outputs).To(ContainSubstring("--boolFlag, -b")) }) It("prints full flag name with double dashes (--) if shortName exists", func() { outputs := fc.ShowUsage(1)
func Push(cliConnection plugin.CliConnection, args []string) { appDir := "." buildpack := "null" dockerImage := "" fc := flags.New() fc.NewStringFlag("filepath", "p", "path to app dir or zip to upload") fc.NewStringFlag("buildpack", "b", "the buildpack to use") fc.NewStringFlag("docker-image", "di", "the docker image to use") fc.Parse(args...) if fc.IsSet("p") { appDir = fc.String("p") } if fc.IsSet("b") { buildpack = fmt.Sprintf(`"%s"`, fc.String("b")) } if fc.IsSet("di") { dockerImage = fmt.Sprintf(`"%s"`, fc.String("di")) } mySpace, _ := cliConnection.GetCurrentSpace() lifecycle := "" if dockerImage != "" { lifecycle = `"lifecycle": { "type": "docker", "data": {} }` } else { lifecycle = fmt.Sprintf(`"lifecycle": { "type": "buildpack", "data": { "buildpack": %s } }`, buildpack) } //create the app rawOutput, err := cliConnection.CliCommandWithoutTerminalOutput("curl", "/v3/apps", "-X", "POST", "-d", fmt.Sprintf(`{"name":"%s", "relationships": { "space": {"guid":"%s"}}, %s}`, fc.Args()[1], mySpace.Guid, lifecycle)) FreakOut(err) output := strings.Join(rawOutput, "") app := V3AppModel{} err = json.Unmarshal([]byte(output), &app) FreakOut(err) if app.Error_Code != "" { FreakOut(errors.New("Error creating v3 app: " + app.Error_Code)) } time.Sleep(2 * time.Second) // wait for app to settle before kicking off the log streamer go Logs(cliConnection, args) time.Sleep(2 * time.Second) // b/c sharing the cliConnection makes things break //create package pack := V3PackageModel{} if dockerImage != "" { request := fmt.Sprintf(`{"type": "docker", "data": {"image": %s}}`, dockerImage) rawOutput, err = cliConnection.CliCommandWithoutTerminalOutput("curl", fmt.Sprintf("/v3/apps/%s/packages", app.Guid), "-X", "POST", "-d", request) FreakOut(err) output = strings.Join(rawOutput, "") err = json.Unmarshal([]byte(output), &pack) if err != nil { FreakOut(errors.New("Error creating v3 app package: " + app.Error_Code)) } } else { //create the empty package to upload the app bits to rawOutput, err = cliConnection.CliCommandWithoutTerminalOutput("curl", fmt.Sprintf("/v3/apps/%s/packages", app.Guid), "-X", "POST", "-d", "{\"type\": \"bits\"}") FreakOut(err) output = strings.Join(rawOutput, "") err = json.Unmarshal([]byte(output), &pack) if err != nil { FreakOut(errors.New("Error creating v3 app package: " + app.Error_Code)) } token, err := cliConnection.AccessToken() FreakOut(err) api, apiErr := cliConnection.ApiEndpoint() FreakOut(apiErr) apiString := fmt.Sprintf("%s", api) if strings.Index(apiString, "s") == 4 { apiString = apiString[:4] + apiString[5:] } //gather files zipper := appfiles.ApplicationZipper{} fileutils.TempFile("uploads", func(zipFile *os.File, err error) { zipper.Zip(appDir, zipFile) _, upload := exec.Command("curl", fmt.Sprintf("%s/v3/packages/%s/upload", apiString, pack.Guid), "-F", fmt.Sprintf("bits=@%s", zipFile.Name()), "-H", fmt.Sprintf("Authorization: %s", token), "-H", "Expect:").Output() FreakOut(upload) }) //waiting for cc to pour bits into blobstore Poll(cliConnection, fmt.Sprintf("/v3/packages/%s", pack.Guid), "READY", 5*time.Minute, "Package failed to upload") } rawOutput, err = cliConnection.CliCommandWithoutTerminalOutput("curl", fmt.Sprintf("/v3/packages/%s/droplets", pack.Guid), "-X", "POST", "-d", "{}") FreakOut(err) output = strings.Join(rawOutput, "") droplet := V3DropletModel{} err = json.Unmarshal([]byte(output), &droplet) if err != nil { FreakOut(errors.New("error marshaling the v3 droplet: " + err.Error())) } //wait for the droplet to be ready Poll(cliConnection, fmt.Sprintf("/v3/droplets/%s", droplet.Guid), "STAGED", 10*time.Minute, "Droplet failed to stage") //assign droplet to the app rawOutput, err = cliConnection.CliCommandWithoutTerminalOutput("curl", fmt.Sprintf("/v3/apps/%s/droplets/current", app.Guid), "-X", "PUT", "-d", fmt.Sprintf("{\"droplet_guid\":\"%s\"}", droplet.Guid)) FreakOut(err) output = strings.Join(rawOutput, "") //pick the first available shared domain, get the guid space, _ := cliConnection.GetCurrentSpace() nextUrl := "/v2/shared_domains" allDomains := DomainsModel{} for nextUrl != "" { rawOutput, err = cliConnection.CliCommandWithoutTerminalOutput("curl", nextUrl) FreakOut(err) output = strings.Join(rawOutput, "") tmp := DomainsModel{} err = json.Unmarshal([]byte(output), &tmp) FreakOut(err) allDomains.Resources = append(allDomains.Resources, tmp.Resources...) if tmp.NextUrl != "" { nextUrl = tmp.NextUrl } else { nextUrl = "" } } domainGuid := allDomains.Resources[0].Metadata.Guid rawOutput, err = cliConnection.CliCommandWithoutTerminalOutput("curl", "v2/routes", "-X", "POST", "-d", fmt.Sprintf(`{"host":"%s","domain_guid":"%s","space_guid":"%s"}`, fc.Args()[1], domainGuid, space.Guid)) output = strings.Join(rawOutput, "") var routeGuid string if strings.Contains(output, "CF-RouteHostTaken") { rawOutput, err = cliConnection.CliCommandWithoutTerminalOutput("curl", fmt.Sprintf("v2/routes?q=host:%s;domain_guid:%s", fc.Args()[1], domainGuid)) output = strings.Join(rawOutput, "") routes := RoutesModel{} err = json.Unmarshal([]byte(output), &routes) routeGuid = routes.Routes[0].Metadata.Guid } else { route := RouteModel{} err = json.Unmarshal([]byte(output), &route) if err != nil { FreakOut(errors.New("error unmarshaling the route: " + err.Error())) } routeGuid = route.Metadata.Guid } FreakOut(err) route := RouteModel{} err = json.Unmarshal([]byte(output), &route) if err != nil { FreakOut(errors.New("error unmarshaling the route: " + err.Error())) } //map the route to the app rawOutput, err = cliConnection.CliCommandWithoutTerminalOutput("curl", "/v3/route_mappings", "-X", "POST", "-d", fmt.Sprintf(`{"relationships": { "route": { "guid": "%s" }, "app": { "guid": "%s" } }`, routeGuid, app.Guid)) FreakOut(err) output = strings.Join(rawOutput, "") //start the app rawOutput, err = cliConnection.CliCommandWithoutTerminalOutput("curl", fmt.Sprintf("/v3/apps/%s/start", app.Guid), "-X", "PUT") FreakOut(err) output = strings.Join(rawOutput, "") fmt.Println("Done pushing! Checkout your processes using 'cf apps'") }