repo stringlengths 5 67 | sha stringlengths 40 40 | path stringlengths 4 234 | url stringlengths 85 339 | language stringclasses 6 values | split stringclasses 3 values | doc stringlengths 3 51.2k | sign stringlengths 5 8.01k | problem stringlengths 13 51.2k | output stringlengths 0 3.87M |
|---|---|---|---|---|---|---|---|---|---|
cloudfoundry/cli | 5010c000047f246b870475e2c299556078cdad30 | util/configv3/plugins_config.go | https://github.com/cloudfoundry/cli/blob/5010c000047f246b870475e2c299556078cdad30/util/configv3/plugins_config.go#L43-L48 | go | train | // PluginCommands returns the plugin's commands sorted by command name. | func (p Plugin) PluginCommands() []PluginCommand | // PluginCommands returns the plugin's commands sorted by command name.
func (p Plugin) PluginCommands() []PluginCommand | {
sort.Slice(p.Commands, func(i, j int) bool {
return strings.ToLower(p.Commands[i].Name) < strings.ToLower(p.Commands[j].Name)
})
return p.Commands
} |
cloudfoundry/cli | 5010c000047f246b870475e2c299556078cdad30 | util/configv3/plugins_config.go | https://github.com/cloudfoundry/cli/blob/5010c000047f246b870475e2c299556078cdad30/util/configv3/plugins_config.go#L58-L63 | go | train | // String returns the plugin's version in the format x.y.z. | func (v PluginVersion) String() string | // String returns the plugin's version in the format x.y.z.
func (v PluginVersion) String() string | {
if v.Major == 0 && v.Minor == 0 && v.Build == 0 {
return notApplicable
}
return fmt.Sprintf("%d.%d.%d", v.Major, v.Minor, v.Build)
} |
cloudfoundry/cli | 5010c000047f246b870475e2c299556078cdad30 | util/configv3/plugins_config.go | https://github.com/cloudfoundry/cli/blob/5010c000047f246b870475e2c299556078cdad30/util/configv3/plugins_config.go#L75-L80 | go | train | // CommandName returns the name of the plugin. The name is concatenated with
// alias if alias is specified. | func (c PluginCommand) CommandName() string | // CommandName returns the name of the plugin. The name is concatenated with
// alias if alias is specified.
func (c PluginCommand) CommandName() string | {
if c.Name != "" && c.Alias != "" {
return fmt.Sprintf("%s, %s", c.Name, c.Alias)
}
return c.Name
} |
cloudfoundry/cli | 5010c000047f246b870475e2c299556078cdad30 | util/configv3/plugins_config.go | https://github.com/cloudfoundry/cli/blob/5010c000047f246b870475e2c299556078cdad30/util/configv3/plugins_config.go#L89-L91 | go | train | // AddPlugin adds the specified plugin to PluginsConfig | func (config *Config) AddPlugin(plugin Plugin) | // AddPlugin adds the specified plugin to PluginsConfig
func (config *Config) AddPlugin(plugin Plugin) | {
config.pluginsConfig.Plugins[plugin.Name] = plugin
} |
cloudfoundry/cli | 5010c000047f246b870475e2c299556078cdad30 | util/configv3/plugins_config.go | https://github.com/cloudfoundry/cli/blob/5010c000047f246b870475e2c299556078cdad30/util/configv3/plugins_config.go#L98-L101 | go | train | // GetPlugin returns the requested plugin and true if it exists. | func (config *Config) GetPlugin(pluginName string) (Plugin, bool) | // GetPlugin returns the requested plugin and true if it exists.
func (config *Config) GetPlugin(pluginName string) (Plugin, bool) | {
plugin, exists := config.pluginsConfig.Plugins[pluginName]
return plugin, exists
} |
cloudfoundry/cli | 5010c000047f246b870475e2c299556078cdad30 | util/configv3/plugins_config.go | https://github.com/cloudfoundry/cli/blob/5010c000047f246b870475e2c299556078cdad30/util/configv3/plugins_config.go#L105-L113 | go | train | // GetPluginCaseInsensitive finds the first matching plugin name case
// insensitive and returns true if it exists. | func (config *Config) GetPluginCaseInsensitive(pluginName string) (Plugin, bool) | // GetPluginCaseInsensitive finds the first matching plugin name case
// insensitive and returns true if it exists.
func (config *Config) GetPluginCaseInsensitive(pluginName string) (Plugin, bool) | {
for name, plugin := range config.pluginsConfig.Plugins {
if strings.EqualFold(name, pluginName) {
return plugin, true
}
}
return Plugin{}, false
} |
cloudfoundry/cli | 5010c000047f246b870475e2c299556078cdad30 | util/configv3/plugins_config.go | https://github.com/cloudfoundry/cli/blob/5010c000047f246b870475e2c299556078cdad30/util/configv3/plugins_config.go#L118-L124 | go | train | // PluginHome returns the plugin configuration directory to:
// 1. The $CF_PLUGIN_HOME/.cf/plugins environment variable if set
// 2. Defaults to the home directory (outlined in LoadConfig)/.cf/plugins | func (config *Config) PluginHome() string | // PluginHome returns the plugin configuration directory to:
// 1. The $CF_PLUGIN_HOME/.cf/plugins environment variable if set
// 2. Defaults to the home directory (outlined in LoadConfig)/.cf/plugins
func (config *Config) PluginHome() string | {
if config.ENV.CFPluginHome != "" {
return filepath.Join(config.ENV.CFPluginHome, ".cf", "plugins")
}
return filepath.Join(homeDirectory(), ".cf", "plugins")
} |
cloudfoundry/cli | 5010c000047f246b870475e2c299556078cdad30 | util/configv3/plugins_config.go | https://github.com/cloudfoundry/cli/blob/5010c000047f246b870475e2c299556078cdad30/util/configv3/plugins_config.go#L127-L136 | go | train | // Plugins returns installed plugins from the config sorted by name (case-insensitive). | func (config *Config) Plugins() []Plugin | // Plugins returns installed plugins from the config sorted by name (case-insensitive).
func (config *Config) Plugins() []Plugin | {
plugins := []Plugin{}
for _, plugin := range config.pluginsConfig.Plugins {
plugins = append(plugins, plugin)
}
sort.Slice(plugins, func(i, j int) bool {
return strings.ToLower(plugins[i].Name) < strings.ToLower(plugins[j].Name)
})
return plugins
} |
cloudfoundry/cli | 5010c000047f246b870475e2c299556078cdad30 | util/configv3/plugins_config.go | https://github.com/cloudfoundry/cli/blob/5010c000047f246b870475e2c299556078cdad30/util/configv3/plugins_config.go#L139-L141 | go | train | // RemovePlugin removes the specified plugin from PluginsConfig idempotently | func (config *Config) RemovePlugin(pluginName string) | // RemovePlugin removes the specified plugin from PluginsConfig idempotently
func (config *Config) RemovePlugin(pluginName string) | {
delete(config.pluginsConfig.Plugins, pluginName)
} |
cloudfoundry/cli | 5010c000047f246b870475e2c299556078cdad30 | util/configv3/plugins_config.go | https://github.com/cloudfoundry/cli/blob/5010c000047f246b870475e2c299556078cdad30/util/configv3/plugins_config.go#L145-L160 | go | train | // WritePluginConfig writes the plugin config to config.json in the plugin home
// directory. | func (config *Config) WritePluginConfig() error | // WritePluginConfig writes the plugin config to config.json in the plugin home
// directory.
func (config *Config) WritePluginConfig() error | {
// Marshal JSON
rawConfig, err := json.MarshalIndent(config.pluginsConfig, "", " ")
if err != nil {
return err
}
pluginFileDir := filepath.Join(config.PluginHome())
err = os.MkdirAll(pluginFileDir, 0700)
if err != nil {
return err
}
// Write to file
return ioutil.WriteFile(filepath.Join(pluginFileDir, "config.json"), rawConfig, 0600)
} |
cloudfoundry/cli | 5010c000047f246b870475e2c299556078cdad30 | cf/commandsloader/commands_loader.go | https://github.com/cloudfoundry/cli/blob/5010c000047f246b870475e2c299556078cdad30/cf/commandsloader/commands_loader.go#L35-L57 | go | train | /*******************
This package make a reference to all the command packages
in cf/commands/..., so all init() in the directories will
get initialized
* Any new command packages must be included here for init() to get called
********************/ | func Load() | /*******************
This package make a reference to all the command packages
in cf/commands/..., so all init() in the directories will
get initialized
* Any new command packages must be included here for init() to get called
********************/
func Load() | {
_ = commands.API{}
_ = application.ListApps{}
_ = buildpack.ListBuildpacks{}
_ = domain.CreateDomain{}
_ = environmentvariablegroup.RunningEnvironmentVariableGroup{}
_ = featureflag.ShowFeatureFlag{}
_ = organization.ListOrgs{}
_ = plugin.Plugins{}
_ = pluginrepo.RepoPlugins{}
_ = quota.CreateQuota{}
_ = route.CreateRoute{}
_ = routergroups.RouterGroups{}
_ = securitygroup.ShowSecurityGroup{}
_ = service.ShowService{}
_ = serviceauthtoken.ListServiceAuthTokens{}
_ = serviceaccess.ServiceAccess{}
_ = servicebroker.ListServiceBrokers{}
_ = servicekey.ServiceKey{}
_ = space.CreateSpace{}
_ = spacequota.SpaceQuota{}
_ = user.CreateUser{}
} |
cloudfoundry/cli | 5010c000047f246b870475e2c299556078cdad30 | actor/pluginaction/actor.go | https://github.com/cloudfoundry/cli/blob/5010c000047f246b870475e2c299556078cdad30/actor/pluginaction/actor.go#L11-L13 | go | train | // NewActor returns a pluginaction Actor | func NewActor(config Config, client PluginClient) *Actor | // NewActor returns a pluginaction Actor
func NewActor(config Config, client PluginClient) *Actor | {
return &Actor{config: config, client: client}
} |
cloudfoundry/cli | 5010c000047f246b870475e2c299556078cdad30 | types/null_bool.go | https://github.com/cloudfoundry/cli/blob/5010c000047f246b870475e2c299556078cdad30/types/null_bool.go#L17-L31 | go | train | // ParseStringValue is used to parse a user provided flag argument. | func (n *NullBool) ParseStringValue(val string) error | // ParseStringValue is used to parse a user provided flag argument.
func (n *NullBool) ParseStringValue(val string) error | {
if val == "" {
return nil
}
boolVal, err := strconv.ParseBool(val)
if err != nil {
return err
}
n.Value = boolVal
n.IsSet = true
return nil
} |
cloudfoundry/cli | 5010c000047f246b870475e2c299556078cdad30 | types/null_bool.go | https://github.com/cloudfoundry/cli/blob/5010c000047f246b870475e2c299556078cdad30/types/null_bool.go#L34-L43 | go | train | // ParseBoolValue is used to parse a user provided *bool argument. | func (n *NullBool) ParseBoolValue(val *bool) | // ParseBoolValue is used to parse a user provided *bool argument.
func (n *NullBool) ParseBoolValue(val *bool) | {
if val == nil {
n.IsSet = false
n.Value = false
return
}
n.Value = *val
n.IsSet = true
} |
cloudfoundry/cli | 5010c000047f246b870475e2c299556078cdad30 | api/cloudcontroller/ccv2/service.go | https://github.com/cloudfoundry/cli/blob/5010c000047f246b870475e2c299556078cdad30/api/cloudcontroller/ccv2/service.go#L31-L49 | go | train | // DeleteService deletes the service with the given GUID, and returns any errors and warnings. | func (client *Client) DeleteService(serviceGUID string, purge bool) (Warnings, error) | // DeleteService deletes the service with the given GUID, and returns any errors and warnings.
func (client *Client) DeleteService(serviceGUID string, purge bool) (Warnings, error) | {
queryParams := url.Values{}
queryParams.Set("purge", strconv.FormatBool(purge))
queryParams.Set("async", "true")
request, err := client.newHTTPRequest(requestOptions{
RequestName: internal.DeleteServiceRequest,
Query: queryParams,
URIParams: Params{"service_guid": serviceGUID},
})
if err != nil {
return nil, err
}
response := cloudcontroller.Response{}
err = client.connection.Make(request, &response)
return response.Warnings, err
} |
cloudfoundry/cli | 5010c000047f246b870475e2c299556078cdad30 | api/cloudcontroller/ccv2/service.go | https://github.com/cloudfoundry/cli/blob/5010c000047f246b870475e2c299556078cdad30/api/cloudcontroller/ccv2/service.go#L52-L93 | go | train | // UnmarshalJSON helps unmarshal a Cloud Controller Service response. | func (service *Service) UnmarshalJSON(data []byte) error | // UnmarshalJSON helps unmarshal a Cloud Controller Service response.
func (service *Service) UnmarshalJSON(data []byte) error | {
var ccService struct {
Metadata internal.Metadata
Entity struct {
Label string `json:"label"`
Description string `json:"description"`
DocumentationURL string `json:"documentation_url"`
ServiceBrokerName string `json:"service_broker_name"`
Extra string `json:"extra"`
}
}
err := cloudcontroller.DecodeJSON(data, &ccService)
if err != nil {
return err
}
service.GUID = ccService.Metadata.GUID
service.Label = ccService.Entity.Label
service.Description = ccService.Entity.Description
service.DocumentationURL = ccService.Entity.DocumentationURL
service.ServiceBrokerName = ccService.Entity.ServiceBrokerName
// We explicitly unmarshal the Extra field to type string because CC returns
// a stringified JSON object ONLY for the 'extra' key (see test stub JSON
// response). This unmarshal strips escaped quotes, at which time we can then
// unmarshal into the ServiceExtra object.
// If 'extra' is null or not provided, this means sharing is NOT enabled
if len(ccService.Entity.Extra) != 0 {
extra := ServiceExtra{}
err = json.Unmarshal([]byte(ccService.Entity.Extra), &extra)
if err != nil {
return err
}
service.Extra.Shareable = extra.Shareable
if service.DocumentationURL == "" {
service.DocumentationURL = extra.DocumentationURL
}
}
return nil
} |
cloudfoundry/cli | 5010c000047f246b870475e2c299556078cdad30 | api/cloudcontroller/ccv2/service.go | https://github.com/cloudfoundry/cli/blob/5010c000047f246b870475e2c299556078cdad30/api/cloudcontroller/ccv2/service.go#L96-L112 | go | train | // GetService returns the service with the given GUID. | func (client *Client) GetService(serviceGUID string) (Service, Warnings, error) | // GetService returns the service with the given GUID.
func (client *Client) GetService(serviceGUID string) (Service, Warnings, error) | {
request, err := client.newHTTPRequest(requestOptions{
RequestName: internal.GetServiceRequest,
URIParams: Params{"service_guid": serviceGUID},
})
if err != nil {
return Service{}, nil, err
}
var service Service
response := cloudcontroller.Response{
DecodeJSONResponseInto: &service,
}
err = client.connection.Make(request, &response)
return service, response.Warnings, err
} |
cloudfoundry/cli | 5010c000047f246b870475e2c299556078cdad30 | api/cloudcontroller/ccv2/service.go | https://github.com/cloudfoundry/cli/blob/5010c000047f246b870475e2c299556078cdad30/api/cloudcontroller/ccv2/service.go#L115-L122 | go | train | // GetServices returns a list of Services given the provided filters. | func (client *Client) GetServices(filters ...Filter) ([]Service, Warnings, error) | // GetServices returns a list of Services given the provided filters.
func (client *Client) GetServices(filters ...Filter) ([]Service, Warnings, error) | {
opts := requestOptions{
RequestName: internal.GetServicesRequest,
Query: ConvertFilterParameters(filters),
}
return client.makeServicesRequest(opts)
} |
cloudfoundry/cli | 5010c000047f246b870475e2c299556078cdad30 | actor/v2action/service_plan_visibility.go | https://github.com/cloudfoundry/cli/blob/5010c000047f246b870475e2c299556078cdad30/actor/v2action/service_plan_visibility.go#L11-L27 | go | train | // GetServicePlanVisibilities fetches service plan visibilities for a plan by GUID. | func (actor *Actor) GetServicePlanVisibilities(planGUID string) ([]ServicePlanVisibility, Warnings, error) | // GetServicePlanVisibilities fetches service plan visibilities for a plan by GUID.
func (actor *Actor) GetServicePlanVisibilities(planGUID string) ([]ServicePlanVisibility, Warnings, error) | {
visibilities, warnings, err := actor.CloudControllerClient.GetServicePlanVisibilities(ccv2.Filter{
Type: constant.ServicePlanGUIDFilter,
Operator: constant.EqualOperator,
Values: []string{planGUID},
})
if err != nil {
return nil, Warnings(warnings), err
}
var visibilitesToReturn []ServicePlanVisibility
for _, v := range visibilities {
visibilitesToReturn = append(visibilitesToReturn, ServicePlanVisibility(v))
}
return visibilitesToReturn, Warnings(warnings), nil
} |
cloudfoundry/cli | 5010c000047f246b870475e2c299556078cdad30 | api/cloudcontroller/ccv3/internal/routing.go | https://github.com/cloudfoundry/cli/blob/5010c000047f246b870475e2c299556078cdad30/api/cloudcontroller/ccv3/internal/routing.go#L73-L93 | go | train | // CreatePath combines the route's path pattern with a Params map
// to produce a valid path. | func (r Route) CreatePath(params Params) (string, error) | // CreatePath combines the route's path pattern with a Params map
// to produce a valid path.
func (r Route) CreatePath(params Params) (string, error) | {
components := strings.Split(r.Path, "/")
for i, c := range components {
if len(c) == 0 {
continue
}
if c[0] == ':' {
val, ok := params[c[1:]]
if !ok {
return "", fmt.Errorf("missing param %s", c)
}
components[i] = val
}
}
u, err := url.Parse(strings.Join(components, "/"))
if err != nil {
return "", err
}
return u.String(), nil
} |
cloudfoundry/cli | 5010c000047f246b870475e2c299556078cdad30 | api/cloudcontroller/ccv3/internal/routing.go | https://github.com/cloudfoundry/cli/blob/5010c000047f246b870475e2c299556078cdad30/api/cloudcontroller/ccv3/internal/routing.go#L103-L112 | go | train | // NewRouter returns a pointer to a new Router. | func NewRouter(routes []Route, resources map[string]string) *Router | // NewRouter returns a pointer to a new Router.
func NewRouter(routes []Route, resources map[string]string) *Router | {
mappedRoutes := map[string]Route{}
for _, route := range routes {
mappedRoutes[route.Name] = route
}
return &Router{
routes: mappedRoutes,
resources: resources,
}
} |
cloudfoundry/cli | 5010c000047f246b870475e2c299556078cdad30 | api/cloudcontroller/ccv3/internal/routing.go | https://github.com/cloudfoundry/cli/blob/5010c000047f246b870475e2c299556078cdad30/api/cloudcontroller/ccv3/internal/routing.go#L116-L138 | go | train | // CreateRequest returns a request key'd off of the name given. The params are
// merged into the URL and body is set as the request body. | func (router Router) CreateRequest(name string, params Params, body io.Reader) (*http.Request, error) | // CreateRequest returns a request key'd off of the name given. The params are
// merged into the URL and body is set as the request body.
func (router Router) CreateRequest(name string, params Params, body io.Reader) (*http.Request, error) | {
route, ok := router.routes[name]
if !ok {
return &http.Request{}, fmt.Errorf("no route exists with the name %s", name)
}
uri, err := route.CreatePath(params)
if err != nil {
return &http.Request{}, err
}
resource, ok := router.resources[route.Resource]
if !ok {
return &http.Request{}, fmt.Errorf("no resource exists with the name %s", route.Resource)
}
url, err := router.urlFrom(resource, uri)
if err != nil {
return &http.Request{}, err
}
return http.NewRequest(route.Method, url, body)
} |
cloudfoundry/cli | 5010c000047f246b870475e2c299556078cdad30 | api/uaa/client.go | https://github.com/cloudfoundry/cli/blob/5010c000047f246b870475e2c299556078cdad30/api/uaa/client.go#L27-L45 | go | train | // NewClient returns a new UAA Client with the provided configuration | func NewClient(config Config) *Client | // NewClient returns a new UAA Client with the provided configuration
func NewClient(config Config) *Client | {
userAgent := fmt.Sprintf("%s/%s (%s; %s %s)",
config.BinaryName(),
config.BinaryVersion(),
runtime.Version(),
runtime.GOARCH,
runtime.GOOS,
)
client := Client{
config: config,
connection: NewConnection(config.SkipSSLValidation(), config.UAADisableKeepAlives(), config.DialTimeout()),
userAgent: userAgent,
}
client.WrapConnection(NewErrorWrapper())
return &client
} |
cloudfoundry/cli | 5010c000047f246b870475e2c299556078cdad30 | util/ui/ui.go | https://github.com/cloudfoundry/cli/blob/5010c000047f246b870475e2c299556078cdad30/util/ui/ui.go#L99-L122 | go | train | // NewUI will return a UI object where Out is set to STDOUT, In is set to
// STDIN, and Err is set to STDERR | func NewUI(config Config) (*UI, error) | // NewUI will return a UI object where Out is set to STDOUT, In is set to
// STDIN, and Err is set to STDERR
func NewUI(config Config) (*UI, error) | {
translateFunc, err := GetTranslationFunc(config)
if err != nil {
return nil, err
}
location := time.Now().Location()
return &UI{
In: os.Stdin,
Out: color.Output,
OutForInteration: os.Stdout,
Err: os.Stderr,
colorEnabled: config.ColorEnabled(),
translate: translateFunc,
terminalLock: &sync.Mutex{},
Exiter: realExiter,
fileLock: &sync.Mutex{},
Interactor: realInteract,
IsTTY: config.IsTTY(),
TerminalWidth: config.TerminalWidth(),
TimezoneLocation: location,
}, nil
} |
cloudfoundry/cli | 5010c000047f246b870475e2c299556078cdad30 | util/ui/ui.go | https://github.com/cloudfoundry/cli/blob/5010c000047f246b870475e2c299556078cdad30/util/ui/ui.go#L157-L170 | go | train | // DisplayError outputs the translated error message to ui.Err if the error
// satisfies TranslatableError, otherwise it outputs the original error message
// to ui.Err. It also outputs "FAILED" in bold red to ui.Out. | func (ui *UI) DisplayError(err error) | // DisplayError outputs the translated error message to ui.Err if the error
// satisfies TranslatableError, otherwise it outputs the original error message
// to ui.Err. It also outputs "FAILED" in bold red to ui.Out.
func (ui *UI) DisplayError(err error) | {
var errMsg string
if translatableError, ok := err.(translatableerror.TranslatableError); ok {
errMsg = translatableError.Translate(ui.translate)
} else {
errMsg = err.Error()
}
fmt.Fprintf(ui.Err, "%s\n", errMsg)
ui.terminalLock.Lock()
defer ui.terminalLock.Unlock()
fmt.Fprintf(ui.Out, "%s\n", ui.modifyColor(ui.TranslateText("FAILED"), color.New(color.FgRed, color.Bold)))
} |
cloudfoundry/cli | 5010c000047f246b870475e2c299556078cdad30 | util/ui/ui.go | https://github.com/cloudfoundry/cli/blob/5010c000047f246b870475e2c299556078cdad30/util/ui/ui.go#L181-L186 | go | train | // DisplayHeader translates the header, bolds and adds the default color to the
// header, and outputs the result to ui.Out. | func (ui *UI) DisplayHeader(text string) | // DisplayHeader translates the header, bolds and adds the default color to the
// header, and outputs the result to ui.Out.
func (ui *UI) DisplayHeader(text string) | {
ui.terminalLock.Lock()
defer ui.terminalLock.Unlock()
fmt.Fprintf(ui.Out, "%s\n", ui.modifyColor(ui.TranslateText(text), color.New(color.Bold)))
} |
cloudfoundry/cli | 5010c000047f246b870475e2c299556078cdad30 | util/ui/ui.go | https://github.com/cloudfoundry/cli/blob/5010c000047f246b870475e2c299556078cdad30/util/ui/ui.go#L189-L194 | go | train | // DisplayNewline outputs a newline to UI.Out. | func (ui *UI) DisplayNewline() | // DisplayNewline outputs a newline to UI.Out.
func (ui *UI) DisplayNewline() | {
ui.terminalLock.Lock()
defer ui.terminalLock.Unlock()
fmt.Fprintf(ui.Out, "\n")
} |
cloudfoundry/cli | 5010c000047f246b870475e2c299556078cdad30 | util/ui/ui.go | https://github.com/cloudfoundry/cli/blob/5010c000047f246b870475e2c299556078cdad30/util/ui/ui.go#L197-L202 | go | train | // DisplayOK outputs a bold green translated "OK" to UI.Out. | func (ui *UI) DisplayOK() | // DisplayOK outputs a bold green translated "OK" to UI.Out.
func (ui *UI) DisplayOK() | {
ui.terminalLock.Lock()
defer ui.terminalLock.Unlock()
fmt.Fprintf(ui.Out, "%s\n\n", ui.modifyColor(ui.TranslateText("OK"), color.New(color.FgGreen, color.Bold)))
} |
cloudfoundry/cli | 5010c000047f246b870475e2c299556078cdad30 | util/ui/ui.go | https://github.com/cloudfoundry/cli/blob/5010c000047f246b870475e2c299556078cdad30/util/ui/ui.go#L206-L211 | go | train | // DisplayText translates the template, substitutes in templateValues, and
// outputs the result to ui.Out. Only the first map in templateValues is used. | func (ui *UI) DisplayText(template string, templateValues ...map[string]interface{}) | // DisplayText translates the template, substitutes in templateValues, and
// outputs the result to ui.Out. Only the first map in templateValues is used.
func (ui *UI) DisplayText(template string, templateValues ...map[string]interface{}) | {
ui.terminalLock.Lock()
defer ui.terminalLock.Unlock()
fmt.Fprintf(ui.Out, "%s\n", ui.TranslateText(template, templateValues...))
} |
cloudfoundry/cli | 5010c000047f246b870475e2c299556078cdad30 | util/ui/ui.go | https://github.com/cloudfoundry/cli/blob/5010c000047f246b870475e2c299556078cdad30/util/ui/ui.go#L230-L239 | go | train | // DisplayTextWithFlavor translates the template, bolds and adds cyan color to
// templateValues, substitutes templateValues into the template, and outputs
// the result to ui.Out. Only the first map in templateValues is used. | func (ui *UI) DisplayTextWithFlavor(template string, templateValues ...map[string]interface{}) | // DisplayTextWithFlavor translates the template, bolds and adds cyan color to
// templateValues, substitutes templateValues into the template, and outputs
// the result to ui.Out. Only the first map in templateValues is used.
func (ui *UI) DisplayTextWithFlavor(template string, templateValues ...map[string]interface{}) | {
ui.terminalLock.Lock()
defer ui.terminalLock.Unlock()
firstTemplateValues := getFirstSet(templateValues)
for key, value := range firstTemplateValues {
firstTemplateValues[key] = ui.modifyColor(fmt.Sprint(value), color.New(color.FgCyan, color.Bold))
}
fmt.Fprintf(ui.Out, "%s\n", ui.TranslateText(template, firstTemplateValues))
} |
cloudfoundry/cli | 5010c000047f246b870475e2c299556078cdad30 | util/ui/ui.go | https://github.com/cloudfoundry/cli/blob/5010c000047f246b870475e2c299556078cdad30/util/ui/ui.go#L243-L245 | go | train | // DisplayWarning translates the warning, substitutes in templateValues, and
// outputs to ui.Err. Only the first map in templateValues is used. | func (ui *UI) DisplayWarning(template string, templateValues ...map[string]interface{}) | // DisplayWarning translates the warning, substitutes in templateValues, and
// outputs to ui.Err. Only the first map in templateValues is used.
func (ui *UI) DisplayWarning(template string, templateValues ...map[string]interface{}) | {
fmt.Fprintf(ui.Err, "%s\n\n", ui.TranslateText(template, templateValues...))
} |
cloudfoundry/cli | 5010c000047f246b870475e2c299556078cdad30 | util/ui/ui.go | https://github.com/cloudfoundry/cli/blob/5010c000047f246b870475e2c299556078cdad30/util/ui/ui.go#L248-L255 | go | train | // DisplayWarnings translates the warnings and outputs to ui.Err. | func (ui *UI) DisplayWarnings(warnings []string) | // DisplayWarnings translates the warnings and outputs to ui.Err.
func (ui *UI) DisplayWarnings(warnings []string) | {
for _, warning := range warnings {
fmt.Fprintf(ui.Err, "%s\n", ui.TranslateText(warning))
}
if len(warnings) > 0 {
fmt.Fprintln(ui.Err)
}
} |
cloudfoundry/cli | 5010c000047f246b870475e2c299556078cdad30 | util/ui/ui.go | https://github.com/cloudfoundry/cli/blob/5010c000047f246b870475e2c299556078cdad30/util/ui/ui.go#L275-L277 | go | train | // TranslateText passes the template through an internationalization function
// to translate it to a pre-configured language, and returns the template with
// templateValues substituted in. Only the first map in templateValues is used. | func (ui *UI) TranslateText(template string, templateValues ...map[string]interface{}) string | // TranslateText passes the template through an internationalization function
// to translate it to a pre-configured language, and returns the template with
// templateValues substituted in. Only the first map in templateValues is used.
func (ui *UI) TranslateText(template string, templateValues ...map[string]interface{}) string | {
return ui.translate(template, getFirstSet(templateValues))
} |
cloudfoundry/cli | 5010c000047f246b870475e2c299556078cdad30 | util/ui/ui.go | https://github.com/cloudfoundry/cli/blob/5010c000047f246b870475e2c299556078cdad30/util/ui/ui.go#L280-L282 | go | train | // UserFriendlyDate converts the time to UTC and then formats it to ISO8601. | func (ui *UI) UserFriendlyDate(input time.Time) string | // UserFriendlyDate converts the time to UTC and then formats it to ISO8601.
func (ui *UI) UserFriendlyDate(input time.Time) string | {
return input.Local().Format("Mon 02 Jan 15:04:05 MST 2006")
} |
cloudfoundry/cli | 5010c000047f246b870475e2c299556078cdad30 | util/configv3/plugin_repository.go | https://github.com/cloudfoundry/cli/blob/5010c000047f246b870475e2c299556078cdad30/util/configv3/plugin_repository.go#L24-L27 | go | train | // AddPluginRepository adds an new repository to the plugin config. It does not
// add duplicates to the config. | func (config *Config) AddPluginRepository(name string, url string) | // AddPluginRepository adds an new repository to the plugin config. It does not
// add duplicates to the config.
func (config *Config) AddPluginRepository(name string, url string) | {
config.ConfigFile.PluginRepositories = append(config.ConfigFile.PluginRepositories,
PluginRepository{Name: name, URL: url})
} |
cloudfoundry/cli | 5010c000047f246b870475e2c299556078cdad30 | util/configv3/plugin_repository.go | https://github.com/cloudfoundry/cli/blob/5010c000047f246b870475e2c299556078cdad30/util/configv3/plugin_repository.go#L31-L37 | go | train | // PluginRepositories returns the currently configured plugin repositories from the
// .cf/config.json. | func (config *Config) PluginRepositories() []PluginRepository | // PluginRepositories returns the currently configured plugin repositories from the
// .cf/config.json.
func (config *Config) PluginRepositories() []PluginRepository | {
repos := config.ConfigFile.PluginRepositories
sort.Slice(repos, func(i, j int) bool {
return strings.ToLower(repos[i].Name) < strings.ToLower(repos[j].Name)
})
return repos
} |
cloudfoundry/cli | 5010c000047f246b870475e2c299556078cdad30 | util/ui/ui_for_push.go | https://github.com/cloudfoundry/cli/blob/5010c000047f246b870475e2c299556078cdad30/util/ui/ui_for_push.go#L26-L69 | go | train | // DisplayChangeForPush will display the header and old/new value with the
// appropriately red/green minuses and pluses. | func (ui *UI) DisplayChangeForPush(header string, stringTypePadding int, hiddenValue bool, originalValue interface{}, newValue interface{}) error | // DisplayChangeForPush will display the header and old/new value with the
// appropriately red/green minuses and pluses.
func (ui *UI) DisplayChangeForPush(header string, stringTypePadding int, hiddenValue bool, originalValue interface{}, newValue interface{}) error | {
ui.terminalLock.Lock()
defer ui.terminalLock.Unlock()
originalType := reflect.ValueOf(originalValue).Type()
newType := reflect.ValueOf(newValue).Type()
if originalType != newType {
return ErrValueMissmatch
}
offset := strings.Repeat(" ", stringTypePadding)
switch oVal := originalValue.(type) {
case int:
nVal := newValue.(int)
ui.displayDiffForInt(offset, header, oVal, nVal)
case types.NullInt:
nVal := newValue.(types.NullInt)
ui.displayDiffForNullInt(offset, header, oVal, nVal)
case uint64:
nVal := newValue.(uint64)
ui.displayDiffForUint64(offset, header, oVal, nVal)
case string:
nVal := newValue.(string)
ui.displayDiffForString(offset, header, hiddenValue, oVal, nVal)
case []string:
nVal := newValue.([]string)
if len(oVal) == 0 && len(nVal) == 0 {
return nil
}
ui.displayDiffForStrings(offset, header, oVal, nVal)
case map[string]string:
nVal := newValue.(map[string]string)
if len(oVal) == 0 && len(nVal) == 0 {
return nil
}
ui.displayDiffForMapStringString(offset, header, oVal, nVal)
default:
panic(fmt.Sprintf("diff display does not have case for '%s'", header))
}
return nil
} |
cloudfoundry/cli | 5010c000047f246b870475e2c299556078cdad30 | util/ui/ui_for_push.go | https://github.com/cloudfoundry/cli/blob/5010c000047f246b870475e2c299556078cdad30/util/ui/ui_for_push.go#L73-L94 | go | train | // DisplayChangesForPush will display the set of changes via
// DisplayChangeForPush in the order given. | func (ui *UI) DisplayChangesForPush(changeSet []Change) error | // DisplayChangesForPush will display the set of changes via
// DisplayChangeForPush in the order given.
func (ui *UI) DisplayChangesForPush(changeSet []Change) error | {
if len(changeSet) == 0 {
return nil
}
var columnWidth int
for _, change := range changeSet {
if width := wordSize(ui.TranslateText(change.Header)); width > columnWidth {
columnWidth = width
}
}
for _, change := range changeSet {
padding := columnWidth - wordSize(ui.TranslateText(change.Header)) + 3
err := ui.DisplayChangeForPush(change.Header, padding, change.HiddenValue, change.CurrentValue, change.NewValue)
if err != nil {
return err
}
}
return nil
} |
cloudfoundry/cli | 5010c000047f246b870475e2c299556078cdad30 | actor/v7action/application_summary.go | https://github.com/cloudfoundry/cli/blob/5010c000047f246b870475e2c299556078cdad30/actor/v7action/application_summary.go#L38-L77 | go | train | // GetApplicationSummaryByNameAndSpace returns an application with process and
// instance stats. | func (actor Actor) GetApplicationSummaryByNameAndSpace(appName string, spaceGUID string, withObfuscatedValues bool, routeActor RouteActor) (ApplicationSummary, Warnings, error) | // GetApplicationSummaryByNameAndSpace returns an application with process and
// instance stats.
func (actor Actor) GetApplicationSummaryByNameAndSpace(appName string, spaceGUID string, withObfuscatedValues bool, routeActor RouteActor) (ApplicationSummary, Warnings, error) | {
app, allWarnings, err := actor.GetApplicationByNameAndSpace(appName, spaceGUID)
if err != nil {
return ApplicationSummary{}, allWarnings, err
}
processSummaries, processWarnings, err := actor.getProcessSummariesForApp(app.GUID, withObfuscatedValues)
allWarnings = append(allWarnings, processWarnings...)
if err != nil {
return ApplicationSummary{}, allWarnings, err
}
droplet, warnings, err := actor.GetCurrentDropletByApplication(app.GUID)
allWarnings = append(allWarnings, warnings...)
if err != nil {
if _, ok := err.(actionerror.DropletNotFoundError); !ok {
return ApplicationSummary{}, allWarnings, err
}
}
var appRoutes v2action.Routes
if routeActor != nil {
routes, warnings, err := routeActor.GetApplicationRoutes(app.GUID)
allWarnings = append(allWarnings, Warnings(warnings)...)
if err != nil {
if _, ok := err.(ccerror.ResourceNotFoundError); !ok {
return ApplicationSummary{}, allWarnings, err
}
}
appRoutes = routes
}
summary := ApplicationSummary{
Application: app,
ProcessSummaries: processSummaries,
CurrentDroplet: droplet,
Routes: appRoutes,
}
return summary, allWarnings, nil
} |
cloudfoundry/cli | 5010c000047f246b870475e2c299556078cdad30 | actor/v2action/service_instance.go | https://github.com/cloudfoundry/cli/blob/5010c000047f246b870475e2c299556078cdad30/actor/v2action/service_instance.go#L14-L29 | go | train | // CreateServiceInstance creates a new service instance with the provided attributes. | func (actor Actor) CreateServiceInstance(spaceGUID, serviceName, servicePlanName, serviceInstanceName, brokerName string, params map[string]interface{}, tags []string) (ServiceInstance, Warnings, error) | // CreateServiceInstance creates a new service instance with the provided attributes.
func (actor Actor) CreateServiceInstance(spaceGUID, serviceName, servicePlanName, serviceInstanceName, brokerName string, params map[string]interface{}, tags []string) (ServiceInstance, Warnings, error) | {
var allWarnings Warnings
plan, allWarnings, err := actor.getServicePlanForServiceInSpace(servicePlanName, serviceName, spaceGUID, brokerName)
if err != nil {
return ServiceInstance{}, allWarnings, err
}
instance, warnings, err := actor.CloudControllerClient.CreateServiceInstance(spaceGUID, plan.GUID, serviceInstanceName, params, tags)
allWarnings = append(allWarnings, warnings...)
if err != nil {
return ServiceInstance{}, allWarnings, err
}
return ServiceInstance(instance), allWarnings, nil
} |
cloudfoundry/cli | 5010c000047f246b870475e2c299556078cdad30 | actor/v2action/route.go | https://github.com/cloudfoundry/cli/blob/5010c000047f246b870475e2c299556078cdad30/actor/v2action/route.go#L19-L25 | go | train | // Summary converts routes into a comma separated string. | func (rs Routes) Summary() string | // Summary converts routes into a comma separated string.
func (rs Routes) Summary() string | {
formattedRoutes := []string{}
for _, route := range rs {
formattedRoutes = append(formattedRoutes, route.String())
}
return strings.Join(formattedRoutes, ", ")
} |
cloudfoundry/cli | 5010c000047f246b870475e2c299556078cdad30 | actor/v2action/route.go | https://github.com/cloudfoundry/cli/blob/5010c000047f246b870475e2c299556078cdad30/actor/v2action/route.go#L43-L57 | go | train | // Validate will return an error if there are invalid HTTP or TCP settings for
// it's given domain. | func (r Route) Validate() error | // Validate will return an error if there are invalid HTTP or TCP settings for
// it's given domain.
func (r Route) Validate() error | {
if r.Domain.IsHTTP() {
if r.Port.IsSet {
return actionerror.InvalidHTTPRouteSettings{Domain: r.Domain.Name}
}
if r.Domain.IsShared() && r.Host == "" {
return actionerror.NoHostnameAndSharedDomainError{}
}
} else { // Is TCP Domain
if r.Host != "" || r.Path != "" {
return actionerror.InvalidTCPRouteSettings{Domain: r.Domain.Name}
}
}
return nil
} |
cloudfoundry/cli | 5010c000047f246b870475e2c299556078cdad30 | actor/v2action/route.go | https://github.com/cloudfoundry/cli/blob/5010c000047f246b870475e2c299556078cdad30/actor/v2action/route.go#L62-L71 | go | train | // ValidateWithRandomPort will return an error if a random port is requested
// for an HTTP route, or if the route is TCP, a random port wasn't requested,
// and the route has no port set. | func (r Route) ValidateWithRandomPort(randomPort bool) error | // ValidateWithRandomPort will return an error if a random port is requested
// for an HTTP route, or if the route is TCP, a random port wasn't requested,
// and the route has no port set.
func (r Route) ValidateWithRandomPort(randomPort bool) error | {
if r.Domain.IsHTTP() && randomPort {
return actionerror.InvalidHTTPRouteSettings{Domain: r.Domain.Name}
}
if r.Domain.IsTCP() && !r.Port.IsSet && !randomPort {
return actionerror.TCPRouteOptionsNotProvidedError{}
}
return r.Validate()
} |
cloudfoundry/cli | 5010c000047f246b870475e2c299556078cdad30 | actor/v2action/route.go | https://github.com/cloudfoundry/cli/blob/5010c000047f246b870475e2c299556078cdad30/actor/v2action/route.go#L74-L92 | go | train | // String formats the route in a human readable format. | func (r Route) String() string | // String formats the route in a human readable format.
func (r Route) String() string | {
routeString := r.Domain.Name
if r.Port.IsSet {
routeString = fmt.Sprintf("%s:%d", routeString, r.Port.Value)
} else if r.RandomTCPPort() {
routeString = fmt.Sprintf("%s:????", routeString)
}
if r.Host != "" {
routeString = fmt.Sprintf("%s.%s", r.Host, routeString)
}
if r.Path != "" {
routeString = path.Join(routeString, r.Path)
}
return routeString
} |
cloudfoundry/cli | 5010c000047f246b870475e2c299556078cdad30 | actor/v2action/route.go | https://github.com/cloudfoundry/cli/blob/5010c000047f246b870475e2c299556078cdad30/actor/v2action/route.go#L165-L194 | go | train | // GetOrphanedRoutesBySpace returns a list of orphaned routes associated with
// the provided Space GUID. | func (actor Actor) GetOrphanedRoutesBySpace(spaceGUID string) ([]Route, Warnings, error) | // GetOrphanedRoutesBySpace returns a list of orphaned routes associated with
// the provided Space GUID.
func (actor Actor) GetOrphanedRoutesBySpace(spaceGUID string) ([]Route, Warnings, error) | {
var (
orphanedRoutes []Route
allWarnings Warnings
)
routes, warnings, err := actor.GetSpaceRoutes(spaceGUID)
allWarnings = append(allWarnings, warnings...)
if err != nil {
return nil, allWarnings, err
}
for _, route := range routes {
apps, warnings, err := actor.GetRouteApplications(route.GUID)
allWarnings = append(allWarnings, warnings...)
if err != nil {
return nil, allWarnings, err
}
if len(apps) == 0 {
orphanedRoutes = append(orphanedRoutes, route)
}
}
if len(orphanedRoutes) == 0 {
return nil, allWarnings, actionerror.OrphanedRoutesNotFoundError{}
}
return orphanedRoutes, allWarnings, nil
} |
cloudfoundry/cli | 5010c000047f246b870475e2c299556078cdad30 | actor/v2action/route.go | https://github.com/cloudfoundry/cli/blob/5010c000047f246b870475e2c299556078cdad30/actor/v2action/route.go#L198-L209 | go | train | // GetApplicationRoutes returns a list of routes associated with the provided
// Application GUID. | func (actor Actor) GetApplicationRoutes(applicationGUID string) (Routes, Warnings, error) | // GetApplicationRoutes returns a list of routes associated with the provided
// Application GUID.
func (actor Actor) GetApplicationRoutes(applicationGUID string) (Routes, Warnings, error) | {
var allWarnings Warnings
ccv2Routes, warnings, err := actor.CloudControllerClient.GetApplicationRoutes(applicationGUID)
allWarnings = append(allWarnings, warnings...)
if err != nil {
return nil, allWarnings, err
}
routes, domainWarnings, err := actor.applyDomain(ccv2Routes)
return routes, append(allWarnings, domainWarnings...), err
} |
cloudfoundry/cli | 5010c000047f246b870475e2c299556078cdad30 | actor/v2action/route.go | https://github.com/cloudfoundry/cli/blob/5010c000047f246b870475e2c299556078cdad30/actor/v2action/route.go#L213-L224 | go | train | // GetSpaceRoutes returns a list of routes associated with the provided Space
// GUID. | func (actor Actor) GetSpaceRoutes(spaceGUID string) ([]Route, Warnings, error) | // GetSpaceRoutes returns a list of routes associated with the provided Space
// GUID.
func (actor Actor) GetSpaceRoutes(spaceGUID string) ([]Route, Warnings, error) | {
var allWarnings Warnings
ccv2Routes, warnings, err := actor.CloudControllerClient.GetSpaceRoutes(spaceGUID)
allWarnings = append(allWarnings, warnings...)
if err != nil {
return nil, allWarnings, err
}
routes, domainWarnings, err := actor.applyDomain(ccv2Routes)
return routes, append(allWarnings, domainWarnings...), err
} |
cloudfoundry/cli | 5010c000047f246b870475e2c299556078cdad30 | actor/v2action/route.go | https://github.com/cloudfoundry/cli/blob/5010c000047f246b870475e2c299556078cdad30/actor/v2action/route.go#L227-L230 | go | train | // DeleteUnmappedRoutes deletes the unmapped routes associated with the provided Space GUID. | func (actor Actor) DeleteUnmappedRoutes(spaceGUID string) (Warnings, error) | // DeleteUnmappedRoutes deletes the unmapped routes associated with the provided Space GUID.
func (actor Actor) DeleteUnmappedRoutes(spaceGUID string) (Warnings, error) | {
warnings, err := actor.CloudControllerClient.DeleteSpaceUnmappedRoutes(spaceGUID)
return Warnings(warnings), err
} |
cloudfoundry/cli | 5010c000047f246b870475e2c299556078cdad30 | actor/v2action/route.go | https://github.com/cloudfoundry/cli/blob/5010c000047f246b870475e2c299556078cdad30/actor/v2action/route.go#L233-L236 | go | train | // DeleteRoute deletes the Route associated with the provided Route GUID. | func (actor Actor) DeleteRoute(routeGUID string) (Warnings, error) | // DeleteRoute deletes the Route associated with the provided Route GUID.
func (actor Actor) DeleteRoute(routeGUID string) (Warnings, error) | {
warnings, err := actor.CloudControllerClient.DeleteRoute(routeGUID)
return Warnings(warnings), err
} |
cloudfoundry/cli | 5010c000047f246b870475e2c299556078cdad30 | actor/v2action/route.go | https://github.com/cloudfoundry/cli/blob/5010c000047f246b870475e2c299556078cdad30/actor/v2action/route.go#L248-L285 | go | train | // FindRouteBoundToSpaceWithSettings finds the route with the given host,
// domain and space. If it is unable to find the route, it will check if it
// exists anywhere in the system. When the route exists in another space,
// RouteInDifferentSpaceError is returned. Use this when you know the space
// GUID. | func (actor Actor) FindRouteBoundToSpaceWithSettings(route Route) (Route, Warnings, error) | // FindRouteBoundToSpaceWithSettings finds the route with the given host,
// domain and space. If it is unable to find the route, it will check if it
// exists anywhere in the system. When the route exists in another space,
// RouteInDifferentSpaceError is returned. Use this when you know the space
// GUID.
func (actor Actor) FindRouteBoundToSpaceWithSettings(route Route) (Route, Warnings, error) | {
existingRoute, warnings, err := actor.GetRouteByComponents(route)
if routeNotFoundErr, ok := err.(actionerror.RouteNotFoundError); ok {
// This check only works for API versions 2.55 or higher. It will return
// false for anything below that.
log.Infof("checking route existence for: %s\n", route)
exists, checkRouteWarnings, chkErr := actor.CheckRoute(route)
if chkErr != nil {
log.Errorln("check route:", err)
return Route{}, append(Warnings(warnings), checkRouteWarnings...), chkErr
}
// This will happen if the route exists in a space to which the user does
// not have access.
if exists {
log.Errorf("unable to find route %s in current space", route.String())
return Route{}, append(Warnings(warnings), checkRouteWarnings...), actionerror.RouteInDifferentSpaceError{Route: route.String()}
}
log.Warnf("negative existence check for route %s - returning partial route", route.String())
log.Debugf("partialRoute: %#v", route)
return Route{}, append(Warnings(warnings), checkRouteWarnings...), routeNotFoundErr
} else if err != nil {
log.Errorln("finding route:", err)
return Route{}, Warnings(warnings), err
}
if existingRoute.SpaceGUID != route.SpaceGUID {
log.WithFields(log.Fields{
"targeted_space_guid": route.SpaceGUID,
"existing_space_guid": existingRoute.SpaceGUID,
}).Errorf("route exists in different space the user has access to")
return Route{}, Warnings(warnings), actionerror.RouteInDifferentSpaceError{Route: route.String()}
}
log.Debugf("found route: %#v", existingRoute)
return existingRoute, Warnings(warnings), err
} |
cloudfoundry/cli | 5010c000047f246b870475e2c299556078cdad30 | actor/v2action/route.go | https://github.com/cloudfoundry/cli/blob/5010c000047f246b870475e2c299556078cdad30/actor/v2action/route.go#L291-L340 | go | train | // GetRouteByComponents returns the route with the matching host, domain, path,
// and port. Use this when you don't know the space GUID.
// TCP routes require a port to be uniquely identified
// HTTP routes using shared domains require a hostname or path to be uniquely identified | func (actor Actor) GetRouteByComponents(route Route) (Route, Warnings, error) | // GetRouteByComponents returns the route with the matching host, domain, path,
// and port. Use this when you don't know the space GUID.
// TCP routes require a port to be uniquely identified
// HTTP routes using shared domains require a hostname or path to be uniquely identified
func (actor Actor) GetRouteByComponents(route Route) (Route, Warnings, error) | {
// TODO: validation should probably be done separately (?)
if route.Domain.IsTCP() && !route.Port.IsSet {
return Route{}, nil, actionerror.PortNotProvidedForQueryError{}
}
if route.Domain.IsShared() && route.Domain.IsHTTP() && route.Host == "" {
return Route{}, nil, actionerror.NoHostnameAndSharedDomainError{}
}
queries := []ccv2.Filter{
{
Type: constant.DomainGUIDFilter,
Operator: constant.EqualOperator,
Values: []string{route.Domain.GUID},
}, {
Type: constant.HostFilter,
Operator: constant.EqualOperator,
Values: []string{route.Host},
}, {
Type: constant.PathFilter,
Operator: constant.EqualOperator,
Values: []string{route.Path},
},
}
if route.Port.IsSet {
queries = append(queries, ccv2.Filter{
Type: constant.PortFilter,
Operator: constant.EqualOperator,
Values: []string{fmt.Sprint(route.Port.Value)},
})
}
ccv2Routes, warnings, err := actor.CloudControllerClient.GetRoutes(queries...)
if err != nil {
return Route{}, Warnings(warnings), err
}
if len(ccv2Routes) == 0 {
return Route{}, Warnings(warnings), actionerror.RouteNotFoundError{
Host: route.Host,
DomainGUID: route.Domain.GUID,
Path: route.Path,
Port: route.Port.Value,
}
}
return CCToActorRoute(ccv2Routes[0], route.Domain), Warnings(warnings), err
} |
cloudfoundry/cli | 5010c000047f246b870475e2c299556078cdad30 | actor/sharedaction/resource.go | https://github.com/cloudfoundry/cli/blob/5010c000047f246b870475e2c299556078cdad30/actor/sharedaction/resource.go#L49-L56 | go | train | // ToV3Resource converts a sharedaction Resource to V3 Resource format | func (r Resource) ToV3Resource() V3Resource | // ToV3Resource converts a sharedaction Resource to V3 Resource format
func (r Resource) ToV3Resource() V3Resource | {
return V3Resource{
FilePath: r.Filename,
Mode: r.Mode,
Checksum: ccv3.Checksum{Value: r.SHA1},
SizeInBytes: r.Size,
}
} |
cloudfoundry/cli | 5010c000047f246b870475e2c299556078cdad30 | actor/sharedaction/resource.go | https://github.com/cloudfoundry/cli/blob/5010c000047f246b870475e2c299556078cdad30/actor/sharedaction/resource.go#L59-L66 | go | train | // ToV2Resource converts a V3 Resource to V2 Resource format | func (r V3Resource) ToV2Resource() Resource | // ToV2Resource converts a V3 Resource to V2 Resource format
func (r V3Resource) ToV2Resource() Resource | {
return Resource{
Filename: r.FilePath,
Mode: r.Mode,
SHA1: r.Checksum.Value,
Size: r.SizeInBytes,
}
} |
cloudfoundry/cli | 5010c000047f246b870475e2c299556078cdad30 | actor/sharedaction/resource.go | https://github.com/cloudfoundry/cli/blob/5010c000047f246b870475e2c299556078cdad30/actor/sharedaction/resource.go#L69-L128 | go | train | // GatherArchiveResources returns a list of resources for an archive. | func (actor Actor) GatherArchiveResources(archivePath string) ([]Resource, error) | // GatherArchiveResources returns a list of resources for an archive.
func (actor Actor) GatherArchiveResources(archivePath string) ([]Resource, error) | {
var resources []Resource
archive, err := os.Open(archivePath)
if err != nil {
return nil, err
}
defer archive.Close()
reader, err := actor.newArchiveReader(archive)
if err != nil {
return nil, err
}
gitIgnore, err := actor.generateArchiveCFIgnoreMatcher(reader.File)
if err != nil {
log.Errorln("reading .cfignore file:", err)
return nil, err
}
for _, archivedFile := range reader.File {
filename := filepath.ToSlash(archivedFile.Name)
if gitIgnore.MatchesPath(filename) {
continue
}
resource := Resource{Filename: filename}
info := archivedFile.FileInfo()
switch {
case info.IsDir():
resource.Mode = DefaultFolderPermissions
case info.Mode()&os.ModeSymlink == os.ModeSymlink:
resource.Mode = info.Mode()
default:
fileReader, err := archivedFile.Open()
if err != nil {
return nil, err
}
defer fileReader.Close()
hash := sha1.New()
_, err = io.Copy(hash, fileReader)
if err != nil {
return nil, err
}
resource.Mode = DefaultArchiveFilePermissions
resource.SHA1 = fmt.Sprintf("%x", hash.Sum(nil))
resource.Size = archivedFile.FileInfo().Size()
}
resources = append(resources, resource)
}
if len(resources) <= 1 {
return nil, actionerror.EmptyArchiveError{Path: archivePath}
}
return resources, nil
} |
cloudfoundry/cli | 5010c000047f246b870475e2c299556078cdad30 | actor/sharedaction/resource.go | https://github.com/cloudfoundry/cli/blob/5010c000047f246b870475e2c299556078cdad30/actor/sharedaction/resource.go#L131-L210 | go | train | // GatherDirectoryResources returns a list of resources for a directory. | func (actor Actor) GatherDirectoryResources(sourceDir string) ([]Resource, error) | // GatherDirectoryResources returns a list of resources for a directory.
func (actor Actor) GatherDirectoryResources(sourceDir string) ([]Resource, error) | {
var (
resources []Resource
gitIgnore *ignore.GitIgnore
)
gitIgnore, err := actor.generateDirectoryCFIgnoreMatcher(sourceDir)
if err != nil {
log.Errorln("reading .cfignore file:", err)
return nil, err
}
evalDir, err := filepath.EvalSymlinks(sourceDir)
if err != nil {
log.Errorln("evaluating symlink:", err)
return nil, err
}
walkErr := filepath.Walk(evalDir, func(fullPath string, info os.FileInfo, err error) error {
if err != nil {
return err
}
relPath, err := filepath.Rel(evalDir, fullPath)
if err != nil {
return err
}
// if file ignored continue to the next file
if gitIgnore.MatchesPath(relPath) {
return nil
}
if relPath == "." {
return nil
}
resource := Resource{
Filename: filepath.ToSlash(relPath),
}
switch {
case info.IsDir():
// If the file is a directory
resource.Mode = DefaultFolderPermissions
case info.Mode()&os.ModeSymlink == os.ModeSymlink:
// If the file is a Symlink we just set the mode of the file
// We won't be using any sha information since we don't do
// any resource matching on symlinks.
resource.Mode = fixMode(info.Mode())
default:
// If the file is regular we want to open
// and calculate the sha of the file
file, err := os.Open(fullPath)
if err != nil {
return err
}
defer file.Close()
sum := sha1.New()
_, err = io.Copy(sum, file)
if err != nil {
return err
}
resource.Mode = fixMode(info.Mode())
resource.SHA1 = fmt.Sprintf("%x", sum.Sum(nil))
resource.Size = info.Size()
}
resources = append(resources, resource)
return nil
})
if len(resources) == 0 {
return nil, actionerror.EmptyDirectoryError{Path: sourceDir}
}
return resources, walkErr
} |
cloudfoundry/cli | 5010c000047f246b870475e2c299556078cdad30 | actor/sharedaction/resource.go | https://github.com/cloudfoundry/cli/blob/5010c000047f246b870475e2c299556078cdad30/actor/sharedaction/resource.go#L215-L270 | go | train | // ZipArchiveResources zips an archive and a sorted (based on full
// path/filename) list of resources and returns the location. On Windows, the
// filemode for user is forced to be readable and executable. | func (actor Actor) ZipArchiveResources(sourceArchivePath string, filesToInclude []Resource) (string, error) | // ZipArchiveResources zips an archive and a sorted (based on full
// path/filename) list of resources and returns the location. On Windows, the
// filemode for user is forced to be readable and executable.
func (actor Actor) ZipArchiveResources(sourceArchivePath string, filesToInclude []Resource) (string, error) | {
log.WithField("sourceArchive", sourceArchivePath).Info("zipping source files from archive")
zipFile, err := ioutil.TempFile("", "cf-cli-")
if err != nil {
return "", err
}
defer zipFile.Close()
zipPath := zipFile.Name()
writer := zip.NewWriter(zipFile)
defer writer.Close()
source, err := os.Open(sourceArchivePath)
if err != nil {
return zipPath, err
}
defer source.Close()
reader, err := actor.newArchiveReader(source)
if err != nil {
return zipPath, err
}
for _, archiveFile := range reader.File {
resource, ok := actor.findInResources(archiveFile.Name, filesToInclude)
if !ok {
log.WithField("archiveFileName", archiveFile.Name).Debug("skipping file")
continue
}
log.WithField("archiveFileName", archiveFile.Name).Debug("zipping file")
// archiveFile.Open opens the symlink file, not the file it points too
reader, openErr := archiveFile.Open()
if openErr != nil {
log.WithField("archiveFile", archiveFile.Name).Errorln("opening path in dir:", openErr)
return zipPath, openErr
}
defer reader.Close()
err = actor.addFileToZipFromFileSystem(
resource.Filename, reader, archiveFile.FileInfo(),
resource, writer,
)
if err != nil {
log.WithField("archiveFileName", archiveFile.Name).Errorln("zipping file:", err)
return zipPath, err
}
reader.Close()
}
log.WithFields(log.Fields{
"zip_file_location": zipFile.Name(),
"zipped_file_count": len(filesToInclude),
}).Info("zip file created")
return zipPath, nil
} |
cloudfoundry/cli | 5010c000047f246b870475e2c299556078cdad30 | actor/sharedaction/resource.go | https://github.com/cloudfoundry/cli/blob/5010c000047f246b870475e2c299556078cdad30/actor/sharedaction/resource.go#L275-L330 | go | train | // ZipDirectoryResources zips a directory and a sorted (based on full
// path/filename) list of resources and returns the location. On Windows, the
// filemode for user is forced to be readable and executable. | func (actor Actor) ZipDirectoryResources(sourceDir string, filesToInclude []Resource) (string, error) | // ZipDirectoryResources zips a directory and a sorted (based on full
// path/filename) list of resources and returns the location. On Windows, the
// filemode for user is forced to be readable and executable.
func (actor Actor) ZipDirectoryResources(sourceDir string, filesToInclude []Resource) (string, error) | {
log.WithField("sourceDir", sourceDir).Info("zipping source files from directory")
zipFile, err := ioutil.TempFile("", "cf-cli-")
if err != nil {
return "", err
}
defer zipFile.Close()
zipPath := zipFile.Name()
writer := zip.NewWriter(zipFile)
defer writer.Close()
for _, resource := range filesToInclude {
fullPath := filepath.Join(sourceDir, resource.Filename)
log.WithField("fullPath", fullPath).Debug("zipping file")
fileInfo, err := os.Lstat(fullPath)
if err != nil {
log.WithField("fullPath", fullPath).Errorln("stat error in dir:", err)
return zipPath, err
}
log.WithField("file-mode", fileInfo.Mode().String()).Debug("resource file info")
if fileInfo.Mode()&os.ModeSymlink == os.ModeSymlink {
// we need to user os.Readlink to read a symlink file from a directory
err = actor.addLinkToZipFromFileSystem(fullPath, fileInfo, resource, writer)
if err != nil {
log.WithField("fullPath", fullPath).Errorln("zipping file:", err)
return zipPath, err
}
} else {
srcFile, err := os.Open(fullPath)
if err != nil {
log.WithField("fullPath", fullPath).Errorln("opening path in dir:", err)
return zipPath, err
}
defer srcFile.Close()
err = actor.addFileToZipFromFileSystem(
fullPath, srcFile, fileInfo,
resource, writer,
)
srcFile.Close()
if err != nil {
log.WithField("fullPath", fullPath).Errorln("zipping file:", err)
return zipPath, err
}
}
}
log.WithFields(log.Fields{
"zip_file_location": zipFile.Name(),
"zipped_file_count": len(filesToInclude),
}).Info("zip file created")
return zipPath, nil
} |
cloudfoundry/cli | 5010c000047f246b870475e2c299556078cdad30 | api/cloudcontroller/ccv2/application.go | https://github.com/cloudfoundry/cli/blob/5010c000047f246b870475e2c299556078cdad30/api/cloudcontroller/ccv2/application.go#L89-L149 | go | train | // MarshalJSON converts an application into a Cloud Controller Application. | func (application Application) MarshalJSON() ([]byte, error) | // MarshalJSON converts an application into a Cloud Controller Application.
func (application Application) MarshalJSON() ([]byte, error) | {
ccApp := struct {
Buildpack *string `json:"buildpack,omitempty"`
Command *string `json:"command,omitempty"`
DiskQuota *uint64 `json:"disk_quota,omitempty"`
DockerCredentials *DockerCredentials `json:"docker_credentials,omitempty"`
DockerImage string `json:"docker_image,omitempty"`
EnvironmentVariables map[string]string `json:"environment_json,omitempty"`
HealthCheckHTTPEndpoint *string `json:"health_check_http_endpoint,omitempty"`
HealthCheckTimeout uint64 `json:"health_check_timeout,omitempty"`
HealthCheckType constant.ApplicationHealthCheckType `json:"health_check_type,omitempty"`
Instances *int `json:"instances,omitempty"`
Memory *uint64 `json:"memory,omitempty"`
Name string `json:"name,omitempty"`
SpaceGUID string `json:"space_guid,omitempty"`
StackGUID string `json:"stack_guid,omitempty"`
State constant.ApplicationState `json:"state,omitempty"`
}{
DockerImage: application.DockerImage,
EnvironmentVariables: application.EnvironmentVariables,
HealthCheckTimeout: application.HealthCheckTimeout,
HealthCheckType: application.HealthCheckType,
Name: application.Name,
SpaceGUID: application.SpaceGUID,
StackGUID: application.StackGUID,
State: application.State,
}
if application.Buildpack.IsSet {
ccApp.Buildpack = &application.Buildpack.Value
}
if application.Command.IsSet {
ccApp.Command = &application.Command.Value
}
if application.DiskQuota.IsSet {
ccApp.DiskQuota = &application.DiskQuota.Value
}
if application.DockerCredentials.Username != "" || application.DockerCredentials.Password != "" {
ccApp.DockerCredentials = &DockerCredentials{
Username: application.DockerCredentials.Username,
Password: application.DockerCredentials.Password,
}
}
if application.Instances.IsSet {
ccApp.Instances = &application.Instances.Value
}
if application.HealthCheckType != "" {
ccApp.HealthCheckHTTPEndpoint = &application.HealthCheckHTTPEndpoint
}
if application.Memory.IsSet {
ccApp.Memory = &application.Memory.Value
}
return json.Marshal(ccApp)
} |
cloudfoundry/cli | 5010c000047f246b870475e2c299556078cdad30 | api/cloudcontroller/ccv2/application.go | https://github.com/cloudfoundry/cli/blob/5010c000047f246b870475e2c299556078cdad30/api/cloudcontroller/ccv2/application.go#L152-L223 | go | train | // UnmarshalJSON helps unmarshal a Cloud Controller Application response. | func (application *Application) UnmarshalJSON(data []byte) error | // UnmarshalJSON helps unmarshal a Cloud Controller Application response.
func (application *Application) UnmarshalJSON(data []byte) error | {
var ccApp struct {
Metadata internal.Metadata `json:"metadata"`
Entity struct {
Buildpack string `json:"buildpack"`
Command string `json:"command"`
DetectedBuildpack string `json:"detected_buildpack"`
DetectedStartCommand string `json:"detected_start_command"`
DiskQuota *uint64 `json:"disk_quota"`
DockerImage string `json:"docker_image"`
DockerCredentials DockerCredentials `json:"docker_credentials"`
// EnvironmentVariables' values can be any type, so we must accept
// interface{}, but we convert to string.
EnvironmentVariables map[string]interface{} `json:"environment_json"`
HealthCheckHTTPEndpoint string `json:"health_check_http_endpoint"`
HealthCheckTimeout uint64 `json:"health_check_timeout"`
HealthCheckType string `json:"health_check_type"`
Instances json.Number `json:"instances"`
Memory *uint64 `json:"memory"`
Name string `json:"name"`
PackageState string `json:"package_state"`
PackageUpdatedAt *time.Time `json:"package_updated_at"`
SpaceGUID string `json:"space_guid"`
StackGUID string `json:"stack_guid"`
StagingFailedDescription string `json:"staging_failed_description"`
StagingFailedReason string `json:"staging_failed_reason"`
State string `json:"state"`
} `json:"entity"`
}
err := cloudcontroller.DecodeJSON(data, &ccApp)
if err != nil {
return err
}
application.Buildpack.ParseValue(ccApp.Entity.Buildpack)
application.Command.ParseValue(ccApp.Entity.Command)
application.DetectedBuildpack.ParseValue(ccApp.Entity.DetectedBuildpack)
application.DetectedStartCommand.ParseValue(ccApp.Entity.DetectedStartCommand)
application.DiskQuota.ParseUint64Value(ccApp.Entity.DiskQuota)
application.DockerCredentials = ccApp.Entity.DockerCredentials
application.DockerImage = ccApp.Entity.DockerImage
application.GUID = ccApp.Metadata.GUID
application.HealthCheckHTTPEndpoint = ccApp.Entity.HealthCheckHTTPEndpoint
application.HealthCheckTimeout = ccApp.Entity.HealthCheckTimeout
application.HealthCheckType = constant.ApplicationHealthCheckType(ccApp.Entity.HealthCheckType)
application.Memory.ParseUint64Value(ccApp.Entity.Memory)
application.Name = ccApp.Entity.Name
application.PackageState = constant.ApplicationPackageState(ccApp.Entity.PackageState)
application.SpaceGUID = ccApp.Entity.SpaceGUID
application.StackGUID = ccApp.Entity.StackGUID
application.StagingFailedDescription = ccApp.Entity.StagingFailedDescription
application.StagingFailedReason = ccApp.Entity.StagingFailedReason
application.State = constant.ApplicationState(ccApp.Entity.State)
if len(ccApp.Entity.EnvironmentVariables) > 0 {
envVariableValues := map[string]string{}
for key, value := range ccApp.Entity.EnvironmentVariables {
envVariableValues[key] = fmt.Sprint(value)
}
application.EnvironmentVariables = envVariableValues
}
err = application.Instances.ParseStringValue(ccApp.Entity.Instances.String())
if err != nil {
return err
}
if ccApp.Entity.PackageUpdatedAt != nil {
application.PackageUpdatedAt = *ccApp.Entity.PackageUpdatedAt
}
return nil
} |
cloudfoundry/cli | 5010c000047f246b870475e2c299556078cdad30 | api/cloudcontroller/ccv2/application.go | https://github.com/cloudfoundry/cli/blob/5010c000047f246b870475e2c299556078cdad30/api/cloudcontroller/ccv2/application.go#L227-L248 | go | train | // CreateApplication creates a cloud controller application in with the given
// settings. SpaceGUID and Name are the only required fields. | func (client *Client) CreateApplication(app Application) (Application, Warnings, error) | // CreateApplication creates a cloud controller application in with the given
// settings. SpaceGUID and Name are the only required fields.
func (client *Client) CreateApplication(app Application) (Application, Warnings, error) | {
body, err := json.Marshal(app)
if err != nil {
return Application{}, nil, err
}
request, err := client.newHTTPRequest(requestOptions{
RequestName: internal.PostAppRequest,
Body: bytes.NewReader(body),
})
if err != nil {
return Application{}, nil, err
}
var updatedApp Application
response := cloudcontroller.Response{
DecodeJSONResponseInto: &updatedApp,
}
err = client.connection.Make(request, &response)
return updatedApp, response.Warnings, err
} |
cloudfoundry/cli | 5010c000047f246b870475e2c299556078cdad30 | api/cloudcontroller/ccv2/application.go | https://github.com/cloudfoundry/cli/blob/5010c000047f246b870475e2c299556078cdad30/api/cloudcontroller/ccv2/application.go#L251-L267 | go | train | // GetApplication returns back an Application. | func (client *Client) GetApplication(guid string) (Application, Warnings, error) | // GetApplication returns back an Application.
func (client *Client) GetApplication(guid string) (Application, Warnings, error) | {
request, err := client.newHTTPRequest(requestOptions{
RequestName: internal.GetAppRequest,
URIParams: Params{"app_guid": guid},
})
if err != nil {
return Application{}, nil, err
}
var app Application
response := cloudcontroller.Response{
DecodeJSONResponseInto: &app,
}
err = client.connection.Make(request, &response)
return app, response.Warnings, err
} |
cloudfoundry/cli | 5010c000047f246b870475e2c299556078cdad30 | api/cloudcontroller/ccv2/application.go | https://github.com/cloudfoundry/cli/blob/5010c000047f246b870475e2c299556078cdad30/api/cloudcontroller/ccv2/application.go#L298-L322 | go | train | // GetRouteApplications returns a list of Applications based off a route
// GUID and the provided filters. | func (client *Client) GetRouteApplications(routeGUID string, filters ...Filter) ([]Application, Warnings, error) | // GetRouteApplications returns a list of Applications based off a route
// GUID and the provided filters.
func (client *Client) GetRouteApplications(routeGUID string, filters ...Filter) ([]Application, Warnings, error) | {
request, err := client.newHTTPRequest(requestOptions{
RequestName: internal.GetRouteAppsRequest,
URIParams: map[string]string{"route_guid": routeGUID},
Query: ConvertFilterParameters(filters),
})
if err != nil {
return nil, nil, err
}
var fullAppsList []Application
warnings, err := client.paginate(request, Application{}, func(item interface{}) error {
if app, ok := item.(Application); ok {
fullAppsList = append(fullAppsList, app)
} else {
return ccerror.UnknownObjectInListError{
Expected: Application{},
Unexpected: item,
}
}
return nil
})
return fullAppsList, warnings, err
} |
cloudfoundry/cli | 5010c000047f246b870475e2c299556078cdad30 | api/cloudcontroller/ccv2/application.go | https://github.com/cloudfoundry/cli/blob/5010c000047f246b870475e2c299556078cdad30/api/cloudcontroller/ccv2/application.go#L325-L341 | go | train | // RestageApplication restages the application with the given GUID. | func (client *Client) RestageApplication(app Application) (Application, Warnings, error) | // RestageApplication restages the application with the given GUID.
func (client *Client) RestageApplication(app Application) (Application, Warnings, error) | {
request, err := client.newHTTPRequest(requestOptions{
RequestName: internal.PostAppRestageRequest,
URIParams: Params{"app_guid": app.GUID},
})
if err != nil {
return Application{}, nil, err
}
var restagedApp Application
response := cloudcontroller.Response{
DecodeJSONResponseInto: &restagedApp,
}
err = client.connection.Make(request, &response)
return restagedApp, response.Warnings, err
} |
cloudfoundry/cli | 5010c000047f246b870475e2c299556078cdad30 | api/cloudcontroller/ccv2/application.go | https://github.com/cloudfoundry/cli/blob/5010c000047f246b870475e2c299556078cdad30/api/cloudcontroller/ccv2/application.go#L345-L367 | go | train | // UpdateApplication updates the application with the given GUID. Note: Sending
// DockerImage and StackGUID at the same time will result in an API error. | func (client *Client) UpdateApplication(app Application) (Application, Warnings, error) | // UpdateApplication updates the application with the given GUID. Note: Sending
// DockerImage and StackGUID at the same time will result in an API error.
func (client *Client) UpdateApplication(app Application) (Application, Warnings, error) | {
body, err := json.Marshal(app)
if err != nil {
return Application{}, nil, err
}
request, err := client.newHTTPRequest(requestOptions{
RequestName: internal.PutAppRequest,
URIParams: Params{"app_guid": app.GUID},
Body: bytes.NewReader(body),
})
if err != nil {
return Application{}, nil, err
}
var updatedApp Application
response := cloudcontroller.Response{
DecodeJSONResponseInto: &updatedApp,
}
err = client.connection.Make(request, &response)
return updatedApp, response.Warnings, err
} |
cloudfoundry/cli | 5010c000047f246b870475e2c299556078cdad30 | actor/pushaction/application.go | https://github.com/cloudfoundry/cli/blob/5010c000047f246b870475e2c299556078cdad30/actor/pushaction/application.go#L22-L32 | go | train | // CalculatedBuildpacks will return back the buildpacks for the application. | func (app Application) CalculatedBuildpacks() []string | // CalculatedBuildpacks will return back the buildpacks for the application.
func (app Application) CalculatedBuildpacks() []string | {
buildpack := app.CalculatedBuildpack()
switch {
case app.Buildpacks != nil:
return app.Buildpacks
case len(buildpack) > 0:
return []string{buildpack}
default:
return nil
}
} |
cloudfoundry/cli | 5010c000047f246b870475e2c299556078cdad30 | actor/pushaction/application.go | https://github.com/cloudfoundry/cli/blob/5010c000047f246b870475e2c299556078cdad30/actor/pushaction/application.go#L145-L151 | go | train | // For some versions of CC, sending state will always result in CC
// attempting to do perform that request (i.e. started -> start/restart).
// In order to prevent repeated unintended restarts in the middle of a
// push, don't send state. This will be fixed in capi-release 1.48.0. | func (actor Actor) ignoreSameState(config ApplicationConfig, v2App v2action.Application) v2action.Application | // For some versions of CC, sending state will always result in CC
// attempting to do perform that request (i.e. started -> start/restart).
// In order to prevent repeated unintended restarts in the middle of a
// push, don't send state. This will be fixed in capi-release 1.48.0.
func (actor Actor) ignoreSameState(config ApplicationConfig, v2App v2action.Application) v2action.Application | {
if config.CurrentApplication.State == config.DesiredApplication.State {
v2App.State = ""
}
return v2App
} |
cloudfoundry/cli | 5010c000047f246b870475e2c299556078cdad30 | actor/pushaction/application.go | https://github.com/cloudfoundry/cli/blob/5010c000047f246b870475e2c299556078cdad30/actor/pushaction/application.go#L155-L161 | go | train | // Apps updates with both docker image and stack guids fail. So do not send
// StackGUID unless it is necessary. | func (actor Actor) ignoreSameStackGUID(config ApplicationConfig, v2App v2action.Application) v2action.Application | // Apps updates with both docker image and stack guids fail. So do not send
// StackGUID unless it is necessary.
func (actor Actor) ignoreSameStackGUID(config ApplicationConfig, v2App v2action.Application) v2action.Application | {
if config.CurrentApplication.StackGUID == config.DesiredApplication.StackGUID {
v2App.StackGUID = ""
}
return v2App
} |
cloudfoundry/cli | 5010c000047f246b870475e2c299556078cdad30 | actor/pushaction/application.go | https://github.com/cloudfoundry/cli/blob/5010c000047f246b870475e2c299556078cdad30/actor/pushaction/application.go#L165-L179 | go | train | // If 'buildpacks' is set with only one buildpack, set `buildpack` (singular)
// on the application. | func (Actor) setBuildpack(config ApplicationConfig) types.FilteredString | // If 'buildpacks' is set with only one buildpack, set `buildpack` (singular)
// on the application.
func (Actor) setBuildpack(config ApplicationConfig) types.FilteredString | {
buildpacks := config.DesiredApplication.Buildpacks
if len(buildpacks) == 1 {
var filtered types.FilteredString
filtered.ParseValue(buildpacks[0])
return filtered
}
if buildpacks != nil && len(buildpacks) == 0 {
return types.FilteredString{IsSet: true}
}
return config.DesiredApplication.Buildpack
} |
cloudfoundry/cli | 5010c000047f246b870475e2c299556078cdad30 | api/cloudcontroller/ccv3/environment_variables.go | https://github.com/cloudfoundry/cli/blob/5010c000047f246b870475e2c299556078cdad30/api/cloudcontroller/ccv3/environment_variables.go#L40-L61 | go | train | // UpdateApplicationEnvironmentVariables adds/updates the user provided
// environment variables on an application. A restart is required for changes
// to take effect. | func (client *Client) UpdateApplicationEnvironmentVariables(appGUID string, envVars EnvironmentVariables) (EnvironmentVariables, Warnings, error) | // UpdateApplicationEnvironmentVariables adds/updates the user provided
// environment variables on an application. A restart is required for changes
// to take effect.
func (client *Client) UpdateApplicationEnvironmentVariables(appGUID string, envVars EnvironmentVariables) (EnvironmentVariables, Warnings, error) | {
bodyBytes, err := json.Marshal(envVars)
if err != nil {
return EnvironmentVariables{}, nil, err
}
request, err := client.newHTTPRequest(requestOptions{
URIParams: internal.Params{"app_guid": appGUID},
RequestName: internal.PatchApplicationEnvironmentVariablesRequest,
Body: bytes.NewReader(bodyBytes),
})
if err != nil {
return EnvironmentVariables{}, nil, err
}
var responseEnvVars EnvironmentVariables
response := cloudcontroller.Response{
DecodeJSONResponseInto: &responseEnvVars,
}
err = client.connection.Make(request, &response)
return responseEnvVars, response.Warnings, err
} |
cloudfoundry/cli | 5010c000047f246b870475e2c299556078cdad30 | plugin/plugin_shim.go | https://github.com/cloudfoundry/cli/blob/5010c000047f246b870475e2c299556078cdad30/plugin/plugin_shim.go#L15-L36 | go | train | /**
* This function is called by the plugin to setup their server. This allows us to call Run on the plugin
* os.Args[1] port CF_CLI rpc server is running on
* os.Args[2] **OPTIONAL**
* SendMetadata - used to fetch the plugin metadata
**/ | func Start(cmd Plugin) | /**
* This function is called by the plugin to setup their server. This allows us to call Run on the plugin
* os.Args[1] port CF_CLI rpc server is running on
* os.Args[2] **OPTIONAL**
* SendMetadata - used to fetch the plugin metadata
**/
func Start(cmd Plugin) | {
if len(os.Args) < 2 {
fmt.Printf("This cf CLI plugin is not intended to be run on its own\n\n")
os.Exit(1)
}
cliConnection := NewCliConnection(os.Args[1])
cliConnection.pingCLI()
if isMetadataRequest(os.Args) {
cliConnection.sendPluginMetadataToCliServer(cmd.GetMetadata())
} else {
if version := MinCliVersionStr(cmd.GetMetadata().MinCliVersion); version != "" {
ok := cliConnection.isMinCliVersion(version)
if !ok {
fmt.Printf("Minimum CLI version %s is required to run this plugin command\n\n", version)
os.Exit(0)
}
}
cmd.Run(cliConnection, os.Args[2:])
}
} |
cloudfoundry/cli | 5010c000047f246b870475e2c299556078cdad30 | api/plugin/client.go | https://github.com/cloudfoundry/cli/blob/5010c000047f246b870475e2c299556078cdad30/api/plugin/client.go#L39-L53 | go | train | // NewClient returns a new plugin Client. | func NewClient(config Config) *Client | // NewClient returns a new plugin Client.
func NewClient(config Config) *Client | {
userAgent := fmt.Sprintf("%s/%s (%s; %s %s)",
config.AppName,
config.AppVersion,
runtime.Version(),
runtime.GOARCH,
runtime.GOOS,
)
client := Client{
userAgent: userAgent,
connection: NewConnection(config.SkipSSLValidation, config.DialTimeout),
}
return &client
} |
cloudfoundry/cli | 5010c000047f246b870475e2c299556078cdad30 | actor/v7pushaction/update_application_settings.go | https://github.com/cloudfoundry/cli/blob/5010c000047f246b870475e2c299556078cdad30/actor/v7pushaction/update_application_settings.go#L10-L31 | go | train | // UpdateApplicationSettings syncs the Application state and GUID with the API. | func (actor Actor) UpdateApplicationSettings(pushPlans []PushPlan) ([]PushPlan, Warnings, error) | // UpdateApplicationSettings syncs the Application state and GUID with the API.
func (actor Actor) UpdateApplicationSettings(pushPlans []PushPlan) ([]PushPlan, Warnings, error) | {
appNames := actor.getAppNames(pushPlans)
applications, getWarnings, err := actor.V7Actor.GetApplicationsByNamesAndSpace(appNames, pushPlans[0].SpaceGUID)
warnings := Warnings(getWarnings)
if err != nil {
log.Errorln("Looking up applications:", err)
return nil, warnings, err
}
nameToApp := actor.generateAppNameToApplicationMapping(applications)
var updatedPushPlans []PushPlan
for _, pushPlan := range pushPlans {
app := nameToApp[pushPlan.Application.Name]
pushPlan.Application.GUID = app.GUID
pushPlan.Application.State = app.State
updatedPushPlans = append(updatedPushPlans, pushPlan)
}
return updatedPushPlans, warnings, err
} |
cloudfoundry/cli | 5010c000047f246b870475e2c299556078cdad30 | api/cloudcontroller/ccv2/application_instance_status.go | https://github.com/cloudfoundry/cli/blob/5010c000047f246b870475e2c299556078cdad30/api/cloudcontroller/ccv2/application_instance_status.go#L43-L73 | go | train | // UnmarshalJSON helps unmarshal a Cloud Controller application instance
// response. | func (instance *ApplicationInstanceStatus) UnmarshalJSON(data []byte) error | // UnmarshalJSON helps unmarshal a Cloud Controller application instance
// response.
func (instance *ApplicationInstanceStatus) UnmarshalJSON(data []byte) error | {
var ccInstance struct {
State string `json:"state"`
IsolationSegment string `json:"isolation_segment"`
Stats struct {
Usage struct {
Disk int64 `json:"disk"`
Memory int64 `json:"mem"`
CPU float64 `json:"cpu"`
} `json:"usage"`
MemoryQuota int64 `json:"mem_quota"`
DiskQuota int64 `json:"disk_quota"`
Uptime int64 `json:"uptime"`
} `json:"stats"`
}
err := cloudcontroller.DecodeJSON(data, &ccInstance)
if err != nil {
return err
}
instance.CPU = ccInstance.Stats.Usage.CPU
instance.Disk = ccInstance.Stats.Usage.Disk
instance.DiskQuota = ccInstance.Stats.DiskQuota
instance.IsolationSegment = ccInstance.IsolationSegment
instance.Memory = ccInstance.Stats.Usage.Memory
instance.MemoryQuota = ccInstance.Stats.MemoryQuota
instance.State = constant.ApplicationInstanceState(ccInstance.State)
instance.Uptime = ccInstance.Stats.Uptime
return nil
} |
cloudfoundry/cli | 5010c000047f246b870475e2c299556078cdad30 | actor/pushaction/merge_and_validate_settings_and_manifest.go | https://github.com/cloudfoundry/cli/blob/5010c000047f246b870475e2c299556078cdad30/actor/pushaction/merge_and_validate_settings_and_manifest.go#L19-L57 | go | train | // MergeAndValidateSettingsAndManifests merges command line settings and
// manifest settings. It does this by:
// - Validating command line setting and their effect on the provided manifests
// - Override manifest settings with command line settings (when applicable)
// - Sanitizing the inputs
// - Validate merged manifest | func (actor Actor) MergeAndValidateSettingsAndManifests(cmdLineSettings CommandLineSettings, apps []manifest.Application) ([]manifest.Application, error) | // MergeAndValidateSettingsAndManifests merges command line settings and
// manifest settings. It does this by:
// - Validating command line setting and their effect on the provided manifests
// - Override manifest settings with command line settings (when applicable)
// - Sanitizing the inputs
// - Validate merged manifest
func (actor Actor) MergeAndValidateSettingsAndManifests(cmdLineSettings CommandLineSettings, apps []manifest.Application) ([]manifest.Application, error) | {
var mergedApps []manifest.Application
if len(apps) == 0 {
log.Info("no manifest, generating one from command line settings")
mergedApps = append(mergedApps, cmdLineSettings.OverrideManifestSettings(manifest.Application{}))
} else {
if cmdLineSettings.Name != "" && len(apps) > 1 {
var err error
apps, err = actor.selectApp(cmdLineSettings.Name, apps)
if err != nil {
return nil, err
}
}
err := actor.validateCommandLineSettingsAndManifestCombinations(cmdLineSettings, apps)
if err != nil {
return nil, err
}
for _, app := range apps {
mergedApps = append(mergedApps, cmdLineSettings.OverrideManifestSettings(app))
}
}
mergedApps, err := actor.sanitizeAppPath(mergedApps)
if err != nil {
return nil, err
}
mergedApps = actor.setSaneEndpoint(mergedApps)
log.Debugf("merged app settings: %#v", mergedApps)
err = actor.validateMergedSettings(mergedApps)
if err != nil {
log.Errorln("validation error post merge:", err)
return nil, err
}
return mergedApps, nil
} |
cloudfoundry/cli | 5010c000047f246b870475e2c299556078cdad30 | util/configv3/locale.go | https://github.com/cloudfoundry/cli/blob/5010c000047f246b870475e2c299556078cdad30/util/configv3/locale.go#L16-L30 | go | train | // Locale returns the locale/language the UI should be displayed in. This value
// is based off of:
// 1. The 'Locale' setting in the .cf/config.json
// 2. The $LC_ALL environment variable if set
// 3. The $LANG environment variable if set
// 4. Defaults to DefaultLocale | func (config *Config) Locale() string | // Locale returns the locale/language the UI should be displayed in. This value
// is based off of:
// 1. The 'Locale' setting in the .cf/config.json
// 2. The $LC_ALL environment variable if set
// 3. The $LANG environment variable if set
// 4. Defaults to DefaultLocale
func (config *Config) Locale() string | {
if config.ConfigFile.Locale != "" {
return config.ConfigFile.Locale
}
if config.ENV.LCAll != "" {
return config.convertLocale(config.ENV.LCAll)
}
if config.ENV.Lang != "" {
return config.convertLocale(config.ENV.Lang)
}
return DefaultLocale
} |
cloudfoundry/cli | 5010c000047f246b870475e2c299556078cdad30 | cf/api/logs/noaa_message_queue.go | https://github.com/cloudfoundry/cli/blob/5010c000047f246b870475e2c299556078cdad30/cf/api/logs/noaa_message_queue.go#L27-L29 | go | train | // implement sort interface so we can sort messages as we receive them in PushMessage | func (pq *NoaaMessageQueue) Less(i, j int) bool | // implement sort interface so we can sort messages as we receive them in PushMessage
func (pq *NoaaMessageQueue) Less(i, j int) bool | {
return *pq.messages[i].Timestamp < *pq.messages[j].Timestamp
} |
cloudfoundry/cli | 5010c000047f246b870475e2c299556078cdad30 | actor/v7pushaction/create_push_plans.go | https://github.com/cloudfoundry/cli/blob/5010c000047f246b870475e2c299556078cdad30/actor/v7pushaction/create_push_plans.go#L10-L37 | go | train | // CreatePushPlans returns a set of PushPlan objects based off the inputs
// provided. It's assumed that all flag and argument and manifest combinations
// have been validated prior to calling this function. | func (actor Actor) CreatePushPlans(appNameArg string, spaceGUID string, orgGUID string, parser ManifestParser, overrides FlagOverrides) ([]PushPlan, error) | // CreatePushPlans returns a set of PushPlan objects based off the inputs
// provided. It's assumed that all flag and argument and manifest combinations
// have been validated prior to calling this function.
func (actor Actor) CreatePushPlans(appNameArg string, spaceGUID string, orgGUID string, parser ManifestParser, overrides FlagOverrides) ([]PushPlan, error) | {
var pushPlans []PushPlan
eligibleApps, err := actor.getEligibleApplications(parser, appNameArg)
if err != nil {
return nil, err
}
for _, manifestApplication := range eligibleApps {
plan := PushPlan{
OrgGUID: orgGUID,
SpaceGUID: spaceGUID,
}
// List of PushPlanFuncs is defined in NewActor
for _, updatePlan := range actor.PushPlanFuncs {
var err error
plan, err = updatePlan(plan, overrides, manifestApplication)
if err != nil {
return nil, err
}
}
pushPlans = append(pushPlans, plan)
}
return pushPlans, nil
} |
cloudfoundry/cli | 5010c000047f246b870475e2c299556078cdad30 | api/cloudcontroller/ccv3/buildpack.go | https://github.com/cloudfoundry/cli/blob/5010c000047f246b870475e2c299556078cdad30/api/cloudcontroller/ccv3/buildpack.go#L40-L63 | go | train | // MarshalJSON converts a Package into a Cloud Controller Package. | func (buildpack Buildpack) MarshalJSON() ([]byte, error) | // MarshalJSON converts a Package into a Cloud Controller Package.
func (buildpack Buildpack) MarshalJSON() ([]byte, error) | {
ccBuildpack := struct {
Name string `json:"name,omitempty"`
Stack string `json:"stack,omitempty"`
Position *int `json:"position,omitempty"`
Enabled *bool `json:"enabled,omitempty"`
Locked *bool `json:"locked,omitempty"`
}{
Name: buildpack.Name,
Stack: buildpack.Stack,
}
if buildpack.Position.IsSet {
ccBuildpack.Position = &buildpack.Position.Value
}
if buildpack.Enabled.IsSet {
ccBuildpack.Enabled = &buildpack.Enabled.Value
}
if buildpack.Locked.IsSet {
ccBuildpack.Locked = &buildpack.Locked.Value
}
return json.Marshal(ccBuildpack)
} |
cloudfoundry/cli | 5010c000047f246b870475e2c299556078cdad30 | api/cloudcontroller/ccv3/buildpack.go | https://github.com/cloudfoundry/cli/blob/5010c000047f246b870475e2c299556078cdad30/api/cloudcontroller/ccv3/buildpack.go#L122-L137 | go | train | // DeleteBuildpack deletes the buildpack with the provided guid. | func (client Client) DeleteBuildpack(buildpackGUID string) (JobURL, Warnings, error) | // DeleteBuildpack deletes the buildpack with the provided guid.
func (client Client) DeleteBuildpack(buildpackGUID string) (JobURL, Warnings, error) | {
request, err := client.newHTTPRequest(requestOptions{
RequestName: internal.DeleteBuildpackRequest,
URIParams: map[string]string{
"buildpack_guid": buildpackGUID,
},
})
if err != nil {
return "", nil, err
}
response := cloudcontroller.Response{}
err = client.connection.Make(request, &response)
return JobURL(response.ResourceLocationURL), response.Warnings, err
} |
cloudfoundry/cli | 5010c000047f246b870475e2c299556078cdad30 | actor/v7pushaction/resource_match.go | https://github.com/cloudfoundry/cli/blob/5010c000047f246b870475e2c299556078cdad30/actor/v7pushaction/resource_match.go#L6-L22 | go | train | // MatchResources returns back a list of matched and unmatched resources for the provided resources. | func (actor Actor) MatchResources(resources []sharedaction.V3Resource) ([]sharedaction.V3Resource, []sharedaction.V3Resource, Warnings, error) | // MatchResources returns back a list of matched and unmatched resources for the provided resources.
func (actor Actor) MatchResources(resources []sharedaction.V3Resource) ([]sharedaction.V3Resource, []sharedaction.V3Resource, Warnings, error) | {
matches, warnings, err := actor.V7Actor.ResourceMatch(resources)
mapChecksumToResource := map[string]sharedaction.V3Resource{}
for _, resource := range matches {
mapChecksumToResource[resource.Checksum.Value] = resource
}
var unmatches []sharedaction.V3Resource
for _, resource := range resources {
if _, ok := mapChecksumToResource[resource.Checksum.Value]; !ok {
unmatches = append(unmatches, resource)
}
}
return matches, unmatches, Warnings(warnings), err
} |
cloudfoundry/cli | 5010c000047f246b870475e2c299556078cdad30 | api/cloudcontroller/ccv2/user.go | https://github.com/cloudfoundry/cli/blob/5010c000047f246b870475e2c299556078cdad30/api/cloudcontroller/ccv2/user.go#L18-L29 | go | train | // UnmarshalJSON helps unmarshal a Cloud Controller User response. | func (user *User) UnmarshalJSON(data []byte) error | // UnmarshalJSON helps unmarshal a Cloud Controller User response.
func (user *User) UnmarshalJSON(data []byte) error | {
var ccUser struct {
Metadata internal.Metadata `json:"metadata"`
}
err := cloudcontroller.DecodeJSON(data, &ccUser)
if err != nil {
return err
}
user.GUID = ccUser.Metadata.GUID
return nil
} |
cloudfoundry/cli | 5010c000047f246b870475e2c299556078cdad30 | api/cloudcontroller/ccv2/user.go | https://github.com/cloudfoundry/cli/blob/5010c000047f246b870475e2c299556078cdad30/api/cloudcontroller/ccv2/user.go#L33-L64 | go | train | // CreateUser creates a new Cloud Controller User from the provided UAA user
// ID. | func (client *Client) CreateUser(uaaUserID string) (User, Warnings, error) | // CreateUser creates a new Cloud Controller User from the provided UAA user
// ID.
func (client *Client) CreateUser(uaaUserID string) (User, Warnings, error) | {
type userRequestBody struct {
GUID string `json:"guid"`
}
bodyBytes, err := json.Marshal(userRequestBody{
GUID: uaaUserID,
})
if err != nil {
return User{}, nil, err
}
request, err := client.newHTTPRequest(requestOptions{
RequestName: internal.PostUserRequest,
Body: bytes.NewReader(bodyBytes),
})
if err != nil {
return User{}, nil, err
}
var user User
response := cloudcontroller.Response{
DecodeJSONResponseInto: &user,
}
err = client.connection.Make(request, &response)
if err != nil {
return User{}, response.Warnings, err
}
return user, response.Warnings, nil
} |
cloudfoundry/cli | 5010c000047f246b870475e2c299556078cdad30 | api/router/router_connection.go | https://github.com/cloudfoundry/cli/blob/5010c000047f246b870475e2c299556078cdad30/api/router/router_connection.go#L48-L61 | go | train | // Make performs the request and parses the response. | func (connection *RouterConnection) Make(request *Request, responseToPopulate *Response) error | // Make performs the request and parses the response.
func (connection *RouterConnection) Make(request *Request, responseToPopulate *Response) error | {
// In case this function is called from a retry, passedResponse may already
// be populated with a previous response. We reset in case there's an HTTP
// error and we don't repopulate it in populateResponse.
responseToPopulate.reset()
httpResponse, err := connection.HTTPClient.Do(request.Request)
if err != nil {
// request could not be made, e.g., ssl handshake or tcp dial timeout
return connection.processRequestErrors(request.Request, err)
}
return connection.populateResponse(httpResponse, responseToPopulate)
} |
cloudfoundry/cli | 5010c000047f246b870475e2c299556078cdad30 | api/router/client.go | https://github.com/cloudfoundry/cli/blob/5010c000047f246b870475e2c299556078cdad30/api/router/client.go#L42-L62 | go | train | // NewClient returns a new Router Client. | func NewClient(config Config) *Client | // NewClient returns a new Router Client.
func NewClient(config Config) *Client | {
userAgent := fmt.Sprintf("%s/%s (%s; %s %s)",
config.AppName,
config.AppVersion,
runtime.Version(),
runtime.GOARCH,
runtime.GOOS,
)
client := Client{
userAgent: userAgent,
router: rata.NewRequestGenerator(config.RoutingEndpoint, internal.APIRoutes),
connection: NewConnection(config.ConnectionConfig),
}
for _, wrapper := range config.Wrappers {
client.connection = wrapper.Wrap(client.connection)
}
return &client
} |
cloudfoundry/cli | 5010c000047f246b870475e2c299556078cdad30 | api/cloudcontroller/ccv2/service_instance_shared_from.go | https://github.com/cloudfoundry/cli/blob/5010c000047f246b870475e2c299556078cdad30/api/cloudcontroller/ccv2/service_instance_shared_from.go#L26-L42 | go | train | // GetServiceInstanceSharedFrom returns back a ServiceInstanceSharedFrom
// object. | func (client *Client) GetServiceInstanceSharedFrom(serviceInstanceGUID string) (ServiceInstanceSharedFrom, Warnings, error) | // GetServiceInstanceSharedFrom returns back a ServiceInstanceSharedFrom
// object.
func (client *Client) GetServiceInstanceSharedFrom(serviceInstanceGUID string) (ServiceInstanceSharedFrom, Warnings, error) | {
request, err := client.newHTTPRequest(requestOptions{
RequestName: internal.GetServiceInstanceSharedFromRequest,
URIParams: Params{"service_instance_guid": serviceInstanceGUID},
})
if err != nil {
return ServiceInstanceSharedFrom{}, nil, err
}
var serviceInstanceSharedFrom ServiceInstanceSharedFrom
response := cloudcontroller.Response{
DecodeJSONResponseInto: &serviceInstanceSharedFrom,
}
err = client.connection.Make(request, &response)
return serviceInstanceSharedFrom, response.Warnings, err
} |
cloudfoundry/cli | 5010c000047f246b870475e2c299556078cdad30 | api/cloudcontroller/ccv3/feature_flag.go | https://github.com/cloudfoundry/cli/blob/5010c000047f246b870475e2c299556078cdad30/api/cloudcontroller/ccv3/feature_flag.go#L51-L75 | go | train | // GetFeatureFlags lists feature flags. | func (client *Client) GetFeatureFlags() ([]FeatureFlag, Warnings, error) | // GetFeatureFlags lists feature flags.
func (client *Client) GetFeatureFlags() ([]FeatureFlag, Warnings, error) | {
request, err := client.newHTTPRequest(requestOptions{
RequestName: internal.GetFeatureFlagsRequest,
})
if err != nil {
return nil, nil, err
}
var fullFeatureFlagList []FeatureFlag
warnings, err := client.paginate(request, FeatureFlag{}, func(item interface{}) error {
if featureFlag, ok := item.(FeatureFlag); ok {
fullFeatureFlagList = append(fullFeatureFlagList, featureFlag)
} else {
return ccerror.UnknownObjectInListError{
Expected: FeatureFlag{},
Unexpected: item,
}
}
return nil
})
return fullFeatureFlagList, warnings, err
} |
cloudfoundry/cli | 5010c000047f246b870475e2c299556078cdad30 | command/v7/ssh_command.go | https://github.com/cloudfoundry/cli/blob/5010c000047f246b870475e2c299556078cdad30/command/v7/ssh_command.go#L118-L142 | go | train | // EvaluateTTYOption determines which TTY options are mutually exclusive and
// returns an error accordingly. | func (cmd SSHCommand) EvaluateTTYOption() (sharedaction.TTYOption, error) | // EvaluateTTYOption determines which TTY options are mutually exclusive and
// returns an error accordingly.
func (cmd SSHCommand) EvaluateTTYOption() (sharedaction.TTYOption, error) | {
var count int
option := sharedaction.RequestTTYAuto
if cmd.DisablePseudoTTY {
option = sharedaction.RequestTTYNo
count++
}
if cmd.ForcePseudoTTY {
option = sharedaction.RequestTTYForce
count++
}
if cmd.RequestPseudoTTY {
option = sharedaction.RequestTTYYes
count++
}
if count > 1 {
return option, translatableerror.ArgumentCombinationError{Args: []string{
"--disable-pseudo-tty", "-T", "--force-pseudo-tty", "--request-pseudo-tty", "-t",
}}
}
return option, nil
} |
cloudfoundry/cli | 5010c000047f246b870475e2c299556078cdad30 | actor/v2action/space_quota.go | https://github.com/cloudfoundry/cli/blob/5010c000047f246b870475e2c299556078cdad30/actor/v2action/space_quota.go#L22-L36 | go | train | // GetSpaceQuotaByName finds the quota by name and returns an error if not found | func (actor Actor) GetSpaceQuotaByName(quotaName, orgGUID string) (SpaceQuota, Warnings, error) | // GetSpaceQuotaByName finds the quota by name and returns an error if not found
func (actor Actor) GetSpaceQuotaByName(quotaName, orgGUID string) (SpaceQuota, Warnings, error) | {
quotas, warnings, err := actor.CloudControllerClient.GetSpaceQuotas(orgGUID)
if err != nil {
return SpaceQuota{}, Warnings(warnings), err
}
for _, quota := range quotas {
if quota.Name == quotaName {
return SpaceQuota(quota), Warnings(warnings), nil
}
}
return SpaceQuota{}, Warnings(warnings), actionerror.SpaceQuotaNotFoundByNameError{Name: quotaName}
} |
cloudfoundry/cli | 5010c000047f246b870475e2c299556078cdad30 | actor/v2action/space_quota.go | https://github.com/cloudfoundry/cli/blob/5010c000047f246b870475e2c299556078cdad30/actor/v2action/space_quota.go#L39-L42 | go | train | // SetSpaceQuota sets the space quota for the corresponding space | func (actor Actor) SetSpaceQuota(spaceGUID, quotaGUID string) (Warnings, error) | // SetSpaceQuota sets the space quota for the corresponding space
func (actor Actor) SetSpaceQuota(spaceGUID, quotaGUID string) (Warnings, error) | {
warnings, err := actor.CloudControllerClient.SetSpaceQuota(spaceGUID, quotaGUID)
return Warnings(warnings), err
} |
cloudfoundry/cli | 5010c000047f246b870475e2c299556078cdad30 | cf/configuration/coreconfig/config_repository.go | https://github.com/cloudfoundry/cli/blob/5010c000047f246b870475e2c299556078cdad30/cf/configuration/coreconfig/config_repository.go#L141-L148 | go | train | // ACCESS CONTROL | func (c *ConfigRepository) init() | // ACCESS CONTROL
func (c *ConfigRepository) init() | {
c.initOnce.Do(func() {
err := c.persistor.Load(c.data)
if err != nil {
c.onError(err)
}
})
} |
cloudfoundry/cli | 5010c000047f246b870475e2c299556078cdad30 | cf/configuration/coreconfig/config_repository.go | https://github.com/cloudfoundry/cli/blob/5010c000047f246b870475e2c299556078cdad30/cf/configuration/coreconfig/config_repository.go#L181-L186 | go | train | // GETTERS | func (c *ConfigRepository) APIVersion() (apiVersion string) | // GETTERS
func (c *ConfigRepository) APIVersion() (apiVersion string) | {
c.read(func() {
apiVersion = c.data.APIVersion
})
return
} |
cloudfoundry/cli | 5010c000047f246b870475e2c299556078cdad30 | cf/configuration/coreconfig/config_repository.go | https://github.com/cloudfoundry/cli/blob/5010c000047f246b870475e2c299556078cdad30/cf/configuration/coreconfig/config_repository.go#L432-L439 | go | train | // SETTERS | func (c *ConfigRepository) ClearSession() | // SETTERS
func (c *ConfigRepository) ClearSession() | {
c.write(func() {
c.data.AccessToken = ""
c.data.RefreshToken = ""
c.data.OrganizationFields = models.OrganizationFields{}
c.data.SpaceFields = models.SpaceFields{}
})
} |
cloudfoundry/cli | 5010c000047f246b870475e2c299556078cdad30 | actor/v2action/domain.go | https://github.com/cloudfoundry/cli/blob/5010c000047f246b870475e2c299556078cdad30/actor/v2action/domain.go#L38-L41 | go | train | // TODO: Move into own file or add function to CCV2/3 | func isResourceNotFoundError(err error) bool | // TODO: Move into own file or add function to CCV2/3
func isResourceNotFoundError(err error) bool | {
_, isResourceNotFound := err.(ccerror.ResourceNotFoundError)
return isResourceNotFound
} |
cloudfoundry/cli | 5010c000047f246b870475e2c299556078cdad30 | actor/v2action/domain.go | https://github.com/cloudfoundry/cli/blob/5010c000047f246b870475e2c299556078cdad30/actor/v2action/domain.go#L45-L66 | go | train | // GetDomain returns the shared or private domain associated with the provided
// Domain GUID. | func (actor Actor) GetDomain(domainGUID string) (Domain, Warnings, error) | // GetDomain returns the shared or private domain associated with the provided
// Domain GUID.
func (actor Actor) GetDomain(domainGUID string) (Domain, Warnings, error) | {
var allWarnings Warnings
domain, warnings, err := actor.GetSharedDomain(domainGUID)
allWarnings = append(allWarnings, warnings...)
switch err.(type) {
case nil:
return domain, allWarnings, nil
case actionerror.DomainNotFoundError:
default:
return Domain{}, allWarnings, err
}
domain, warnings, err = actor.GetPrivateDomain(domainGUID)
allWarnings = append(allWarnings, warnings...)
switch err.(type) {
case nil:
return domain, allWarnings, nil
default:
return Domain{}, allWarnings, err
}
} |
cloudfoundry/cli | 5010c000047f246b870475e2c299556078cdad30 | actor/v2action/domain.go | https://github.com/cloudfoundry/cli/blob/5010c000047f246b870475e2c299556078cdad30/actor/v2action/domain.go#L71-L115 | go | train | // GetDomainsByNameAndOrganization returns back a list of domains given a list
// of domains names and the organization GUID. If no domains are given, than this
// command will not lookup any domains. | func (actor Actor) GetDomainsByNameAndOrganization(domainNames []string, orgGUID string) ([]Domain, Warnings, error) | // GetDomainsByNameAndOrganization returns back a list of domains given a list
// of domains names and the organization GUID. If no domains are given, than this
// command will not lookup any domains.
func (actor Actor) GetDomainsByNameAndOrganization(domainNames []string, orgGUID string) ([]Domain, Warnings, error) | {
if len(domainNames) == 0 {
return nil, nil, nil
}
var domains []Domain
var allWarnings Warnings
// TODO: If the following causes URI length problems, break domainNames into
// batched (based on character length?) and loop over them.
sharedDomains, warnings, err := actor.CloudControllerClient.GetSharedDomains(ccv2.Filter{
Type: constant.NameFilter,
Operator: constant.InOperator,
Values: domainNames,
})
allWarnings = append(allWarnings, warnings...)
if err != nil {
return nil, allWarnings, err
}
for _, domain := range sharedDomains {
domains = append(domains, Domain(domain))
actor.saveDomain(domain)
}
privateDomains, warnings, err := actor.CloudControllerClient.GetOrganizationPrivateDomains(
orgGUID,
ccv2.Filter{
Type: constant.NameFilter,
Operator: constant.InOperator,
Values: domainNames,
})
allWarnings = append(allWarnings, warnings...)
if err != nil {
return nil, allWarnings, err
}
for _, domain := range privateDomains {
domains = append(domains, Domain(domain))
actor.saveDomain(domain)
}
return domains, allWarnings, err
} |
cloudfoundry/cli | 5010c000047f246b870475e2c299556078cdad30 | actor/v2action/domain.go | https://github.com/cloudfoundry/cli/blob/5010c000047f246b870475e2c299556078cdad30/actor/v2action/domain.go#L146-L162 | go | train | // GetSharedDomain returns the shared domain associated with the provided
// Domain GUID. | func (actor Actor) GetSharedDomain(domainGUID string) (Domain, Warnings, error) | // GetSharedDomain returns the shared domain associated with the provided
// Domain GUID.
func (actor Actor) GetSharedDomain(domainGUID string) (Domain, Warnings, error) | {
if domain, found := actor.loadDomain(domainGUID); found {
log.WithFields(log.Fields{
"domain": domain.Name,
"GUID": domain.GUID,
}).Debug("using domain from cache")
return domain, nil, nil
}
domain, warnings, err := actor.CloudControllerClient.GetSharedDomain(domainGUID)
if isResourceNotFoundError(err) {
return Domain{}, Warnings(warnings), actionerror.DomainNotFoundError{GUID: domainGUID}
}
actor.saveDomain(domain)
return Domain(domain), Warnings(warnings), err
} |
cloudfoundry/cli | 5010c000047f246b870475e2c299556078cdad30 | actor/v2action/domain.go | https://github.com/cloudfoundry/cli/blob/5010c000047f246b870475e2c299556078cdad30/actor/v2action/domain.go#L186-L213 | go | train | // GetOrganizationDomains returns the shared and private domains associated
// with an organization. | func (actor Actor) GetOrganizationDomains(orgGUID string) ([]Domain, Warnings, error) | // GetOrganizationDomains returns the shared and private domains associated
// with an organization.
func (actor Actor) GetOrganizationDomains(orgGUID string) ([]Domain, Warnings, error) | {
var (
allWarnings Warnings
allDomains []Domain
)
domains, warnings, err := actor.CloudControllerClient.GetSharedDomains()
allWarnings = append(allWarnings, warnings...)
if err != nil {
return []Domain{}, allWarnings, err
}
for _, domain := range domains {
allDomains = append(allDomains, Domain(domain))
}
domains, warnings, err = actor.CloudControllerClient.GetOrganizationPrivateDomains(orgGUID)
allWarnings = append(allWarnings, warnings...)
if err != nil {
return []Domain{}, allWarnings, err
}
for _, domain := range domains {
allDomains = append(allDomains, Domain(domain))
}
return allDomains, allWarnings, nil
} |
cloudfoundry/cli | 5010c000047f246b870475e2c299556078cdad30 | actor/v2action/actor.go | https://github.com/cloudfoundry/cli/blob/5010c000047f246b870475e2c299556078cdad30/actor/v2action/actor.go#L17-L24 | go | train | // NewActor returns a new actor. | func NewActor(ccClient CloudControllerClient, uaaClient UAAClient, config Config) *Actor | // NewActor returns a new actor.
func NewActor(ccClient CloudControllerClient, uaaClient UAAClient, config Config) *Actor | {
return &Actor{
CloudControllerClient: ccClient,
Config: config,
UAAClient: uaaClient,
domainCache: map[string]Domain{},
}
} |
cloudfoundry/cli | 5010c000047f246b870475e2c299556078cdad30 | actor/v7action/process_instance.go | https://github.com/cloudfoundry/cli/blob/5010c000047f246b870475e2c299556078cdad30/actor/v7action/process_instance.go#L21-L23 | go | train | // StartTime returns the time that the instance started. | func (instance *ProcessInstance) StartTime() time.Time | // StartTime returns the time that the instance started.
func (instance *ProcessInstance) StartTime() time.Time | {
return time.Now().Add(-instance.Uptime)
} |
cloudfoundry/cli | 5010c000047f246b870475e2c299556078cdad30 | command/plugin/shared/new_client.go | https://github.com/cloudfoundry/cli/blob/5010c000047f246b870475e2c299556078cdad30/command/plugin/shared/new_client.go#L11-L32 | go | train | // NewClient creates a new V2 Cloud Controller client and UAA client using the
// passed in config. | func NewClient(config command.Config, ui command.UI, skipSSLValidation bool) *plugin.Client | // NewClient creates a new V2 Cloud Controller client and UAA client using the
// passed in config.
func NewClient(config command.Config, ui command.UI, skipSSLValidation bool) *plugin.Client | {
verbose, location := config.Verbose()
pluginClient := plugin.NewClient(plugin.Config{
AppName: config.BinaryName(),
AppVersion: config.BinaryVersion(),
DialTimeout: config.DialTimeout(),
SkipSSLValidation: skipSSLValidation,
})
if verbose {
pluginClient.WrapConnection(wrapper.NewRequestLogger(ui.RequestLoggerTerminalDisplay()))
}
if location != nil {
pluginClient.WrapConnection(wrapper.NewRequestLogger(ui.RequestLoggerFileWriter(location)))
}
pluginClient.WrapConnection(wrapper.NewRetryRequest(config.RequestRetryCount()))
return pluginClient
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.