### Install golangci-lint using go install Source: https://github.com/golangci/golangci-lint/blob/main/docs/content/docs/welcome/install/local.md Installs golangci-lint using the `go install` command. This method is not recommended due to potential issues with Go versions and dependency management. ```bash go install github.com/golangci/golangci-lint/v2/cmd/golangci-lint@{{< golangci/latest-version >}} ``` -------------------------------- ### Install golangci-lint into ./bin/ Source: https://github.com/golangci/golangci-lint/blob/main/docs/content/docs/welcome/install/local.md Installs the golangci-lint binary into the local ./bin/ directory. Requires curl. ```bash curl -sSfL https://golangci-lint.run/install.sh | sh -s {{< golangci/latest-version >}} ``` -------------------------------- ### Install golangci-lint using curl Source: https://github.com/golangci/golangci-lint/blob/main/docs/content/docs/welcome/install/local.md Installs the golangci-lint binary to $(go env GOPATH)/bin. Ensure you have curl installed. ```bash curl -sSfL https://golangci-lint.run/install.sh | sh -s -- -b $(go env GOPATH)/bin {{< golangci/latest-version >}} ``` -------------------------------- ### Install golangci-lint using mise Source: https://github.com/golangci/golangci-lint/blob/main/docs/content/docs/welcome/install/local.md Installs golangci-lint using the mise tool, leveraging the aqua backend for binaries from GitHub assets. ```bash mise use -g golangci-lint@{{< golangci/latest-version >}} ``` -------------------------------- ### Run the migrate command Source: https://github.com/golangci/golangci-lint/blob/main/docs/content/docs/product/migration-guide.md Execute the `migrate` command to start the configuration migration process. ```bash golangci-lint migrate ``` -------------------------------- ### Bash Completion Setup for Golangci-lint Source: https://github.com/golangci/golangci-lint/blob/main/docs/content/docs/welcome/integrations.md Instructions for setting up Bash completion for golangci-lint on macOS, assuming Bash 4.1+ and Homebrew. This involves installing bash-completion v2 and then sourcing the golangci-lint completion script into your .bashrc. This ensures command-line autocompletion works correctly. ```bash # Install bash-completion v2 brew install bash-completion@2 echo 'export BASH_COMPLETION_COMPAT_DIR="/usr/local/etc/bash_completion.d"' >>~/.bashrc echo '[[ -r "/usr/local/etc/profile.d/bash_completion.sh" ]] && . "/usr/local/etc/profile.d/bash_completion.sh"' >>~/.bashrc exec bash # reload and replace (if it was updated) shell type _init_completion && echo "completion is OK" # verify that bash-completion v2 is correctly installed # Add golangci-lint bash completion echo 'source <(golangci-lint completion bash)' >>~/.bashrc source ~/.bashrc ``` -------------------------------- ### Install golangci-lint using Chocolatey Source: https://github.com/golangci/golangci-lint/blob/main/docs/content/docs/welcome/install/local.md Installs golangci-lint on Windows using the Chocolatey package manager. ```bash choco install golangci-lint ``` -------------------------------- ### Install golangci-lint using Homebrew Source: https://github.com/golangci/golangci-lint/blob/main/docs/content/docs/welcome/install/local.md Installs or upgrades golangci-lint using the Homebrew package manager on macOS. ```bash brew install golangci-lint ``` ```bash brew upgrade golangci-lint ``` -------------------------------- ### Install golangci-lint on Alpine Linux using wget Source: https://github.com/golangci/golangci-lint/blob/main/docs/content/docs/welcome/install/local.md Installs golangci-lint on Alpine Linux using wget, as curl may not be available by default. ```bash wget -O- -nv https://golangci-lint.run/install.sh | sh -s {{< golangci/latest-version >}} ``` -------------------------------- ### Verify golangci-lint installation Source: https://github.com/golangci/golangci-lint/blob/main/docs/content/docs/welcome/install/local.md Checks the installed version of golangci-lint. ```bash golangci-lint --version ``` -------------------------------- ### Migrate linters.enable-all to linters.default: all Source: https://github.com/golangci/golangci-lint/blob/main/docs/content/docs/product/migration-guide.md This tabbed example illustrates the transformation of `linters.enable-all: true` in v1 to `linters.default: all` in v2 configuration. ```yaml linters: enable-all: true ``` ```yaml linters: default: all ``` -------------------------------- ### VS Code Settings for Golangci-lint (Extension Install) Source: https://github.com/golangci/golangci-lint/blob/main/docs/content/docs/welcome/integrations.md Recommended VS Code settings for using golangci-lint when installed via the Go extension, specifically for golangci-lint v2. This setup ensures that v1 and v2 can coexist and configures the Go extension to use 'golangci-lint-v2' for linting and formatting. Using '--fast-only' is advised to maintain editor responsiveness. ```json { "go.lintTool": "golangci-lint-v2", "go.lintFlags": [ "--path-mode=abs", "--fast-only" ], "go.formatTool": "custom", "go.alternateTools": { "customFormatter": "golangci-lint-v2" }, "go.formatFlags": [ "fmt", "--stdin" ] } ``` -------------------------------- ### Migrate configuration to JSON format Source: https://github.com/golangci/golangci-lint/blob/main/docs/content/docs/product/migration-guide.md Use the `--format` flag to specify the output format for the migrated configuration. This example sets the format to JSON. ```bash golangci-lint migrate --format json ``` -------------------------------- ### Install golangci-lint using MacPorts Source: https://github.com/golangci/golangci-lint/blob/main/docs/content/docs/welcome/install/local.md Installs golangci-lint using the MacPorts package manager. Note: This installation is community-driven. ```bash sudo port install golangci-lint ``` -------------------------------- ### Example: Run specific linter with JSON output (v1) Source: https://github.com/golangci/golangci-lint/blob/main/docs/content/docs/product/migration-guide.md This command demonstrates running only the `govet` linter, outputting results in JSON format, and sorting them using older flags. ```bash golangci-lint run --disable-all --enable=govet --out-format=json --sort-order=linter --sort-results ``` -------------------------------- ### Example: Mixed output formats (v2) Source: https://github.com/golangci/golangci-lint/blob/main/docs/content/docs/product/migration-guide.md This command shows how to achieve mixed output formats: text to stdout without colors and Code Climate to a file, using the new flags. ```bash golangci-lint run --output.text.path=stdout --output.text.colors=false --output.text.print-issued-lines=false --output.code-climate.path=gl-code-quality-report.json ``` -------------------------------- ### Migrate linters to formatters section Source: https://github.com/golangci/golangci-lint/blob/main/docs/content/docs/product/migration-guide.md This tabbed example demonstrates the migration of linters like `gci`, `gofmt`, `gofumpt`, and `goimports` from the `linters.enable` list in v1 to the `formatters.enable` section in v2. ```yaml linters: enable: - gci - gofmt - gofumpt - goimports ``` ```yaml formatters: enable: - gci - gofmt - gofumpt - goimports ``` -------------------------------- ### Install golangci-lint using Scoop Source: https://github.com/golangci/golangci-lint/blob/main/docs/content/docs/welcome/install/local.md Installs golangci-lint on Windows using the Scoop package manager. Note: This package is not officially maintained. ```bash scoop install main/golangci-lint ``` -------------------------------- ### Migrate linters.enable[].{stylecheck,gosimple,staticcheck} to linters.enable: staticcheck Source: https://github.com/golangci/golangci-lint/blob/main/docs/content/docs/product/migration-guide.md This tabbed example shows how `stylecheck`, `gosimple`, and `staticcheck` in the `linters.enable` list of v1 are consolidated under `linters.enable: staticcheck` in v2. ```yaml linters: enable: - gosimple - staticcheck - stylecheck ``` ```yaml linters: enable: - staticcheck ``` -------------------------------- ### Setup Go workspace for dedicated module Source: https://github.com/golangci/golangci-lint/blob/main/docs/content/docs/welcome/install/local.md Initializes a Go workspace to manage multiple modules, specifically for isolating golangci-lint when using the 'dedicated module' method. ```sh # Setup a Go workspace go work init . golangci-lint ``` -------------------------------- ### Buildkite Plugin Configuration Source: https://github.com/golangci/golangci-lint/blob/main/docs/content/docs/welcome/install/ci.md This configuration demonstrates how to use the golangci-lint Buildkite plugin. It specifies the plugin version and points to a configuration file for golangci-lint. The plugin can utilize a Docker image or a local binary. ```yaml plugins: - golangci-lint#v1.0.0: config: .golangci.yml ``` -------------------------------- ### Update golangci-lint with dedicated module Source: https://github.com/golangci/golangci-lint/blob/main/docs/content/docs/welcome/install/local.md Updates golangci-lint to the latest version using `go get -tool` within a dedicated module setup. This method is not recommended. ```sh # Update golangci-lint go get -tool -modfile=golangci-lint/go.mod github.com/golangci/golangci-lint/v2/cmd/golangci-lint@latest ``` -------------------------------- ### Migrate linters.disable-all to linters.default: none Source: https://github.com/golangci/golangci-lint/blob/main/docs/content/docs/product/migration-guide.md This tabbed example shows the migration of `linters.disable-all: true` in v1 configuration to `linters.default: none` in v2. ```yaml linters: disable-all: true ``` ```yaml linters: default: none ``` -------------------------------- ### Run golangci-lint using go tool with dedicated module Source: https://github.com/golangci/golangci-lint/blob/main/docs/content/docs/welcome/install/local.md Runs golangci-lint as a tool within a Go workspace, using the `go tool` command. This installation method is not recommended. ```sh # Run golangci-lint as a tool go tool golangci-lint run ``` -------------------------------- ### Example: Run specific linter with JSON output (v2) Source: https://github.com/golangci/golangci-lint/blob/main/docs/content/docs/product/migration-guide.md This command shows how to run only the `govet` linter, outputting results to stdout in JSON format using the new default and output flags. ```bash golangci-lint run --default=none --enable=govet --output.json.path=stdout ``` -------------------------------- ### VS Code Settings for Golangci-lint (Manual Install) Source: https://github.com/golangci/golangci-lint/blob/main/docs/content/docs/welcome/integrations.md Recommended VS Code settings for using golangci-lint when installed manually. These settings configure the Go extension to use golangci-lint as the linter and formatter, with specific flags for path mode and fast-only linting. It's crucial to use '--fast-only' to prevent editor freezes. ```json { "go.lintTool": "golangci-lint", "go.lintFlags": [ "--path-mode=abs", "--fast-only" ], "go.formatTool": "custom", "go.alternateTools": { "customFormatter": "golangci-lint" }, "go.formatFlags": [ "fmt", "--stdin" ] } ``` -------------------------------- ### Migrate run.show-stats to output.show-stats Source: https://github.com/golangci/golangci-lint/blob/main/docs/content/docs/product/migration-guide.md The 'run.show-stats' property is deprecated and replaced by 'output.show-stats'. This example demonstrates moving the configuration to the new property. ```yaml run: show-stats: true ``` ```yaml output: show-stats: true ``` -------------------------------- ### Handle removed usestdlibvars syslog-priority option Source: https://github.com/golangci/golangci-lint/blob/main/docs/content/docs/product/migration-guide.md The `linters-settings.usestdlibvars.syslog-priority` option has been removed. This example shows the previous configuration and its removal. ```yaml linters-settings: usestdlibvars: syslog-priority: true ``` ```yaml # Removed ``` -------------------------------- ### Migrate output.formats[].format: line-number to text format Source: https://github.com/golangci/golangci-lint/blob/main/docs/content/docs/product/migration-guide.md The 'line-number' format is replaced by the 'text' format. This example demonstrates the change in configuration. ```yaml output: formats: - format: line-number ``` ```yaml output: formats: text: path: stdout ``` -------------------------------- ### Migrate output.format to output.formats Source: https://github.com/golangci/golangci-lint/blob/main/docs/content/docs/product/migration-guide.md The 'output.format' property is deprecated and replaced by 'output.formats'. This example shows the migration from a single string format to a structured map. ```yaml output: format: 'checkstyle:report.xml,json:stdout,colored-line-number' ``` ```yaml output: formats: checkstyle: path: 'report.xml' json: path: stdout text: path: stdout color: true ``` -------------------------------- ### Example: Mixed output formats (v1) Source: https://github.com/golangci/golangci-lint/blob/main/docs/content/docs/product/migration-guide.md This command demonstrates not printing issued lines and outputting results to stdout in text format, alongside Code Climate format to a file, using older flags. ```bash golangci-lint run --print-issued-lines=false --out-format code-climate:gl-code-quality-report.json,line-number ``` -------------------------------- ### Migrate run.relative-path-mode default Source: https://github.com/golangci/golangci-lint/blob/main/docs/content/docs/product/migration-guide.md The default value for 'run.relative-path-mode' has changed from 'wd' to 'cfg'. This example shows the explicit setting of the new default. ```yaml run: # When not specified, relative-path-mode is set to 'wd' by default ``` ```yaml run: relative-path-mode: 'cfg' ``` -------------------------------- ### Configure Custom Linter in .golangci.yml Source: https://github.com/golangci/golangci-lint/blob/main/docs/content/docs/plugins/go-plugins.md Example configuration for a custom linter within the `.golangci.yml` file. It specifies the path to the plugin, description, original URL, and optional settings. ```yaml version: "2" linters: settings: custom: example: path: /example.so description: The description of the linter original-url: github.com/golangci/example-linter settings: # Settings are optional. one: Foo two: - name: Bar three: name: Bar ``` -------------------------------- ### Migrate run.skip-dirs-use-default to issues.exclude-dirs-use-default Source: https://github.com/golangci/golangci-lint/blob/main/docs/content/docs/product/migration-guide.md The 'run.skip-dirs-use-default' property is deprecated and replaced by 'issues.exclude-dirs-use-default'. This example shows the property moved to a different configuration section. ```yaml run: skip-dirs-use-default: false ``` ```yaml issues: exclude-dirs-use-default: false ``` -------------------------------- ### Add golangci-lint as a tool with dedicated module file Source: https://github.com/golangci/golangci-lint/blob/main/docs/content/docs/welcome/install/local.md Adds golangci-lint as a tool using `go get -tool` with a specified module file. This ensures golangci-lint is managed separately. ```sh # Add golangci-lint as a tool go get -tool -modfile=golangci-lint.mod github.com/golangci/golangci-lint/v2/cmd/golangci-lint@{{< golangci/latest-version >}} ``` -------------------------------- ### Migrate output.formats[].format: colored-line-number to text format with color Source: https://github.com/golangci/golangci-lint/blob/main/docs/content/docs/product/migration-guide.md The 'colored-line-number' format is replaced by the 'text' format with the 'color' option set to true. This example shows the migration. ```yaml output: formats: - format: colored-line-number ``` ```yaml output: formats: text: path: stdout colors: true ``` -------------------------------- ### Migrate output.uniq-by-line to issues.uniq-by-line Source: https://github.com/golangci/golangci-lint/blob/main/docs/content/docs/product/migration-guide.md The 'output.uniq-by-line' property is deprecated and replaced by 'issues.uniq-by-line'. This example shows the property moved to a different configuration section. ```yaml output: uniq-by-line: true ``` ```yaml issues: uniq-by-line: true ``` -------------------------------- ### Add golangci-lint as a tool with dedicated module Source: https://github.com/golangci/golangci-lint/blob/main/docs/content/docs/welcome/install/local.md Adds golangci-lint as a tool to the Go workspace using `go get -tool`, referencing the dedicated module file. This method is not recommended. ```sh # Add golangci-lint as a tool go get -tool -modfile=golangci-lint/go.mod github.com/golangci/golangci-lint/v2/cmd/golangci-lint ``` -------------------------------- ### Migrate output.formats[].format: colored-tab to tab format with color Source: https://github.com/golangci/golangci-lint/blob/main/docs/content/docs/product/migration-guide.md The 'colored-tab' format is replaced by the 'tab' format with the 'colors' option set to true. This example illustrates the configuration change. ```yaml output: formats: - format: colored-tab ``` ```yaml output: formats: tab: path: stdout colors: true ``` -------------------------------- ### GitLab CI Integration using Component Source: https://github.com/golangci/golangci-lint/blob/main/docs/content/docs/welcome/install/ci.md This snippet shows how to integrate golangci-lint into GitLab CI using a CI component. It requires referencing a component within the same GitLab instance. The component handles the integration and reporting of linting results. ```yaml include: - component: $CI_SERVER_FQDN/components/code-quality-oss/codequality-os-scanners-integration/golangci@1.0.1 ``` -------------------------------- ### Update golangci-lint with dedicated module file Source: https://github.com/golangci/golangci-lint/blob/main/docs/content/docs/welcome/install/local.md Updates golangci-lint to the latest version using `go get -tool` while specifying the dedicated module file. ```sh # Update golangci-lint go get -tool -modfile=golangci-lint.mod github.com/golangci/golangci-lint/v2/cmd/golangci-lint@latest ``` -------------------------------- ### Combine Filter Bar and Filter Badge Shortcodes Source: https://github.com/golangci/golangci-lint/blob/main/docs/layouts/_shortcodes/golangci/items/filter.html This example demonstrates how to combine the `filter` and `filter-badge` shortcodes to create a functional filter bar with a specific badge. The `filter` shortcode acts as the container, and `filter-badge` adds a labeled item within it. ```Go Template {{< golangci/items/filter >}}{{< golangci/items/filter-badge content="Example">}}{{< golangci/items/filter >}} ``` -------------------------------- ### Get Optimized Linters for Execution (Go) Source: https://github.com/golangci/golangci-lint/blob/main/docs/content/docs/contributing/architecture.md Returns a slice of enabled linters after applying optimizations, such as merging multiple go/analysis linters into a single meta-linter. This aims to improve execution speed through data reuse. ```go // GetOptimizedLinters returns enabled linters after optimization (merging) of multiple linters into a fewer number of linters. // E.g. some go/analysis linters can be optimized into one metalinter for data reuse and speed up. func (m *Manager) GetOptimizedLinters() ([]*linter.Config, error) { // ... m.combineGoAnalysisLinters(resultLintersSet) // ... } ``` -------------------------------- ### Verify local build and execution Source: https://github.com/golangci/golangci-lint/blob/main/docs/content/docs/contributing/workflow.md Use these commands to compile the project and verify the linter runs correctly in the local environment. ```bash make build ./golangci-lint run -v ``` -------------------------------- ### Replace revive ignore-generated-header with exclusions.generated Source: https://github.com/golangci/golangci-lint/blob/main/docs/content/docs/product/migration-guide.md The `linters-settings.revive.ignore-generated-header` option has been removed and replaced by `linters.exclusions.generated`. Migrate your settings using this example. ```yaml linters-settings: revive: ignore-generated-header: true ``` ```yaml linters: exclusions: generated: strict ``` -------------------------------- ### Display Golangci-lint Configuration Section Source: https://github.com/golangci/golangci-lint/blob/main/docs/layouts/_shortcodes/golangci/configuration-file-snippet.html Use this shortcode to render a specific section from the `configuration_file` data. It takes a `section` parameter to specify which part of the configuration to display. ```html {{- /* Creates a code block with the contents of a configuration file section. @param {string} section The name of the section inside the data file. @returns {string} @example {{% golangci/configuration-file-snippet section="sectionName" %}} */ -}} {{- $sectionName := .Get "section" -}} {{- $file := index hugo.Data.configuration_file -}} ```yaml {{ index $file $sectionName | safeHTML }} ``` ``` -------------------------------- ### Handle removed unused exported-is-used option Source: https://github.com/golangci/golangci-lint/blob/main/docs/content/docs/product/migration-guide.md The `linters-settings.unused.exported-is-used` option has been removed. This example shows the old configuration and indicates its removal. ```yaml linters-settings: unused: exported-is-used: true ``` ```yaml # Removed ``` -------------------------------- ### Build Golangci-Lint Website (Makefile) Source: https://github.com/golangci/golangci-lint/blob/main/docs/content/docs/contributing/website.md Commands to build the golangci-lint website. These commands can be executed from the repository root or by navigating into the docs directory after expanding templates. ```bash # (in the root of the repository) make docs_build ``` ```bash # (in the root of the repository) make website_copy_jsonschema website_expand_templates cd docs/ # (inside the docs/ folder) make build ``` -------------------------------- ### Create a dedicated directory for golangci-lint Source: https://github.com/golangci/golangci-lint/blob/main/docs/content/docs/welcome/install/local.md Sets up a dedicated directory to house golangci-lint and its dependencies when using the 'dedicated module' method. ```sh # Create a dedicated directory mkdir golangci-lint ``` -------------------------------- ### Run golangci-lint with colored output using Docker Source: https://github.com/golangci/golangci-lint/blob/main/docs/content/docs/welcome/install/local.md Runs golangci-lint in a Docker container with TTY enabled for colored output. ```bash docker run -t --rm -v $(pwd):/app -w /app golangci/golangci-lint:{{< golangci/latest-version >}} golangci-lint run ``` -------------------------------- ### List All Supported Formatters Source: https://github.com/golangci/golangci-lint/blob/main/docs/content/docs/formatters/_index.md Use this command to see a comprehensive list of all formatters that golangci-lint supports. ```bash golangci-lint help formatters ``` -------------------------------- ### Serve Golangci-Lint Website Locally (Makefile) Source: https://github.com/golangci/golangci-lint/blob/main/docs/content/docs/contributing/website.md Commands to serve the golangci-lint website locally using Hugo. This involves running a make target in the repository root or navigating into the docs directory and running a local make target. ```bash # (in the root of the repository) make docs_serve ``` ```bash # (in the root of the repository) make website_expand_templates cd docs/ # (inside the docs/ folder) make serve ``` -------------------------------- ### Run golangci-lint using Docker Source: https://github.com/golangci/golangci-lint/blob/main/docs/content/docs/welcome/install/local.md Executes golangci-lint within a Docker container, mounting the current directory for analysis. ```bash docker run --rm -v $(pwd):/app -w /app golangci/golangci-lint:{{< golangci/latest-version >}} golangci-lint run ``` -------------------------------- ### Run golangci-lint using go tool with dedicated module file Source: https://github.com/golangci/golangci-lint/blob/main/docs/content/docs/welcome/install/local.md Executes golangci-lint using the `go tool` command, specifying the dedicated module file. This method is not recommended. ```sh # Run golangci-lint as a tool go tool -modfile=golangci-lint.mod golangci-lint run ``` -------------------------------- ### Build Go Plugin Source: https://github.com/golangci/golangci-lint/blob/main/docs/content/docs/plugins/go-plugins.md Command to build a Go plugin from a source file. This generates a `*.so` file that can be used by golangci-lint. ```bash go build -buildmode=plugin plugin/example.go ``` -------------------------------- ### Initialize dedicated module file within a directory Source: https://github.com/golangci/golangci-lint/blob/main/docs/content/docs/welcome/install/local.md Initializes a Go module file within a dedicated directory for managing golangci-lint. This approach is not recommended. ```sh # Create a dedicated module file go mod init -modfile=golangci-lint/go.mod /golangci-lint # Example: go mod init -modfile=golangci-lint/go.mod github.com/org/repo/golangci-lint ``` -------------------------------- ### Build Enabled Linters Configuration (Go) Source: https://github.com/golangci/golangci-lint/blob/main/docs/content/docs/contributing/architecture.md This function builds a list of `linter.Config` objects for all enabled linters based on the provided configuration. It demonstrates how linters like `bodyclose` and `govet` are instantiated and configured with metadata such as version, URL, and analysis type. ```go func (b LinterBuilder) Build(cfg *config.Config) []*linter.Config { // ... return []*linter.Config{ // ... linter.NewConfig(golinters.NewBodyclose()). WithSince("v1.18.0"). WithLoadForGoAnalysis(). WithURL("https://github.com/timakin/bodyclose"), // ... linter.NewConfig(golinters.NewGovet(govetCfg)). WithGroups(config.GroupStandard). WithSince("v1.0.0"). WithLoadForGoAnalysis(). WithURL("https://pkg.go.dev/cmd/vet"), // ... } } ``` -------------------------------- ### List All Supported Linters Source: https://github.com/golangci/golangci-lint/blob/main/docs/content/docs/linters/_index.md Use this command to see a comprehensive list of all linters supported by golangci-lint. This includes information on which linters are enabled by default. ```bash golangci-lint help linters ``` -------------------------------- ### Load packages using PackageLoader Source: https://github.com/golangci/golangci-lint/blob/main/docs/content/docs/contributing/architecture.md Demonstrates the entry point for loading packages and their dependencies within golangci-lint. It utilizes the go/packages library to retrieve package data based on the requirements of enabled linters. ```go func (l *PackageLoader) Load(ctx context.Context, linters []*linter.Config) (pkgs, deduplicatedPkgs []*packages.Package, err error) { loadMode := findLoadMode(linters) pkgs, err = l.loadPackages(ctx, loadMode) if err != nil { return nil, nil, fmt.Errorf("failed to load packages: %w", err) } // ... ``` -------------------------------- ### Initialize dedicated module file for go tool Source: https://github.com/golangci/golangci-lint/blob/main/docs/content/docs/welcome/install/local.md Creates a dedicated module file for isolating golangci-lint when using `go tool`. This helps prevent conflicts with project dependencies. ```sh # Create a dedicated module file go mod init -modfile=golangci-lint.mod /golangci-lint # Example: go mod init -modfile=golangci-lint.mod github.com/org/repo/golangci-lint ``` -------------------------------- ### Displaying GolangCI CLI Help Output Source: https://github.com/golangci/golangci-lint/blob/main/docs/layouts/_shortcodes/golangci/cli-output.html This snippet displays the help output for a specified golangci-lint command or a general section. It uses Hugo's data files to retrieve and format the output. ```html {{- /* Creates a code block with the output of the CLI. @param {string} cmd The name of the command. @param {string} section The name of the section inside the data file. @example {{% golangci/cli-output %}} @example {{% golangci/cli-output cmd="foo" %}} @example {{% golangci/cli-output section="sectionName" cmd="foo bar" %}} */ -}} {{- $cmdName := .Get "cmd" -}} {{- $section := .Get "section" -}} {{- $cliData := index hugo.Data.cli\_help -}} ```console {{ if $section -}} $ golangci-lint {{ $cmdName }}{{- else -}} {{- $section = print (or $cmdName "root") "Output" -}} $ golangci-lint{{ if $cmdName }} {{ $cmdName }}{{ end }} -h {{- end }} {{ index $cliData $section | safeHTML }} ``` ``` -------------------------------- ### Get Enabled Linters Map (Go) Source: https://github.com/golangci/golangci-lint/blob/main/docs/content/docs/contributing/architecture.md Retrieves a map of enabled linters, keyed by their names, along with any potential errors during the process. This function is crucial for accessing the configured linters before optimization. ```go func (m *Manager) GetEnabledLintersMap() (map[string]*linter.Config, error) ``` -------------------------------- ### Run golangci-lint with preserved caches using Docker Source: https://github.com/golangci/golangci-lint/blob/main/docs/content/docs/welcome/install/local.md Executes golangci-lint in Docker, preserving Go build cache, module cache, and golangci-lint cache between runs. ```bash docker run --rm -t -v $(pwd):/app -w /app \ --user $(id -u):$(id -g) \ -v $(go env GOCACHE):/.cache/go-build -e GOCACHE=/.cache/go-build \ -v $(go env GOMODCACHE):/.cache/mod -e GOMODCACHE=/.cache/mod \ -v ~/.cache/golangci-lint:/.cache/golangci-lint -e GOLANGCI_LINT_CACHE=/.cache/golangci-lint \ golangci/golangci-lint:{{< golangci/latest-version >}} golangci-lint run ``` -------------------------------- ### Display Linter/Formatter Settings Source: https://github.com/golangci/golangci-lint/blob/main/docs/layouts/_shortcodes/golangci/items/settings.html This shortcode iterates through linters/formatters, displaying their name, description, badges, and configuration settings. It fetches data from `info` and `settings` files and renders them. Use this shortcode to create detailed documentation pages for individual linters or formatters. ```html {{- "/golangci/golangci-lint/blob/master/docs/layouts/_shortcodes/golangci/items/settings.html" -}} {{- $fileInfo := .Get "info" -}} {{- $fileSettings := .Get "settings" -}} {{- $gcilVersion := index hugo.Data.version.version -}} {{- $info := index hugo.Data $fileInfo -}} {{- $settings := index hugo.Data $fileSettings -}} {{- range sort $info "name" -}} {{- if .internal -}} {{- continue -}} {{- end -}} ## {{ .name }} {{/* Description */}} {{ if .deprecation -}} {{- $replacement := "" -}} {{- if .deprecation.replacement -}} {{- $replacement = print " Use `" .deprecation.replacement "` instead." -}} {{- end -}} {{ print (partial "golangci/items/format-description" .deprecation.message) $replacement }} {{ else }} {{ partial "golangci/items/format-description" .desc }} {{ end }} {{/* Badges */}} {{ partial "shortcodes/badge" (dict "border" false "icon" "calendar" "class" "hx:mx-1" "content" (print "Since golangci-lint " .since) ) }} {{ if .deprecation -}} {{ partial "shortcodes/badge" (dict "border" true "icon" "sparkles" "class" "hx:mx-1" "content" (print "Deprecated since " .deprecation.since) "color" "red" ) }} {{ else }} {{ if (partial "golangci/items/compare-versions" (dict "a" $gcilVersion "b" .since)) }} {{ partial "shortcodes/badge" (dict "border" false "icon" "sparkles" "class" "hx:mx-1" "content" "New" "color" "yellow" ) }} {{ end }} {{ if .canAutoFix }} {{ partial "shortcodes/badge" (dict "border" false "icon" "sparkles" "class" "hx:mx-1" "content" "Autofix" "color" "blue" ) }} {{ end }} {{ end }} {{- if .originalURL -}} [{{ partial "shortcodes/badge" (dict "border" true "icon" "github" "class" "hx:mx-1" "content" "Repository" "link" .originalURL ) }}]({{ .originalURL }} "Repository") {{- end -}} {{/* Settings */}} {{- $setting := index $settings .name -}} {{- if $setting -}} ```yaml {{ $setting | safeHTML}} ``` {{- else -}} _No settings available._ {{- end }} {{ end -}} ``` -------------------------------- ### Benchmark a single linter using a local version Source: https://github.com/golangci/golangci-lint/blob/main/scripts/bench/readme.md Executes a benchmark for a specific linter against a local build of golangci-lint. Requires the LINTER and VERSION variables to be defined. ```bash make bench_local LINTER=gosec VERSION=v1.59.0 ``` -------------------------------- ### Initialize Quicklink and Filter UI Source: https://github.com/golangci/golangci-lint/blob/main/docs/layouts/_partials/custom/head-end.html Initializes the quicklink library on page load and sets up event listeners for filter buttons and the reset button. It manages the visibility of items based on data-badge attributes and toggles CSS classes for visual feedback. ```javascript window.addEventListener('load', () => { quicklink.listen(); }); window.addEventListener('load', () => { const resetButton = document.querySelector('.gl-filter-reset'); if (!resetButton) { return } const borderClass = 'hx:border' const hiddenClass = 'gl-hidden' document.querySelectorAll('.gl-filter').forEach(button => { button.addEventListener('click', event => { let clean = event.currentTarget.querySelectorAll('.hx\\:border').length > 0 document.querySelectorAll('.gl-item').forEach(element => element.classList.remove(hiddenClass)); document.querySelectorAll('.gl-filter > *').forEach(element => element.classList.remove(borderClass)); if (clean) { resetButton.classList.add(hiddenClass); } else { resetButton.classList.remove(hiddenClass); document.querySelectorAll('.gl-filter').forEach(element => element.classList.remove(borderClass)) event.currentTarget.querySelector('*').classList.add(borderClass); let selector = '' switch (event.currentTarget.dataset.badge) { case 'default': selector = '.gl-item:not(.gl-default)'; break; case 'new': selector = '.gl-item:not(.gl-new)'; break; case 'autofix': selector = '.gl-item:not(.gl-autofix)'; break; case 'fast': selector = '.gl-item:not(.gl-fast)'; break; case 'slow': selector = '.gl-item:not(.gl-slow)'; break; case 'deprecated': selector = '.gl-item:not(.gl-deprecated)'; break; } if (selector) { document.querySelectorAll(selector).forEach(element => element.classList.add(hiddenClass)); } } }); }); resetButton.addEventListener('click', (event) => { event.currentTarget.classList.add(hiddenClass); document.querySelectorAll('.gl-item').forEach(element => element.classList.remove(hiddenClass)); document.querySelectorAll('.gl-filter > *').forEach(element => element.classList.remove(borderClass)); }); }); ``` -------------------------------- ### Run project test suite Source: https://github.com/golangci/golangci-lint/blob/main/docs/content/docs/contributing/workflow.md Executes all linters and tests to ensure changes do not introduce regressions. ```bash make test ``` -------------------------------- ### Run New Linter Test Source: https://github.com/golangci/golangci-lint/blob/main/docs/content/docs/contributing/new-linters.md Execute tests for a newly added linter. Ensure to replace placeholders with your linter's name and path. ```bash go run ./cmd/golangci-lint/ run --no-config --default=none --enable={yourlintername} ./pkg/golinters/{yourlintername}/testdata/{yourlintername}.go ``` -------------------------------- ### VS Code configuration for golangci-lint (v1) Source: https://github.com/golangci/golangci-lint/blob/main/docs/content/docs/product/migration-guide.md Initial Visual Studio Code configuration for using golangci-lint as the linting tool. ```jsonata "go.lintTool": "golangci-lint", "go.lintFlags": [ "--fast" ] ``` -------------------------------- ### VS Code configuration for golangci-lint (v2) Source: https://github.com/golangci/golangci-lint/blob/main/docs/content/docs/product/migration-guide.md Updated Visual Studio Code configuration including linting, formatting, and alternate tools. ```jsonata "go.lintTool": "golangci-lint", "go.lintFlags": [ "--fast-only" ], "go.formatTool": "custom", "go.alternateTools": { "customFormatter": "golangci-lint" }, "go.formatFlags": [ "fmt", "--stdin" ] ``` -------------------------------- ### Benchmark a single linter between two versions Source: https://github.com/golangci/golangci-lint/blob/main/scripts/bench/readme.md Compares the performance of a specific linter between two distinct versions of golangci-lint. Requires LINTER, VERSION_OLD, and VERSION_NEW variables. ```bash make bench_version LINTER=gosec VERSION_OLD=v1.58.1 VERSION_NEW=v1.59.0 ``` -------------------------------- ### Enforcing nolint directive explanations in Go Source: https://github.com/golangci/golangci-lint/blob/main/pkg/golinters/nolintlint/internal/README.md Demonstrates the transition from ill-formed, unexplained nolint directives to compliant directives that specify the linter and provide a descriptive reason for the suppression. ```Go import "crypto/md5" //nolint:all func hash(data []byte) []byte { return md5.New().Sum(data) //nolint:all } ``` ```Go import "crypto/md5" //nolint:gosec // this is not used in a secure application func hash(data []byte) []byte { return md5.New().Sum(data) //nolint:gosec // this result is not used in a secure application } ``` -------------------------------- ### Migrating Linters Settings Source: https://github.com/golangci/golangci-lint/blob/main/docs/content/docs/product/migration-guide.md Settings for linters and formatters have been reorganized. `linters-settings` is now split into `linters.settings` and `formatters.settings`. ```yaml linters-settings: govet: enable-all: true gofmt: simplify: false ``` ```yaml linters: settings: govet: enable-all: true formatters: settings: gofmt: simplify: false ``` -------------------------------- ### Migrate output.formats[].format to output.formats[]. Source: https://github.com/golangci/golangci-lint/blob/main/docs/content/docs/product/migration-guide.md The 'output.formats[].format' property has been replaced by specific format keys within 'output.formats'. This shows the transition from a list of formats to a map of formats. ```yaml output: formats: - format: json path: stderr - format: checkstyle path: report.xml ``` ```yaml output: formats: json: path: stderr checkstyle: path: report.xml ``` -------------------------------- ### Enable custom linters in .golangci.yml Source: https://github.com/golangci/golangci-lint/blob/main/docs/content/docs/plugins/module-plugins.md Configures the linter settings to use a module-type plugin. ```yaml version: "2" linters: default: none enable: - foo settings: custom: foo: type: "module" description: This is an example usage of a plugin linter. settings: message: hello ``` -------------------------------- ### List Enabled Formatters Source: https://github.com/golangci/golangci-lint/blob/main/docs/content/docs/formatters/_index.md Run this command to display only the formatters that are currently enabled in your golangci-lint configuration. ```bash golangci-lint formatters ``` -------------------------------- ### Migrate issues.exclude-dirs-use-default to linters.exclusions.paths Source: https://github.com/golangci/golangci-lint/blob/main/docs/content/docs/product/migration-guide.md The `issues.exclude-dirs-use-default` property is removed. Use `linters.exclusions.paths` and `formatters.exclusions.paths` to exclude directories. ```yaml issues: exclude-dirs-use-default: true ``` ```yaml linters: exclusions: paths: - third_party$ - builtin$ - examples$ ``` -------------------------------- ### Configure custom plugins in .custom-gcl.yml Source: https://github.com/golangci/golangci-lint/blob/main/docs/content/docs/plugins/module-plugins.md Defines external modules or local paths for custom linters to be built into a custom golangci-lint binary. ```yaml version: {{< golangci/latest-version >}} plugins: # a plugin from a Go proxy - module: 'github.com/golangci/plugin1' import: 'github.com/golangci/plugin1/foo' version: v1.0.0 # a plugin from local source - module: 'github.com/golangci/plugin2' path: /my/local/path/plugin2 ``` -------------------------------- ### Replace staticcheck go option with run.go Source: https://github.com/golangci/golangci-lint/blob/main/docs/content/docs/product/migration-guide.md The `linters-settings.staticcheck.go` option has been removed and replaced by `run.go`. Use this to update your Go version configuration. ```yaml linters-settings: staticcheck: go: '1.22' ``` ```yaml run: go: '1.22' ``` -------------------------------- ### Configure linter load modes Source: https://github.com/golangci/golangci-lint/blob/main/docs/content/docs/contributing/architecture.md Configures the load mode for linters based on their data requirements. WithLoadFiles is used for AST-only linters, while WithLoadForGoAnalysis is used for linters requiring full type information. ```go func (lc *Config) WithLoadFiles() *Config { lc.LoadMode |= packages.NeedName | packages.NeedFiles | packages.NeedCompiledGoFiles return lc } func (lc *Config) WithLoadForGoAnalysis() *Config { lc = lc.WithLoadFiles() lc.LoadMode |= packages.NeedImports | packages.NeedDeps | packages.NeedExportFile | packages.NeedTypesSizes lc.IsSlow = true return lc } ``` -------------------------------- ### Migrate govet.check-shadowing to govet.enable: shadow Source: https://github.com/golangci/golangci-lint/blob/main/docs/content/docs/product/migration-guide.md The `govet.check-shadowing` option is deprecated and removed. Use `linters.settings.govet.enable: shadow` instead. ```yaml linters-settings: govet: check-shadowing: true ``` ```yaml linters: settings: govet: enable: - shadow ``` -------------------------------- ### Migrate gci.local-prefixes to gci.sections Source: https://github.com/golangci/golangci-lint/blob/main/docs/content/docs/product/migration-guide.md The `gci.local-prefixes` option is deprecated and removed. Use `linters.settings.gci.sections` with the `prefix` directive instead. ```yaml linters-settings: gci: local-prefixes: 'github.com/example/pkg' ``` ```yaml linters: settings: gci: sections: - standard - default - prefix(github.com/example/pkg) ``` -------------------------------- ### Replaced `--out-format` with specific output flags (junit-xml) Source: https://github.com/golangci/golangci-lint/blob/main/docs/content/docs/product/migration-guide.md The `--out-format` flag for JUnit XML output has been replaced by `--output.junit-xml.path` and `--output.junit-xml.extended`. ```bash # Previously 'junit-xml' and 'junit-xml-extended' --output.junit-xml.path --output.junit-xml.extended ``` -------------------------------- ### GolangCI Exclusion Presets Configuration Source: https://github.com/golangci/golangci-lint/blob/main/docs/layouts/_shortcodes/golangci/exclusion-presets-snippet.html Use this snippet to define exclusion presets in your golangci-lint configuration. It dynamically lists all available presets from the exclusion_presets data. ```yaml linters: exclusions: presets: - "build-errors" - "test-errors" - "performance" - "security" - "style" - "all" ``` -------------------------------- ### Create Image Card Shortcode (Go Template) Source: https://github.com/golangci/golangci-lint/blob/main/docs/layouts/_shortcodes/golangci/image-card.html This Go template code defines a shortcode that generates a Markdown image link. It takes 'src' for the image path and 'title' for the alt text and caption. The output is a standard Markdown image format. ```go-template {{- /* Creates a card for an image. @param {string} src The path to the image. @param {string} title The title text for the image. @example {{< golangci/image-card src="path/to/image.png" title="Image description" >}} */ -}} {{- $src := .Get "src" -}} {{- $title := .Get "title" -}} ![{{ $title }}]({{ $src }} "{{ $title }}") ``` -------------------------------- ### Reference configuration for .custom-gcl.yml Source: https://github.com/golangci/golangci-lint/blob/main/docs/content/docs/plugins/module-plugins.md Embeds the reference configuration file for the custom plugin system. ```yml {{% golangci/embed file=".tmp/.custom-gcl.reference.yml" %}} ``` -------------------------------- ### Enable granular debug logging with GL_DEBUG Source: https://github.com/golangci/golangci-lint/blob/main/docs/content/docs/contributing/debug.md Uses the GL_DEBUG environment variable to enable detailed logs for specific internal components. The value should be a comma-separated list of debug tags. ```bash GL_DEBUG="loader,gocritic" golangci-lint run ``` ```bash GL_DEBUG="loader,env" golangci-lint run ``` -------------------------------- ### Migrate forbidigo.forbid.p to forbidigo.forbid.pattern Source: https://github.com/golangci/golangci-lint/blob/main/docs/content/docs/product/migration-guide.md The `forbidigo.forbid.p` field is replaced with `linters-settings.forbidigo.forbid.pattern`. ```yaml linters-settings: forbidigo: forbid: - p: '^fmt\.Print.*$' msg: Do not commit print statements. ``` ```yaml linters: settings: forbidigo: forbid: - pattern: '^fmt\.Print.*$' msg: Do not commit print statements. ``` -------------------------------- ### Replaced: Default severity using `severity.default` Source: https://github.com/golangci/golangci-lint/blob/main/docs/content/docs/product/migration-guide.md Use `severity.default` instead of `severity.default-severity` to set the default severity. ```yaml severity: default: error ```