func NewSSHOptions(fc flags.FlagContext) (*SSHOptions, error) { sshOptions := &SSHOptions{} sshOptions.AppName = fc.Args()[0] sshOptions.Index = uint(fc.Int("i")) sshOptions.SkipHostValidation = fc.Bool("k") sshOptions.SkipRemoteExecution = fc.Bool("N") sshOptions.Command = fc.StringSlice("c") if fc.IsSet("L") { for _, arg := range fc.StringSlice("L") { forwardSpec, err := sshOptions.parseLocalForwardingSpec(arg) if err != nil { return sshOptions, err } sshOptions.ForwardSpecs = append(sshOptions.ForwardSpecs, *forwardSpec) } } if fc.IsSet("t") && fc.Bool("t") { sshOptions.TerminalRequest = RequestTTYYes } if fc.IsSet("tt") && fc.Bool("tt") { sshOptions.TerminalRequest = RequestTTYForce } if fc.Bool("T") { sshOptions.TerminalRequest = RequestTTYNo } return sshOptions, nil }
func (cmd *MapRoute) Execute(c flags.FlagContext) error { hostName := c.String("n") path := c.String("path") domain := cmd.domainReq.GetDomain() app := cmd.appReq.GetApplication() port := c.Int("port") randomPort := c.Bool("random-port") route, err := cmd.routeCreator.CreateRoute(hostName, path, port, randomPort, domain, cmd.config.SpaceFields()) if err != nil { return errors.New(T("Error resolving route:\n{{.Err}}", map[string]interface{}{"Err": err.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())})) err = cmd.routeRepo.Bind(route.GUID, app.GUID) if err != nil { return err } cmd.ui.Ok() return nil }
func (cmd *SSH) Requirements(requirementsFactory requirements.Factory, fc flags.FlagContext) ([]requirements.Requirement, error) { if len(fc.Args()) != 1 { cmd.ui.Failed(T("Incorrect Usage. Requires APP_NAME as argument") + "\n\n" + commandregistry.Commands.CommandUsage("ssh")) return nil, fmt.Errorf("Incorrect usage: %d arguments of %d required", len(fc.Args()), 1) } if fc.IsSet("i") && fc.Int("i") < 0 { cmd.ui.Failed(fmt.Sprintf(T("Incorrect Usage:")+" %s\n\n%s", T("Value for flag 'app-instance-index' cannot be negative"), commandregistry.Commands.CommandUsage("ssh"))) return nil, fmt.Errorf("Incorrect usage: app-instance-index cannot be negative") } var err error cmd.opts, err = options.NewSSHOptions(fc) if err != nil { cmd.ui.Failed(fmt.Sprintf(T("Incorrect Usage:")+" %s\n\n%s", err.Error(), commandregistry.Commands.CommandUsage("ssh"))) return nil, err } cmd.appReq = requirementsFactory.NewApplicationRequirement(cmd.opts.AppName) reqs := []requirements.Requirement{ requirementsFactory.NewLoginRequirement(), requirementsFactory.NewTargetedSpaceRequirement(), cmd.appReq, } return reqs, nil }
func (cmd *ConfigCommands) Execute(context flags.FlagContext) error { if !context.IsSet("trace") && !context.IsSet("async-timeout") && !context.IsSet("color") && !context.IsSet("locale") { return errors.New(T("Incorrect Usage") + "\n\n" + commandregistry.Commands.CommandUsage("config")) } if context.IsSet("async-timeout") { asyncTimeout := context.Int("async-timeout") if asyncTimeout < 0 { return errors.New(T("Incorrect Usage") + "\n\n" + commandregistry.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: return errors.New(T("Incorrect Usage") + "\n\n" + commandregistry.Commands.CommandUsage("config")) } } if context.IsSet("locale") { locale := context.String("locale") if locale == "CLEAR" { cmd.config.SetLocale("") return nil } if IsSupportedLocale(locale) { cmd.config.SetLocale(locale) return nil } unsupportedLocaleMessage := T("Could not find locale '{{.UnsupportedLocale}}'. The known locales are:\n", map[string]interface{}{ "UnsupportedLocale": locale, }) supportedLocales := SupportedLocales() sort.Strings(supportedLocales) for i := range supportedLocales { unsupportedLocaleMessage = unsupportedLocaleMessage + "\n" + supportedLocales[i] } return errors.New(unsupportedLocaleMessage) } return nil }
func (cmd *CreateRoute) Execute(c flags.FlagContext) error { hostName := c.String("n") space := cmd.spaceReq.GetSpace() domain := cmd.domainReq.GetDomain() path := c.String("path") port := c.Int("port") randomPort := c.Bool("random-port") _, err := cmd.CreateRoute(hostName, path, port, randomPort, domain, space.SpaceFields) if err != nil { return err } return nil }
func (cmd *Files) Execute(c flags.FlagContext) error { app := cmd.appReq.GetApplication() var instance int if c.IsSet("i") { instance = c.Int("i") if instance < 0 { return errors.New(T("Invalid instance: {{.Instance}}\nInstance must be a positive integer", map[string]interface{}{ "Instance": instance, })) } if instance >= app.InstanceCount { return errors.New(T("Invalid instance: {{.Instance}}\nInstance must be less than {{.InstanceCount}}", map[string]interface{}{ "Instance": instance, "InstanceCount": app.InstanceCount, })) } } cmd.ui.Say(T("Getting files for app {{.AppName}} in org {{.OrgName}} / space {{.SpaceName}} as {{.Username}}...", map[string]interface{}{ "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())})) path := "/" if len(c.Args()) > 1 { path = c.Args()[1] } list, err := cmd.appFilesRepo.ListFiles(app.GUID, instance, path) if err != nil { return err } cmd.ui.Ok() cmd.ui.Say("") if list == "" { cmd.ui.Say("Empty file or folder") } else { cmd.ui.Say("%s", list) } return nil }
func (cmd *DeleteRoute) Execute(c flags.FlagContext) error { host := c.String("n") path := c.String("path") domainName := c.Args()[0] port := c.Int("port") url := (&models.RoutePresenter{ Host: host, Domain: domainName, Path: path, Port: port, }).URL() if !c.Bool("f") { if !cmd.ui.ConfirmDelete("route", url) { return nil } } cmd.ui.Say(T("Deleting route {{.URL}}...", map[string]interface{}{"URL": terminal.EntityNameColor(url)})) domain := cmd.domainReq.GetDomain() route, err := cmd.routeRepo.Find(host, domain, path, port) if err != nil { if _, ok := err.(*errors.ModelNotFoundError); ok { cmd.ui.Warn(T("Unable to delete, route '{{.URL}}' does not exist.", map[string]interface{}{"URL": url})) return nil } return err } err = cmd.routeRepo.Delete(route.GUID) if err != nil { return err } cmd.ui.Ok() return nil }
func (cmd *UnmapRoute) Execute(c flags.FlagContext) error { hostName := c.String("n") path := c.String("path") port := c.Int("port") domain := cmd.domainReq.GetDomain() app := cmd.appReq.GetApplication() route, err := cmd.routeRepo.Find(hostName, domain, path, port) if err != nil { return err } 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 err = cmd.routeRepo.Unbind(route.GUID, app.GUID) if err != nil { return err } break } } cmd.ui.Ok() if !routeFound { cmd.ui.Warn(T("\nRoute to be unmapped is not currently mapped to the application.")) } return nil }
Expect(fc.IsSet("force")).To(BeFalse()) fc.NewBoolFlag("force", "f", "force process") fc.Parse("--force") Expect(fc.IsSet("force")).To(BeTrue()) Expect(fc.IsSet("f")).To(BeTrue()) Expect(fc.Bool("force")).To(BeTrue()) Expect(fc.Bool("f")).To(BeTrue()) }) }) Describe("NewIntFlag()", func() { It("init the flag context with a new int flagset", func() { fc.Parse("-i", "5") Expect(fc.IsSet("i")).To(BeFalse()) Expect(fc.Int("i")).To(Equal(0)) fc.NewIntFlag("i", "i2", "setting new int flag") fc.Parse("-i", "5") Expect(fc.IsSet("i")).To(BeTrue()) Expect(fc.IsSet("i2")).To(BeTrue()) Expect(fc.Int("i")).To(Equal(5)) Expect(fc.Int("i2")).To(Equal(5)) }) }) Describe("NewIntFlagWithDefault()", func() { It("init the flag context with a new int flagset with default value", func() { fc.Parse("-i", "5") Expect(fc.IsSet("i")).To(BeFalse()) Expect(fc.Int("i")).To(Equal(0))
func (cmd *Scale) Execute(c flags.FlagContext) error { currentApp := cmd.appReq.GetApplication() if !anyFlagsSet(c) { cmd.ui.Say(T("Showing current scale of app {{.AppName}} in org {{.OrgName}} / space {{.SpaceName}} as {{.CurrentUser}}...", map[string]interface{}{ "AppName": terminal.EntityNameColor(currentApp.Name), "OrgName": terminal.EntityNameColor(cmd.config.OrganizationFields().Name), "SpaceName": terminal.EntityNameColor(cmd.config.SpaceFields().Name), "CurrentUser": terminal.EntityNameColor(cmd.config.Username()), })) cmd.ui.Ok() cmd.ui.Say("") cmd.ui.Say("%s %s", terminal.HeaderColor(T("memory:")), formatters.ByteSize(currentApp.Memory*bytesInAMegabyte)) cmd.ui.Say("%s %s", terminal.HeaderColor(T("disk:")), formatters.ByteSize(currentApp.DiskQuota*bytesInAMegabyte)) cmd.ui.Say("%s %d", terminal.HeaderColor(T("instances:")), currentApp.InstanceCount) return nil } params := models.AppParams{} shouldRestart := false if c.String("m") != "" { memory, err := formatters.ToMegabytes(c.String("m")) if err != nil { return errors.New(T("Invalid memory limit: {{.Memory}}\n{{.ErrorDescription}}", map[string]interface{}{ "Memory": c.String("m"), "ErrorDescription": err, })) } params.Memory = &memory shouldRestart = true } if c.String("k") != "" { diskQuota, err := formatters.ToMegabytes(c.String("k")) if err != nil { return errors.New(T("Invalid disk quota: {{.DiskQuota}}\n{{.ErrorDescription}}", map[string]interface{}{ "DiskQuota": c.String("k"), "ErrorDescription": err, })) } params.DiskQuota = &diskQuota shouldRestart = true } if c.IsSet("i") { instances := c.Int("i") params.InstanceCount = &instances } if shouldRestart && !cmd.confirmRestart(c, currentApp.Name) { return nil } cmd.ui.Say(T("Scaling app {{.AppName}} in org {{.OrgName}} / space {{.SpaceName}} as {{.CurrentUser}}...", map[string]interface{}{ "AppName": terminal.EntityNameColor(currentApp.Name), "OrgName": terminal.EntityNameColor(cmd.config.OrganizationFields().Name), "SpaceName": terminal.EntityNameColor(cmd.config.SpaceFields().Name), "CurrentUser": terminal.EntityNameColor(cmd.config.Username()), })) updatedApp, err := cmd.appRepo.Update(currentApp.GUID, params) if err != nil { return err } cmd.ui.Ok() if shouldRestart { err = cmd.restarter.ApplicationRestart(updatedApp, cmd.config.OrganizationFields().Name, cmd.config.SpaceFields().Name) if err != nil { return err } } return nil }
func (cmd *CreateSpaceQuota) Execute(context flags.FlagContext) error { name := context.Args()[0] org := cmd.config.OrganizationFields() cmd.ui.Say(T("Creating space quota {{.QuotaName}} for org {{.OrgName}} as {{.Username}}...", map[string]interface{}{ "QuotaName": terminal.EntityNameColor(name), "OrgName": terminal.EntityNameColor(org.Name), "Username": terminal.EntityNameColor(cmd.config.Username()), })) quota := models.SpaceQuota{ Name: name, OrgGUID: org.GUID, } memoryLimit := context.String("m") if memoryLimit != "" { parsedMemory, errr := formatters.ToMegabytes(memoryLimit) if errr != nil { return errors.New(T("Invalid memory limit: {{.MemoryLimit}}\n{{.Err}}", map[string]interface{}{"MemoryLimit": memoryLimit, "Err": errr})) } quota.MemoryLimit = parsedMemory } instanceMemoryLimit := context.String("i") var parsedMemory int64 var err error if instanceMemoryLimit == "-1" || instanceMemoryLimit == "" { parsedMemory = -1 } else { parsedMemory, err = formatters.ToMegabytes(instanceMemoryLimit) if err != nil { return errors.New(T("Invalid instance memory limit: {{.MemoryLimit}}\n{{.Err}}", map[string]interface{}{"MemoryLimit": instanceMemoryLimit, "Err": err})) } } 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 } if context.IsSet("a") { quota.AppInstanceLimit = context.Int("a") } else { quota.AppInstanceLimit = resources.UnlimitedAppInstances } if context.IsSet("reserved-route-ports") { quota.ReservedRoutePortsLimit = json.Number(strconv.Itoa(context.Int("reserved-route-ports"))) } err = cmd.quotaRepo.Create(quota) httpErr, ok := err.(errors.HTTPError) if ok && httpErr.ErrorCode() == errors.QuotaDefinitionNameTaken { cmd.ui.Ok() cmd.ui.Warn(T("Space Quota Definition {{.QuotaName}} already exists", map[string]interface{}{"QuotaName": quota.Name})) return nil } if err != nil { return err } cmd.ui.Ok() return nil }
Ω(fCtx.StringSlice("slice")[0]).To(Equal("value1"), "slice[0] should be 'value1'") Ω(fCtx.StringSlice("slice")[1]).To(Equal("value2"), "slice[1] should be 'value2'") }) It("errors when a non-boolean flag is provided without a value", func() { err := fCtx.Parse("-name") Expect(err).To(HaveOccurred()) Expect(err.Error()).To(ContainSubstring("No value provided for flag")) Expect(fCtx.String("name")).To(Equal("")) }) It("sets Int(<flag>) to return provided value when a int flag is provided", func() { err := fCtx.Parse("--instance", "10") Expect(err).NotTo(HaveOccurred()) Expect(fCtx.Int("instance")).To(Equal(10)) Expect(fCtx.IsSet("instance")).To(Equal(true)) Expect(fCtx.Int("non-exist-flag")).To(Equal(0)) Expect(fCtx.IsSet("non-exist-flag")).To(Equal(false)) }) It("sets Float64(<flag>) to return provided value when a float64 flag is provided", func() { err := fCtx.Parse("-float", "10.5") Expect(err).NotTo(HaveOccurred()) Expect(fCtx.Float64("float")).To(Equal(10.5)) Expect(fCtx.IsSet("float")).To(Equal(true)) Expect(fCtx.Float64("non-exist-flag")).To(Equal(float64(0))) Expect(fCtx.IsSet("non-exist-flag")).To(Equal(false))
func (cmd *UpdateSpaceQuota) Execute(c flags.FlagContext) error { name := c.Args()[0] spaceQuota, err := cmd.spaceQuotaRepo.FindByName(name) if err != nil { return err } allowPaidServices := c.Bool("allow-paid-service-plans") disallowPaidServices := c.Bool("disallow-paid-service-plans") if allowPaidServices && disallowPaidServices { return errors.New(T("Please choose either allow or disallow. Both flags are not permitted to be passed in the same command.")) } if allowPaidServices { spaceQuota.NonBasicServicesAllowed = true } if disallowPaidServices { spaceQuota.NonBasicServicesAllowed = false } if c.String("i") != "" { var memory int64 var formatError error memFlag := c.String("i") if memFlag == "-1" { memory = -1 } else { memory, formatError = formatters.ToMegabytes(memFlag) if formatError != nil { return errors.New(T("Incorrect Usage") + "\n\n" + commandregistry.Commands.CommandUsage("update-space-quota")) } } spaceQuota.InstanceMemoryLimit = memory } if c.String("m") != "" { memory, formatError := formatters.ToMegabytes(c.String("m")) if formatError != nil { return errors.New(T("Incorrect Usage") + "\n\n" + commandregistry.Commands.CommandUsage("update-space-quota")) } spaceQuota.MemoryLimit = memory } if c.String("n") != "" { spaceQuota.Name = c.String("n") } if c.IsSet("s") { spaceQuota.ServicesLimit = c.Int("s") } if c.IsSet("r") { spaceQuota.RoutesLimit = c.Int("r") } if c.IsSet("a") { spaceQuota.AppInstanceLimit = c.Int("a") } if c.IsSet("reserved-route-ports") { spaceQuota.ReservedRoutePortsLimit = json.Number(strconv.Itoa(c.Int("reserved-route-ports"))) } cmd.ui.Say(T("Updating space quota {{.Quota}} as {{.Username}}...", map[string]interface{}{ "Quota": terminal.EntityNameColor(name), "Username": terminal.EntityNameColor(cmd.config.Username()), })) err = cmd.spaceQuotaRepo.Update(spaceQuota) if err != nil { return err } cmd.ui.Ok() return nil }
func (cmd *Push) getAppParamsFromContext(c flags.FlagContext) (models.AppParams, error) { noHostBool := c.Bool("no-hostname") appParams := models.AppParams{ NoRoute: c.Bool("no-route"), UseRandomRoute: c.Bool("random-route"), NoHostname: &noHostBool, } if len(c.Args()) > 0 { appParams.Name = &c.Args()[0] } if c.String("n") != "" { appParams.Hosts = []string{c.String("n")} } if c.String("route-path") != "" { routePath := c.String("route-path") appParams.RoutePath = &routePath } if c.String("app-ports") != "" { appPortStrings := strings.Split(c.String("app-ports"), ",") appPorts := make([]int, len(appPortStrings)) for i, s := range appPortStrings { p, err := strconv.Atoi(s) if err != nil { return models.AppParams{}, errors.New(T("Invalid app port: {{.AppPort}}\nApp port must be a number", map[string]interface{}{ "AppPort": s, })) } appPorts[i] = p } appParams.AppPorts = &appPorts } if c.String("b") != "" { buildpack := c.String("b") if buildpack == "null" || buildpack == "default" { buildpack = "" } appParams.BuildpackURL = &buildpack } if c.String("c") != "" { command := c.String("c") if command == "null" || command == "default" { command = "" } appParams.Command = &command } if c.String("d") != "" { appParams.Domains = []string{c.String("d")} } if c.IsSet("i") { instances := c.Int("i") if instances < 1 { return models.AppParams{}, errors.New(T("Invalid instance count: {{.InstancesCount}}\nInstance count must be a positive integer", map[string]interface{}{"InstancesCount": instances})) } appParams.InstanceCount = &instances } if c.String("k") != "" { diskQuota, err := formatters.ToMegabytes(c.String("k")) if err != nil { return models.AppParams{}, errors.New(T("Invalid disk quota: {{.DiskQuota}}\n{{.Err}}", map[string]interface{}{"DiskQuota": c.String("k"), "Err": err.Error()})) } appParams.DiskQuota = &diskQuota } if c.String("m") != "" { memory, err := formatters.ToMegabytes(c.String("m")) if err != nil { return models.AppParams{}, errors.New(T("Invalid memory limit: {{.MemLimit}}\n{{.Err}}", map[string]interface{}{"MemLimit": c.String("m"), "Err": err.Error()})) } appParams.Memory = &memory } if c.String("docker-image") != "" { dockerImage := c.String("docker-image") appParams.DockerImage = &dockerImage } if c.String("p") != "" { path := c.String("p") appParams.Path = &path } if c.String("s") != "" { stackName := c.String("s") appParams.StackName = &stackName } if c.String("t") != "" { timeout, err := strconv.Atoi(c.String("t")) if err != nil { return models.AppParams{}, fmt.Errorf("Error: %s", fmt.Errorf(T("Invalid timeout param: {{.Timeout}}\n{{.Err}}", map[string]interface{}{"Timeout": c.String("t"), "Err": err.Error()}))) } appParams.HealthCheckTimeout = &timeout } if healthCheckType := c.String("u"); healthCheckType != "" { if healthCheckType != "port" && healthCheckType != "none" { return models.AppParams{}, fmt.Errorf("Error: %s", fmt.Errorf(T("Invalid health-check-type param: {{.healthCheckType}}", map[string]interface{}{"healthCheckType": healthCheckType}))) } appParams.HealthCheckType = &healthCheckType } return appParams, nil }
func (cmd *UpdateBuildpack) Execute(c flags.FlagContext) error { buildpack := cmd.buildpackReq.GetBuildpack() cmd.ui.Say(T("Updating buildpack {{.BuildpackName}}...", map[string]interface{}{"BuildpackName": terminal.EntityNameColor(buildpack.Name)})) updateBuildpack := false if c.IsSet("i") { position := c.Int("i") buildpack.Position = &position updateBuildpack = true } enabled := c.Bool("enable") disabled := c.Bool("disable") if enabled && disabled { return errors.New(T("Cannot specify both {{.Enabled}} and {{.Disabled}}.", map[string]interface{}{ "Enabled": "enabled", "Disabled": "disabled", })) } if enabled { buildpack.Enabled = &enabled updateBuildpack = true } if disabled { disabled = false buildpack.Enabled = &disabled updateBuildpack = true } lock := c.Bool("lock") unlock := c.Bool("unlock") if lock && unlock { return errors.New(T("Cannot specify both lock and unlock options.")) } path := c.String("p") if path != "" && (lock || unlock) { return errors.New(T("Cannot specify buildpack bits and lock/unlock.")) } if lock { buildpack.Locked = &lock updateBuildpack = true } if unlock { unlock = false buildpack.Locked = &unlock updateBuildpack = true } var ( buildpackFile *os.File buildpackFileName string err error ) if path != "" { buildpackFile, buildpackFileName, err = cmd.buildpackBitsRepo.CreateBuildpackZipFile(path) if err != nil { cmd.ui.Warn(T("Failed to create a local temporary zip file for the buildpack")) return err } } if updateBuildpack { newBuildpack, err := cmd.buildpackRepo.Update(buildpack) if err != nil { return errors.New(T("Error updating buildpack {{.Name}}\n{{.Error}}", map[string]interface{}{ "Name": terminal.EntityNameColor(buildpack.Name), "Error": err.Error(), })) } buildpack = newBuildpack } if path != "" { err := cmd.buildpackBitsRepo.UploadBuildpack(buildpack, buildpackFile, buildpackFileName) if err != nil { return errors.New(T("Error uploading buildpack {{.Name}}\n{{.Error}}", map[string]interface{}{ "Name": terminal.EntityNameColor(buildpack.Name), "Error": err.Error(), })) } } cmd.ui.Ok() return nil }