Skip to content

Commit

Permalink
chore: enable perfsprint linter
Browse files Browse the repository at this point in the history
Signed-off-by: Matthieu MOREL <[email protected]>
  • Loading branch information
mmorel-35 committed Nov 6, 2024
1 parent b9d5387 commit a2feff9
Show file tree
Hide file tree
Showing 18 changed files with 56 additions and 40 deletions.
12 changes: 12 additions & 0 deletions .golangci.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,7 @@ linters:
- govet
- ineffassign
- misspell
- perfsprint
- staticcheck
- testifylint
- thelper
Expand All @@ -39,6 +40,17 @@ linters-settings:
- typeSwitchVar
goimports:
local-prefixes: github.com/argoproj/argo-cd/v2
perfsprint:
# Optimizes even if it requires an int or uint type cast.
int-conversion: true
# Optimizes into `err.Error()` even if it is only equivalent for non-nil errors.
err-error: false
# Optimizes `fmt.Errorf`.
errorf: false
# Optimizes `fmt.Sprintf` with only one argument.
sprintf1: true
# Optimizes into strings concatenation.
strconcat: false
testifylint:
enable-all: true
disable:
Expand Down
15 changes: 8 additions & 7 deletions applicationset/controllers/applicationset_controller.go
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,7 @@ import (
"fmt"
"reflect"
"sort"
"strconv"
"strings"
"time"

Expand Down Expand Up @@ -1047,7 +1048,7 @@ func (r *ApplicationSetReconciler) updateApplicationSetApplicationStatus(ctx con
LastTransitionTime: &now,
Message: "No Application status found, defaulting status to Waiting.",
Status: "Waiting",
Step: fmt.Sprint(getAppStep(app.Name, appStepMap)),
Step: strconv.Itoa(getAppStep(app.Name, appStepMap)),
TargetRevisions: app.Status.GetRevisions(),
}
} else {
Expand All @@ -1072,7 +1073,7 @@ func (r *ApplicationSetReconciler) updateApplicationSetApplicationStatus(ctx con
currentAppStatus.LastTransitionTime = &now
currentAppStatus.Status = "Waiting"
currentAppStatus.Message = "Application has pending changes, setting status to Waiting."
currentAppStatus.Step = fmt.Sprint(getAppStep(currentAppStatus.Application, appStepMap))
currentAppStatus.Step = strconv.Itoa(getAppStep(currentAppStatus.Application, appStepMap))
currentAppStatus.TargetRevisions = app.Status.GetRevisions()
}

Expand All @@ -1090,14 +1091,14 @@ func (r *ApplicationSetReconciler) updateApplicationSetApplicationStatus(ctx con
currentAppStatus.LastTransitionTime = &now
currentAppStatus.Status = "Progressing"
currentAppStatus.Message = "Application resource completed a sync successfully, updating status from Pending to Progressing."
currentAppStatus.Step = fmt.Sprint(getAppStep(currentAppStatus.Application, appStepMap))
currentAppStatus.Step = strconv.Itoa(getAppStep(currentAppStatus.Application, appStepMap))
}
} else if operationPhaseString == "Running" || healthStatusString == "Progressing" {
logCtx.Infof("Application %v has entered Progressing status, updating its ApplicationSet status to Progressing", app.Name)
currentAppStatus.LastTransitionTime = &now
currentAppStatus.Status = "Progressing"
currentAppStatus.Message = "Application resource became Progressing, updating status from Pending to Progressing."
currentAppStatus.Step = fmt.Sprint(getAppStep(currentAppStatus.Application, appStepMap))
currentAppStatus.Step = strconv.Itoa(getAppStep(currentAppStatus.Application, appStepMap))
}
}

Expand All @@ -1106,15 +1107,15 @@ func (r *ApplicationSetReconciler) updateApplicationSetApplicationStatus(ctx con
currentAppStatus.LastTransitionTime = &now
currentAppStatus.Status = healthStatusString
currentAppStatus.Message = "Application resource is already Healthy, updating status from Waiting to Healthy."
currentAppStatus.Step = fmt.Sprint(getAppStep(currentAppStatus.Application, appStepMap))
currentAppStatus.Step = strconv.Itoa(getAppStep(currentAppStatus.Application, appStepMap))
}

if currentAppStatus.Status == "Progressing" && isApplicationHealthy(app) {
logCtx.Infof("Application %v has completed Progressing status, updating its ApplicationSet status to Healthy", app.Name)
currentAppStatus.LastTransitionTime = &now
currentAppStatus.Status = healthStatusString
currentAppStatus.Message = "Application resource became Healthy, updating status from Progressing to Healthy."
currentAppStatus.Step = fmt.Sprint(getAppStep(currentAppStatus.Application, appStepMap))
currentAppStatus.Step = strconv.Itoa(getAppStep(currentAppStatus.Application, appStepMap))
}

appStatuses = append(appStatuses, currentAppStatus)
Expand Down Expand Up @@ -1185,7 +1186,7 @@ func (r *ApplicationSetReconciler) updateApplicationSetApplicationStatusProgress
appStatus.LastTransitionTime = &now
appStatus.Status = "Pending"
appStatus.Message = "Application moved to Pending status, watching for the Application resource to start Progressing."
appStatus.Step = fmt.Sprint(getAppStep(appStatus.Application, appStepMap))
appStatus.Step = strconv.Itoa(getAppStep(appStatus.Application, appStepMap))

updateCountMap[appStepMap[appStatus.Application]] += 1
}
Expand Down
2 changes: 1 addition & 1 deletion applicationset/utils/map.go
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,7 @@ func ConvertToMapStringString(mapStringInterface map[string]interface{}) map[str
mapStringString := make(map[string]string, len(mapStringInterface))

for key, value := range mapStringInterface {
strKey := fmt.Sprintf("%v", key)
strKey := key
strValue := fmt.Sprintf("%v", value)

mapStringString[strKey] = strValue
Expand Down
3 changes: 2 additions & 1 deletion common/common_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@ import (
"context"
"fmt"
"os"
"strconv"
"testing"
"time"

Expand Down Expand Up @@ -41,7 +42,7 @@ func Test_GRPCKeepAliveMinIsSet(t *testing.T) {
// Test invalid env var set for EnvGRPCKeepAliveMin
func Test_GRPCKeepAliveMinIncorrectlySet(t *testing.T) {
numSeconds := 15
os.Setenv(EnvGRPCKeepAliveMin, fmt.Sprintf("%d", numSeconds))
os.Setenv(EnvGRPCKeepAliveMin, strconv.Itoa(numSeconds))

grpcKeepAliveMin := GetGRPCKeepAliveEnforcementMinimum()
grpcKeepAliveExpectedMin := defaultGRPCKeepAliveEnforcementMinimum
Expand Down
2 changes: 1 addition & 1 deletion controller/cache/info.go
Original file line number Diff line number Diff line change
Expand Up @@ -451,7 +451,7 @@ func populatePodInfo(un *unstructured.Unstructured, res *ResourceInfo) {
res.Info = append(res.Info, v1alpha1.InfoItem{Name: "Node", Value: pod.Spec.NodeName})
res.Info = append(res.Info, v1alpha1.InfoItem{Name: "Containers", Value: fmt.Sprintf("%d/%d", readyContainers, totalContainers)})
if restarts > 0 {
res.Info = append(res.Info, v1alpha1.InfoItem{Name: "Restart Count", Value: fmt.Sprintf("%d", restarts)})
res.Info = append(res.Info, v1alpha1.InfoItem{Name: "Restart Count", Value: strconv.Itoa(restarts)})
}

var urls []string
Expand Down
2 changes: 1 addition & 1 deletion controller/sharding/sharding_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -226,7 +226,7 @@ func TestGetShardByIndexModuloReplicasCountDistributionFunctionWhenClusterNumber
// The other implementation was giving almost linear time of 400ms up to 10'000 clusters
clusterPointers := []*v1alpha1.Cluster{}
for i := 0; i < 2048; i++ {
cluster := createCluster(fmt.Sprintf("cluster-%d", i), fmt.Sprintf("%d", i))
cluster := createCluster(fmt.Sprintf("cluster-%d", i), strconv.Itoa(i))
clusterPointers = append(clusterPointers, &cluster)
}
replicasCount := 2
Expand Down
2 changes: 1 addition & 1 deletion controller/sharding/shuffle_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -20,7 +20,7 @@ func TestLargeShuffle(t *testing.T) {
clusterList := &v1alpha1.ClusterList{Items: []v1alpha1.Cluster{}}
for i := 0; i < math.MaxInt/4096; i += 256 {
// fmt.Fprintf(os.Stdout, "%d", i)
cluster := createCluster(fmt.Sprintf("cluster-%d", i), fmt.Sprintf("%d", i))
cluster := createCluster(fmt.Sprintf("cluster-%d", i), strconv.Itoa(i))
clusterList.Items = append(clusterList.Items, cluster)
}
db.On("ListClusters", mock.Anything).Return(clusterList, nil)
Expand Down
2 changes: 1 addition & 1 deletion reposerver/repository/chart.go
Original file line number Diff line number Diff line change
Expand Up @@ -20,7 +20,7 @@ func getChartDetails(chartYAML string) (*v1alpha1.ChartDetails, error) {
if maintainer.Email != "" {
maintainers = append(maintainers, strings.Trim(fmt.Sprintf("%v <%v>", maintainer.Name, maintainer.Email), " "))
} else {
maintainers = append(maintainers, fmt.Sprintf("%v", maintainer.Name))
maintainers = append(maintainers, maintainer.Name)
}
}
return &v1alpha1.ChartDetails{
Expand Down
4 changes: 2 additions & 2 deletions server/application/application_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -242,7 +242,7 @@ func newTestAppServerWithEnforcerConfigure(t *testing.T, f func(*rbac.Enforcer),
oldVersion = 0
}
clonedApp := app.DeepCopy()
clonedApp.ResourceVersion = fmt.Sprintf("%d", oldVersion+1)
clonedApp.ResourceVersion = strconv.Itoa(oldVersion + 1)
events <- &appsv1.ApplicationWatchEvent{Type: watch.Added, Application: *clonedApp}
}
}
Expand Down Expand Up @@ -425,7 +425,7 @@ func newTestAppServerWithEnforcerConfigureWithBenchmark(b *testing.B, f func(*rb
oldVersion = 0
}
clonedApp := app.DeepCopy()
clonedApp.ResourceVersion = fmt.Sprintf("%d", oldVersion+1)
clonedApp.ResourceVersion = strconv.Itoa(oldVersion + 1)
events <- &appsv1.ApplicationWatchEvent{Type: watch.Added, Application: *clonedApp}
}
}
Expand Down
4 changes: 2 additions & 2 deletions server/logout/logout_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -3,10 +3,10 @@ package logout
import (
"context"
"errors"
"fmt"
"net/http"
"net/http/httptest"
"regexp"
"strconv"
"testing"

"github.com/argoproj/argo-cd/v2/common"
Expand Down Expand Up @@ -385,7 +385,7 @@ func TestHandlerConstructLogoutURL(t *testing.T) {
if status := tt.responseRecorder.Code; status != http.StatusSeeOther {
if !tt.wantErr {
t.Error(tt.responseRecorder.Body.String())
t.Error("handler returned wrong status code: " + fmt.Sprintf("%d", tt.responseRecorder.Code))
t.Error("handler returned wrong status code: " + strconv.Itoa(tt.responseRecorder.Code))
}
} else {
if tt.wantErr {
Expand Down
5 changes: 3 additions & 2 deletions test/e2e/fixture/app/actions.go
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@ import (
"encoding/json"
"fmt"
"os"
"strconv"

log "github.com/sirupsen/logrus"
v1 "k8s.io/apimachinery/pkg/apis/meta/v1"
Expand Down Expand Up @@ -345,7 +346,7 @@ func (a *Actions) Sync(args ...string) *Actions {
if a.context.name != "" {
args = append(args, a.context.AppQualifiedName())
}
args = append(args, "--timeout", fmt.Sprintf("%v", a.context.timeout))
args = append(args, "--timeout", strconv.Itoa(a.context.timeout))

if a.context.async {
args = append(args, "--async")
Expand Down Expand Up @@ -441,7 +442,7 @@ func (a *Actions) Wait(args ...string) *Actions {
if a.context.name != "" {
args = append(args, a.context.AppQualifiedName())
}
args = append(args, "--timeout", fmt.Sprintf("%v", a.context.timeout))
args = append(args, "--timeout", strconv.Itoa(a.context.timeout))
a.runCli(args...)
return a
}
Expand Down
8 changes: 4 additions & 4 deletions test/e2e/project_management_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -566,11 +566,11 @@ func TestGetVirtualProjectNoMatch(t *testing.T) {
time.Sleep(time.Second * 2)

// App trying to sync a resource which is not blacked listed anywhere
_, err = fixture.RunCli("app", "sync", fixture.Name(), "--resource", "apps:Deployment:guestbook-ui", "--timeout", fmt.Sprintf("%v", 10))
_, err = fixture.RunCli("app", "sync", fixture.Name(), "--resource", "apps:Deployment:guestbook-ui", "--timeout", strconv.Itoa(10))
require.NoError(t, err)

// app trying to sync a resource which is black listed by global project
_, err = fixture.RunCli("app", "sync", fixture.Name(), "--resource", ":Service:guestbook-ui", "--timeout", fmt.Sprintf("%v", 10))
_, err = fixture.RunCli("app", "sync", fixture.Name(), "--resource", ":Service:guestbook-ui", "--timeout", strconv.Itoa(10))
require.NoError(t, err)
}

Expand Down Expand Up @@ -606,11 +606,11 @@ func TestGetVirtualProjectMatch(t *testing.T) {
time.Sleep(time.Second * 2)

// App trying to sync a resource which is not blacked listed anywhere
_, err = fixture.RunCli("app", "sync", fixture.Name(), "--resource", "apps:Deployment:guestbook-ui", "--timeout", fmt.Sprintf("%v", 10))
_, err = fixture.RunCli("app", "sync", fixture.Name(), "--resource", "apps:Deployment:guestbook-ui", "--timeout", strconv.Itoa(10))
require.ErrorContains(t, err, "blocked by sync window")

// app trying to sync a resource which is black listed by global project
_, err = fixture.RunCli("app", "sync", fixture.Name(), "--resource", ":Service:guestbook-ui", "--timeout", fmt.Sprintf("%v", 10))
_, err = fixture.RunCli("app", "sync", fixture.Name(), "--resource", ":Service:guestbook-ui", "--timeout", strconv.Itoa(10))
assert.ErrorContains(t, err, "blocked by sync window")
}

Expand Down
17 changes: 9 additions & 8 deletions util/env/env_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@ package env
import (
"fmt"
"math"
"strconv"
"testing"
"time"

Expand All @@ -23,10 +24,10 @@ func TestParseNumFromEnv(t *testing.T) {
{"Valid positive number", "200", 200},
{"Valid negative number", "-200", -200},
{"Invalid number", "abc", def},
{"Equals minimum", fmt.Sprintf("%d", math.MinInt+1), min},
{"Equals maximum", fmt.Sprintf("%d", math.MaxInt-1), max},
{"Less than minimum", fmt.Sprintf("%d", math.MinInt), def},
{"Greater than maximum", fmt.Sprintf("%d", math.MaxInt), def},
{"Equals minimum", strconv.Itoa(math.MinInt + 1), min},
{"Equals maximum", strconv.Itoa(math.MaxInt - 1), max},
{"Less than minimum", strconv.Itoa(math.MinInt), def},
{"Greater than maximum", strconv.Itoa(math.MaxInt), def},
{"Variable not set", "", def},
}

Expand Down Expand Up @@ -81,10 +82,10 @@ func TestParseInt64FromEnv(t *testing.T) {
}{
{"Valid int64", "200", 200},
{"Text as invalid int64", "abc", def},
{"Equals maximum", fmt.Sprintf("%d", max), max},
{"Equals minimum", fmt.Sprintf("%d", min), min},
{"Greater than maximum", fmt.Sprintf("%d", max+1), def},
{"Less than minimum", fmt.Sprintf("%d", min-1), def},
{"Equals maximum", strconv.FormatInt(max, 10), max},
{"Equals minimum", strconv.FormatInt(min, 10), min},
{"Greater than maximum", strconv.FormatInt(max+1, 10), def},
{"Less than minimum", strconv.FormatInt(min-1, 10), def},
{"Environment not set", "", def},
}

Expand Down
2 changes: 1 addition & 1 deletion util/exec/exec.go
Original file line number Diff line number Diff line change
Expand Up @@ -52,7 +52,7 @@ func RunWithRedactor(cmd *exec.Cmd, redactor func(text string) string) (string,
func RunWithExecRunOpts(cmd *exec.Cmd, opts ExecRunOpts) (string, error) {
cmdOpts := argoexec.CmdOpts{Timeout: timeout, Redactor: opts.Redactor, TimeoutBehavior: opts.TimeoutBehavior, SkipErrorLogging: opts.SkipErrorLogging}
span := tracing.NewLoggingTracer(log.NewLogrusLogger(log.NewWithCurrentConfig())).StartSpan(fmt.Sprintf("exec %v", cmd.Args[0]))
span.SetBaggageItem("dir", fmt.Sprintf("%v", cmd.Dir))
span.SetBaggageItem("dir", cmd.Dir)
if cmdOpts.Redactor != nil {
span.SetBaggageItem("args", opts.Redactor(fmt.Sprintf("%v", cmd.Args)))
} else {
Expand Down
5 changes: 3 additions & 2 deletions util/git/creds.go
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@ import (
"context"
"crypto/sha256"
"encoding/base64"
"encoding/hex"
"encoding/json"
"errors"
"fmt"
Expand Down Expand Up @@ -427,7 +428,7 @@ func (g GitHubAppCreds) getAccessToken() (string, error) {
if err != nil {
return "", err
}
key := fmt.Sprintf("%x", h.Sum(nil))
key := hex.EncodeToString(h.Sum(nil))

// Check cache for GitHub transport which helps fetch an API token
t, found := githubAppTokenCache.Get(key)
Expand Down Expand Up @@ -543,7 +544,7 @@ func (c GoogleCloudCreds) getAccessToken() (string, error) {
if err != nil {
return "", err
}
key := fmt.Sprintf("%x", h.Sum(nil))
key := hex.EncodeToString(h.Sum(nil))

t, found := googleCloudTokenSource.Get(key)
if found {
Expand Down
3 changes: 1 addition & 2 deletions util/jwt/jwt_test.go
Original file line number Diff line number Diff line change
@@ -1,7 +1,6 @@
package jwt

import (
"fmt"
"testing"
"time"

Expand Down Expand Up @@ -45,7 +44,7 @@ func TestIssuedAtTime_Int64(t *testing.T) {
claims := jwt.MapClaims{"iat": int64(1606831200)}
issuedAt, err := IssuedAtTime(claims)
require.NoError(t, err)
str := fmt.Sprint(issuedAt.UTC().Format("Mon Jan _2 15:04:05 2006"))
str := issuedAt.UTC().Format("Mon Jan _2 15:04:05 2006")
assert.Equal(t, "Tue Dec 1 14:00:00 2020", str)
}

Expand Down
4 changes: 2 additions & 2 deletions util/lua/oslib_safe.go
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@ package lua
// github.com/yuin/gopher-lua.

import (
"fmt"
"strconv"
"strings"
"time"

Expand Down Expand Up @@ -116,7 +116,7 @@ func strftime(t time.Time, cfmt string) string {
} else {
switch c {
case 'w':
sc.AppendString(fmt.Sprint(int(t.Weekday())))
sc.AppendString(strconv.Itoa(int(t.Weekday())))
default:
sc.AppendChar('%')
sc.AppendChar(c)
Expand Down
4 changes: 2 additions & 2 deletions util/session/sessionmanager_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -478,8 +478,8 @@ func TestCacheValueGetters(t *testing.T) {
})

t.Run("Greater than allowed in environment overrides", func(t *testing.T) {
t.Setenv(envLoginMaxFailCount, fmt.Sprintf("%d", math.MaxInt32+1))
t.Setenv(envLoginMaxCacheSize, fmt.Sprintf("%d", math.MaxInt32+1))
t.Setenv(envLoginMaxFailCount, strconv.Itoa(math.MaxInt32+1))
t.Setenv(envLoginMaxCacheSize, strconv.Itoa(math.MaxInt32+1))

mlf := getMaxLoginFailures()
assert.Equal(t, defaultMaxLoginFailures, mlf)
Expand Down

0 comments on commit a2feff9

Please sign in to comment.