Skip to content

Commit 32b0b88

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 c59e254 commit 32b0b88

14 files changed

Lines changed: 43 additions & 48 deletions

‎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
@@ -3900,7 +3900,7 @@ func newCNPGStrategyTestClient(t *testing.T, objs ...client.Object) client.Clien
39003900
func reconcileCNPGRestoreToTerminal(t *testing.T, ctx context.Context, r *RestoreJobReconciler, c client.Client, backup *backupsv1alpha1.Backup, ns, name string) *backupsv1alpha1.RestoreJob {
39013901
t.Helper()
39023902
got := &backupsv1alpha1.RestoreJob{}
3903-
for i := 0; i < 8; i++ {
3903+
for range 8 {
39043904
rj := &backupsv1alpha1.RestoreJob{}
39053905
if err := c.Get(ctx, client.ObjectKey{Namespace: ns, Name: name}, rj); err != nil {
39063906
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/fluxplunger/drain.go‎

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -193,11 +193,11 @@ func (r apiEventRecorder) Event(obj runtime.Object, eventtype, reason, message s
193193
r.write(obj, eventtype, reason, message)
194194
}
195195

196-
func (r apiEventRecorder) Eventf(obj runtime.Object, eventtype, reason, messageFmt string, args ...interface{}) {
196+
func (r apiEventRecorder) Eventf(obj runtime.Object, eventtype, reason, messageFmt string, args ...any) {
197197
r.write(obj, eventtype, reason, fmt.Sprintf(messageFmt, args...))
198198
}
199199

200-
func (r apiEventRecorder) AnnotatedEventf(obj runtime.Object, _ map[string]string, eventtype, reason, messageFmt string, args ...interface{}) {
200+
func (r apiEventRecorder) AnnotatedEventf(obj runtime.Object, _ map[string]string, eventtype, reason, messageFmt string, args ...any) {
201201
r.write(obj, eventtype, reason, fmt.Sprintf(messageFmt, args...))
202202
}
203203

‎internal/controller/workloadmonitor_controller.go‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -205,7 +205,7 @@ func dataVolumeFailureMessage(dv *unstructured.Unstructured) string {
205205
}
206206
message, _ := cond["message"].(string)
207207
var parts []string
208-
for _, part := range strings.Split(message, " and ") {
208+
for part := range strings.SplitSeq(message, " and ") {
209209
if part != "" {
210210
parts = append(parts, part)
211211
}

‎internal/controller/workloadmonitor_controller_test.go‎

Lines changed: 12 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -1465,8 +1465,8 @@ func TestReconcile_PVCStorageClassResourceKey(t *testing.T) {
14651465
wantKey string
14661466
}{
14671467
{"unset falls back to default", nil, "default.storageclass.storage.k8s.io/requests.storage"},
1468-
{"empty falls back to default", ptr.To(""), "default.storageclass.storage.k8s.io/requests.storage"},
1469-
{"explicit class is kept", ptr.To("replicated"), "replicated.storageclass.storage.k8s.io/requests.storage"},
1468+
{"empty falls back to default", new(""), "default.storageclass.storage.k8s.io/requests.storage"},
1469+
{"explicit class is kept", new("replicated"), "replicated.storageclass.storage.k8s.io/requests.storage"},
14701470
}
14711471
for _, tc := range cases {
14721472
t.Run(tc.name, func(t *testing.T) {
@@ -1751,7 +1751,7 @@ func TestReconcile_PopulatedDataVolumeClearsTheLastVerdict(t *testing.T) {
17511751
ObjectMeta: metav1.ObjectMeta{Name: "vm-disk-test", Namespace: "default"},
17521752
Spec: cozyv1alpha1.WorkloadMonitorSpec{Selector: selector, MinReplicas: ptr.To[int32](0)},
17531753
Status: cozyv1alpha1.WorkloadMonitorStatus{
1754-
Operational: ptr.To(false),
1754+
Operational: new(false),
17551755
Message: "DataVolume vm-disk-test is ImportInProgress",
17561756
Reason: cozyv1alpha1.WorkloadMonitorReasonDataVolumeNotReady,
17571757
},
@@ -1926,7 +1926,7 @@ func TestReconcile_UnreadDataVolumesKeepTheLastVerdict(t *testing.T) {
19261926
for _, withReader := range []bool{true, false} {
19271927
t.Run(fmt.Sprintf("reader=%v", withReader), func(t *testing.T) {
19281928
got, _, _ := reconcileWithUnreadableDataVolumes(t, withReader, false, cozyv1alpha1.WorkloadMonitorStatus{
1929-
Operational: ptr.To(false),
1929+
Operational: new(false),
19301930
Message: stuck,
19311931
Reason: cozyv1alpha1.WorkloadMonitorReasonDataVolumeNotReady,
19321932
})
@@ -1943,7 +1943,7 @@ func TestReconcile_UnreadDataVolumesKeepTheLastVerdict(t *testing.T) {
19431943
func TestReconcile_SyncingDataVolumeWatchPublishesAndRequeues(t *testing.T) {
19441944
const stuck = "DataVolume m is Failed"
19451945
got, result, events, err := reconcileWithUnreadableDataVolumesEvents(t, false, true, cozyv1alpha1.WorkloadMonitorStatus{
1946-
Operational: ptr.To(false),
1946+
Operational: new(false),
19471947
Message: stuck,
19481948
Reason: cozyv1alpha1.WorkloadMonitorReasonDataVolumeNotReady,
19491949
})
@@ -2136,7 +2136,7 @@ func TestTryStartDataVolumeWatch_UnsyncedSourceLeavesNoReaderAndRetries(t *testi
21362136
w := &startingWatcher{}
21372137
informers, fi := dataVolumeInformers(false)
21382138

2139-
for attempt := 0; attempt < 3; attempt++ {
2139+
for range 3 {
21402140
done, err := r.tryStartDataVolumeWatch(context.Background(), servedMapper(), w, informers, 50*time.Millisecond)
21412141
if err == nil || done || readerOf(r) != nil {
21422142
t.Fatalf("informer never synced: done=%v err=%v reader=%v, want an error, not done, no reader", done, err, readerOf(r))
@@ -2213,15 +2213,15 @@ func TestTryStartDataVolumeWatch_StoredVerdictIsRecomputedOnceTheReaderIsInstall
22132213
MinReplicas: ptr.To[int32](0),
22142214
},
22152215
Status: cozyv1alpha1.WorkloadMonitorStatus{
2216-
Operational: ptr.To(false),
2216+
Operational: new(false),
22172217
Message: "DataVolume stuck is ImportInProgress",
22182218
Reason: cozyv1alpha1.WorkloadMonitorReasonDataVolumeNotReady,
22192219
},
22202220
}
22212221
noVerdict := &cozyv1alpha1.WorkloadMonitor{
22222222
ObjectMeta: metav1.ObjectMeta{Name: "no-verdict", Namespace: "default"},
22232223
Spec: cozyv1alpha1.WorkloadMonitorSpec{MinReplicas: ptr.To[int32](0)},
2224-
Status: cozyv1alpha1.WorkloadMonitorStatus{Operational: ptr.To(true)},
2224+
Status: cozyv1alpha1.WorkloadMonitorStatus{Operational: new(true)},
22252225
}
22262226
fakeClient := fake.NewClientBuilder().WithScheme(s).
22272227
WithObjects(stuck, noVerdict).WithStatusSubresource(stuck, noVerdict).Build()
@@ -2316,14 +2316,14 @@ func TestTryStartDataVolumeWatch_FailedWatchLeavesNoReader(t *testing.T) {
23162316
// While the DataVolume watch syncs, every monitor is requeued every few
23172317
// seconds, so a pass that changes nothing must not write status.
23182318
func TestReconcile_UnchangedStatusIsNotWritten(t *testing.T) {
2319-
settled := cozyv1alpha1.WorkloadMonitorStatus{Operational: ptr.To(true), AvailableReplicas: 1, ObservedReplicas: 1}
2319+
settled := cozyv1alpha1.WorkloadMonitorStatus{Operational: new(true), AvailableReplicas: 1, ObservedReplicas: 1}
23202320
for _, tc := range []struct {
23212321
name string
23222322
status cozyv1alpha1.WorkloadMonitorStatus
23232323
writes int
23242324
}{
23252325
{"unchanged", settled, 0},
2326-
{"changed", cozyv1alpha1.WorkloadMonitorStatus{Operational: ptr.To(true)}, 1},
2326+
{"changed", cozyv1alpha1.WorkloadMonitorStatus{Operational: new(true)}, 1},
23272327
} {
23282328
t.Run(tc.name, func(t *testing.T) {
23292329
s := newTestScheme()
@@ -2385,7 +2385,7 @@ func TestReconcile_PVCOfANotReadyDataVolumeIsNotOperational(t *testing.T) {
23852385
{name: "not owned by the DataVolume", phase: "ImportInProgress", reader: true, want: true},
23862386
{name: "controller of another kind", phase: "ImportInProgress", reader: true, controlled: true, ownerGVK: &schema.GroupVersionKind{Group: dataVolumeGVK.Group, Version: dataVolumeGVK.Version, Kind: "DataSource"}, want: true},
23872387
{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},
2388-
{name: "unread keeps the stored verdict", phase: "Succeeded", stored: ptr.To(false), controlled: true, want: false},
2388+
{name: "unread keeps the stored verdict", phase: "Succeeded", stored: new(false), controlled: true, want: false},
23892389
{name: "unread and new reads bind state", phase: "ImportInProgress", controlled: true, want: true},
23902390
} {
23912391
t.Run(tc.name, func(t *testing.T) {
@@ -2398,7 +2398,7 @@ func TestReconcile_PVCOfANotReadyDataVolumeIsNotOperational(t *testing.T) {
23982398
dv.SetUID("dv-uid")
23992399
pvc := &corev1.PersistentVolumeClaim{
24002400
ObjectMeta: metav1.ObjectMeta{Name: "vm-disk-test", Namespace: "default", Labels: selector},
2401-
Spec: corev1.PersistentVolumeClaimSpec{StorageClassName: ptr.To("replicated")},
2401+
Spec: corev1.PersistentVolumeClaimSpec{StorageClassName: new("replicated")},
24022402
Status: corev1.PersistentVolumeClaimStatus{Phase: corev1.ClaimBound},
24032403
}
24042404
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

0 commit comments

Comments
 (0)