core: fix golangci-lint check QF1003 QF1002

Refactored multiple conditional if-else blocks into switch statements to improve readability and maintainability. Also removed outdated staticcheck rule comments (QF1002, QF1003) from .golangci.yaml.

Signed-off-by: Carlos Barria <cbarria@yahoo.com>
This commit is contained in:
Carlos Barria committed 2025-05-27 13:49:49 -04:00
1 parent d2dfc29ed6
commit 030ada45b0
19 files changed
+91 -79

No files matched your search

-6
View File
@@ -16,9 +16,6 @@ linters:
- legacy
- std-error-handling
rules:
- linters:
- staticcheck
text: "QF1003:" # could use tagged switch on errCode (staticcheck)
- linters:
- staticcheck
text: "QF1008:" # could remove embedded field "Connection" from selector (staticcheck)
@@ -28,9 +25,6 @@ linters:
- linters:
- staticcheck
text: "QF1001:" # could apply De Morgan's law (staticcheck)
- linters:
- staticcheck
text: "QF1002:" # could use tagged switch on args[0] (staticcheck)
- linters:
- staticcheck
text: "ST1019" # package "github.com/rook/rook/pkg/daemon/ceph/client" is being imported more than once (staticcheck)
+5 -3
View File
@@ -70,17 +70,19 @@ func TestEnablePoolMirroring(t *testing.T) {
executor := &exectest.MockExecutor{}
executor.MockExecuteCommandWithOutput = func(command string, args ...string) (string, error) {
if args[0] == "mirror" {
if args[2] == "enable" {
switch args[2] {
case "enable":
assert.Equal(t, "pool", args[1])
assert.Equal(t, pool.Name, args[3])
assert.Equal(t, pool.Mirroring.Mode, args[4])
return "", nil
} else if args[2] == "info" {
case "info":
assert.Equal(t, "pool", args[1])
assert.Equal(t, pool.Name, args[3])
return poolInfo, nil
default:
return "", nil
}
return "", nil
}
return "", errors.New("unknown command")
}
+4 -3
View File
@@ -187,11 +187,12 @@ func CreatePoolWithPGs(context *clusterd.Context, clusterInfo *ClusterInfo, clus
return errors.New("pool name must be specified")
}
// Override the application name for built-in pools
if pool.Name == ".mgr" {
switch pool.Name {
case ".mgr":
pool.Application = "mgr"
} else if pool.Name == ".nfs" {
case ".nfs":
pool.Application = "nfs"
} else if pool.Name == ".rgw.root" {
case ".rgw.root":
pool.Application = "rgw"
}
+4 -4
View File
@@ -495,8 +495,8 @@ func testCreateStretchCrushRule(t *testing.T, alreadyExists bool) {
}
}
if command == "crushtool" {
switch {
case args[0] == "--decompile" || args[0] == "--compile":
switch args[0] {
case "--decompile", "--compile":
if alreadyExists {
return "", errors.New("--compile or --decompile not expected for already existing crush rule")
}
@@ -626,8 +626,8 @@ func testCreateHybridCrushRule(t *testing.T, alreadyExists bool) {
}
}
if command == "crushtool" {
switch {
case args[0] == "--decompile" || args[0] == "--compile":
switch args[0] {
case "--decompile", "--compile":
if alreadyExists {
return "", errors.New("--compile or --decompile not expected for already existing crush rule")
}
+4 -3
View File
@@ -75,11 +75,12 @@ func TestRadosRemoveObject(t *testing.T) {
subCommand := arg[4]
assert.Equal(t, arg[5], "someobj")
if subCommand == "stat" {
switch subCommand {
case "stat":
return "", nil // successful stat means obj exists
} else if subCommand == "rm" {
case "rm":
return "", errors.New("induced rm error")
} else {
default:
panic(fmt.Sprintf("unhandled subcommand %q", subCommand))
}
},
+4 -3
View File
@@ -550,11 +550,12 @@ func getAvailableDevices(context *clusterd.Context, agent *OsdAgent) (*DeviceOsd
// It is particularly useful when a metadata PVC is used because we need to identify it in the map
// So the entry must be named "metadata" so it can accessed later
if agent.pvcBacked {
if device.Type == pvcDataTypeDevice {
switch device.Type {
case pvcDataTypeDevice:
available.Entries[pvcDataTypeDevice] = deviceInfo
} else if device.Type == pvcMetadataTypeDevice {
case pvcMetadataTypeDevice:
available.Entries[pvcMetadataTypeDevice] = deviceInfo
} else if device.Type == pvcWalTypeDevice {
case pvcWalTypeDevice:
available.Entries[pvcWalTypeDevice] = deviceInfo
}
} else {
+5 -4
View File
@@ -236,11 +236,12 @@ func validateVaultConnectionDetails(ctx context.Context, clusterdContext *cluste
}
func tlsSecretKeyToCheck(tlsOption string) string {
if tlsOption == api.EnvVaultCACert || tlsOption == api.EnvVaultClientCert {
switch tlsOption {
case api.EnvVaultCACert, api.EnvVaultClientCert:
return vaultCACertSecretKeyName
} else if tlsOption == api.EnvVaultClientKey {
case api.EnvVaultClientKey:
return vaultKeySecretKeyName
default:
return ""
}
return ""
}
+6 -6
View File
@@ -412,8 +412,8 @@ func TestGetCephVolumeInventory(t *testing.T) {
MockExecuteCommandWithOutput: func(command string, arg ...string) (string, error) {
run++
logger.Infof("run %d command %s", run, command)
switch {
case run == 1:
switch run {
case 1:
return `[{"available": true, "rejected_reasons": [], "sys_api": {"scheduler_mode": "noop",
"rotational": "0", "vendor": "ATA", "human_readable_size": "25.00 GB", "sectors": 0, "sas_device_handle": "",
"partitions": {}, "rev": "1.0", "sas_address": "", "locked": 0, "sectorsize": "512", "removable": "0", "path": "/dev/sdb",
@@ -426,13 +426,13 @@ func TestGetCephVolumeInventory(t *testing.T) {
"model": "VBOX HARDDISK", "ro": "0", "nr_requests": "128", "size": 34359738368.0}, "lvs": [{"comment": "not used by ceph", "name": "swap"},
{"comment": "not used by ceph", "name": "root"}], "path": "/dev/sda"}]
`, nil
case run == 2: // No data returned from Ceph Volume
case 2: // No data returned from Ceph Volume
return ``, nil
case run == 3: // No devices returned from Ceph Volume
case 3: // No devices returned from Ceph Volume
return `[]`, nil
case run == 4: // Error executing Ceph Volume
case 4: // Error executing Ceph Volume
return ``, fmt.Errorf("unexplainable error")
case run == 5: // A device without sys_api data
case 5: // A device without sys_api data
return `[{"available": true }]`, nil
}
return "", nil
@@ -88,9 +88,10 @@ func TestStartSecureDashboard(t *testing.T) {
logger.Infof("command: %s %v", command, args)
exitCodeResponse = 0
if args[1] == "module" {
if args[2] == "enable" {
switch args[2] {
case "enable":
enables++
} else if args[2] == "disable" {
case "disable":
disables++
}
}
+4 -3
View File
@@ -399,12 +399,13 @@ func TestPostReconcileUpdateOSDProperties(t *testing.T) {
return osdDFResults, nil
}
if args[1] == "crush" {
if args[2] == "rm-device-class" {
switch args[2] {
case "rm-device-class":
removedDeviceClassOSD = args[3]
} else if args[2] == "set-device-class" {
case "set-device-class":
setDeviceClass = args[3]
setDeviceClassOSD = args[4]
} else if args[2] == "reweight" {
case "reweight":
osdID = append(osdID, args[3])
crushWeight = append(crushWeight, args[4])
}
+12 -9
View File
@@ -260,9 +260,10 @@ var mockExecutor = &exectest.MockExecutor{
logger.Infof("Command: %s %v", command, args)
// Fake pool details for "rook-ceph-primary" cluster
if args[0] == "osd" && args[1] == "pool" && args[2] == "get" && strings.HasSuffix(args[6], ns) {
if args[3] == "mirrorPool1" {
switch args[3] {
case "mirrorPool1":
return `{"pool_id": 1}`, nil
} else if args[3] == "mirrorPool2" {
case "mirrorPool2":
return `{"pool_id": 2}`, nil
}
}
@@ -271,13 +272,14 @@ var mockExecutor = &exectest.MockExecutor{
MockExecuteCommandWithTimeout: func(timeout time.Duration, command string, args ...string) (string, error) {
logger.Infof("Command: %s %v", command, args)
if args[0] == "osd" && args[1] == "pool" && args[2] == "get" && strings.HasSuffix(args[5], "peer1") {
if args[3] == "mirrorPool1" {
switch args[3] {
case "mirrorPool1":
err := saveMockDataInTempFile(`{"pool_id": 2}`, peerPoolTempFile)
if err != nil {
return "", err
}
return `{"pool_id": 2}`, nil
} else if args[3] == "mirrorPool2" {
case "mirrorPool2":
err := saveMockDataInTempFile(`{"pool_id": 3}`, peerPoolTempFile)
if err != nil {
return "", err
@@ -286,13 +288,14 @@ var mockExecutor = &exectest.MockExecutor{
}
}
if args[0] == "osd" && args[1] == "pool" && args[2] == "get" && strings.HasSuffix(args[5], "peer2") {
if args[3] == "mirrorPool1" {
switch args[3] {
case "mirrorPool1":
err := saveMockDataInTempFile(`{"pool_id": 3}`, peerPoolTempFile)
if err != nil {
return "", err
}
return `{"pool_id": 3}`, nil
} else if args[3] == "mirrorPool2" {
case "mirrorPool2":
err := saveMockDataInTempFile(`{"pool_id": 4}`, peerPoolTempFile)
if err != nil {
return "", err
@@ -301,13 +304,13 @@ var mockExecutor = &exectest.MockExecutor{
}
}
if args[0] == "osd" && args[1] == "pool" && args[2] == "get" && strings.HasSuffix(args[5], "peer3") {
if args[3] == "mirrorPool1" {
switch args[3] {
case "mirrorPool1":
err := saveMockDataInTempFile(`{"pool_id": 4}`, peerPoolTempFile)
if err != nil {
return "", err
}
return `{"pool_id": 4}`, nil
} else if args[3] == "mirrorPool2" {
case "mirrorPool2":
err := saveMockDataInTempFile(`{"pool_id": 5}`, peerPoolTempFile)
if err != nil {
return "", err
+3 -2
View File
@@ -678,9 +678,10 @@ func TestCephObjectStoreControllerMultisite(t *testing.T) {
return realmGetMultisiteJSON, nil
}
if args[0] == "zonegroup" {
if args[1] == "get" {
switch args[1] {
case "get":
return zoneGroupGetMultisiteJSON, nil
} else if args[1] == "modify" {
case "modify":
zoneGroupGetMultisiteJSON = zoneGroupGetMultisiteJSONWithEndpoint
return zoneGroupGetMultisiteJSON, nil
}
+3 -4
View File
@@ -1158,7 +1158,8 @@ func checkDashboardUser(context *Context, user ObjectUser) (bool, error) {
dUser, errId, err := GetUser(context, DashboardUser)
// If not found or "none" error, all is good to not return the error
if errId == RGWErrorNone {
switch errId {
case RGWErrorNone:
// If the access key or secret key is not the same as the given user, return false
if user.AccessKey != nil && *user.AccessKey != *dUser.AccessKey {
return false, nil
@@ -1166,12 +1167,10 @@ func checkDashboardUser(context *Context, user ObjectUser) (bool, error) {
if user.SecretKey != nil && *user.SecretKey != *dUser.SecretKey {
return false, nil
}
return true, nil
} else if errId == RGWErrorNotFound {
case RGWErrorNotFound:
return false, nil
}
return false, err
}
+9 -6
View File
@@ -594,9 +594,10 @@ func TestCheckDashboardUser(t *testing.T) {
objContext.Context.Executor = &exectest.MockExecutor{
MockExecuteCommandWithOutput: func(command string, args ...string) (string, error) {
if args[0] == "dashboard" {
if args[1] == "get-rgw-api-access-key" {
switch args[1] {
case "get-rgw-api-access-key":
return access_key, nil
} else if args[1] == "get-rgw-api-secret-key" {
case "get-rgw-api-secret-key":
return secret_key, nil
}
}
@@ -626,9 +627,10 @@ func TestCheckDashboardUser(t *testing.T) {
objContext.Context.Executor = &exectest.MockExecutor{
MockExecuteCommandWithOutput: func(command string, args ...string) (string, error) {
if args[0] == "dashboard" {
if args[1] == "get-rgw-api-access-key" {
switch args[1] {
case "get-rgw-api-access-key":
return "incorrect", nil
} else if args[1] == "get-rgw-api-secret-key" {
case "get-rgw-api-secret-key":
return "incorrect", nil
}
}
@@ -663,9 +665,10 @@ func TestDashboard(t *testing.T) {
},
MockExecuteCommandWithTimeout: func(timeout time.Duration, command string, args ...string) (string, error) {
if args[0] == "user" {
if args[1] == "info" {
switch args[1] {
case "info":
return "no user info saved", nil
} else if args[1] == "create" {
case "create":
return dashboardAdminCreateJSON, nil
}
}
+4 -3
View File
@@ -404,17 +404,18 @@ func GetTlsCaCert(objContext *Context, objectStoreSpec *cephv1.ObjectStoreSpec)
if err != nil {
return nil, false, errors.Wrapf(err, "failed to get secret %q containing TLS certificate defined in %q", objectStoreSpec.Gateway.SSLCertificateRef, objContext.Name)
}
if tlsSecretCert.Type == v1.SecretTypeOpaque {
switch tlsSecretCert.Type {
case v1.SecretTypeOpaque:
tlsCert, ok = tlsSecretCert.Data[certKeyName]
if !ok {
return nil, false, errors.Errorf("failed to get TLS certificate from secret, token is %q but key %q does not exist", v1.SecretTypeOpaque, certKeyName)
}
} else if tlsSecretCert.Type == v1.SecretTypeTLS {
case v1.SecretTypeTLS:
tlsCert, ok = tlsSecretCert.Data[v1.TLSCertKey]
if !ok {
return nil, false, errors.Errorf("failed to get TLS certificate from secret, token is %q but key %q does not exist", v1.SecretTypeTLS, v1.TLSCertKey)
}
} else {
default:
return nil, false, errors.Errorf("failed to get TLS certificate from secret, unknown secret type %q", tlsSecretCert.Type)
}
// If the secret contains an indication that the TLS connection should be insecure, then
+3 -2
View File
@@ -178,9 +178,10 @@ func CreateOrRecreateUserIfExists(c *Context, user ObjectUser, force bool) (*Obj
return nil, errCode, err
}
if errCode == RGWErrorNone {
switch errCode {
case RGWErrorNone:
return objUser, errCode, err
} else if errCode == ErrorCodeFileExists {
case ErrorCodeFileExists:
// If the user already exists, delete and re-create it
_, err := DeleteUser(c, user.UserID)
if err != nil {
@@ -476,15 +476,16 @@ func TestCreateOrUpdateCephUser(t *testing.T) {
}
}
if req.Method == http.MethodPut {
if req.URL.RawQuery == "enabled=false&format=json&max-objects=-1&max-size=-1&quota=&quota-type=user&uid=my-user" ||
req.URL.RawQuery == "enabled=true&format=json&max-objects=10000&max-size=-1&quota=&quota-type=user&uid=my-user" ||
req.URL.RawQuery == "enabled=true&format=json&max-objects=-1&max-size=10000000000&quota=&quota-type=user&uid=my-user" ||
req.URL.RawQuery == "enabled=true&format=json&max-objects=10000&max-size=10000000000&quota=&quota-type=user&uid=my-user" {
switch req.URL.RawQuery {
case "enabled=false&format=json&max-objects=-1&max-size=-1&quota=&quota-type=user&uid=my-user",
"enabled=true&format=json&max-objects=10000&max-size=-1&quota=&quota-type=user&uid=my-user",
"enabled=true&format=json&max-objects=-1&max-size=10000000000&quota=&quota-type=user&uid=my-user",
"enabled=true&format=json&max-objects=10000&max-size=10000000000&quota=&quota-type=user&uid=my-user":
return &http.Response{
StatusCode: 200,
Body: io.NopCloser(bytes.NewReader([]byte(userCreateJSON))),
}, nil
} else if req.URL.RawQuery == "caps=&format=json&uid=my-user&user-caps=users%3Dread%3Bbuckets%3Dwrite%3Broles%3D%2A%3Binfo%3Dread%2C%20write%3B" {
case "caps=&format=json&uid=my-user&user-caps=users%3Dread%3Bbuckets%3Dwrite%3Broles%3D%2A%3Binfo%3Dread%2C%20write%3B":
return &http.Response{
StatusCode: 200,
Body: io.NopCloser(bytes.NewReader([]byte(userCapsJSON))),
+8 -8
View File
@@ -117,21 +117,21 @@ func TestGetPartitions(t *testing.T) {
MockExecuteCommandWithOutput: func(command string, arg ...string) (string, error) {
run++
logger.Infof("run %d command %s", run, command)
switch {
case run == 1:
switch run {
case 1:
return `NAME="sdc" SIZE="100000" TYPE="disk" PKNAME=""`, nil
case run == 2:
case 2:
return `NAME="sdb" SIZE="65" TYPE="disk" PKNAME=""
NAME="sdb2" SIZE="10" TYPE="part" PKNAME="sdb"
NAME="sdb3" SIZE="20" TYPE="part" PKNAME="sdb"
NAME="sdb1" SIZE="30" TYPE="part" PKNAME="sdb"`, nil
case run == 3:
case 3:
return fmt.Sprintf(udevPartOutput, "ROOK-OSD0-DB"), nil
case run == 4:
case 4:
return fmt.Sprintf(udevPartOutput, "ROOK-OSD0-BLOCK"), nil
case run == 5:
case 5:
return fmt.Sprintf(udevPartOutput, "ROOK-OSD0-WAL"), nil
case run == 6:
case 6:
return `NAME="sda" SIZE="19818086400" TYPE="disk" PKNAME=""
NAME="sda4" SIZE="1073741824" TYPE="part" PKNAME="sda"
NAME="sda2" SIZE="2097152" TYPE="part" PKNAME="sda"
@@ -141,7 +141,7 @@ NAME="sda3" SIZE="1073741824" TYPE="part" PKNAME="sda"
NAME="usr" SIZE="1065345024" TYPE="crypt" PKNAME="sda3"
NAME="sda1" SIZE="134217728" TYPE="part" PKNAME="sda"
NAME="sda6" SIZE="134217728" TYPE="part" PKNAME="sda"`, nil
case run == 14:
case 14:
return `NAME="dm-0" SIZE="100000" TYPE="lvm" PKNAME=""
NAME="ceph--89fa04fa--b93a--4874--9364--c95be3ec01c6-osd--data--70847bdb--2ec1--4874--98ba--d87d4860a70d" SIZE="31138512896" TYPE="lvm" PKNAME=""`, nil
}
@@ -200,11 +200,12 @@ func (h *CephInstaller) ConfirmHelmClusterInstalledCorrectly() error {
foundStorageClasses := 0
for _, storageClass := range storageClassList.Items {
if storageClass.Name == BlockPoolSCName {
switch storageClass.Name {
case BlockPoolSCName:
foundStorageClasses++
} else if storageClass.Name == FilesystemSCName {
case FilesystemSCName:
foundStorageClasses++
} else if storageClass.Name == ObjectStoreSCName {
case ObjectStoreSCName:
foundStorageClasses++
}
}