Apply linter suggestions (#2786)

* Refactor: if-elif-else => switch

Signed-off-by: Matej Vašek <mvasek@redhat.com>

* Cleanup: calls to embedded fields

Signed-off-by: Matej Vašek <mvasek@redhat.com>

* Fix: add missing err checks

Signed-off-by: Matej Vašek <mvasek@redhat.com>

* Cleanup: fix format of error messages

Signed-off-by: Matej Vašek <mvasek@redhat.com>

* Cleanup: omit type where possible

Signed-off-by: Matej Vašek <mvasek@redhat.com>

* Cleanup: apply De Morgan's law

Signed-off-by: Matej Vašek <mvasek@redhat.com>

* Cleanup: call ReplaceAll where possible

Signed-off-by: Matej Vašek <mvasek@redhat.com>

* Cleanup: fix format of error messages

Signed-off-by: Matej Vašek <mvasek@redhat.com>

* Cleanup: fix format of error messages

Signed-off-by: Matej Vašek <mvasek@redhat.com>

---------

Signed-off-by: Matej Vašek <mvasek@redhat.com>
This commit is contained in:
Matej Vašek 2025-04-15 11:43:13 +02:00 committed by GitHub
parent 36e27203a9
commit 8e0b752edc
No known key found for this signature in database
GPG Key ID: B5690EEEBB952194
26 changed files with 52 additions and 46 deletions

View File

@ -359,7 +359,7 @@ func (c buildConfig) Validate() (err error) {
// Platform is only supported with the S2I builder at this time
if c.Platform != "" && c.Builder != builders.S2I {
err = errors.New("Only S2I builds currently support specifying platform")
err = errors.New("only S2I builds currently support specifying platform")
return
}

View File

@ -534,7 +534,7 @@ func newHelpTemplate(cmd *cobra.Command) *template.Template {
fm := template.FuncMap{
"indent": func(i int, c string, v string) string {
indentation := strings.Repeat(c, i)
return indentation + strings.Replace(v, "\n", "\n"+indentation, -1)
return indentation + strings.ReplaceAll(v, "\n", "\n"+indentation)
},
}
t.Funcs(fm)

View File

@ -105,7 +105,7 @@ func newDeleteConfig(cmd *cobra.Command, args []string) (cfg deleteConfig, err e
// logicially inconsistent to supply only a namespace.
// Either use the function's local state in its entirety, or specify
// both a name and a namespace to ignore any local function source.
err = fmt.Errorf("must also specify a name when specifying namespace.")
err = fmt.Errorf("must also specify a name when specifying namespace")
}
if cfg.Name != "" && cmd.Flags().Changed("path") {
// logically inconsistent to provide both a name and a path to source.

View File

@ -378,7 +378,7 @@ func build(cmd *cobra.Command, flag string, f fn.Function, client *fn.Client, bu
return f, false, err
}
} else if _, err = strconv.ParseBool(flag); err != nil {
return f, false, fmt.Errorf("--build ($FUNC_BUILD) %q not recognized. Should be 'auto' or a truthy value such as 'true', 'false', '0', or '1'.", flag)
return f, false, fmt.Errorf("invalid value for the build flag (%q), valid value is either 'auto' or a boolean", flag)
} else if !build {
return f, false, nil
}

View File

@ -118,7 +118,7 @@ func newDescribeConfig(cmd *cobra.Command, args []string) (cfg describeConfig, e
// logicially inconsistent to supply only a namespace.
// Either use the function's local state in its entirety, or specify
// both a name and a namespace to ignore any local function source.
err = fmt.Errorf("must also specify a name when specifying namespace.")
err = fmt.Errorf("must also specify a name when specifying namespace")
}
if cfg.Name != "" && cmd.Flags().Changed("path") {
// logically inconsistent to provide both a name and a path to source.

View File

@ -44,7 +44,7 @@ func write(out io.Writer, s Formatter, formatName string) {
case URL:
err = s.URL(out)
default:
err = fmt.Errorf("format not recognized: %v\n", formatName)
err = fmt.Errorf("format not recognized: %v", formatName)
}
if err != nil {
panic(err)

View File

@ -39,7 +39,7 @@ func main() {
os.Exit(137)
}()
var cmd func(context.Context) error = unknown
var cmd = unknown
switch filepath.Base(os.Args[0]) {
case "deploy":

View File

@ -130,7 +130,7 @@ func newListConfig(cmd *cobra.Command) (cfg listConfig, err error) {
// specifying both -A and --namespace is logically inconsistent
if cmd.Flags().Changed("namespace") && viper.GetBool("all-namespaces") {
err = errors.New("Both --namespace and --all-namespaces specified.")
err = errors.New("both --namespace and --all-namespaces specified")
}
return

View File

@ -529,7 +529,7 @@ func runRepositoryRemove(_ *cobra.Command, args []string, newClient ClientFactor
}
if len(repositories) == 0 {
return errors.New("No repositories installed. use 'add' to install")
return errors.New("no repositories installed. use 'add' to install")
}
// Confirm (interactive prompt mode)

View File

@ -350,7 +350,7 @@ func (c runConfig) Validate(cmd *cobra.Command, f fn.Function) (err error) {
}
if !c.Container && !oci.IsSupported(f.Runtime) {
return fmt.Errorf("The %q runtime currently requires being run in a container", f.Runtime)
return fmt.Errorf("the %q runtime currently requires being run in a container", f.Runtime)
}
// When the docker runner respects the StartTimeout, this validation check

View File

@ -21,7 +21,7 @@ var (
fm = template.FuncMap{
"indent": func(i int, c string, v string) string {
indentation := strings.Repeat(c, i)
return indentation + strings.Replace(v, "\n", "\n"+indentation, -1)
return indentation + strings.ReplaceAll(v, "\n", "\n"+indentation)
},
"rootCmdUse": func() string {
return rootName

View File

@ -818,7 +818,7 @@ func fixupGoBuildpackARM64(ctx context.Context, config *builder.Config) error {
goBuildpackVersion string
)
for i, moduleConfig := range config.Buildpacks {
uri := moduleConfig.ImageOrURI.URI
uri := moduleConfig.URI
if strings.Contains(uri, "buildpacks/go:") {
goBuildpackIndex = i
goBuildpackVersion = uri[strings.LastIndex(uri, ":")+1:]
@ -879,7 +879,7 @@ func fixupGoBuildpackARM64(ctx context.Context, config *builder.Config) error {
re := regexp.MustCompile(`^urn:cnb:registry:paketo-buildpacks/([\w-]+)@([\d.]+)$`)
for i, dep := range packageConfig.Dependencies {
m := re.FindStringSubmatch(dep.BuildpackURI.URI)
m := re.FindStringSubmatch(dep.URI)
if len(m) != 3 {
return fmt.Errorf("cannot match buildpack name")
}
@ -931,7 +931,7 @@ func fixupGoBuildpackARM64(ctx context.Context, config *builder.Config) error {
return err
}
config.Buildpacks[goBuildpackIndex].BuildpackURI.URI = "file://" + filepath.Join(goBuildpackSrcDir, "build", "buildpackage.cnb")
config.Buildpacks[goBuildpackIndex].URI = "file://" + filepath.Join(goBuildpackSrcDir, "build", "buildpackage.cnb")
fmt.Println(goBuildpackSrcDir)
return nil
}
@ -1176,6 +1176,9 @@ func patchStack(stackTomlPath string) error {
m["run"].(map[string]any)["platforms"] = map[string]any{"linux/arm64": args}
output, err := toml.Marshal(data)
if err != nil {
return fmt.Errorf("cannot marshal config: %w", err)
}
err = os.WriteFile(stackTomlPath, output, 0644)
if err != nil {
return fmt.Errorf("cannot write patched stack toml: %w", err)

View File

@ -120,7 +120,7 @@ var DefaultLifecycleImage = "docker.io/buildpacksio/lifecycle:553c041"
// Build the Function at path.
func (b *Builder) Build(ctx context.Context, f fn.Function, platforms []fn.Platform) (err error) {
if len(platforms) != 0 {
return errors.New("the pack builder does not support specifying target platforms directly.")
return errors.New("the pack builder does not support specifying target platforms directly")
}
// Builder image from the function if defined, default otherwise.

View File

@ -197,7 +197,7 @@ func (b *Builder) Build(ctx context.Context, f fn.Function, platforms []fn.Platf
for _, e := range errs {
fmt.Fprintf(os.Stderr, "ERROR: %s\n", e)
}
return errors.New("Unable to build via the s2i builder.")
return errors.New("unable to build via the s2i builder")
}
// Create the S2I builder instance if not overridden

View File

@ -210,7 +210,7 @@ func TestCheckAuthEmptyCreds(t *testing.T) {
// generate Certificates
func generateCert(t *testing.T) (tls.Certificate, *x509.Certificate) {
var randReader io.Reader = rand.Reader
var randReader = rand.Reader
caPublicKey, caPrivateKey, err := ed25519.GenerateKey(randReader)
if err != nil {

View File

@ -187,7 +187,7 @@ func (n *Pusher) pushImage(ctx context.Context, f fn.Function, credentials Crede
}
if f.Build.Image == "" {
return "", errors.New("Function has no associated image. Has it been built?")
return "", errors.New("function has no associated image. Has it been built?")
}
registry, err := GetRegistry(f.Build.Image)

View File

@ -121,16 +121,16 @@ func (n *Runner) Run(ctx context.Context, f fn.Function, startTimeout time.Durat
Timeout: &timeoutSecs,
}
if err = c.ContainerStop(ctx, id, ctrStopOpts); err != nil {
return fmt.Errorf("error stopping container %v: %v\n", id, err)
return fmt.Errorf("error stopping container %v: %v", id, err)
}
if err = c.ContainerRemove(ctx, id, container.RemoveOptions{}); err != nil {
return fmt.Errorf("error removing container %v: %v\n", id, err)
return fmt.Errorf("error removing container %v: %v", id, err)
}
if err = conn.Close(); err != nil {
return fmt.Errorf("error closing connection to container: %v\n", err)
return fmt.Errorf("error closing connection to container: %v", err)
}
if err = c.Close(); err != nil {
return fmt.Errorf("error closing daemon client: %v\n", err)
return fmt.Errorf("error closing daemon client: %v", err)
}
return nil
}

View File

@ -893,7 +893,7 @@ func (c *Client) Route(ctx context.Context, f Function) (string, Function, error
}
if f.Deploy.Namespace == "" {
return "", Function{}, errors.New("Unable to route function without a namespace. Is it deployed?")
return "", Function{}, errors.New("unable to route function without a namespace. Is it deployed?")
}
// Return the correct route.

View File

@ -74,10 +74,10 @@ func (t template) Write(ctx context.Context, f *Function) error {
f.Run.Envs = t.config.RunEnvs
}
if f.Deploy.HealthEndpoints.Liveness == "" {
f.Deploy.HealthEndpoints.Liveness = t.config.HealthEndpoints.Liveness
f.Deploy.HealthEndpoints.Liveness = t.config.Liveness
}
if f.Deploy.HealthEndpoints.Readiness == "" {
f.Deploy.HealthEndpoints.Readiness = t.config.HealthEndpoints.Readiness
f.Deploy.HealthEndpoints.Readiness = t.config.Readiness
}
if f.Invoke == "" && t.config.Invoke != "http" {
f.Invoke = t.config.Invoke

View File

@ -41,14 +41,14 @@ func (c Client) CreateWebHook(ctx context.Context, repoOwner, repoName, payloadU
return err
}
if res.Response.StatusCode != http.StatusCreated {
if res.StatusCode != http.StatusCreated {
payload, err := io.ReadAll(res.Body)
if err != nil {
return fmt.Errorf("failed to read response body: %w", err)
}
return fmt.Errorf("failed to create webhook on repository %v/%v, status code: %v, error : %v",
repoOwner, repoName, res.Response.StatusCode, payload)
repoOwner, repoName, res.StatusCode, payload)
}
return nil

View File

@ -70,7 +70,7 @@ type contextDialer struct {
}
func (c *contextDialer) DialContext(ctx context.Context, network string, addr string) (net.Conn, error) {
if !(network == "tcp" || network == "tcp4" || network == "tcp6") {
if network != "tcp" && network != "tcp4" && network != "tcp6" {
return nil, fmt.Errorf("unsupported network: %q", network)
}

View File

@ -141,7 +141,7 @@ func (d *Deployer) Deploy(ctx context.Context, f fn.Function) (fn.DeploymentResu
namespace = f.Deploy.Namespace
}
if namespace == "" {
return fn.DeploymentResult{}, fmt.Errorf("deployer requires either a target namespace or that the function be already deployed.")
return fn.DeploymentResult{}, fmt.Errorf("deployer requires either a target namespace or that the function be already deployed")
}
// Clients
@ -583,8 +583,8 @@ func updateService(f fn.Function, previousService *v1.Service, newEnv []corev1.E
revisionAnnotations[k] = v
}
service.ObjectMeta.Annotations = annotations
service.Spec.Template.ObjectMeta.Annotations = revisionAnnotations
service.Annotations = annotations
service.Spec.Template.Annotations = revisionAnnotations
// I hate that we have to do this. Users should not see these values.
// It is an implementation detail. These health endpoints should not be
@ -611,8 +611,8 @@ func updateService(f fn.Function, previousService *v1.Service, newEnv []corev1.E
return nil, err
}
service.ObjectMeta.Labels = labels
service.Spec.Template.ObjectMeta.Labels = labels
service.Labels = labels
service.Spec.Template.Labels = labels
err = flags.UpdateImage(&service.Spec.Template.Spec.PodSpec, f.Deploy.Image)
if err != nil {
@ -622,8 +622,8 @@ func updateService(f fn.Function, previousService *v1.Service, newEnv []corev1.E
cp.Env = newEnv
cp.EnvFrom = newEnvFrom
cp.VolumeMounts = newVolumeMounts
service.Spec.ConfigurationSpec.Template.Spec.Volumes = newVolumes
service.Spec.ConfigurationSpec.Template.Spec.PodSpec.ServiceAccountName = f.Deploy.ServiceAccountName
service.Spec.Template.Spec.Volumes = newVolumes
service.Spec.Template.Spec.ServiceAccountName = f.Deploy.ServiceAccountName
return service, nil
}
}
@ -1056,20 +1056,20 @@ func setServiceOptions(template *v1.RevisionTemplateSpec, options fn.Options) er
}
// in the container always set Requests/Limits & Concurrency values based on the contents of config
template.Spec.PodSpec.Containers[0].Resources.Requests = nil
template.Spec.PodSpec.Containers[0].Resources.Limits = nil
template.Spec.Containers[0].Resources.Requests = nil
template.Spec.Containers[0].Resources.Limits = nil
template.Spec.ContainerConcurrency = nil
if options.Resources != nil {
if options.Resources.Requests != nil {
template.Spec.PodSpec.Containers[0].Resources.Requests = corev1.ResourceList{}
template.Spec.Containers[0].Resources.Requests = corev1.ResourceList{}
if options.Resources.Requests.CPU != nil {
value, err := resource.ParseQuantity(*options.Resources.Requests.CPU)
if err != nil {
return err
}
template.Spec.PodSpec.Containers[0].Resources.Requests[corev1.ResourceCPU] = value
template.Spec.Containers[0].Resources.Requests[corev1.ResourceCPU] = value
}
if options.Resources.Requests.Memory != nil {
@ -1077,19 +1077,19 @@ func setServiceOptions(template *v1.RevisionTemplateSpec, options fn.Options) er
if err != nil {
return err
}
template.Spec.PodSpec.Containers[0].Resources.Requests[corev1.ResourceMemory] = value
template.Spec.Containers[0].Resources.Requests[corev1.ResourceMemory] = value
}
}
if options.Resources.Limits != nil {
template.Spec.PodSpec.Containers[0].Resources.Limits = corev1.ResourceList{}
template.Spec.Containers[0].Resources.Limits = corev1.ResourceList{}
if options.Resources.Limits.CPU != nil {
value, err := resource.ParseQuantity(*options.Resources.Limits.CPU)
if err != nil {
return err
}
template.Spec.PodSpec.Containers[0].Resources.Limits[corev1.ResourceCPU] = value
template.Spec.Containers[0].Resources.Limits[corev1.ResourceCPU] = value
}
if options.Resources.Limits.Memory != nil {
@ -1097,7 +1097,7 @@ func setServiceOptions(template *v1.RevisionTemplateSpec, options fn.Options) er
if err != nil {
return err
}
template.Spec.PodSpec.Containers[0].Resources.Limits[corev1.ResourceMemory] = value
template.Spec.Containers[0].Resources.Limits[corev1.ResourceMemory] = value
}
if options.Resources.Limits.Concurrency != nil {

View File

@ -68,6 +68,9 @@ func (b goBuilder) WritePlatform(cfg buildJob, p v1.Platform) (layers []imageLay
fmt.Printf("mv %v %v\n", rel(cfg.buildDir(), target), rel(cfg.buildDir(), blob))
}
err = os.Rename(target, blob)
if err != nil {
return nil, fmt.Errorf("cannot rename blob: %w", err)
}
// NOTE: base is intentionally blank indiciating it is to be built without
// a base layer.

View File

@ -28,7 +28,7 @@ func NewRegistry() *Registry {
}
func (r *Registry) Addr() net.Addr {
return r.Server.Listener.Addr()
return r.Listener.Addr()
}
func (r *Registry) Close() {

View File

@ -436,7 +436,7 @@ spec:
// GetClusterTasks returns multi-document yaml containing tekton tasks used by func.
func GetClusterTasks() string {
tasks := getBuildpackTask() + "\n---\n" + getS2ITask() + "\n---\n" + getDeployTask() + "\n---\n" + getScaffoldTask()
tasks = strings.Replace(tasks, "kind: Task", "kind: ClusterTask", -1)
tasks = strings.ReplaceAll(tasks, "kind: Task", "kind: ClusterTask")
tasks = strings.ReplaceAll(tasks, "apiVersion: tekton.dev/v1", "apiVersion: tekton.dev/v1beta1")
return tasks
}

View File

@ -28,7 +28,7 @@ func Extract(input io.Reader, destDir string) error {
r := tar.NewReader(input)
var first bool = true
var first = true
for {
var hdr *tar.Header
hdr, err = r.Next()