style: clear unused code and style findings reported by staticcheck

Remove helpers and constants nothing references, escape format
characters in test literals, and take the simplifications staticcheck
suggests where they read the same. Error strings no longer start with a
capital: they keep their meaning, with the kind or component name moved
out of first position. Callers match errors by type, not text; the one
test that matches text, for Kafka, keeps the phrase it looks for.

Assisted-by: LLM
Signed-off-by: Aleksei Sviridkin <f@lex.la>
This commit is contained in:
Aleksei Sviridkin committed 2026-11-13 11:37:41 +03:00
1 parent 0f169540a1
commit 4c3a4b42cc
22 files changed
+43 -86

No files matched your search

+3 -3
View File
@@ -142,11 +142,11 @@ func TestOptionInjection(t *testing.T) {
// no bidi override reorders it and no zero-width character hides in it.
func TestDeferredBlockCleansFileNames(t *testing.T) {
l, _ := parseLine("release-1.6")
files := []string{"app/‮txt.exe", "app/zero​width.yaml"}
files := []string{"app/\u202etxt.exe", "app/zero\u200bwidth.yaml"}
conflict := pick{v: &verdict{o: &original{number: 5}}, files: files, failed: strings.Repeat("a", 40)}
waiting := pick{v: &verdict{o: &original{number: 6}}, files: files}
block := deferredBlock(l, []pick{conflict}, nil, []pick{waiting})
if strings.ContainsAny(block, "‮​") {
if strings.ContainsAny(block, "\u202e\u200b") {
t.Errorf("the block carries format characters: %q", block)
}
want := []string{"app/txt.exe", "app/zerowidth.yaml"}
@@ -154,7 +154,7 @@ func TestDeferredBlockCleansFileNames(t *testing.T) {
if err != nil || !slices.Equal(got[5].Files, want) || !slices.Equal(got[6].Files, want) {
t.Errorf("parseDeferred = %+v, %v; want both originals with %q", got, err, want)
}
if files[0] != "app/‮txt.exe" {
if files[0] != "app/\u202etxt.exe" {
t.Errorf("deferredBlock rewrote the pick's own file names: %q", files)
}
}
+2 -2
View File
@@ -41,12 +41,12 @@ func TestOntoContinues(t *testing.T) {
f.lines()
head := pushed(t, f)
f.pr(6, "fix(app): six", "", map[string]string{"app/six.txt": "6\n"})
code, stdout, stderr := f.exec(&fakeGH{}, "run", "--line", "release-1.1", "--onto", head, "--date", "2026-10-29")
code, _, stderr := f.exec(&fakeGH{}, "run", "--line", "release-1.1", "--onto", head, "--date", "2026-10-29")
if code != 2 || !strings.Contains(stderr, "not the head of backport-batch/release-1.1-20261029") {
t.Errorf("--onto with another date = %d (%s), want a refusal", code, stderr)
}
f.now = f.now.AddDate(0, 0, 3)
code, stdout, stderr = f.exec(&fakeGH{}, "run", "--line", "release-1.1", "--onto", head)
code, stdout, stderr := f.exec(&fakeGH{}, "run", "--line", "release-1.1", "--onto", head)
if code != 0 {
t.Fatalf("run --onto = %d\n%s", code, stderr)
}
+2 -2
View File
@@ -176,7 +176,7 @@ func TestPolicyPageMatchesCode(t *testing.T) {
t.Errorf("the page's block gives %d released lines, want 2 written out", pol.released)
}
rule2 := regexp.MustCompile("(?m)^2\\. Its title type is (.*)$").FindStringSubmatch(page)
rule2 := regexp.MustCompile(`(?m)^2\. Its title type is (.*)$`).FindStringSubmatch(page)
if rule2 == nil {
t.Fatal("the page has no rule 2")
}
@@ -187,7 +187,7 @@ func TestPolicyPageMatchesCode(t *testing.T) {
if !slices.Equal(types, takenTypes) {
t.Errorf("rule 2 on the page takes %v, the code %v", types, takenTypes)
}
never := regexp.MustCompile("(?m)^### What waits for the next minor\\n\\n(.*)$").FindStringSubmatch(page)
never := regexp.MustCompile(`(?m)^### What waits for the next minor\n\n(.*)$`).FindStringSubmatch(page)
if never == nil {
t.Fatal("the page has no list of what never goes into a patch release")
}
+1 -1
View File
@@ -390,7 +390,7 @@ func createPackageFromFile(ctx context.Context, k8sClient client.Client, filePat
}
}
return fmt.Errorf("Package %s not found in file", packageName)
return fmt.Errorf("no Package %s in file", packageName)
}
func installPackage(ctx context.Context, k8sClient client.Client, packageSourceName string) error {
+1 -1
View File
@@ -663,7 +663,7 @@ func validateGitRef(refMap map[string]string) error {
return fmt.Errorf("commit SHA should be at least 7 characters, got: %s", commit)
}
for _, c := range commit {
if !((c >= '0' && c <= '9') || (c >= 'a' && c <= 'f') || (c >= 'A' && c <= 'F')) {
if (c < '0' || c > '9') && (c < 'a' || c > 'f') && (c < 'A' || c > 'F') {
return fmt.Errorf("commit SHA should be a hexadecimal string, got: %s", commit)
}
}
@@ -631,7 +631,7 @@ func (r *BackupJobReconciler) createAltinityBackupArtifact(
// used name meets the earlier run's Backup here. Only one recording
// this run's archive was created by an earlier reconcile of this run.
if got := existing.Spec.DriverMetadata[altinityArchiveMetaKey]; got != archive {
return nil, fmt.Errorf("Backup %s/%s already exists and records archive %q, not %q that this run wrote",
return nil, fmt.Errorf("existing Backup %s/%s records archive %q, not %q that this run wrote",
backup.Namespace, backup.Name, got, archive)
}
return existing, nil
@@ -134,14 +134,14 @@ var etcdClusterGVR = schema.GroupVersionResource{
// the wrong CRD via the typed client.
func validateEtcdApplicationRef(ref corev1.TypedLocalObjectReference) error {
if ref.Kind != etcdAppKind {
return fmt.Errorf("Etcd strategy supports applicationRef.kind=%q, got %q", etcdAppKind, ref.Kind)
return fmt.Errorf("the Etcd strategy supports applicationRef.kind=%q, got %q", etcdAppKind, ref.Kind)
}
apiGroup := ""
if ref.APIGroup != nil {
apiGroup = *ref.APIGroup
}
if apiGroup != "" && apiGroup != etcdapp.GroupName {
return fmt.Errorf("Etcd strategy supports applicationRef.apiGroup=%q, got %q", etcdapp.GroupName, apiGroup)
return fmt.Errorf("the Etcd strategy supports applicationRef.apiGroup=%q, got %q", etcdapp.GroupName, apiGroup)
}
return nil
}
@@ -104,10 +104,10 @@ func kafkaClusterName(appName string) string {
// apps.cozystack.io/Kafka application.
func validateKafkaApplicationRef(ref corev1.TypedLocalObjectReference) error {
if ref.Kind != kafkaApplicationKind {
return fmt.Errorf("Kafka strategy only supports applicationRef.kind=%q, got %q", kafkaApplicationKind, ref.Kind)
return fmt.Errorf("the Kafka strategy only supports applicationRef.kind=%q, got %q", kafkaApplicationKind, ref.Kind)
}
if ref.APIGroup != nil && *ref.APIGroup != "" && *ref.APIGroup != backupsv1alpha1.DefaultApplicationAPIGroup {
return fmt.Errorf("Kafka strategy only supports applicationRef.apiGroup=%q, got %q", backupsv1alpha1.DefaultApplicationAPIGroup, *ref.APIGroup)
return fmt.Errorf("the Kafka strategy only supports applicationRef.apiGroup=%q, got %q", backupsv1alpha1.DefaultApplicationAPIGroup, *ref.APIGroup)
}
return nil
}
@@ -528,7 +528,7 @@ func (r *BackupJobReconciler) createKafkaBackupArtifact(
// RabbitMQ driver's guard).
if existing.Spec.ApplicationRef.Kind != backup.Spec.ApplicationRef.Kind ||
existing.Spec.ApplicationRef.Name != backup.Spec.ApplicationRef.Name {
return nil, fmt.Errorf("Backup %s/%s already exists for a different application (%s/%s, not %s/%s)",
return nil, fmt.Errorf("existing Backup %s/%s belongs to a different application (%s/%s, not %s/%s)",
backup.Namespace, backup.Name,
existing.Spec.ApplicationRef.Kind, existing.Spec.ApplicationRef.Name,
backup.Spec.ApplicationRef.Kind, backup.Spec.ApplicationRef.Name)
@@ -513,7 +513,7 @@ func (r *BackupJobReconciler) createRabbitmqBackupArtifact(
// this run's success while describing something else.
if existing.Spec.ApplicationRef.Kind != backup.Spec.ApplicationRef.Kind ||
existing.Spec.ApplicationRef.Name != backup.Spec.ApplicationRef.Name {
return nil, fmt.Errorf("Backup %s/%s already exists for a different application (%s/%s, not %s/%s)",
return nil, fmt.Errorf("existing Backup %s/%s belongs to a different application (%s/%s, not %s/%s)",
backup.Namespace, backup.Name,
existing.Spec.ApplicationRef.Kind, existing.Spec.ApplicationRef.Name,
backup.Spec.ApplicationRef.Kind, backup.Spec.ApplicationRef.Name)
@@ -219,7 +219,7 @@ func (r *KubeOVNPlunger) WriteClusterMetrics(db string, snaps []ovnstatus.Health
r.metrics.allAgree.WithLabelValues(db, cid).Set(b2f(ecv.AllAgree))
r.metrics.membersExpected.WithLabelValues(db, cid).Set(float64(expectedReplicas))
r.metrics.membersObserved.WithLabelValues(db, cid).Set(float64(ecv.MembersCount))
r.metrics.ipsExpected.WithLabelValues(db, cid).Set(float64(len(ecv.ConsensusResult.TruthView.Members))) // optional; or len(hints.ExpectedIPs)
r.metrics.ipsExpected.WithLabelValues(db, cid).Set(float64(len(ecv.TruthView.Members))) // optional; or len(hints.ExpectedIPs)
r.metrics.ipsObserved.WithLabelValues(db, cid).Set(float64(ecv.DistinctIPCount))
r.metrics.excessMembers.WithLabelValues(db, cid).Set(float64(ecv.ExpectedExcess))
r.metrics.missingMembers.WithLabelValues(db, cid).Set(float64(ecv.ExpectedShortfall))
@@ -3,7 +3,6 @@ package controller
import (
"context"
"strings"
"time"
corev1 "k8s.io/api/core/v1"
apierrors "k8s.io/apimachinery/pkg/api/errors"
@@ -15,10 +14,6 @@ import (
cozyv1alpha1 "github.com/cozystack/cozystack/api/v1alpha1"
)
const (
deletionRequeueDelay = 30 * time.Second
)
// WorkloadMonitorReconciler reconciles a WorkloadMonitor object
type WorkloadReconciler struct {
client.Client
+1 -1
View File
@@ -171,7 +171,7 @@ func extractNamespace(objects []*unstructured.Unstructured) (string, error) {
if obj.GetKind() == "Namespace" {
namespace := obj.GetName()
if namespace == "" {
return "", fmt.Errorf("Namespace object has no name")
return "", fmt.Errorf("the Namespace object has no name")
}
return namespace, nil
}
+1 -1
View File
@@ -176,7 +176,7 @@ func (h *LineageControllerWebhook) computeLabels(ctx context.Context, obj *unstr
return s
}
s = s[:63]
for b := s[62]; !((b >= 'a' && b <= 'z') || (b >= 'A' && b <= 'Z') || (b >= '0' && b <= '9')); s = s[:len(s)-1] {
for b := s[62]; (b < 'a' || b > 'z') && (b < 'A' || b > 'Z') && (b < '0' || b > '9'); s = s[:len(s)-1] {
b = s[len(s)-1]
}
return s
+2 -2
View File
@@ -146,7 +146,7 @@ func (c *inventoryClient) VMs(ctx context.Context, providerUID string) ([]invent
defer func() { _ = resp.Body.Close() }()
if resp.StatusCode != http.StatusOK {
return nil, fmt.Errorf("Forklift inventory returned %s listing VMs", resp.Status)
return nil, fmt.Errorf("listing VMs: the Forklift inventory returned %s", resp.Status)
}
var vms []inventoryVMRef
@@ -195,7 +195,7 @@ func (c *inventoryClient) VM(ctx context.Context, providerUID, vmID string) (*in
case http.StatusNotFound:
return nil, &notFoundError{vmID: vmID}
default:
return nil, fmt.Errorf("Forklift inventory returned %s for VM %q", resp.Status, vmID)
return nil, fmt.Errorf("VM %q: the Forklift inventory returned %s", vmID, resp.Status)
}
vm := &inventoryVM{}
@@ -790,15 +790,6 @@ func scanRecordingClient(scheme *runtime.Scheme, listed *[]string, writes *int,
}).Build()
}
func listedKind(listed []string, kind string) bool {
for _, l := range listed {
if strings.Contains(l, kind) {
return true
}
}
return false
}
// The comparison guarding that write has to be semantic rather than structural, or a
// LimitRange written in a different but equivalent notation would re-apply on every
// reconcile — invisible in a test that only looked at the resulting object, since every one
+2 -2
View File
@@ -118,11 +118,11 @@ func (c *Collector) collect(ctx context.Context) {
// Write application count metrics
for kind, count := range appKindCounts {
metrics.WriteString(fmt.Sprintf(
fmt.Fprintf(&metrics,
"cozy_application_count{kind=\"%s\"} %d\n",
kind,
count,
))
)
}
// Send metrics only if there's something to send
+11 -11
View File
@@ -133,11 +133,11 @@ func (c *OperatorCollector) collect(ctx context.Context) {
var metrics strings.Builder
// Add cluster info metric
metrics.WriteString(fmt.Sprintf(
fmt.Fprintf(&metrics,
"cozy_cluster_info{cozystack_version=\"%s\",kubernetes_version=\"%s\"} 1\n",
version.Version,
k8sVersion.GitVersion,
))
)
// Collect node metrics grouped by OS and kernel
nodeOSCount := make(map[string]map[string]int) // os -> kernel -> count
@@ -153,12 +153,12 @@ func (c *OperatorCollector) collect(ctx context.Context) {
for osKey, kernels := range nodeOSCount {
for kernel, count := range kernels {
metrics.WriteString(fmt.Sprintf(
fmt.Fprintf(&metrics,
"cozy_nodes_count{os=\"%s\",kernel=\"%s\"} %d\n",
osKey,
kernel,
count,
))
)
}
}
@@ -174,11 +174,11 @@ func (c *OperatorCollector) collect(ctx context.Context) {
}
for resourceName, total := range capacityTotals {
metrics.WriteString(fmt.Sprintf(
fmt.Fprintf(&metrics,
"cozy_cluster_capacity{resource=\"%s\"} %d\n",
resourceName,
total,
))
)
}
// Collect LoadBalancer services metrics
@@ -192,7 +192,7 @@ func (c *OperatorCollector) collect(ctx context.Context) {
lbCount++
}
}
metrics.WriteString(fmt.Sprintf("cozy_loadbalancers_count %d\n", lbCount))
fmt.Fprintf(&metrics, "cozy_loadbalancers_count %d\n", lbCount)
}
// Collect PV metrics grouped by driver and size
@@ -224,12 +224,12 @@ func (c *OperatorCollector) collect(ctx context.Context) {
for size, drivers := range pvMetrics {
for driver, count := range drivers {
metrics.WriteString(fmt.Sprintf(
fmt.Fprintf(&metrics,
"cozy_pvs_count{driver=\"%s\",size=\"%s\"} %d\n",
driver,
size,
count,
))
)
}
}
}
@@ -244,11 +244,11 @@ func (c *OperatorCollector) collect(ctx context.Context) {
if variant == "" {
variant = "default"
}
metrics.WriteString(fmt.Sprintf(
fmt.Fprintf(&metrics,
"cozy_package_info{name=\"%s\",variant=\"%s\"} 1\n",
pkg.Name,
variant,
))
)
}
}
+3 -3
View File
@@ -78,7 +78,7 @@ func init() {
// Register HelmRelease types.
if err := helmv2.AddToScheme(mgrScheme); err != nil {
panic(fmt.Errorf("Failed to add HelmRelease types to scheme: %w", err))
panic(fmt.Errorf("failed to add HelmRelease types to scheme: %w", err))
}
// Register the in-tree CiliumNetworkPolicy mirror backing SecurityGroup.
@@ -87,10 +87,10 @@ func init() {
}
if err := corev1.AddToScheme(mgrScheme); err != nil {
panic(fmt.Errorf("Failed to add core types to scheme: %w", err))
panic(fmt.Errorf("failed to add core types to scheme: %w", err))
}
if err := rbacv1.AddToScheme(mgrScheme); err != nil {
panic(fmt.Errorf("Failed to add RBAC types to scheme: %w", err))
panic(fmt.Errorf("failed to add RBAC types to scheme: %w", err))
}
// Register Cozystack types for WorkloadMonitor queries.
+2 -2
View File
@@ -319,7 +319,7 @@ func BuildPostProcessV3(kindSchemas map[string]string) func(*spec3.OpenAPI) (*sp
base, ok1 := doc.Components.Schemas[baseRef]
list, ok2 := doc.Components.Schemas[baseListRef]
stat, ok3 := doc.Components.Schemas[baseStatusRef]
if !(ok1 && ok2 && ok3) {
if !ok1 || !ok2 || !ok3 {
return doc, nil // not the apps GV — nothing to patch
}
@@ -463,7 +463,7 @@ func BuildPostProcessV2(kindSchemas map[string]string) func(*spec.Swagger) (*spe
base, ok1 := defs[baseRef]
list, ok2 := defs[baseListRef]
stat, ok3 := defs[baseStatusRef]
if !(ok1 && ok2 && ok3) {
if !ok1 || !ok2 || !ok3 {
return sw, nil // not the apps GV — nothing to patch
}
-27
View File
@@ -277,33 +277,6 @@ func defaultRunner(ctx context.Context, bin string, args ...string) (string, err
return out, nil
}
/************** Helpers **************/
func parseClusterStatusJSON(out string) (ClusterStatus, bool) {
var cs ClusterStatus
if json.Unmarshal([]byte(out), &cs) == nil && len(cs.Servers) > 0 {
return cs, true
}
var wrap struct {
Data ClusterStatus `json:"data"`
}
if json.Unmarshal([]byte(out), &wrap) == nil && len(wrap.Data.Servers) > 0 {
return wrap.Data, true
}
return ClusterStatus{}, false
}
func portOf(db DB) string {
switch db {
case DBNorthbound:
return "6641"
case DBSouthbound:
return "6642"
default:
return "0"
}
}
/************** Minimal text fallback for "Servers" **************/
// Accepts variants like:
+1 -3
View File
@@ -28,9 +28,7 @@ var expectedServersBlock = `` +
func TestExtractServersBlock(t *testing.T) {
if actual := extractServersBlock(testStdout); actual != expectedServersBlock {
fmt.Println([]byte(actual))
fmt.Println([]byte(expectedServersBlock))
t.Errorf("error extracting servers block from following string:\n%s\nexpected:\n%s\ngot:\n%s\n", testStdout, expectedServersBlock, actual)
t.Errorf("error extracting servers block from following string:\n%s\nexpected:\n%q\ngot:\n%q\n", testStdout, expectedServersBlock, actual)
}
}
+3 -3
View File
@@ -284,9 +284,9 @@ func mulQuantity(q, n ref.Val) ref.Val {
if !ok {
return types.MaybeNoSuchOverloadErr(n)
}
out := qq.Quantity.DeepCopy()
out := qq.DeepCopy()
if !out.Mul(int64(nn)) {
return types.NewErr("quantity %s * %d overflows", qq.Quantity.String(), int64(nn))
return types.NewErr("quantity %s * %d overflows", qq.String(), int64(nn))
}
return apiservercel.Quantity{Quantity: &out}
}
@@ -294,7 +294,7 @@ func mulQuantity(q, n ref.Val) ref.Val {
func toQuantity(v ref.Val) (resource.Quantity, error) {
switch t := v.(type) {
case apiservercel.Quantity:
return t.Quantity.DeepCopy(), nil
return t.DeepCopy(), nil
case types.Int:
return *resource.NewQuantity(int64(t), resource.DecimalSI), nil
case types.Uint: