Fix govet+staticcheck issues (#20263)

This is better: https://github.com/golang/go/issues/60529
This commit is contained in:
Klaus Post 2024-08-14 10:11:51 -07:00 committed by GitHub
parent 51b1f41518
commit 3ffeabdfcb
No known key found for this signature in database
GPG Key ID: B5690EEEBB952194
16 changed files with 49 additions and 37 deletions

View File

@ -800,7 +800,7 @@ func (a adminAPIHandlers) ImportBucketMetadataHandler(w http.ResponseWriter, r *
case bucketPolicyConfig:
// Error out if Content-Length is beyond allowed size.
if sz > maxBucketPolicySize {
rpt.SetStatus(bucket, fileName, fmt.Errorf(ErrPolicyTooLarge.String()))
rpt.SetStatus(bucket, fileName, errors.New(ErrPolicyTooLarge.String()))
continue
}
@ -818,7 +818,7 @@ func (a adminAPIHandlers) ImportBucketMetadataHandler(w http.ResponseWriter, r *
// Version in policy must not be empty
if bucketPolicy.Version == "" {
rpt.SetStatus(bucket, fileName, fmt.Errorf(ErrPolicyInvalidVersion.String()))
rpt.SetStatus(bucket, fileName, errors.New(ErrPolicyInvalidVersion.String()))
continue
}

View File

@ -758,7 +758,7 @@ func serverHandleEnvVars() {
if len(domains) != 0 {
for _, domainName := range strings.Split(domains, config.ValueSeparator) {
if _, ok := dns2.IsDomainName(domainName); !ok {
logger.Fatal(config.ErrInvalidDomainValue(nil).Msg("Unknown value `%s`", domainName),
logger.Fatal(config.ErrInvalidDomainValue(nil).Msgf("Unknown value `%s`", domainName),
"Invalid MINIO_DOMAIN value in environment variable")
}
globalDomainNames = append(globalDomainNames, domainName)
@ -767,7 +767,7 @@ func serverHandleEnvVars() {
lcpSuf := lcpSuffix(globalDomainNames)
for _, domainName := range globalDomainNames {
if domainName == lcpSuf && len(globalDomainNames) > 1 {
logger.Fatal(config.ErrOverlappingDomainValue(nil).Msg("Overlapping domains `%s` not allowed", globalDomainNames),
logger.Fatal(config.ErrOverlappingDomainValue(nil).Msgf("Overlapping domains `%s` not allowed", globalDomainNames),
"Invalid MINIO_DOMAIN value in environment variable")
}
}

View File

@ -311,7 +311,7 @@ func GetAllSets(setDriveCount uint64, args ...string) ([][]string, error) {
for _, sargs := range setArgs {
for _, arg := range sargs {
if uniqueArgs.Contains(arg) {
return nil, config.ErrInvalidErasureEndpoints(nil).Msg(fmt.Sprintf("Input args (%s) has duplicate ellipses", args))
return nil, config.ErrInvalidErasureEndpoints(nil).Msgf("Input args (%s) has duplicate ellipses", args)
}
uniqueArgs.Add(arg)
}

View File

@ -114,7 +114,7 @@ func ftpTrace(s *ftp.Context, startTime time.Time, source, objPath string, err e
TraceType: madmin.TraceFTP,
Time: startTime,
NodeName: globalLocalNodeName,
FuncName: fmt.Sprintf(s.Cmd),
FuncName: s.Cmd,
Duration: time.Since(startTime),
Path: objPath,
Error: errStr,

View File

@ -194,7 +194,7 @@ func (er *erasureObjects) healErasureSet(ctx context.Context, buckets []string,
numHealers = uint64(v)
}
healingLogEvent(ctx, fmt.Sprintf("Healing drive '%s' - use %d parallel workers.", tracker.disk.String(), numHealers))
healingLogEvent(ctx, "Healing drive '%s' - use %d parallel workers.", tracker.disk.String(), numHealers)
jt, _ := workers.New(int(numHealers))

View File

@ -79,7 +79,7 @@ func testObjectNewMultipartUpload(obj ObjectLayer, instanceType string, t TestEr
case InvalidUploadID:
t.Fatalf("%s: New Multipart upload failed to create uuid file.", instanceType)
default:
t.Fatalf(err.Error())
t.Fatal(err.Error())
}
}
}

View File

@ -1193,7 +1193,7 @@ func logFatalErrs(err error, endpoint Endpoint, exit bool) {
} else {
hint = "Drives do not support O_DIRECT flags, MinIO erasure coding requires filesystems with O_DIRECT support"
}
logger.Fatal(config.ErrUnsupportedBackend(err).Hint(hint), "Unable to initialize backend")
logger.Fatal(config.ErrUnsupportedBackend(err).Hint("%s", hint), "Unable to initialize backend")
case errors.Is(err, errDiskNotDir):
var hint string
if endpoint.URL != nil {
@ -1201,7 +1201,7 @@ func logFatalErrs(err error, endpoint Endpoint, exit bool) {
} else {
hint = "Drives are not directories, MinIO erasure coding needs directories"
}
logger.Fatal(config.ErrUnableToWriteInBackend(err).Hint(hint), "Unable to initialize backend")
logger.Fatal(config.ErrUnableToWriteInBackend(err).Hint("%s", hint), "Unable to initialize backend")
case errors.Is(err, errDiskAccessDenied):
// Show a descriptive error with a hint about how to fix it.
var username string
@ -1220,7 +1220,7 @@ func logFatalErrs(err error, endpoint Endpoint, exit bool) {
if !exit {
storageLogOnceIf(GlobalContext, fmt.Errorf("Drive is not writable %s, %s", endpoint, hint), "log-fatal-errs")
} else {
logger.Fatal(config.ErrUnableToWriteInBackend(err).Hint(hint), "Unable to initialize backend")
logger.Fatal(config.ErrUnableToWriteInBackend(err).Hint("%s", hint), "Unable to initialize backend")
}
case errors.Is(err, errFaultyDisk):
if !exit {

View File

@ -289,7 +289,7 @@ func (sts *stsAPIHandlers) AssumeRole(w http.ResponseWriter, r *http.Request) {
if apiErrCode != ErrNone {
stsErr := apiToSTSError(apiErrCode)
// Borrow the description error from the API error code
writeSTSErrorResponse(ctx, w, stsErr, fmt.Errorf(errorCodes[apiErrCode].Description))
writeSTSErrorResponse(ctx, w, stsErr, errors.New(errorCodes[apiErrCode].Description))
return
}

View File

@ -268,7 +268,7 @@ func TestDownloadReleaseData(t *testing.T) {
}{
{httpServer1.URL, "", nil},
{httpServer2.URL, "fbe246edbd382902db9a4035df7dce8cb441357d minio.RELEASE.2016-10-07T01-16-39Z\n", nil},
{httpServer3.URL, "", fmt.Errorf("Error downloading URL " + httpServer3.URL + ". Response: 404 Not Found")},
{httpServer3.URL, "", fmt.Errorf("Error downloading URL %s. Response: 404 Not Found", httpServer3.URL)},
}
for _, testCase := range testCases {

View File

@ -21,7 +21,6 @@ import (
"bytes"
"context"
"crypto/rand"
"fmt"
"io"
"net/url"
"os"
@ -158,22 +157,22 @@ func createPermDeniedFile(t *testing.T) (permDeniedDir string) {
permDeniedDir = t.TempDir()
if err = os.Mkdir(slashpath.Join(permDeniedDir, "mybucket"), 0o775); err != nil {
t.Fatalf(fmt.Sprintf("Unable to create temporary directory %v. %v", slashpath.Join(permDeniedDir, "mybucket"), err))
t.Fatalf("Unable to create temporary directory %v. %v", slashpath.Join(permDeniedDir, "mybucket"), err)
}
if err = os.WriteFile(slashpath.Join(permDeniedDir, "mybucket", "myobject"), []byte(""), 0o400); err != nil {
t.Fatalf(fmt.Sprintf("Unable to create file %v. %v", slashpath.Join(permDeniedDir, "mybucket", "myobject"), err))
t.Fatalf("Unable to create file %v. %v", slashpath.Join(permDeniedDir, "mybucket", "myobject"), err)
}
if err = os.Chmod(slashpath.Join(permDeniedDir, "mybucket"), 0o400); err != nil {
t.Fatalf(fmt.Sprintf("Unable to change permission to temporary directory %v. %v", slashpath.Join(permDeniedDir, "mybucket"), err))
t.Fatalf("Unable to change permission to temporary directory %v. %v", slashpath.Join(permDeniedDir, "mybucket"), err)
}
t.Cleanup(func() {
os.Chmod(slashpath.Join(permDeniedDir, "mybucket"), 0o775)
})
if err = os.Chmod(permDeniedDir, 0o400); err != nil {
t.Fatalf(fmt.Sprintf("Unable to change permission to temporary directory %v. %v", permDeniedDir, err))
t.Fatalf("Unable to change permission to temporary directory %v. %v", permDeniedDir, err)
}
t.Cleanup(func() {
os.Chmod(permDeniedDir, 0o775)

View File

@ -49,19 +49,19 @@ func ParsePublicCertFile(certFile string) (x509Certs []*x509.Certificate, err er
for len(current) > 0 {
var pemBlock *pem.Block
if pemBlock, current = pem.Decode(current); pemBlock == nil {
return nil, ErrTLSUnexpectedData(nil).Msg("Could not read PEM block from file %s", certFile)
return nil, ErrTLSUnexpectedData(nil).Msgf("Could not read PEM block from file %s", certFile)
}
var x509Cert *x509.Certificate
if x509Cert, err = x509.ParseCertificate(pemBlock.Bytes); err != nil {
return nil, ErrTLSUnexpectedData(nil).Msg("Failed to parse `%s`: %s", certFile, err.Error())
return nil, ErrTLSUnexpectedData(nil).Msgf("Failed to parse `%s`: %s", certFile, err.Error())
}
x509Certs = append(x509Certs, x509Cert)
}
if len(x509Certs) == 0 {
return nil, ErrTLSUnexpectedData(nil).Msg("Empty public certificate file %s", certFile)
return nil, ErrTLSUnexpectedData(nil).Msgf("Empty public certificate file %s", certFile)
}
return x509Certs, nil
@ -73,18 +73,18 @@ func ParsePublicCertFile(certFile string) (x509Certs []*x509.Certificate, err er
func LoadX509KeyPair(certFile, keyFile string) (tls.Certificate, error) {
certPEMBlock, err := os.ReadFile(certFile)
if err != nil {
return tls.Certificate{}, ErrTLSReadError(nil).Msg("Unable to read the public key: %s", err)
return tls.Certificate{}, ErrTLSReadError(nil).Msgf("Unable to read the public key: %s", err)
}
keyPEMBlock, err := os.ReadFile(keyFile)
if err != nil {
return tls.Certificate{}, ErrTLSReadError(nil).Msg("Unable to read the private key: %s", err)
return tls.Certificate{}, ErrTLSReadError(nil).Msgf("Unable to read the private key: %s", err)
}
key, rest := pem.Decode(keyPEMBlock)
if len(rest) > 0 {
return tls.Certificate{}, ErrTLSUnexpectedData(nil).Msg("The private key contains additional data")
return tls.Certificate{}, ErrTLSUnexpectedData(nil).Msgf("The private key contains additional data")
}
if key == nil {
return tls.Certificate{}, ErrTLSUnexpectedData(nil).Msg("The private key is not readable")
return tls.Certificate{}, ErrTLSUnexpectedData(nil).Msgf("The private key is not readable")
}
if x509.IsEncryptedPEMBlock(key) {
password := env.Get(EnvCertPassword, "")

View File

@ -58,9 +58,20 @@ func (u Err) Error() string {
}
// Msg - Replace the current error's message
func (u Err) Msg(m string, args ...interface{}) Err {
func (u Err) Msg(m string) Err {
e := u.Clone()
e.msg = m
return e
}
// Msgf - Replace the current error's message
func (u Err) Msgf(m string, args ...interface{}) Err {
e := u.Clone()
if len(args) == 0 {
e.msg = m
} else {
e.msg = fmt.Sprintf(m, args...)
}
return e
}

View File

@ -23,14 +23,10 @@ package disk
import (
"os"
"reflect"
"runtime"
"testing"
)
func TestReadDriveStats(t *testing.T) {
if runtime.GOOS == "windows" {
t.Skip("skipping this test in windows")
}
testCases := []struct {
stat string
expectedIOStats IOStats

View File

@ -210,7 +210,7 @@ const (
func init() {
// Static check if we exceed 255 handler ids.
// Extend the type to uint16 when hit.
if handlerLast > 255 {
if uint32(handlerLast) > 255 {
panic(fmt.Sprintf("out of handler IDs. %d > %d", handlerLast, 255))
}
}
@ -435,6 +435,7 @@ func recycleFunc[RT RoundTripper](newRT func() RT) (newFn func() RT, recycle fun
return func() RT { return pool.Get().(RT) },
func(r RT) {
if r != rZero {
//nolint:staticcheck // SA6002 IT IS A GENERIC VALUE!
pool.Put(r)
}
}
@ -601,15 +602,18 @@ func GetCaller(ctx context.Context) *RemoteClient {
// GetSubroute returns caller information from contexts provided to handlers.
func GetSubroute(ctx context.Context) string {
//nolint:staticcheck // SA1029 Staticcheck is drunk.
val, _ := ctx.Value(ctxSubrouteKey{}).(string)
return val
}
func setCaller(ctx context.Context, cl *RemoteClient) context.Context {
//nolint:staticcheck // SA1029 Staticcheck is drunk.
return context.WithValue(ctx, ctxCallerKey{}, cl)
}
func setSubroute(ctx context.Context, s string) context.Context {
//nolint:staticcheck // SA1029 Staticcheck is drunk.
return context.WithValue(ctx, ctxSubrouteKey{}, s)
}
@ -681,6 +685,7 @@ func (h *StreamTypeHandler[Payload, Req, Resp]) NewRequest() Req {
// These should be returned by the handler.
func (h *StreamTypeHandler[Payload, Req, Resp]) PutRequest(r Req) {
if r != h.nilReq {
//nolint:staticcheck // SA6002 IT IS A GENERIC VALUE! (and always a pointer)
h.reqPool.Put(r)
}
}
@ -689,6 +694,7 @@ func (h *StreamTypeHandler[Payload, Req, Resp]) PutRequest(r Req) {
// These should be returned by the caller.
func (h *StreamTypeHandler[Payload, Req, Resp]) PutResponse(r Resp) {
if r != h.nilResp {
//nolint:staticcheck // SA6002 IT IS A GENERIC VALUE! (and always a pointer)
h.respPool.Put(r)
}
}

View File

@ -598,6 +598,7 @@ func (p *ArrayOf[T]) newA(sz uint32) []T {
func (p *ArrayOf[T]) putA(v []T) {
var zero T // nil
for i, t := range v {
//nolint:staticcheck // SA6002 IT IS A GENERIC VALUE!
p.ePool.Put(t)
v[i] = zero
}

View File

@ -18,7 +18,6 @@
package pubsub
import (
"fmt"
"testing"
"time"
)
@ -138,7 +137,7 @@ func TestPubSub(t *testing.T) {
ps.Publish(val)
msg := <-ch1
if msg != val {
t.Fatalf(fmt.Sprintf("expected %s , found %s", val, msg))
t.Fatalf("expected %s , found %s", val, msg)
}
}
@ -160,7 +159,7 @@ func TestMultiPubSub(t *testing.T) {
msg1 := <-ch1
msg2 := <-ch2
if msg1 != val && msg2 != val {
t.Fatalf(fmt.Sprintf("expected both subscribers to have%s , found %s and %s", val, msg1, msg2))
t.Fatalf("expected both subscribers to have%s , found %s and %s", val, msg1, msg2)
}
}
@ -189,12 +188,12 @@ func TestMultiPubSubMask(t *testing.T) {
msg1 := <-ch1
msg2 := <-ch2
if msg1 != val && msg2 != val {
t.Fatalf(fmt.Sprintf("expected both subscribers to have%s , found %s and %s", val, msg1, msg2))
t.Fatalf("expected both subscribers to have%s , found %s and %s", val, msg1, msg2)
}
select {
case msg := <-ch3:
t.Fatalf(fmt.Sprintf("unexpected msg, f got %s", msg))
t.Fatalf("unexpected msg, f got %s", msg)
default:
}
}