From 9f1e2e84530e94a110a66c3cd95793584c8f313e Mon Sep 17 00:00:00 2001 From: Matthieu MOREL Date: Thu, 13 Jun 2024 21:10:00 +0200 Subject: [PATCH] chore: enable gocritic linter (#18633) * chore: enable gocritic linter Signed-off-by: Matthieu MOREL * Update settings.go Signed-off-by: Matthieu MOREL * Update app.go Signed-off-by: Matthieu MOREL * Update grpcproxy.go Signed-off-by: Matthieu MOREL * Update grpcproxy.go Signed-off-by: Matthieu MOREL * Update util.go Signed-off-by: Matthieu MOREL * Update server.go Signed-off-by: Matthieu MOREL * Update app_management_ns_test.go Signed-off-by: Matthieu MOREL * Update app_management_test.go Signed-off-by: Matthieu MOREL * Update path_traversal.go Signed-off-by: Matthieu MOREL * Update sessionmanager.go Signed-off-by: Matthieu MOREL * Update .golangci.yaml Signed-off-by: Matthieu MOREL --------- Signed-off-by: Matthieu MOREL --- .golangci.yaml | 13 +++++++ applicationset/generators/git.go | 4 +- applicationset/generators/plugin_test.go | 2 +- applicationset/utils/clusterUtils.go | 6 +-- applicationset/utils/utils.go | 4 +- .../commands/admin/project_allowlist.go | 2 +- cmd/argocd/commands/app.go | 6 +-- cmd/util/app.go | 6 +-- controller/appcontroller.go | 12 +++--- controller/metrics/metrics.go | 6 +-- .../controller/controller.go | 4 +- pkg/apis/application/v1alpha1/generated.proto | 4 +- .../application/v1alpha1/openapi_generated.go | 4 +- pkg/apis/application/v1alpha1/types.go | 10 ++--- server/application/application.go | 8 ++-- server/badge/badge.go | 6 +-- server/project/project_test.go | 2 +- test/e2e/app_management_ns_test.go | 6 +-- test/e2e/app_management_test.go | 6 +-- util/argo/argo.go | 8 ++-- util/cache/cache.go | 2 +- util/cert/cert.go | 4 +- util/db/certificate.go | 8 ++-- util/dex/dex.go | 4 +- util/grpc/sanitizer.go | 2 +- util/lua/lua.go | 10 ++--- util/lua/oslib_safe.go | 38 +++++++++---------- .../expression/shared/appdetail.go | 10 ++--- util/session/sessionmanager.go | 8 ++-- util/session/sessionmanager_test.go | 2 +- util/settings/settings_test.go | 2 +- 31 files changed, 98 insertions(+), 111 deletions(-) diff --git a/.golangci.yaml b/.golangci.yaml index e17d06ec997a9..528cd85e5078e 100644 --- a/.golangci.yaml +++ b/.golangci.yaml @@ -1,5 +1,6 @@ issues: exclude: + - SA1019 - SA5011 exclude-rules: - path: "(applicationset|cmd|cmpserver|controller|pkg|reposerver|server|test)/" @@ -16,6 +17,7 @@ linters: enable: - errcheck - errorlint + - gocritic - gofumpt - goimports - gosimple @@ -27,6 +29,17 @@ linters: - unused - whitespace linters-settings: + gocritic: + disabled-checks: + - appendAssign + - assignOp # Keep it disabled for readability + - badCond + - commentFormatting + - exitAfterDefer + - ifElseChain + - mapKey + - singleCaseSwitch + - typeSwitchVar goimports: local-prefixes: github.com/argoproj/argo-cd/v2 testifylint: diff --git a/applicationset/generators/git.go b/applicationset/generators/git.go index 821ad66118762..a5fb2576f8f6a 100644 --- a/applicationset/generators/git.go +++ b/applicationset/generators/git.go @@ -226,13 +226,13 @@ func (g *GitGenerator) generateParamsFromGitFile(filePath string, fileContent [] return res, nil } -func (g *GitGenerator) filterApps(Directories []argoprojiov1alpha1.GitDirectoryGeneratorItem, allPaths []string) []string { +func (g *GitGenerator) filterApps(directories []argoprojiov1alpha1.GitDirectoryGeneratorItem, allPaths []string) []string { res := []string{} for _, appPath := range allPaths { appInclude := false appExclude := false // Iterating over each appPath and check whether directories object has requestedPath that matches the appPath - for _, requestedPath := range Directories { + for _, requestedPath := range directories { match, err := path.Match(requestedPath.Path, appPath) if err != nil { log.WithError(err).WithField("requestedPath", requestedPath). diff --git a/applicationset/generators/plugin_test.go b/applicationset/generators/plugin_test.go index e5f8be7ec8658..0b3deb9e0ab04 100644 --- a/applicationset/generators/plugin_test.go +++ b/applicationset/generators/plugin_test.go @@ -645,7 +645,7 @@ func TestPluginGenerateParams(t *testing.T) { handler := http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { authHeader := r.Header.Get("Authorization") _, tokenKey := plugin.ParseSecretKey(testCase.configmap.Data["token"]) - expectedToken := testCase.secret.Data[strings.Replace(tokenKey, "$", "", -1)] + expectedToken := testCase.secret.Data[strings.ReplaceAll(tokenKey, "$", "")] if authHeader != "Bearer "+string(expectedToken) { w.WriteHeader(http.StatusUnauthorized) return diff --git a/applicationset/utils/clusterUtils.go b/applicationset/utils/clusterUtils.go index f1d30674a7ebc..a56be51fdb7a2 100644 --- a/applicationset/utils/clusterUtils.go +++ b/applicationset/utils/clusterUtils.go @@ -61,10 +61,8 @@ func ValidateDestination(ctx context.Context, dest *appv1.ApplicationDestination return fmt.Errorf("application references destination cluster %s which does not exist", dest.Name) } dest.SetInferredServer(server) - } else { - if !dest.IsServerInferred() { - return fmt.Errorf("application destination can't have both name and server defined: %s %s", dest.Name, dest.Server) - } + } else if !dest.IsServerInferred() { + return fmt.Errorf("application destination can't have both name and server defined: %s %s", dest.Name, dest.Server) } } return nil diff --git a/applicationset/utils/utils.go b/applicationset/utils/utils.go index 749e810d3b6e5..dfcc11cbdd35a 100644 --- a/applicationset/utils/utils.go +++ b/applicationset/utils/utils.go @@ -268,8 +268,8 @@ func (r *Render) RenderTemplateParams(tmpl *argoappsv1.Application, syncPolicy * // b) there IS a syncPolicy, but preserveResourcesOnDeletion is set to false // See TestRenderTemplateParamsFinalizers in util_test.go for test-based definition of behaviour if (syncPolicy == nil || !syncPolicy.PreserveResourcesOnDeletion) && - ((*replacedTmpl).ObjectMeta.Finalizers == nil || len((*replacedTmpl).ObjectMeta.Finalizers) == 0) { - (*replacedTmpl).ObjectMeta.Finalizers = []string{"resources-finalizer.argocd.argoproj.io"} + (replacedTmpl.ObjectMeta.Finalizers == nil || len(replacedTmpl.ObjectMeta.Finalizers) == 0) { + replacedTmpl.ObjectMeta.Finalizers = []string{"resources-finalizer.argocd.argoproj.io"} } return replacedTmpl, nil diff --git a/cmd/argocd/commands/admin/project_allowlist.go b/cmd/argocd/commands/admin/project_allowlist.go index bbc72284daa20..9f436f2f3a81c 100644 --- a/cmd/argocd/commands/admin/project_allowlist.go +++ b/cmd/argocd/commands/admin/project_allowlist.go @@ -120,7 +120,7 @@ func generateProjectAllowList(serverResources []*metav1.APIResourceList, cluster resourceList := make([]metav1.GroupKind, 0) for _, rule := range clusterRole.Rules { - if len(rule.APIGroups) <= 0 { + if len(rule.APIGroups) == 0 { continue } diff --git a/cmd/argocd/commands/app.go b/cmd/argocd/commands/app.go index 6aee6bee8d0ae..b4d03c618692f 100644 --- a/cmd/argocd/commands/app.go +++ b/cmd/argocd/commands/app.go @@ -2544,10 +2544,8 @@ func setParameterOverrides(app *argoappv1.Application, parameters []string, sour sourceType = *st } else if app.Status.SourceType != "" { sourceType = app.Status.SourceType - } else { - if len(strings.SplitN(parameters[0], "=", 2)) == 2 { - sourceType = argoappv1.ApplicationSourceTypeHelm - } + } else if len(strings.SplitN(parameters[0], "=", 2)) == 2 { + sourceType = argoappv1.ApplicationSourceTypeHelm } switch sourceType { diff --git a/cmd/util/app.go b/cmd/util/app.go index f1d0254aa5a54..1ac606a22ba5c 100644 --- a/cmd/util/app.go +++ b/cmd/util/app.go @@ -434,10 +434,8 @@ func SetParameterOverrides(app *argoappv1.Application, parameters []string, inde sourceType = *st } else if app.Status.SourceType != "" { sourceType = app.Status.SourceType - } else { - if len(strings.SplitN(parameters[0], "=", 2)) == 2 { - sourceType = argoappv1.ApplicationSourceTypeHelm - } + } else if len(strings.SplitN(parameters[0], "=", 2)) == 2 { + sourceType = argoappv1.ApplicationSourceTypeHelm } switch sourceType { diff --git a/controller/appcontroller.go b/controller/appcontroller.go index 9d500a7af0b59..a15628d8b640f 100644 --- a/controller/appcontroller.go +++ b/controller/appcontroller.go @@ -305,13 +305,11 @@ func (ctrl *ApplicationController) InvalidateProjectsCache(names ...string) { for _, name := range names { ctrl.projByNameCache.Delete(name) } - } else { - if ctrl != nil { - ctrl.projByNameCache.Range(func(key, _ interface{}) bool { - ctrl.projByNameCache.Delete(key) - return true - }) - } + } else if ctrl != nil { + ctrl.projByNameCache.Range(func(key, _ interface{}) bool { + ctrl.projByNameCache.Delete(key) + return true + }) } } diff --git a/controller/metrics/metrics.go b/controller/metrics/metrics.go index 85169bf217d62..3e7e70ae05da5 100644 --- a/controller/metrics/metrics.go +++ b/controller/metrics/metrics.go @@ -62,21 +62,21 @@ var ( append(descAppDefaultLabels, "autosync_enabled", "repo", "dest_server", "dest_namespace", "sync_status", "health_status", "operation"), nil, ) - // DEPRECATED + // Deprecated descAppCreated = prometheus.NewDesc( "argocd_app_created_time", "Creation time in unix timestamp for an application.", descAppDefaultLabels, nil, ) - // DEPRECATED: superseded by sync_status label in argocd_app_info + // Deprecated: superseded by sync_status label in argocd_app_info descAppSyncStatusCode = prometheus.NewDesc( "argocd_app_sync_status", "The application current sync status.", append(descAppDefaultLabels, "sync_status"), nil, ) - // DEPRECATED: superseded by health_status label in argocd_app_info + // Deprecated: superseded by health_status label in argocd_app_info descAppHealthStatus = prometheus.NewDesc( "argocd_app_health_status", "The application current health status.", diff --git a/notification_controller/controller/controller.go b/notification_controller/controller/controller.go index 39efef32b0749..1bc3e73a6fbd7 100644 --- a/notification_controller/controller/controller.go +++ b/notification_controller/controller/controller.go @@ -166,9 +166,7 @@ func newInformer(resClient dynamic.ResourceInterface, controllerNamespace string &unstructured.Unstructured{}, resyncPeriod, cache.Indexers{ - cache.NamespaceIndex: func(obj interface{}) ([]string, error) { - return cache.MetaNamespaceIndexFunc(obj) - }, + cache.NamespaceIndex: cache.MetaNamespaceIndexFunc, }, ) return informer diff --git a/pkg/apis/application/v1alpha1/generated.proto b/pkg/apis/application/v1alpha1/generated.proto index f1d958b6db1d4..bc162dca1fc3f 100644 --- a/pkg/apis/application/v1alpha1/generated.proto +++ b/pkg/apis/application/v1alpha1/generated.proto @@ -729,11 +729,11 @@ message Cluster { // Config holds cluster information for connecting to a cluster optional ClusterConfig config = 3; - // DEPRECATED: use Info.ConnectionState field instead. + // Deprecated: use Info.ConnectionState field instead. // ConnectionState contains information about cluster connection state optional ConnectionState connectionState = 4; - // DEPRECATED: use Info.ServerVersion field instead. + // Deprecated: use Info.ServerVersion field instead. // The server version optional string serverVersion = 5; diff --git a/pkg/apis/application/v1alpha1/openapi_generated.go b/pkg/apis/application/v1alpha1/openapi_generated.go index 28755d785d364..2fcbbb94edb0b 100644 --- a/pkg/apis/application/v1alpha1/openapi_generated.go +++ b/pkg/apis/application/v1alpha1/openapi_generated.go @@ -2645,14 +2645,14 @@ func schema_pkg_apis_application_v1alpha1_Cluster(ref common.ReferenceCallback) }, "connectionState": { SchemaProps: spec.SchemaProps{ - Description: "DEPRECATED: use Info.ConnectionState field instead. ConnectionState contains information about cluster connection state", + Description: "Deprecated: use Info.ConnectionState field instead. ConnectionState contains information about cluster connection state", Default: map[string]interface{}{}, Ref: ref("github.com/argoproj/argo-cd/v2/pkg/apis/application/v1alpha1.ConnectionState"), }, }, "serverVersion": { SchemaProps: spec.SchemaProps{ - Description: "DEPRECATED: use Info.ServerVersion field instead. The server version", + Description: "Deprecated: use Info.ServerVersion field instead. The server version", Type: []string{"string"}, Format: "", }, diff --git a/pkg/apis/application/v1alpha1/types.go b/pkg/apis/application/v1alpha1/types.go index f998a9956beea..f31ae025e452a 100644 --- a/pkg/apis/application/v1alpha1/types.go +++ b/pkg/apis/application/v1alpha1/types.go @@ -1770,10 +1770,10 @@ type Cluster struct { Name string `json:"name" protobuf:"bytes,2,opt,name=name"` // Config holds cluster information for connecting to a cluster Config ClusterConfig `json:"config" protobuf:"bytes,3,opt,name=config"` - // DEPRECATED: use Info.ConnectionState field instead. + // Deprecated: use Info.ConnectionState field instead. // ConnectionState contains information about cluster connection state ConnectionState ConnectionState `json:"connectionState,omitempty" protobuf:"bytes,4,opt,name=connectionState"` - // DEPRECATED: use Info.ServerVersion field instead. + // Deprecated: use Info.ServerVersion field instead. // The server version ServerVersion string `json:"serverVersion,omitempty" protobuf:"bytes,5,opt,name=serverVersion"` // Holds list of namespaces which are accessible in that cluster. Cluster level resources will be ignored if namespace list is not empty. @@ -2472,10 +2472,8 @@ func (w *SyncWindows) hasDeny() (bool, bool) { if a.Kind == "deny" { if !denyFound { manualEnabled = a.ManualSync - } else { - if manualEnabled { - manualEnabled = a.ManualSync - } + } else if manualEnabled { + manualEnabled = a.ManualSync } denyFound = true } diff --git a/server/application/application.go b/server/application/application.go index ec517a30c89fa..7fd22c37458d6 100644 --- a/server/application/application.go +++ b/server/application/application.go @@ -1091,11 +1091,9 @@ func (s *Server) Delete(ctx context.Context, q *application.ApplicationDeleteReq a.SetCascadedDeletion(policyFinalizer) patchFinalizer = true } - } else { - if a.CascadedDeletion() { - a.UnSetCascadedDeletion() - patchFinalizer = true - } + } else if a.CascadedDeletion() { + a.UnSetCascadedDeletion() + patchFinalizer = true } if patchFinalizer { diff --git a/server/badge/badge.go b/server/badge/badge.go index 1fcd29f305114..bc599e61ca0b2 100644 --- a/server/badge/badge.go +++ b/server/badge/badge.go @@ -132,10 +132,8 @@ func (h *Handler) ServeHTTP(w http.ResponseWriter, r *http.Request) { if app.Status.OperationState != nil && app.Status.OperationState.SyncResult != nil { revision = app.Status.OperationState.SyncResult.Revision } - } else { - if errors.IsNotFound(err) { - notFound = true - } + } else if errors.IsNotFound(err) { + notFound = true } } else { w.WriteHeader(http.StatusBadRequest) diff --git a/server/project/project_test.go b/server/project/project_test.go index 11626925e3b28..00354ae6ffebe 100644 --- a/server/project/project_test.go +++ b/server/project/project_test.go @@ -646,7 +646,7 @@ p, role:admin, projects, update, *, allow`) projWithRole := existingProj.DeepCopy() role := v1alpha1.ProjectRole{Name: roleName, JWTTokens: []v1alpha1.JWTToken{{IssuedAt: 1}}} - noSpacesPolicyTemplate := strings.Replace(policyTemplate, " ", "", -1) + noSpacesPolicyTemplate := strings.ReplaceAll(policyTemplate, " ", "") invalidPolicy := fmt.Sprintf(noSpacesPolicyTemplate, projWithRole.Name, roleName, action, projWithRole.Name, object, effect) role.Policies = append(role.Policies, invalidPolicy) projWithRole.Spec.Roles = append(projWithRole.Spec.Roles, role) diff --git a/test/e2e/app_management_ns_test.go b/test/e2e/app_management_ns_test.go index fb991a5df7957..f84b43b3db7f4 100644 --- a/test/e2e/app_management_ns_test.go +++ b/test/e2e/app_management_ns_test.go @@ -1092,10 +1092,8 @@ func assertNSResourceActions(t *testing.T, appName string, successful bool) { assertError := func(err error, message string) { if successful { assert.NoError(t, err) - } else { - if assert.Error(t, err) { - assert.Contains(t, err.Error(), message) - } + } else if assert.Error(t, err) { + assert.Contains(t, err.Error(), message) } } diff --git a/test/e2e/app_management_test.go b/test/e2e/app_management_test.go index 428f0ee0765f6..5c28cf28992cf 100644 --- a/test/e2e/app_management_test.go +++ b/test/e2e/app_management_test.go @@ -1450,10 +1450,8 @@ func assertResourceActions(t *testing.T, appName string, successful bool) { assertError := func(err error, message string) { if successful { assert.NoError(t, err) - } else { - if assert.Error(t, err) { - assert.Contains(t, err.Error(), message) - } + } else if assert.Error(t, err) { + assert.Contains(t, err.Error(), message) } } diff --git a/util/argo/argo.go b/util/argo/argo.go index f5f7cefe585f3..8024e07bcddab 100644 --- a/util/argo/argo.go +++ b/util/argo/argo.go @@ -501,10 +501,8 @@ func ValidateDestination(ctx context.Context, dest *argoappv1.ApplicationDestina return fmt.Errorf("application references destination cluster %s which does not exist", dest.Name) } dest.SetInferredServer(server) - } else { - if !dest.IsServerInferred() { - return fmt.Errorf("application destination can't have both name and server defined: %s %s", dest.Name, dest.Server) - } + } else if !dest.IsServerInferred() { + return fmt.Errorf("application destination can't have both name and server defined: %s %s", dest.Name, dest.Server) } } return nil @@ -1005,7 +1003,7 @@ func GenerateSpecIsDifferentErrorMessage(entity string, a, b interface{}) string if len(difference) == 0 { return basicMsg } - return fmt.Sprintf("%s; difference in keys \"%s\"", basicMsg, strings.Join(difference[:], ",")) + return fmt.Sprintf("%s; difference in keys \"%s\"", basicMsg, strings.Join(difference, ",")) } func GetDifferentPathsBetweenStructs(a, b interface{}) ([]string, error) { diff --git a/util/cache/cache.go b/util/cache/cache.go index 616cfa870d023..fb1d20c5b723b 100644 --- a/util/cache/cache.go +++ b/util/cache/cache.go @@ -96,7 +96,7 @@ func (o *Options) callOnClientCreated(client *redis.Client) { } func (o *Options) getEnvPrefix() string { - return strings.Replace(strings.ToUpper(o.FlagPrefix), "-", "_", -1) + return strings.ReplaceAll(strings.ToUpper(o.FlagPrefix), "-", "_") } func mergeOptions(opts ...Options) Options { diff --git a/util/cert/cert.go b/util/cert/cert.go index 3826c72b7d6e7..4fe39299666a9 100644 --- a/util/cert/cert.go +++ b/util/cert/cert.go @@ -271,8 +271,8 @@ func TokenizedDataToPublicKey(hostname string, subType string, rawKeyData string // Returns the requested pattern with all possible square brackets escaped func nonBracketedPattern(pattern string) string { - ret := strings.Replace(pattern, "[", `\[`, -1) - return strings.Replace(ret, "]", `\]`, -1) + ret := strings.ReplaceAll(pattern, "[", `\[`) + return strings.ReplaceAll(ret, "]", `\]`) } // We do not use full fledged regular expression for matching the hostname. diff --git a/util/db/certificate.go b/util/db/certificate.go index 9674a1489a71e..3bedbc5e6f4ea 100644 --- a/util/db/certificate.go +++ b/util/db/certificate.go @@ -289,13 +289,11 @@ func (db *db) CreateRepoCertificate(ctx context.Context, certificates *appsv1.Re Data: string(certificate.CertData), } tlsCertificates = append(tlsCertificates, tlsCertificate) - } else { + } else if tlsCertificate.Data != string(certificate.CertData) { // We have made sure the upsert flag was set above. Now just figure out // again if we have to actually update the data in the existing cert. - if tlsCertificate.Data != string(certificate.CertData) { - tlsCertificate.Data = string(certificate.CertData) - upserted = true - } + tlsCertificate.Data = string(certificate.CertData) + upserted = true } if newEntry || upserted { diff --git a/util/dex/dex.go b/util/dex/dex.go index 9dec26a0ec060..34b3c552f32be 100644 --- a/util/dex/dex.go +++ b/util/dex/dex.go @@ -102,11 +102,11 @@ func NewDexHTTPReverseProxy(serverAddr string, baseHRef string, tlsConfig *DexTL } // NewDexRewriteURLRoundTripper creates a new DexRewriteURLRoundTripper -func NewDexRewriteURLRoundTripper(dexServerAddr string, T http.RoundTripper) DexRewriteURLRoundTripper { +func NewDexRewriteURLRoundTripper(dexServerAddr string, t http.RoundTripper) DexRewriteURLRoundTripper { dexURL, _ := url.Parse(dexServerAddr) return DexRewriteURLRoundTripper{ DexURL: dexURL, - T: T, + T: t, } } diff --git a/util/grpc/sanitizer.go b/util/grpc/sanitizer.go index 8d471a5521c19..36739e7def1cb 100644 --- a/util/grpc/sanitizer.go +++ b/util/grpc/sanitizer.go @@ -64,7 +64,7 @@ func NewSanitizer() *sanitizer { // AddReplacement adds a replacement to the Sanitizer func (s *sanitizer) AddReplacement(val string, replacement string) { s.replacers = append(s.replacers, func(in string) string { - return strings.Replace(in, val, replacement, -1) + return strings.ReplaceAll(in, val, replacement) }) } diff --git a/util/lua/lua.go b/util/lua/lua.go index 704f817bc64d7..956235751df09 100644 --- a/util/lua/lua.go +++ b/util/lua/lua.go @@ -423,7 +423,7 @@ func isValidHealthStatusCode(statusCode health.HealthStatusCode) bool { // Took logic from the link below and added the int, int32, and int64 types since the value would have type int64 // while actually running in the controller and it was not reproducible through testing. // https://github.com/layeh/gopher-json/blob/97fed8db84274c421dbfffbb28ec859901556b97/json.go#L154 -func decodeValue(L *lua.LState, value interface{}) lua.LValue { +func decodeValue(l *lua.LState, value interface{}) lua.LValue { switch converted := value.(type) { case bool: return lua.LBool(converted) @@ -440,15 +440,15 @@ func decodeValue(L *lua.LState, value interface{}) lua.LValue { case int64: return lua.LNumber(converted) case []interface{}: - arr := L.CreateTable(len(converted), 0) + arr := l.CreateTable(len(converted), 0) for _, item := range converted { - arr.Append(decodeValue(L, item)) + arr.Append(decodeValue(l, item)) } return arr case map[string]interface{}: - tbl := L.CreateTable(0, len(converted)) + tbl := l.CreateTable(0, len(converted)) for key, item := range converted { - tbl.RawSetH(lua.LString(key), decodeValue(L, item)) + tbl.RawSetH(lua.LString(key), decodeValue(l, item)) } return tbl case nil: diff --git a/util/lua/oslib_safe.go b/util/lua/oslib_safe.go index d933c7f23000a..1b84a18b61905 100644 --- a/util/lua/oslib_safe.go +++ b/util/lua/oslib_safe.go @@ -13,15 +13,15 @@ import ( lua "github.com/yuin/gopher-lua" ) -func OpenSafeOs(L *lua.LState) int { - tabmod := L.RegisterModule(lua.TabLibName, osFuncs) - L.Push(tabmod) +func OpenSafeOs(l *lua.LState) int { + tabmod := l.RegisterModule(lua.TabLibName, osFuncs) + l.Push(tabmod) return 1 } -func SafeOsLoader(L *lua.LState) int { - mod := L.SetFuncs(L.NewTable(), osFuncs) - L.Push(mod) +func SafeOsLoader(l *lua.LState) int { + mod := l.SetFuncs(l.NewTable(), osFuncs) + l.Push(mod) return 1 } @@ -30,11 +30,11 @@ var osFuncs = map[string]lua.LGFunction{ "date": osDate, } -func osTime(L *lua.LState) int { - if L.GetTop() == 0 { - L.Push(lua.LNumber(time.Now().Unix())) +func osTime(l *lua.LState) int { + if l.GetTop() == 0 { + l.Push(lua.LNumber(time.Now().Unix())) } else { - tbl := L.CheckTable(1) + tbl := l.CheckTable(1) sec := getIntField(tbl, "sec", 0) min := getIntField(tbl, "min", 0) hour := getIntField(tbl, "hour", 12) @@ -47,7 +47,7 @@ func osTime(L *lua.LState) int { if false { print(isdst) } - L.Push(lua.LNumber(t.Unix())) + l.Push(lua.LNumber(t.Unix())) } return 1 } @@ -68,20 +68,20 @@ func getBoolField(tb *lua.LTable, key string, v bool) bool { return v } -func osDate(L *lua.LState) int { +func osDate(l *lua.LState) int { t := time.Now() cfmt := "%c" - if L.GetTop() >= 1 { - cfmt = L.CheckString(1) + if l.GetTop() >= 1 { + cfmt = l.CheckString(1) if strings.HasPrefix(cfmt, "!") { t = time.Now().UTC() cfmt = strings.TrimLeft(cfmt, "!") } - if L.GetTop() >= 2 { - t = time.Unix(L.CheckInt64(2), 0) + if l.GetTop() >= 2 { + t = time.Unix(l.CheckInt64(2), 0) } if strings.HasPrefix(cfmt, "*t") { - ret := L.NewTable() + ret := l.NewTable() ret.RawSetString("year", lua.LNumber(t.Year())) ret.RawSetString("month", lua.LNumber(t.Month())) ret.RawSetString("day", lua.LNumber(t.Day())) @@ -92,11 +92,11 @@ func osDate(L *lua.LState) int { // TODO yday & dst ret.RawSetString("yday", lua.LNumber(0)) ret.RawSetString("isdst", lua.LFalse) - L.Push(ret) + l.Push(ret) return 1 } } - L.Push(lua.LString(strftime(t, cfmt))) + l.Push(lua.LString(strftime(t, cfmt))) return 1 } diff --git a/util/notification/expression/shared/appdetail.go b/util/notification/expression/shared/appdetail.go index bdde222a4268b..e3156ff4a0e44 100644 --- a/util/notification/expression/shared/appdetail.go +++ b/util/notification/expression/shared/appdetail.go @@ -35,26 +35,26 @@ type CustomHelmAppSpec struct { HelmParameterOverrides []v1alpha1.HelmParameter } -func (has CustomHelmAppSpec) GetParameterValueByName(Name string) string { +func (has CustomHelmAppSpec) GetParameterValueByName(name string) string { // Check in overrides first for i := range has.HelmParameterOverrides { - if has.HelmParameterOverrides[i].Name == Name { + if has.HelmParameterOverrides[i].Name == name { return has.HelmParameterOverrides[i].Value } } for i := range has.HelmAppSpec.Parameters { - if has.HelmAppSpec.Parameters[i].Name == Name { + if has.HelmAppSpec.Parameters[i].Name == name { return has.HelmAppSpec.Parameters[i].Value } } return "" } -func (has CustomHelmAppSpec) GetFileParameterPathByName(Name string) string { +func (has CustomHelmAppSpec) GetFileParameterPathByName(name string) string { var path string for i := range has.HelmAppSpec.FileParameters { - if has.HelmAppSpec.FileParameters[i].Name == Name { + if has.HelmAppSpec.FileParameters[i].Name == name { path = has.HelmAppSpec.FileParameters[i].Path break } diff --git a/util/session/sessionmanager.go b/util/session/sessionmanager.go index 16e88665934d0..09ba6aa43cd38 100644 --- a/util/session/sessionmanager.go +++ b/util/session/sessionmanager.go @@ -366,11 +366,9 @@ func (mgr *SessionManager) updateFailureCount(username string, failed bool) { attempt.LastFailed = time.Now() failures[username] = attempt log.Warnf("User %s failed login %d time(s)", username, attempt.FailCount) - } else { - if attempt.FailCount > 0 { - // Forget username for cache size enforcement, since entry in cache was deleted - delete(failures, username) - } + } else if attempt.FailCount > 0 { + // Forget username for cache size enforcement, since entry in cache was deleted + delete(failures, username) } err := mgr.storage.SetLoginAttempts(failures) diff --git a/util/session/sessionmanager_test.go b/util/session/sessionmanager_test.go index 4f0367a82f365..b5e51a977a2c7 100644 --- a/util/session/sessionmanager_test.go +++ b/util/session/sessionmanager_test.go @@ -653,7 +653,7 @@ clientSecret: yyy requestedScopes: ["oidc"] rootCA: | %s -`, oidcTestServer.URL, strings.Replace(string(cert), "\n", "\n ", -1)), +`, oidcTestServer.URL, strings.ReplaceAll(string(cert), "\n", "\n ")), } settingsMgr := settings.NewSettingsManager(context.Background(), getKubeClientWithConfig(dexConfig, nil), "argocd") diff --git a/util/settings/settings_test.go b/util/settings/settings_test.go index 169e4148b9dec..aa78730ace513 100644 --- a/util/settings/settings_test.go +++ b/util/settings/settings_test.go @@ -1450,7 +1450,7 @@ clientSecret: yyy requestedScopes: ["oidc"] rootCA: | %s -`, strings.Replace(string(test.Cert), "\n", "\n ", -1))}, +`, strings.ReplaceAll(string(test.Cert), "\n", "\n "))}, }, { name: "OIDC configured, invalid root CA",