Skip to content

Commit

Permalink
feat(perf): add new linter prealloc to enforce slice declarations b…
Browse files Browse the repository at this point in the history
…est practice (kyverno#10250)

* feat(perf): add new linter prealloc to enforce slice declarations best practice

Signed-off-by: ShutingZhao <[email protected]>

* fix(linter): prealloac slices

Signed-off-by: ShutingZhao <[email protected]>

---------

Signed-off-by: ShutingZhao <[email protected]>
  • Loading branch information
realshuting authored May 20, 2024
1 parent 46e5d81 commit fb9c66f
Show file tree
Hide file tree
Showing 37 changed files with 50 additions and 50 deletions.
1 change: 1 addition & 0 deletions .golangci.yml
Original file line number Diff line number Diff line change
Expand Up @@ -38,6 +38,7 @@ linters:
- unused
- wastedassign
- whitespace
- prealloc

run:
timeout: 15m
Expand Down
2 changes: 1 addition & 1 deletion cmd/cli/kubectl-kyverno/commands/apply/command.go
Original file line number Diff line number Diff line change
Expand Up @@ -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()))
Expand Down
2 changes: 1 addition & 1 deletion cmd/cli/kubectl-kyverno/commands/fix/policy/options.go
Original file line number Diff line number Diff line change
Expand Up @@ -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)
Expand Down
2 changes: 1 addition & 1 deletion cmd/cli/kubectl-kyverno/commands/jp/parse/command.go
Original file line number Diff line number Diff line change
Expand Up @@ -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)
Expand Down
2 changes: 1 addition & 1 deletion cmd/cli/kubectl-kyverno/commands/jp/query/command.go
Original file line number Diff line number Diff line change
Expand Up @@ -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)
Expand Down
2 changes: 1 addition & 1 deletion cmd/cli/kubectl-kyverno/commands/json/scan/options.go
Original file line number Diff line number Diff line change
Expand Up @@ -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,
Expand Down
2 changes: 1 addition & 1 deletion cmd/cli/kubectl-kyverno/commands/test/command.go
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
2 changes: 1 addition & 1 deletion cmd/cli/kubectl-kyverno/commands/test/test.go
Original file line number Diff line number Diff line change
Expand Up @@ -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()))
Expand Down
2 changes: 1 addition & 1 deletion cmd/cli/kubectl-kyverno/fix/test.go
Original file line number Diff line number Diff line change
Expand Up @@ -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")
Expand Down
2 changes: 1 addition & 1 deletion cmd/cli/kubectl-kyverno/output/table/table.go
Original file line number Diff line number Diff line change
Expand Up @@ -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)
}
Expand Down
7 changes: 3 additions & 4 deletions cmd/cli/kubectl-kyverno/output/table/table_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -85,15 +85,14 @@ func TestTable_AddFailed(t *testing.T) {

func TestTable_Rows(t *testing.T) {
var nilRows []Row
var nilCompactRows []RowCompact
tests := []struct {
name string
RawRows []Row
detailed bool
want interface{}
}{{
name: "nil",
want: nilCompactRows,
want: []RowCompact{},
}, {
name: "nil - detailed",
detailed: true,
Expand Down Expand Up @@ -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)
}
})
}
Expand Down
2 changes: 1 addition & 1 deletion cmd/cli/kubectl-kyverno/path/path.go
Original file line number Diff line number Diff line change
Expand Up @@ -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))
}
Expand Down
2 changes: 1 addition & 1 deletion cmd/cli/kubectl-kyverno/processor/policy_processor.go
Original file line number Diff line number Diff line change
Expand Up @@ -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() {
Expand Down
2 changes: 1 addition & 1 deletion cmd/cli/kubectl-kyverno/processor/vap_processor.go
Original file line number Diff line number Diff line change
Expand Up @@ -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 {
Expand Down
2 changes: 1 addition & 1 deletion cmd/cli/kubectl-kyverno/resource/resource.go
Original file line number Diff line number Diff line change
Expand Up @@ -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 {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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 {
Expand All @@ -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)
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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 {
Expand All @@ -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)
}
Expand Down
2 changes: 1 addition & 1 deletion pkg/autogen/autogen.go
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
2 changes: 1 addition & 1 deletion pkg/controllers/report/aggregate/controller.go
Original file line number Diff line number Diff line change
Expand Up @@ -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)
}
Expand Down
2 changes: 1 addition & 1 deletion pkg/controllers/report/background/controller.go
Original file line number Diff line number Diff line change
Expand Up @@ -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))
}
Expand Down
4 changes: 2 additions & 2 deletions pkg/controllers/webhook/controller.go
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -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
Expand Down
2 changes: 1 addition & 1 deletion pkg/controllers/webhook/utils.go
Original file line number Diff line number Diff line change
Expand Up @@ -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]
Expand Down
2 changes: 1 addition & 1 deletion pkg/cosign/cosign.go
Original file line number Diff line number Diff line change
Expand Up @@ -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 {
Expand Down
2 changes: 1 addition & 1 deletion pkg/engine/adapters/dclient.go
Original file line number Diff line number Diff line change
Expand Up @@ -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,
Expand Down
2 changes: 1 addition & 1 deletion pkg/engine/handlers/mutation/load_targets.go
Original file line number Diff line number Diff line change
Expand Up @@ -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()
Expand All @@ -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,
Expand Down
2 changes: 1 addition & 1 deletion pkg/engine/handlers/validation/validate_pss.go
Original file line number Diff line number Diff line change
Expand Up @@ -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)
Expand Down
6 changes: 3 additions & 3 deletions pkg/engine/internal/imageverifier.go
Original file line number Diff line number Diff line change
Expand Up @@ -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)
Expand All @@ -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{
Expand All @@ -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 {
Expand Down
4 changes: 2 additions & 2 deletions pkg/engine/jmespath/functionentry.go
Original file line number Diff line number Diff line change
Expand Up @@ -32,15 +32,15 @@ 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 {
aTypes = append(aTypes, string(t))
}
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))
}
Expand Down
2 changes: 1 addition & 1 deletion pkg/event/events.go
Original file line number Diff line number Diff line change
Expand Up @@ -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 {
Expand Down
2 changes: 1 addition & 1 deletion pkg/informers/helpers.go
Original file line number Diff line number Diff line change
Expand Up @@ -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)
}
Expand Down
2 changes: 1 addition & 1 deletion pkg/policy/utils.go
Original file line number Diff line number Diff line change
Expand Up @@ -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())
}
Expand Down
4 changes: 2 additions & 2 deletions pkg/pss/evaluate.go
Original file line number Diff line number Diff line change
Expand Up @@ -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)
}
Expand Down Expand Up @@ -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)
Expand Down
2 changes: 1 addition & 1 deletion pkg/utils/api/image.go
Original file line number Diff line number Diff line change
Expand Up @@ -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...)
Expand Down
2 changes: 1 addition & 1 deletion pkg/utils/json/utils.go
Original file line number Diff line number Diff line change
Expand Up @@ -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 {
Expand Down
Loading

0 comments on commit fb9c66f

Please sign in to comment.