chore: enable err-error and strconcat of perfsprint linter (#21267)

Signed-off-by: Matthieu MOREL <[email protected]>
This commit is contained in:
Matthieu MOREL
2024-12-20 16:22:28 +00:00
committed by GitHub
parent 2a4db08e0f
commit 4156151f8f
85 changed files with 210 additions and 226 deletions
+2 -2
View File
@@ -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:
+2 -2
View File
@@ -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
}
}
+1 -1
View File
@@ -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
}
}
+1 -1
View File
@@ -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)
@@ -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
}
}
+1 -2
View File
@@ -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
@@ -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
+1 -1
View File
@@ -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
}
@@ -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)
@@ -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
@@ -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)
+4 -4
View File
@@ -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)
+1 -1
View File
@@ -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)"
}
}
@@ -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
}
@@ -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")
}
+2 -3
View File
@@ -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)
+1 -1
View File
@@ -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)"
}
+1 -2
View File
@@ -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)
}
}
+4 -4
View File
@@ -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)
+2 -2
View File
@@ -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 <ARGOCD_SERVER_ADDRESS>
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) {
+1 -1
View File
@@ -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)
+1 -1
View File
@@ -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)
+1 -1
View File
@@ -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,
},
{
+1 -1
View File
@@ -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,
}
+6 -6
View File
@@ -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
+2 -2
View File
@@ -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
+2 -2
View File
@@ -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)
+2 -3
View File
@@ -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()
}
+2 -2
View File
@@ -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_))
}
+2 -2
View File
@@ -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
+1 -2
View File
@@ -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)
+5 -5
View File
@@ -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))
}
+15 -15
View File
@@ -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",
},
+2 -2
View File
@@ -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)
+2 -2
View File
@@ -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
}
+1 -1
View File
@@ -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]
+2 -2
View File
@@ -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
+4 -5
View File
@@ -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())
}
+3 -3
View File
@@ -153,7 +153,7 @@ var backoff = wait.Backoff{
}
var (
clientConstraint = fmt.Sprintf(">= %s", common.MinClientVersion)
clientConstraint = ">= " + common.MinClientVersion
baseHRefRegex = regexp.MustCompile(`<base href="(.*?)">`)
// 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)
+1 -1
View File
@@ -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",
},
{
+3 -3
View File
@@ -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)
+2 -2
View File
@@ -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,
+2 -2
View File
@@ -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,
+1 -1
View File
@@ -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)
+2 -2
View File
@@ -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
}
+2 -2
View File
@@ -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
}
}
+8 -8
View File
@@ -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)
}
}
+1 -1
View File
@@ -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...))
+2 -2
View File
@@ -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,
))
}
+4 -4
View File
@@ -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{}))
+2 -2
View File
@@ -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)
+1 -1
View File
@@ -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)
}
+1 -1
View File
@@ -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."
}
}
+7 -7
View File
@@ -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) {
+3 -3
View File
@@ -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 {
+1 -2
View File
@@ -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)
}
+1 -2
View File
@@ -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))
})
}
+1 -1
View File
@@ -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)
+1 -1
View File
@@ -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
+4 -4
View File
@@ -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)
}
}
}
+15 -16
View File
@@ -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()
+10 -10
View File
@@ -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)
+7 -7
View File
@@ -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'")
+1 -2
View File
@@ -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() {
+2 -2
View File
@@ -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?
+2 -2
View File
@@ -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())
+2 -2
View File
@@ -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
}
+4 -4
View File
@@ -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",
},
}
+1 -1
View File
@@ -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)
}
}
}
+2 -3
View File
@@ -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)
+1 -1
View File
@@ -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,
+1 -1
View File
@@ -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.
@@ -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)
+2 -3
View File
@@ -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
})
}
+1 -1
View File
@@ -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")
+1 -1
View File
@@ -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) {
+3 -4
View File
@@ -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
}
+3 -3
View File
@@ -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}
+1 -2
View File
@@ -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")
+2 -2
View File
@@ -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)
+1 -1
View File
@@ -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
}
+1 -1
View File
@@ -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),
}
+2 -2
View File
@@ -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",
+2 -2
View File
@@ -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)
+1 -1
View File
@@ -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
}