1
0
Fork 0
mirror of https://github.com/kyverno/kyverno.git synced 2024-12-14 11:57:48 +00:00

chore: replace utils.ContainsString with builtin slices.Contains (#5496)

Signed-off-by: Charles-Edouard Brétéché <charles.edouard@nirmata.com>

Signed-off-by: Charles-Edouard Brétéché <charles.edouard@nirmata.com>
Co-authored-by: shuting <shuting@nirmata.com>
This commit is contained in:
Charles-Edouard Brétéché 2022-11-29 09:04:49 +01:00 committed by GitHub
parent bf303f78ad
commit 6f1bd5fff2
No known key found for this signature in database
GPG key ID: 4AEE18F83AFDEB23
12 changed files with 32 additions and 74 deletions

View file

@ -29,9 +29,9 @@ import (
"github.com/kyverno/kyverno/pkg/engine/response"
"github.com/kyverno/kyverno/pkg/openapi"
policy2 "github.com/kyverno/kyverno/pkg/policy"
util "github.com/kyverno/kyverno/pkg/utils"
"github.com/lensesio/tableprinter"
"github.com/spf13/cobra"
"golang.org/x/exp/slices"
corev1 "k8s.io/api/core/v1"
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
"k8s.io/apimachinery/pkg/apis/meta/v1/unstructured"
@ -566,9 +566,9 @@ func buildPolicyResults(engineResponses []*response.EngineResponse, testResults
if resource == resourceName {
var resultsKey string
resultsKey = GetResultKeyAccordingToTestResults(userDefinedPolicyNamespace, test.Policy, test.Rule, test.Namespace, test.Kind, resource)
if !util.ContainsString(rules, test.Rule) {
if !util.ContainsString(rules, "autogen-"+test.Rule) {
if !util.ContainsString(rules, "autogen-cronjob-"+test.Rule) {
if !slices.Contains(rules, test.Rule) {
if !slices.Contains(rules, "autogen-"+test.Rule) {
if !slices.Contains(rules, "autogen-cronjob-"+test.Rule) {
result.Result = policyreportv1alpha2.StatusSkip
} else {
testResults[i].AutoGeneratedRule = "autogen-cronjob"
@ -599,9 +599,9 @@ func buildPolicyResults(engineResponses []*response.EngineResponse, testResults
if test.Policy == policyName && test.Resource == resourceName {
var resultsKey string
resultsKey = GetResultKeyAccordingToTestResults(userDefinedPolicyNamespace, test.Policy, test.Rule, test.Namespace, test.Kind, test.Resource)
if !util.ContainsString(rules, test.Rule) {
if !util.ContainsString(rules, "autogen-"+test.Rule) {
if !util.ContainsString(rules, "autogen-cronjob-"+test.Rule) {
if !slices.Contains(rules, test.Rule) {
if !slices.Contains(rules, "autogen-"+test.Rule) {
if !slices.Contains(rules, "autogen-cronjob-"+test.Rule) {
result.Result = policyreportv1alpha2.StatusSkip
} else {
testResults[i].AutoGeneratedRule = "autogen-cronjob"

View file

@ -7,9 +7,9 @@ import (
"strings"
kyvernov1 "github.com/kyverno/kyverno/api/kyverno/v1"
"github.com/kyverno/kyverno/pkg/utils"
jsonutils "github.com/kyverno/kyverno/pkg/utils/json"
kubeutils "github.com/kyverno/kyverno/pkg/utils/kube"
"golang.org/x/exp/slices"
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
"k8s.io/apimachinery/pkg/util/sets"
)
@ -146,7 +146,7 @@ func GetControllers(meta *metav1.ObjectMeta, spec *kyvernov1.Spec) ([]string, []
// filter supported controllers, keeping only those that have been requested
var activated []string
for _, controller := range supported {
if utils.ContainsString(requested, controller) {
if slices.Contains(requested, controller) {
activated = append(activated, controller)
}
}

View file

@ -29,6 +29,7 @@ import (
"github.com/kyverno/kyverno/pkg/event"
kyvernoutils "github.com/kyverno/kyverno/pkg/utils"
kubeutils "github.com/kyverno/kyverno/pkg/utils/kube"
"golang.org/x/exp/slices"
apierrors "k8s.io/apimachinery/pkg/api/errors"
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
"k8s.io/apimachinery/pkg/apis/meta/v1/unstructured"
@ -320,7 +321,7 @@ func (c *GenerateController) ApplyGeneratePolicy(log logr.Logger, policyContext
continue
}
if !kyvernoutils.ContainsString(applicableRules, rule.Name) {
if !slices.Contains(applicableRules, rule.Name) {
continue
}

View file

@ -12,10 +12,10 @@ import (
"github.com/kyverno/kyverno/pkg/clients/dclient"
"github.com/kyverno/kyverno/pkg/controllers"
"github.com/kyverno/kyverno/pkg/controllers/report/utils"
pkgutils "github.com/kyverno/kyverno/pkg/utils"
controllerutils "github.com/kyverno/kyverno/pkg/utils/controller"
kubeutils "github.com/kyverno/kyverno/pkg/utils/kube"
reportutils "github.com/kyverno/kyverno/pkg/utils/report"
"golang.org/x/exp/slices"
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
"k8s.io/apimachinery/pkg/apis/meta/v1/unstructured"
"k8s.io/apimachinery/pkg/labels"
@ -146,7 +146,7 @@ func (c *controller) updateDynamicWatchers(ctx context.Context) error {
if !reportutils.IsGvkSupported(gvk) {
logger.Info("kind is not supported", "gvk", gvk)
} else {
if pkgutils.ContainsString(apiResource.Verbs, "list") && pkgutils.ContainsString(apiResource.Verbs, "watch") {
if slices.Contains(apiResource.Verbs, "list") && slices.Contains(apiResource.Verbs, "watch") {
gvrs[gvk] = gvr
} else {
logger.Info("list/watch not supported for kind", "kind", kind)

View file

@ -4,7 +4,6 @@ import (
"strings"
kyvernov1 "github.com/kyverno/kyverno/api/kyverno/v1"
"github.com/kyverno/kyverno/pkg/utils"
"golang.org/x/exp/slices"
admissionregistrationv1 "k8s.io/api/admissionregistration/v1"
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
@ -91,7 +90,7 @@ func hasWildcard(policies ...kyvernov1.PolicyInterface) bool {
for _, policy := range policies {
spec := policy.GetSpec()
for _, rule := range spec.Rules {
if kinds := rule.MatchResources.GetKinds(); utils.ContainsString(kinds, "*") {
if kinds := rule.MatchResources.GetKinds(); slices.Contains(kinds, "*") {
return true
}
}

View file

@ -19,6 +19,7 @@ import (
"github.com/kyverno/kyverno/pkg/utils"
wildcard "github.com/kyverno/kyverno/pkg/utils/wildcard"
"github.com/pkg/errors"
"golang.org/x/exp/slices"
"golang.org/x/text/cases"
"golang.org/x/text/language"
authenticationv1 "k8s.io/api/authentication/v1"
@ -270,7 +271,7 @@ func matchSubjects(ruleSubjects []rbacv1.Subject, userInfo authenticationv1.User
return true
}
case "User", "Group":
if utils.ContainsString(userGroups, subject.Name) {
if slices.Contains(userGroups, subject.Name) {
return true
}
}

View file

@ -11,7 +11,7 @@ import (
openapiv2 "github.com/google/gnostic/openapiv2"
"github.com/kyverno/kyverno/data"
"github.com/kyverno/kyverno/pkg/logging"
"github.com/kyverno/kyverno/pkg/utils"
"golang.org/x/exp/slices"
"gopkg.in/yaml.v3"
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
)
@ -204,7 +204,7 @@ func setPreferredVersions(kindToAPIVersions map[string]apiVersions, preferredAPI
preferredGV := preferredAPIResourcesList.GroupVersion
preferredGVK := preferredGV + "/" + resource.Kind
if utils.ContainsString(versions.gvks, preferredGVK) {
if slices.Contains(versions.gvks, preferredGVK) {
v := kindToAPIVersions[kind]
// if a Kind belongs to multiple groups, the first group/version

View file

@ -9,7 +9,7 @@ import (
"github.com/kyverno/kyverno/pkg/policy/generate"
"github.com/kyverno/kyverno/pkg/policy/mutate"
"github.com/kyverno/kyverno/pkg/policy/validate"
"github.com/kyverno/kyverno/pkg/utils"
"golang.org/x/exp/slices"
)
// Validation provides methods to validate a rule
@ -61,7 +61,7 @@ func validateActions(idx int, rule *kyvernov1.Rule, client dclient.Interface, mo
}
}
if utils.ContainsString(rule.MatchResources.Kinds, rule.Generation.Kind) {
if slices.Contains(rule.MatchResources.Kinds, rule.Generation.Kind) {
return fmt.Errorf("generation kind and match resource kind should not be the same")
}
}

View file

@ -24,8 +24,8 @@ import (
"github.com/kyverno/kyverno/pkg/config"
"github.com/kyverno/kyverno/pkg/event"
"github.com/kyverno/kyverno/pkg/metrics"
"github.com/kyverno/kyverno/pkg/utils"
kubeutils "github.com/kyverno/kyverno/pkg/utils/kube"
"golang.org/x/exp/slices"
corev1 "k8s.io/api/core/v1"
"k8s.io/apimachinery/pkg/api/errors"
"k8s.io/apimachinery/pkg/apis/meta/v1/unstructured"
@ -441,7 +441,7 @@ func missingAutoGenRules(policy kyvernov1.PolicyInterface, log logr.Logger) bool
ruleCount = 2
}
if len(res) > 1 {
if utils.ContainsString(res, "CronJob") {
if slices.Contains(res, "CronJob") {
ruleCount = 3
} else {
ruleCount = 2

View file

@ -25,6 +25,7 @@ import (
"github.com/kyverno/kyverno/pkg/utils"
kubeutils "github.com/kyverno/kyverno/pkg/utils/kube"
"github.com/pkg/errors"
"golang.org/x/exp/slices"
"k8s.io/apiextensions-apiserver/pkg/apis/apiextensions"
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
"k8s.io/apimachinery/pkg/apis/meta/v1/unstructured"
@ -277,7 +278,7 @@ func Validate(policy kyvernov1.PolicyInterface, client dclient.Interface, mock b
if wildcardErr != nil {
return warnings, wildcardErr
}
if !utils.ContainsString(value.ResourceDescription.Kinds, "*") {
if !slices.Contains(value.ResourceDescription.Kinds, "*") {
err := validateKinds(value.ResourceDescription.Kinds, mock, client, policy)
if err != nil {
return warnings, errors.Wrapf(err, "the kind defined in the any match resource is invalid")
@ -289,7 +290,7 @@ func Validate(policy kyvernov1.PolicyInterface, client dclient.Interface, mock b
if wildcardErr != nil {
return warnings, wildcardErr
}
if !utils.ContainsString(value.ResourceDescription.Kinds, "*") {
if !slices.Contains(value.ResourceDescription.Kinds, "*") {
err := validateKinds(value.ResourceDescription.Kinds, mock, client, policy)
if err != nil {
return warnings, errors.Wrapf(err, "the kind defined in the all match resource is invalid")
@ -301,7 +302,7 @@ func Validate(policy kyvernov1.PolicyInterface, client dclient.Interface, mock b
if wildcardErr != nil {
return warnings, wildcardErr
}
if !utils.ContainsString(value.ResourceDescription.Kinds, "*") {
if !slices.Contains(value.ResourceDescription.Kinds, "*") {
err := validateKinds(value.ResourceDescription.Kinds, mock, client, policy)
if err != nil {
return warnings, errors.Wrapf(err, "the kind defined in the any exclude resource is invalid")
@ -313,7 +314,7 @@ func Validate(policy kyvernov1.PolicyInterface, client dclient.Interface, mock b
if wildcardErr != nil {
return warnings, wildcardErr
}
if !utils.ContainsString(value.ResourceDescription.Kinds, "*") {
if !slices.Contains(value.ResourceDescription.Kinds, "*") {
err := validateKinds(value.ResourceDescription.Kinds, mock, client, policy)
if err != nil {
return warnings, errors.Wrapf(err, "the kind defined in the all exclude resource is invalid")
@ -321,7 +322,7 @@ func Validate(policy kyvernov1.PolicyInterface, client dclient.Interface, mock b
}
}
if !utils.ContainsString(rule.MatchResources.Kinds, "*") {
if !slices.Contains(rule.MatchResources.Kinds, "*") {
err := validateKinds(rule.MatchResources.Kinds, mock, client, policy)
if err != nil {
return warnings, errors.Wrapf(err, "match resource kind is invalid")
@ -1139,7 +1140,7 @@ func jsonPatchOnPod(rule kyvernov1.Rule) bool {
return false
}
if utils.ContainsString(rule.MatchResources.Kinds, "Pod") && rule.Mutation.PatchesJSON6902 != "" {
if slices.Contains(rule.MatchResources.Kinds, "Pod") && rule.Mutation.PatchesJSON6902 != "" {
return true
}
@ -1163,13 +1164,13 @@ func podControllerAutoGenExclusion(policy kyvernov1.PolicyInterface) bool {
// validateWildcard check for an Match/Exclude block contains "*"
func validateWildcard(kinds []string, spec *kyvernov1.Spec, rule kyvernov1.Rule) error {
if utils.ContainsString(kinds, "*") && spec.BackgroundProcessingEnabled() {
if slices.Contains(kinds, "*") && spec.BackgroundProcessingEnabled() {
return fmt.Errorf("wildcard policy not allowed in background mode. Set spec.background=false to disable background mode for this policy rule ")
}
if utils.ContainsString(kinds, "*") && len(kinds) > 1 {
if slices.Contains(kinds, "*") && len(kinds) > 1 {
return fmt.Errorf("wildard policy can not deal more than one kind")
}
if utils.ContainsString(kinds, "*") {
if slices.Contains(kinds, "*") {
if rule.HasGenerate() || rule.HasVerifyImages() || rule.Validation.ForEachValidation != nil {
return fmt.Errorf("wildcard policy does not support rule type")
}

View file

@ -86,11 +86,6 @@ func ContainsNamepace(patterns []string, ns string) bool {
return contains(patterns, ns, comparePatterns)
}
// ContainsString checks if the string is contained in the list
func ContainsString(list []string, element string) bool {
return contains(list, element, compareString)
}
func ContainsWildcardPatterns(patterns []string, key string) bool {
return contains(patterns, key, comparePatterns)
}
@ -99,10 +94,6 @@ func comparePatterns(pattern, ns string) bool {
return wildcard.Match(pattern, ns)
}
func compareString(str, name string) bool {
return str == name
}
// CRDsInstalled checks if the Kyverno CRDs are installed or not
func CRDsInstalled(discovery dclient.IDiscovery) bool {
kyvernoCRDs := []string{"ClusterPolicy", "ClusterPolicyReport", "PolicyReport", "AdmissionReport", "BackgroundScanReport", "ClusterAdmissionReport", "ClusterBackgroundScanReport"}
@ -328,13 +319,11 @@ func SliceContains(slice []string, values ...string) bool {
for _, sliceElement := range slice {
sliceElementsMap[sliceElement] = true
}
for _, value := range values {
if sliceElementsMap[value] {
return true
}
}
return false
}

View file

@ -36,39 +36,6 @@ func Test_OriginalSliceMustNotBeChanged(t *testing.T) {
assert.Equal(t, originalSlice[0], 3711)
}
func Test_allEmpty(t *testing.T) {
var list []string
var element string
res := ContainsString(list, element)
assert.Assert(t, res == false)
}
func Test_emptyList(t *testing.T) {
var list []string
element := "foo"
res := ContainsString(list, element)
assert.Assert(t, res == false)
}
func Test_emptyElement(t *testing.T) {
list := []string{"foo", "bar"}
var element string
res := ContainsString(list, element)
assert.Assert(t, res == false)
}
func Test_emptyElementInList(t *testing.T) {
list := []string{"foo", "bar", ""}
var element string
res := ContainsString(list, element)
assert.Assert(t, res == true)
list = []string{"foo", "bar", "bar"}
element = "bar"
res = ContainsString(list, element)
assert.Assert(t, res == true)
}
func Test_containsNs(t *testing.T) {
var patterns []string
var res bool