diff --git a/.golangci.yml b/.golangci.yml index c35094d46116..0382330dd444 100644 --- a/.golangci.yml +++ b/.golangci.yml @@ -38,6 +38,7 @@ linters: - unused - wastedassign - whitespace + - prealloc run: timeout: 15m diff --git a/cmd/cli/kubectl-kyverno/commands/apply/command.go b/cmd/cli/kubectl-kyverno/commands/apply/command.go index 4a7b8578a7f3..2c51a4f385a7 100644 --- a/cmd/cli/kubectl-kyverno/commands/apply/command.go +++ b/cmd/cli/kubectl-kyverno/commands/apply/command.go @@ -264,7 +264,7 @@ func (c *ApplyCommandConfig) applyPolicytoResource( } var rc processor.ResultCounts // validate policies - var validPolicies []kyvernov1.PolicyInterface + validPolicies := make([]kyvernov1.PolicyInterface, 0, len(policies)) for _, pol := range policies { // TODO we should return this info to the caller _, err := policyvalidation.Validate(pol, nil, nil, nil, true, config.KyvernoUserName(config.KyvernoServiceAccountName())) diff --git a/cmd/cli/kubectl-kyverno/commands/fix/policy/options.go b/cmd/cli/kubectl-kyverno/commands/fix/policy/options.go index c8f3e203201f..95a0bd96d727 100644 --- a/cmd/cli/kubectl-kyverno/commands/fix/policy/options.go +++ b/cmd/cli/kubectl-kyverno/commands/fix/policy/options.go @@ -68,7 +68,7 @@ func (o options) processFile(out io.Writer, path string) { if len(policies) == 0 { return } - var fixed []kyvernov1.PolicyInterface + fixed := make([]kyvernov1.PolicyInterface, 0, len(policies)) for _, policy := range policies { copy := policy.CreateDeepCopy() fmt.Fprintf(out, "Processing file (%s)...\n", path) diff --git a/cmd/cli/kubectl-kyverno/commands/jp/parse/command.go b/cmd/cli/kubectl-kyverno/commands/jp/parse/command.go index fd468c1d4df2..0a14582f8169 100644 --- a/cmd/cli/kubectl-kyverno/commands/jp/parse/command.go +++ b/cmd/cli/kubectl-kyverno/commands/jp/parse/command.go @@ -62,7 +62,7 @@ func loadFile(cmd *cobra.Command, file string) (string, error) { } func loadExpressions(cmd *cobra.Command, args []string, files []string) ([]string, error) { - var expressions []string + expressions := make([]string, 0, len(args)) expressions = append(expressions, args...) for _, file := range files { expression, err := loadFile(cmd, file) diff --git a/cmd/cli/kubectl-kyverno/commands/jp/query/command.go b/cmd/cli/kubectl-kyverno/commands/jp/query/command.go index f2547742fe62..ab3ea5c76e8e 100644 --- a/cmd/cli/kubectl-kyverno/commands/jp/query/command.go +++ b/cmd/cli/kubectl-kyverno/commands/jp/query/command.go @@ -107,7 +107,7 @@ func readQuery(cmd *cobra.Command) (string, error) { } func loadQueries(cmd *cobra.Command, args []string, files []string) ([]string, error) { - var queries []string + queries := make([]string, 0, len(args)) queries = append(queries, args...) for _, file := range files { query, err := loadFile(cmd, file) diff --git a/cmd/cli/kubectl-kyverno/commands/json/scan/options.go b/cmd/cli/kubectl-kyverno/commands/json/scan/options.go index 7b857313b749..0b0c2cc2e9e8 100644 --- a/cmd/cli/kubectl-kyverno/commands/json/scan/options.go +++ b/cmd/cli/kubectl-kyverno/commands/json/scan/options.go @@ -76,7 +76,7 @@ func (c *options) run(cmd *cobra.Command, _ []string) error { } out.println("Running", "(", "evaluating", len(resources), pluralize.Pluralize(len(resources), "resource", "resources"), "against", len(policies), pluralize.Pluralize(len(policies), "policy", "policies"), ")", "...") e := jsonengine.New() - var responses []jsonengine.Response + responses := make([]jsonengine.Response, 0, len(resources)) for _, resource := range resources { responses = append(responses, e.Run(context.Background(), jsonengine.Request{ Resource: resource, diff --git a/cmd/cli/kubectl-kyverno/commands/test/command.go b/cmd/cli/kubectl-kyverno/commands/test/command.go index 33ee9609891f..2fafc8dd90d9 100644 --- a/cmd/cli/kubectl-kyverno/commands/test/command.go +++ b/cmd/cli/kubectl-kyverno/commands/test/command.go @@ -183,7 +183,7 @@ func checkResult(test v1alpha1.TestResult, fs billy.Filesystem, resoucePath stri } func lookupEngineResponses(test v1alpha1.TestResult, resourceName string, responses ...engineapi.EngineResponse) []engineapi.EngineResponse { - var matches []engineapi.EngineResponse + matches := make([]engineapi.EngineResponse, 0, len(responses)) for _, response := range responses { policy := response.Policy() resource := response.Resource diff --git a/cmd/cli/kubectl-kyverno/commands/test/test.go b/cmd/cli/kubectl-kyverno/commands/test/test.go index 920d3d6c3abc..921477d7b237 100644 --- a/cmd/cli/kubectl-kyverno/commands/test/test.go +++ b/cmd/cli/kubectl-kyverno/commands/test/test.go @@ -142,7 +142,7 @@ func runTest(out io.Writer, testCase test.TestCase, registryAccess bool, auditWa } } // validate policies - var validPolicies []kyvernov1.PolicyInterface + validPolicies := make([]kyvernov1.PolicyInterface, 0, len(policies)) for _, pol := range policies { // TODO we should return this info to the caller _, err := policyvalidation.Validate(pol, nil, nil, nil, true, config.KyvernoUserName(config.KyvernoServiceAccountName())) diff --git a/cmd/cli/kubectl-kyverno/fix/test.go b/cmd/cli/kubectl-kyverno/fix/test.go index f629fb4f525e..1409aa2ea625 100644 --- a/cmd/cli/kubectl-kyverno/fix/test.go +++ b/cmd/cli/kubectl-kyverno/fix/test.go @@ -31,7 +31,7 @@ func FixTest(test v1alpha1.Test, compress bool) (v1alpha1.Test, []string, error) if len(test.Resources) == 0 { messages = append(messages, "test has no resources") } - var results []v1alpha1.TestResult + results := make([]v1alpha1.TestResult, 0, len(test.Results)) for _, result := range test.Results { if result.Resource != "" && len(result.Resources) != 0 { messages = append(messages, "test result should not use both `resource` and `resources` fields") diff --git a/cmd/cli/kubectl-kyverno/output/table/table.go b/cmd/cli/kubectl-kyverno/output/table/table.go index 7c2f34033983..01af1aa3b3dd 100644 --- a/cmd/cli/kubectl-kyverno/output/table/table.go +++ b/cmd/cli/kubectl-kyverno/output/table/table.go @@ -20,7 +20,7 @@ func (t *Table) Rows(detailed bool) interface{} { if detailed { return t.RawRows } - var rows []RowCompact + rows := make([]RowCompact, 0, len(t.RawRows)) for _, row := range t.RawRows { rows = append(rows, row.RowCompact) } diff --git a/cmd/cli/kubectl-kyverno/output/table/table_test.go b/cmd/cli/kubectl-kyverno/output/table/table_test.go index 7c7946196592..b15d39539fb1 100644 --- a/cmd/cli/kubectl-kyverno/output/table/table_test.go +++ b/cmd/cli/kubectl-kyverno/output/table/table_test.go @@ -85,7 +85,6 @@ func TestTable_AddFailed(t *testing.T) { func TestTable_Rows(t *testing.T) { var nilRows []Row - var nilCompactRows []RowCompact tests := []struct { name string RawRows []Row @@ -93,7 +92,7 @@ func TestTable_Rows(t *testing.T) { want interface{} }{{ name: "nil", - want: nilCompactRows, + want: []RowCompact{}, }, { name: "nil - detailed", detailed: true, @@ -186,13 +185,13 @@ func TestTable_Rows(t *testing.T) { Message: "message2", }}, }} - for _, tt := range tests { + for i, tt := range tests { t.Run(tt.name, func(t *testing.T) { tr := &Table{ RawRows: tt.RawRows, } if got := tr.Rows(tt.detailed); !reflect.DeepEqual(got, tt.want) { - t.Errorf("Table.Rows() = %v, want %v", got, tt.want) + t.Errorf("test=%v, Table.Rows() = %v, want %v", i, got, tt.want) } }) } diff --git a/cmd/cli/kubectl-kyverno/path/path.go b/cmd/cli/kubectl-kyverno/path/path.go index 72769bf54eeb..cce6ab35c234 100644 --- a/cmd/cli/kubectl-kyverno/path/path.go +++ b/cmd/cli/kubectl-kyverno/path/path.go @@ -16,7 +16,7 @@ func GetFullPaths(paths []string, basePath string, git bool) []string { if git { return paths } - var out []string + out := make([]string, 0, len(paths)) for _, path := range paths { out = append(out, GetFullPath(path, basePath)) } diff --git a/cmd/cli/kubectl-kyverno/processor/policy_processor.go b/cmd/cli/kubectl-kyverno/processor/policy_processor.go index 34663a75cd10..75be95fc7b66 100644 --- a/cmd/cli/kubectl-kyverno/processor/policy_processor.go +++ b/cmd/cli/kubectl-kyverno/processor/policy_processor.go @@ -104,7 +104,7 @@ func (p *PolicyProcessor) ApplyPoliciesOnResource() ([]engineapi.EngineResponse, } } resPath := fmt.Sprintf("%s/%s/%s", resource.GetNamespace(), resource.GetKind(), resource.GetName()) - var responses []engineapi.EngineResponse + responses := make([]engineapi.EngineResponse, 0, len(p.Policies)) // mutate for _, policy := range p.Policies { if !policy.GetSpec().HasMutate() { diff --git a/cmd/cli/kubectl-kyverno/processor/vap_processor.go b/cmd/cli/kubectl-kyverno/processor/vap_processor.go index 58f219932311..414bc00072ca 100644 --- a/cmd/cli/kubectl-kyverno/processor/vap_processor.go +++ b/cmd/cli/kubectl-kyverno/processor/vap_processor.go @@ -19,7 +19,7 @@ type ValidatingAdmissionPolicyProcessor struct { } func (p *ValidatingAdmissionPolicyProcessor) ApplyPolicyOnResource() ([]engineapi.EngineResponse, error) { - var responses []engineapi.EngineResponse + responses := make([]engineapi.EngineResponse, 0, len(p.Policies)) for _, policy := range p.Policies { policyData := validatingadmissionpolicy.NewPolicyData(policy) for _, binding := range p.Bindings { diff --git a/cmd/cli/kubectl-kyverno/resource/resource.go b/cmd/cli/kubectl-kyverno/resource/resource.go index cd5ccd2da480..b80648415eee 100644 --- a/cmd/cli/kubectl-kyverno/resource/resource.go +++ b/cmd/cli/kubectl-kyverno/resource/resource.go @@ -19,11 +19,11 @@ import ( ) func GetUnstructuredResources(resourceBytes []byte) ([]*unstructured.Unstructured, error) { - var resources []*unstructured.Unstructured documents, err := yamlutils.SplitDocuments(resourceBytes) if err != nil { return nil, err } + resources := make([]*unstructured.Unstructured, 0, len(documents)) for _, document := range documents { resource, err := YamlToUnstructured(document) if err != nil { diff --git a/cmd/cli/kubectl-kyverno/utils/common/kyverno_resources_types.go b/cmd/cli/kubectl-kyverno/utils/common/kyverno_resources_types.go index 45aae6fa4e7c..a5884ffb83eb 100644 --- a/cmd/cli/kubectl-kyverno/utils/common/kyverno_resources_types.go +++ b/cmd/cli/kubectl-kyverno/utils/common/kyverno_resources_types.go @@ -20,7 +20,6 @@ func (r *KyvernoResources) FetchResourcesFromPolicy(out io.Writer, resourcePaths var err error resourceTypesMap := make(map[schema.GroupVersionKind]bool) - var resourceTypes []schema.GroupVersionKind var subresourceMap map[schema.GroupVersionKind]v1alpha1.Subresource for _, policy := range r.policies { @@ -33,6 +32,7 @@ func (r *KyvernoResources) FetchResourcesFromPolicy(out io.Writer, resourcePaths } } + resourceTypes := make([]schema.GroupVersionKind, 0, len(resourceTypesMap)) for kind := range resourceTypesMap { resourceTypes = append(resourceTypes, kind) } diff --git a/cmd/cli/kubectl-kyverno/utils/common/validating_admission_resources.go b/cmd/cli/kubectl-kyverno/utils/common/validating_admission_resources.go index ff60f5a733e3..12b7982ce95e 100644 --- a/cmd/cli/kubectl-kyverno/utils/common/validating_admission_resources.go +++ b/cmd/cli/kubectl-kyverno/utils/common/validating_admission_resources.go @@ -19,7 +19,6 @@ func (r *ValidatingAdmissionResources) FetchResourcesFromPolicy(out io.Writer, r var err error resourceTypesMap := make(map[schema.GroupVersionKind]bool) - var resourceTypes []schema.GroupVersionKind var subresourceMap map[schema.GroupVersionKind]v1alpha1.Subresource for _, policy := range r.policies { @@ -33,6 +32,7 @@ func (r *ValidatingAdmissionResources) FetchResourcesFromPolicy(out io.Writer, r } } + resourceTypes := make([]schema.GroupVersionKind, 0, len(resourceTypesMap)) for kind := range resourceTypesMap { resourceTypes = append(resourceTypes, kind) } diff --git a/pkg/autogen/autogen.go b/pkg/autogen/autogen.go index 337bb08aa69f..4d6db9f2bfde 100644 --- a/pkg/autogen/autogen.go +++ b/pkg/autogen/autogen.go @@ -42,8 +42,8 @@ func checkAutogenSupport(needed *bool, subjects ...kyvernov1.ResourceDescription // stripCronJob removes CronJob from controllers func stripCronJob(controllers string) string { - var newControllers []string controllerArr := splitKinds(controllers, ",") + newControllers := make([]string, 0, len(controllerArr)) for _, c := range controllerArr { if c == PodControllerCronJob { continue diff --git a/pkg/controllers/report/aggregate/controller.go b/pkg/controllers/report/aggregate/controller.go index 2cc6933f0d99..f5aefb3a56db 100644 --- a/pkg/controllers/report/aggregate/controller.go +++ b/pkg/controllers/report/aggregate/controller.go @@ -419,7 +419,7 @@ func (c *controller) backReconcile(ctx context.Context, logger logr.Logger, _, n reports = append(reports, ephemeralReports...) merged := map[string]policyreportv1alpha2.PolicyReportResult{} mergeReports(policyMap, vapMap, merged, types.UID(name), reports...) - var results []policyreportv1alpha2.PolicyReportResult + results := make([]policyreportv1alpha2.PolicyReportResult, 0, len(merged)) for _, result := range merged { results = append(results, result) } diff --git a/pkg/controllers/report/background/controller.go b/pkg/controllers/report/background/controller.go index e464e604b3b8..eb3fa59058c5 100644 --- a/pkg/controllers/report/background/controller.go +++ b/pkg/controllers/report/background/controller.go @@ -503,7 +503,7 @@ func (c *controller) reconcile(ctx context.Context, log logr.Logger, key, namesp } // load background policies kyvernoPolicies = utils.RemoveNonBackgroundPolicies(kyvernoPolicies...) - var policies []engineapi.GenericPolicy + policies := make([]engineapi.GenericPolicy, 0, len(kyvernoPolicies)) for _, pol := range kyvernoPolicies { policies = append(policies, engineapi.NewKyvernoPolicy(pol)) } diff --git a/pkg/controllers/webhook/controller.go b/pkg/controllers/webhook/controller.go index cd6d78930fa7..206fb52bf197 100644 --- a/pkg/controllers/webhook/controller.go +++ b/pkg/controllers/webhook/controller.go @@ -737,7 +737,7 @@ func (c *controller) buildResourceMutatingWebhookConfiguration(ctx context.Conte } func (c *controller) buildResourceMutatingWebhookRules(caBundle []byte, webhookCfg config.WebhookConfig, sideEffects *admissionregistrationv1.SideEffectClass, webhooks []*webhook, mapResourceToOpnType map[string][]admissionregistrationv1.OperationType) []admissionregistrationv1.MutatingWebhook { - var mutatingWebhooks []admissionregistrationv1.MutatingWebhook + mutatingWebhooks := make([]admissionregistrationv1.MutatingWebhook, 0, len(webhooks)) for _, webhook := range webhooks { if webhook.isEmpty() { continue @@ -911,7 +911,7 @@ func (c *controller) buildResourceValidatingWebhookConfiguration(ctx context.Con } func (c *controller) buildResourceValidatingWebhookRules(caBundle []byte, webhookCfg config.WebhookConfig, sideEffects *admissionregistrationv1.SideEffectClass, webhooks []*webhook, mapResourceToOpnType map[string][]admissionregistrationv1.OperationType) []admissionregistrationv1.ValidatingWebhook { - var validatingWebhooks []admissionregistrationv1.ValidatingWebhook + validatingWebhooks := make([]admissionregistrationv1.ValidatingWebhook, 0, len(webhooks)) for _, webhook := range webhooks { if webhook.isEmpty() { continue diff --git a/pkg/controllers/webhook/utils.go b/pkg/controllers/webhook/utils.go index 9258aa2163f8..95b0c9b140c7 100644 --- a/pkg/controllers/webhook/utils.go +++ b/pkg/controllers/webhook/utils.go @@ -72,7 +72,7 @@ func newWebhookPerPolicy(timeout int32, failurePolicy admissionregistrationv1.Fa } func (wh *webhook) buildRulesWithOperations(final map[string][]admissionregistrationv1.OperationType, defaultOpn []admissionregistrationv1.OperationType) []admissionregistrationv1.RuleWithOperations { - var rules []admissionregistrationv1.RuleWithOperations + rules := make([]admissionregistrationv1.RuleWithOperations, 0, len(wh.rules)) for gv, resources := range wh.rules { firstResource := sets.List(resources)[0] diff --git a/pkg/cosign/cosign.go b/pkg/cosign/cosign.go index bfa698c7eedb..b9363ee4424f 100644 --- a/pkg/cosign/cosign.go +++ b/pkg/cosign/cosign.go @@ -471,7 +471,7 @@ func decodePEM(raw []byte, signatureAlgorithm crypto.Hash) (signature.Verifier, } func extractPayload(verified []oci.Signature) ([]payload.SimpleContainerImage, error) { - var sigPayloads []payload.SimpleContainerImage + sigPayloads := make([]payload.SimpleContainerImage, 0, len(verified)) for _, sig := range verified { pld, err := sig.Payload() if err != nil { diff --git a/pkg/engine/adapters/dclient.go b/pkg/engine/adapters/dclient.go index bf4b7e66c3eb..384574e69178 100644 --- a/pkg/engine/adapters/dclient.go +++ b/pkg/engine/adapters/dclient.go @@ -30,7 +30,7 @@ func (a *dclientAdapter) GetResources(ctx context.Context, group, version, kind, if err != nil { return nil, err } - var result []engineapi.Resource + result := make([]engineapi.Resource, 0, len(resources)) for _, resource := range resources { result = append(result, engineapi.Resource{ Group: resource.Group, diff --git a/pkg/engine/handlers/mutation/load_targets.go b/pkg/engine/handlers/mutation/load_targets.go index bcdbf3caa2fe..28ceb71daaca 100644 --- a/pkg/engine/handlers/mutation/load_targets.go +++ b/pkg/engine/handlers/mutation/load_targets.go @@ -82,7 +82,6 @@ func resolveSpec(i int, target kyvernov1.TargetResourceSpec, ctx engineapi.Polic } func getTargets(ctx context.Context, client engineapi.Client, target kyvernov1.ResourceSpec, policyCtx engineapi.PolicyContext) ([]resourceInfo, error) { - var targetObjects []resourceInfo namespace := target.Namespace name := target.Name policy := policyCtx.Policy() @@ -95,6 +94,7 @@ func getTargets(ctx context.Context, client engineapi.Client, target kyvernov1.R if err != nil { return nil, err } + targetObjects := make([]resourceInfo, 0, len(resources)) for _, resource := range resources { targetObjects = append(targetObjects, resourceInfo{ unstructured: resource.Unstructured, diff --git a/pkg/engine/handlers/validation/validate_pss.go b/pkg/engine/handlers/validation/validate_pss.go index 1d60a8f5a58f..991f07ff2ffc 100644 --- a/pkg/engine/handlers/validation/validate_pss.go +++ b/pkg/engine/handlers/validation/validate_pss.go @@ -162,7 +162,7 @@ func addImages(checks []pssutils.PSSCheckResult, imageInfos map[string]map[strin // return image references for containers func getImages(containerNames []string, imageInfos map[string]map[string]api.ImageInfo) []string { - var images []string + images := make([]string, 0, len(containerNames)) for _, cn := range containerNames { image := getImageReference(cn, imageInfos) images = append(images, image) diff --git a/pkg/engine/internal/imageverifier.go b/pkg/engine/internal/imageverifier.go index daf2bf1e4d40..5df45683597e 100644 --- a/pkg/engine/internal/imageverifier.go +++ b/pkg/engine/internal/imageverifier.go @@ -138,7 +138,7 @@ func isImageVerified(resource unstructured.Unstructured, image string, log logr. } func ExpandStaticKeys(attestorSet kyvernov1.AttestorSet) kyvernov1.AttestorSet { - var entries []kyvernov1.Attestor + entries := make([]kyvernov1.Attestor, 0, len(attestorSet.Entries)) for _, e := range attestorSet.Entries { if e.Keys != nil { keys := splitPEM(e.Keys.PublicKeys) @@ -165,7 +165,7 @@ func splitPEM(pem string) []string { } func createStaticKeyAttestors(keys []string) []kyvernov1.Attestor { - var attestors []kyvernov1.Attestor + attestors := make([]kyvernov1.Attestor, 0, len(keys)) for _, k := range keys { a := kyvernov1.Attestor{ Keys: &kyvernov1.StaticKeyAttestor{ @@ -179,7 +179,7 @@ func createStaticKeyAttestors(keys []string) []kyvernov1.Attestor { func buildStatementMap(statements []map[string]interface{}) (map[string][]map[string]interface{}, []string) { results := map[string][]map[string]interface{}{} - var predicateTypes []string + predicateTypes := make([]string, 0, len(statements)) for _, s := range statements { predicateType := s["type"].(string) if results[predicateType] != nil { diff --git a/pkg/engine/jmespath/functionentry.go b/pkg/engine/jmespath/functionentry.go index cb702fe15d5f..0bd90fa4ca9a 100644 --- a/pkg/engine/jmespath/functionentry.go +++ b/pkg/engine/jmespath/functionentry.go @@ -32,7 +32,7 @@ func (f FunctionEntry) String() string { if f.Name == "" { return "" } - var args []string + args := make([]string, 0, len(f.Arguments)) for _, a := range f.Arguments { var aTypes []string for _, t := range a.Types { @@ -40,7 +40,7 @@ func (f FunctionEntry) String() string { } args = append(args, strings.Join(aTypes, "|")) } - var returnArgs []string + returnArgs := make([]string, 0, len(f.ReturnType)) for _, ra := range f.ReturnType { returnArgs = append(returnArgs, string(ra)) } diff --git a/pkg/event/events.go b/pkg/event/events.go index 2383fcd55e35..89bdc241ee63 100644 --- a/pkg/event/events.go +++ b/pkg/event/events.go @@ -192,7 +192,7 @@ func NewBackgroundFailedEvent(err error, policy kyvernov1.PolicyInterface, rule } func NewBackgroundSuccessEvent(source Source, policy kyvernov1.PolicyInterface, resources []kyvernov1.ResourceSpec) []Info { - var events []Info + events := make([]Info, 0, len(resources)) msg := "resource generated" action := ResourceGenerated if source == MutateExistingController { diff --git a/pkg/informers/helpers.go b/pkg/informers/helpers.go index 1805bdffc6fd..9963ab989ef9 100644 --- a/pkg/informers/helpers.go +++ b/pkg/informers/helpers.go @@ -20,7 +20,7 @@ func StartInformers(ctx context.Context, informers ...informer) { } func WaitForCacheSync(ctx context.Context, logger logr.Logger, informers ...informer) bool { - var cacheSyncs []cache.InformerSynced + cacheSyncs := make([]cache.InformerSynced, 0, len(informers)) for i := range informers { cacheSyncs = append(cacheSyncs, informers[i].Informer().HasSynced) } diff --git a/pkg/policy/utils.go b/pkg/policy/utils.go index 6429b35ef0d2..9d6a1ab85903 100644 --- a/pkg/policy/utils.go +++ b/pkg/policy/utils.go @@ -21,7 +21,7 @@ func fetchUniqueKinds(rule kyvernov1.Rule) []string { } func convertlist(ulists []unstructured.Unstructured) []*unstructured.Unstructured { - var result []*unstructured.Unstructured + result := make([]*unstructured.Unstructured, 0, len(ulists)) for _, list := range ulists { result = append(result, list.DeepCopy()) } diff --git a/pkg/pss/evaluate.go b/pkg/pss/evaluate.go index 9fea6bd41d8e..52ac14f5789d 100644 --- a/pkg/pss/evaluate.go +++ b/pkg/pss/evaluate.go @@ -147,7 +147,7 @@ func exemptExclusions(defaultCheckResults, excludeCheckResults []pssutils.PSSChe } } - var newDefaultCheckResults []pssutils.PSSCheckResult + newDefaultCheckResults := make([]pssutils.PSSCheckResult, 0, len(defaultCheckResultsMap)) for _, result := range defaultCheckResultsMap { newDefaultCheckResults = append(newDefaultCheckResults, result) } @@ -189,7 +189,7 @@ func parseField(field string) (string, []int, string, bool) { matchesIdx := regexIndex.FindAllStringSubmatch(field, -1) matchesStr := regexStr.FindAllString(field, -1) field = regexIndex.ReplaceAllString(field, "*") - var indexes []int + indexes := make([]int, 0, len(matchesIdx)) for _, match := range matchesIdx { index, _ := strconv.Atoi(match[0]) indexes = append(indexes, index) diff --git a/pkg/utils/api/image.go b/pkg/utils/api/image.go index 6e9e4def1e75..8b43f54f5e3f 100644 --- a/pkg/utils/api/image.go +++ b/pkg/utils/api/image.go @@ -131,7 +131,7 @@ func extract( } func BuildStandardExtractors(tags ...string) []imageExtractor { - var extractors []imageExtractor + extractors := make([]imageExtractor, 0, 3) for _, tag := range []string{"initContainers", "containers", "ephemeralContainers"} { var t []string t = append(t, tags...) diff --git a/pkg/utils/json/utils.go b/pkg/utils/json/utils.go index b9aeca5f9e6c..0dc85aef7d70 100644 --- a/pkg/utils/json/utils.go +++ b/pkg/utils/json/utils.go @@ -12,7 +12,7 @@ func JoinPatches(patches ...[]byte) []byte { return nil } - var patchOperations []string + patchOperations := make([]string, 0, len(patches)) for _, patch := range patches { str := strings.TrimSpace(string(patch)) if len(str) == 0 { diff --git a/pkg/utils/report/results.go b/pkg/utils/report/results.go index 062dc6421f1a..ac21016dc164 100644 --- a/pkg/utils/report/results.go +++ b/pkg/utils/report/results.go @@ -176,7 +176,7 @@ func EngineResponseToReportResults(response engineapi.EngineResponse) []policyre policyType := pol.GetType() annotations := pol.GetAnnotations() - var results []policyreportv1alpha2.PolicyReportResult + results := make([]policyreportv1alpha2.PolicyReportResult, 0, len(response.PolicyResponse.Rules)) for _, ruleResult := range response.PolicyResponse.Rules { result := ToPolicyReportResult(policyType, policyName, ruleResult, annotations, nil) results = append(results, result) diff --git a/pkg/validatingadmissionpolicy/api.go b/pkg/validatingadmissionpolicy/api.go index 076ed001ccb5..b8030406de5c 100644 --- a/pkg/validatingadmissionpolicy/api.go +++ b/pkg/validatingadmissionpolicy/api.go @@ -41,11 +41,11 @@ type CustomNamespaceLister struct { } func (c *CustomNamespaceLister) List(selector labels.Selector) (ret []*corev1.Namespace, err error) { - var namespaces []*corev1.Namespace namespace, err := c.dClient.GetKubeClient().CoreV1().Namespaces().List(context.Background(), metav1.ListOptions{}) if err != nil { return nil, err } + namespaces := make([]*corev1.Namespace, 0, len(namespace.Items)) for _, ns := range namespace.Items { nsCopy := ns namespaces = append(namespaces, &nsCopy) diff --git a/pkg/validatingadmissionpolicy/version_converter.go b/pkg/validatingadmissionpolicy/version_converter.go index 1e2d294417b2..a8428fe4048c 100644 --- a/pkg/validatingadmissionpolicy/version_converter.go +++ b/pkg/validatingadmissionpolicy/version_converter.go @@ -83,7 +83,7 @@ func ConvertValidatingAdmissionPolicyBinding(v1alpha1binding v1alpha1.Validating } func convertRules(v1alpha1rules []v1alpha1.NamedRuleWithOperations) []v1beta1.NamedRuleWithOperations { - var v1beta1rules []v1beta1.NamedRuleWithOperations + v1beta1rules := make([]v1beta1.NamedRuleWithOperations, 0, len(v1alpha1rules)) for _, r := range v1alpha1rules { v1beta1rules = append(v1beta1rules, v1beta1.NamedRuleWithOperations(r)) } @@ -91,7 +91,7 @@ func convertRules(v1alpha1rules []v1alpha1.NamedRuleWithOperations) []v1beta1.Na } func convertValidations(v1alpha1validations []v1alpha1.Validation) []v1beta1.Validation { - var v1beta1validations []v1beta1.Validation + v1beta1validations := make([]v1beta1.Validation, 0, len(v1alpha1validations)) for _, v := range v1alpha1validations { v1beta1validations = append(v1beta1validations, v1beta1.Validation(v)) } @@ -99,7 +99,7 @@ func convertValidations(v1alpha1validations []v1alpha1.Validation) []v1beta1.Val } func convertAuditAnnotations(v1alpha1auditanns []v1alpha1.AuditAnnotation) []v1beta1.AuditAnnotation { - var v1beta1auditanns []v1beta1.AuditAnnotation + v1beta1auditanns := make([]v1beta1.AuditAnnotation, 0, len(v1alpha1auditanns)) for _, a := range v1alpha1auditanns { v1beta1auditanns = append(v1beta1auditanns, v1beta1.AuditAnnotation(a)) } @@ -107,7 +107,7 @@ func convertAuditAnnotations(v1alpha1auditanns []v1alpha1.AuditAnnotation) []v1b } func convertMatchConditions(v1alpha1conditions []v1alpha1.MatchCondition) []v1beta1.MatchCondition { - var v1beta1conditions []v1beta1.MatchCondition + v1beta1conditions := make([]v1beta1.MatchCondition, 0, len(v1alpha1conditions)) for _, m := range v1alpha1conditions { v1beta1conditions = append(v1beta1conditions, v1beta1.MatchCondition(m)) } @@ -115,7 +115,7 @@ func convertMatchConditions(v1alpha1conditions []v1alpha1.MatchCondition) []v1be } func convertVariables(v1alpha1variables []v1alpha1.Variable) []v1beta1.Variable { - var v1beta1variables []v1beta1.Variable + v1beta1variables := make([]v1beta1.Variable, 0, len(v1alpha1variables)) for _, v := range v1alpha1variables { v1beta1variables = append(v1beta1variables, v1beta1.Variable(v)) } @@ -123,7 +123,7 @@ func convertVariables(v1alpha1variables []v1alpha1.Variable) []v1beta1.Variable } func convertValidationActions(v1alpha1actions []v1alpha1.ValidationAction) []v1beta1.ValidationAction { - var v1beta1actions []v1beta1.ValidationAction + v1beta1actions := make([]v1beta1.ValidationAction, 0, len(v1alpha1actions)) for _, a := range v1alpha1actions { v1beta1actions = append(v1beta1actions, v1beta1.ValidationAction(a)) } @@ -131,7 +131,7 @@ func convertValidationActions(v1alpha1actions []v1alpha1.ValidationAction) []v1b } func ConvertMatchConditionsV1(v1alpha1conditions []v1alpha1.MatchCondition) []admissionregistrationv1.MatchCondition { - var v1conditions []admissionregistrationv1.MatchCondition + v1conditions := make([]admissionregistrationv1.MatchCondition, 0, len(v1alpha1conditions)) for _, m := range v1alpha1conditions { v1conditions = append(v1conditions, admissionregistrationv1.MatchCondition(m)) }