Skip to content

Commit 1946356

Browse files
committed
refactor: apply the Go 1.27 modernizers
go fix brings the code written since the modernizers last ran onto the same idioms: any, range over int, maps.Copy, slices.Backward and slices.ContainsFunc, strings.SplitSeq, and new(value) in place of ptr.To. embedlit stays off because its syntax needs Go 1.27 and would break backports to release branches on Go 1.26; omitzero stays off because it would make metadata, spec and status required in the published OpenAPI schemas. Assisted-by: LLM Signed-off-by: Aleksei Sviridkin <[email protected]>
1 parent eb7b275 commit 1946356

12 files changed

Lines changed: 40 additions & 45 deletions

File tree

‎cmd/backport-audit/main.go‎

Lines changed: 5 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -23,6 +23,7 @@ import (
2323
"encoding/json"
2424
"errors"
2525
"fmt"
26+
"maps"
2627
"os"
2728
"os/exec"
2829
"regexp"
@@ -637,9 +638,7 @@ func lineOpenDates() ([]lineOpen, error) {
637638
if err != nil {
638639
return nil, err
639640
}
640-
for l, when := range frozen {
641-
earliest[l] = when
642-
}
641+
maps.Copy(earliest, frozen)
643642

644643
opened := make([]lineOpen, 0, len(earliest))
645644
for l, when := range earliest {
@@ -974,12 +973,12 @@ func botAuthor(login string) bool {
974973

975974
// lastHumanComment is the last comment on a PR not written by the backport bot.
976975
func lastHumanComment(pr backportPR) string {
977-
for i := len(pr.Comments) - 1; i >= 0; i-- {
978-
login := pr.Comments[i].Author.Login
976+
for _, v := range slices.Backward(pr.Comments) {
977+
login := v.Author.Login
979978
if botAuthor(login) {
980979
continue
981980
}
982-
text := strings.Join(strings.Fields(pr.Comments[i].Body), " ")
981+
text := strings.Join(strings.Fields(v.Body), " ")
983982
if text == "" {
984983
continue
985984
}

‎internal/backupcontroller/cnpgstrategy_controller_test.go‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -3748,7 +3748,7 @@ func newCNPGStrategyTestClient(t *testing.T, objs ...client.Object) client.Clien
37483748
func reconcileCNPGRestoreToTerminal(t *testing.T, ctx context.Context, r *RestoreJobReconciler, c client.Client, backup *backupsv1alpha1.Backup, ns, name string) *backupsv1alpha1.RestoreJob {
37493749
t.Helper()
37503750
got := &backupsv1alpha1.RestoreJob{}
3751-
for i := 0; i < 8; i++ {
3751+
for range 8 {
37523752
rj := &backupsv1alpha1.RestoreJob{}
37533753
if err := c.Get(ctx, client.ObjectKey{Namespace: ns, Name: name}, rj); err != nil {
37543754
t.Fatalf("get RestoreJob: %v", err)

‎internal/backupcontroller/mariadbstrategy_controller.go‎

Lines changed: 1 addition & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -13,7 +13,6 @@ import (
1313
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
1414
"k8s.io/apimachinery/pkg/runtime"
1515
"k8s.io/apimachinery/pkg/types"
16-
"k8s.io/utils/ptr"
1716
ctrl "sigs.k8s.io/controller-runtime"
1817
"sigs.k8s.io/controller-runtime/pkg/client"
1918

@@ -306,7 +305,7 @@ func (r *BackupJobReconciler) ensureMariaDBBackup(ctx context.Context, j *backup
306305
// Keep the source's grant table out of the dump so a restore into a
307306
// copy leaves the target's chart-managed users and root intact (see
308307
// BackupSpec.IgnoreGlobalPriv).
309-
IgnoreGlobalPriv: ptr.To(true),
308+
IgnoreGlobalPriv: new(true),
310309
},
311310
}
312311

‎internal/backupcontroller/psmdbstrategy_controller.go‎

Lines changed: 6 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -903,9 +903,9 @@ func shouldInjectMongoDBSystemStorage(useSystemBucket bool, rendered *strategyv1
903903
// the forcePathStyle omit-when-nil (a nil pointer must not surface as a
904904
// forcePathStyle:false the app never chose), and the {"type":"s3","s3":{…}}
905905
// shape are exercised without a live apiserver.
906-
func buildMongoDBSystemStorageEntry(s3 *strategyv1alpha1.MongoDBStorageS3) map[string]interface{} {
906+
func buildMongoDBSystemStorageEntry(s3 *strategyv1alpha1.MongoDBStorageS3) map[string]any {
907907
cred := psmdbInjectedCredentialsSecret(s3)
908-
s3Cfg := map[string]interface{}{
908+
s3Cfg := map[string]any{
909909
"bucket": s3.Bucket,
910910
"endpointUrl": s3.EndpointURL,
911911
"region": s3.Region,
@@ -916,7 +916,7 @@ func buildMongoDBSystemStorageEntry(s3 *strategyv1alpha1.MongoDBStorageS3) map[s
916916
if s3.ForcePathStyle != nil {
917917
s3Cfg["forcePathStyle"] = *s3.ForcePathStyle
918918
}
919-
return map[string]interface{}{"type": "s3", "s3": s3Cfg}
919+
return map[string]any{"type": "s3", "s3": s3Cfg}
920920
}
921921

922922
// applyMongoDBSystemStorage SSA-injects the system-bucket S3 storage onto the
@@ -1014,8 +1014,8 @@ func psmdbStorageEntrySettled(raw runtime.RawExtension, s3 *strategyv1alpha1.Mon
10141014
return false
10151015
}
10161016
var live struct {
1017-
Type string `json:"type"`
1018-
S3 map[string]interface{} `json:"s3"`
1017+
Type string `json:"type"`
1018+
S3 map[string]any `json:"s3"`
10191019
}
10201020
if err := json.Unmarshal(raw.Raw, &live); err != nil {
10211021
return false
@@ -1024,7 +1024,7 @@ func psmdbStorageEntrySettled(raw runtime.RawExtension, s3 *strategyv1alpha1.Mon
10241024
if want, _ := desired["type"].(string); live.Type != want {
10251025
return false
10261026
}
1027-
want := desired["s3"].(map[string]interface{})
1027+
want := desired["s3"].(map[string]any)
10281028
for k, v := range want {
10291029
got, ok := live.S3[k]
10301030
if !ok {

‎internal/backupcontroller/psmdbstrategy_controller_test.go‎

Lines changed: 3 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -994,7 +994,7 @@ func TestBuildMongoDBSystemStorageEntry(t *testing.T) {
994994
if entry["type"] != "s3" {
995995
t.Fatalf("type = %v, want s3", entry["type"])
996996
}
997-
s3, ok := entry["s3"].(map[string]interface{})
997+
s3, ok := entry["s3"].(map[string]any)
998998
if !ok {
999999
t.Fatalf("s3 block is not a map: %#v", entry["s3"])
10001000
}
@@ -1004,7 +1004,7 @@ func TestBuildMongoDBSystemStorageEntry(t *testing.T) {
10041004
if _, present := s3["forcePathStyle"]; present {
10051005
t.Errorf("forcePathStyle must be omitted when the pointer is nil; got %v", s3["forcePathStyle"])
10061006
}
1007-
for k, want := range map[string]interface{}{
1007+
for k, want := range map[string]any{
10081008
"bucket": "sys-bucket",
10091009
"endpointUrl": "https://s3.example",
10101010
"region": "us-east-1",
@@ -1025,7 +1025,7 @@ func TestBuildMongoDBSystemStorageEntry(t *testing.T) {
10251025
ForcePathStyle: &fps,
10261026
InsecureSkipTLSVerify: true,
10271027
})
1028-
s3 := entry["s3"].(map[string]interface{})
1028+
s3 := entry["s3"].(map[string]any)
10291029
if s3["credentialsSecret"] != "custom-creds" {
10301030
t.Errorf("credentialsSecret = %v, want custom-creds", s3["credentialsSecret"])
10311031
}
@@ -3471,7 +3471,6 @@ func TestReconcileMongoDB_StorageRaceRetryBudgetExhausted(t *testing.T) {
34713471
// away, and the fresh CR resolves the storage from a stale cache and errors.
34723472
operator := func(t *testing.T) {
34733473
for _, cr := range listCRs(t) {
3474-
cr := cr
34753474
if !cr.DeletionTimestamp.IsZero() {
34763475
base := cr.DeepCopy()
34773476
cr.Finalizers = nil

‎internal/controller/workloadmonitor_controller_test.go‎

Lines changed: 12 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -1464,8 +1464,8 @@ func TestReconcile_PVCStorageClassResourceKey(t *testing.T) {
14641464
wantKey string
14651465
}{
14661466
{"unset falls back to default", nil, "default.storageclass.storage.k8s.io/requests.storage"},
1467-
{"empty falls back to default", ptr.To(""), "default.storageclass.storage.k8s.io/requests.storage"},
1468-
{"explicit class is kept", ptr.To("replicated"), "replicated.storageclass.storage.k8s.io/requests.storage"},
1467+
{"empty falls back to default", new(""), "default.storageclass.storage.k8s.io/requests.storage"},
1468+
{"explicit class is kept", new("replicated"), "replicated.storageclass.storage.k8s.io/requests.storage"},
14691469
}
14701470
for _, tc := range cases {
14711471
t.Run(tc.name, func(t *testing.T) {
@@ -1655,7 +1655,7 @@ func TestReconcile_PopulatedDataVolumeClearsTheLastVerdict(t *testing.T) {
16551655
ObjectMeta: metav1.ObjectMeta{Name: "vm-disk-test", Namespace: "default"},
16561656
Spec: cozyv1alpha1.WorkloadMonitorSpec{Selector: selector, MinReplicas: ptr.To[int32](0)},
16571657
Status: cozyv1alpha1.WorkloadMonitorStatus{
1658-
Operational: ptr.To(false),
1658+
Operational: new(false),
16591659
Message: "DataVolume vm-disk-test is ImportInProgress",
16601660
Reason: cozyv1alpha1.WorkloadMonitorReasonDataVolumeNotReady,
16611661
},
@@ -1830,7 +1830,7 @@ func TestReconcile_UnreadDataVolumesKeepTheLastVerdict(t *testing.T) {
18301830
for _, withReader := range []bool{true, false} {
18311831
t.Run(fmt.Sprintf("reader=%v", withReader), func(t *testing.T) {
18321832
got, _, _ := reconcileWithUnreadableDataVolumes(t, withReader, false, cozyv1alpha1.WorkloadMonitorStatus{
1833-
Operational: ptr.To(false),
1833+
Operational: new(false),
18341834
Message: stuck,
18351835
Reason: cozyv1alpha1.WorkloadMonitorReasonDataVolumeNotReady,
18361836
})
@@ -1847,7 +1847,7 @@ func TestReconcile_UnreadDataVolumesKeepTheLastVerdict(t *testing.T) {
18471847
func TestReconcile_SyncingDataVolumeWatchPublishesAndRequeues(t *testing.T) {
18481848
const stuck = "DataVolume m is Failed"
18491849
got, result, events, err := reconcileWithUnreadableDataVolumesEvents(t, false, true, cozyv1alpha1.WorkloadMonitorStatus{
1850-
Operational: ptr.To(false),
1850+
Operational: new(false),
18511851
Message: stuck,
18521852
Reason: cozyv1alpha1.WorkloadMonitorReasonDataVolumeNotReady,
18531853
})
@@ -2040,7 +2040,7 @@ func TestTryStartDataVolumeWatch_UnsyncedSourceLeavesNoReaderAndRetries(t *testi
20402040
w := &startingWatcher{}
20412041
informers, fi := dataVolumeInformers(false)
20422042

2043-
for attempt := 0; attempt < 3; attempt++ {
2043+
for range 3 {
20442044
done, err := r.tryStartDataVolumeWatch(context.Background(), servedMapper(), w, informers, 50*time.Millisecond)
20452045
if err == nil || done || readerOf(r) != nil {
20462046
t.Fatalf("informer never synced: done=%v err=%v reader=%v, want an error, not done, no reader", done, err, readerOf(r))
@@ -2117,15 +2117,15 @@ func TestTryStartDataVolumeWatch_StoredVerdictIsRecomputedOnceTheReaderIsInstall
21172117
MinReplicas: ptr.To[int32](0),
21182118
},
21192119
Status: cozyv1alpha1.WorkloadMonitorStatus{
2120-
Operational: ptr.To(false),
2120+
Operational: new(false),
21212121
Message: "DataVolume stuck is ImportInProgress",
21222122
Reason: cozyv1alpha1.WorkloadMonitorReasonDataVolumeNotReady,
21232123
},
21242124
}
21252125
noVerdict := &cozyv1alpha1.WorkloadMonitor{
21262126
ObjectMeta: metav1.ObjectMeta{Name: "no-verdict", Namespace: "default"},
21272127
Spec: cozyv1alpha1.WorkloadMonitorSpec{MinReplicas: ptr.To[int32](0)},
2128-
Status: cozyv1alpha1.WorkloadMonitorStatus{Operational: ptr.To(true)},
2128+
Status: cozyv1alpha1.WorkloadMonitorStatus{Operational: new(true)},
21292129
}
21302130
fakeClient := fake.NewClientBuilder().WithScheme(s).
21312131
WithObjects(stuck, noVerdict).WithStatusSubresource(stuck, noVerdict).Build()
@@ -2220,14 +2220,14 @@ func TestTryStartDataVolumeWatch_FailedWatchLeavesNoReader(t *testing.T) {
22202220
// While the DataVolume watch syncs, every monitor is requeued every few
22212221
// seconds, so a pass that changes nothing must not write status.
22222222
func TestReconcile_UnchangedStatusIsNotWritten(t *testing.T) {
2223-
settled := cozyv1alpha1.WorkloadMonitorStatus{Operational: ptr.To(true), AvailableReplicas: 1, ObservedReplicas: 1}
2223+
settled := cozyv1alpha1.WorkloadMonitorStatus{Operational: new(true), AvailableReplicas: 1, ObservedReplicas: 1}
22242224
for _, tc := range []struct {
22252225
name string
22262226
status cozyv1alpha1.WorkloadMonitorStatus
22272227
writes int
22282228
}{
22292229
{"unchanged", settled, 0},
2230-
{"changed", cozyv1alpha1.WorkloadMonitorStatus{Operational: ptr.To(true)}, 1},
2230+
{"changed", cozyv1alpha1.WorkloadMonitorStatus{Operational: new(true)}, 1},
22312231
} {
22322232
t.Run(tc.name, func(t *testing.T) {
22332233
s := newTestScheme()
@@ -2289,7 +2289,7 @@ func TestReconcile_PVCOfANotReadyDataVolumeIsNotOperational(t *testing.T) {
22892289
{name: "not owned by the DataVolume", phase: "ImportInProgress", reader: true, want: true},
22902290
{name: "controller of another kind", phase: "ImportInProgress", reader: true, controlled: true, ownerGVK: &schema.GroupVersionKind{Group: dataVolumeGVK.Group, Version: dataVolumeGVK.Version, Kind: "DataSource"}, want: true},
22912291
{name: "DataVolume kind of another group", phase: "ImportInProgress", reader: true, controlled: true, ownerGVK: &schema.GroupVersionKind{Group: "example.com", Version: "v1", Kind: dataVolumeGVK.Kind}, want: true},
2292-
{name: "unread keeps the stored verdict", phase: "Succeeded", stored: ptr.To(false), controlled: true, want: false},
2292+
{name: "unread keeps the stored verdict", phase: "Succeeded", stored: new(false), controlled: true, want: false},
22932293
{name: "unread and new reads bind state", phase: "ImportInProgress", controlled: true, want: true},
22942294
} {
22952295
t.Run(tc.name, func(t *testing.T) {
@@ -2302,7 +2302,7 @@ func TestReconcile_PVCOfANotReadyDataVolumeIsNotOperational(t *testing.T) {
23022302
dv.SetUID("dv-uid")
23032303
pvc := &corev1.PersistentVolumeClaim{
23042304
ObjectMeta: metav1.ObjectMeta{Name: "vm-disk-test", Namespace: "default", Labels: selector},
2305-
Spec: corev1.PersistentVolumeClaimSpec{StorageClassName: ptr.To("replicated")},
2305+
Spec: corev1.PersistentVolumeClaimSpec{StorageClassName: new("replicated")},
23062306
Status: corev1.PersistentVolumeClaimStatus{Phase: corev1.ClaimBound},
23072307
}
23082308
if tc.controlled {

‎internal/migrationcontroller/settle_reclaim_policy_test.go‎

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -344,8 +344,8 @@ func TestFulfillRestoresTheReclaimPolicyBeforeFinishing(t *testing.T) {
344344
vm.SetName("test-vm")
345345
vm.SetNamespace(settleNS)
346346
vm.SetLabels(map[string]string{"plan": "plan-uid"})
347-
if err := unstructured.SetNestedSlice(vm.Object, []interface{}{
348-
map[string]interface{}{"name": "disk0", "dataVolume": map[string]interface{}{"name": "forklift-claim"}},
347+
if err := unstructured.SetNestedSlice(vm.Object, []any{
348+
map[string]any{"name": "disk0", "dataVolume": map[string]any{"name": "forklift-claim"}},
349349
}, "spec", "template", "spec", "volumes"); err != nil {
350350
t.Fatalf("build vm: %v", err)
351351
}

‎internal/operator/package_reconciler.go‎

Lines changed: 2 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -1123,10 +1123,8 @@ func (r *PackageReconciler) foreignContainerMemoryPolicy(ctx context.Context, ns
11231123
if lr.Name == SystemDefaultsLimitRangeName && lr.Labels[managedByLabel] == packageControllerFieldOwner {
11241124
continue
11251125
}
1126-
for _, item := range lr.Spec.Limits {
1127-
if constrainsMemory(item) {
1128-
return lr.Name, nil
1129-
}
1126+
if slices.ContainsFunc(lr.Spec.Limits, constrainsMemory) {
1127+
return lr.Name, nil
11301128
}
11311129
}
11321130
return "", nil

‎pkg/lineage/cache_test.go‎

Lines changed: 5 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -95,7 +95,7 @@ func TestParseWalkMemory(t *testing.T) {
9595
}
9696

9797
legacy := map[ObjectID]bool{{Name: "x"}: true}
98-
st, err = parseWalkMemory([]interface{}{legacy})
98+
st, err = parseWalkMemory([]any{legacy})
9999
if err != nil {
100100
t.Fatalf("legacy form should accept map[ObjectID]bool, got err=%v", err)
101101
}
@@ -104,7 +104,7 @@ func TestParseWalkMemory(t *testing.T) {
104104
}
105105

106106
var nilLegacy map[ObjectID]bool
107-
st, err = parseWalkMemory([]interface{}{nilLegacy})
107+
st, err = parseWalkMemory([]any{nilLegacy})
108108
if err != nil {
109109
t.Fatalf("nil legacy map should be tolerated, got err=%v", err)
110110
}
@@ -115,15 +115,15 @@ func TestParseWalkMemory(t *testing.T) {
115115

116116
cache := NewObjectCache(time.Minute)
117117
original := &walkState{visited: map[ObjectID]bool{{Name: "y"}: true}, cache: cache}
118-
st, err = parseWalkMemory([]interface{}{original})
118+
st, err = parseWalkMemory([]any{original})
119119
if err != nil {
120120
t.Fatalf("walkState form should be accepted, got err=%v", err)
121121
}
122122
if st != original {
123123
t.Fatal("walkState should be reused by reference so recursion shares cache")
124124
}
125125

126-
st, err = parseWalkMemory([]interface{}{"oops"})
126+
st, err = parseWalkMemory([]any{"oops"})
127127
if err == nil {
128128
t.Fatal("expected error for unsupported memory type")
129129
}
@@ -135,7 +135,7 @@ func TestParseWalkMemory(t *testing.T) {
135135
func TestObjectCache_EvictionSampleIsBounded(t *testing.T) {
136136
c := NewObjectCache(time.Hour)
137137

138-
for i := 0; i < evictionThreshold+1000; i++ {
138+
for i := range evictionThreshold + 1000 {
139139
key := cacheKey{apiVersion: "v1", kind: "Pod", namespace: "ns", name: strconv.Itoa(i)}
140140
c.items[key] = cacheEntry{
141141
obj: nil,

‎pkg/lineage/getobject_test.go‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -64,7 +64,7 @@ func TestGetUnstructuredObject_CachesSuccess(t *testing.T) {
6464
dyn, mapper, gets := newGetFixture(t, nil)
6565
cache := NewObjectCache(time.Minute)
6666

67-
for i := 0; i < 2; i++ {
67+
for i := range 2 {
6868
if _, err := getTestHR(dyn, mapper, cache, "harbor-demo"); err != nil {
6969
t.Fatalf("call %d: %v", i, err)
7070
}

0 commit comments

Comments
 (0)