3

I enabled goimports in my GolangCI tool using my makefile and it's able to spot unused imports but is not automatically remove them. How do I enable my golangCI tool to remove the unused imports automatically?

Below is my makefile command for the golangci linting, I am using the --fix tag:

##@ Linting
lint:
    @echo "lint via golangci-lint in " $(OUTPUT_DIR)/src
    docker run --rm -v $(PWD):/local \
        -w /local golangci/golangci-lint:latest \
        golangci-lint run --fix --config .golangci.yaml $(OUTPUT_DIR)/src/*.go

Below is my golangci.yaml file, I am setting remove-unused to true :

run:
  timeout: 5m
  modules-download-mode: readonly

linters:
  enable:
    - errcheck
    - goimports
    - revive
    - govet
    - staticcheck

  # Configuration for the goimports linter
  goimports:
    # Set to true to remove unused imports automatically
    remove-unused: true

  # Configuration for the revive linter
  revive:
    # Add any custom rules you want to use
    rules:
      - id: 'import-shadowing'
        severity: warning
        match: '\bimport\s+\.\s+\S+'
        message: 'Importing packages using dot notation (.) is discouraged.'

issues:
  exclude-use-default: false
  max-issues-per-linter: 0
  max-same-issues: 0
Mabel Oza
  • 557
  • 8
  • 22

2 Answers2

3

I'm not sure if golangci-lint can do in-place fixes.

The easiest way to remove unused imports would be to use the goimports tool.

$ go install golang.org/x/tools/cmd/goimports@latest

Call it with the "-w" option to fix your imports directly in-place, e.g.

 $ goimports -w sourcefile.go
Hechi
  • 456
  • 5
  • 9
1

I'm very happy using goimports-reviser. I find it superior to goimports as it not only removes unused imports when called with -rm-unused fla,g but also re-groups and sorts imports. By default, it arranges std, external and local imports in separate groups and there's also support for custom company prefix if you would like a separate group for your organization.

Seer.The
  • 475
  • 5
  • 15