Writing linters is simple. I was surprised how it’s easy to write a Go linter. Today, we’ll write a linter that will calculate the cyclomatic complexity of the Go code.
What is cyclomatic complexity?
Cyclomatic complexity is a software metric used to indicate the complexity of a program. ref
The idea is simple — every time we find any control flow statements we increase the complexity by one. I know I oversimplified it a bit but I don’t want to overwhelm you with unnecessary details.
There are a few steps we should follow to write our custom linter. Firstly, we can create a test that will check if our linter works or not. Let’s put him into pkg/analyzer/analyzer_test.go
file.
package analyzer
import (
"os"
"path/filepath"
"testing"
"golang.org/x/tools/go/analysis/analysistest"
)
func TestAll(t *testing.T) {
wd, err := os.Getwd()
if err != nil {
t.Fatalf("Failed to get wd: %s", err)
}
testdata := filepath.Join(filepath.Dir(filepath.Dir(wd)), "testdata")
analysistest.Run(t, testdata, NewAnalyzer(), "complexity")
}
The analysistest.Run()
function is a helper that simplifies testing linters. What it does is running our linter on package complexity
in testate
folder. We use NewAnalyzer()
function that will return instance of our analyzer. Let’s add it to pkg/analyzer/analyzer.go
.
#go #golang #linter