Skip to content

feat(sggolangcilintv2): add golangci-lint v2 #661

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

Open
wants to merge 2 commits into
base: master
Choose a base branch
from

Conversation

fredrikaverpil
Copy link
Member

@fredrikaverpil fredrikaverpil commented Mar 24, 2025

Why?

Golangci-lint was bumped to v2.

What?

  • Add sggolangcilintv2 as there are backwards braking changes to the CLI. The CLI arguments will differ from golangci-lint v1 and options around exclusion paths have been moved from the CLI so they must be defined in the config yaml.
  • Deprecate sggolangcilint.
  • Use golangci-lint v2.1.1.
  • Run golangci-lint migrate -c golangci.yml. This sorted the linters for us, so they are now in alphabetical order. The gci, gofumpt linters were removed (now exists as formatters) and gosimple has been absorbed by staticcheck.
  • Add comments back in which were removed by the migration tool.
  • Address new linting issues found by golangci-lint.
  • Use templating to allow per-project customization.

Will be saved for a separate PR

Enabled vs disabled linters
Name Description Enabled
asasalint Check for pass []any as any in variadic func(...any).
asciicheck Checks that all code identifiers does not have non-ASCII symbols in the name.
bidichk Checks for dangerous unicode character sequences.
bodyclose Checks whether HTTP response body is closed successfully.
canonicalheader Canonicalheader checks whether net/http.Header uses canonical header.
containedctx Containedctx is a linter that detects struct contained context.Context field.  
contextcheck Check whether the function uses a non-inherited context.  
copyloopvar A linter detects places where loop variables are copied.
cyclop Checks function and package cyclomatic complexity.  
decorder Check declaration order and count of types, constants, variables and functions.  
depguard Go linter that checks if package imports are in a list of acceptable packages.  
dogsled Checks assignments with too many blank identifiers (e.g. x, , , _, := f()).  
dupl Detects duplicate fragments of code.  
dupword Checks for duplicate words in the source code.
durationcheck Check for two durations multiplied together.
err113 Go linter to check the errors handling expressions.
errcheck Check for unchecked errors. Unchecked errors can be critical bugs in some cases.
errchkjson Checks types passed to the json encoding functions. Reports unsupported types and reports occurrences where the check for the returned error can be omitted.
errname Checks that sentinel errors are prefixed with the Err and error types are suffixed with the Error.
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.
exhaustive Check exhaustiveness of enum switch statements.  
exhaustruct Checks if all structure fields are initialized.  
exptostd Detects functions from golang.org/x/exp/ that can be replaced by std functions.
fatcontext Detects nested contexts in loops and function literals.
forbidigo Forbids identifiers.  
forcetypeassert Finds forced type assertions.  
funlen Checks for long functions.  
ginkgolinter Enforces standards of using ginkgo and gomega.
gocheckcompilerdirectives Checks that go compiler directive comments (//go:) are valid.  
gochecknoglobals Check that no global variables exist. ✅ 
gochecknoinits Checks that no init functions are present in Go code. ✅ 
gochecksumtype Run exhaustiveness checks on Go "sum types".  
gocognit Computes and checks the cognitive complexity of functions.  
goconst Finds repeated strings that could be replaced by a constant.  
gocritic Provides diagnostics that check for bugs, performance and style issues.Extensible without recompilation through dynamic rules.Dynamic rules are written declaratively with AST patterns, filters, report message and optional suggestion.
gocyclo Computes and checks the cyclomatic complexity of functions.  
godot Check if comments end in a period.
godox Detects usage of FIXME, TODO and other keywords inside comments.  
goheader Checks if file header matches to pattern.
gomoddirectives Manage the use of 'replace', 'retract', and 'excludes' directives in go.mod. ✅ 
gomodguard Allow and block list linter for direct Go module dependencies. This is different from depguard where there are different block types for example version constraints and module recommendations. ✅ 
goprintffuncname Checks that printf-like functions are named with f at the end. ✅ 
gosec Inspects source code for security problems.
gosmopolitan Report certain i18n/l10n anti-patterns in your Go codebase.  
govet Report suspicious constructs, such as Printf calls whose arguments do not align with the format string.
grouper Analyze expression groups.  
iface Detect the incorrect use of interfaces, helping developers avoid interface pollution.
importas Enforces consistent import aliases.
inamedparam Reports interfaces with unnamed method parameters.  
ineffassign Detect when assignments to existing variables are not used.
interfacebloat A linter that checks the number of methods inside an interface.  
intrange Intrange is a linter to find places where for loops could make use of an integer range.
ireturn Accept Interfaces, Return Concrete Types.  
lll Reports long lines.
loggercheck Checks key value pairs for common logger libraries (kitlog,klog,logr,zap).  
maintidx Maintidx measures the maintainability index of each function.  
makezero Finds slice declarations with non-zero initial length.
mirror Reports wrong mirror patterns of bytes/strings usage.
misspell Finds commonly misspelled English words.
mnd An analyzer to detect magic numbers.  
musttag Enforce field tags in (un)marshaled structs.  
nakedret Checks that functions with naked returns are not longer than a maximum size (can be zero).
nestif Reports deeply nested if statements.  
nilerr Finds the code that returns nil even if it checks that the error is not nil. ✅ 
nilnesserr Reports constructs that checks for err != nil, but returns a different nil value error.Powered by nilness and nilerr.  
nilnil Checks that there is no simultaneous return of nil error and an invalid value.  
nlreturn Nlreturn checks for a new line before return and branch statements to increase code clarity.
noctx Finds sending http request without context.Context.
nolintlint Reports ill-formed or insufficient nolint directives.
nonamedreturns Reports all named returns.  
nosprintfhostport Checks for misuse of Sprintf to construct a host with port in a URL.  
paralleltest Detects missing usage of t.Parallel() method in your Go test.  
perfsprint Checks that fmt.Sprintf can be replaced with a faster alternative.
prealloc Finds slice declarations that could potentially be pre-allocated. ✅ 
predeclared Find code that shadows one of Go's predeclared identifiers.
promlinter Check Prometheus metrics naming via promlint.
protogetter Reports direct reads from proto message fields when getters should be used.
reassign Checks that package variables are not reassigned.  
recvcheck Checks for receiver type consistency.  
revive Fast, configurable, extensible, flexible, and beautiful linter for Go. Drop-in replacement of golint.
rowserrcheck Checks whether Rows.Err of rows is checked successfully.  ✅
sloglint Ensure consistent code style when using log/slog.
spancheck Checks for mistakes with OpenTelemetry/Census spans.
staticcheck Go vet on steroids, applying a ton of static analysis checks.
sqlclosecheck Checks that sql.Rows, sql.Stmt, sqlx.NamedStmt, pgx.Query are closed. ✅ 
tagalign Check that struct tags are well aligned.
tagliatelle Checks the struct tags.  
testableexamples Linter checks if examples are testable (have an expected output).  
testifylint Checks usage of github.com/stretchr/testify.
testpackage Linter that makes you use a separate _test package.  
thelper Thelper detects tests helpers which is not start with t.Helper() method.  
tparallel Tparallel detects inappropriate usage of t.Parallel() method in your Go test codes.
unconvert Remove unnecessary type conversions.
unused Check Go code for unused constants, variables, functions and types
unparam Reports unused function parameters.  
usestdlibvars A linter that detect the possibility to use variables/constants from the Go standard library.
usetesting Reports uses of functions with replacement inside the testing package.
varnamelen Checks that the length of a variable's name matches its scope.  
wastedassign Finds wasted assignment statements.  ✅
whitespace Whitespace is a linter that checks for unnecessary newlines at the start and end of functions, if, for, etc.
wrapcheck Checks that errors returned from external packages are wrapped.  
wsl Add or remove empty lines.
zerologlint Detects the wrong usage of zerolog that a user forgets to dispatch with Send or Msg.  

Notes

@fredrikaverpil fredrikaverpil requested review from a team as code owners March 24, 2025 12:44
@fredrikaverpil fredrikaverpil self-assigned this Mar 24, 2025
@fredrikaverpil fredrikaverpil marked this pull request as draft March 24, 2025 12:46
@fredrikaverpil fredrikaverpil force-pushed the golangci-v2 branch 4 times, most recently from ecfc792 to 96e6f65 Compare March 24, 2025 13:23
@fredrikaverpil fredrikaverpil marked this pull request as ready for review March 24, 2025 13:33
@fredrikaverpil fredrikaverpil marked this pull request as draft March 24, 2025 13:38
@fredrikaverpil fredrikaverpil changed the title feat(golangci): bump major feat(golangcilint): bump to v2.0.0 Mar 24, 2025
@fredrikaverpil fredrikaverpil force-pushed the golangci-v2 branch 19 times, most recently from 1f9c6b8 to 1a48393 Compare March 24, 2025 16:59
@fredrikaverpil fredrikaverpil force-pushed the golangci-v2 branch 17 times, most recently from 1d887db to 879aba3 Compare April 13, 2025 12:45
cmd.Dir = directory
return cmd
}

// Run GolangCI-Lint in every Go module from the root of the current git repo.
func Run(ctx context.Context, args ...string) error {
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This will be a breaking change for all clients, would be nice if clients that are using the default config today, doesnt need to do anything, and for clients that are using custom config, can supply a config.
Could maybe add RunWithConfig?

Copy link
Member Author

@fredrikaverpil fredrikaverpil Apr 14, 2025

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I guess that would mean adding a new function for each existing function, right?
That would be RunWithConfig, FixWithConfig, CommandWithConfig, CommandInDirectoryWithConfig, PrepareCommandWithConfig.

And then I guess you would want the old Run, Fix etc hard-code a config that would be used, or did you want to keep using the old v1 config file?

Technically, the bump to v2 is a breaking change also for the CLI arguments which clients may be passing. We could add a whole new sggolangcilintv2 package instead, and you can keep using this sggolangcilint (v1) as-is for as long as you want?

Copy link
Member Author

@fredrikaverpil fredrikaverpil Apr 14, 2025

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I've now created a sggolangcilintv2 package instead. Let me know what you think.

We could also deprecate the functions in the sggolangcilint package, so to signal that one can move onto the v2 package.

I can also squash together the commits later. I just kept them now since we are iterating here.

Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I think that is better, then clients can choose when to update 👍 So marking it as deprecated is good, so we eventually can remove it.

Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Ok, now I have also deprecated sggolangcilint. Let me know if you are missing anything.

Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Tested it in pod-gateway, then it fails with deprecation warning 🤦‍♂️ maybe best to skip that initially then?

[sggolangcilint:prepare-command] fetching https://github.com/golangci/golangci-lint/releases/download/v1.64.8/golangci-lint-1.64.8-linux-amd64.tar.gz ...
[go-lint] main.go:132:9: SA1019: sggolangcilint.Run is deprecated: Use `sggolangcilintv2.Run` instead. Run GolangCI-Lint in every Go module from the root of the current git repo. (staticcheck)
[go-lint]       return sggolangcilint.Run(

Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Yeah, that was expected 😄 but sure, I removed that last commit now.

@fredrikaverpil fredrikaverpil requested a review from thall April 14, 2025 12:39
@fredrikaverpil fredrikaverpil changed the title feat(golangcilint): bump to v2 feat: golangcilintv2 Apr 14, 2025
@fredrikaverpil fredrikaverpil changed the title feat: golangcilintv2 feat: sggolangcilintv2 Apr 14, 2025
@fredrikaverpil fredrikaverpil changed the title feat: sggolangcilintv2 feat(sggolangcilintv2): add golangci-lint v2 Apr 14, 2025
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging this pull request may close these issues.

3 participants