Skip to content

Commit

Permalink
Enable prealloc linter (elastic#1728)
Browse files Browse the repository at this point in the history
  • Loading branch information
moukoublen authored Dec 22, 2023
1 parent 4ff666a commit aca7660
Show file tree
Hide file tree
Showing 14 changed files with 49 additions and 30 deletions.
13 changes: 13 additions & 0 deletions .golangci.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -22,6 +22,14 @@ linters:
- unparam
- unused
- whitespace
- prealloc

issues:
exclude-rules:
- path: _test\.go
linters: [prealloc]
- path: resources/utils/testhelper/*.go
linters: [prealloc]

linters-settings:
gocritic:
Expand Down Expand Up @@ -129,3 +137,8 @@ linters-settings:
local-variables-are-used: false
tenv:
all: true

prealloc:
simple: true
range-loops: true
for-loops: false
2 changes: 1 addition & 1 deletion deploy/cloudformation/gomain.go
Original file line number Diff line number Diff line change
Expand Up @@ -153,7 +153,7 @@ func createStack(stackName string, templatePath string, params map[string]string
}

svc := cloudformation.NewFromConfig(cfg)
var cfParams []types.Parameter
cfParams := make([]types.Parameter, 0, len(params))
for key, value := range params {
p := types.Parameter{
ParameterKey: aws.String(key),
Expand Down
2 changes: 1 addition & 1 deletion evaluator/logger.go
Original file line number Diff line number Diff line change
Expand Up @@ -74,7 +74,7 @@ func (l *logger) SetLevel(level logging.Level) {
}

func mapToArray(m map[string]any) []any {
var ret []any
ret := make([]any, 0, len(m))
for k, v := range m {
ret = append(ret, k, v)
}
Expand Down
2 changes: 1 addition & 1 deletion flavors/benchmark/aws_org.go
Original file line number Diff line number Diff line change
Expand Up @@ -112,7 +112,7 @@ func (a *AWSOrg) getAwsAccounts(ctx context.Context, log *logp.Logger, initialCf
return nil, err
}

var accounts []preset.AwsAccount
accounts := make([]preset.AwsAccount, 0, len(accountIdentities))
for _, identity := range accountIdentities {
var memberCfg awssdk.Config
if identity.Account == rootIdentity.Account {
Expand Down
2 changes: 1 addition & 1 deletion resources/fetching/registry/registry.go
Original file line number Diff line number Diff line change
Expand Up @@ -67,7 +67,7 @@ func NewRegistry(log *logp.Logger, options ...Option) Registry {
}

func (r *registry) Keys() []string {
var keys []string
keys := make([]string, 0, len(r.reg))
for k := range r.reg {
keys = append(keys, k)
}
Expand Down
2 changes: 1 addition & 1 deletion resources/providers/aws_cis/logging/provider.go
Original file line number Diff line number Diff line change
Expand Up @@ -45,7 +45,7 @@ func (p *Provider) DescribeTrails(ctx context.Context) ([]awslib.AwsResource, er
return nil, trailsErr
}

var enrichedTrails []awslib.AwsResource
enrichedTrails := make([]awslib.AwsResource, 0, len(trails))
for _, info := range trails {
if info.Trail.S3BucketName == nil {
continue
Expand Down
2 changes: 1 addition & 1 deletion resources/providers/awslib/cloudtrail/provider.go
Original file line number Diff line number Diff line change
Expand Up @@ -45,7 +45,7 @@ func (p Provider) DescribeTrails(ctx context.Context) ([]TrailInfo, error) {
return nil, err
}

var result []TrailInfo
result := make([]TrailInfo, 0, len(output.TrailList))
for _, trail := range output.TrailList {
if trail.Name == nil {
continue
Expand Down
19 changes: 11 additions & 8 deletions resources/providers/awslib/ec2/provider.go
Original file line number Diff line number Diff line change
Expand Up @@ -30,9 +30,11 @@ import (
"github.com/elastic/cloudbeat/resources/providers/awslib"
)

var subnetAssociationIdFilterName = "association.subnet-id"
var subnetVpcIdFilterName = "vpc-id"
var subnetMainAssociationFilterName = "association.main"
var (
subnetAssociationIdFilterName = "association.subnet-id"
subnetVpcIdFilterName = "vpc-id"
subnetMainAssociationFilterName = "association.main"
)

type Provider struct {
log *logp.Logger
Expand Down Expand Up @@ -219,7 +221,7 @@ func (p *Provider) CreateSnapshots(ctx context.Context, ins *Ec2Instance) ([]EBS
return nil, err
}

var result []EBSSnapshot
result := make([]EBSSnapshot, 0, len(res.Snapshots))
for _, snap := range res.Snapshots {
result = append(result, FromSnapshotInfo(snap, ins.Region, p.awsAccountID, *ins))
}
Expand All @@ -241,7 +243,7 @@ func (p *Provider) DescribeSnapshots(ctx context.Context, snapshot EBSSnapshot)
return nil, err
}

var result []EBSSnapshot
result := make([]EBSSnapshot, 0, len(res.Snapshots))
for _, snap := range res.Snapshots {
result = append(result, FromSnapshot(snap, snapshot.Region, p.awsAccountID, snapshot.Instance))
}
Expand All @@ -268,10 +270,11 @@ func (p *Provider) GetRouteTableForSubnet(ctx context.Context, region string, su
}

// Fetching route tables explicitly attached to the subnet
routeTables, err := client.DescribeRouteTables(ctx, &ec2.DescribeRouteTablesInput{Filters: []types.Filter{
{Name: &subnetAssociationIdFilterName, Values: []string{subnetId}}},
routeTables, err := client.DescribeRouteTables(ctx, &ec2.DescribeRouteTablesInput{
Filters: []types.Filter{
{Name: &subnetAssociationIdFilterName, Values: []string{subnetId}},
},
})

if err != nil {
return types.RouteTable{}, err
}
Expand Down
3 changes: 1 addition & 2 deletions resources/providers/awslib/iam/policy.go
Original file line number Diff line number Diff line change
Expand Up @@ -216,13 +216,12 @@ func (p Provider) listInlinePolicies(ctx context.Context, identity *string) ([]P
input.Marker = output.Marker
}

var policies []PolicyDocument
policies := make([]PolicyDocument, 0, len(policyNames))
for i := range policyNames {
inlinePolicy, err := p.client.GetUserPolicy(ctx, &iamsdk.GetUserPolicyInput{
PolicyName: &policyNames[i],
UserName: identity,
})

if err != nil {
p.log.Errorf("fail to get inline policy for user: %s, policy name: %s", *identity, policyNames[i])
policies = append(policies, PolicyDocument{PolicyName: policyNames[i]})
Expand Down
6 changes: 3 additions & 3 deletions resources/providers/awslib/iam/user.go
Original file line number Diff line number Diff line change
Expand Up @@ -43,7 +43,6 @@ const (
)

func (p Provider) GetUsers(ctx context.Context) ([]awslib.AwsResource, error) {
var users []awslib.AwsResource
apiUsers, err := p.listUsers(ctx)
if err != nil {
p.log.Errorf("fail to list users, error: %v", err)
Expand All @@ -60,6 +59,7 @@ func (p Provider) GetUsers(ctx context.Context) ([]awslib.AwsResource, error) {
apiUsers = append(apiUsers, *rootUser)
}

users := make([]awslib.AwsResource, 0, len(apiUsers))
var userAccount *CredentialReport
for _, apiUser := range apiUsers {
var username string
Expand Down Expand Up @@ -182,7 +182,7 @@ func (p Provider) listMFADevices(ctx context.Context, user types.User) ([]AuthDe
input.Marker = output.Marker
}

var devices []AuthDevice
devices := make([]AuthDevice, 0, len(apiDevices))
for _, apiDevice := range apiDevices {
isVirtual := true
if !strings.HasPrefix(*apiDevice.SerialNumber, "arn:") {
Expand Down Expand Up @@ -243,7 +243,7 @@ func (p Provider) getCredentialReport(ctx context.Context) (map[string]*Credenti
}

// loop until max retries or till the report is ready
var countRetries = 0
countRetries := 0
report, err = p.client.GetCredentialReport(ctx, &iamsdk.GetCredentialReportInput{})
if errors.As(err, &apiErr) {
for apiErr.ErrorCode() == "NoSuchEntity" || apiErr.ErrorCode() == "ReportInProgress" {
Expand Down
2 changes: 1 addition & 1 deletion resources/providers/awslib/rds/provider.go
Original file line number Diff line number Diff line change
Expand Up @@ -84,7 +84,7 @@ func (p Provider) DescribeDBInstances(ctx context.Context) ([]awslib.AwsResource
}

func (p Provider) getDBInstanceSubnets(ctx context.Context, region string, dbInstance types.DBInstance) []Subnet {
var results []Subnet
results := make([]Subnet, 0, len(dbInstance.DBSubnetGroup.Subnets))
for _, subnet := range dbInstance.DBSubnetGroup.Subnets {
resultSubnet := Subnet{ID: *subnet.SubnetIdentifier, RouteTable: nil}
routeTableForSubnet, err := p.ec2.GetRouteTableForSubnet(ctx, region, *subnet.SubnetIdentifier, *dbInstance.DBSubnetGroup.VpcId)
Expand Down
14 changes: 9 additions & 5 deletions resources/providers/awslib/rds/provider_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -38,8 +38,10 @@ type ProviderTestSuite struct {
suite.Suite
}

type rdsClientMockReturnVals map[string]map[string][]any
type ec2GetRouteTableForSubnetVals [][]any
type (
rdsClientMockReturnVals map[string]map[string][]any
ec2GetRouteTableForSubnetVals [][]any
)

var (
identifier = "identifier"
Expand Down Expand Up @@ -115,7 +117,7 @@ func (s *ProviderTestSuite) TestProvider_DescribeDBInstances() {
StorageEncrypted: false,
AutoMinorVersionUpgrade: false,
PubliclyAccessible: false,
Subnets: []Subnet(nil),
Subnets: []Subnet{},
region: awslib.DefaultRegion,
},
DBInstance{
Expand All @@ -128,8 +130,10 @@ func (s *ProviderTestSuite) TestProvider_DescribeDBInstances() {
{ID: identifier2, RouteTable: &RouteTable{
ID: identifier,
Routes: []Route{{DestinationCidrBlock: &destinationCidrBlock, GatewayId: &gatewayId}},
}}},
region: awslib.DefaultRegion},
}},
},
region: awslib.DefaultRegion,
},
},
},
}
Expand Down
6 changes: 3 additions & 3 deletions resources/providers/gcplib/inventory/provider.go
Original file line number Diff line number Diff line change
Expand Up @@ -379,7 +379,7 @@ func decodeDnsPolicies(dnsPolicyAssets []*assetpb.Asset) []*dnsPolicyFields {
// getAssetsByProject groups assets by project, extracts metadata for each project, and adds folder and organization-level resources for each group.
func getAssetsByProject[T any](assets []*ExtendedGcpAsset, log *logp.Logger, f TypeGenerator[T]) []*T {
assetsByProject := lo.GroupBy(assets, func(asset *ExtendedGcpAsset) string { return asset.Ecs.ProjectId })
var enrichedAssets []*T
enrichedAssets := make([]*T, 0, len(assetsByProject))
for projectId, projectAssets := range assetsByProject {
if projectId == "" {
continue
Expand Down Expand Up @@ -439,7 +439,7 @@ func mergeAssetContentType(assets []*assetpb.Asset) []*assetpb.Asset {
item.IamPolicy = asset.IamPolicy
}
}
var results []*assetpb.Asset
results := make([]*assetpb.Asset, 0, len(resultsMap))
for _, asset := range resultsMap {
results = append(results, asset)
}
Expand All @@ -448,7 +448,7 @@ func mergeAssetContentType(assets []*assetpb.Asset) []*assetpb.Asset {

// extends the assets with the project and organization display name
func extendWithECS(ctx context.Context, crm *ResourceManagerWrapper, cache map[string]*fetching.EcsGcp, assets []*assetpb.Asset) []*ExtendedGcpAsset {
var extendedAssets []*ExtendedGcpAsset
extendedAssets := make([]*ExtendedGcpAsset, 0, len(assets))
for _, asset := range assets {
keys := getAssetIds(asset)
cacheKey := fmt.Sprintf("%s/%s", keys.parentProject, keys.parentOrg)
Expand Down
4 changes: 2 additions & 2 deletions resources/utils/testhelper/helper.go
Original file line number Diff line number Diff line change
Expand Up @@ -70,15 +70,15 @@ func CollectResourcesWithTimeout[T any](ch chan T, maxCount int, timeout time.Du
// This function waits for the channel to close before returning.
// See CollectResources for a non-blocking version of the function.
func CollectResourcesBlocking[T any](ch chan T) []T {
var results []T
results := make([]T, 0)
for v := range ch {
results = append(results, v)
}
return results
}

func CreateMockClients[T any](client T, regions []string) map[string]T {
var m = make(map[string]T, 0)
m := make(map[string]T, 0)
for _, clientRegion := range regions {
m[clientRegion] = client
}
Expand Down

0 comments on commit aca7660

Please sign in to comment.