Skip to content

Commit

Permalink
Merge pull request hashicorp#21332 from hashicorp/svcpkg-linting-gomnd
Browse files Browse the repository at this point in the history
linting: Restores `gomnd` linter
  • Loading branch information
gdavison authored Oct 19, 2021
2 parents 69fce61 + 9e1cca8 commit 1b0103e
Show file tree
Hide file tree
Showing 57 changed files with 255 additions and 144 deletions.
16 changes: 12 additions & 4 deletions .golangci.yml
Original file line number Diff line number Diff line change
Expand Up @@ -18,7 +18,7 @@ linters:
- deadcode
- errcheck
- gofmt
# - gomnd
- gomnd
- gosimple
- ineffassign
- makezero
Expand All @@ -44,17 +44,25 @@ linters-settings:
ignored-functions:
# AWS Go SDK
- aws.Int64
- nullable.*
- request.ConstantWaiterDelay
- request.WithWaiterMaxAttempts
# AWS Provider
- mapMaxItems
- wafv2RootStatementSchema
- wafv2WebACLRootStatementSchema
- nullable.*
- sweep.SweepOrchestratorContext
# Terraform Plugin SDK
- resource.Retry
- schema.DefaultTimeout
- validation.*
# Go
- make
- strconv.FormatFloat
- strconv.FormatInt
- strconv.ParseFloat
- strconv.ParseInt
- strings.SplitN
- validation.*
nolintlint:
allow-leading-space: false
require-explanation: true
Expand All @@ -64,4 +72,4 @@ linters-settings:
- gomnd

run:
timeout: 15m
timeout: 20m
14 changes: 14 additions & 0 deletions .semgrep.yml
Original file line number Diff line number Diff line change
Expand Up @@ -638,3 +638,17 @@ rules:
patterns:
- pattern: 'if d.HasChangeExcept("tags_all") {...}'
severity: WARNING

- id: unnecessary-literal-type-conversion
languages: [go]
message: Literal numbers do not need type conversions
paths:
include:
- internal/
patterns:
- pattern: "aws.Int64(int64($X))"
- metavariable-regex:
metavariable: $X
regex: (\d+)
severity: ERROR
fix: "aws.Int64($X)"
35 changes: 24 additions & 11 deletions internal/acctest/acctest.go
Original file line number Diff line number Diff line change
Expand Up @@ -1910,7 +1910,7 @@ func (d domainName) Subdomain(name string) domainName {
}

func (d domainName) RandomSubdomain() domainName {
return d.Subdomain(sdkacctest.RandString(8))
return d.Subdomain(sdkacctest.RandString(8)) //nolint:gomnd
}

func (d domainName) FQDN() domainName {
Expand Down Expand Up @@ -1956,6 +1956,20 @@ func PreCheckOutpostsOutposts(t *testing.T) {
}
}

const (
// ACM domain names cannot be longer than 64 characters
// Other resources, e.g. Cognito User Pool Domains, limit this to 63
acmCertificateDomainMaxLen = 63

acmRandomSubDomainPrefix = "tf-acc-"
acmRandomSubDomainPrefixLen = len(acmRandomSubDomainPrefix)

// Max length (63)
// Subtract "tf-acc-" prefix (7)
// Subtract "." between prefix and root domain (1)
acmRandomSubDomainRemainderLen = acmCertificateDomainMaxLen - acmRandomSubDomainPrefixLen - 1
)

func ACMCertificateDomainFromEnv(t *testing.T) string {
rootDomain := os.Getenv("ACM_CERTIFICATE_ROOT_DOMAIN")

Expand All @@ -1970,11 +1984,11 @@ func ACMCertificateDomainFromEnv(t *testing.T) string {
"contact addresses.")
}

if len(rootDomain) >= 56 {
t.Skip(
"Environment variable ACM_CERTIFICATE_ROOT_DOMAIN is too long. " +
"The domain must be shorter than 56 characters to allow for " +
"subdomain randomization in the testing.")
if len(rootDomain) > acmRandomSubDomainRemainderLen {
t.Skipf(
"Environment variable ACM_CERTIFICATE_ROOT_DOMAIN is too long. "+
"The domain must be %d characters or shorter to allow for "+
"subdomain randomization in the testing.", acmRandomSubDomainRemainderLen)
}

return rootDomain
Expand All @@ -1983,11 +1997,10 @@ func ACMCertificateDomainFromEnv(t *testing.T) string {
// ACM domain names cannot be longer than 64 characters
// Other resources, e.g. Cognito User Pool Domains, limit this to 63
func ACMCertificateRandomSubDomain(rootDomain string) string {
// Max length (63)
// Subtract "tf-acc-" prefix (7)
// Subtract "." between prefix and root domain (1)
// Subtract length of root domain
return fmt.Sprintf("tf-acc-%s.%s", sdkacctest.RandString(55-len(rootDomain)), rootDomain)
return fmt.Sprintf(
acmRandomSubDomainPrefix+"%s.%s",
sdkacctest.RandString(acmRandomSubDomainRemainderLen-len(rootDomain)),
rootDomain)
}

func CheckACMPCACertificateAuthorityActivateCA(certificateAuthority *acmpca.CertificateAuthority) resource.TestCheckFunc {
Expand Down
8 changes: 4 additions & 4 deletions internal/acctest/crypto.go
Original file line number Diff line number Diff line change
Expand Up @@ -19,7 +19,7 @@ const (
pemBlockTypeCertificateRequest = `CERTIFICATE REQUEST`
)

var tlsX509CertificateSerialNumberLimit = new(big.Int).Lsh(big.NewInt(1), 128)
var tlsX509CertificateSerialNumberLimit = new(big.Int).Lsh(big.NewInt(1), 128) //nolint:gomnd

// TLSRSAPrivateKeyPEM generates a RSA private key PEM string.
// Wrap with TLSPEMEscapeNewlines() to allow simple fmt.Sprintf()
Expand Down Expand Up @@ -110,7 +110,7 @@ func TLSRSAX509LocallySignedCertificatePEM(caKeyPem, caCertificatePem, keyPem, c
BasicConstraintsValid: true,
ExtKeyUsage: []x509.ExtKeyUsage{x509.ExtKeyUsageServerAuth},
KeyUsage: x509.KeyUsageDigitalSignature | x509.KeyUsageKeyEncipherment,
NotAfter: time.Now().Add(24 * time.Hour),
NotAfter: time.Now().Add(24 * time.Hour), //nolint:gomnd
NotBefore: time.Now(),
SerialNumber: serialNumber,
Subject: pkix.Name{
Expand Down Expand Up @@ -168,7 +168,7 @@ func TLSRSAX509SelfSignedCACertificatePEM(keyPem string) string {
ExtKeyUsage: []x509.ExtKeyUsage{x509.ExtKeyUsageServerAuth},
IsCA: true,
KeyUsage: x509.KeyUsageDigitalSignature | x509.KeyUsageKeyEncipherment,
NotAfter: time.Now().Add(24 * time.Hour),
NotAfter: time.Now().Add(24 * time.Hour), //nolint:gomnd
NotBefore: time.Now(),
SerialNumber: serialNumber,
Subject: pkix.Name{
Expand Down Expand Up @@ -217,7 +217,7 @@ func TLSRSAX509SelfSignedCertificatePEM(keyPem, commonName string) string {
BasicConstraintsValid: true,
ExtKeyUsage: []x509.ExtKeyUsage{x509.ExtKeyUsageServerAuth},
KeyUsage: x509.KeyUsageDigitalSignature | x509.KeyUsageKeyEncipherment,
NotAfter: time.Now().Add(24 * time.Hour),
NotAfter: time.Now().Add(24 * time.Hour), //nolint:gomnd
NotBefore: time.Now(),
SerialNumber: serialNumber,
Subject: pkix.Name{
Expand Down
22 changes: 17 additions & 5 deletions internal/service/acmpca/certificate_authority.go
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,12 @@ import (
"github.com/hashicorp/terraform-provider-aws/internal/verify"
)

const (
certificateAuthorityPermanentDeletionTimeInDaysMin = 7
certificateAuthorityPermanentDeletionTimeInDaysMax = 30
certificateAuthorityPermanentDeletionTimeInDaysDefault = certificateAuthorityPermanentDeletionTimeInDaysMax
)

func ResourceCertificateAuthority() *schema.Resource {
//lintignore:R011
return &schema.Resource{
Expand All @@ -26,7 +32,10 @@ func ResourceCertificateAuthority() *schema.Resource {
Delete: resourceCertificateAuthorityDelete,
Importer: &schema.ResourceImporter{
State: func(d *schema.ResourceData, meta interface{}) ([]*schema.ResourceData, error) {
d.Set("permanent_deletion_time_in_days", 30)
d.Set(
"permanent_deletion_time_in_days",
certificateAuthorityPermanentDeletionTimeInDaysDefault,
)

return []*schema.ResourceData{d}, nil
},
Expand Down Expand Up @@ -258,10 +267,13 @@ func ResourceCertificateAuthority() *schema.Resource {
Computed: true,
},
"permanent_deletion_time_in_days": {
Type: schema.TypeInt,
Optional: true,
Default: 30,
ValidateFunc: validation.IntBetween(7, 30),
Type: schema.TypeInt,
Optional: true,
Default: certificateAuthorityPermanentDeletionTimeInDaysDefault,
ValidateFunc: validation.IntBetween(
certificateAuthorityPermanentDeletionTimeInDaysMin,
certificateAuthorityPermanentDeletionTimeInDaysMax,
),
},
"tags": tftags.TagsSchema(),
"tags_all": tftags.TagsSchemaComputed(),
Expand Down
2 changes: 1 addition & 1 deletion internal/service/acmpca/sweep.go
Original file line number Diff line number Diff line change
Expand Up @@ -68,7 +68,7 @@ func sweepCertificateAuthorities(region string) error {
log.Printf("[INFO] Deleting ACM PCA Certificate Authority: %s", arn)
_, err := conn.DeleteCertificateAuthority(&acmpca.DeleteCertificateAuthorityInput{
CertificateAuthorityArn: aws.String(arn),
PermanentDeletionTimeInDays: aws.Int64(int64(7)),
PermanentDeletionTimeInDays: aws.Int64(7),
})
if tfawserr.ErrMessageContains(err, acmpca.ErrCodeResourceNotFoundException, "") {
continue
Expand Down
4 changes: 2 additions & 2 deletions internal/service/autoscaling/flex_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -45,7 +45,7 @@ func TestExpandStepAdjustments(t *testing.T) {
expected := &autoscaling.StepAdjustment{
MetricIntervalLowerBound: aws.Float64(1.0),
MetricIntervalUpperBound: aws.Float64(2.0),
ScalingAdjustment: aws.Int64(int64(1)),
ScalingAdjustment: aws.Int64(1),
}

if !reflect.DeepEqual(parameters[0], expected) {
Expand All @@ -61,7 +61,7 @@ func TestFlattenStepAdjustments(t *testing.T) {
{
MetricIntervalLowerBound: aws.Float64(1.0),
MetricIntervalUpperBound: aws.Float64(2.5),
ScalingAdjustment: aws.Int64(int64(1)),
ScalingAdjustment: aws.Int64(1),
},
}

Expand Down
4 changes: 2 additions & 2 deletions internal/service/autoscaling/group.go
Original file line number Diff line number Diff line change
Expand Up @@ -661,8 +661,8 @@ func resourceGroupCreate(d *schema.ResourceData, meta interface{}) error {
maxSize := aws.Int64(int64(d.Get("max_size").(int)))

if twoPhases {
createOpts.MinSize = aws.Int64(int64(0))
createOpts.MaxSize = aws.Int64(int64(0))
createOpts.MinSize = aws.Int64(0)
createOpts.MaxSize = aws.Int64(0)

updateOpts.MinSize = minSize
updateOpts.MaxSize = maxSize
Expand Down
10 changes: 5 additions & 5 deletions internal/service/batch/job_definition_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -200,31 +200,31 @@ func TestAccBatchJobDefinition_ContainerProperties_advanced(t *testing.T) {
"param2": aws.String("val2"),
},
RetryStrategy: &batch.RetryStrategy{
Attempts: aws.Int64(int64(1)),
Attempts: aws.Int64(1),
EvaluateOnExit: []*batch.EvaluateOnExit{
{Action: aws.String(strings.ToLower(batch.RetryActionRetry)), OnStatusReason: aws.String("Host EC2*")},
{Action: aws.String(strings.ToLower(batch.RetryActionExit)), OnReason: aws.String("*")},
},
},
Timeout: &batch.JobTimeout{
AttemptDurationSeconds: aws.Int64(int64(60)),
AttemptDurationSeconds: aws.Int64(60),
},
ContainerProperties: &batch.ContainerProperties{
Command: []*string{aws.String("ls"), aws.String("-la")},
Environment: []*batch.KeyValuePair{
{Name: aws.String("VARNAME"), Value: aws.String("VARVAL")},
},
Image: aws.String("busybox"),
Memory: aws.Int64(int64(512)),
Memory: aws.Int64(512),
MountPoints: []*batch.MountPoint{
{ContainerPath: aws.String("/tmp"), ReadOnly: aws.Bool(false), SourceVolume: aws.String("tmp")},
},
ResourceRequirements: []*batch.ResourceRequirement{},
Secrets: []*batch.Secret{},
Ulimits: []*batch.Ulimit{
{HardLimit: aws.Int64(int64(1024)), Name: aws.String("nofile"), SoftLimit: aws.Int64(int64(1024))},
{HardLimit: aws.Int64(1024), Name: aws.String("nofile"), SoftLimit: aws.Int64(1024)},
},
Vcpus: aws.Int64(int64(1)),
Vcpus: aws.Int64(1),
Volumes: []*batch.Volume{
{
Host: &batch.Host{SourcePath: aws.String("/tmp")},
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -1238,7 +1238,7 @@ func flattenRestrictions(r *cloudfront.Restrictions) []interface{} {

func ExpandGeoRestriction(m map[string]interface{}) *cloudfront.GeoRestriction {
gr := &cloudfront.GeoRestriction{
Quantity: aws.Int64(int64(0)),
Quantity: aws.Int64(0),
RestrictionType: aws.String(m["restriction_type"].(string)),
}

Expand Down
5 changes: 3 additions & 2 deletions internal/service/cloudwatchevents/rule.go
Original file line number Diff line number Diff line change
Expand Up @@ -355,8 +355,9 @@ func validateEventPatternValue() schema.SchemaValidateFunc {
}

// Check whether the normalized JSON is within the given length.
if len(json) > 2048 {
errors = append(errors, fmt.Errorf("%q cannot be longer than %d characters: %q", k, 2048, json))
const maxJsonLength = 2048
if len(json) > maxJsonLength {
errors = append(errors, fmt.Errorf("%q cannot be longer than %d characters: %q", k, maxJsonLength, json))
}
return
}
Expand Down
2 changes: 1 addition & 1 deletion internal/service/codepipeline/webhook.go
Original file line number Diff line number Diff line change
Expand Up @@ -174,7 +174,7 @@ func GetWebhook(conn *codepipeline.CodePipeline, arn string) (*codepipeline.List

for {
input := &codepipeline.ListWebhooksInput{
MaxResults: aws.Int64(int64(60)),
MaxResults: aws.Int64(60),
}
if nextToken != "" {
input.NextToken = aws.String(nextToken)
Expand Down
2 changes: 1 addition & 1 deletion internal/service/cognitoidentity/pool_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -372,7 +372,7 @@ func testAccPreCheck(t *testing.T) {
conn := acctest.Provider.Meta().(*conns.AWSClient).CognitoIdentityConn

input := &cognitoidentity.ListIdentityPoolsInput{
MaxResults: aws.Int64(int64(1)),
MaxResults: aws.Int64(1),
}

_, err := conn.ListIdentityPools(input)
Expand Down
4 changes: 2 additions & 2 deletions internal/service/cognitoidp/sweep.go
Original file line number Diff line number Diff line change
Expand Up @@ -37,7 +37,7 @@ func sweepUserPoolDomains(region string) error {
conn := client.(*conns.AWSClient).CognitoIDPConn

input := &cognitoidentityprovider.ListUserPoolsInput{
MaxResults: aws.Int64(int64(50)),
MaxResults: aws.Int64(50),
}

err = conn.ListUserPoolsPages(input, func(resp *cognitoidentityprovider.ListUserPoolsOutput, lastPage bool) bool {
Expand Down Expand Up @@ -89,7 +89,7 @@ func sweepUserPools(region string) error {
conn := client.(*conns.AWSClient).CognitoIDPConn

input := &cognitoidentityprovider.ListUserPoolsInput{
MaxResults: aws.Int64(int64(50)),
MaxResults: aws.Int64(50),
}

err = conn.ListUserPoolsPages(input, func(resp *cognitoidentityprovider.ListUserPoolsOutput, lastPage bool) bool {
Expand Down
2 changes: 1 addition & 1 deletion internal/service/cognitoidp/user_pool_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -1473,7 +1473,7 @@ func testAccPreCheckIdentityProvider(t *testing.T) {
conn := acctest.Provider.Meta().(*conns.AWSClient).CognitoIDPConn

input := &cognitoidentityprovider.ListUserPoolsInput{
MaxResults: aws.Int64(int64(1)),
MaxResults: aws.Int64(1),
}

_, err := conn.ListUserPools(input)
Expand Down
2 changes: 1 addition & 1 deletion internal/service/cognitoidp/user_pools_data_source.go
Original file line number Diff line number Diff line change
Expand Up @@ -76,7 +76,7 @@ func getAllCognitoUserPools(conn *cognitoidentityprovider.CognitoIdentityProvide
for {
input := &cognitoidentityprovider.ListUserPoolsInput{
// MaxResults Valid Range: Minimum value of 1. Maximum value of 60
MaxResults: aws.Int64(int64(60)),
MaxResults: aws.Int64(60),
}
if nextToken != "" {
input.NextToken = aws.String(nextToken)
Expand Down
4 changes: 2 additions & 2 deletions internal/service/directconnect/lag.go
Original file line number Diff line number Diff line change
Expand Up @@ -97,9 +97,9 @@ func resourceLagCreate(d *schema.ResourceData, meta interface{}) error {
if v, ok := d.GetOk("connection_id"); ok {
connectionIDSpecified = true
input.ConnectionId = aws.String(v.(string))
input.NumberOfConnections = aws.Int64(int64(1))
input.NumberOfConnections = aws.Int64(1)
} else {
input.NumberOfConnections = aws.Int64(int64(1))
input.NumberOfConnections = aws.Int64(1)
}

if v, ok := d.GetOk("provider_name"); ok {
Expand Down
Loading

0 comments on commit 1b0103e

Please sign in to comment.