Skip to content

Commit

Permalink
chore: fix gocritic linter
Browse files Browse the repository at this point in the history
  • Loading branch information
remyleone committed May 19, 2022
1 parent 3aca0e0 commit f243c17
Show file tree
Hide file tree
Showing 18 changed files with 83 additions and 84 deletions.
5 changes: 3 additions & 2 deletions .golangci.yml
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,7 @@ linters:
- forbidigo # Forbids identifiers [fast: true, auto-fix: false]
- gci # Gci controls golang package import order and makes it always deterministic. [fast: true, auto-fix: false]
- goconst # Finds repeated strings that could be replaced by a constant [fast: true, auto-fix: false]
- gocritic # Provides diagnostics that check for bugs, performance and style issues. [fast: false, auto-fix: false]
- gocyclo # Computes and checks the cyclomatic complexity of functions [fast: true, auto-fix: false]
- gofmt # Gofmt checks whether code was gofmt-ed. By default this tool runs with -s option to check for code simplification [fast: true, auto-fix: true]
- goheader # Checks is file header matches to pattern [fast: true, auto-fix: false]
Expand Down Expand Up @@ -63,12 +64,10 @@ linters:
- errorlint # errorlint is a linter for that can be used to find code that will cause problems with the error wrapping scheme introduced in Go 1.13. [fast: false, auto-fix: false]
- exhaustive # check exhaustiveness of enum switch statements [fast: false, auto-fix: false]
- exhaustruct # Checks if all structure fields are initialized [fast: false, auto-fix: false]
- forcetypeassert # finds forced type assertions [fast: true, auto-fix: false]
- funlen # Tool for detection of long functions [fast: true, auto-fix: false]
- gochecknoglobals # check that no global variables exist [fast: true, auto-fix: false]
- gochecknoinits # Checks that no init functions are present in Go code [fast: true, auto-fix: false]
- gocognit # Computes and checks the cognitive complexity of functions [fast: true, auto-fix: false]
- gocritic # Provides diagnostics that check for bugs, performance and style issues. [fast: false, auto-fix: false]
- godot # Check if comments end in a period [fast: true, auto-fix: true]
- godox # Tool for detection of FIXME, TODO and other comment keywords [fast: true, auto-fix: false]
- goerr113 # Golang linter to check the errors handling expressions [fast: false, auto-fix: false]
Expand Down Expand Up @@ -102,3 +101,5 @@ issues:
linters:
- stylecheck
- gosec
max-same-issues: 0
max-issues-per-linter: 0
2 changes: 1 addition & 1 deletion scaleway/data_source_baremetal_offer_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -43,7 +43,7 @@ func TestAccScalewayDataSourceBaremetalOffer_Basic(t *testing.T) {
resource.TestCheckResourceAttr("data.scaleway_baremetal_offer.test2", "include_disabled", "false"),
resource.TestCheckResourceAttr("data.scaleway_baremetal_offer.test2", "bandwidth", "1000000000"),
resource.TestCheckResourceAttr("data.scaleway_baremetal_offer.test2", "commercial_range", "aluminium"),
//resource.TestCheckResourceAttr("data.scaleway_baremetal_offer.test2", "stock", "available"), // skipping this as stocks vary too much
// resource.TestCheckResourceAttr("data.scaleway_baremetal_offer.test2", "stock", "available"), // skipping this as stocks vary too much
resource.TestCheckResourceAttr("data.scaleway_baremetal_offer.test2", "cpu.0.name", "AMD Ryzen PRO 3600"),
resource.TestCheckResourceAttr("data.scaleway_baremetal_offer.test2", "cpu.0.core_count", "6"),
resource.TestCheckResourceAttr("data.scaleway_baremetal_offer.test2", "cpu.0.frequency", "3600"),
Expand Down
2 changes: 1 addition & 1 deletion scaleway/data_source_object_bucket_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,7 @@ func TestAccScalewayDataSourceObjectStorage_Basic(t *testing.T) {
tt := NewTestTools(t)
defer tt.Cleanup()
bucketName := sdkacctest.RandomWithPrefix("test-acc-scaleway-object-bucket")
//resourceName := "data.scaleway_object_bucket.main"
// resourceName := "data.scaleway_object_bucket.main"
resource.ParallelTest(t, resource.TestCase{
PreCheck: func() { testAccPreCheck(t) },
ProviderFactories: tt.ProviderFactories,
Expand Down
25 changes: 12 additions & 13 deletions scaleway/helpers.go
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,6 @@ import (
"github.com/hashicorp/terraform-plugin-sdk/v2/helper/validation"
"github.com/scaleway/scaleway-sdk-go/namegenerator"
"github.com/scaleway/scaleway-sdk-go/scw"
"golang.org/x/xerrors"
)

var (
Expand All @@ -44,7 +43,7 @@ func newRegionalID(region scw.Region, id string) RegionalID {

func expandRegionalID(id interface{}) RegionalID {
regionalID := RegionalID{}
tab := strings.SplitN(id.(string), "/", -1)
tab := strings.Split(id.(string), "/")
if len(tab) != 2 {
regionalID.ID = id.(string)
} else {
Expand Down Expand Up @@ -75,7 +74,7 @@ func newZonedID(zone scw.Zone, id string) ZonedID {

func expandZonedID(id interface{}) ZonedID {
zonedID := ZonedID{}
tab := strings.SplitN(id.(string), "/", -1)
tab := strings.Split(id.(string), "/")
if len(tab) != 2 {
zonedID.ID = id.(string)
} else {
Expand All @@ -88,8 +87,8 @@ func expandZonedID(id interface{}) ZonedID {
}

// parseLocalizedID parses a localizedID and extracts the resource locality and id.
func parseLocalizedID(localizedID string) (locality string, ID string, err error) {
tab := strings.SplitN(localizedID, "/", -1)
func parseLocalizedID(localizedID string) (locality string, id string, err error) {
tab := strings.Split(localizedID, "/")
if len(tab) != 2 {
return "", localizedID, fmt.Errorf("cant parse localized id: %s", localizedID)
}
Expand All @@ -98,7 +97,7 @@ func parseLocalizedID(localizedID string) (locality string, ID string, err error

// parseLocalizedNestedID parses a localizedNestedID and extracts the resource locality, the inner and outer id.
func parseLocalizedNestedID(localizedID string) (locality string, innerID, outerID string, err error) {
tab := strings.SplitN(localizedID, "/", -1)
tab := strings.Split(localizedID, "/")
if len(tab) != 3 {
return "", "", localizedID, fmt.Errorf("cant parse localized id: %s", localizedID)
}
Expand Down Expand Up @@ -219,7 +218,7 @@ func isHTTPCodeError(err error, statusCode int) bool {
}

responseError := &scw.ResponseError{}
if xerrors.As(err, &responseError) && responseError.StatusCode == statusCode {
if errors.As(err, &responseError) && responseError.StatusCode == statusCode {
return true
}
return false
Expand All @@ -228,25 +227,25 @@ func isHTTPCodeError(err error, statusCode int) bool {
// is404Error returns true if err is an HTTP 404 error
func is404Error(err error) bool {
notFoundError := &scw.ResourceNotFoundError{}
return isHTTPCodeError(err, http.StatusNotFound) || xerrors.As(err, &notFoundError)
return isHTTPCodeError(err, http.StatusNotFound) || errors.As(err, &notFoundError)
}

func is412Error(err error) bool {
preConditionFailedError := &scw.PreconditionFailedError{}
return isHTTPCodeError(err, http.StatusPreconditionFailed) || xerrors.As(err, &preConditionFailedError)
return isHTTPCodeError(err, http.StatusPreconditionFailed) || errors.As(err, &preConditionFailedError)
}

// is403Error returns true if err is an HTTP 403 error
func is403Error(err error) bool {
permissionsDeniedError := &scw.PermissionsDeniedError{}
return isHTTPCodeError(err, http.StatusForbidden) || xerrors.As(err, &permissionsDeniedError)
return isHTTPCodeError(err, http.StatusForbidden) || errors.As(err, &permissionsDeniedError)
}

// is409Error return true is err is an HTTP 409 error
func is409Error(err error) bool {
//check transient error
// check transient error
transientStateError := &scw.TransientStateError{}
return isHTTPCodeError(err, http.StatusConflict) || xerrors.As(err, &transientStateError)
return isHTTPCodeError(err, http.StatusConflict) || errors.As(err, &transientStateError)
}

// organizationIDSchema returns a standard schema for a organization_id
Expand Down Expand Up @@ -560,7 +559,7 @@ func diffSuppressFuncIgnoreCase(k, old, new string, d *schema.ResourceData) bool
}

func diffSuppressFuncIgnoreCaseAndHyphen(k, old, new string, d *schema.ResourceData) bool {
return strings.Replace(strings.ToLower(old), "-", "_", -1) == strings.Replace(strings.ToLower(new), "-", "_", -1)
return strings.ReplaceAll(strings.ToLower(old), "-", "_") == strings.ReplaceAll(strings.ToLower(new), "-", "_")
}

// diffSuppressFuncLocality is a SuppressDiffFunc to remove the locality from an ID when checking diff.
Expand Down
4 changes: 2 additions & 2 deletions scaleway/helpers_apple_silicon.go
Original file line number Diff line number Diff line change
Expand Up @@ -42,14 +42,14 @@ func asAPIWithZoneAndID(m interface{}, id string) (*applesilicon.API, scw.Zone,
return asAPI, zone, ID, nil
}

func waitForAppleSiliconServer(ctx context.Context, api *applesilicon.API, zone scw.Zone, ID string, timeout time.Duration) (*applesilicon.Server, error) {
func waitForAppleSiliconServer(ctx context.Context, api *applesilicon.API, zone scw.Zone, serverID string, timeout time.Duration) (*applesilicon.Server, error) {
retryInterval := defaultAppleSiliconServerRetryInterval
if DefaultWaitRetryInterval != nil {
retryInterval = *DefaultWaitRetryInterval
}

server, err := api.WaitForServer(&applesilicon.WaitForServerRequest{
ServerID: ID,
ServerID: serverID,
Zone: zone,
Timeout: scw.TimeDurationPtr(timeout),
RetryInterval: &retryInterval,
Expand Down
8 changes: 4 additions & 4 deletions scaleway/helpers_baremetal.go
Original file line number Diff line number Diff line change
Expand Up @@ -102,31 +102,31 @@ func flattenBaremetalIPs(ips []*baremetal.IP) interface{} {
return flattendIPs
}

func waitForBaremetalServer(ctx context.Context, api *baremetal.API, zone scw.Zone, ID string, timeout time.Duration) (*baremetal.Server, error) {
func waitForBaremetalServer(ctx context.Context, api *baremetal.API, zone scw.Zone, serverID string, timeout time.Duration) (*baremetal.Server, error) {
retryInterval := baremetalRetryInterval
if DefaultWaitRetryInterval != nil {
retryInterval = *DefaultWaitRetryInterval
}

server, err := api.WaitForServer(&baremetal.WaitForServerRequest{
Zone: zone,
ServerID: ID,
ServerID: serverID,
Timeout: scw.TimeDurationPtr(timeout),
RetryInterval: &retryInterval,
}, scw.WithContext(ctx))

return server, err
}

func waitForBaremetalServerInstall(ctx context.Context, api *baremetal.API, zone scw.Zone, ID string, timeout time.Duration) (*baremetal.Server, error) {
func waitForBaremetalServerInstall(ctx context.Context, api *baremetal.API, zone scw.Zone, serverID string, timeout time.Duration) (*baremetal.Server, error) {
retryInterval := baremetalRetryInterval
if DefaultWaitRetryInterval != nil {
retryInterval = *DefaultWaitRetryInterval
}

server, err := api.WaitForServerInstall(&baremetal.WaitForServerInstallRequest{
Zone: zone,
ServerID: ID,
ServerID: serverID,
Timeout: scw.TimeDurationPtr(timeout),
RetryInterval: &retryInterval,
}, scw.WithContext(ctx))
Expand Down
28 changes: 14 additions & 14 deletions scaleway/helpers_lb.go
Original file line number Diff line number Diff line change
Expand Up @@ -69,7 +69,7 @@ func expandLbACL(i interface{}) *lbSDK.ACL {
Action: expandLbACLAction(rawRule["action"]),
}

//remove http filter values if we do not pass any http filter
// remove http filter values if we do not pass any http filter
if acl.Match.HTTPFilter == "" || acl.Match.HTTPFilter == lbSDK.ACLHTTPFilterACLHTTPFilterNone {
acl.Match.HTTPFilter = lbSDK.ACLHTTPFilterACLHTTPFilterNone
acl.Match.HTTPFilterValue = []*string{}
Expand Down Expand Up @@ -116,18 +116,18 @@ func expandPrivateNetworks(data interface{}, lbID string) ([]*lbSDK.ZonedAPIAtta
return res, nil
}

func isPrivateNetworkEqual(A, B interface{}) bool {
func isPrivateNetworkEqual(a, b interface{}) bool {
// Find out the diff Private Network or not
if _, ok := A.(*lbSDK.PrivateNetwork); ok {
if _, ok := B.(*lbSDK.PrivateNetwork); ok {
if A.(*lbSDK.PrivateNetwork).PrivateNetworkID == B.(*lbSDK.PrivateNetwork).PrivateNetworkID {
if _, ok := a.(*lbSDK.PrivateNetwork); ok {
if _, ok := b.(*lbSDK.PrivateNetwork); ok {
if a.(*lbSDK.PrivateNetwork).PrivateNetworkID == b.(*lbSDK.PrivateNetwork).PrivateNetworkID {
// if both has dhcp config should not update
if A.(*lbSDK.PrivateNetwork).DHCPConfig != nil && B.(*lbSDK.PrivateNetwork).DHCPConfig != nil {
if a.(*lbSDK.PrivateNetwork).DHCPConfig != nil && b.(*lbSDK.PrivateNetwork).DHCPConfig != nil {
return true
}
// check static config
aConfig := A.(*lbSDK.PrivateNetwork).StaticConfig
bConfig := B.(*lbSDK.PrivateNetwork).StaticConfig
aConfig := a.(*lbSDK.PrivateNetwork).StaticConfig
bConfig := b.(*lbSDK.PrivateNetwork).StaticConfig
if aConfig != nil && bConfig != nil {
// check if static config is different
return reflect.DeepEqual(aConfig.IPAddress, bConfig.IPAddress)
Expand Down Expand Up @@ -159,7 +159,7 @@ func privateNetworksToDetach(pns []*lbSDK.PrivateNetwork, updates interface{}) (
actions[pn.PrivateNetworkID] = true
configs[pn.PrivateNetworkID] = pn
}
//check if private network still exist or is different
// check if private network still exist or is different
for _, pn := range updates.([]interface{}) {
r := pn.(map[string]interface{})
_, pnID, err := parseZonedID(r["private_network_id"].(string))
Expand Down Expand Up @@ -226,7 +226,7 @@ func expandLbACLMatch(raw interface{}) *lbSDK.ACLMatch {
}
rawMap := raw.([]interface{})[0].(map[string]interface{})

//scaleway api require ip subnet, so if we did not specify one, just put 0.0.0.0/0 instead
// scaleway api require ip subnet, so if we did not specify one, just put 0.0.0.0/0 instead
ipSubnet := expandSliceStringPtr(rawMap["ip_subnet"].([]interface{}))
if len(ipSubnet) == 0 {
ipSubnet = []*string{expandStringPtr("0.0.0.0/0")}
Expand Down Expand Up @@ -435,14 +435,14 @@ func expandLbPrivateNetworkDHCPConfig(raw interface{}) *lbSDK.PrivateNetworkDHCP
return &lbSDK.PrivateNetworkDHCPConfig{}
}

func waitForLB(ctx context.Context, lbAPI *lbSDK.ZonedAPI, zone scw.Zone, LbID string, timeout time.Duration) (*lbSDK.LB, error) {
func waitForLB(ctx context.Context, lbAPI *lbSDK.ZonedAPI, zone scw.Zone, lbID string, timeout time.Duration) (*lbSDK.LB, error) {
retryInterval := defaultWaitLBRetryInterval
if DefaultWaitRetryInterval != nil {
retryInterval = *DefaultWaitRetryInterval
}

loadBalancer, err := lbAPI.WaitForLb(&lbSDK.ZonedAPIWaitForLBRequest{
LBID: LbID,
LBID: lbID,
Zone: zone,
Timeout: scw.TimeDurationPtr(timeout),
RetryInterval: &retryInterval,
Expand All @@ -467,14 +467,14 @@ func waitForLbInstances(ctx context.Context, lbAPI *lbSDK.ZonedAPI, zone scw.Zon
return loadBalancer, err
}

func waitForLBPN(ctx context.Context, lbAPI *lbSDK.ZonedAPI, zone scw.Zone, LbID string, timeout time.Duration) ([]*lbSDK.PrivateNetwork, error) {
func waitForLBPN(ctx context.Context, lbAPI *lbSDK.ZonedAPI, zone scw.Zone, lbID string, timeout time.Duration) ([]*lbSDK.PrivateNetwork, error) {
retryInterval := defaultWaitLBRetryInterval
if DefaultWaitRetryInterval != nil {
retryInterval = *DefaultWaitRetryInterval
}

privateNetworks, err := lbAPI.WaitForLBPN(&lbSDK.ZonedAPIWaitForLBPNRequest{
LBID: LbID,
LBID: lbID,
Zone: zone,
Timeout: scw.TimeDurationPtr(timeout),
RetryInterval: &retryInterval,
Expand Down
10 changes: 5 additions & 5 deletions scaleway/helpers_rdb.go
Original file line number Diff line number Diff line change
Expand Up @@ -168,12 +168,12 @@ func newEndPointPrivateNetworkDetails(id, ip, locality string) (*rdb.EndpointPri
}, nil
}

func isEndPointEqual(A, B interface{}) bool {
func isEndPointEqual(a, b interface{}) bool {
// Find out the diff Private Network or not
if _, ok := A.(*rdb.EndpointPrivateNetworkDetails); ok {
if _, ok := B.(*rdb.EndpointPrivateNetworkDetails); ok {
detailsA := A.(*rdb.EndpointPrivateNetworkDetails)
detailsB := B.(*rdb.EndpointPrivateNetworkDetails)
if _, ok := a.(*rdb.EndpointPrivateNetworkDetails); ok {
if _, ok := b.(*rdb.EndpointPrivateNetworkDetails); ok {
detailsA := a.(*rdb.EndpointPrivateNetworkDetails)
detailsB := b.(*rdb.EndpointPrivateNetworkDetails)
return reflect.DeepEqual(detailsA, detailsB)
}
}
Expand Down
2 changes: 1 addition & 1 deletion scaleway/provider_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -32,7 +32,7 @@ func getTestFilePath(t *testing.T, suffix string) string {
specialChars := regexp.MustCompile(`[\\?%*:|"<>. ]`)

// Replace nested tests separators.
fileName := strings.Replace(t.Name(), "/", "-", -1)
fileName := strings.ReplaceAll(t.Name(), "/", "-")

fileName = strcase.ToBashArg(fileName)

Expand Down
2 changes: 1 addition & 1 deletion scaleway/resource_domain_record.go
Original file line number Diff line number Diff line change
Expand Up @@ -304,7 +304,7 @@ func resourceScalewayDomainRecordRead(ctx context.Context, d *schema.ResourceDat
currentData := d.Get("data")
// check if this is an inline import. Like: "terraform import scaleway_domain_record.www subdomain.domain.tld/11111111-1111-1111-1111-111111111111"
if strings.Contains(d.Id(), "/") {
tab := strings.SplitN(d.Id(), "/", -1)
tab := strings.Split(d.Id(), "/")
if len(tab) != 2 {
return diag.FromErr(fmt.Errorf("cant parse record id: %s", d.Id()))
}
Expand Down
8 changes: 4 additions & 4 deletions scaleway/resource_instance_server.go
Original file line number Diff line number Diff line change
Expand Up @@ -599,11 +599,11 @@ func resourceScalewayInstanceServerRead(ctx context.Context, d *schema.ResourceD
if err != nil {
return diag.FromErr(err)
}
//if key != "cloud-init" {
// if key != "cloud-init" {
userData[key] = string(userDataValue)
// } else {
//_ = d.Set("cloud_init", string(userDataValue))
//}
// _ = d.Set("cloud_init", string(userDataValue))
// }
}
if len(userData) > 0 {
_ = d.Set("user_data", userData)
Expand Down Expand Up @@ -744,7 +744,7 @@ func resourceScalewayInstanceServerUpdate(ctx context.Context, d *schema.Resourc
if err != nil {
return diag.FromErr(err)
}
//we wait to ensure to not detach the new ip.
// we wait to ensure to not detach the new ip.
_, err := waitForInstanceServer(ctx, instanceAPI, zone, id, d.Timeout(schema.TimeoutUpdate))
if err != nil {
return diag.FromErr(err)
Expand Down
6 changes: 3 additions & 3 deletions scaleway/resource_iot_device_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -114,9 +114,9 @@ func TestAccScalewayIotDevice_MessageFilters(t *testing.T) {
resource.TestCheckResourceAttr("scaleway_iot_device.default-4", "allow_multiple_connections", "false"),
resource.TestCheckResourceAttr("scaleway_iot_device.default-4", "message_filters.0.publish.0.policy", "reject"),
// TODO: The following checks seem to be flaky.
//resource.TestCheckResourceAttr("scaleway_iot_device.default-4", "message_filters.0.publish.0.topics.0", "1"),
//resource.TestCheckResourceAttr("scaleway_iot_device.default-4", "message_filters.0.subscribe.0.policy", "accept"),
//resource.TestCheckResourceAttr("scaleway_iot_device.default-4", "message_filters.0.subscribe.0.topics.0", "4"),
// resource.TestCheckResourceAttr("scaleway_iot_device.default-4", "message_filters.0.publish.0.topics.0", "1"),
// resource.TestCheckResourceAttr("scaleway_iot_device.default-4", "message_filters.0.subscribe.0.policy", "accept"),
// resource.TestCheckResourceAttr("scaleway_iot_device.default-4", "message_filters.0.subscribe.0.topics.0", "4"),
),
},
},
Expand Down
2 changes: 1 addition & 1 deletion scaleway/resource_k8s_cluster_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -81,7 +81,7 @@ func testSweepK8SCluster(_ string) error {
}

for _, cluster := range listClusters.Clusters {
//remove pools
// remove pools
listPools, err := k8sAPI.ListPools(&k8s.ListPoolsRequest{
Region: region,
ClusterID: cluster.ID,
Expand Down
4 changes: 2 additions & 2 deletions scaleway/resource_lb.go
Original file line number Diff line number Diff line change
Expand Up @@ -151,7 +151,7 @@ func resourceScalewayLbCreate(ctx context.Context, d *schema.ResourceData, meta
return diag.FromErr(err)
}

//attach private network
// attach private network
pnConfigs, pnExist := d.GetOk("private_network")
if pnExist {
pnConfigs, err := expandPrivateNetworks(pnConfigs, lb.ID)
Expand Down Expand Up @@ -271,7 +271,7 @@ func resourceScalewayLbUpdate(ctx context.Context, d *schema.ResourceData, meta
}
}

//attach private network
// attach private network
pnConfigs, pnExist := d.GetOk("private_network")
if pnExist {
pnConfigs, err := expandPrivateNetworks(pnConfigs, ID)
Expand Down

0 comments on commit f243c17

Please sign in to comment.