func (cmd *CreateRoute) Requirements(requirementsFactory requirements.Factory, fc flags.FlagContext) ([]requirements.Requirement, error) { if len(fc.Args()) != 2 { cmd.ui.Failed(T("Incorrect Usage. Requires SPACE and DOMAIN as arguments\n\n") + command_registry.Commands.CommandUsage("create-route")) } domainName := fc.Args()[1] cmd.spaceReq = requirementsFactory.NewSpaceRequirement(fc.Args()[0]) cmd.domainReq = requirementsFactory.NewDomainRequirement(domainName) reqs := []requirements.Requirement{ requirementsFactory.NewLoginRequirement(), requirementsFactory.NewTargetedOrgRequirement(), cmd.spaceReq, cmd.domainReq, } if fc.String("path") != "" { minRequiredAPIVersion, err := semver.Make("2.36.0") if err != nil { panic(err.Error()) } reqs = append(reqs, requirementsFactory.NewMinAPIVersionRequirement("create-route", minRequiredAPIVersion)) } return reqs, nil }
func (cmd *CreateUserProvidedService) Execute(c flags.FlagContext) { name := c.Args()[0] drainUrl := c.String("l") params := c.String("p") params = strings.Trim(params, `"`) paramsMap := make(map[string]interface{}) err := json.Unmarshal([]byte(params), ¶msMap) if err != nil && params != "" { paramsMap = cmd.mapValuesFromPrompt(params, paramsMap) } cmd.ui.Say(T("Creating user provided service {{.ServiceName}} in org {{.OrgName}} / space {{.SpaceName}} as {{.CurrentUser}}...", map[string]interface{}{ "ServiceName": terminal.EntityNameColor(name), "OrgName": terminal.EntityNameColor(cmd.config.OrganizationFields().Name), "SpaceName": terminal.EntityNameColor(cmd.config.SpaceFields().Name), "CurrentUser": terminal.EntityNameColor(cmd.config.Username()), })) apiErr := cmd.userProvidedServiceInstanceRepo.Create(name, drainUrl, paramsMap) if apiErr != nil { cmd.ui.Failed(apiErr.Error()) return } cmd.ui.Ok() }
func (cmd *CreateQuota) Execute(context flags.FlagContext) { name := context.Args()[0] cmd.ui.Say(T("Creating quota {{.QuotaName}} as {{.Username}}...", map[string]interface{}{ "QuotaName": terminal.EntityNameColor(name), "Username": terminal.EntityNameColor(cmd.config.Username()), })) quota := models.QuotaFields{ Name: name, } memoryLimit := context.String("m") if memoryLimit != "" { parsedMemory, err := formatters.ToMegabytes(memoryLimit) if err != nil { cmd.ui.Failed(T("Invalid memory limit: {{.MemoryLimit}}\n{{.Err}}", map[string]interface{}{"MemoryLimit": memoryLimit, "Err": err})) } quota.MemoryLimit = parsedMemory } instanceMemoryLimit := context.String("i") if instanceMemoryLimit == "-1" || instanceMemoryLimit == "" { quota.InstanceMemoryLimit = -1 } else { parsedMemory, errr := formatters.ToMegabytes(instanceMemoryLimit) if errr != nil { cmd.ui.Failed(T("Invalid instance memory limit: {{.MemoryLimit}}\n{{.Err}}", map[string]interface{}{"MemoryLimit": instanceMemoryLimit, "Err": errr})) } quota.InstanceMemoryLimit = parsedMemory } if context.IsSet("r") { quota.RoutesLimit = context.Int("r") } if context.IsSet("s") { quota.ServicesLimit = context.Int("s") } if context.IsSet("allow-paid-service-plans") { quota.NonBasicServicesAllowed = true } err := cmd.quotaRepo.Create(quota) httpErr, ok := err.(errors.HttpError) if ok && httpErr.ErrorCode() == errors.QUOTA_EXISTS { cmd.ui.Ok() cmd.ui.Warn(T("Quota Definition {{.QuotaName}} already exists", map[string]interface{}{"QuotaName": quota.Name})) return } if err != nil { cmd.ui.Failed(err.Error()) } cmd.ui.Ok() }
func (cmd *MapRoute) Execute(c flags.FlagContext) { hostName := c.String("n") domain := cmd.domainReq.GetDomain() app := cmd.appReq.GetApplication() route, apiErr := cmd.routeCreator.CreateRoute(hostName, domain, cmd.config.SpaceFields()) if apiErr != nil { cmd.ui.Failed(T("Error resolving route:\n{{.Err}}", map[string]interface{}{"Err": apiErr.Error()})) } cmd.ui.Say(T("Adding route {{.URL}} to app {{.AppName}} in org {{.OrgName}} / space {{.SpaceName}} as {{.Username}}...", map[string]interface{}{ "URL": terminal.EntityNameColor(route.URL()), "AppName": terminal.EntityNameColor(app.Name), "OrgName": terminal.EntityNameColor(cmd.config.OrganizationFields().Name), "SpaceName": terminal.EntityNameColor(cmd.config.SpaceFields().Name), "Username": terminal.EntityNameColor(cmd.config.Username())})) apiErr = cmd.routeRepo.Bind(route.Guid, app.Guid) if apiErr != nil { cmd.ui.Failed(apiErr.Error()) return } cmd.ui.Ok() }
func (cmd *UnmapRoute) Execute(c flags.FlagContext) { hostName := c.String("n") domain := cmd.domainReq.GetDomain() app := cmd.appReq.GetApplication() route, apiErr := cmd.routeRepo.FindByHostAndDomain(hostName, domain) if apiErr != nil { cmd.ui.Failed(apiErr.Error()) } cmd.ui.Say(T("Removing route {{.URL}} from app {{.AppName}} in org {{.OrgName}} / space {{.SpaceName}} as {{.Username}}...", map[string]interface{}{ "URL": terminal.EntityNameColor(route.URL()), "AppName": terminal.EntityNameColor(app.Name), "OrgName": terminal.EntityNameColor(cmd.config.OrganizationFields().Name), "SpaceName": terminal.EntityNameColor(cmd.config.SpaceFields().Name), "Username": terminal.EntityNameColor(cmd.config.Username())})) var routeFound bool for _, routeApp := range route.Apps { if routeApp.Guid == app.Guid { routeFound = true apiErr = cmd.routeRepo.Unbind(route.Guid, app.Guid) if apiErr != nil { cmd.ui.Failed(apiErr.Error()) return } } } cmd.ui.Ok() if !routeFound { cmd.ui.Warn(T("\nRoute to be unmapped is not currently mapped to the application.")) } }
func (cmd *CreateServiceKey) Execute(c flags.FlagContext) { serviceInstance := cmd.serviceInstanceRequirement.GetServiceInstance() serviceKeyName := c.Args()[1] params := c.String("c") paramsMap, err := json.ParseJsonFromFileOrString(params) if err != nil { cmd.ui.Failed(T("Invalid configuration provided for -c flag. Please provide a valid JSON object or path to a file containing a valid JSON object.")) } cmd.ui.Say(T("Creating service key {{.ServiceKeyName}} for service instance {{.ServiceInstanceName}} as {{.CurrentUser}}...", map[string]interface{}{ "ServiceInstanceName": terminal.EntityNameColor(serviceInstance.Name), "ServiceKeyName": terminal.EntityNameColor(serviceKeyName), "CurrentUser": terminal.EntityNameColor(cmd.config.Username()), })) err = cmd.serviceKeyRepo.CreateServiceKey(serviceInstance.Guid, serviceKeyName, paramsMap) switch err.(type) { case nil: cmd.ui.Ok() case *errors.ModelAlreadyExistsError: cmd.ui.Ok() cmd.ui.Warn(err.Error()) default: cmd.ui.Failed(err.Error()) } }
func (cmd *Target) Execute(c flags.FlagContext) { orgName := c.String("o") spaceName := c.String("s") if orgName != "" { err := cmd.setOrganization(orgName) if err != nil { cmd.ui.Failed(err.Error()) } else if spaceName == "" { spaceList, apiErr := cmd.getSpaceList() if apiErr == nil && len(spaceList) == 1 { cmd.setSpace(spaceList[0].Name) } } } if spaceName != "" { err := cmd.setSpace(spaceName) if err != nil { cmd.ui.Failed(err.Error()) } } cmd.ui.ShowConfiguration(cmd.config) if !cmd.config.IsLoggedIn() { cmd.ui.PanicQuietly() } cmd.ui.NotifyUpdateIfNeeded(cmd.config) return }
func (cmd *CreateOrg) Execute(c flags.FlagContext) { name := c.Args()[0] cmd.ui.Say(T("Creating org {{.OrgName}} as {{.Username}}...", map[string]interface{}{ "OrgName": terminal.EntityNameColor(name), "Username": terminal.EntityNameColor(cmd.config.Username())})) org := models.Organization{OrganizationFields: models.OrganizationFields{Name: name}} quotaName := c.String("q") if quotaName != "" { quota, err := cmd.quotaRepo.FindByName(quotaName) if err != nil { cmd.ui.Failed(err.Error()) } org.QuotaDefinition.Guid = quota.Guid } err := cmd.orgRepo.Create(org) if err != nil { if apiErr, ok := err.(errors.HttpError); ok && apiErr.ErrorCode() == errors.ORG_EXISTS { cmd.ui.Ok() cmd.ui.Warn(T("Org {{.OrgName}} already exists", map[string]interface{}{"OrgName": name})) return } else { cmd.ui.Failed(err.Error()) } } cmd.ui.Ok() cmd.ui.Say(T("\nTIP: Use '{{.Command}}' to target new org", map[string]interface{}{"Command": terminal.CommandColor(cf.Name() + " target -o " + name)})) }
func (cmd *RepoPlugins) Execute(c flags.FlagContext) { var repos []models.PluginRepo repoName := c.String("r") repos = cmd.config.PluginRepos() if repoName == "" { cmd.ui.Say(T("Getting plugins from all repositories ... ")) } else { index := cmd.findRepoIndex(repoName) if index != -1 { cmd.ui.Say(T("Getting plugins from repository '") + repoName + "' ...") repos = []models.PluginRepo{repos[index]} } else { cmd.ui.Failed(repoName + T(" does not exist as an available plugin repo."+"\nTip: use `add-plugin-repo` command to add repos.")) } } cmd.ui.Say("") repoPlugins, repoError := cmd.pluginRepo.GetPlugins(repos) cmd.printTable(repoPlugins) cmd.printErrors(repoError) }
func (cmd Login) authenticate(c flags.FlagContext) { usernameFlagValue := c.String("u") passwordFlagValue := c.String("p") prompts, err := cmd.authenticator.GetLoginPromptsAndSaveUAAServerURL() if err != nil { cmd.ui.Failed(err.Error()) } passwordKeys := []string{} credentials := make(map[string]string) if value, ok := prompts["username"]; ok { if prompts["username"].Type == core_config.AuthPromptTypeText && usernameFlagValue != "" { credentials["username"] = usernameFlagValue } else { credentials["username"] = cmd.ui.Ask("%s", value.DisplayName) } } for key, prompt := range prompts { if prompt.Type == core_config.AuthPromptTypePassword { if key == "passcode" { continue } passwordKeys = append(passwordKeys, key) } else if key == "username" { continue } else { credentials[key] = cmd.ui.Ask("%s", prompt.DisplayName) } } for i := 0; i < maxLoginTries; i++ { for _, key := range passwordKeys { if key == "password" && passwordFlagValue != "" { credentials[key] = passwordFlagValue passwordFlagValue = "" } else { credentials[key] = cmd.ui.AskForPassword("%s", prompts[key].DisplayName) } } cmd.ui.Say(T("Authenticating...")) err = cmd.authenticator.Authenticate(credentials) if err == nil { cmd.ui.Ok() cmd.ui.Say("") break } cmd.ui.Say(err.Error()) } if err != nil { cmd.ui.Failed(T("Unable to authenticate.")) } }
func (cmd *MarketplaceServices) Execute(c flags.FlagContext) { serviceName := c.String("s") if serviceName != "" { cmd.marketplaceByService(serviceName) } else { cmd.marketplace() } }
func (cmd *CreateRoute) Execute(c flags.FlagContext) { hostName := c.String("n") space := cmd.spaceReq.GetSpace() domain := cmd.domainReq.GetDomain() _, apiErr := cmd.CreateRoute(hostName, domain, space.SpaceFields) if apiErr != nil { cmd.ui.Failed(apiErr.Error()) return } }
func (cmd *CreateSpace) Requirements(requirementsFactory requirements.Factory, fc flags.FlagContext) (reqs []requirements.Requirement, err error) { if len(fc.Args()) != 1 { cmd.ui.Failed(T("Incorrect Usage. Requires an argument\n\n") + command_registry.Commands.CommandUsage("create-space")) } reqs = []requirements.Requirement{requirementsFactory.NewLoginRequirement()} if fc.String("o") == "" { reqs = append(reqs, requirementsFactory.NewTargetedOrgRequirement()) } return }
func (cmd *CreateService) Execute(c flags.FlagContext) { serviceName := c.Args()[0] planName := c.Args()[1] serviceInstanceName := c.Args()[2] params := c.String("c") tags := c.String("t") tagsList := ui_helpers.ParseTags(tags) paramsMap, err := json.ParseJsonFromFileOrString(params) if err != nil { cmd.ui.Failed(T("Invalid configuration provided for -c flag. Please provide a valid JSON object or path to a file containing a valid JSON object.")) } cmd.ui.Say(T("Creating service instance {{.ServiceName}} in org {{.OrgName}} / space {{.SpaceName}} as {{.CurrentUser}}...", map[string]interface{}{ "ServiceName": terminal.EntityNameColor(serviceInstanceName), "OrgName": terminal.EntityNameColor(cmd.config.OrganizationFields().Name), "SpaceName": terminal.EntityNameColor(cmd.config.SpaceFields().Name), "CurrentUser": terminal.EntityNameColor(cmd.config.Username()), })) plan, err := cmd.CreateService(serviceName, planName, serviceInstanceName, paramsMap, tagsList) switch err.(type) { case nil: err := printSuccessMessageForServiceInstance(serviceInstanceName, cmd.serviceRepo, cmd.ui) if err != nil { cmd.ui.Failed(err.Error()) } if !plan.Free { cmd.ui.Say("") cmd.ui.Say(T("Attention: The plan `{{.PlanName}}` of service `{{.ServiceName}}` is not free. The instance `{{.ServiceInstanceName}}` will incur a cost. Contact your administrator if you think this is in error.", map[string]interface{}{ "PlanName": terminal.EntityNameColor(plan.Name), "ServiceName": terminal.EntityNameColor(serviceName), "ServiceInstanceName": terminal.EntityNameColor(serviceInstanceName), })) cmd.ui.Say("") } case *errors.ModelAlreadyExistsError: cmd.ui.Ok() cmd.ui.Warn(err.Error()) default: cmd.ui.Failed(err.Error()) } }
func (cmd Login) decideEndpoint(c flags.FlagContext) (string, bool) { endpoint := c.String("a") skipSSL := c.Bool("skip-ssl-validation") if endpoint == "" { endpoint = cmd.config.ApiEndpoint() skipSSL = cmd.config.IsSSLDisabled() || skipSSL } if endpoint == "" { endpoint = cmd.ui.Ask(T("API endpoint")) } else { cmd.ui.Say(T("API endpoint: {{.Endpoint}}", map[string]interface{}{"Endpoint": terminal.EntityNameColor(endpoint)})) } return endpoint, skipSSL }
func (cmd *UpdateUserProvidedService) Execute(c flags.FlagContext) { serviceInstance := cmd.serviceInstanceReq.GetServiceInstance() if !serviceInstance.IsUserProvided() { cmd.ui.Failed(T("Service Instance is not user provided")) return } drainUrl := c.String("l") params := c.String("p") paramsMap := make(map[string]interface{}) if params != "" { err := json.Unmarshal([]byte(params), ¶msMap) if err != nil { cmd.ui.Failed(T("JSON is invalid: {{.ErrorDescription}}", map[string]interface{}{"ErrorDescription": err.Error()})) return } } cmd.ui.Say(T("Updating user provided service {{.ServiceName}} in org {{.OrgName}} / space {{.SpaceName}} as {{.CurrentUser}}...", map[string]interface{}{ "ServiceName": terminal.EntityNameColor(serviceInstance.Name), "OrgName": terminal.EntityNameColor(cmd.config.OrganizationFields().Name), "SpaceName": terminal.EntityNameColor(cmd.config.SpaceFields().Name), "CurrentUser": terminal.EntityNameColor(cmd.config.Username()), })) serviceInstance.Params = paramsMap serviceInstance.SysLogDrainUrl = drainUrl apiErr := cmd.userProvidedServiceInstanceRepo.Update(serviceInstance.ServiceInstanceFields) if apiErr != nil { cmd.ui.Failed(apiErr.Error()) return } cmd.ui.Ok() cmd.ui.Say(T("TIP: Use '{{.CFRestageCommand}}' for any bound apps to ensure your env variable changes take effect", map[string]interface{}{ "CFRestageCommand": terminal.CommandColor(cf.Name() + " restage"), })) if params == "" && drainUrl == "" { cmd.ui.Warn(T("No flags specified. No changes were made.")) } }
func (cmd *PluginInstall) Execute(c flags.FlagContext) { if !cmd.confirmWithUser( c, T("**Attention: Plugins are binaries written by potentially untrusted authors. Install and use plugins at your own risk.**\n\nDo you want to install the plugin {{.Plugin}}? (y or n)", map[string]interface{}{"Plugin": c.Args()[0]}), ) { cmd.ui.Failed(T("Plugin installation cancelled")) } fileDownloader := downloader.NewDownloader(os.TempDir()) removeTmpFile := func() { err := fileDownloader.RemoveFile() if err != nil { cmd.ui.Say(T("Problem removing downloaded binary in temp directory: ") + err.Error()) } } defer removeTmpFile() deps := &plugin_installer.PluginInstallerContext{ Checksummer: cmd.checksum, GetPluginRepos: cmd.config.PluginRepos, FileDownloader: fileDownloader, PluginRepo: cmd.pluginRepo, RepoName: c.String("r"), Ui: cmd.ui, } installer := plugin_installer.NewPluginInstaller(deps) pluginSourceFilepath := installer.Install(c.Args()[0]) cmd.ui.Say(fmt.Sprintf(T("Installing plugin {{.PluginPath}}...", map[string]interface{}{"PluginPath": pluginSourceFilepath}))) _, pluginExecutableName := filepath.Split(pluginSourceFilepath) pluginDestinationFilepath := filepath.Join(cmd.pluginConfig.GetPluginPath(), pluginExecutableName) cmd.ensurePluginBinaryWithSameFileNameDoesNotAlreadyExist(pluginDestinationFilepath, pluginExecutableName) pluginMetadata := cmd.runBinaryAndObtainPluginMetadata(pluginSourceFilepath) cmd.ensurePluginIsSafeForInstallation(pluginMetadata, pluginDestinationFilepath, pluginSourceFilepath) cmd.installPlugin(pluginMetadata, pluginDestinationFilepath, pluginSourceFilepath) cmd.ui.Ok() cmd.ui.Say(fmt.Sprintf(T("Plugin {{.PluginName}} v{{.Version}} successfully installed.", map[string]interface{}{"PluginName": pluginMetadata.Name, "Version": fmt.Sprintf("%d.%d.%d", pluginMetadata.Version.Major, pluginMetadata.Version.Minor, pluginMetadata.Version.Build)}))) }
func (cmd *CreateAppManifest) Execute(c flags.FlagContext) { app := cmd.appReq.GetApplication() application, apiErr := cmd.appSummaryRepo.GetSummary(app.Guid) if apiErr != nil { cmd.ui.Failed(T("Error getting application summary: ") + apiErr.Error()) } cmd.ui.Say(T("Creating an app manifest from current settings of app ") + application.Name + " ...") cmd.ui.Say("") savePath := "./" + application.Name + "_manifest.yml" if c.String("p") != "" { savePath = c.String("p") } cmd.createManifest(application, savePath) }
func (cmd *Push) Execute(c flags.FlagContext) { appSet := cmd.findAndValidateAppsToPush(c) _, apiErr := cmd.authRepo.RefreshAuthToken() if apiErr != nil { cmd.ui.Failed(apiErr.Error()) return } routeActor := actors.NewRouteActor(cmd.ui, cmd.routeRepo) for _, appParams := range appSet { cmd.fetchStackGuid(&appParams) if c.IsSet("docker-image") { diego := true appParams.Diego = &diego } app := cmd.createOrUpdateApp(appParams) cmd.updateRoutes(routeActor, app, appParams) if c.String("docker-image") == "" { cmd.ui.Say(T("Uploading {{.AppName}}...", map[string]interface{}{"AppName": terminal.EntityNameColor(app.Name)})) apiErr := cmd.uploadApp(app.Guid, *appParams.Path) if apiErr != nil { cmd.ui.Failed(fmt.Sprintf(T("Error uploading application.\n{{.ApiErr}}", map[string]interface{}{"ApiErr": apiErr.Error()}))) return } cmd.ui.Ok() } if appParams.ServicesToBind != nil { cmd.bindAppToServices(*appParams.ServicesToBind, app) } cmd.restart(app, appParams, c) } }
func (cmd *EnableServiceAccess) Execute(c flags.FlagContext) { _, err := cmd.tokenRefresher.RefreshAuthToken() if err != nil { cmd.ui.Failed(err.Error()) } serviceName := c.Args()[0] planName := c.String("p") orgName := c.String("o") if planName != "" && orgName != "" { cmd.enablePlanAndOrgForService(serviceName, planName, orgName) } else if planName != "" { cmd.enablePlanForService(serviceName, planName) } else if orgName != "" { cmd.enableAllPlansForSingleOrgForService(serviceName, orgName) } else { cmd.enableAllPlansForService(serviceName) } cmd.ui.Ok() }
func (cmd *Push) getAppParamsFromManifest(c flags.FlagContext) []models.AppParams { if c.Bool("no-manifest") { return []models.AppParams{} } var path string if c.String("f") != "" { path = c.String("f") } else { var err error path, err = os.Getwd() if err != nil { cmd.ui.Failed(T("Could not determine the current working directory!"), err) } } m, err := cmd.manifestRepo.ReadManifest(path) if err != nil { if m.Path == "" && c.String("f") == "" { return []models.AppParams{} } else { cmd.ui.Failed(T("Error reading manifest file:\n{{.Err}}", map[string]interface{}{"Err": err.Error()})) } } apps, err := m.Applications() if err != nil { cmd.ui.Failed("Error reading manifest file:\n%s", err) } cmd.ui.Say(T("Using manifest file {{.Path}}\n", map[string]interface{}{"Path": terminal.EntityNameColor(m.Path)})) return apps }
func (cmd Login) setOrganization(c flags.FlagContext) (isOrgSet bool) { orgName := c.String("o") if orgName == "" { availableOrgs := []models.Organization{} orgs, apiErr := cmd.orgRepo.ListOrgs() if apiErr != nil { cmd.ui.Failed(T("Error finding available orgs\n{{.ApiErr}}", map[string]interface{}{"ApiErr": apiErr.Error()})) } for _, org := range orgs { if len(availableOrgs) < maxChoices { availableOrgs = append(availableOrgs, org) } } if len(availableOrgs) == 0 { return false } else if len(availableOrgs) == 1 { cmd.targetOrganization(availableOrgs[0]) return true } else { orgName = cmd.promptForOrgName(availableOrgs) if orgName == "" { cmd.ui.Say("") return false } } } org, err := cmd.orgRepo.FindByName(orgName) if err != nil { cmd.ui.Failed(T("Error finding org {{.OrgName}}\n{{.Err}}", map[string]interface{}{"OrgName": terminal.EntityNameColor(orgName), "Err": err.Error()})) } cmd.targetOrganization(org) return true }
func (cmd *ConfigCommands) Execute(context flags.FlagContext) { if !context.IsSet("trace") && !context.IsSet("async-timeout") && !context.IsSet("color") && !context.IsSet("locale") { cmd.ui.Failed(T("Incorrect Usage\n\n") + command_registry.Commands.CommandUsage("config")) return } if context.IsSet("async-timeout") { asyncTimeout := context.Int("async-timeout") if asyncTimeout < 0 { cmd.ui.Failed(T("Incorrect Usage\n\n") + command_registry.Commands.CommandUsage("config")) } cmd.config.SetAsyncTimeout(uint(asyncTimeout)) } if context.IsSet("trace") { cmd.config.SetTrace(context.String("trace")) } if context.IsSet("color") { value := context.String("color") switch value { case "true": cmd.config.SetColorEnabled("true") case "false": cmd.config.SetColorEnabled("false") default: cmd.ui.Failed(T("Incorrect Usage\n\n") + command_registry.Commands.CommandUsage("config")) } } if context.IsSet("locale") { locale := context.String("locale") if locale == "CLEAR" { cmd.config.SetLocale("") return } foundLocale := false for _, value := range SUPPORTED_LOCALES { if value == locale { cmd.config.SetLocale(locale) foundLocale = true break } } if !foundLocale { cmd.ui.Say(fmt.Sprintf("Could not find locale %s. The known locales are:", locale)) cmd.ui.Say("") for _, locale := range SUPPORTED_LOCALES { cmd.ui.Say(locale) } } } }
func (cmd *BindService) Execute(c flags.FlagContext) { app := cmd.appReq.GetApplication() serviceInstance := cmd.serviceInstanceReq.GetServiceInstance() params := c.String("c") paramsMap, err := json.ParseJsonFromFileOrString(params) if err != nil { cmd.ui.Failed(T("Invalid configuration provided for -c flag. Please provide a valid JSON object or path to a file containing a valid JSON object.")) } cmd.ui.Say(T("Binding service {{.ServiceInstanceName}} to app {{.AppName}} in org {{.OrgName}} / space {{.SpaceName}} as {{.CurrentUser}}...", map[string]interface{}{ "ServiceInstanceName": terminal.EntityNameColor(serviceInstance.Name), "AppName": terminal.EntityNameColor(app.Name), "OrgName": terminal.EntityNameColor(cmd.config.OrganizationFields().Name), "SpaceName": terminal.EntityNameColor(cmd.config.SpaceFields().Name), "CurrentUser": terminal.EntityNameColor(cmd.config.Username()), })) err = cmd.BindApplication(app, serviceInstance, paramsMap) if err != nil { if httperr, ok := err.(errors.HttpError); ok && httperr.ErrorCode() == errors.APP_ALREADY_BOUND { cmd.ui.Ok() cmd.ui.Warn(T("App {{.AppName}} is already bound to {{.ServiceName}}.", map[string]interface{}{ "AppName": app.Name, "ServiceName": serviceInstance.Name, })) return } else { cmd.ui.Failed(err.Error()) } } cmd.ui.Ok() cmd.ui.Say(T("TIP: Use '{{.CFCommand}} {{.AppName}}' to ensure your env variable changes take effect", map[string]interface{}{"CFCommand": terminal.CommandColor(cf.Name() + " restage"), "AppName": app.Name})) }
func (cmd *DeleteRoute) Execute(c flags.FlagContext) { host := c.String("n") domainName := c.Args()[0] url := domainName if host != "" { url = host + "." + domainName } if !c.Bool("f") { if !cmd.ui.ConfirmDelete("route", url) { return } } cmd.ui.Say(T("Deleting route {{.URL}}...", map[string]interface{}{"URL": terminal.EntityNameColor(url)})) domain := cmd.domainReq.GetDomain() route, apiErr := cmd.routeRepo.FindByHostAndDomain(host, domain) switch apiErr.(type) { case nil: case *errors.ModelNotFoundError: cmd.ui.Warn(T("Unable to delete, route '{{.URL}}' does not exist.", map[string]interface{}{"URL": url})) return default: cmd.ui.Failed(apiErr.Error()) return } apiErr = cmd.routeRepo.Delete(route.Guid) if apiErr != nil { cmd.ui.Failed(apiErr.Error()) return } cmd.ui.Ok() }
func (cmd Login) setSpace(c flags.FlagContext) { spaceName := c.String("s") if spaceName == "" { var availableSpaces []models.Space err := cmd.spaceRepo.ListSpaces(func(space models.Space) bool { availableSpaces = append(availableSpaces, space) return (len(availableSpaces) < maxChoices) }) if err != nil { cmd.ui.Failed(T("Error finding available spaces\n{{.Err}}", map[string]interface{}{"Err": err.Error()})) } if len(availableSpaces) == 0 { return } else if len(availableSpaces) == 1 { cmd.targetSpace(availableSpaces[0]) return } else { spaceName = cmd.promptForSpaceName(availableSpaces) if spaceName == "" { cmd.ui.Say("") return } } } space, err := cmd.spaceRepo.FindByName(spaceName) if err != nil { cmd.ui.Failed(T("Error finding space {{.SpaceName}}\n{{.Err}}", map[string]interface{}{"SpaceName": terminal.EntityNameColor(spaceName), "Err": err.Error()})) } cmd.targetSpace(space) }
func (cmd *ServiceAccess) Execute(c flags.FlagContext) { _, err := cmd.tokenRefresher.RefreshAuthToken() if err != nil { cmd.ui.Failed(err.Error()) } brokerName := c.String("b") serviceName := c.String("e") orgName := c.String("o") if brokerName != "" && serviceName != "" && orgName != "" { cmd.ui.Say(T("Getting service access for broker {{.Broker}} and service {{.Service}} and organization {{.Organization}} as {{.Username}}...", map[string]interface{}{ "Broker": terminal.EntityNameColor(brokerName), "Service": terminal.EntityNameColor(serviceName), "Organization": terminal.EntityNameColor(orgName), "Username": terminal.EntityNameColor(cmd.config.Username())})) } else if serviceName != "" && orgName != "" { cmd.ui.Say(T("Getting service access for service {{.Service}} and organization {{.Organization}} as {{.Username}}...", map[string]interface{}{ "Service": terminal.EntityNameColor(serviceName), "Organization": terminal.EntityNameColor(orgName), "Username": terminal.EntityNameColor(cmd.config.Username())})) } else if brokerName != "" && orgName != "" { cmd.ui.Say(T("Getting service access for broker {{.Broker}} and organization {{.Organization}} as {{.Username}}...", map[string]interface{}{ "Broker": terminal.EntityNameColor(brokerName), "Organization": terminal.EntityNameColor(orgName), "Username": terminal.EntityNameColor(cmd.config.Username())})) } else if brokerName != "" && serviceName != "" { cmd.ui.Say(T("Getting service access for broker {{.Broker}} and service {{.Service}} as {{.Username}}...", map[string]interface{}{ "Broker": terminal.EntityNameColor(brokerName), "Service": terminal.EntityNameColor(serviceName), "Username": terminal.EntityNameColor(cmd.config.Username())})) } else if brokerName != "" { cmd.ui.Say(T("Getting service access for broker {{.Broker}} as {{.Username}}...", map[string]interface{}{ "Broker": terminal.EntityNameColor(brokerName), "Username": terminal.EntityNameColor(cmd.config.Username())})) } else if serviceName != "" { cmd.ui.Say(T("Getting service access for service {{.Service}} as {{.Username}}...", map[string]interface{}{ "Service": terminal.EntityNameColor(serviceName), "Username": terminal.EntityNameColor(cmd.config.Username())})) } else if orgName != "" { cmd.ui.Say(T("Getting service access for organization {{.Organization}} as {{.Username}}...", map[string]interface{}{ "Organization": terminal.EntityNameColor(orgName), "Username": terminal.EntityNameColor(cmd.config.Username())})) } else { cmd.ui.Say(T("Getting service access as {{.Username}}...", map[string]interface{}{ "Username": terminal.EntityNameColor(cmd.config.Username())})) } brokers, err := cmd.actor.FilterBrokers(brokerName, serviceName, orgName) if err != nil { cmd.ui.Failed(err.Error()) return } cmd.printTable(brokers) }
func (cmd *Curl) Execute(c flags.FlagContext) { path := c.Args()[0] method := c.String("X") headers := c.StringSlice("H") body := c.String("d") verbose := c.Bool("v") reqHeader := strings.Join(headers, "\n") if verbose { trace.EnableTrace() } responseHeader, responseBody, apiErr := cmd.curlRepo.Request(method, path, reqHeader, body) if apiErr != nil { cmd.ui.Failed(T("Error creating request:\n{{.Err}}", map[string]interface{}{"Err": apiErr.Error()})) } if verbose { return } if c.Bool("i") { cmd.ui.Say(responseHeader) } if c.String("output") != "" { err := cmd.writeToFile(responseBody, c.String("output")) if err != nil { cmd.ui.Failed(T("Error creating request:\n{{.Err}}", map[string]interface{}{"Err": err})) } } else { if strings.Contains(responseHeader, "application/json") { buffer := bytes.Buffer{} err := json.Indent(&buffer, []byte(responseBody), "", " ") if err == nil { responseBody = buffer.String() } } cmd.ui.Say(responseBody) } return }
func (cmd *ConfigCommands) Execute(context flags.FlagContext) { if !context.IsSet("trace") && !context.IsSet("async-timeout") && !context.IsSet("color") && !context.IsSet("locale") { cmd.ui.Failed(T("Incorrect Usage\n\n") + command_registry.Commands.CommandUsage("config")) return } if context.IsSet("async-timeout") { asyncTimeout := context.Int("async-timeout") if asyncTimeout < 0 { cmd.ui.Failed(T("Incorrect Usage\n\n") + command_registry.Commands.CommandUsage("config")) } cmd.config.SetAsyncTimeout(uint(asyncTimeout)) } if context.IsSet("trace") { cmd.config.SetTrace(context.String("trace")) } if context.IsSet("color") { value := context.String("color") switch value { case "true": cmd.config.SetColorEnabled("true") case "false": cmd.config.SetColorEnabled("false") default: cmd.ui.Failed(T("Incorrect Usage\n\n") + command_registry.Commands.CommandUsage("config")) } } if context.IsSet("locale") { locale := context.String("locale") if locale == "CLEAR" { cmd.config.SetLocale("") return } if IsSupportedLocale(locale) { cmd.config.SetLocale(locale) return } cmd.ui.Say(fmt.Sprintf("Could not find locale '%s'. The known locales are:", locale)) cmd.ui.Say("") supportedLocales := SupportedLocales() sort.Strings(supportedLocales) for i := range supportedLocales { cmd.ui.Say(supportedLocales[i]) } } }
func (cmd *UpdateService) Execute(c flags.FlagContext) { planName := c.String("p") params := c.String("c") tagsSet := c.IsSet("t") tagsList := c.String("t") if planName == "" && params == "" && tagsSet == false { cmd.ui.Ok() cmd.ui.Say(T("No changes were made")) return } serviceInstanceName := c.Args()[0] serviceInstance, err := cmd.serviceRepo.FindInstanceByName(serviceInstanceName) if err != nil { cmd.ui.Failed(err.Error()) } paramsMap, err := json.ParseJsonFromFileOrString(params) if err != nil { cmd.ui.Failed(T("Invalid configuration provided for -c flag. Please provide a valid JSON object or path to a file containing a valid JSON object.")) } tags := ui_helpers.ParseTags(tagsList) var plan models.ServicePlanFields if planName != "" { cmd.checkUpdateServicePlanApiVersion() plan, err = cmd.findPlan(serviceInstance, planName) if err != nil { cmd.ui.Failed(err.Error()) } } cmd.printUpdatingServiceInstanceMessage(serviceInstanceName) err = cmd.serviceRepo.UpdateServiceInstance(serviceInstance.Guid, plan.Guid, paramsMap, tags) if err != nil { cmd.ui.Failed(err.Error()) } err = printSuccessMessageForServiceInstance(serviceInstanceName, cmd.serviceRepo, cmd.ui) if err != nil { cmd.ui.Failed(err.Error()) } }