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")
	credentials := strings.Trim(c.String("p"), `'"`)
	routeServiceUrl := c.String("r")

	credentialsMap := make(map[string]interface{})

	if c.IsSet("p") {
		jsonBytes, err := util.GetContentsFromFlagValue(credentials)
		if err != nil && strings.HasPrefix(credentials, "@") {
			cmd.ui.Failed(err.Error())
		}

		if bytes.IndexAny(jsonBytes, "[{") != -1 {
			err = json.Unmarshal(jsonBytes, &credentialsMap)
			if err != nil {
				cmd.ui.Failed(T("JSON is invalid: {{.ErrorDescription}}", map[string]interface{}{"ErrorDescription": err.Error()}))
			}
		} else {
			for _, param := range strings.Split(credentials, ",") {
				param = strings.Trim(param, " ")
				credentialsMap[param] = cmd.ui.Ask("%s", param)
			}
		}
	}

	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 = credentialsMap
	serviceInstance.SysLogDrainUrl = drainUrl
	serviceInstance.RouteServiceUrl = routeServiceUrl

	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 routeServiceUrl == "" && credentials == "" && drainUrl == "" {
		cmd.ui.Warn(T("No flags specified. No changes were made."))
	}
}
Example #2
0
File: ssh.go Project: yingkitw/cli
func (cmd *SSH) Requirements(requirementsFactory requirements.Factory, fc flags.FlagContext) []requirements.Requirement {
	if len(fc.Args()) != 1 {
		cmd.ui.Failed(T("Incorrect Usage. Requires APP_NAME as argument") + "\n\n" + commandregistry.Commands.CommandUsage("ssh"))
	}

	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")))
	}

	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")))
	}

	cmd.appReq = requirementsFactory.NewApplicationRequirement(cmd.opts.AppName)

	reqs := []requirements.Requirement{
		requirementsFactory.NewLoginRequirement(),
		requirementsFactory.NewTargetedSpaceRequirement(),
		cmd.appReq,
	}

	return reqs
}
func (cmd *UpdateUserProvidedService) Execute(c flags.FlagContext) error {
	serviceInstance := cmd.serviceInstanceReq.GetServiceInstance()
	if !serviceInstance.IsUserProvided() {
		return errors.New(T("Service Instance is not user provided"))
	}

	drainURL := c.String("l")
	credentials := strings.Trim(c.String("p"), `'"`)
	routeServiceURL := c.String("r")

	credentialsMap := make(map[string]interface{})

	if c.IsSet("p") {
		jsonBytes, err := util.GetContentsFromFlagValue(credentials)
		if err != nil {
			return err
		}

		err = json.Unmarshal(jsonBytes, &credentialsMap)
		if err != nil {
			for _, param := range strings.Split(credentials, ",") {
				param = strings.Trim(param, " ")
				credentialsMap[param] = cmd.ui.Ask(param)
			}
		}
	}

	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 = credentialsMap
	serviceInstance.SysLogDrainURL = drainURL
	serviceInstance.RouteServiceURL = routeServiceURL

	err := cmd.userProvidedServiceInstanceRepo.Update(serviceInstance.ServiceInstanceFields)
	if err != nil {
		return err
	}

	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 routeServiceURL == "" && credentials == "" && drainURL == "" {
		cmd.ui.Warn(T("No flags specified. No changes were made."))
	}
	return nil
}
Example #4
0
File: curl.go Project: Reejoshi/cli
func (cmd *Curl) Execute(c flags.FlagContext) error {
	path := c.Args()[0]
	headers := c.StringSlice("H")

	var method string
	var body string

	if c.IsSet("d") {
		method = "POST"

		jsonBytes, err := util.GetContentsFromOptionalFlagValue(c.String("d"))
		if err != nil {
			return err
		}
		body = string(jsonBytes)
	}

	if c.IsSet("X") {
		method = c.String("X")
	}

	reqHeader := strings.Join(headers, "\n")

	responseHeader, responseBody, apiErr := cmd.curlRepo.Request(method, path, reqHeader, body)
	if apiErr != nil {
		return errors.New(T("Error creating request:\n{{.Err}}", map[string]interface{}{"Err": apiErr.Error()}))
	}

	if trace.LoggingToStdout {
		return nil
	}

	if c.Bool("i") {
		cmd.ui.Say(responseHeader)
	}

	if c.String("output") != "" {
		err := cmd.writeToFile(responseBody, c.String("output"))
		if err != nil {
			return errors.New(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 nil
}
Example #5
0
func (cmd *BindRouteService) Execute(c flags.FlagContext) error {
	var port int

	host := c.String("hostname")
	domain := cmd.domainReq.GetDomain()
	path := c.String("path")
	if !strings.HasPrefix(path, "/") && len(path) > 0 {
		path = fmt.Sprintf("/%s", path)
	}

	var parameters string

	if c.IsSet("parameters") {
		jsonBytes, err := util.GetContentsFromFlagValue(c.String("parameters"))
		if err != nil {
			return err
		}
		parameters = string(jsonBytes)
	}

	route, err := cmd.routeRepo.Find(host, domain, path, port)
	if err != nil {
		return err
	}

	serviceInstance := cmd.serviceInstanceReq.GetServiceInstance()

	cmd.ui.Say(T("Binding route {{.URL}} to service instance {{.ServiceInstanceName}} in org {{.OrgName}} / space {{.SpaceName}} as {{.CurrentUser}}...",
		map[string]interface{}{
			"ServiceInstanceName": terminal.EntityNameColor(serviceInstance.Name),
			"URL":         terminal.EntityNameColor(route.URL()),
			"OrgName":     terminal.EntityNameColor(cmd.config.OrganizationFields().Name),
			"SpaceName":   terminal.EntityNameColor(cmd.config.SpaceFields().Name),
			"CurrentUser": terminal.EntityNameColor(cmd.config.Username()),
		}))

	err = cmd.routeServiceBindingRepo.Bind(serviceInstance.GUID, route.GUID, serviceInstance.IsUserProvided(), parameters)
	if err != nil {
		if httpErr, ok := err.(errors.HTTPError); ok && httpErr.ErrorCode() == errors.ServiceInstanceAlreadyBoundToSameRoute {
			cmd.ui.Warn(T("Route {{.URL}} is already bound to service instance {{.ServiceInstanceName}}.",
				map[string]interface{}{
					"URL": route.URL(),
					"ServiceInstanceName": serviceInstance.Name,
				}))
		} else {
			return err
		}
	}

	cmd.ui.Ok()
	return nil
}
Example #6
0
func (cmd *Curl) Execute(c flags.FlagContext) {
	path := c.Args()[0]
	method := c.String("X")
	headers := c.StringSlice("H")
	var body string
	if c.IsSet("d") {
		jsonBytes, err := util.GetContentsFromFlagValue(c.String("d"))
		if err != nil {
			cmd.ui.Failed(err.Error())
		}
		body = string(jsonBytes)
	}
	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
}
Example #7
0
func (cmd *DeleteRoute) Requirements(requirementsFactory requirements.Factory, fc flags.FlagContext) []requirements.Requirement {
	if len(fc.Args()) != 1 {
		cmd.ui.Failed(T("Incorrect Usage. Requires an argument\n\n") + commandregistry.Commands.CommandUsage("delete-route"))
	}

	if fc.IsSet("port") && (fc.IsSet("hostname") || fc.IsSet("path")) {
		cmd.ui.Failed(T("Cannot specify port together with hostname and/or path."))
	}

	cmd.domainReq = requirementsFactory.NewDomainRequirement(fc.Args()[0])

	requiredVersion, err := semver.Make("2.36.0")
	if err != nil {
		panic(err.Error())
	}

	var reqs []requirements.Requirement

	if fc.String("path") != "" {
		reqs = append(reqs, requirementsFactory.NewMinAPIVersionRequirement("Option '--path'", requiredVersion))
	}

	if fc.IsSet("port") {
		reqs = append(reqs, requirementsFactory.NewMinAPIVersionRequirement("Option '--port'", cf.TCPRoutingMinimumAPIVersion))
	}

	reqs = append(reqs, []requirements.Requirement{
		requirementsFactory.NewLoginRequirement(),
		cmd.domainReq,
	}...)

	return reqs
}
func (cmd *CreateQuota) Requirements(requirementsFactory requirements.Factory, fc flags.FlagContext) []requirements.Requirement {
	if len(fc.Args()) != 1 {
		cmd.ui.Failed(T("Incorrect Usage. Requires an argument\n\n") + command_registry.Commands.CommandUsage("create-quota"))
	}

	reqs := []requirements.Requirement{
		requirementsFactory.NewLoginRequirement(),
	}

	if fc.IsSet("a") {
		reqs = append(reqs, requirementsFactory.NewMinAPIVersionRequirement("Option '-a'", cf.OrgAppInstanceLimitMinimumApiVersion))
	}

	return reqs
}
func (cmd *CreateServiceBroker) Requirements(requirementsFactory requirements.Factory, fc flags.FlagContext) ([]requirements.Requirement, error) {
	if len(fc.Args()) != 4 {
		cmd.ui.Failed(T("Incorrect Usage. Requires SERVICE_BROKER, USERNAME, PASSWORD, URL as arguments\n\n") + command_registry.Commands.CommandUsage("create-service-broker"))
	}

	var reqs = []requirements.Requirement{
		requirementsFactory.NewLoginRequirement(),
	}

	if fc.IsSet("space-scoped") {
		reqs = append(reqs, requirementsFactory.NewTargetedSpaceRequirement())
	}

	return reqs, nil
}
Example #10
0
func (cmd *Target) Requirements(requirementsFactory requirements.Factory, fc flags.FlagContext) (reqs []requirements.Requirement, err error) {
	if len(fc.Args()) != 0 {
		cmd.ui.Failed(T("Incorrect Usage. No argument required\n\n") + command_registry.Commands.CommandUsage("target"))
	}

	reqs = []requirements.Requirement{
		requirementsFactory.NewApiEndpointRequirement(),
	}

	if fc.IsSet("o") || fc.IsSet("s") {
		reqs = append(reqs, requirementsFactory.NewLoginRequirement())
	}

	return
}
Example #11
0
func (cmd *PurgeServiceOffering) Execute(c flags.FlagContext) error {
	serviceName := c.Args()[0]

	var offering models.ServiceOffering
	if c.IsSet("p") {
		var err error
		offering, err = cmd.serviceRepo.FindServiceOfferingByLabelAndProvider(serviceName, c.String("p"))
		if err != nil {
			if _, ok := err.(*errors.ModelNotFoundError); ok {
				cmd.ui.Warn(T("Service offering does not exist\nTIP: If you are trying to purge a v1 service offering, you must set the -p flag."))
				return nil
			}
			return err
		}
	} else {
		offerings, err := cmd.serviceRepo.FindServiceOfferingsByLabel(serviceName)
		if err != nil {
			if _, ok := err.(*errors.ModelNotFoundError); ok {
				cmd.ui.Warn(T("Service offering does not exist\nTIP: If you are trying to purge a v1 service offering, you must set the -p flag."))
				return nil
			}
			return err
		}
		offering = offerings[0]
	}

	confirmed := c.Bool("f")
	if !confirmed {
		cmd.ui.Warn(scaryWarningMessage())
		confirmed = cmd.ui.Confirm(T("Really purge service offering {{.ServiceName}} from Cloud Foundry?",
			map[string]interface{}{"ServiceName": serviceName},
		))
	}

	if !confirmed {
		return nil
	}

	cmd.ui.Say(T("Purging service {{.ServiceName}}...", map[string]interface{}{"ServiceName": serviceName}))

	err := cmd.serviceRepo.PurgeServiceOffering(offering)
	if err != nil {
		return err
	}

	cmd.ui.Ok()
	return nil
}
Example #12
0
func (cmd *Files) Execute(c flags.FlagContext) {
	app := cmd.appReq.GetApplication()

	var instance int
	if c.IsSet("i") {
		instance = c.Int("i")
		if instance < 0 {
			cmd.ui.Failed(T("Invalid instance: {{.Instance}}\nInstance must be a positive integer",
				map[string]interface{}{
					"Instance": instance,
				}))
		}
		if instance >= app.InstanceCount {
			cmd.ui.Failed(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, apiErr := cmd.appFilesRepo.ListFiles(app.Guid, instance, path)
	if apiErr != nil {
		cmd.ui.Failed(apiErr.Error())
		return
	}

	cmd.ui.Ok()
	cmd.ui.Say("")

	if list == "" {
		cmd.ui.Say("No files found")
	} else {
		cmd.ui.Say("%s", list)
	}
}
Example #13
0
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()
		err, plan = 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())
	}
}
func (cmd *CreateUserProvidedService) Execute(c flags.FlagContext) {
	name := c.Args()[0]
	drainUrl := c.String("l")
	routeServiceUrl := c.String("r")
	credentials := strings.Trim(c.String("p"), `"'`)
	credentialsMap := make(map[string]interface{})

	if c.IsSet("p") {
		switch {
		case strings.HasPrefix(credentials, "@"):
			jsonFileBytes, err := ioutil.ReadFile(credentials[1:])
			if err != nil {
				cmd.ui.Failed(err.Error())
			}

			err = json.Unmarshal(jsonFileBytes, &credentialsMap)
			if err != nil {
				cmd.ui.Failed(err.Error())
			}
		case strings.HasPrefix(credentials, "{"):
			err := json.Unmarshal([]byte(credentials), &credentialsMap)
			if err != nil {
				cmd.ui.Failed(err.Error())
			}
		default:
			credentialsMap = cmd.mapValuesFromPrompt(credentials, credentialsMap)
		}
	}

	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()),
		}))

	err := cmd.userProvidedServiceInstanceRepo.Create(name, drainUrl, routeServiceUrl, credentialsMap)
	if err != nil {
		cmd.ui.Failed(err.Error())
		return
	}

	cmd.ui.Ok()
}
Example #15
0
func (cmd *Target) Requirements(requirementsFactory requirements.Factory, fc flags.FlagContext) []requirements.Requirement {
	usageReq := requirements.NewUsageRequirement(commandregistry.CLICommandUsagePresenter(cmd),
		T("No argument required"),
		func() bool {
			return len(fc.Args()) != 0
		},
	)

	reqs := []requirements.Requirement{
		usageReq,
		requirementsFactory.NewAPIEndpointRequirement(),
	}

	if fc.IsSet("o") || fc.IsSet("s") {
		reqs = append(reqs, requirementsFactory.NewLoginRequirement())
	}

	return reqs
}
Example #16
0
func (cmd *PurgeServiceOffering) Requirements(requirementsFactory requirements.Factory, fc flags.FlagContext) []requirements.Requirement {
	if len(fc.Args()) != 1 {
		cmd.ui.Failed(T("Incorrect Usage. Requires an argument\n\n") + commandregistry.Commands.CommandUsage("purge-service-offering"))
	}

	reqs := []requirements.Requirement{
		requirementsFactory.NewLoginRequirement(),
	}

	if fc.IsSet("p") {
		maximumVersion, err := semver.Make("2.46.0")
		if err != nil {
			panic(err.Error())
		}
		reqs = append(reqs, requirementsFactory.NewMaxAPIVersionRequirement("Option '-p'", maximumVersion))
	}

	return reqs
}
Example #17
0
File: push.go Project: plamenai/cli
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") == "" {
			err := cmd.actor.ProcessPath(*appParams.Path, cmd.processPathCallback(*appParams.Path, app))
			if err != nil {
				cmd.ui.Failed(
					T("Error processing app files: {{.Error}}",
						map[string]interface{}{
							"Error": err.Error(),
						}),
				)
				return
			}
		}

		if appParams.ServicesToBind != nil {
			cmd.bindAppToServices(*appParams.ServicesToBind, app)
		}

		cmd.restart(app, appParams, c)
	}
}
func (cmd *CreateUserProvidedService) Execute(c flags.FlagContext) {
	name := c.Args()[0]
	drainUrl := c.String("l")
	routeServiceUrl := c.String("r")
	credentials := strings.Trim(c.String("p"), `"'`)
	credentialsMap := make(map[string]interface{})

	if c.IsSet("p") {
		jsonBytes, err := util.GetContentsFromFlagValue(credentials)
		if err != nil && strings.HasPrefix(credentials, "@") {
			cmd.ui.Failed(err.Error())
		}

		if bytes.IndexAny(jsonBytes, "[{") != -1 {
			err = json.Unmarshal(jsonBytes, &credentialsMap)
			if err != nil {
				cmd.ui.Failed(err.Error())
			}
		} else {
			for _, param := range strings.Split(credentials, ",") {
				param = strings.Trim(param, " ")
				credentialsMap[param] = cmd.ui.Ask("%s", param)
			}
		}
	}

	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()),
		}))

	err := cmd.userProvidedServiceInstanceRepo.Create(name, drainUrl, routeServiceUrl, credentialsMap)
	if err != nil {
		cmd.ui.Failed(err.Error())
		return
	}

	cmd.ui.Ok()
}
Example #19
0
func (cmd *CreateSpaceQuota) Requirements(requirementsFactory requirements.Factory, fc flags.FlagContext) []requirements.Requirement {
	if len(fc.Args()) != 1 {
		cmd.ui.Failed(T("Incorrect Usage. Requires an argument\n\n") + commandregistry.Commands.CommandUsage("create-space-quota"))
	}

	reqs := []requirements.Requirement{
		requirementsFactory.NewLoginRequirement(),
		requirementsFactory.NewTargetedOrgRequirement(),
	}

	if fc.IsSet("a") {
		reqs = append(reqs, requirementsFactory.NewMinAPIVersionRequirement("Option '-a'", cf.SpaceAppInstanceLimitMinimumAPIVersion))
	}

	if fc.IsSet("reserved-route-ports") {
		reqs = append(reqs, requirementsFactory.NewMinAPIVersionRequirement("Option '--reserved-route-ports'", cf.ReservedRoutePortsMinimumAPIVersion))
	}

	return reqs
}
func (cmd *CreateUserProvidedService) Requirements(requirementsFactory requirements.Factory, fc flags.FlagContext) ([]requirements.Requirement, error) {
	if len(fc.Args()) != 1 {
		cmd.ui.Failed(T("Incorrect Usage. Requires an argument\n\n") + command_registry.Commands.CommandUsage("create-user-provided-service"))
	}

	reqs := []requirements.Requirement{
		requirementsFactory.NewLoginRequirement(),
		requirementsFactory.NewTargetedSpaceRequirement(),
	}

	if fc.IsSet("r") {
		minAPIVersion, err := semver.Make("2.51.0")
		if err != nil {
			panic(err.Error())
		}

		reqs = append(reqs, requirementsFactory.NewMinAPIVersionRequirement("Option '-r'", minAPIVersion))
	}

	return reqs, nil
}
Example #21
0
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()
}
Example #22
0
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 = REQUEST_TTY_YES
	}

	if fc.IsSet("tt") && fc.Bool("tt") {
		sshOptions.TerminalRequest = REQUEST_TTY_FORCE
	}

	if fc.Bool("T") {
		sshOptions.TerminalRequest = REQUEST_TTY_NO
	}

	return sshOptions, nil
}
func (cmd *CreateServiceBroker) Requirements(requirementsFactory requirements.Factory, fc flags.FlagContext) []requirements.Requirement {
	if len(fc.Args()) != 4 {
		cmd.ui.Failed(T("Incorrect Usage. Requires SERVICE_BROKER, USERNAME, PASSWORD, URL as arguments\n\n") + command_registry.Commands.CommandUsage("create-service-broker"))
	}

	reqs := []requirements.Requirement{
		requirementsFactory.NewLoginRequirement(),
	}

	if fc.IsSet("space-scoped") {
		requiredVersion, err := semver.Make("2.47.0")
		if err != nil {
			panic(err.Error())
		}

		reqs = append(
			reqs,
			requirementsFactory.NewTargetedSpaceRequirement(),
			requirementsFactory.NewMinAPIVersionRequirement("--space-scoped", requiredVersion),
		)
	}

	return reqs
}
Example #24
0
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.actor.ProcessPath(*appParams.Path, func(appDir string) {
				localFiles, err := cmd.appfiles.AppFilesInDir(appDir)
				if err != nil {
					cmd.ui.Failed(
						T("Error processing app files in '{{.Path}}': {{.Error}}",
							map[string]interface{}{
								"Path":  *appParams.Path,
								"Error": err.Error(),
							}),
					)
				}

				if len(localFiles) == 0 {
					cmd.ui.Failed(
						T("No app files found in '{{.Path}}'",
							map[string]interface{}{
								"Path": *appParams.Path,
							}),
					)
				}

				cmd.ui.Say(T("Uploading {{.AppName}}...",
					map[string]interface{}{"AppName": terminal.EntityNameColor(app.Name)}))

				apiErr := cmd.uploadApp(app.Guid, appDir, *appParams.Path, localFiles)
				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 *CreateSpaceQuota) Execute(context flags.FlagContext) {
	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 {
			cmd.ui.Failed(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 {
			cmd.ui.Failed(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
	}

	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
	}

	if err != nil {
		cmd.ui.Failed(err.Error())
	}

	cmd.ui.Ok()
}
Example #26
0
func (cmd *UpdateSpaceQuota) Execute(c flags.FlagContext) {
	name := c.Args()[0]

	spaceQuota, apiErr := cmd.spaceQuotaRepo.FindByName(name)
	if apiErr != nil {
		cmd.ui.Failed(apiErr.Error())
		return
	}

	allowPaidServices := c.Bool("allow-paid-service-plans")
	disallowPaidServices := c.Bool("disallow-paid-service-plans")
	if allowPaidServices && disallowPaidServices {
		cmd.ui.Failed(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 {
				cmd.ui.Failed(T("Incorrect Usage.\n\n") + command_registry.Commands.CommandUsage("update-space-quota"))
			}
		}

		spaceQuota.InstanceMemoryLimit = memory
	}

	if c.String("m") != "" {
		memory, formatError := formatters.ToMegabytes(c.String("m"))

		if formatError != nil {
			cmd.ui.Failed(T("Incorrect Usage.\n\n") + command_registry.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")
	}

	cmd.ui.Say(T("Updating space quota {{.Quota}} as {{.Username}}...",
		map[string]interface{}{
			"Quota":    terminal.EntityNameColor(name),
			"Username": terminal.EntityNameColor(cmd.config.Username()),
		}))

	apiErr = cmd.spaceQuotaRepo.Update(spaceQuota)
	if apiErr != nil {
		cmd.ui.Failed(apiErr.Error())
		return
	}

	cmd.ui.Ok()
}
Example #27
0
func (cmd *UpdateBuildpack) Execute(c flags.FlagContext) {
	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 {
		cmd.ui.Failed(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 {
		cmd.ui.Failed(T("Cannot specify both lock and unlock options."))
		return
	}

	path := c.String("p")
	var dir string
	var err error
	if path != "" {
		dir, err = filepath.Abs(path)
		if err != nil {
			cmd.ui.Failed(err.Error())
			return
		}
	}

	if dir != "" && (lock || unlock) {
		cmd.ui.Failed(T("Cannot specify buildpack bits and lock/unlock."))
	}

	if lock {
		buildpack.Locked = &lock
		updateBuildpack = true
	}
	if unlock {
		unlock = false
		buildpack.Locked = &unlock
		updateBuildpack = true
	}

	if updateBuildpack {
		newBuildpack, apiErr := cmd.buildpackRepo.Update(buildpack)
		if apiErr != nil {
			cmd.ui.Failed(T("Error updating buildpack {{.Name}}\n{{.Error}}", map[string]interface{}{
				"Name":  terminal.EntityNameColor(buildpack.Name),
				"Error": apiErr.Error(),
			}))
		}
		buildpack = newBuildpack
	}

	if dir != "" {
		apiErr := cmd.buildpackBitsRepo.UploadBuildpack(buildpack, dir)
		if apiErr != nil {
			cmd.ui.Failed(T("Error uploading buildpack {{.Name}}\n{{.Error}}", map[string]interface{}{
				"Name":  terminal.EntityNameColor(buildpack.Name),
				"Error": apiErr.Error(),
			}))
		}
	}
	cmd.ui.Ok()
}
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
		}

		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]
		}

		cmd.ui.Failed(unsupportedLocaleMessage)
	}
}
Example #29
0
				fCtx = flags.NewFlagContext(cmdFlagMap)
			})

			It("accepts flags with either single '-' or double '-' ", func() {
				err := fCtx.Parse("--name", "blue")
				Expect(err).NotTo(HaveOccurred())

				err = fCtx.Parse("-name", "")
				Expect(err).NotTo(HaveOccurred())
			})

			It("sets a flag with it's full name", func() {
				err := fCtx.Parse("-name", "blue")
				Expect(err).NotTo(HaveOccurred())
				Expect(fCtx.IsSet("name")).To(BeTrue())
				Expect(fCtx.IsSet("n")).To(BeTrue())
				Expect(fCtx.String("name")).To(Equal("blue"))
				Expect(fCtx.String("n")).To(Equal("blue"))
			})

			It("sets a flag with it's short name", func() {
				err := fCtx.Parse("-n", "red")
				Expect(err).NotTo(HaveOccurred())
				Expect(fCtx.IsSet("name")).To(BeTrue())
				Expect(fCtx.IsSet("n")).To(BeTrue())
				Expect(fCtx.String("name")).To(Equal("red"))
				Expect(fCtx.String("n")).To(Equal("red"))
			})

			It("checks if a flag is defined in the FlagContext", func() {
Example #30
0
File: push.go Project: plamenai/cli
func (cmd *Push) getAppParamsFromContext(c flags.FlagContext) (appParams models.AppParams) {
	if len(c.Args()) > 0 {
		appParams.Name = &c.Args()[0]
	}

	appParams.NoRoute = c.Bool("no-route")
	appParams.UseRandomHostname = c.Bool("random-route")
	appParams.NoHostname = c.Bool("no-hostname")

	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("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 {
			cmd.ui.Failed(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 {
			cmd.ui.Failed(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 {
			cmd.ui.Failed(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 {
			cmd.ui.Failed("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" {
			cmd.ui.Failed("Error: %s", fmt.Errorf(T("Invalid health-check-type param: {{.healthCheckType}}",
				map[string]interface{}{"healthCheckType": healthCheckType})))
		}

		appParams.HealthCheckType = &healthCheckType
	}

	return
}