From f245e8beb52e2dd08860f9222a33a2c215b7f291 Mon Sep 17 00:00:00 2001 From: Matthieu MOREL Date: Fri, 20 Dec 2024 17:22:28 +0100 Subject: [PATCH] chore: enable err-error and strconcat of perfsprint linter (#21267) Signed-off-by: Matthieu MOREL --- .golangci.yaml | 4 +-- applicationset/generators/cluster.go | 4 +-- applicationset/generators/duck_type.go | 2 +- applicationset/generators/list.go | 2 +- .../generators/value_interpolation.go | 2 +- applicationset/services/plugin/utils.go | 3 +- applicationset/services/scm_provider/gitea.go | 6 ++-- applicationset/webhook/webhook.go | 2 +- .../commands/argocd_application_controller.go | 4 +-- .../commands/applicationset_controller.go | 4 +-- .../commands/controller.go | 4 +-- cmd/argocd-server/commands/argocd_server.go | 8 ++--- cmd/argocd/commands/account.go | 2 +- .../commands/admin/generatespec_utils.go | 2 +- .../commands/admin/generatespec_utils_test.go | 5 ++- cmd/argocd/commands/admin/notifications.go | 5 ++- cmd/argocd/commands/admin/settings.go | 2 +- cmd/argocd/commands/admin/settings_test.go | 3 +- cmd/argocd/commands/app.go | 8 ++--- cmd/argocd/commands/cluster.go | 4 +-- cmd/argocd/commands/headless/headless.go | 2 +- cmd/argocd/commands/project.go | 2 +- common/common_test.go | 2 +- controller/hydrator/hydrator.go | 2 +- controller/state.go | 12 +++---- controller/sync.go | 4 +-- hack/gen-catalog/main.go | 4 +-- hack/k8s/main.go | 5 ++- pkg/apis/application/v1alpha1/types.go | 4 +-- reposerver/cache/cache.go | 4 +-- reposerver/cache/cache_test.go | 3 +- reposerver/repository/repository.go | 10 +++--- reposerver/repository/repository_test.go | 30 +++++++++--------- reposerver/server.go | 4 +-- server/application/application.go | 4 +-- server/extension/extension.go | 2 +- server/extension/extension_test.go | 4 +-- server/logout/logout.go | 9 +++--- server/server.go | 6 ++-- server/server_norace_test.go | 2 +- server/server_test.go | 6 ++-- test/e2e/app_management_ns_test.go | 4 +-- test/e2e/app_management_test.go | 4 +-- test/e2e/cluster_test.go | 2 +- test/e2e/fixture/app/actions.go | 4 +-- test/e2e/fixture/app/expectation.go | 4 +-- test/e2e/fixture/fixture.go | 16 +++++----- test/e2e/fixture/gpgkeys/gpgkeys.go | 2 +- test/e2e/fixture/repos/repos.go | 4 +-- test/e2e/helm_test.go | 8 ++--- test/e2e/project_management_test.go | 4 +-- test/e2e/selective_sync_test.go | 2 +- util/argo/argo.go | 2 +- util/argo/argo_test.go | 14 ++++----- util/cache/appstate/cache.go | 6 ++-- util/cache/cache_test.go | 3 +- util/cert/cert_test.go | 3 +- util/cli/cli.go | 2 +- util/dex/dex.go | 2 +- util/git/client.go | 8 ++--- util/git/client_test.go | 31 +++++++++---------- util/git/creds.go | 20 ++++++------ util/git/creds_test.go | 14 ++++----- util/git/git_test.go | 3 +- util/gpg/gpg.go | 4 +-- util/gpg/gpg_test.go | 4 +-- util/grpc/logging.go | 4 +-- util/helm/client_test.go | 8 ++--- util/kustomize/kustomize.go | 2 +- util/log/logrus_test.go | 5 ++- util/lua/custom_actions_test.go | 2 +- util/lua/lua.go | 2 +- .../expression/strings/strings_test.go | 3 +- util/notification/k8s/informers.go | 5 ++- util/oidc/oidc.go | 2 +- util/oidc/provider.go | 2 +- util/proxy/proxy.go | 7 ++--- util/rbac/rbac.go | 6 ++-- util/rbac/rbac_test.go | 3 +- util/session/sessionmanager_test.go | 4 +-- util/settings/accounts.go | 2 +- util/settings/settings.go | 2 +- util/settings/settings_test.go | 4 +-- util/tls/tls_test.go | 4 +-- util/webhook/webhook.go | 2 +- 85 files changed, 210 insertions(+), 226 deletions(-) diff --git a/.golangci.yaml b/.golangci.yaml index 5333f86b47f94..d9f482d2b7348 100644 --- a/.golangci.yaml +++ b/.golangci.yaml @@ -44,13 +44,13 @@ linters-settings: # 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 + err-error: true # Optimizes `fmt.Errorf`. errorf: false # Optimizes `fmt.Sprintf` with only one argument. sprintf1: true # Optimizes into strings concatenation. - strconcat: false + strconcat: true testifylint: enable-all: true disable: diff --git a/applicationset/generators/cluster.go b/applicationset/generators/cluster.go index 79765f7bb38e8..d7b35d1815454 100644 --- a/applicationset/generators/cluster.go +++ b/applicationset/generators/cluster.go @@ -149,11 +149,11 @@ func (g *ClusterGenerator) GenerateParams(appSetGenerator *argoappsetv1alpha1.Ap params["metadata"] = meta } else { for key, value := range cluster.ObjectMeta.Annotations { - params[fmt.Sprintf("metadata.annotations.%s", key)] = value + params["metadata.annotations."+key] = value } for key, value := range cluster.ObjectMeta.Labels { - params[fmt.Sprintf("metadata.labels.%s", key)] = value + params["metadata.labels."+key] = value } } diff --git a/applicationset/generators/duck_type.go b/applicationset/generators/duck_type.go index 7bd78a07146b2..b971f7a1e0b1b 100644 --- a/applicationset/generators/duck_type.go +++ b/applicationset/generators/duck_type.go @@ -211,7 +211,7 @@ func (g *DuckTypeGenerator) GenerateParams(appSetGenerator *argoprojiov1alpha1.A } params["values"].(map[string]string)[key] = value } else { - params[fmt.Sprintf("values.%s", key)] = value + params["values."+key] = value } } diff --git a/applicationset/generators/list.go b/applicationset/generators/list.go index fad6a6af5c6d9..5980d95e77332 100644 --- a/applicationset/generators/list.go +++ b/applicationset/generators/list.go @@ -61,7 +61,7 @@ func (g *ListGenerator) GenerateParams(appSetGenerator *argoprojiov1alpha1.Appli if !ok { return nil, fmt.Errorf("error parsing value as string %w", err) } - params[fmt.Sprintf("values.%s", k)] = value + params["values."+k] = value } } else { v, ok := value.(string) diff --git a/applicationset/generators/value_interpolation.go b/applicationset/generators/value_interpolation.go index 814843e3d899d..a87e1fab9bdb1 100644 --- a/applicationset/generators/value_interpolation.go +++ b/applicationset/generators/value_interpolation.go @@ -22,7 +22,7 @@ func appendTemplatedValues(values map[string]string, params map[string]interface } tmp["values"].(map[string]string)[key] = result } else { - tmp[fmt.Sprintf("values.%s", key)] = result + tmp["values."+key] = result } } diff --git a/applicationset/services/plugin/utils.go b/applicationset/services/plugin/utils.go index 26e38e492200d..f165107ee809f 100644 --- a/applicationset/services/plugin/utils.go +++ b/applicationset/services/plugin/utils.go @@ -1,7 +1,6 @@ package plugin import ( - "fmt" "strings" "github.com/argoproj/argo-cd/v2/common" @@ -12,7 +11,7 @@ func ParseSecretKey(key string) (secretName string, tokenKey string) { if strings.Contains(key, ":") { parts := strings.Split(key, ":") secretName = parts[0][1:] - tokenKey = fmt.Sprintf("$%s", parts[1]) + tokenKey = "$" + parts[1] } else { secretName = common.ArgoCDSecretName tokenKey = key diff --git a/applicationset/services/scm_provider/gitea.go b/applicationset/services/scm_provider/gitea.go index 500aa0e981334..9f0650f2d64f8 100644 --- a/applicationset/services/scm_provider/gitea.go +++ b/applicationset/services/scm_provider/gitea.go @@ -131,10 +131,10 @@ func (g *GiteaProvider) RepoHasPath(ctx context.Context, repo *Repository, path if resp != nil && resp.StatusCode == http.StatusNotFound { return false, nil } - if fmt.Sprint(err) == "expect file, got directory" { - return true, nil - } if err != nil { + if err.Error() == "expect file, got directory" { + return true, nil + } return false, err } return true, nil diff --git a/applicationset/webhook/webhook.go b/applicationset/webhook/webhook.go index 503017360d56e..a886cba7c47ef 100644 --- a/applicationset/webhook/webhook.go +++ b/applicationset/webhook/webhook.go @@ -179,7 +179,7 @@ func (h *WebhookHandler) Handler(w http.ResponseWriter, r *http.Request) { if r.Method != http.MethodPost { status = http.StatusMethodNotAllowed } - http.Error(w, fmt.Sprintf("Webhook processing failed: %s", html.EscapeString(err.Error())), status) + http.Error(w, "Webhook processing failed: "+html.EscapeString(err.Error()), status) return } diff --git a/cmd/argocd-application-controller/commands/argocd_application_controller.go b/cmd/argocd-application-controller/commands/argocd_application_controller.go index 83ddabe82b3ef..ec364baf5b9b7 100644 --- a/cmd/argocd-application-controller/commands/argocd_application_controller.go +++ b/cmd/argocd-application-controller/commands/argocd_application_controller.go @@ -149,8 +149,8 @@ func NewCommand() *cobra.Command { // repository server, if strict TLS validation was requested. if !repoServerPlaintext && repoServerStrictTLS { pool, err := tls.LoadX509CertPool( - fmt.Sprintf("%s/controller/tls/tls.crt", env.StringFromEnv(common.EnvAppConfigPath, common.DefaultAppConfigPath)), - fmt.Sprintf("%s/controller/tls/ca.crt", env.StringFromEnv(common.EnvAppConfigPath, common.DefaultAppConfigPath)), + env.StringFromEnv(common.EnvAppConfigPath, common.DefaultAppConfigPath)+"/controller/tls/tls.crt", + env.StringFromEnv(common.EnvAppConfigPath, common.DefaultAppConfigPath)+"/controller/tls/ca.crt", ) if err != nil { log.Fatalf("%v", err) diff --git a/cmd/argocd-applicationset-controller/commands/applicationset_controller.go b/cmd/argocd-applicationset-controller/commands/applicationset_controller.go index ce7b69c69b565..abc4d55035f72 100644 --- a/cmd/argocd-applicationset-controller/commands/applicationset_controller.go +++ b/cmd/argocd-applicationset-controller/commands/applicationset_controller.go @@ -181,8 +181,8 @@ func NewCommand() *cobra.Command { if !repoServerPlaintext && repoServerStrictTLS { pool, err := tls.LoadX509CertPool( - fmt.Sprintf("%s/reposerver/tls/tls.crt", env.StringFromEnv(common.EnvAppConfigPath, common.DefaultAppConfigPath)), - fmt.Sprintf("%s/reposerver/tls/ca.crt", env.StringFromEnv(common.EnvAppConfigPath, common.DefaultAppConfigPath)), + env.StringFromEnv(common.EnvAppConfigPath, common.DefaultAppConfigPath)+"/reposerver/tls/tls.crt", + env.StringFromEnv(common.EnvAppConfigPath, common.DefaultAppConfigPath)+"/reposerver/tls/ca.crt", ) errors.CheckError(err) tlsConfig.Certificates = pool diff --git a/cmd/argocd-notification/commands/controller.go b/cmd/argocd-notification/commands/controller.go index 6f2dcc86a569d..152dab6a078f3 100644 --- a/cmd/argocd-notification/commands/controller.go +++ b/cmd/argocd-notification/commands/controller.go @@ -129,8 +129,8 @@ func NewCommand() *cobra.Command { } if !tlsConfig.DisableTLS && tlsConfig.StrictValidation { pool, err := tls.LoadX509CertPool( - fmt.Sprintf("%s/reposerver/tls/tls.crt", env.StringFromEnv(common.EnvAppConfigPath, common.DefaultAppConfigPath)), - fmt.Sprintf("%s/reposerver/tls/ca.crt", env.StringFromEnv(common.EnvAppConfigPath, common.DefaultAppConfigPath)), + env.StringFromEnv(common.EnvAppConfigPath, common.DefaultAppConfigPath)+"/reposerver/tls/tls.crt", + env.StringFromEnv(common.EnvAppConfigPath, common.DefaultAppConfigPath)+"/reposerver/tls/ca.crt", ) if err != nil { return fmt.Errorf("failed to load repo-server certificate pool: %w", err) diff --git a/cmd/argocd-server/commands/argocd_server.go b/cmd/argocd-server/commands/argocd_server.go index 0b89dad23e853..403cfdae16633 100644 --- a/cmd/argocd-server/commands/argocd_server.go +++ b/cmd/argocd-server/commands/argocd_server.go @@ -170,8 +170,8 @@ func NewCommand() *cobra.Command { // repository server, if strict TLS validation was requested. if !repoServerPlaintext && repoServerStrictTLS { pool, err := tls.LoadX509CertPool( - fmt.Sprintf("%s/server/tls/tls.crt", env.StringFromEnv(common.EnvAppConfigPath, common.DefaultAppConfigPath)), - fmt.Sprintf("%s/server/tls/ca.crt", env.StringFromEnv(common.EnvAppConfigPath, common.DefaultAppConfigPath)), + env.StringFromEnv(common.EnvAppConfigPath, common.DefaultAppConfigPath)+"/server/tls/tls.crt", + env.StringFromEnv(common.EnvAppConfigPath, common.DefaultAppConfigPath)+"/server/tls/ca.crt", ) if err != nil { log.Fatalf("%v", err) @@ -186,14 +186,14 @@ func NewCommand() *cobra.Command { if !dexServerPlaintext && dexServerStrictTLS { pool, err := tls.LoadX509CertPool( - fmt.Sprintf("%s/dex/tls/ca.crt", env.StringFromEnv(common.EnvAppConfigPath, common.DefaultAppConfigPath)), + env.StringFromEnv(common.EnvAppConfigPath, common.DefaultAppConfigPath) + "/dex/tls/ca.crt", ) if err != nil { log.Fatalf("%v", err) } dexTlsConfig.RootCAs = pool cert, err := tls.LoadX509Cert( - fmt.Sprintf("%s/dex/tls/tls.crt", env.StringFromEnv(common.EnvAppConfigPath, common.DefaultAppConfigPath)), + env.StringFromEnv(common.EnvAppConfigPath, common.DefaultAppConfigPath) + "/dex/tls/tls.crt", ) if err != nil { log.Fatalf("%v", err) diff --git a/cmd/argocd/commands/account.go b/cmd/argocd/commands/account.go index 03fe9932ee23c..4307990f81528 100644 --- a/cmd/argocd/commands/account.go +++ b/cmd/argocd/commands/account.go @@ -358,7 +358,7 @@ func printAccountDetails(acc *accountpkg.Account) { expiresAt := time.Unix(t.ExpiresAt, 0) expiresAtFormatted = expiresAt.Format(time.RFC3339) if expiresAt.Before(time.Now()) { - expiresAtFormatted = fmt.Sprintf("%s (expired)", expiresAtFormatted) + expiresAtFormatted = expiresAtFormatted + " (expired)" } } diff --git a/cmd/argocd/commands/admin/generatespec_utils.go b/cmd/argocd/commands/admin/generatespec_utils.go index f9d902111a5d1..71d59c56da94d 100644 --- a/cmd/argocd/commands/admin/generatespec_utils.go +++ b/cmd/argocd/commands/admin/generatespec_utils.go @@ -23,7 +23,7 @@ func getOutWriter(inline bool, filePath string) (io.Writer, io.Closer, error) { return nil, nil, errors.New("The file path must be specified using flag '--file'") } - err := os.Rename(filePath, fmt.Sprintf("%s.back", filePath)) + err := os.Rename(filePath, filePath+".back") if err != nil { return nil, nil, err } diff --git a/cmd/argocd/commands/admin/generatespec_utils_test.go b/cmd/argocd/commands/admin/generatespec_utils_test.go index 9c5735df5838d..13d946d2c7478 100644 --- a/cmd/argocd/commands/admin/generatespec_utils_test.go +++ b/cmd/argocd/commands/admin/generatespec_utils_test.go @@ -2,7 +2,6 @@ package admin import ( "bytes" - "fmt" "os" "testing" @@ -25,7 +24,7 @@ func TestGetOutWriter_InlineOff(t *testing.T) { func TestGetOutWriter_InlineOn(t *testing.T) { tmpFile := t.TempDir() defer func() { - _ = os.Remove(fmt.Sprintf("%s.back", tmpFile)) + _ = os.Remove(tmpFile + ".back") }() out, closer, err := getOutWriter(true, tmpFile) @@ -33,7 +32,7 @@ func TestGetOutWriter_InlineOn(t *testing.T) { defer io.Close(closer) assert.Equal(t, tmpFile, out.(*os.File).Name()) - _, err = os.Stat(fmt.Sprintf("%s.back", tmpFile)) + _, err = os.Stat(tmpFile + ".back") require.NoError(t, err, "Back file must be created") } diff --git a/cmd/argocd/commands/admin/notifications.go b/cmd/argocd/commands/admin/notifications.go index 32ae589270938..0442e5b5f02f0 100644 --- a/cmd/argocd/commands/admin/notifications.go +++ b/cmd/argocd/commands/admin/notifications.go @@ -1,7 +1,6 @@ package admin import ( - "fmt" "log" "k8s.io/apimachinery/pkg/runtime/schema" @@ -51,8 +50,8 @@ func NewNotificationsCommand() *cobra.Command { } if !tlsConfig.DisableTLS && tlsConfig.StrictValidation { pool, err := tls.LoadX509CertPool( - fmt.Sprintf("%s/reposerver/tls/tls.crt", env.StringFromEnv(common.EnvAppConfigPath, common.DefaultAppConfigPath)), - fmt.Sprintf("%s/reposerver/tls/ca.crt", env.StringFromEnv(common.EnvAppConfigPath, common.DefaultAppConfigPath)), + env.StringFromEnv(common.EnvAppConfigPath, common.DefaultAppConfigPath)+"/reposerver/tls/tls.crt", + env.StringFromEnv(common.EnvAppConfigPath, common.DefaultAppConfigPath)+"/reposerver/tls/ca.crt", ) if err != nil { log.Fatalf("Failed to load tls certs: %v", err) diff --git a/cmd/argocd/commands/admin/settings.go b/cmd/argocd/commands/admin/settings.go index 85baf9bfd1389..78fac6ca2246d 100644 --- a/cmd/argocd/commands/admin/settings.go +++ b/cmd/argocd/commands/admin/settings.go @@ -211,7 +211,7 @@ var validatorsByGroup = map[string]settingValidator{ } var summary string if ssoProvider != "" { - summary = fmt.Sprintf("%s is configured", ssoProvider) + summary = ssoProvider + " is configured" if general.URL == "" { summary = summary + " ('url' field is missing)" } diff --git a/cmd/argocd/commands/admin/settings_test.go b/cmd/argocd/commands/admin/settings_test.go index 9ff9af5411f97..1f9af47540e6c 100644 --- a/cmd/argocd/commands/admin/settings_test.go +++ b/cmd/argocd/commands/admin/settings_test.go @@ -3,7 +3,6 @@ package admin import ( "bytes" "context" - "fmt" "io" "os" "testing" @@ -270,7 +269,7 @@ func TestValidateSettingsCommand_NoErrors(t *testing.T) { require.NoError(t, err) for k := range validatorsByGroup { - assert.Contains(t, out, fmt.Sprintf("✅ %s", k)) + assert.Contains(t, out, "✅ "+k) } } diff --git a/cmd/argocd/commands/app.go b/cmd/argocd/commands/app.go index 3cfc5f13f1d9c..50230e0bb354b 100644 --- a/cmd/argocd/commands/app.go +++ b/cmd/argocd/commands/app.go @@ -670,9 +670,9 @@ func printAppSummaryTable(app *argoappv1.Application, appURL string, windows *ar syncStatusStr := string(app.Status.Sync.Status) switch app.Status.Sync.Status { case argoappv1.SyncStatusCodeSynced: - syncStatusStr += fmt.Sprintf(" to %s", app.Spec.GetSource().TargetRevision) + syncStatusStr += " to " + app.Spec.GetSource().TargetRevision case argoappv1.SyncStatusCodeOutOfSync: - syncStatusStr += fmt.Sprintf(" from %s", app.Spec.GetSource().TargetRevision) + syncStatusStr += " from " + app.Spec.GetSource().TargetRevision } if !git.IsCommitSHA(app.Spec.GetSource().TargetRevision) && !git.IsTruncatedCommitSHA(app.Spec.GetSource().TargetRevision) && len(app.Status.Sync.Revision) > 7 { syncStatusStr += fmt.Sprintf(" (%s)", app.Status.Sync.Revision[0:7]) @@ -2054,7 +2054,7 @@ func NewApplicationSyncCommand(clientOpts *argocdclient.ClientOptions) *cobra.Co if len(list.Items) == 0 { errMsg := "No matching apps found for filter:" if selector != "" { - errMsg += fmt.Sprintf(" selector %s", selector) + errMsg += " selector " + selector } if len(projects) != 0 { errMsg += fmt.Sprintf(" projects %v", projects) @@ -3149,7 +3149,7 @@ func NewApplicationEditCommand(clientOpts *argocdclient.ClientOptions) *cobra.Co appData, err = yaml.JSONToYAML(appData) errors.CheckError(err) - cli.InteractiveEdit(fmt.Sprintf("%s-*-edit.yaml", appName), appData, func(input []byte) error { + cli.InteractiveEdit(appName+"-*-edit.yaml", appData, func(input []byte) error { input, err = yaml.YAMLToJSON(input) if err != nil { return fmt.Errorf("error converting YAML to JSON: %w", err) diff --git a/cmd/argocd/commands/cluster.go b/cmd/argocd/commands/cluster.go index 65a3981dabac8..da8447c7f9c02 100644 --- a/cmd/argocd/commands/cluster.go +++ b/cmd/argocd/commands/cluster.go @@ -88,7 +88,7 @@ func NewClusterAddCommand(clientOpts *argocdclient.ClientOptions, pathOpts *clie ) command := &cobra.Command{ Use: "add CONTEXT", - Short: fmt.Sprintf("%s cluster add CONTEXT", cliName), + Short: cliName + " cluster add CONTEXT", Run: func(c *cobra.Command, args []string) { ctx := c.Context() @@ -541,7 +541,7 @@ argocd cluster list -o server func NewClusterRotateAuthCommand(clientOpts *argocdclient.ClientOptions) *cobra.Command { command := &cobra.Command{ Use: "rotate-auth SERVER/NAME", - Short: fmt.Sprintf("%s cluster rotate-auth SERVER/NAME", cliName), + Short: cliName + " cluster rotate-auth SERVER/NAME", Example: `argocd cluster rotate-auth https://12.34.567.89 argocd cluster rotate-auth cluster-name`, Run: func(c *cobra.Command, args []string) { diff --git a/cmd/argocd/commands/headless/headless.go b/cmd/argocd/commands/headless/headless.go index 40ef90b84c7e5..c8d69b441d9f5 100644 --- a/cmd/argocd/commands/headless/headless.go +++ b/cmd/argocd/commands/headless/headless.go @@ -212,7 +212,7 @@ func MaybeStartLocalServer(ctx context.Context, clientOpts *apiclient.ClientOpti address = ptr.To("localhost") } if port == nil || *port == 0 { - addr := fmt.Sprintf("%s:0", *address) + addr := *address + ":0" ln, err := net.Listen("tcp", addr) if err != nil { return fmt.Errorf("failed to listen on %q: %w", addr, err) diff --git a/cmd/argocd/commands/project.go b/cmd/argocd/commands/project.go index b3dc9498d6b84..2eaa156414c10 100644 --- a/cmd/argocd/commands/project.go +++ b/cmd/argocd/commands/project.go @@ -1077,7 +1077,7 @@ func NewProjectEditCommand(clientOpts *argocdclient.ClientOptions) *cobra.Comman projData, err = yaml.JSONToYAML(projData) errors.CheckError(err) - cli.InteractiveEdit(fmt.Sprintf("%s-*-edit.yaml", projName), projData, func(input []byte) error { + cli.InteractiveEdit(projName+"-*-edit.yaml", projData, func(input []byte) error { input, err = yaml.YAMLToJSON(input) if err != nil { return fmt.Errorf("error converting YAML to JSON: %w", err) diff --git a/common/common_test.go b/common/common_test.go index 5fc8faf2a2618..7ceb42f5e8605 100644 --- a/common/common_test.go +++ b/common/common_test.go @@ -72,7 +72,7 @@ func TestSetOptionalRedisPasswordFromKubeConfig(t *testing.T) { name: "Secret does not exist", namespace: "default", expectedPassword: "", - expectedErr: fmt.Sprintf("failed to get secret default/%s", RedisInitialCredentials), + expectedErr: "failed to get secret default/" + RedisInitialCredentials, secret: nil, }, { diff --git a/controller/hydrator/hydrator.go b/controller/hydrator/hydrator.go index 6d1fe10ffc7cd..5b37374b3af1a 100644 --- a/controller/hydrator/hydrator.go +++ b/controller/hydrator/hydrator.go @@ -304,7 +304,7 @@ func (h *Hydrator) hydrate(logCtx *log.Entry, apps []*appv1.Application) (string SyncBranch: syncBranch, TargetBranch: targetBranch, DrySha: targetRevision, - CommitMessage: fmt.Sprintf("[Argo CD Bot] hydrate %s", targetRevision), + CommitMessage: "[Argo CD Bot] hydrate " + targetRevision, Paths: paths, } diff --git a/controller/state.go b/controller/state.go index a120158b802bf..f9b8628d89d29 100644 --- a/controller/state.go +++ b/controller/state.go @@ -534,7 +534,7 @@ func (m *appStateManager) CompareAppState(app *v1alpha1.Application, project *v1 targetObjs, manifestInfos, revisionUpdated, err = m.GetRepoObjs(app, sources, appLabelKey, revisions, noCache, noRevisionCache, verifySignature, project, rollback, true) if err != nil { targetObjs = make([]*unstructured.Unstructured, 0) - msg := fmt.Sprintf("Failed to load target state: %s", err.Error()) + msg := "Failed to load target state: " + err.Error() conditions = append(conditions, v1alpha1.ApplicationCondition{Type: v1alpha1.ApplicationConditionComparisonError, Message: msg, LastTransitionTime: &now}) if firstSeen, ok := m.repoErrorCache.Load(app.Name); ok { if time.Since(firstSeen.(time.Time)) <= m.repoErrorGracePeriod && !noRevisionCache { @@ -564,7 +564,7 @@ func (m *appStateManager) CompareAppState(app *v1alpha1.Application, project *v1 targetObjs, err = unmarshalManifests(localManifests) if err != nil { targetObjs = make([]*unstructured.Unstructured, 0) - msg := fmt.Sprintf("Failed to load local manifests: %s", err.Error()) + msg := "Failed to load local manifests: " + err.Error() conditions = append(conditions, v1alpha1.ApplicationCondition{Type: v1alpha1.ApplicationConditionComparisonError, Message: msg, LastTransitionTime: &now}) failedToLoadObjs = true } @@ -581,7 +581,7 @@ func (m *appStateManager) CompareAppState(app *v1alpha1.Application, project *v1 } targetObjs, dedupConditions, err := DeduplicateTargetObjects(app.Spec.Destination.Namespace, targetObjs, infoProvider) if err != nil { - msg := fmt.Sprintf("Failed to deduplicate target state: %s", err.Error()) + msg := "Failed to deduplicate target state: " + err.Error() conditions = append(conditions, v1alpha1.ApplicationCondition{Type: v1alpha1.ApplicationConditionComparisonError, Message: msg, LastTransitionTime: &now}) } conditions = append(conditions, dedupConditions...) @@ -609,7 +609,7 @@ func (m *appStateManager) CompareAppState(app *v1alpha1.Application, project *v1 liveObjByKey, err := m.liveStateCache.GetManagedLiveObjs(app, targetObjs) if err != nil { liveObjByKey = make(map[kubeutil.ResourceKey]*unstructured.Unstructured) - msg := fmt.Sprintf("Failed to load live state: %s", err.Error()) + msg := "Failed to load live state: " + err.Error() conditions = append(conditions, v1alpha1.ApplicationCondition{Type: v1alpha1.ApplicationConditionComparisonError, Message: msg, LastTransitionTime: &now}) failedToLoadObjs = true } @@ -761,7 +761,7 @@ func (m *appStateManager) CompareAppState(app *v1alpha1.Application, project *v1 if err != nil { diffResults = &diff.DiffResultList{} failedToLoadObjs = true - msg := fmt.Sprintf("Failed to compare desired state to live state: %s", err.Error()) + msg := "Failed to compare desired state to live state: " + err.Error() conditions = append(conditions, v1alpha1.ApplicationCondition{Type: v1alpha1.ApplicationConditionComparisonError, Message: msg, LastTransitionTime: &now}) } ts.AddCheckpoint("diff_ms") @@ -903,7 +903,7 @@ func (m *appStateManager) CompareAppState(app *v1alpha1.Application, project *v1 healthStatus, err := setApplicationHealth(managedResources, resourceSummaries, resourceOverrides, app, m.persistResourceHealth) if err != nil { - conditions = append(conditions, v1alpha1.ApplicationCondition{Type: v1alpha1.ApplicationConditionComparisonError, Message: fmt.Sprintf("error setting app health: %s", err.Error()), LastTransitionTime: &now}) + conditions = append(conditions, v1alpha1.ApplicationCondition{Type: v1alpha1.ApplicationConditionComparisonError, Message: "error setting app health: " + err.Error(), LastTransitionTime: &now}) } // Git has already performed the signature verification via its GPG interface, and the result is available diff --git a/controller/sync.go b/controller/sync.go index dcbb768a79be8..fc1aeb19246e5 100644 --- a/controller/sync.go +++ b/controller/sync.go @@ -117,7 +117,7 @@ func (m *appStateManager) SyncAppState(app *v1alpha1.Application, state *v1alpha if syncOp.SyncOptions.HasOption("FailOnSharedResource=true") && hasSharedResource { state.Phase = common.OperationFailed - state.Message = fmt.Sprintf("Shared resource found: %s", sharedResourceMessage) + state.Message = "Shared resource found: " + sharedResourceMessage return } @@ -625,7 +625,7 @@ func deriveServiceAccountToImpersonate(project *v1alpha1.AppProject, application return "", fmt.Errorf("default service account contains invalid chars '%s'", item.DefaultServiceAccount) } else if strings.Contains(item.DefaultServiceAccount, ":") { // service account is specified along with its namespace. - return fmt.Sprintf("system:serviceaccount:%s", item.DefaultServiceAccount), nil + return "system:serviceaccount:" + item.DefaultServiceAccount, nil } else { // service account needs to be prefixed with a namespace return fmt.Sprintf("system:serviceaccount:%s:%s", serviceAccountNamespace, item.DefaultServiceAccount), nil diff --git a/hack/gen-catalog/main.go b/hack/gen-catalog/main.go index c7963dbf83ab4..962ecc6a7e8c6 100644 --- a/hack/gen-catalog/main.go +++ b/hack/gen-catalog/main.go @@ -68,14 +68,14 @@ func newCatalogCommand() *cobra.Command { trigger := triggers[name] t, err := yaml.Marshal(trigger) dieOnError(err, "Failed to marshal trigger") - cm.Data[fmt.Sprintf("trigger.%s", name)] = string(t) + cm.Data["trigger."+name] = string(t) }) misc.IterateStringKeyMap(templates, func(name string) { template := templates[name] t, err := yaml.Marshal(template) dieOnError(err, "Failed to marshal template") - cm.Data[fmt.Sprintf("template.%s", name)] = string(t) + cm.Data["template."+name] = string(t) }) d, err := yaml.Marshal(cm) diff --git a/hack/k8s/main.go b/hack/k8s/main.go index 99a9ca2deb84c..8228485bb2cd3 100644 --- a/hack/k8s/main.go +++ b/hack/k8s/main.go @@ -2,7 +2,6 @@ package main import ( "context" - "fmt" "os" "os/exec" "path/filepath" @@ -29,7 +28,7 @@ func main() { kubeConfigPath = os.Args[1] } - println(fmt.Sprintf("Kubeconfig is available at %s", kubeConfigPath)) + println("Kubeconfig is available at " + kubeConfigPath) errors.CheckError(kube.WriteKubeConfig(cfg, "default", kubeConfigPath)) client, err := kubernetes.NewForConfig(cfg) errors.CheckError(err) @@ -46,7 +45,7 @@ func main() { errors.CheckError(err) cmd := exec.Command("kubectl", "apply", "-k", "manifests/base/config") - cmd.Env = []string{fmt.Sprintf("KUBECONFIG=%s", kubeConfigPath)} + cmd.Env = []string{"KUBECONFIG=" + kubeConfigPath} errors.CheckError(cmd.Run()) <-context.Background().Done() } diff --git a/pkg/apis/application/v1alpha1/types.go b/pkg/apis/application/v1alpha1/types.go index 5e7e99960c54d..2c57c60d58b19 100644 --- a/pkg/apis/application/v1alpha1/types.go +++ b/pkg/apis/application/v1alpha1/types.go @@ -1009,12 +1009,12 @@ func (p ApplicationSourcePluginParameters) Environ() ([]string, error) { if err != nil { return nil, fmt.Errorf("failed to marshal plugin parameters: %w", err) } - jsonParam := fmt.Sprintf("ARGOCD_APP_PARAMETERS=%s", string(out)) + jsonParam := "ARGOCD_APP_PARAMETERS=" + string(out) env := []string{jsonParam} for _, param := range p { - envBaseName := fmt.Sprintf("PARAM_%s", escaped(param.Name)) + envBaseName := "PARAM_" + escaped(param.Name) if param.String_ != nil { env = append(env, fmt.Sprintf("%s=%s", envBaseName, *param.String_)) } diff --git a/reposerver/cache/cache.go b/reposerver/cache/cache.go index cdc16ea4ebb82..1fa9eb1c0fe2d 100644 --- a/reposerver/cache/cache.go +++ b/reposerver/cache/cache.go @@ -162,7 +162,7 @@ func (c *Cache) SetApps(repoUrl, revision string, apps map[string]string) error } func helmIndexRefsKey(repo string) string { - return fmt.Sprintf("helm-index|%s", repo) + return "helm-index|" + repo } // SetHelmIndex stores helm repository index.yaml content to cache @@ -183,7 +183,7 @@ func (c *Cache) GetHelmIndex(repo string, indexData *[]byte) error { } func gitRefsKey(repo string) string { - return fmt.Sprintf("git-refs|%s", repo) + return "git-refs|" + repo } // SetGitReferences saves resolved Git repository references to cache diff --git a/reposerver/cache/cache_test.go b/reposerver/cache/cache_test.go index 23cbe995f06aa..f8279693c2afb 100644 --- a/reposerver/cache/cache_test.go +++ b/reposerver/cache/cache_test.go @@ -3,7 +3,6 @@ package cache import ( "encoding/json" "errors" - "fmt" "testing" "time" @@ -419,7 +418,7 @@ func TestTryLockGitRefCache_OwnershipFlows(t *testing.T) { fixtures.mockCache.AssertCacheCalledTimes(t, &mocks.CacheCallCounts{ExternalSets: 1, ExternalGets: 1}) require.NoError(t, err) var output [][2]string - key := fmt.Sprintf("git-refs|%s", "my-repo-url") + key := "git-refs|" + "my-repo-url" err = utilCache.GetItem(key, &output) fixtures.mockCache.AssertCacheCalledTimes(t, &mocks.CacheCallCounts{ExternalSets: 1, ExternalGets: 2}) require.NoError(t, err) diff --git a/reposerver/repository/repository.go b/reposerver/repository/repository.go index 11bc154d4f69c..5efc3876d5475 100644 --- a/reposerver/repository/repository.go +++ b/reposerver/repository/repository.go @@ -2246,10 +2246,10 @@ func populatePluginAppDetails(ctx context.Context, res *apiclient.RepoAppDetails res.Plugin = &apiclient.PluginAppSpec{} envVars := []string{ - fmt.Sprintf("ARGOCD_APP_NAME=%s", q.AppName), - fmt.Sprintf("ARGOCD_APP_SOURCE_REPO_URL=%s", q.Repo.Repo), - fmt.Sprintf("ARGOCD_APP_SOURCE_PATH=%s", q.Source.Path), - fmt.Sprintf("ARGOCD_APP_SOURCE_TARGET_REVISION=%s", q.Source.TargetRevision), + "ARGOCD_APP_NAME=" + q.AppName, + "ARGOCD_APP_SOURCE_REPO_URL=" + q.Repo.Repo, + "ARGOCD_APP_SOURCE_PATH=" + q.Source.Path, + "ARGOCD_APP_SOURCE_TARGET_REVISION=" + q.Source.TargetRevision, } env, err := getPluginParamEnvs(envVars, q.Source.Plugin) @@ -2351,7 +2351,7 @@ func (s *Service) GetRevisionMetadata(ctx context.Context, q *apiclient.RepoServ if cs != "" { vr := gpg.ParseGitCommitVerification(cs) if vr.Result == gpg.VerifyResultUnknown { - signatureInfo = fmt.Sprintf("UNKNOWN signature: %s", vr.Message) + signatureInfo = "UNKNOWN signature: " + vr.Message } else { signatureInfo = fmt.Sprintf("%s signature from %s key %s", vr.Result, vr.Cipher, gpg.KeyID(vr.KeyID)) } diff --git a/reposerver/repository/repository_test.go b/reposerver/repository/repository_test.go index d85e501e05d42..e15fc11903e78 100644 --- a/reposerver/repository/repository_test.go +++ b/reposerver/repository/repository_test.go @@ -363,8 +363,8 @@ func TestGenerateManifests_EmptyCache(t *testing.T) { func TestGenerateManifest_RefOnlyShortCircuit(t *testing.T) { lsremoteCalled := false dir := t.TempDir() - repopath := fmt.Sprintf("%s/tmprepo", dir) - repoRemote := fmt.Sprintf("file://%s", repopath) + repopath := dir + "/tmprepo" + repoRemote := "file://" + repopath cacheMocks := newCacheMocks() t.Cleanup(cacheMocks.mockCache.StopRedisCallback) service := NewService(metrics.NewMetricsServer(), cacheMocks.cache, RepoServerInitConstants{ParallelismLimit: 1}, argo.NewResourceTracking(), &git.NoopCredsStore{}, repopath) @@ -411,14 +411,14 @@ func TestGenerateManifest_RefOnlyShortCircuit(t *testing.T) { }) assert.True(t, lsremoteCalled, "ls-remote should be called when the source is ref only") var revisions [][2]string - require.NoError(t, cacheMocks.cacheutilCache.GetItem(fmt.Sprintf("git-refs|%s", repoRemote), &revisions)) + require.NoError(t, cacheMocks.cacheutilCache.GetItem("git-refs|"+repoRemote, &revisions)) assert.ElementsMatch(t, [][2]string{{"refs/heads/main", revision}, {"HEAD", "ref: refs/heads/main"}}, revisions) } // Test that calling manifest generation on source helm reference helm files that when the revision is cached it does not call ls-remote func TestGenerateManifestsHelmWithRefs_CachedNoLsRemote(t *testing.T) { dir := t.TempDir() - repopath := fmt.Sprintf("%s/tmprepo", dir) + repopath := dir + "/tmprepo" cacheMocks := newCacheMocks() t.Cleanup(func() { cacheMocks.mockCache.StopRedisCallback() @@ -446,7 +446,7 @@ func TestGenerateManifestsHelmWithRefs_CachedNoLsRemote(t *testing.T) { gitClient, err = git.NewClientExt(rawRepoURL, root, creds, insecure, enableLfs, proxy, noProxy, opts...) return gitClient, err } - repoRemote := fmt.Sprintf("file://%s", repopath) + repoRemote := "file://" + repopath revision := initGitRepo(t, newGitRepoOptions{ path: repopath, createPath: true, @@ -472,7 +472,7 @@ func TestGenerateManifestsHelmWithRefs_CachedNoLsRemote(t *testing.T) { ProjectSourceRepos: []string{"*"}, RefSources: map[string]*argoappv1.RefTarget{"$ref": {TargetRevision: "HEAD", Repo: *repo}}, } - err = cacheMocks.cacheutilCache.SetItem(fmt.Sprintf("git-refs|%s", repoRemote), [][2]string{{"HEAD", revision}}, nil) + err = cacheMocks.cacheutilCache.SetItem("git-refs|"+repoRemote, [][2]string{{"HEAD", revision}}, nil) require.NoError(t, err) _, err = service.GenerateManifest(context.Background(), &q) require.NoError(t, err) @@ -1142,7 +1142,7 @@ func TestHelmWithMissingValueFiles(t *testing.T) { // Should fail since we're passing a non-existent values file, and error should indicate that _, err := service.GenerateManifest(context.Background(), req) - require.ErrorContains(t, err, fmt.Sprintf("%s: no such file or directory", missingValuesFile)) + require.ErrorContains(t, err, missingValuesFile+": no such file or directory") // Should template without error even if defining a non-existent values file req.ApplicationSource.Helm.IgnoreMissingValueFiles = true @@ -3913,7 +3913,7 @@ func TestGetRefs_CacheWithLockDisabled(t *testing.T) { wg.Add(1) go func() { defer wg.Done() - client, err := git.NewClient(fmt.Sprintf("file://%s", dir), git.NopCreds{}, true, false, "", "", git.WithCache(cacheMocks.cache, true)) + client, err := git.NewClient("file://"+dir, git.NopCreds{}, true, false, "", "", git.WithCache(cacheMocks.cache, true)) require.NoError(t, err) refs, err := client.LsRefs() require.NoError(t, err) @@ -3940,7 +3940,7 @@ func TestGetRefs_CacheDisabled(t *testing.T) { }) cacheMocks := newCacheMocks() t.Cleanup(cacheMocks.mockCache.StopRedisCallback) - client, err := git.NewClient(fmt.Sprintf("file://%s", dir), git.NopCreds{}, true, false, "", "", git.WithCache(cacheMocks.cache, false)) + client, err := git.NewClient("file://"+dir, git.NopCreds{}, true, false, "", "", git.WithCache(cacheMocks.cache, false)) require.NoError(t, err) refs, err := client.LsRefs() require.NoError(t, err) @@ -3969,7 +3969,7 @@ func TestGetRefs_CacheWithLock(t *testing.T) { wg.Add(1) go func() { defer wg.Done() - client, err := git.NewClient(fmt.Sprintf("file://%s", dir), git.NopCreds{}, true, false, "", "", git.WithCache(cacheMocks.cache, true)) + client, err := git.NewClient("file://"+dir, git.NopCreds{}, true, false, "", "", git.WithCache(cacheMocks.cache, true)) require.NoError(t, err) refs, err := client.LsRefs() require.NoError(t, err) @@ -3997,7 +3997,7 @@ func TestGetRefs_CacheUnlockedOnUpdateFailed(t *testing.T) { }) cacheMocks := newCacheMocks() t.Cleanup(cacheMocks.mockCache.StopRedisCallback) - repoUrl := fmt.Sprintf("file://%s", dir) + repoUrl := "file://" + dir client, err := git.NewClient(repoUrl, git.NopCreds{}, true, false, "", "", git.WithCache(cacheMocks.cache, true)) require.NoError(t, err) refs, err := client.LsRefs() @@ -4026,7 +4026,7 @@ func TestGetRefs_CacheLockTryLockGitRefCacheError(t *testing.T) { }) cacheMocks := newCacheMocks() t.Cleanup(cacheMocks.mockCache.StopRedisCallback) - repoUrl := fmt.Sprintf("file://%s", dir) + repoUrl := "file://" + dir // buf := bytes.Buffer{} // log.SetOutput(&buf) client, err := git.NewClient(repoUrl, git.NopCreds{}, true, false, "", "", git.WithCache(cacheMocks.cache, true)) @@ -4042,7 +4042,7 @@ func TestGetRevisionChartDetails(t *testing.T) { service := newService(t, root) _, err := service.GetRevisionChartDetails(context.Background(), &apiclient.RepoServerRevisionChartDetailsRequest{ Repo: &v1alpha1.Repository{ - Repo: fmt.Sprintf("file://%s", root), + Repo: "file://" + root, Name: "test-repo-name", Type: "helm", }, @@ -4055,7 +4055,7 @@ func TestGetRevisionChartDetails(t *testing.T) { t.Run("Test GetRevisionChartDetails", func(t *testing.T) { root := t.TempDir() service := newService(t, root) - repoUrl := fmt.Sprintf("file://%s", root) + repoUrl := "file://" + root err := service.cache.SetRevisionChartDetails(repoUrl, "my-chart", "1.1.0", &argoappv1.ChartDetails{ Description: "test-description", Home: "test-home", @@ -4064,7 +4064,7 @@ func TestGetRevisionChartDetails(t *testing.T) { require.NoError(t, err) chartDetails, err := service.GetRevisionChartDetails(context.Background(), &apiclient.RepoServerRevisionChartDetailsRequest{ Repo: &v1alpha1.Repository{ - Repo: fmt.Sprintf("file://%s", root), + Repo: "file://" + root, Name: "test-repo-name", Type: "helm", }, diff --git a/reposerver/server.go b/reposerver/server.go index 5d280329deed3..56ed69b99b06a 100644 --- a/reposerver/server.go +++ b/reposerver/server.go @@ -55,8 +55,8 @@ func NewServer(metricsServer *metrics.MetricsServer, cache *reposervercache.Cach // repository server. if tlsConfCustomizer != nil { var err error - certPath := fmt.Sprintf("%s/reposerver/tls/tls.crt", env.StringFromEnv(common.EnvAppConfigPath, common.DefaultAppConfigPath)) - keyPath := fmt.Sprintf("%s/reposerver/tls/tls.key", env.StringFromEnv(common.EnvAppConfigPath, common.DefaultAppConfigPath)) + certPath := env.StringFromEnv(common.EnvAppConfigPath, common.DefaultAppConfigPath) + "/reposerver/tls/tls.crt" + keyPath := env.StringFromEnv(common.EnvAppConfigPath, common.DefaultAppConfigPath) + "/reposerver/tls/tls.key" tlsConfig, err = tlsutil.CreateServerTLSConfig(certPath, keyPath, tlsHostList) if err != nil { return nil, fmt.Errorf("error creating server TLS config: %w", err) diff --git a/server/application/application.go b/server/application/application.go index 9fee8369795b1..7ffbca4f886d2 100644 --- a/server/application/application.go +++ b/server/application/application.go @@ -2520,10 +2520,10 @@ func (s *Server) RunResourceAction(ctx context.Context, q *application.ResourceA } if res == nil { - s.logAppEvent(a, ctx, argo.EventReasonResourceActionRan, fmt.Sprintf("ran action %s", q.GetAction())) + s.logAppEvent(a, ctx, argo.EventReasonResourceActionRan, "ran action "+q.GetAction()) } else { s.logAppEvent(a, ctx, argo.EventReasonResourceActionRan, fmt.Sprintf("ran action %s on resource %s/%s/%s", q.GetAction(), res.Group, res.Kind, res.Name)) - s.logResourceEvent(res, ctx, argo.EventReasonResourceActionRan, fmt.Sprintf("ran action %s", q.GetAction())) + s.logResourceEvent(res, ctx, argo.EventReasonResourceActionRan, "ran action "+q.GetAction()) } return &application.ApplicationResponse{}, nil } diff --git a/server/extension/extension.go b/server/extension/extension.go index d28d3aac5dc9f..f7506692d7ebb 100644 --- a/server/extension/extension.go +++ b/server/extension/extension.go @@ -729,7 +729,7 @@ func (m *Manager) CallExtension() func(http.ResponseWriter, *http.Request) { return func(w http.ResponseWriter, r *http.Request) { segments := strings.Split(strings.TrimPrefix(r.URL.Path, "/"), "/") if segments[0] != "extensions" { - http.Error(w, fmt.Sprintf("Invalid URL: first segment must be %s", URLPrefix), http.StatusBadRequest) + http.Error(w, "Invalid URL: first segment must be "+URLPrefix, http.StatusBadRequest) return } extName := segments[1] diff --git a/server/extension/extension_test.go b/server/extension/extension_test.go index 3a92fcfeffb8f..9e42386481fb2 100644 --- a/server/extension/extension_test.go +++ b/server/extension/extension_test.go @@ -258,7 +258,7 @@ func TestCallExtension(t *testing.T) { mux := http.NewServeMux() extHandler := http.HandlerFunc(m.CallExtension()) - mux.Handle(fmt.Sprintf("%s/", extension.URLPrefix), extHandler) + mux.Handle(extension.URLPrefix+"/", extHandler) return &fixture{ mux: mux, @@ -713,7 +713,7 @@ func TestCallExtension(t *testing.T) { withUser(f, "some-user", []string{"group1", "group2"}) ts := startTestServer(t, f) defer ts.Close() - r := newExtensionRequest(t, "Get", fmt.Sprintf("%s/extensions/", ts.URL)) + r := newExtensionRequest(t, "Get", ts.URL+"/extensions/") f.appGetterMock.On("Get", mock.Anything, mock.Anything).Return(getApp("", "", differentProject), nil) // when diff --git a/server/logout/logout.go b/server/logout/logout.go index 6129e2f9a85be..e94424bc7035a 100644 --- a/server/logout/logout.go +++ b/server/logout/logout.go @@ -2,7 +2,6 @@ package logout import ( "context" - "fmt" "net/http" "regexp" "strings" @@ -61,7 +60,7 @@ func (h *Handler) ServeHTTP(w http.ResponseWriter, r *http.Request) { argoCDSettings, err := h.settingsMgr.GetSettings() if err != nil { w.WriteHeader(http.StatusInternalServerError) - http.Error(w, "Failed to retrieve argoCD settings: "+fmt.Sprintf("%s", err), http.StatusInternalServerError) + http.Error(w, "Failed to retrieve argoCD settings: "+err.Error(), http.StatusInternalServerError) return } @@ -73,7 +72,7 @@ func (h *Handler) ServeHTTP(w http.ResponseWriter, r *http.Request) { // golang does not provide any easy way to determine scheme of current request // so redirecting ot http which will auto-redirect too https if necessary host := strings.TrimRight(r.Host, "/") - argoURL = fmt.Sprintf("http://%s", host) + "/" + strings.TrimRight(strings.TrimLeft(h.rootPath, "/"), "/") + argoURL = "http://" + host + "/" + strings.TrimRight(strings.TrimLeft(h.rootPath, "/"), "/") } logoutRedirectURL := strings.TrimRight(strings.TrimLeft(argoURL, "/"), "/") @@ -82,7 +81,7 @@ func (h *Handler) ServeHTTP(w http.ResponseWriter, r *http.Request) { tokenString, err = httputil.JoinCookies(common.AuthCookieName, cookies) if tokenString == "" || err != nil { w.WriteHeader(http.StatusBadRequest) - http.Error(w, "Failed to retrieve ArgoCD auth token: "+fmt.Sprintf("%s", err), http.StatusBadRequest) + http.Error(w, "Failed to retrieve ArgoCD auth token: "+err.Error(), http.StatusBadRequest) return } @@ -96,7 +95,7 @@ func (h *Handler) ServeHTTP(w http.ResponseWriter, r *http.Request) { Value: "", } - argocdCookie.Path = fmt.Sprintf("/%s", strings.TrimRight(strings.TrimLeft(h.baseHRef, "/"), "/")) + argocdCookie.Path = "/" + strings.TrimRight(strings.TrimLeft(h.baseHRef, "/"), "/") w.Header().Add("Set-Cookie", argocdCookie.String()) } diff --git a/server/server.go b/server/server.go index 91007bfd34333..29c7da2ab1552 100644 --- a/server/server.go +++ b/server/server.go @@ -153,7 +153,7 @@ var backoff = wait.Backoff{ } var ( - clientConstraint = fmt.Sprintf(">= %s", common.MinClientVersion) + clientConstraint = ">= " + common.MinClientVersion baseHRefRegex = regexp.MustCompile(``) // limits number of concurrent login requests to prevent password brute forcing. If set to 0 then no limit is enforced. maxConcurrentLoginRequestsCount = 50 @@ -1102,7 +1102,7 @@ func (a *ArgoCDServer) translateGrpcCookieHeader(ctx context.Context, w http.Res } func (a *ArgoCDServer) setTokenCookie(token string, w http.ResponseWriter) error { - cookiePath := fmt.Sprintf("path=/%s", strings.TrimRight(strings.TrimLeft(a.ArgoCDServerOpts.BaseHRef, "/"), "/")) + cookiePath := "path=/" + strings.TrimRight(strings.TrimLeft(a.ArgoCDServerOpts.BaseHRef, "/"), "/") flags := []string{cookiePath, "SameSite=lax", "httpOnly"} if !a.Insecure { flags = append(flags, "Secure") @@ -1268,7 +1268,7 @@ func registerExtensions(mux *http.ServeMux, a *ArgoCDServer, metricsReg HTTPMetr extHandler := http.HandlerFunc(a.extensionManager.CallExtension()) authMiddleware := a.sessionMgr.AuthMiddlewareFunc(a.DisableAuth) // auth middleware ensures that requests to all extensions are authenticated first - mux.Handle(fmt.Sprintf("%s/", extension.URLPrefix), authMiddleware(extHandler)) + mux.Handle(extension.URLPrefix+"/", authMiddleware(extHandler)) a.extensionManager.AddMetricsRegistry(metricsReg) diff --git a/server/server_norace_test.go b/server/server_norace_test.go index cd73a54f12c41..5dbebd88c6da7 100644 --- a/server/server_norace_test.go +++ b/server/server_norace_test.go @@ -50,7 +50,7 @@ func TestUserAgent(t *testing.T) { tests := []testData{ { // Reject out-of-date user-agent - userAgent: fmt.Sprintf("%s/0.10.0", common.ArgoCDUserAgentName), + userAgent: common.ArgoCDUserAgentName + "/0.10.0", errorMsg: "unsatisfied client version constraint", }, { diff --git a/server/server_test.go b/server/server_test.go index 87a782b0fe245..02bab631ef664 100644 --- a/server/server_test.go +++ b/server/server_test.go @@ -903,7 +903,7 @@ func TestAuthenticate_3rd_party_JWTs(t *testing.T) { argocd, oidcURL := getTestServer(t, testDataCopy.anonymousEnabled, true, testDataCopy.useDex, settings_util.OIDCConfig{}) if testDataCopy.useDex { - testDataCopy.claims.Issuer = fmt.Sprintf("%s/api/dex", oidcURL) + testDataCopy.claims.Issuer = oidcURL + "/api/dex" } else { testDataCopy.claims.Issuer = oidcURL } @@ -1003,7 +1003,7 @@ func TestAuthenticate_no_SSO(t *testing.T) { ctx := context.Background() //nolint:ineffassign,staticcheck argocd, dexURL := getTestServer(t, testDataCopy.anonymousEnabled, false, true, settings_util.OIDCConfig{}) - token := jwt.NewWithClaims(jwt.SigningMethodHS256, jwt.RegisteredClaims{Issuer: fmt.Sprintf("%s/api/dex", dexURL)}) + token := jwt.NewWithClaims(jwt.SigningMethodHS256, jwt.RegisteredClaims{Issuer: dexURL + "/api/dex"}) tokenString, err := token.SignedString([]byte("key")) require.NoError(t, err) ctx = metadata.NewIncomingContext(context.Background(), metadata.Pairs(apiclient.MetaDataTokenKey, tokenString)) @@ -1460,7 +1460,7 @@ func TestCacheControlHeaders(t *testing.T) { handler := argocd.newStaticAssetsHandler() rr := httptest.NewRecorder() - req := httptest.NewRequest("", fmt.Sprintf("/%s", testCase.filename), nil) + req := httptest.NewRequest("", "/"+testCase.filename, nil) fp := filepath.Join(argocd.TmpAssetsDir, testCase.filename) diff --git a/test/e2e/app_management_ns_test.go b/test/e2e/app_management_ns_test.go index 328d252f66703..217d7e8559e57 100644 --- a/test/e2e/app_management_ns_test.go +++ b/test/e2e/app_management_ns_test.go @@ -967,7 +967,7 @@ func TestNamespacedSyncResourceByLabel(t *testing.T) { Sync(). Then(). And(func(app *Application) { - _, _ = RunCli("app", "sync", ctx.AppQualifiedName(), "--label", fmt.Sprintf("app.kubernetes.io/instance=%s", app.Name)) + _, _ = RunCli("app", "sync", ctx.AppQualifiedName(), "--label", "app.kubernetes.io/instance="+app.Name) }). Expect(SyncStatusIs(SyncStatusCodeSynced)). And(func(app *Application) { @@ -1116,7 +1116,7 @@ func assertNSResourceActions(t *testing.T, appName string, successful bool) { _, err = logs.Recv() assertError(err, "EOF") - expectedError := fmt.Sprintf("Deployment apps guestbook-ui not found as part of application %s", appName) + expectedError := "Deployment apps guestbook-ui not found as part of application " + appName _, err = cdClient.ListResourceEvents(context.Background(), &applicationpkg.ApplicationResourceEventsQuery{ Name: &appName, diff --git a/test/e2e/app_management_test.go b/test/e2e/app_management_test.go index 3b471bc304718..db4272b823bc0 100644 --- a/test/e2e/app_management_test.go +++ b/test/e2e/app_management_test.go @@ -1319,7 +1319,7 @@ func TestSyncResourceByLabel(t *testing.T) { Sync(). Then(). And(func(app *Application) { - _, _ = RunCli("app", "sync", app.Name, "--label", fmt.Sprintf("app.kubernetes.io/instance=%s", app.Name)) + _, _ = RunCli("app", "sync", app.Name, "--label", "app.kubernetes.io/instance="+app.Name) }). Expect(SyncStatusIs(SyncStatusCodeSynced)). And(func(app *Application) { @@ -1473,7 +1473,7 @@ func assertResourceActions(t *testing.T, appName string, successful bool) { _, err = logs.Recv() assertError(err, "EOF") - expectedError := fmt.Sprintf("Deployment apps guestbook-ui not found as part of application %s", appName) + expectedError := "Deployment apps guestbook-ui not found as part of application " + appName _, err = cdClient.ListResourceEvents(context.Background(), &applicationpkg.ApplicationResourceEventsQuery{ Name: &appName, diff --git a/test/e2e/cluster_test.go b/test/e2e/cluster_test.go index eab0d49f6aeea..a79772614580f 100644 --- a/test/e2e/cluster_test.go +++ b/test/e2e/cluster_test.go @@ -213,7 +213,7 @@ func TestClusterURLInRestAPI(t *testing.T) { clusterURL := url.QueryEscape(KubernetesInternalAPIServerAddr) var cluster Cluster - err := DoHttpJsonRequest("GET", fmt.Sprintf("/api/v1/clusters/%s", clusterURL), &cluster) + err := DoHttpJsonRequest("GET", "/api/v1/clusters/"+clusterURL, &cluster) require.NoError(t, err) assert.Equal(t, "in-cluster", cluster.Name) diff --git a/test/e2e/fixture/app/actions.go b/test/e2e/fixture/app/actions.go index ee623f73d424f..9a61f81b5f613 100644 --- a/test/e2e/fixture/app/actions.go +++ b/test/e2e/fixture/app/actions.go @@ -455,13 +455,13 @@ func (a *Actions) Delete(cascade bool) *Actions { func (a *Actions) DeleteBySelector(selector string) *Actions { a.context.t.Helper() - a.runCli("app", "delete", fmt.Sprintf("--selector=%s", selector), "--yes") + a.runCli("app", "delete", "--selector="+selector, "--yes") return a } func (a *Actions) DeleteBySelectorWithWait(selector string) *Actions { a.context.t.Helper() - a.runCli("app", "delete", fmt.Sprintf("--selector=%s", selector), "--yes", "--wait") + a.runCli("app", "delete", "--selector="+selector, "--yes", "--wait") return a } diff --git a/test/e2e/fixture/app/expectation.go b/test/e2e/fixture/app/expectation.go index b5e83a664085c..06b547aade3fd 100644 --- a/test/e2e/fixture/app/expectation.go +++ b/test/e2e/fixture/app/expectation.go @@ -112,7 +112,7 @@ func Namespace(name string, block func(app *Application, ns *v1.Namespace)) Expe return func(c *Consequences) (state, string) { ns, err := namespace(name) if err != nil { - return failed, fmt.Sprintf("namespace not found %s", err.Error()) + return failed, "namespace not found " + err.Error() } block(c.app(), ns) @@ -288,7 +288,7 @@ func NoNamespace(name string) Expectation { return succeeded, "namespace not found" } - return failed, fmt.Sprintf("found namespace %s", name) + return failed, "found namespace " + name } } diff --git a/test/e2e/fixture/fixture.go b/test/e2e/fixture/fixture.go index 03863a5ef53a0..d26d2e73b7a35 100644 --- a/test/e2e/fixture/fixture.go +++ b/test/e2e/fixture/fixture.go @@ -342,7 +342,7 @@ func RepoURL(urlType RepoURLType) string { case RepoURLTypeHelmOCI: return HelmOCIRegistryURL default: - return GetEnvWithDefault(EnvRepoURLDefault, fmt.Sprintf("file://%s", repoDirectory())) + return GetEnvWithDefault(EnvRepoURLDefault, "file://"+repoDirectory()) } } @@ -356,7 +356,7 @@ func DeploymentNamespace() string { // creates a secret for the current test, this currently can only create a single secret func CreateSecret(username, password string) string { - secretName := fmt.Sprintf("argocd-e2e-%s", name) + secretName := "argocd-e2e-" + name FailOnErr(Run("", "kubectl", "create", "secret", "generic", secretName, "--from-literal=username="+username, "--from-literal=password="+password, @@ -415,7 +415,7 @@ func updateGenericConfigMap(name string, updater func(cm *corev1.ConfigMap) erro func SetEnableManifestGeneration(val map[v1alpha1.ApplicationSourceType]bool) error { return updateSettingConfigMap(func(cm *corev1.ConfigMap) error { for k, v := range val { - cm.Data[fmt.Sprintf("%s.enable", strings.ToLower(string(k)))] = strconv.FormatBool(v) + cm.Data[strings.ToLower(string(k))+".enable"] = strconv.FormatBool(v) } return nil }) @@ -505,7 +505,7 @@ func getResourceOverrideSplitKey(key string, customizeType string) string { func SetAccounts(accounts map[string][]string) error { return updateSettingConfigMap(func(cm *corev1.ConfigMap) error { for k, v := range accounts { - cm.Data[fmt.Sprintf("accounts.%s", k)] = strings.Join(v, ",") + cm.Data["accounts."+k] = strings.Join(v, ",") } return nil }) @@ -962,7 +962,7 @@ func EnsureCleanState(t *testing.T, opts ...TestOption) { postFix := "-" + strings.ToLower(randString) id = t.Name() + postFix name = DnsFriendly(t.Name(), "") - deploymentNamespace = DnsFriendly(fmt.Sprintf("argocd-e2e-%s", t.Name()), postFix) + deploymentNamespace = DnsFriendly("argocd-e2e-"+t.Name(), postFix) // create namespace _, err = Run("", "kubectl", "create", "ns", DeploymentNamespace()) if err != nil { @@ -1087,7 +1087,7 @@ func AddSignedFile(path, contents string) { os.Setenv("GNUPGHOME", TmpDir+"/gpg") FailOnErr(Run(repoDirectory(), "git", "diff")) FailOnErr(Run(repoDirectory(), "git", "add", ".")) - FailOnErr(Run(repoDirectory(), "git", "-c", fmt.Sprintf("user.signingkey=%s", GpgGoodKeyID), "commit", "-S", "-am", "add file")) + FailOnErr(Run(repoDirectory(), "git", "-c", "user.signingkey="+GpgGoodKeyID, "commit", "-S", "-am", "add file")) os.Setenv("GNUPGHOME", prevGnuPGHome) if IsRemote() { FailOnErr(Run(repoDirectory(), "git", "push", "-f", "origin", "master")) @@ -1098,7 +1098,7 @@ func AddSignedTag(name string) { prevGnuPGHome := os.Getenv("GNUPGHOME") os.Setenv("GNUPGHOME", TmpDir+"/gpg") defer os.Setenv("GNUPGHOME", prevGnuPGHome) - FailOnErr(Run(repoDirectory(), "git", "-c", fmt.Sprintf("user.signingkey=%s", GpgGoodKeyID), "tag", "-sm", "add signed tag", name)) + FailOnErr(Run(repoDirectory(), "git", "-c", "user.signingkey="+GpgGoodKeyID, "tag", "-sm", "add signed tag", name)) if IsRemote() { FailOnErr(Run(repoDirectory(), "git", "push", "--tags", "-f", "origin", "master")) } @@ -1269,7 +1269,7 @@ func RecordTestRun(t *testing.T) { t.Fatalf("could not close record file %s: %v", rf, err) } }() - if _, err := f.WriteString(fmt.Sprintf("%s\n", t.Name())); err != nil { + if _, err := f.WriteString(t.Name() + "\n"); err != nil { t.Fatalf("could not write to %s: %v", rf, err) } } diff --git a/test/e2e/fixture/gpgkeys/gpgkeys.go b/test/e2e/fixture/gpgkeys/gpgkeys.go index 0751f67ad2cec..28c49fdd74053 100644 --- a/test/e2e/fixture/gpgkeys/gpgkeys.go +++ b/test/e2e/fixture/gpgkeys/gpgkeys.go @@ -11,7 +11,7 @@ import ( // Add GPG public key via API and create appropriate file where the ConfigMap mount would de it as well func AddGPGPublicKey() { - keyPath, err := filepath.Abs(fmt.Sprintf("../fixture/gpg/%s", fixture.GpgGoodKeyID)) + keyPath, err := filepath.Abs("../fixture/gpg/" + fixture.GpgGoodKeyID) errors.CheckError(err) args := []string{"gpg", "add", "--from", keyPath} errors.FailOnErr(fixture.RunCli(args...)) diff --git a/test/e2e/fixture/repos/repos.go b/test/e2e/fixture/repos/repos.go index e64f6e20fe8fa..0a647a1ffe6d8 100644 --- a/test/e2e/fixture/repos/repos.go +++ b/test/e2e/fixture/repos/repos.go @@ -160,7 +160,7 @@ func PushChartToOCIRegistry(chartPathName, chartName, chartVersion string) { errors.CheckError(err1) defer func() { _ = os.RemoveAll(tempDest) }() - chartAbsPath, err2 := filepath.Abs(fmt.Sprintf("./testdata/%s", chartPathName)) + chartAbsPath, err2 := filepath.Abs("./testdata/" + chartPathName) errors.CheckError(err2) _ = os.Setenv("HELM_EXPERIMENTAL_OCI", "1") @@ -172,6 +172,6 @@ func PushChartToOCIRegistry(chartPathName, chartName, chartVersion string) { "helm", "push", fmt.Sprintf("%s/%s-%s.tgz", tempDest, chartName, chartVersion), - fmt.Sprintf("oci://%s", fixture.HelmOCIRegistryURL), + "oci://"+fixture.HelmOCIRegistryURL, )) } diff --git a/test/e2e/helm_test.go b/test/e2e/helm_test.go index a893486811df5..858626b4246ac 100644 --- a/test/e2e/helm_test.go +++ b/test/e2e/helm_test.go @@ -511,10 +511,10 @@ func testHelmWithDependencies(t *testing.T, chartPath string, legacyRepo bool) { ctx.And(func() { FailOnErr(fixture.Run("", "kubectl", "create", "secret", "generic", "helm-repo", "-n", fixture.TestNamespace(), - fmt.Sprintf("--from-file=certSecret=%s", repos.CertPath), - fmt.Sprintf("--from-file=keySecret=%s", repos.CertKeyPath), - fmt.Sprintf("--from-literal=username=%s", GitUsername), - fmt.Sprintf("--from-literal=password=%s", GitPassword), + "--from-file=certSecret="+repos.CertPath, + "--from-file=keySecret="+repos.CertKeyPath, + "--from-literal=username="+GitUsername, + "--from-literal=password="+GitPassword, )) FailOnErr(fixture.KubeClientset.CoreV1().Secrets(fixture.TestNamespace()).Patch(context.Background(), "helm-repo", types.MergePatchType, []byte(`{"metadata": { "labels": {"e2e.argoproj.io": "true"} }}`), metav1.PatchOptions{})) diff --git a/test/e2e/project_management_test.go b/test/e2e/project_management_test.go index 169227eea52a5..95688aaa59394 100644 --- a/test/e2e/project_management_test.go +++ b/test/e2e/project_management_test.go @@ -520,7 +520,7 @@ func TestGetVirtualProjectNoMatch(t *testing.T) { projectName := "proj-" + fixture.Name() _, err = fixture.RunCli("proj", "create", projectName, "--description", "Test description", - "-d", fmt.Sprintf("%s,*", v1alpha1.KubernetesInternalAPIServerAddr), + "-d", v1alpha1.KubernetesInternalAPIServerAddr+",*", "-s", "*", "--orphaned-resources") require.NoError(t, err) @@ -551,7 +551,7 @@ func TestGetVirtualProjectMatch(t *testing.T) { projectName := "proj-" + fixture.Name() _, err = fixture.RunCli("proj", "create", projectName, "--description", "Test description", - "-d", fmt.Sprintf("%s,*", v1alpha1.KubernetesInternalAPIServerAddr), + "-d", v1alpha1.KubernetesInternalAPIServerAddr+",*", "-s", "*", "--orphaned-resources") require.NoError(t, err) diff --git a/test/e2e/selective_sync_test.go b/test/e2e/selective_sync_test.go index 2f7704aa6b2ea..5cbf44643a37b 100644 --- a/test/e2e/selective_sync_test.go +++ b/test/e2e/selective_sync_test.go @@ -116,5 +116,5 @@ func getNewNamespace(t *testing.T) string { require.NoError(t, err) postFix := "-" + strings.ToLower(randStr) name := fixture.DnsFriendly(t.Name(), "") - return fixture.DnsFriendly(fmt.Sprintf("argocd-e2e-%s", name), postFix) + return fixture.DnsFriendly("argocd-e2e-"+name, postFix) } diff --git a/util/argo/argo.go b/util/argo/argo.go index 1119d06271728..23fac86c6bf0c 100644 --- a/util/argo/argo.go +++ b/util/argo/argo.go @@ -55,7 +55,7 @@ func AugmentSyncMsg(res common.ResourceSyncResult, apiResourceInfoGetter func() default: // Check if the message contains "metadata.annotation: Too long" if strings.Contains(res.Message, "metadata.annotations: Too long: must have at most 262144 bytes") { - res.Message = fmt.Sprintf("%s \n -Additional Info: This error usually means that you are trying to add a large resource on client side. Consider using Server-side apply or syncing with replace enabled. Note: Syncing with Replace enabled is potentially destructive as it may cause resource deletion and re-creation.", res.Message) + res.Message = res.Message + " \n -Additional Info: This error usually means that you are trying to add a large resource on client side. Consider using Server-side apply or syncing with replace enabled. Note: Syncing with Replace enabled is potentially destructive as it may cause resource deletion and re-creation." } } diff --git a/util/argo/argo_test.go b/util/argo/argo_test.go index 420eee9b7471c..76cb6c9fc7b21 100644 --- a/util/argo/argo_test.go +++ b/util/argo/argo_test.go @@ -366,7 +366,7 @@ func TestValidateRepo(t *testing.T) { }} kubeVersion := "v1.16" kustomizeOptions := &argoappv1.KustomizeOptions{BuildOptions: ""} - repo := &argoappv1.Repository{Repo: fmt.Sprintf("file://%s", repoPath)} + repo := &argoappv1.Repository{Repo: "file://" + repoPath} cluster := &argoappv1.Cluster{Server: "sample server"} app := &argoappv1.Application{ Spec: argoappv1.ApplicationSpec{ @@ -475,7 +475,7 @@ func TestFormatAppConditions(t *testing.T) { t.Run("Single Condition", func(t *testing.T) { res := FormatAppConditions(conditions[0:1]) assert.NotEmpty(t, res) - assert.Equal(t, fmt.Sprintf("%s: Foo", EventReasonOperationCompleted), res) + assert.Equal(t, EventReasonOperationCompleted+": Foo", res) }) t.Run("Multiple Conditions", func(t *testing.T) { @@ -1294,12 +1294,12 @@ func Test_GetRefSources(t *testing.T) { } } - repo := &argoappv1.Repository{Repo: fmt.Sprintf("file://%s", repoPath)} + repo := &argoappv1.Repository{Repo: "file://" + repoPath} t.Run("target ref exists", func(t *testing.T) { argoSpec := getMultiSourceAppSpec(argoappv1.ApplicationSources{ - {RepoURL: fmt.Sprintf("file://%s", repoPath), Ref: "source-1_2"}, - {RepoURL: fmt.Sprintf("file://%s", repoPath)}, + {RepoURL: "file://" + repoPath, Ref: "source-1_2"}, + {RepoURL: "file://" + repoPath}, }) refSources, err := GetRefSources(context.Background(), argoSpec.Sources, argoSpec.Project, func(ctx context.Context, url string, project string) (*argoappv1.Repository, error) { @@ -1319,7 +1319,7 @@ func Test_GetRefSources(t *testing.T) { t.Run("target ref does not exist", func(t *testing.T) { argoSpec := getMultiSourceAppSpec(argoappv1.ApplicationSources{ {RepoURL: "file://does-not-exist", Ref: "source1"}, - {RepoURL: fmt.Sprintf("file://%s", repoPath)}, + {RepoURL: "file://" + repoPath}, }) refSources, err := GetRefSources(context.Background(), argoSpec.Sources, argoSpec.Project, func(ctx context.Context, url string, project string) (*argoappv1.Repository, error) { @@ -1333,7 +1333,7 @@ func Test_GetRefSources(t *testing.T) { t.Run("invalid ref", func(t *testing.T) { argoSpec := getMultiSourceAppSpec(argoappv1.ApplicationSources{ {RepoURL: "file://does-not-exist", Ref: "%invalid-name%"}, - {RepoURL: fmt.Sprintf("file://%s", repoPath)}, + {RepoURL: "file://" + repoPath}, }) refSources, err := GetRefSources(context.TODO(), argoSpec.Sources, argoSpec.Project, func(ctx context.Context, url string, project string) (*argoappv1.Repository, error) { diff --git a/util/cache/appstate/cache.go b/util/cache/appstate/cache.go index 5ad5b2154a3b1..f0c335abb9287 100644 --- a/util/cache/appstate/cache.go +++ b/util/cache/appstate/cache.go @@ -56,7 +56,7 @@ func (c *Cache) SetItem(key string, item interface{}, expiration time.Duration, } func appManagedResourcesKey(appName string) string { - return fmt.Sprintf("app|managed-resources|%s", appName) + return "app|managed-resources|" + appName } func (c *Cache) GetAppManagedResources(appName string, res *[]*appv1.ResourceDiff) error { @@ -72,7 +72,7 @@ func (c *Cache) SetAppManagedResources(appName string, managedResources []*appv1 } func appResourcesTreeKey(appName string, shard int64) string { - key := fmt.Sprintf("app|resources-tree|%s", appName) + key := "app|resources-tree|" + appName if shard > 0 { key = fmt.Sprintf("%s|%d", key, shard) } @@ -80,7 +80,7 @@ func appResourcesTreeKey(appName string, shard int64) string { } func clusterInfoKey(server string) string { - return fmt.Sprintf("cluster|info|%s", server) + return "cluster|info|" + server } func (c *Cache) GetAppResourcesTree(appName string, res *appv1.ApplicationTree) error { diff --git a/util/cache/cache_test.go b/util/cache/cache_test.go index 921b2b1dc1b9b..98d289d92030f 100644 --- a/util/cache/cache_test.go +++ b/util/cache/cache_test.go @@ -1,7 +1,6 @@ package cache import ( - "fmt" "testing" "time" @@ -86,5 +85,5 @@ func TestGenerateCacheKey(t *testing.T) { client := NewInMemoryCache(60 * time.Second) cache := NewCache(client) testKey := cache.generateFullKey("testkey") - assert.Equal(t, fmt.Sprintf("testkey|%s", common.CacheVersion), testKey) + assert.Equal(t, "testkey|"+common.CacheVersion, testKey) } diff --git a/util/cert/cert_test.go b/util/cert/cert_test.go index cfc4b4385dd07..d91505589145b 100644 --- a/util/cert/cert_test.go +++ b/util/cert/cert_test.go @@ -1,7 +1,6 @@ package cert import ( - "fmt" "os" "path" "testing" @@ -399,7 +398,7 @@ func Test_ValidHostnames(t *testing.T) { } for hostName, valid := range hostNames { - t.Run(fmt.Sprintf("Test validity for hostname %s", hostName), func(t *testing.T) { + t.Run("Test validity for hostname "+hostName, func(t *testing.T) { assert.Equal(t, valid, IsValidHostname(hostName, false)) }) } diff --git a/util/cli/cli.go b/util/cli/cli.go index a84e031f6d76c..92f41d2bed779 100644 --- a/util/cli/cli.go +++ b/util/cli/cli.go @@ -309,7 +309,7 @@ func PrintDiff(name string, live *unstructured.Unstructured, target *unstructure if err != nil { return err } - liveFile := path.Join(tempDir, fmt.Sprintf("%s-live.yaml", name)) + liveFile := path.Join(tempDir, name+"-live.yaml") liveData := []byte("") if live != nil { liveData, err = yaml.Marshal(live) diff --git a/util/dex/dex.go b/util/dex/dex.go index 34b3c552f32be..5c417f73293cb 100644 --- a/util/dex/dex.go +++ b/util/dex/dex.go @@ -88,7 +88,7 @@ func NewDexHTTPReverseProxy(serverAddr string, baseHRef string, tlsConfig *DexTL }).Errorf("received error from dex: %s", string(b)) resp.ContentLength = 0 resp.Header.Set("Content-Length", strconv.Itoa(0)) - resp.Header.Set("Location", fmt.Sprintf("%s?has_sso_error=true", path.Join(baseHRef, "login"))) + resp.Header.Set("Location", path.Join(baseHRef, "login")+"?has_sso_error=true") resp.StatusCode = http.StatusSeeOther resp.Body = io.NopCloser(bytes.NewReader(make([]byte, 0))) return nil diff --git a/util/git/client.go b/util/git/client.go index 0b9ab11b79eee..76160204fcd71 100644 --- a/util/git/client.go +++ b/util/git/client.go @@ -943,7 +943,7 @@ func (m *nativeGitClient) CommitAndPush(branch, message string) (string, error) // runWrapper runs a custom command with all the semantics of running the Git client func (m *nativeGitClient) runGnuPGWrapper(wrapper string, args ...string) (string, error) { cmd := exec.Command(wrapper, args...) - cmd.Env = append(cmd.Env, fmt.Sprintf("GNUPGHOME=%s", common.GetGnuPGHomePath()), "LANG=C") + cmd.Env = append(cmd.Env, "GNUPGHOME="+common.GetGnuPGHomePath(), "LANG=C") return m.runCmdOutput(cmd, runOpts{}) } @@ -965,8 +965,8 @@ func (m *nativeGitClient) runCredentialedCmd(args ...string) error { // If a basic auth header is explicitly set, tell Git to send it to the // server to force use of basic auth instead of negotiating the auth scheme for _, e := range environ { - if strings.HasPrefix(e, fmt.Sprintf("%s=", forceBasicAuthHeaderEnv)) { - args = append([]string{"--config-env", fmt.Sprintf("http.extraHeader=%s", forceBasicAuthHeaderEnv)}, args...) + if strings.HasPrefix(e, forceBasicAuthHeaderEnv+"=") { + args = append([]string{"--config-env", "http.extraHeader=" + forceBasicAuthHeaderEnv}, args...) } } @@ -1002,7 +1002,7 @@ func (m *nativeGitClient) runCmdOutput(cmd *exec.Cmd, ropts runOpts) (string, er } else { caPath, err := certutil.GetCertBundlePathForRepository(parsedURL.Host) if err == nil && caPath != "" { - cmd.Env = append(cmd.Env, fmt.Sprintf("GIT_SSL_CAINFO=%s", caPath)) + cmd.Env = append(cmd.Env, "GIT_SSL_CAINFO="+caPath) } } } diff --git a/util/git/client_test.go b/util/git/client_test.go index a335d4a1bd6c8..497c32fc0a9d3 100644 --- a/util/git/client_test.go +++ b/util/git/client_test.go @@ -1,7 +1,6 @@ package git import ( - "fmt" "os" "os/exec" "path" @@ -48,7 +47,7 @@ func Test_nativeGitClient_Fetch(t *testing.T) { tempDir, err := _createEmptyGitRepo() require.NoError(t, err) - client, err := NewClient(fmt.Sprintf("file://%s", tempDir), NopCreds{}, true, false, "", "") + client, err := NewClient("file://"+tempDir, NopCreds{}, true, false, "", "") require.NoError(t, err) err = client.Init() @@ -62,7 +61,7 @@ func Test_nativeGitClient_Fetch_Prune(t *testing.T) { tempDir, err := _createEmptyGitRepo() require.NoError(t, err) - client, err := NewClient(fmt.Sprintf("file://%s", tempDir), NopCreds{}, true, false, "", "") + client, err := NewClient("file://"+tempDir, NopCreds{}, true, false, "", "") require.NoError(t, err) err = client.Init() @@ -85,7 +84,7 @@ func Test_nativeGitClient_Fetch_Prune(t *testing.T) { func Test_IsAnnotatedTag(t *testing.T) { tempDir := t.TempDir() - client, err := NewClient(fmt.Sprintf("file://%s", tempDir), NopCreds{}, true, false, "", "") + client, err := NewClient("file://"+tempDir, NopCreds{}, true, false, "", "") require.NoError(t, err) err = client.Init() @@ -130,7 +129,7 @@ func Test_IsAnnotatedTag(t *testing.T) { func Test_ChangedFiles(t *testing.T) { tempDir := t.TempDir() - client, err := NewClientExt(fmt.Sprintf("file://%s", tempDir), tempDir, NopCreds{}, true, false, "", "") + client, err := NewClientExt("file://"+tempDir, tempDir, NopCreds{}, true, false, "", "") require.NoError(t, err) err = client.Init() @@ -185,7 +184,7 @@ func Test_ChangedFiles(t *testing.T) { func Test_SemverTags(t *testing.T) { tempDir := t.TempDir() - client, err := NewClientExt(fmt.Sprintf("file://%s", tempDir), tempDir, NopCreds{}, true, false, "", "") + client, err := NewClientExt("file://"+tempDir, tempDir, NopCreds{}, true, false, "", "") require.NoError(t, err) err = client.Init() @@ -360,7 +359,7 @@ func Test_nativeGitClient_Submodule(t *testing.T) { err = runCmd(tempDir, "git", "clone", foo) require.NoError(t, err) - client, err := NewClient(fmt.Sprintf("file://%s", foo), NopCreds{}, true, false, "", "") + client, err := NewClient("file://"+foo, NopCreds{}, true, false, "", "") require.NoError(t, err) err = client.Init() @@ -416,7 +415,7 @@ func TestNewClient_invalidSSHURL(t *testing.T) { func Test_IsRevisionPresent(t *testing.T) { tempDir := t.TempDir() - client, err := NewClientExt(fmt.Sprintf("file://%s", tempDir), tempDir, NopCreds{}, true, false, "", "") + client, err := NewClientExt("file://"+tempDir, tempDir, NopCreds{}, true, false, "", "") require.NoError(t, err) err = client.Init() @@ -450,7 +449,7 @@ func Test_IsRevisionPresent(t *testing.T) { func Test_nativeGitClient_RevisionMetadata(t *testing.T) { tempDir := t.TempDir() - client, err := NewClient(fmt.Sprintf("file://%s", tempDir), NopCreds{}, true, false, "", "") + client, err := NewClient("file://"+tempDir, NopCreds{}, true, false, "", "") require.NoError(t, err) err = client.Init() @@ -495,7 +494,7 @@ func Test_nativeGitClient_SetAuthor(t *testing.T) { tempDir, err := _createEmptyGitRepo() require.NoError(t, err) - client, err := NewClient(fmt.Sprintf("file://%s", tempDir), NopCreds{}, true, false, "", "") + client, err := NewClient("file://"+tempDir, NopCreds{}, true, false, "", "") require.NoError(t, err) err = client.Init() @@ -525,7 +524,7 @@ func Test_nativeGitClient_CheckoutOrOrphan(t *testing.T) { tempDir, err := _createEmptyGitRepo() require.NoError(t, err) - client, err := NewClientExt(fmt.Sprintf("file://%s", tempDir), tempDir, NopCreds{}, true, false, "", "") + client, err := NewClientExt("file://"+tempDir, tempDir, NopCreds{}, true, false, "", "") require.NoError(t, err) err = client.Init() @@ -577,7 +576,7 @@ func Test_nativeGitClient_CheckoutOrOrphan(t *testing.T) { // make origin git repository tempDir, err := _createEmptyGitRepo() require.NoError(t, err) - originGitRepoUrl := fmt.Sprintf("file://%s", tempDir) + originGitRepoUrl := "file://" + tempDir err = runCmd(tempDir, "git", "commit", "-m", "Second commit", "--allow-empty") require.NoError(t, err) @@ -654,7 +653,7 @@ func Test_nativeGitClient_CheckoutOrNew(t *testing.T) { tempDir, err := _createEmptyGitRepo() require.NoError(t, err) - client, err := NewClientExt(fmt.Sprintf("file://%s", tempDir), tempDir, NopCreds{}, true, false, "", "") + client, err := NewClientExt("file://"+tempDir, tempDir, NopCreds{}, true, false, "", "") require.NoError(t, err) err = client.Init() @@ -713,7 +712,7 @@ func Test_nativeGitClient_CheckoutOrNew(t *testing.T) { tempDir, err := _createEmptyGitRepo() require.NoError(t, err) - client, err := NewClientExt(fmt.Sprintf("file://%s", tempDir), tempDir, NopCreds{}, true, false, "", "") + client, err := NewClientExt("file://"+tempDir, tempDir, NopCreds{}, true, false, "", "") require.NoError(t, err) err = client.Init() @@ -757,7 +756,7 @@ func Test_nativeGitClient_RemoveContents(t *testing.T) { tempDir, err := _createEmptyGitRepo() require.NoError(t, err) - client, err := NewClient(fmt.Sprintf("file://%s", tempDir), NopCreds{}, true, false, "", "") + client, err := NewClient("file://"+tempDir, NopCreds{}, true, false, "", "") require.NoError(t, err) err = client.Init() @@ -805,7 +804,7 @@ func Test_nativeGitClient_CommitAndPush(t *testing.T) { require.NoError(t, err) branch := strings.TrimSpace(string(gitCurrentBranch)) - client, err := NewClient(fmt.Sprintf("file://%s", tempDir), NopCreds{}, true, false, "", "") + client, err := NewClient("file://"+tempDir, NopCreds{}, true, false, "", "") require.NoError(t, err) err = client.Init() diff --git a/util/git/creds.go b/util/git/creds.go index 9f3675cac12a2..19308112c9c29 100644 --- a/util/git/creds.go +++ b/util/git/creds.go @@ -215,7 +215,7 @@ func (c HTTPSCreds) Environ() (io.Closer, []string, error) { return NopCloser{}, nil, err } // GIT_SSL_CERT is the full path to a client certificate to be used - env = append(env, fmt.Sprintf("GIT_SSL_CERT=%s", certFile.Name())) + env = append(env, "GIT_SSL_CERT="+certFile.Name()) _, err = keyFile.WriteString(c.clientCertKey) if err != nil { @@ -223,7 +223,7 @@ func (c HTTPSCreds) Environ() (io.Closer, []string, error) { return NopCloser{}, nil, err } // GIT_SSL_KEY is the full path to a client certificate's key to be used - env = append(env, fmt.Sprintf("GIT_SSL_KEY=%s", keyFile.Name())) + env = append(env, "GIT_SSL_KEY="+keyFile.Name()) } // If at least password is set, we will set ARGOCD_BASIC_AUTH_HEADER to // hold the HTTP authorization header, so auth mechanism negotiation is @@ -323,7 +323,7 @@ func (c SSHCreds) Environ() (io.Closer, []string, error) { args := []string{"ssh", "-i", file.Name()} var env []string if c.caPath != "" { - env = append(env, fmt.Sprintf("GIT_SSL_CAINFO=%s", c.caPath)) + env = append(env, "GIT_SSL_CAINFO="+c.caPath) } if c.insecure { log.Warn("temporarily disabling strict host key checking (i.e. '-o StrictHostKeyChecking=no -o UserKnownHostsFile=/dev/null'), please don't use in production") @@ -332,7 +332,7 @@ func (c SSHCreds) Environ() (io.Closer, []string, error) { args = append(args, "-o", "StrictHostKeyChecking=no", "-o", "UserKnownHostsFile=/dev/null") } else { knownHostsFile := certutil.GetSSHKnownHostsDataPath() - args = append(args, "-o", "StrictHostKeyChecking=yes", "-o", fmt.Sprintf("UserKnownHostsFile=%s", knownHostsFile)) + args = append(args, "-o", "StrictHostKeyChecking=yes", "-o", "UserKnownHostsFile="+knownHostsFile) } // Handle SSH socks5 proxy settings proxyEnv := []string{} @@ -346,13 +346,13 @@ func (c SSHCreds) Environ() (io.Closer, []string, error) { parsedProxyURL.Hostname(), parsedProxyURL.Port())) if parsedProxyURL.User != nil { - proxyEnv = append(proxyEnv, fmt.Sprintf("SOCKS5_USER=%s", parsedProxyURL.User.Username())) + proxyEnv = append(proxyEnv, "SOCKS5_USER="+parsedProxyURL.User.Username()) if socks5_passwd, isPasswdSet := parsedProxyURL.User.Password(); isPasswdSet { - proxyEnv = append(proxyEnv, fmt.Sprintf("SOCKS5_PASSWD=%s", socks5_passwd)) + proxyEnv = append(proxyEnv, "SOCKS5_PASSWD="+socks5_passwd) } } } - env = append(env, []string{fmt.Sprintf("GIT_SSH_COMMAND=%s", strings.Join(args, " "))}...) + env = append(env, []string{"GIT_SSH_COMMAND=" + strings.Join(args, " ")}...) env = append(env, proxyEnv...) return sshCloser, env, nil } @@ -425,7 +425,7 @@ func (g GitHubAppCreds) Environ() (io.Closer, []string, error) { return NopCloser{}, nil, err } // GIT_SSL_CERT is the full path to a client certificate to be used - env = append(env, fmt.Sprintf("GIT_SSL_CERT=%s", certFile.Name())) + env = append(env, "GIT_SSL_CERT="+certFile.Name()) _, err = keyFile.WriteString(g.clientCertKey) if err != nil { @@ -433,7 +433,7 @@ func (g GitHubAppCreds) Environ() (io.Closer, []string, error) { return NopCloser{}, nil, err } // GIT_SSL_KEY is the full path to a client certificate's key to be used - env = append(env, fmt.Sprintf("GIT_SSL_KEY=%s", keyFile.Name())) + env = append(env, "GIT_SSL_KEY="+keyFile.Name()) } nonce := g.store.Add(githubAccessTokenUsername, token) env = append(env, g.store.Environ(nonce)...) @@ -464,7 +464,7 @@ func (g GitHubAppCreds) GetUserInfo(ctx context.Context) (string, string, error) httpClient := http.Client{Transport: appInstallTransport} client := github.NewClient(&httpClient) - appLogin := fmt.Sprintf("%s[bot]", app.GetSlug()) + appLogin := app.GetSlug() + "[bot]" user, _, err := client.Users.Get(ctx, appLogin) if err != nil { return "", "", fmt.Errorf("failed to get app user info: %w", err) diff --git a/util/git/creds_test.go b/util/git/creds_test.go index 865e2316e0790..303ac2f8f4752 100644 --- a/util/git/creds_test.go +++ b/util/git/creds_test.go @@ -100,7 +100,7 @@ func TestHTTPSCreds_Environ_forceBasicAuth(t *testing.T) { defer closer.Close() var header string for _, envVar := range env { - if strings.HasPrefix(envVar, fmt.Sprintf("%s=", forceBasicAuthHeaderEnv)) { + if strings.HasPrefix(envVar, forceBasicAuthHeaderEnv+"=") { header = envVar[len(forceBasicAuthHeaderEnv)+1:] } if header != "" { @@ -118,7 +118,7 @@ func TestHTTPSCreds_Environ_forceBasicAuth(t *testing.T) { defer closer.Close() var header string for _, envVar := range env { - if strings.HasPrefix(envVar, fmt.Sprintf("%s=", forceBasicAuthHeaderEnv)) { + if strings.HasPrefix(envVar, forceBasicAuthHeaderEnv+"=") { header = envVar[len(forceBasicAuthHeaderEnv)+1:] } if header != "" { @@ -135,7 +135,7 @@ func TestHTTPSCreds_Environ_forceBasicAuth(t *testing.T) { defer closer.Close() var header string for _, envVar := range env { - if strings.HasPrefix(envVar, fmt.Sprintf("%s=", forceBasicAuthHeaderEnv)) { + if strings.HasPrefix(envVar, forceBasicAuthHeaderEnv+"=") { header = envVar[len(forceBasicAuthHeaderEnv)+1:] } if header != "" { @@ -153,7 +153,7 @@ func TestHTTPSCreds_Environ_forceBasicAuth(t *testing.T) { defer closer.Close() var header string for _, envVar := range env { - if strings.HasPrefix(envVar, fmt.Sprintf("%s=", forceBasicAuthHeaderEnv)) { + if strings.HasPrefix(envVar, forceBasicAuthHeaderEnv+"=") { header = envVar[len(forceBasicAuthHeaderEnv)+1:] } if header != "" { @@ -219,7 +219,7 @@ func Test_SSHCreds_Environ(t *testing.T) { } else { assert.Contains(t, env[1], "-o StrictHostKeyChecking=yes") hostsPath := cert.GetSSHKnownHostsDataPath() - assert.Contains(t, env[1], fmt.Sprintf("-o UserKnownHostsFile=%s", hostsPath)) + assert.Contains(t, env[1], "-o UserKnownHostsFile="+hostsPath) } envRegex := regexp.MustCompile("-i ([^ ]+)") @@ -252,7 +252,7 @@ func Test_SSHCreds_Environ_WithProxy(t *testing.T) { } else { assert.Contains(t, env[1], "-o StrictHostKeyChecking=yes") hostsPath := cert.GetSSHKnownHostsDataPath() - assert.Contains(t, env[1], fmt.Sprintf("-o UserKnownHostsFile=%s", hostsPath)) + assert.Contains(t, env[1], "-o UserKnownHostsFile="+hostsPath) } assert.Contains(t, env[1], "-o ProxyCommand='connect-proxy -S 127.0.0.1:1080 -5 %h %p'") @@ -288,7 +288,7 @@ func Test_SSHCreds_Environ_WithProxyUserNamePassword(t *testing.T) { } else { assert.Contains(t, env[1], "-o StrictHostKeyChecking=yes") hostsPath := cert.GetSSHKnownHostsDataPath() - assert.Contains(t, env[1], fmt.Sprintf("-o UserKnownHostsFile=%s", hostsPath)) + assert.Contains(t, env[1], "-o UserKnownHostsFile="+hostsPath) } assert.Contains(t, env[1], "-o ProxyCommand='connect-proxy -S 127.0.0.1:1080 -5 %h %p'") diff --git a/util/git/git_test.go b/util/git/git_test.go index f06df14c070ea..d46265a879ab3 100644 --- a/util/git/git_test.go +++ b/util/git/git_test.go @@ -1,7 +1,6 @@ package git import ( - "fmt" "io" "net/http" "os" @@ -327,7 +326,7 @@ func TestLFSClient(t *testing.T) { require.NoError(t, err) assert.Len(t, largeFiles, 3) - fileHandle, err := os.Open(fmt.Sprintf("%s/test3.yaml", tempDir)) + fileHandle, err := os.Open(tempDir + "/test3.yaml") require.NoError(t, err) if err == nil { defer func() { diff --git a/util/gpg/gpg.go b/util/gpg/gpg.go index 100a6e7b68899..4e402d645f1cb 100644 --- a/util/gpg/gpg.go +++ b/util/gpg/gpg.go @@ -150,7 +150,7 @@ const MaxVerificationLinesToParse = 40 // Helper function to append GNUPGHOME for a command execution environment func getGPGEnviron() []string { - return append(os.Environ(), fmt.Sprintf("GNUPGHOME=%s", common.GetGnuPGHomePath()), "LANG=C") + return append(os.Environ(), "GNUPGHOME="+common.GetGnuPGHomePath(), "LANG=C") } // Helper function to write some data to a temp file and return its path @@ -617,7 +617,7 @@ func ParseGitCommitVerification(signature string) PGPVerifyResult { result.Cipher = keyID[1] result.KeyID = KeyID(keyID[2]) if result.KeyID == "" { - return unknownResult(fmt.Sprintf("Invalid PGP key ID found in verification result: %s", result.KeyID)) + return unknownResult("Invalid PGP key ID found in verification result: " + result.KeyID) } // What was the result of signature verification? diff --git a/util/gpg/gpg_test.go b/util/gpg/gpg_test.go index e279f1e9ad554..e6f3093e42d18 100644 --- a/util/gpg/gpg_test.go +++ b/util/gpg/gpg_test.go @@ -79,7 +79,7 @@ func Test_GPG_InitializeGnuPG(t *testing.T) { // During unit-tests, we need to also kill gpg-agent so we can create a new key. // In real world scenario -- i.e. container crash -- gpg-agent is not running yet. cmd := exec.Command("gpgconf", "--kill", "gpg-agent") - cmd.Env = []string{fmt.Sprintf("GNUPGHOME=%s", p)} + cmd.Env = []string{"GNUPGHOME=" + p} err = cmd.Run() require.NoError(t, err) @@ -104,7 +104,7 @@ func Test_GPG_InitializeGnuPG(t *testing.T) { t.Run("Unaccessible GNUPGHOME", func(t *testing.T) { p := initTempDir(t) - fp := fmt.Sprintf("%s/gpg", p) + fp := p + "/gpg" err = os.Mkdir(fp, 0o000) if err != nil { panic(err.Error()) diff --git a/util/grpc/logging.go b/util/grpc/logging.go index 37dfc286caaed..271111977473b 100644 --- a/util/grpc/logging.go +++ b/util/grpc/logging.go @@ -76,7 +76,7 @@ func PayloadStreamServerInterceptor(entry *logrus.Entry, logClaims bool, decider return handler(srv, stream) } logEntry := entry.WithFields(ctx_logrus.Extract(stream.Context()).Data) - newStream := &loggingServerStream{ServerStream: stream, entry: logEntry, logClaims: logClaims, info: fmt.Sprintf("received streaming call %s", info.FullMethod)} + newStream := &loggingServerStream{ServerStream: stream, entry: logEntry, logClaims: logClaims, info: "received streaming call " + info.FullMethod} return handler(srv, newStream) } } @@ -87,7 +87,7 @@ func PayloadUnaryServerInterceptor(entry *logrus.Entry, logClaims bool, decider return handler(ctx, req) } logEntry := entry.WithFields(ctx_logrus.Extract(ctx).Data) - logRequest(logEntry, fmt.Sprintf("received unary call %s", info.FullMethod), req, ctx, logClaims) + logRequest(logEntry, "received unary call "+info.FullMethod, req, ctx, logClaims) resp, err := handler(ctx, req) return resp, err } diff --git a/util/helm/client_test.go b/util/helm/client_test.go index 97c27d6c1f62c..00362ee06b699 100644 --- a/util/helm/client_test.go +++ b/util/helm/client_test.go @@ -257,7 +257,7 @@ func TestGetTagsFromURLPrivateRepoAuthentication(t *testing.T) { }, { name: "should login correctly when the repo path is not in the server root with http scheme", - repoURL: fmt.Sprintf("%s/my-repo", server.URL), + repoURL: server.URL + "/my-repo", }, { name: "should login correctly when the repo path is in the server root without http scheme", @@ -265,7 +265,7 @@ func TestGetTagsFromURLPrivateRepoAuthentication(t *testing.T) { }, { name: "should login correctly when the repo path is not in the server root without http scheme", - repoURL: fmt.Sprintf("%s/my-repo", serverURL.Host), + repoURL: serverURL.Host + "/my-repo", }, } @@ -342,7 +342,7 @@ func TestGetTagsFromURLEnvironmentAuthentication(t *testing.T) { }, { name: "should login correctly when the repo path is not in the server root with http scheme", - repoURL: fmt.Sprintf("%s/my-repo", server.URL), + repoURL: server.URL + "/my-repo", }, { name: "should login correctly when the repo path is in the server root without http scheme", @@ -350,7 +350,7 @@ func TestGetTagsFromURLEnvironmentAuthentication(t *testing.T) { }, { name: "should login correctly when the repo path is not in the server root without http scheme", - repoURL: fmt.Sprintf("%s/my-repo", serverURL.Host), + repoURL: serverURL.Host + "/my-repo", }, } diff --git a/util/kustomize/kustomize.go b/util/kustomize/kustomize.go index 3509f4689de96..226a07a09c8de 100644 --- a/util/kustomize/kustomize.go +++ b/util/kustomize/kustomize.go @@ -130,7 +130,7 @@ func (k *kustomize) Build(opts *v1alpha1.ApplicationSourceKustomize, kustomizeOp log.Debugf("No caCert found for repo %s", parsedURL.Host) } else { // Make Git use CA bundle - environ = append(environ, fmt.Sprintf("GIT_SSL_CAINFO=%s", caPath)) + environ = append(environ, "GIT_SSL_CAINFO="+caPath) } } } diff --git a/util/log/logrus_test.go b/util/log/logrus_test.go index 0613d4ced0af0..881e5c94fccf4 100644 --- a/util/log/logrus_test.go +++ b/util/log/logrus_test.go @@ -1,7 +1,6 @@ package log import ( - "fmt" "testing" "github.com/sirupsen/logrus" @@ -26,12 +25,12 @@ func TestCreateFormatter(t *testing.T) { result := CreateFormatter("text") assert.Equal(t, &logrus.TextFormatter{}, result) }) - t.Run(fmt.Sprintf("%s == 1", common.EnvLogFormatEnableFullTimestamp), func(t *testing.T) { + t.Run(common.EnvLogFormatEnableFullTimestamp+" == 1", func(t *testing.T) { t.Setenv(common.EnvLogFormatEnableFullTimestamp, "1") result := CreateFormatter("text") assert.Equal(t, &logrus.TextFormatter{FullTimestamp: true}, result) }) - t.Run(fmt.Sprintf("%s != 1", common.EnvLogFormatEnableFullTimestamp), func(t *testing.T) { + t.Run(common.EnvLogFormatEnableFullTimestamp+" != 1", func(t *testing.T) { t.Setenv(common.EnvLogFormatEnableFullTimestamp, "0") result := CreateFormatter("text") assert.Equal(t, &logrus.TextFormatter{}, result) diff --git a/util/lua/custom_actions_test.go b/util/lua/custom_actions_test.go index da635af3b02ac..4b7a06bf7dc7e 100644 --- a/util/lua/custom_actions_test.go +++ b/util/lua/custom_actions_test.go @@ -117,7 +117,7 @@ func TestLuaResourceActionsScript(t *testing.T) { require.NoError(t, err) for i := range resourceTest.DiscoveryTests { test := resourceTest.DiscoveryTests[i] - testName := fmt.Sprintf("discovery/%s", test.InputPath) + testName := "discovery/" + test.InputPath t.Run(testName, func(t *testing.T) { vm := VM{ UseOpenLibs: true, diff --git a/util/lua/lua.go b/util/lua/lua.go index 5183d018f84a4..215d8041ac626 100644 --- a/util/lua/lua.go +++ b/util/lua/lua.go @@ -396,7 +396,7 @@ func (vm VM) GetResourceActionDiscovery(obj *unstructured.Unstructured) ([]strin } // Fetch predefined Lua scripts - discoveryKey := fmt.Sprintf("%s/actions/", key) + discoveryKey := key + "/actions/" discoveryScript, err := vm.getPredefinedLuaScripts(discoveryKey, actionDiscoveryScriptFile) // Ignore the error if the script does not exist. diff --git a/util/notification/expression/strings/strings_test.go b/util/notification/expression/strings/strings_test.go index 660ec66aa4cf2..76cb57606b2f6 100644 --- a/util/notification/expression/strings/strings_test.go +++ b/util/notification/expression/strings/strings_test.go @@ -1,7 +1,6 @@ package strings import ( - "fmt" "testing" "github.com/stretchr/testify/assert" @@ -50,7 +49,7 @@ func TestUpperAndLower(t *testing.T) { exprs := NewExprs() for _, testCase := range testCases { - t.Run(fmt.Sprintf("With success case: Func: %s", testCase.fn), func(tc *testing.T) { + t.Run("With success case: Func: "+testCase.fn, func(tc *testing.T) { toUpperFn, ok := exprs[testCase.fn].(func(s string) string) assert.True(t, ok) diff --git a/util/notification/k8s/informers.go b/util/notification/k8s/informers.go index 4289df21e021c..361453da0dfc0 100644 --- a/util/notification/k8s/informers.go +++ b/util/notification/k8s/informers.go @@ -1,7 +1,6 @@ package k8s import ( - "fmt" "time" metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" @@ -16,12 +15,12 @@ const ( func NewSecretInformer(clientset kubernetes.Interface, namespace string, secretName string) cache.SharedIndexInformer { return corev1.NewFilteredSecretInformer(clientset, namespace, settingsResyncDuration, cache.Indexers{}, func(options *metav1.ListOptions) { - options.FieldSelector = fmt.Sprintf("metadata.name=%s", secretName) + options.FieldSelector = "metadata.name=" + secretName }) } func NewConfigMapInformer(clientset kubernetes.Interface, namespace string, configMapName string) cache.SharedIndexInformer { return corev1.NewFilteredConfigMapInformer(clientset, namespace, settingsResyncDuration, cache.Indexers{}, func(options *metav1.ListOptions) { - options.FieldSelector = fmt.Sprintf("metadata.name=%s", configMapName) + options.FieldSelector = "metadata.name=" + configMapName }) } diff --git a/util/oidc/oidc.go b/util/oidc/oidc.go index 2f01dc167e3d4..6b475d01c6a81 100644 --- a/util/oidc/oidc.go +++ b/util/oidc/oidc.go @@ -383,7 +383,7 @@ func (a *ClientApp) HandleCallback(w http.ResponseWriter, r *http.Request) { if a.baseHRef != "" { path = strings.TrimRight(strings.TrimLeft(a.baseHRef, "/"), "/") } - cookiePath := fmt.Sprintf("path=/%s", path) + cookiePath := "path=/" + path flags := []string{cookiePath, "SameSite=lax", "httpOnly"} if a.secureCookie { flags = append(flags, "Secure") diff --git a/util/oidc/provider.go b/util/oidc/provider.go index 36601314d00f4..87e9f1f730b10 100644 --- a/util/oidc/provider.go +++ b/util/oidc/provider.go @@ -82,7 +82,7 @@ func (t tokenVerificationError) Error() string { for aud, err := range t.errorsByAudience { errorStrings = append(errorStrings, fmt.Sprintf("error for aud %q: %v", aud, err)) } - return fmt.Sprintf("token verification failed for all audiences: %s", strings.Join(errorStrings, ", ")) + return "token verification failed for all audiences: " + strings.Join(errorStrings, ", ") } func (p *providerImpl) Verify(tokenString string, argoSettings *settings.ArgoCDSettings) (*gooidc.IDToken, error) { diff --git a/util/proxy/proxy.go b/util/proxy/proxy.go index bef4ce47b81dc..c4349e8ad48e3 100644 --- a/util/proxy/proxy.go +++ b/util/proxy/proxy.go @@ -1,7 +1,6 @@ package proxy import ( - "fmt" "net/http" "net/url" "os/exec" @@ -47,13 +46,13 @@ func GetCallback(proxy string, noProxy string) func(*http.Request) (*url.URL, er } func httpProxy(url string) string { - return fmt.Sprintf("http_proxy=%s", url) + return "http_proxy=" + url } func httpsProxy(url string) string { - return fmt.Sprintf("https_proxy=%s", url) + return "https_proxy=" + url } func noProxyVar(noProxy string) string { - return fmt.Sprintf("no_proxy=%s", noProxy) + return "no_proxy=" + noProxy } diff --git a/util/rbac/rbac.go b/util/rbac/rbac.go index ab45cf5c0d69f..1446620d58bd0 100644 --- a/util/rbac/rbac.go +++ b/util/rbac/rbac.go @@ -256,10 +256,10 @@ func (e *Enforcer) EnforceErr(rvals ...interface{}) error { break } if sub := jwtutil.StringField(claims, "sub"); sub != "" { - rvalsStrs = append(rvalsStrs, fmt.Sprintf("sub: %s", sub)) + rvalsStrs = append(rvalsStrs, "sub: "+sub) } if issuedAtTime, err := jwtutil.IssuedAtTime(claims); err == nil { - rvalsStrs = append(rvalsStrs, fmt.Sprintf("iat: %s", issuedAtTime.Format(time.RFC3339))) + rvalsStrs = append(rvalsStrs, "iat: "+issuedAtTime.Format(time.RFC3339)) } } errMsg = fmt.Sprintf("%s: %s", errMsg, strings.Join(rvalsStrs, ", ")) @@ -337,7 +337,7 @@ func (e *Enforcer) SetUserPolicy(policy string) error { // newInformers returns an informer which watches updates on the rbac configmap func (e *Enforcer) newInformer() cache.SharedIndexInformer { tweakConfigMap := func(options *metav1.ListOptions) { - cmFieldSelector := fields.ParseSelectorOrDie(fmt.Sprintf("metadata.name=%s", e.configmap)) + cmFieldSelector := fields.ParseSelectorOrDie("metadata.name=" + e.configmap) options.FieldSelector = cmFieldSelector.String() } indexers := cache.Indexers{cache.NamespaceIndex: cache.MetaNamespaceIndexFunc} diff --git a/util/rbac/rbac_test.go b/util/rbac/rbac_test.go index 8bf1b780af6b4..686d283a3ee50 100644 --- a/util/rbac/rbac_test.go +++ b/util/rbac/rbac_test.go @@ -2,7 +2,6 @@ package rbac import ( "context" - "fmt" "strings" "testing" "time" @@ -371,7 +370,7 @@ func TestEnforceErrorMessage(t *testing.T) { assert.Equal(t, "rpc error: code = PermissionDenied desc = permission denied: project, sub: proj:default:admin", err.Error()) iat := time.Unix(int64(1593035962), 0).Format(time.RFC3339) - exp := fmt.Sprintf("rpc error: code = PermissionDenied desc = permission denied: project, sub: proj:default:admin, iat: %s", iat) + exp := "rpc error: code = PermissionDenied desc = permission denied: project, sub: proj:default:admin, iat: " + iat // nolint:staticcheck ctx = context.WithValue(context.Background(), "claims", &jwt.RegisteredClaims{Subject: "proj:default:admin", IssuedAt: jwt.NewNumericDate(time.Unix(int64(1593035962), 0))}) err = enf.EnforceErr(ctx.Value("claims"), "project") diff --git a/util/session/sessionmanager_test.go b/util/session/sessionmanager_test.go index 73d8fdb8eaecb..efee1951e7899 100644 --- a/util/session/sessionmanager_test.go +++ b/util/session/sessionmanager_test.go @@ -689,7 +689,7 @@ rootCA: | mgr.verificationDelayNoiseEnabled = false claims := jwt.RegisteredClaims{Audience: jwt.ClaimStrings{"test-client"}, Subject: "admin", ExpiresAt: jwt.NewNumericDate(time.Now().Add(time.Hour * 24))} - claims.Issuer = fmt.Sprintf("%s/api/dex", dexTestServer.URL) + claims.Issuer = dexTestServer.URL + "/api/dex" token := jwt.NewWithClaims(jwt.SigningMethodRS512, claims) key, err := jwt.ParseRSAPrivateKeyFromPEM(utiltest.PrivateKey) require.NoError(t, err) @@ -759,7 +759,7 @@ requestedScopes: ["oidc"]`, oidcTestServer.URL), mgr.verificationDelayNoiseEnabled = false claims := jwt.RegisteredClaims{Audience: jwt.ClaimStrings{"test-client"}, Subject: "admin", ExpiresAt: jwt.NewNumericDate(time.Now().Add(time.Hour * 24))} - claims.Issuer = fmt.Sprintf("%s/api/dex", dexTestServer.URL) + claims.Issuer = dexTestServer.URL + "/api/dex" token := jwt.NewWithClaims(jwt.SigningMethodRS512, claims) key, err := jwt.ParseRSAPrivateKeyFromPEM(utiltest.PrivateKey) require.NoError(t, err) diff --git a/util/settings/accounts.go b/util/settings/accounts.go index 3d5b686af8a2a..f172b6c83b19c 100644 --- a/util/settings/accounts.go +++ b/util/settings/accounts.go @@ -237,7 +237,7 @@ func parseAccounts(secret *v1.Secret, cm *v1.ConfigMap) (map[string]Account, err } for key, v := range cm.Data { - if !strings.HasPrefix(key, fmt.Sprintf("%s.", accountsKeyPrefix)) { + if !strings.HasPrefix(key, accountsKeyPrefix+".") { continue } diff --git a/util/settings/settings.go b/util/settings/settings.go index a4e75440cc208..c9ec3573e1562 100644 --- a/util/settings/settings.go +++ b/util/settings/settings.go @@ -2204,7 +2204,7 @@ func (mgr *SettingsManager) InitializeSettings(insecureModeEnabled bool) (*ArgoC hosts := []string{ "localhost", "argocd-server", - fmt.Sprintf("argocd-server.%s", mgr.namespace), + "argocd-server." + mgr.namespace, fmt.Sprintf("argocd-server.%s.svc", mgr.namespace), fmt.Sprintf("argocd-server.%s.svc.cluster.local", mgr.namespace), } diff --git a/util/settings/settings_test.go b/util/settings/settings_test.go index 59ff122704fb3..8822793364038 100644 --- a/util/settings/settings_test.go +++ b/util/settings/settings_test.go @@ -134,8 +134,8 @@ func TestGetExtensionConfigs(t *testing.T) { name: "will return main and additional config successfully", expectedLen: 2, input: map[string]string{ - extensionConfig: "main config", - fmt.Sprintf("%s.anotherExtension", extensionConfig): "another config", + extensionConfig: "main config", + extensionConfig + ".anotherExtension": "another config", }, expected: map[string]string{ "": "main config", diff --git a/util/tls/tls_test.go b/util/tls/tls_test.go index d164c68b233f1..6ce46af940a5b 100644 --- a/util/tls/tls_test.go +++ b/util/tls/tls_test.go @@ -145,7 +145,7 @@ func TestGetTLSVersionByString(t *testing.T) { func TestGetTLSCipherSuitesByString(t *testing.T) { suites := make([]string, 0) for _, s := range tls.CipherSuites() { - t.Run(fmt.Sprintf("Test for valid suite %s", s.Name), func(t *testing.T) { + t.Run("Test for valid suite "+s.Name, func(t *testing.T) { ids, err := getTLSCipherSuitesByString(s.Name) require.NoError(t, err) assert.Len(t, ids, 1) @@ -203,7 +203,7 @@ func TestGenerate(t *testing.T) { }) for _, curve := range []string{"P224", "P256", "P384", "P521"} { - t.Run(fmt.Sprintf("Create certificate with curve %s", curve), func(t *testing.T) { + t.Run("Create certificate with curve "+curve, func(t *testing.T) { opts := CertOptions{Hosts: []string{"localhost"}, Organization: "Acme", ECDSACurve: curve} _, _, err := generate(opts) require.NoError(t, err) diff --git a/util/webhook/webhook.go b/util/webhook/webhook.go index df5c1fecc1273..f56a25a4c4217 100644 --- a/util/webhook/webhook.go +++ b/util/webhook/webhook.go @@ -465,7 +465,7 @@ func (a *ArgoCDWebhookHandler) Handler(w http.ResponseWriter, r *http.Request) { if r.Method != http.MethodPost { status = http.StatusMethodNotAllowed } - http.Error(w, fmt.Sprintf("Webhook processing failed: %s", html.EscapeString(err.Error())), status) + http.Error(w, "Webhook processing failed: "+html.EscapeString(err.Error()), status) return }