Search code examples
golint

Golang linter issues 'context loading failed: no go files to analyze'


We are using

  • golangci-lint version 1.40.1 together with
  • golang version 1.16.4

in our project for linting our Golang code.

Until now, what we did is running this bash script (from the root directory of our repository):

if ! [ -x "$(command -v golangci-lint)" ]; then
    echo "Fetching linter..."
    go install github.com/golangci/golangci-lint/cmd/golangci-lint
    go mod tidy
fi

golangci-lint run --build-tags="unit contract container"

With some recent updates of Golang and golangci-lint, we suddenly face this error message:

ERRO Running error: context loading failed: no go files to analyze 

There is a lengthy post on GitHub regarding this issue but the only useful suggestion there is to turn off the GO111MODULE env variable. When I run the linter with GO111MODULE turned off like

GO111MODULE=off golangci-lint run --build-tags="unit contract container"

the upper error message disappears but instead I am getting lots of false linting errors like:

api/router.go:152:5: undeclared name: `PermissionUpdatePackage` (typecheck)
                                PermissionUpdatePackage,
                                ^

My go environment looks like this:

GO111MODULE=on
GOPATH=/Users/USER/workspace/go
GOROOT=/usr/local/opt/go/libexec
GOPRIVATE=*.CUSTOMER.com
GOSS_PATH=/usr/local/bin/goss

I tried to install the linter via go get... as well as go install ... and finally brew install golangci-lint which seems to be the recommended way following this documentation.


Solution

  • Running a go get ./... in the root of the project eventually solved the issues. In between we ran the following commands that probably cleared some (module?) caches that might have caused trouble as well:

    golangci-lint cache clean && go clean -modcache -cache -i
    golangci-lint run -v --timeout=5s
    

    The error message

    ERRO Running error: context loading failed: failed to load packages: timed out to load packages: context deadline exceeded 
    

    in the latter command pointed us to this GitHub post that made me try out go get ./...

    For installing the linter (with a specified version), we ended up with this script:

    linter_version='1.40.1'
    if ! [ -x "$(command -v golangci-lint)" ]; then
        echo "Fetching linter..."
        # we cannot install linter in the project directory, otherwise we get dependency errors
        # hence, temporarily jump into the /tmp directory
        pushd /tmp > /dev/null
        GO111MODULE=on go get github.com/golangci/golangci-lint/cmd/golangci-lint@v"${linter_version}" 2>&1
        popd >/dev/null
    fi