Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

chore: add support for gocritic #4063

Merged
merged 6 commits into from
Aug 22, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions .golangci.yml
Original file line number Diff line number Diff line change
Expand Up @@ -23,6 +23,7 @@ linters:
- gocheckcompilerdirectives # Checks that go compiler directive comments (//go:) are valid. [fast: true, auto-fix: false]
- gochecksumtype # Run exhaustiveness checks on Go "sum types" [fast: false, 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]
- gofumpt # Gofumpt checks whether code was gofumpt-ed. [fast: true, auto-fix: true]
Expand Down
7 changes: 6 additions & 1 deletion cmd/scw/main.go
Original file line number Diff line number Diff line change
Expand Up @@ -60,6 +60,11 @@ func buildVersion() string {
}

func main() {
exitCode := mainNoExit()
os.Exit(exitCode)
}

func mainNoExit() int {
buildInfo := &core.BuildInfo{
Version: version.Must(version.NewSemver(buildVersion())), // panic when version does not respect semantic versioning
BuildDate: BuildDate,
Expand All @@ -82,5 +87,5 @@ func main() {
Platform: terminal.NewPlatform(buildInfo.GetUserAgent()),
})

os.Exit(exitCode)
return exitCode
}
2 changes: 1 addition & 1 deletion internal/args/marshal.go
Original file line number Diff line number Diff line change
Expand Up @@ -27,7 +27,7 @@ var marshalFuncs = map[reflect.Type]MarshalFunc{
reflect.TypeOf((*scw.Size)(nil)).Elem(): func(src interface{}) (s string, e error) {
v := src.(*scw.Size)
value := humanize.Bytes(uint64(*v))
value = strings.Replace(value, " ", "", -1)
value = strings.ReplaceAll(value, " ", "")
return value, nil
},
reflect.TypeOf((*time.Time)(nil)).Elem(): func(src interface{}) (string, error) {
Expand Down
3 changes: 1 addition & 2 deletions internal/core/autocomplete.go
Original file line number Diff line number Diff line change
Expand Up @@ -370,8 +370,7 @@ func AutoCompleteArgValue(ctx context.Context, cmd *Command, argSpec *ArgSpec, a
possibleValues := []string(nil)

if fieldType, err := args.GetArgType(cmd.ArgsType, argSpec.Name); err == nil {
switch fieldType.Kind() {
case reflect.Bool:
if fieldType.Kind() == reflect.Bool {
possibleValues = []string{"true", "false"}
}
}
Expand Down
4 changes: 2 additions & 2 deletions internal/core/autocomplete_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -89,8 +89,8 @@ func runAutocompleteTest(ctx context.Context, tc *autoCompleteTestCase) func(*te
t.Helper()
words := tc.Words
if len(words) == 0 {
name := strings.Replace(t.Name(), "TestAutocomplete/", "", -1)
name = strings.Replace(name, "_", " ", -1)
name := strings.ReplaceAll(t.Name(), "TestAutocomplete/", "")
name = strings.ReplaceAll(name, "_", " ")
// Test can contain a sharp if duplicated
// MyTest/scw_-flag_#01
sharpIndex := strings.Index(name, "#")
Expand Down
2 changes: 1 addition & 1 deletion internal/core/autocomplete_utils.go
Original file line number Diff line number Diff line change
Expand Up @@ -73,7 +73,7 @@ func AutocompleteProfileName() AutoCompleteArgFunc {
}
}

if strings.HasPrefix(scw.DefaultProfileName, prefix) {
if strings.HasPrefix(scw.DefaultProfileName, prefix) { //nolint:gocritic
res = append(res, scw.DefaultProfileName)
}
return res
Expand Down
2 changes: 1 addition & 1 deletion internal/core/cobra_utils.go
Original file line number Diff line number Diff line change
Expand Up @@ -206,7 +206,7 @@ func handleUnmarshalErrors(cmd *Command, unmarshalErr *args.UnmarshalArgError) e

switch e := wrappedErr.(type) {
case *args.CannotUnmarshalError:
switch e.Err.(type) {
switch e.Err.(type) { //nolint:gocritic
case *args.CannotParseBoolError:
return &CliError{
Err: errors.New(""),
Expand Down
7 changes: 4 additions & 3 deletions internal/core/command.go
Original file line number Diff line number Diff line change
Expand Up @@ -386,11 +386,12 @@ func (c *Commands) applyAliases(config *alias.Config) {
for _, command := range c.commands {
aliases := []alias.Alias(nil)
exists := false
if command.Verb != "" {
switch {
case command.Verb != "":
aliases, exists = config.ResolveAliasesByFirstWord(command.Verb)
} else if command.Resource != "" {
case command.Resource != "":
aliases, exists = config.ResolveAliasesByFirstWord(command.Resource)
} else if command.Namespace != "" {
case command.Namespace != "":
aliases, exists = config.ResolveAliasesByFirstWord(command.Namespace)
}
if exists {
Expand Down
6 changes: 2 additions & 4 deletions internal/core/command_interceptor.go
Original file line number Diff line number Diff line change
Expand Up @@ -103,8 +103,7 @@ func sdkStdErrorInterceptor(ctx context.Context, args interface{}, runner Comman
}
case *scw.ResourceExpiredError:
var hint string
switch resourceName := sdkError.Resource; resourceName {
case "account_token":
if sdkError.Resource == "account_token" {
hint = "Try to generate a new token here https://console.scaleway.com/iam/api-keys"
}

Expand All @@ -124,8 +123,7 @@ func sdkStdTypeInterceptor(ctx context.Context, args interface{}, runner Command
if err != nil {
return res, err
}
switch sdkValue := res.(type) {
case *scw.File:
if sdkValue, ok := res.(*scw.File); ok {
ExtractLogger(ctx).Debug("Intercepting scw.File type, rendering as string")
fileContent, err := io.ReadAll(sdkValue.Content)
if err != nil {
Expand Down
18 changes: 6 additions & 12 deletions internal/core/reflect_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -91,10 +91,8 @@ func Test_getValuesForFieldByName(t *testing.T) {
values, err := core.GetValuesForFieldByName(reflect.ValueOf(tc.cmdArgs), strings.Split(tc.fieldName, "."))
if err != nil {
assert.Equal(t, tc.expectedError, err.Error())
} else {
if tc.expectedValues != nil && !reflect.DeepEqual(tc.expectedValues[0].Interface(), values[0].Interface()) {
t.Errorf("Expected %v, got %v", tc.expectedValues[0].Interface(), values[0].Interface())
}
} else if tc.expectedValues != nil && !reflect.DeepEqual(tc.expectedValues[0].Interface(), values[0].Interface()) {
t.Errorf("Expected %v, got %v", tc.expectedValues[0].Interface(), values[0].Interface())
}
},
},
Expand Down Expand Up @@ -122,10 +120,8 @@ func Test_getValuesForFieldByName(t *testing.T) {
values, err := core.GetValuesForFieldByName(reflect.ValueOf(tc.cmdArgs), strings.Split(tc.fieldName, "."))
if err != nil {
assert.Equal(t, tc.expectedError, err.Error())
} else {
if tc.expectedValues != nil && !reflect.DeepEqual(tc.expectedValues[0].Interface(), values[0].Interface()) {
t.Errorf("Expected %v, got %v", tc.expectedValues[0].Interface(), values[0].Interface())
}
} else if tc.expectedValues != nil && !reflect.DeepEqual(tc.expectedValues[0].Interface(), values[0].Interface()) {
t.Errorf("Expected %v, got %v", tc.expectedValues[0].Interface(), values[0].Interface())
}
},
},
Expand Down Expand Up @@ -166,10 +162,8 @@ func Test_getValuesForFieldByName(t *testing.T) {
values, err := core.GetValuesForFieldByName(reflect.ValueOf(tc.cmdArgs), strings.Split(tc.fieldName, "."))
if err != nil {
assert.Equal(t, nil, err.Error())
} else {
if tc.expectedValues != nil && !reflect.DeepEqual(tc.expectedValues[0].Interface(), values[0].Interface()) {
t.Errorf("Expected %v, got %v", tc.expectedValues[0].Interface(), values[0].Interface())
}
} else if tc.expectedValues != nil && !reflect.DeepEqual(tc.expectedValues[0].Interface(), values[0].Interface()) {
t.Errorf("Expected %v, got %v", tc.expectedValues[0].Interface(), values[0].Interface())
}
},
},
Expand Down
7 changes: 4 additions & 3 deletions internal/core/shell.go
Original file line number Diff line number Diff line change
Expand Up @@ -77,11 +77,12 @@ func ArgIsOption(arg string) bool {
}

func argIsPositional(cmd *Command, arg string) bool {
if cmd.Verb != "" && cmd.Verb == arg {
switch {
case cmd.Verb != "" && cmd.Verb == arg:
return false
} else if cmd.Resource != "" && cmd.Resource == arg {
case cmd.Resource != "" && cmd.Resource == arg:
return false
} else if cmd.Namespace != "" && cmd.Resource == arg {
case cmd.Namespace != "" && cmd.Resource == arg:
return false
}

Expand Down
4 changes: 2 additions & 2 deletions internal/core/testing.go
Original file line number Diff line number Diff line change
Expand Up @@ -204,7 +204,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 Expand Up @@ -712,7 +712,7 @@ func removeRandomPrefixFromOutput(output string) string {
end := strings.IndexByte(output[begin:], '\n')
actualBucketName := output[begin : begin+end]
normalizedBucketName := strings.TrimRight(actualBucketName, "0123456789")
return strings.Replace(output, actualBucketName, normalizedBucketName, -1)
return strings.ReplaceAll(output, actualBucketName, normalizedBucketName)
}

// TestCheckError asserts error
Expand Down
2 changes: 1 addition & 1 deletion internal/gofields/gofields.go
Original file line number Diff line number Diff line change
Expand Up @@ -145,7 +145,7 @@ func listFields(t reflect.Type, parents []string, filter ListFieldFilter) []stri

fieldParents := parents
if !field.Anonymous {
fieldParents = append(parents, field.Name)
fieldParents = append(parents, field.Name) //nolint:gocritic
}

res = append(res, listFields(field.Type, fieldParents, filter)...)
Expand Down
3 changes: 1 addition & 2 deletions internal/human/marshal_func.go
Original file line number Diff line number Diff line change
Expand Up @@ -172,8 +172,7 @@ func defaultMarshalerFunc(i interface{}, _ *MarshalOpt) (string, error) {
i = "-"
}

switch v := i.(type) {
case string:
if v, ok := i.(string); ok {
if v == "" {
i = "-"
}
Expand Down
2 changes: 1 addition & 1 deletion internal/human/marshal_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -81,7 +81,7 @@ func TestMarshal(t *testing.T) {

// Format expected to allow indentation when writing test
expected := tc.result
expected = strings.Replace(expected, "\t", "", -1)
expected = strings.ReplaceAll(expected, "\t", "")
expected = strings.Trim(expected, "\n")

if tc.result != "" {
Expand Down
5 changes: 2 additions & 3 deletions internal/interactive/list.go
Original file line number Diff line number Diff line change
Expand Up @@ -28,9 +28,8 @@ func (m *ListPrompt) Init() tea.Cmd {
}

func (m *ListPrompt) Update(msg tea.Msg) (tea.Model, tea.Cmd) {
switch msg := msg.(type) {
// Key is pressed
case tea.KeyMsg:
if msg, ok := msg.(tea.KeyMsg); ok {
// Key is pressed
switch msg.String() {
case "ctrl+c", "q":
m.cancelled = true
Expand Down
4 changes: 2 additions & 2 deletions internal/interactive/prompt.go
Original file line number Diff line number Diff line change
Expand Up @@ -36,9 +36,9 @@ func PromptBoolWithConfig(config *PromptBoolConfig) (bool, error) {
for {
prompt := terminal.Style(config.Prompt, color.Bold)
if config.DefaultValue {
prompt = prompt + " (Y/n): "
prompt += " (Y/n): "
} else {
prompt = prompt + " (y/N): "
prompt += " (y/N): "
}

str, err := Readline(&ReadlineConfig{
Expand Down
4 changes: 2 additions & 2 deletions internal/namespaces/autocomplete/errors.go
Original file line number Diff line number Diff line change
Expand Up @@ -13,9 +13,9 @@ func unsupportedShellError(shell string) *core.CliError {
}
}

func unsupportedOsError(OS string) *core.CliError {
func unsupportedOsError(os string) *core.CliError {
return &core.CliError{
Err: fmt.Errorf("unsupported OS '%v'", OS),
Err: fmt.Errorf("unsupported OS '%v'", os),
}
}

Expand Down
4 changes: 2 additions & 2 deletions internal/namespaces/baremetal/v1/custom_offer.go
Original file line number Diff line number Diff line change
Expand Up @@ -41,8 +41,8 @@ func listOfferMarshalerFunc(i interface{}, opt *human.MarshalOpt) (string, error
Title: "PrivateBandwidth(Mbit/s)",
},
}
baremetalOffer.PrivateBandwidth = baremetalOffer.PrivateBandwidth / 1000000
baremetalOffer.Bandwidth = baremetalOffer.Bandwidth / 1000000
baremetalOffer.PrivateBandwidth /= 1000000
baremetalOffer.Bandwidth /= 1000000
str, err := human.Marshal(baremetalOffer, opt)
if err != nil {
return "", err
Expand Down
10 changes: 2 additions & 8 deletions internal/namespaces/billing/v2beta1/custom_invoice_download.go
Original file line number Diff line number Diff line change
Expand Up @@ -138,21 +138,15 @@ func invoiceDownloadBuilder(command *core.Command) *core.Command {
}

func addDownloadExt(fileName, contentType string) string {
switch contentType {
case "application/pdf":
if contentType == "application/pdf" {
fileName += ".pdf"
}

return fileName
}

func checkDownloadInvoiceExt(ext string) bool {
switch ext {
case ".pdf":
return true
}

return false
return ext == ".pdf"
}

func billingDownloadRun(ctx context.Context, argsI interface{}) (interface{}, error) {
Expand Down
10 changes: 2 additions & 8 deletions internal/namespaces/billing/v2beta1/custom_invoice_export.go
Original file line number Diff line number Diff line change
Expand Up @@ -184,19 +184,13 @@ func billingExportRun(ctx context.Context, argsI interface{}) (interface{}, erro
}

func addExportExt(fileName, contentType string) string {
switch contentType {
case "text/csv":
if contentType == "text/csv" {
fileName += ".csv"
}

return fileName
}

func checkExportInvoiceExt(ext string) bool {
switch ext {
case ".csv":
return true
}

return false
return ext == ".csv"
}
6 changes: 2 additions & 4 deletions internal/namespaces/init/prompt.go
Original file line number Diff line number Diff line change
Expand Up @@ -136,8 +136,7 @@ func promptSecretKey(ctx context.Context) (string, error) {
Ctx: ctx,
PromptFunc: func(value string) string {
secretKey := "secret-key"
switch {
case validation.IsUUID(value):
if validation.IsUUID(value) {
secretKey = terminal.Style(secretKey, color.FgBlue)
}
return terminal.Style(fmt.Sprintf("Enter a valid %s: ", secretKey), color.Bold)
Expand Down Expand Up @@ -169,8 +168,7 @@ func promptAccessKey(ctx context.Context) (string, error) {
Ctx: ctx,
PromptFunc: func(value string) string {
accessKey := "access-key"
switch {
case validation.IsAccessKey(value):
if validation.IsAccessKey(value) {
accessKey = terminal.Style(accessKey, color.FgBlue)
}
return terminal.Style(fmt.Sprintf("Enter a valid %s: ", accessKey), color.Bold)
Expand Down
8 changes: 4 additions & 4 deletions internal/namespaces/instance/v1/custom_server_create.go
Original file line number Diff line number Diff line change
Expand Up @@ -45,7 +45,7 @@ type instanceCreateServerRequest struct {
CloudInit string
BootType string

// Deprecated, use project-id instead
// Deprecated: use project-id instead
OrganizationID *string
}

Expand Down Expand Up @@ -513,7 +513,7 @@ func buildVolumeTemplateFromSnapshot(api *instance.API, zone scw.Zone, snapshotU
}, nil
}

func validateImageServerTypeCompatibility(image *instance.Image, serverType *instance.ServerType, CommercialType string) error {
func validateImageServerTypeCompatibility(image *instance.Image, serverType *instance.ServerType, commercialType string) error {
// An instance might not have any constraints on the local volume size
if serverType.VolumesConstraint.MaxSize == 0 {
return nil
Expand All @@ -524,7 +524,7 @@ func validateImageServerTypeCompatibility(image *instance.Image, serverType *ins
humanize.Bytes(uint64(image.RootVolume.Size)),
humanize.Bytes(uint64(serverType.VolumesConstraint.MinSize)),
humanize.Bytes(uint64(serverType.VolumesConstraint.MaxSize)),
CommercialType,
commercialType,
)
}

Expand Down Expand Up @@ -641,7 +641,7 @@ func instanceServerCreateImageAutoCompleteFunc(ctx context.Context, prefix strin
completeListImagesCache = res
}

prefix = strings.ToLower(strings.Replace(prefix, "-", "_", -1))
prefix = strings.ToLower(strings.ReplaceAll(prefix, "-", "_"))

for _, image := range completeListImagesCache.Images {
if strings.HasPrefix(image.Label, prefix) {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -144,7 +144,7 @@ func (sb *ServerBuilder) AddImage(image string) (*ServerBuilder, error) {
case image == "none":
return sb, nil
case !validation.IsUUID(image):
imageLabel := strings.Replace(image, "-", "_", -1)
imageLabel := strings.ReplaceAll(image, "-", "_")

localImage, err := sb.apiMarketplace.GetLocalImageByLabel(&marketplace.GetLocalImageByLabelRequest{
ImageLabel: imageLabel,
Expand Down
3 changes: 2 additions & 1 deletion internal/namespaces/instance/v1/custom_ssh_key.go
Original file line number Diff line number Diff line change
Expand Up @@ -112,7 +112,8 @@ Lookup /root/.ssh/authorized_keys on your server for more information`,
}
}

tags := append(server.Server.Tags, formattedKey)
tags := server.Server.Tags
tags = append(tags, formattedKey)

_, err = api.UpdateServer(&instance.UpdateServerRequest{
Zone: args.Zone,
Expand Down
3 changes: 2 additions & 1 deletion internal/namespaces/instance/v1/custom_ssh_key_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,8 @@ import (
func addSSHKey(serverKey string, sshKey string) core.BeforeFunc {
return func(ctx *core.BeforeFuncCtx) error {
server := ctx.Meta[serverKey].(*instanceSDK.Server)
tags := append(server.Tags, instance.FormatSSHKeyToTag(sshKey))
tags := server.Tags
tags = append(tags, instance.FormatSSHKeyToTag(sshKey))

resp, err := instanceSDK.NewAPI(ctx.Client).UpdateServer(&instanceSDK.UpdateServerRequest{
Zone: server.Zone,
Expand Down
3 changes: 1 addition & 2 deletions internal/namespaces/k8s/v1/custom_node.go
Original file line number Diff line number Diff line change
Expand Up @@ -43,8 +43,7 @@ func waitForNodeFunc(action int) core.WaitFunc {
Timeout: scw.TimeDurationPtr(nodeActionTimeout),
RetryInterval: core.DefaultRetryInterval,
})
switch action {
case nodeActionReboot:
if action == nodeActionReboot {
return node, err
}
return nil, err
Expand Down
Loading
Loading