func ParseVersion(input string) (Version, error) { parts := strings.Split(input, ".") if len(parts) != 3 { return Version{}, errors.NewWithFmt("Could not parse version number: %s", input) } major, err1 := strconv.ParseUint(parts[0], 10, 64) minor, err2 := strconv.ParseUint(parts[1], 10, 64) patch, err3 := strconv.ParseUint(parts[2], 10, 64) if err1 != nil || err2 != nil || err3 != nil { return Version{}, errors.NewWithFmt("Could not parse version number: %s", input) } return Version{major, minor, patch}, nil }
func (cmd CreateBuildpack) createBuildpack(buildpackName string, c *cli.Context) (buildpack models.Buildpack, apiErr error) { position, err := strconv.Atoi(c.Args()[2]) if err != nil { apiErr = errors.NewWithFmt("Invalid position. %s", err.Error()) return } enabled := c.Bool("enable") disabled := c.Bool("disable") if enabled && disabled { apiErr = errors.New("Cannot specify both enabled and disabled.") return } var enableOption *bool = nil if enabled { enableOption = &enabled } if disabled { disabled = false enableOption = &disabled } buildpack, apiErr = cmd.buildpackRepo.Create(buildpackName, &position, enableOption, nil) return }
func (m Manifest) getAppMaps(data generic.Map) (apps []generic.Map, errs []error) { globalProperties := data.Except([]interface{}{"applications"}) if data.Has("applications") { appMaps, ok := data.Get("applications").([]interface{}) if !ok { errs = append(errs, errors.New("Expected applications to be a list")) return } for _, appData := range appMaps { if !generic.IsMappable(appData) { errs = append(errs, errors.NewWithFmt("Expected application to be a list of key/value pairs\nError occurred in manifest near:\n'%s'", appData)) continue } appMap := generic.DeepMerge(globalProperties, generic.NewMap(appData)) apps = append(apps, appMap) } } else { apps = append(apps, globalProperties) } return }
func (gateway Gateway) waitForJob(jobUrl, accessToken string, timeout time.Duration) (err error) { startTime := time.Now() for true { if time.Since(startTime) > timeout { err = errors.NewWithFmt("Error: timed out waiting for async job '%s' to finish", jobUrl) return } var request *Request request, err = gateway.NewRequest("GET", jobUrl, accessToken, nil) response := &JobResource{} _, err = gateway.PerformRequestForJSONResponse(request, response) if err != nil { return } switch response.Entity.Status { case JOB_FINISHED: return case JOB_FAILED: err = errors.New(response.Entity.ErrorDetails.Description) return } accessToken = request.HttpReq.Header.Get("Authorization") time.Sleep(gateway.PollingThrottle) } return }
func sliceOrEmptyVal(yamlMap generic.Map, key string, errs *[]error) *[]string { if !yamlMap.Has(key) { return new([]string) } var ( stringSlice []string err error ) sliceErr := errors.NewWithFmt("Expected %s to be a list of strings.", key) switch input := yamlMap.Get(key).(type) { case []interface{}: for _, value := range input { stringValue, ok := value.(string) if !ok { err = sliceErr break } stringSlice = append(stringSlice, stringValue) } default: err = sliceErr } if err != nil { *errs = append(*errs, err) return nil } return &stringSlice }
func intVal(yamlMap generic.Map, key string, errs *[]error) *int { var ( intVal int err error ) switch val := yamlMap.Get(key).(type) { case string: intVal, err = strconv.Atoi(val) case int: intVal = val case int64: intVal = int(val) case nil: return nil default: err = errors.NewWithFmt("Expected %s to be a number, but it was a %T.", key, val) } if err != nil { *errs = append(*errs, err) return nil } return &intVal }
func (repo CloudControllerUserRepository) checkSpaceRole(userGuid, spaceGuid, role string) (fullPath string, apiErr error) { rolePath, found := spaceRoleToPathMap[role] if !found { apiErr = errors.NewWithFmt("Invalid Role %s", role) } fullPath = fmt.Sprintf("%s/v2/spaces/%s/%s/%s", repo.config.ApiEndpoint(), spaceGuid, rolePath, userGuid) return }
func findAppWithNameInManifest(name string, manifestApps []models.AppParams) (app models.AppParams, err error) { for _, appParams := range manifestApps { if appParams.Name != nil && *appParams.Name == name { app = appParams return } } err = errors.NewWithFmt("Could not find app named '%s' in manifest", name) return }
func checkForNulls(yamlMap generic.Map) (errs []error) { generic.Each(yamlMap, func(key interface{}, value interface{}) { if key == "command" || key == "buildpack" { return } if value == nil { errs = append(errs, errors.NewWithFmt("%s should not be null", key)) } }) return }
func bytesVal(yamlMap generic.Map, key string, errs *[]error) *uint64 { yamlVal := yamlMap.Get(key) if yamlVal == nil { return nil } value, err := formatters.ToMegabytes(yamlVal.(string)) if err != nil { *errs = append(*errs, errors.NewWithFmt("Unexpected value for %s :\n%s", key, err.Error())) return nil } return &value }
func stringVal(yamlMap generic.Map, key string, errs *[]error) *string { val := yamlMap.Get(key) if val == nil { return nil } result, ok := val.(string) if !ok { *errs = append(*errs, errors.NewWithFmt("%s must be a string value", key)) return nil } return &result }
func envVarOrEmptyMap(yamlMap generic.Map, errs *[]error) *map[string]string { key := "env" switch envVars := yamlMap.Get(key).(type) { case nil: aMap := make(map[string]string, 0) return &aMap case map[string]interface{}: yamlMap.Set(key, generic.NewMap(yamlMap.Get(key))) return envVarOrEmptyMap(yamlMap, errs) case map[interface{}]interface{}: yamlMap.Set(key, generic.NewMap(yamlMap.Get(key))) return envVarOrEmptyMap(yamlMap, errs) case generic.Map: merrs := validateEnvVars(envVars) if merrs != nil { *errs = append(*errs, merrs...) return nil } result := make(map[string]string, envVars.Count()) generic.Each(envVars, func(key, value interface{}) { switch value.(type) { case string: result[key.(string)] = value.(string) case int64, int, int32: result[key.(string)] = fmt.Sprintf("%d", value) case float32, float64: result[key.(string)] = fmt.Sprintf("%f", value) default: *errs = append(*errs, errors.NewWithFmt("Expected environment variable %s to have a string value, but it was a %T.", key, value)) } }) return &result default: *errs = append(*errs, errors.NewWithFmt("Expected %s to be a set of key => value, but it was a %T.", key, envVars)) return nil } }
func (cmd Target) setOrganization(orgName string) error { // setting an org necessarily invalidates any space you had previously targeted cmd.config.SetOrganizationFields(models.OrganizationFields{}) cmd.config.SetSpaceFields(models.SpaceFields{}) org, apiErr := cmd.orgRepo.FindByName(orgName) if apiErr != nil { return errors.NewWithFmt("Could not target org.\n%s", apiErr.Error()) } cmd.config.SetOrganizationFields(org.OrganizationFields) return nil }
func boolVal(yamlMap generic.Map, key string, errs *[]error) bool { switch val := yamlMap.Get(key).(type) { case nil: return false case bool: return val case string: return val == "true" default: *errs = append(*errs, errors.NewWithFmt("Expected %s to be a boolean.", key)) return false } }
func stringOrNullVal(yamlMap generic.Map, key string, errs *[]error) *string { if !yamlMap.Has(key) { return nil } switch val := yamlMap.Get(key).(type) { case string: return &val case nil: empty := "" return &empty default: *errs = append(*errs, errors.NewWithFmt("%s must be a string or null value", key)) return nil } }
func (repo CloudControllerStackRepository) FindByName(name string) (stack models.Stack, apiErr error) { path := fmt.Sprintf("%s/v2/stacks?q=%s", repo.config.ApiEndpoint(), url.QueryEscape("name:"+name)) stacks, apiErr := repo.findAllWithPath(path) if apiErr != nil { return } if len(stacks) == 0 { apiErr = errors.NewWithFmt("Stack '%s' not found", name) return } stack = stacks[0] return }
func (cmd Target) setSpace(spaceName string) error { cmd.config.SetSpaceFields(models.SpaceFields{}) if !cmd.config.HasOrganization() { return errors.New("An org must be targeted before targeting a space") } space, apiErr := cmd.spaceRepo.FindByName(spaceName) if apiErr != nil { return errors.NewWithFmt("Unable to access space %s.\n%s", spaceName, apiErr.Error()) } cmd.config.SetSpaceFields(space.SpaceFields) return nil }
func expandProperties(input interface{}, babbler words.WordGenerator) (output interface{}, errs []error) { switch input := input.(type) { case string: match := propertyRegex.FindStringSubmatch(input) if match != nil { if match[0] == "${random-word}" { output = strings.Replace(input, "${random-word}", strings.ToLower(babbler.Babble()), -1) } else { err := errors.NewWithFmt("Property '%s' found in manifest. This feature is no longer supported. Please remove it and try again.", match[0]) errs = append(errs, err) } } else { output = input } case []interface{}: outputSlice := make([]interface{}, len(input)) for index, item := range input { itemOutput, itemErrs := expandProperties(item, babbler) outputSlice[index] = itemOutput errs = append(errs, itemErrs...) } output = outputSlice case map[interface{}]interface{}: outputMap := make(map[interface{}]interface{}) for key, value := range input { itemOutput, itemErrs := expandProperties(value, babbler) outputMap[key] = itemOutput errs = append(errs, itemErrs...) } output = outputMap case generic.Map: outputMap := generic.NewMap() generic.Each(input, func(key, value interface{}) { itemOutput, itemErrs := expandProperties(value, babbler) outputMap.Set(key, itemOutput) errs = append(errs, itemErrs...) }) output = outputMap default: output = input } return }
func stringValOrDefault(yamlMap generic.Map, key string, errs *[]error) *string { if !yamlMap.Has(key) { return nil } empty := "" switch val := yamlMap.Get(key).(type) { case string: if val == "default" { return &empty } else { return &val } case nil: return &empty default: *errs = append(*errs, errors.NewWithFmt("%s must be a string or null value", key)) return nil } }
func (repo CloudControllerUserRepository) setOrUnsetOrgRole(verb, userGuid, orgGuid, role string) (apiErr error) { rolePath, found := orgRoleToPathMap[role] if !found { apiErr = errors.NewWithFmt("Invalid Role %s", role) return } path := fmt.Sprintf("%s/v2/organizations/%s/%s/%s", repo.config.ApiEndpoint(), orgGuid, rolePath, userGuid) request, apiErr := repo.ccGateway.NewRequest(verb, path, repo.config.AccessToken(), nil) if apiErr != nil { return } _, apiErr = repo.ccGateway.PerformRequest(request) if apiErr != nil { return } return }
func (cmd *Push) getAppParamsFromContext(c *cli.Context) (appParams models.AppParams) { if len(c.Args()) > 0 { appParams.Name = &c.Args()[0] } if c.String("b") != "" { buildpack := c.String("b") appParams.BuildpackUrl = &buildpack } if c.String("m") != "" { memory, err := formatters.ToMegabytes(c.String("m")) if err != nil { cmd.ui.Failed("Error: %s", errors.NewWithFmt("Invalid memory param: %s\n%s", c.String("m"), err)) return } appParams.Memory = &memory } appParams.NoRoute = c.Bool("no-route") appParams.UseRandomHostname = c.Bool("random-route") if c.String("n") != "" { hostname := c.String("n") appParams.Host = &hostname } if c.String("d") != "" { domain := c.String("d") appParams.Domain = &domain } if c.String("c") != "" { command := c.String("c") appParams.Command = &command } if c.String("c") == "null" { emptyStr := "" appParams.Command = &emptyStr } if c.String("i") != "" { instances, err := strconv.Atoi(c.String("i")) if err != nil { cmd.ui.Failed("Error: %s", errors.NewWithFmt("Invalid instances param: %s\n%s", c.String("i"), err)) } appParams.InstanceCount = &instances } 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", errors.NewWithFmt("Invalid timeout param: %s\n%s", c.String("t"), err)) } appParams.HealthCheckTimeout = &timeout } if c.String("p") != "" { path := c.String("p") appParams.Path = &path } return }
func (cmd *Push) getAppParamsFromContext(c *cli.Context) (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") if c.String("n") != "" { hostname := c.String("n") appParams.Host = &hostname } 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") != "" { domain := c.String("d") appParams.Domain = &domain } if c.IsSet("i") { instances := c.Int("i") if instances < 1 { cmd.ui.Failed("Invalid instance count: %d\nInstance count must be a positive integer", instances) } appParams.InstanceCount = &instances } if c.String("k") != "" { diskQuota, err := formatters.ToMegabytes(c.String("k")) if err != nil { cmd.ui.Failed("Invalid disk quota: %s\n%s", c.String("k"), err) } appParams.DiskQuota = &diskQuota } if c.String("m") != "" { memory, err := formatters.ToMegabytes(c.String("m")) if err != nil { cmd.ui.Failed("Invalid memory limit: %s\n%s", c.String("m"), err) } appParams.Memory = &memory } 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", errors.NewWithFmt("Invalid timeout param: %s\n%s", c.String("t"), err)) } appParams.HealthCheckTimeout = &timeout } return }