Skip to content

Commit

Permalink
chore: add support for gocritic
Browse files Browse the repository at this point in the history
  • Loading branch information
remyleone committed Aug 21, 2024
1 parent 44f37c5 commit 3006ee8
Show file tree
Hide file tree
Showing 39 changed files with 358 additions and 353 deletions.
1 change: 1 addition & 0 deletions .golangci.yml
Original file line number Diff line number Diff line change
Expand Up @@ -46,6 +46,7 @@ linters:
- unused #(megacheck): Checks Go code for unused constants, variables, functions and types [fast: false, auto-fix: false]
- whitespace # Tool for detection of leading and trailing whitespace [fast: true, auto-fix: true]
- zerologlint # Detects the wrong usage of `zerolog` that a user forgets to dispatch with `Send` or `Msg` [fast: false, auto-fix: false]
- gocritic # Provides diagnostics that check for bugs, performance and style issues. [fast: false, auto-fix: false]

disable:
- cyclop # checks function and package cyclomatic complexity [fast: false, auto-fix: false]
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
return func(t *testing.T) {
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
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 @@ -90,10 +90,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 All @@ -120,10 +118,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 @@ -163,10 +159,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 @@ -203,7 +203,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 @@ -704,7 +704,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
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 @@ -27,9 +27,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 @@ -12,9 +12,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 @@ -137,21 +137,15 @@ func invoiceDownloadBuilder(command *core.Command) *core.Command {
}

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

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 @@ -183,19 +183,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 = fmt.Sprintf("%s.csv", fileName)
}

return fileName
}

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

return false
return ext == ".csv"
}
Loading

0 comments on commit 3006ee8

Please sign in to comment.