Skip to content

Golangci-lint v2 fixes #17573

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 15 commits into from
Aug 23, 2025
5 changes: 2 additions & 3 deletions channels/pkg/cmd/apply_channel.go
Original file line number Diff line number Diff line change
Expand Up @@ -24,7 +24,6 @@ import (
"os"

"github.com/blang/semver/v4"
"github.com/cert-manager/cert-manager/pkg/client/clientset/versioned"
certmanager "github.com/cert-manager/cert-manager/pkg/client/clientset/versioned"
"github.com/spf13/cobra"
"go.uber.org/multierr"
Expand Down Expand Up @@ -120,7 +119,7 @@ func RunApplyChannel(ctx context.Context, f *ChannelsFactory, out io.Writer, opt
return applyMenu(ctx, menu, f.VFSContext(), k8sClient, cmClient, dynamicClient, restMapper, options.Yes)
}

func applyMenu(ctx context.Context, menu *channels.AddonMenu, vfsContext *vfs.VFSContext, k8sClient kubernetes.Interface, cmClient versioned.Interface, dynamicClient dynamic.Interface, restMapper *restmapper.DeferredDiscoveryRESTMapper, apply bool) error {
func applyMenu(ctx context.Context, menu *channels.AddonMenu, vfsContext *vfs.VFSContext, k8sClient kubernetes.Interface, cmClient certmanager.Interface, dynamicClient dynamic.Interface, restMapper *restmapper.DeferredDiscoveryRESTMapper, apply bool) error {
// channelVersions is the list of installed addons in the cluster.
// It is keyed by <namespace>:<addon name>.
channelVersions, err := getChannelVersions(ctx, k8sClient)
Expand Down Expand Up @@ -198,7 +197,7 @@ func applyMenu(ctx context.Context, menu *channels.AddonMenu, vfsContext *vfs.VF
return merr
}

func getUpdates(ctx context.Context, menu *channels.AddonMenu, k8sClient kubernetes.Interface, cmClient versioned.Interface, channelVersions map[string]*channels.ChannelVersion) ([]*channels.AddonUpdate, []*channels.Addon, error) {
func getUpdates(ctx context.Context, menu *channels.AddonMenu, k8sClient kubernetes.Interface, cmClient certmanager.Interface, channelVersions map[string]*channels.ChannelVersion) ([]*channels.AddonUpdate, []*channels.Addon, error) {
var updates []*channels.AddonUpdate
var needUpdates []*channels.Addon
for _, addon := range menu.Addons {
Expand Down
7 changes: 4 additions & 3 deletions cloudmock/openstack/mocknetworking/routers.go
Original file line number Diff line number Diff line change
Expand Up @@ -181,7 +181,8 @@ func (m *MockClient) routerInterface(w http.ResponseWriter, r *http.Request) {
if err != nil {
panic("error decoding create router interface request")
}
if parts[2] == "add_router_interface" {
switch parts[2] {
case "add_router_interface":
subnet := m.subnets[createInterface.SubnetID]
interfaces := m.routerInterfaces[routerID]
interfaces = append(interfaces, routers.InterfaceInfo{
Expand All @@ -201,15 +202,15 @@ func (m *MockClient) routerInterface(w http.ResponseWriter, r *http.Request) {
},
}
m.ports[port.ID] = port
} else if parts[2] == "remove_router_interface" {
case "remove_router_interface":
interfaces := make([]routers.InterfaceInfo, 0)
for _, i := range m.routerInterfaces[routerID] {
if i.SubnetID != createInterface.SubnetID {
interfaces = append(interfaces, i)
}
}
m.routerInterfaces[routerID] = interfaces
} else {
default:
w.WriteHeader(http.StatusBadRequest)
return
}
Expand Down
2 changes: 1 addition & 1 deletion cloudmock/scaleway/mockdns/api.go
Original file line number Diff line number Diff line change
Expand Up @@ -107,7 +107,7 @@ func (f *FakeDomainAPI) UpdateDNSZoneRecords(req *domain.UpdateDNSZoneRecordsReq
break
}
}
if found == false {
if !found {
return nil, fmt.Errorf("could not find record %s to delete", *change.Delete.ID)
}

Expand Down
6 changes: 3 additions & 3 deletions cmd/kops-controller/pkg/server/server.go
Original file line number Diff line number Diff line change
Expand Up @@ -161,7 +161,7 @@ func (s *Server) bootstrap(w http.ResponseWriter, r *http.Request) {
if err != nil {
klog.Infof("bootstrap %s read err: %v", r.RemoteAddr, err)
w.WriteHeader(http.StatusBadRequest)
_, _ = w.Write([]byte(fmt.Sprintf("bootstrap %s failed to read body: %v", r.RemoteAddr, err)))
_, _ = fmt.Fprintf(w, "bootstrap %s failed to read body: %v", r.RemoteAddr, err)
return
}

Expand Down Expand Up @@ -208,7 +208,7 @@ func (s *Server) bootstrap(w http.ResponseWriter, r *http.Request) {
if err := json.Unmarshal(body, req); err != nil {
klog.Infof("bootstrap %s decode err: %v", r.RemoteAddr, err)
w.WriteHeader(http.StatusBadRequest)
_, _ = w.Write([]byte(fmt.Sprintf("failed to decode: %v", err)))
_, _ = fmt.Fprintf(w, "failed to decode: %v", err)
return
}

Expand Down Expand Up @@ -264,7 +264,7 @@ func (s *Server) bootstrap(w http.ResponseWriter, r *http.Request) {
if err != nil {
klog.Infof("bootstrap %s cert %q issue err: %v", r.RemoteAddr, name, err)
w.WriteHeader(http.StatusBadRequest)
_, _ = w.Write([]byte(fmt.Sprintf("failed to issue %q: %v", name, err)))
_, _ = fmt.Fprintf(w, "failed to issue %q: %v", name, err)
return
}
resp.Certs[name] = cert
Expand Down
2 changes: 1 addition & 1 deletion cmd/kops/create_cluster.go
Original file line number Diff line number Diff line change
Expand Up @@ -858,7 +858,7 @@ func parseCloudLabels(s string) (map[string]string, error) {
// Replace commas with newlines to allow a single pass with csv.Reader.
// We can't use csv.Reader for the initial split because it would see each key=value record as a single field
// and significantly complicates using quoted fields as keys or values.
records := strings.Replace(s, ",", "\n", -1)
records := strings.ReplaceAll(s, ",", "\n")

// Let the CSV library do the heavy-lifting in handling nested ='s
r := csv.NewReader(strings.NewReader(records))
Expand Down
7 changes: 4 additions & 3 deletions cmd/kops/integration_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -1605,7 +1605,7 @@ func (i *integrationTest) runTestTerraformAWS(t *testing.T) {
"aws_cloudwatch_event_rule_" + awsup.GetClusterName40(i.clusterName) + "-SpotInterruption_event_pattern",
"aws_cloudwatch_event_rule_" + awsup.GetClusterName40(i.clusterName) + "-InstanceStateChange_event_pattern",
"aws_cloudwatch_event_rule_" + awsup.GetClusterName40(i.clusterName) + "-InstanceScheduledChange_event_pattern",
"aws_sqs_queue_" + strings.Replace(i.clusterName, ".", "-", -1) + "-nth_policy",
"aws_sqs_queue_" + strings.ReplaceAll(i.clusterName, ".", "-") + "-nth_policy",
}...)
}
if i.nthRebalance {
Expand Down Expand Up @@ -1633,7 +1633,8 @@ func (i *integrationTest) runTestPhase(t *testing.T, phase cloudup.Phase) {

expectedFilenames := i.expectTerraformFilenames

if phase == cloudup.PhaseSecurity {
switch phase {
case cloudup.PhaseSecurity:
expectedFilenames = []string{
"aws_iam_role_masters." + i.clusterName + "_policy",
"aws_iam_role_nodes." + i.clusterName + "_policy",
Expand All @@ -1648,7 +1649,7 @@ func (i *integrationTest) runTestPhase(t *testing.T, phase cloudup.Phase) {
"aws_launch_template_bastion." + i.clusterName + "_user_data",
}...)
}
} else if phase == cloudup.PhaseCluster {
case cloudup.PhaseCluster:
expectedFilenames = []string{
"aws_launch_template_nodes." + i.clusterName + "_user_data",
}
Expand Down
2 changes: 1 addition & 1 deletion cmd/kops/lifecycle_integration_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -56,7 +56,7 @@ func (o *LifecycleTestOptions) AddDefaults() {
o.Version = "v1alpha2"
}
if o.ClusterName == "" {
o.ClusterName = strings.Replace(o.SrcDir, "_", "", -1) + ".example.com"
o.ClusterName = strings.ReplaceAll(o.SrcDir, "_", "") + ".example.com"
}

o.SrcDir = "../../tests/integration/update_cluster/" + o.SrcDir
Expand Down
7 changes: 4 additions & 3 deletions cmd/kops/toolbox_instance-selector.go
Original file line number Diff line number Diff line change
Expand Up @@ -520,7 +520,8 @@ func decorateWithMixedInstancesPolicy(instanceGroup *kops.InstanceGroup, usageCl
ig := instanceGroup
ig.Spec.MachineType = instanceSelections[0]

if usageClass == ec2types.UsageClassTypeSpot {
switch usageClass {
case ec2types.UsageClassTypeSpot:
ondemandBase := int64(0)
ondemandAboveBase := int64(0)
spotAllocationStrategy := "capacity-optimized"
Expand All @@ -530,11 +531,11 @@ func decorateWithMixedInstancesPolicy(instanceGroup *kops.InstanceGroup, usageCl
OnDemandAboveBase: &ondemandAboveBase,
SpotAllocationStrategy: &spotAllocationStrategy,
}
} else if usageClass == ec2types.UsageClassTypeOnDemand {
case ec2types.UsageClassTypeOnDemand:
ig.Spec.MixedInstancesPolicy = &kops.MixedInstancesPolicySpec{
Instances: instanceSelections,
}
} else {
default:
return nil, fmt.Errorf("error node usage class not supported")
}

Expand Down
5 changes: 2 additions & 3 deletions cmd/kops/validate_cluster.go
Original file line number Diff line number Diff line change
Expand Up @@ -36,7 +36,6 @@ import (
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
"k8s.io/klog/v2"
"k8s.io/kops/cmd/kops/util"
"k8s.io/kops/pkg/apis/kops"
kopsapi "k8s.io/kops/pkg/apis/kops"
"k8s.io/kops/pkg/validation"
"k8s.io/kops/util/pkg/tables"
Expand All @@ -63,15 +62,15 @@ var (

type ValidateClusterOptions struct {
ClusterName string
InstanceGroupRoles []kops.InstanceGroupRole
InstanceGroupRoles []kopsapi.InstanceGroupRole
output string
wait time.Duration
count int
interval time.Duration
kubeconfig string

// filterInstanceGroups is a function that returns true if the instance group should be validated
filterInstanceGroups func(ig *kops.InstanceGroup) bool
filterInstanceGroups func(ig *kopsapi.InstanceGroup) bool

// filterPodsForValidation is a function that returns true if the pod should be validated
filterPodsForValidation func(pod *v1.Pod) bool
Expand Down
5 changes: 3 additions & 2 deletions dns-controller/pkg/watchers/node.go
Original file line number Diff line number Diff line change
Expand Up @@ -201,9 +201,10 @@ func (c *NodeController) updateNodeRecords(node *v1.Node) string {

for _, a := range node.Status.Addresses {
var roleType string
if a.Type == v1.NodeInternalIP {
switch a.Type {
case v1.NodeInternalIP:
roleType = dns.RoleTypeInternal
} else if a.Type == v1.NodeExternalIP {
case v1.NodeExternalIP:
roleType = dns.RoleTypeExternal
}
var recordType dns.RecordType = dns.RecordTypeA
Expand Down
7 changes: 4 additions & 3 deletions dns-controller/pkg/watchers/service.go
Original file line number Diff line number Diff line change
Expand Up @@ -152,7 +152,8 @@ func (c *ServiceController) updateServiceRecords(service *v1.Service) string {
if len(specExternal) != 0 || len(specInternal) != 0 {
var ingresses []dns.Record

if service.Spec.Type == v1.ServiceTypeLoadBalancer {
switch service.Spec.Type {
case v1.ServiceTypeLoadBalancer:
for i := range service.Status.LoadBalancer.Ingress {
ingress := &service.Status.LoadBalancer.Ingress[i]
if ingress.Hostname != "" {
Expand All @@ -175,7 +176,7 @@ func (c *ServiceController) updateServiceRecords(service *v1.Service) string {
klog.V(4).Infof("Found A record for service %s/%s: %q", service.Namespace, service.Name, ingress.IP)
}
}
} else if service.Spec.Type == v1.ServiceTypeNodePort {
case v1.ServiceTypeNodePort:
var roleType string
if len(specExternal) != 0 && len(specInternal) != 0 {
klog.Warningln("DNS Records not possible for both Internal and Externals IPs.")
Expand All @@ -190,7 +191,7 @@ func (c *ServiceController) updateServiceRecords(service *v1.Service) string {
Value: dns.AliasForNodesInRole("node", roleType),
})
klog.V(4).Infof("Setting internal alias for NodePort service %s/%s", service.Namespace, service.Name)
} else {
default:
// TODO: Emit event so that users are informed of this
klog.V(2).Infof("Cannot expose service %s/%s of type %q", service.Namespace, service.Name, service.Spec.Type)
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -46,6 +46,6 @@ func (m *ManagedZonesService) List(project string) interfaces.ManagedZonesListCa
}

func (m *ManagedZonesService) NewManagedZone(dnsName string) interfaces.ManagedZone {
name := "x" + strings.Replace(string(uuid.NewUUID()), "-", "", -1)[0:30] // Unique name, strip out the "-" chars to shorten it, start with a lower case alpha, and truncate to Cloud DNS 32 character limit
name := "x" + strings.ReplaceAll(string(uuid.NewUUID()), "-", "")[0:30] // Unique name, strip out the "-" chars to shorten it, start with a lower case alpha, and truncate to Cloud DNS 32 character limit
return &ManagedZone{impl: &dns.ManagedZone{Name: name, Description: "Kubernetes Federated Service", DnsName: dnsName}}
}
2 changes: 1 addition & 1 deletion nodeup/pkg/model/kube_apiserver.go
Original file line number Diff line number Diff line change
Expand Up @@ -795,7 +795,7 @@ func (b *KubeAPIServerBuilder) buildPod(ctx context.Context, kubeAPIServer *kops
}

for _, path := range b.SSLHostPaths() {
name := strings.Replace(path, "/", "", -1)
name := strings.ReplaceAll(path, "/", "")
kubemanifest.AddHostPathMapping(pod, container, name, path)
}

Expand Down
2 changes: 1 addition & 1 deletion nodeup/pkg/model/kube_controller_manager.go
Original file line number Diff line number Diff line change
Expand Up @@ -261,7 +261,7 @@ func (b *KubeControllerManagerBuilder) buildPod(kcm *kops.KubeControllerManagerC
container.Args = append(container.Args, sortedStrings(flags)...)
}
for _, path := range b.SSLHostPaths() {
name := strings.Replace(path, "/", "", -1)
name := strings.ReplaceAll(path, "/", "")
kubemanifest.AddHostPathMapping(pod, container, name, path)
}

Expand Down
4 changes: 2 additions & 2 deletions nodeup/pkg/model/kubelet_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -101,8 +101,8 @@ func TestTaintsApplied(t *testing.T) {
}

func stringSlicesEqual(exp, other []string) bool {
sort.Sort(sort.StringSlice(exp))
sort.Sort(sort.StringSlice(other))
sort.Strings(exp)
sort.Strings(other)
if exp == nil && other != nil {
return false
}
Expand Down
5 changes: 3 additions & 2 deletions pkg/apis/kops/validation/validation.go
Original file line number Diff line number Diff line change
Expand Up @@ -1629,13 +1629,14 @@ func validateCalicoAutoDetectionMethod(fldPath *field.Path, runtime string, vers
case "can-reach":
destStr := method[1]
ip := netutils.ParseIPSloppy(destStr)
if version == ipv4.Version {
switch version {
case ipv4.Version:
if ip == nil || ip.To4() == nil {
return field.ErrorList{field.Invalid(fldPath, runtime, "must be a valid IPv4 address")}
} else {
return nil
}
} else if version == ipv6.Version {
case ipv6.Version:
if ip == nil || ip.To4() != nil {
return field.ErrorList{field.Invalid(fldPath, runtime, "must be a valid IPv6 address")}
} else {
Expand Down
7 changes: 4 additions & 3 deletions pkg/applylib/mocks/mockkubeapiserver/putresource.go
Original file line number Diff line number Diff line change
Expand Up @@ -62,17 +62,18 @@ func (req *putResource) Run(s *MockKubeAPIServer) error {

var updated *unstructured.Unstructured

if req.SubResource == "" {
switch req.SubResource {
case "":
updated = body
} else if req.SubResource == "status" {
case "status":
updated = existing.DeepCopyObject().(*unstructured.Unstructured)
newStatus := body.Object["status"]
if newStatus == nil {
// TODO: This might be allowed?
return fmt.Errorf("status not specified on status subresource update")
}
updated.Object["status"] = newStatus
} else {
default:
// TODO: We need to implement put properly
return fmt.Errorf("unknown subresource %q", req.SubResource)
}
Expand Down
2 changes: 1 addition & 1 deletion pkg/assets/builder.go
Original file line number Diff line number Diff line change
Expand Up @@ -374,7 +374,7 @@ func NormalizeImage(a *AssetBuilder, image string) string {
if !strings.HasPrefix(normalized, registryMirror+"/") {
// We can't nest arbitrarily
// Some risk of collisions, but also -- and __ in the names appear to be blocked by docker hub
normalized = strings.Replace(normalized, "/", "-", -1)
normalized = strings.ReplaceAll(normalized, "/", "-")
normalized = registryMirror + "/" + normalized
}
image = normalized
Expand Down
2 changes: 1 addition & 1 deletion pkg/client/simple/api/clientset.go
Original file line number Diff line number Diff line change
Expand Up @@ -196,6 +196,6 @@ func restNamespaceForClusterName(clusterName string) string {
// We are not allowed dots, so we map them to dashes
// This can conflict, but this will simply be a limitation that we pass on to the user
// i.e. it will not be possible to create a.b.example.com and a-b.example.com
namespace := strings.Replace(clusterName, ".", "-", -1)
namespace := strings.ReplaceAll(clusterName, ".", "-")
return namespace
}
5 changes: 1 addition & 4 deletions pkg/commands/toolbox_enroll.go
Original file line number Diff line number Diff line change
Expand Up @@ -118,10 +118,7 @@ func RunToolboxEnroll(ctx context.Context, f commandutils.Factory, out io.Writer
return err
}

sudo := true
if options.SSHUser == "root" {
sudo = false
}
sudo := options.SSHUser != "root"

sshTarget, err := NewSSHHost(ctx, options.Host, options.SSHPort, options.SSHUser, sudo)
if err != nil {
Expand Down
2 changes: 1 addition & 1 deletion pkg/model/awsmodel/api_loadbalancer.go
Original file line number Diff line number Diff line change
Expand Up @@ -607,7 +607,7 @@ func (a ByScoreDescending) Swap(i, j int) { a[i], a[j] = a[j], a[i] }
func (a ByScoreDescending) Less(i, j int) bool {
if a[i].score != a[j].score {
// ! to sort highest score first
return !(a[i].score < a[j].score)
return a[i].score >= a[j].score
}
// Use name to break ties consistently
return a[i].subnet.Name < a[j].subnet.Name
Expand Down
7 changes: 4 additions & 3 deletions pkg/model/awsmodel/autoscalinggroup.go
Original file line number Diff line number Diff line change
Expand Up @@ -311,11 +311,12 @@ func (b *AutoscalingGroupModelBuilder) buildLaunchTemplateTask(c *fi.CloudupMode
lt.HTTPTokens = fi.PtrTo(ec2types.LaunchTemplateHttpTokensStateOptional)
}

if rootVolumeType == ec2types.VolumeTypeIo1 || rootVolumeType == ec2types.VolumeTypeIo2 {
switch rootVolumeType {
case ec2types.VolumeTypeIo1, ec2types.VolumeTypeIo2:
if ig.Spec.RootVolume == nil || fi.ValueOf(ig.Spec.RootVolume.IOPS) < 100 {
lt.RootVolumeIops = fi.PtrTo(int32(DefaultVolumeIonIops))
}
} else if rootVolumeType == ec2types.VolumeTypeGp3 {
case ec2types.VolumeTypeGp3:
if ig.Spec.RootVolume == nil || fi.ValueOf(ig.Spec.RootVolume.IOPS) < 3000 {
lt.RootVolumeIops = fi.PtrTo(int32(DefaultVolumeGp3Iops))
}
Expand All @@ -324,7 +325,7 @@ func (b *AutoscalingGroupModelBuilder) buildLaunchTemplateTask(c *fi.CloudupMode
} else {
lt.RootVolumeThroughput = fi.PtrTo(int32(fi.ValueOf(ig.Spec.RootVolume.Throughput)))
}
} else {
default:
lt.RootVolumeIops = nil
}

Expand Down
2 changes: 1 addition & 1 deletion pkg/model/context.go
Original file line number Diff line number Diff line change
Expand Up @@ -265,7 +265,7 @@ func (b *KopsModelContext) CloudTags(name string, shared bool) map[string]string
}
case kops.CloudProviderScaleway:
for k, v := range b.Cluster.Spec.CloudLabels {
if k == scaleway.TagClusterName && shared == true {
if k == scaleway.TagClusterName && shared {
klog.V(4).Infof("Skipping %q tag for shared resource", scaleway.TagClusterName)
continue
}
Expand Down
2 changes: 1 addition & 1 deletion pkg/model/domodel/network.go
Original file line number Diff line number Diff line change
Expand Up @@ -39,7 +39,7 @@ func (b *NetworkModelBuilder) Build(c *fi.CloudupModelBuilderContext) error {
return nil
}

clusterName := strings.Replace(b.ClusterName(), ".", "-", -1)
clusterName := strings.ReplaceAll(b.ClusterName(), ".", "-")
vpcName := "vpc-" + clusterName

// Create a separate vpc for this cluster.
Expand Down
5 changes: 1 addition & 4 deletions pkg/model/gcemodel/autoscalinggroup.go
Original file line number Diff line number Diff line change
Expand Up @@ -283,10 +283,7 @@ func (b *AutoscalingGroupModelBuilder) splitToZones(ig *kops.InstanceGroup) (map
totalSize += targetSizes[i]
}
i := 0
for {
if totalSize >= minSize {
break
}
for totalSize < minSize {
targetSizes[i]++
totalSize++

Expand Down
Loading
Loading