Skip to content

Commit b167421

Browse files
committed
gofumpt: Add lang-version option + update linter
Without the Go language version input, `gofumpt` cannot apply some rules which are version dependent. Defaulting `lang-version` to the Go version of the running environment if not specified. Signed-off-by: Kailun Qin <[email protected]>
1 parent ba45043 commit b167421

File tree

3 files changed

+23
-3
lines changed

3 files changed

+23
-3
lines changed

.golangci.example.yml

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -259,6 +259,10 @@ linters-settings:
259259
simplify: true
260260

261261
gofumpt:
262+
# Select the Go language version to target.
263+
# Default is the Go version installed in the running environment.
264+
lang-version: "1.15"
265+
262266
# Choose whether or not to use the extra rules that are disabled
263267
# by default
264268
extra-rules: false

pkg/config/linters_settings.go

Lines changed: 4 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -59,7 +59,8 @@ var defaultLintersSettings = LintersSettings{
5959
DefaultSignifiesExhaustive: false,
6060
},
6161
Gofumpt: GofumptSettings{
62-
ExtraRules: false,
62+
LangVersion: "",
63+
ExtraRules: false,
6364
},
6465
ErrorLint: ErrorLintSettings{
6566
Errorf: true,
@@ -232,7 +233,8 @@ type GoFmtSettings struct {
232233
}
233234

234235
type GofumptSettings struct {
235-
ExtraRules bool `mapstructure:"extra-rules"`
236+
LangVersion string `mapstructure:"lang-version"`
237+
ExtraRules bool `mapstructure:"extra-rules"`
236238
}
237239

238240
type GoHeaderSettings struct {

pkg/golinters/gofumpt.go

Lines changed: 15 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -4,6 +4,7 @@ import (
44
"bytes"
55
"fmt"
66
"io/ioutil"
7+
"os/exec"
78
"sync"
89

910
"github.com/pkg/errors"
@@ -46,8 +47,21 @@ func NewGofumpt() *goanalysis.Linter {
4647
if err != nil {
4748
return nil, fmt.Errorf("unable to open file %s: %w", f, err)
4849
}
50+
51+
// Get the target Go language version to be used in gofumpt.
52+
// Reuse logic from `https://github.com/mvdan/gofumpt/blob/master/gofmt.go`.
53+
langVersion := lintCtx.Settings().Gofumpt.LangVersion
54+
if langVersion == "" {
55+
outGoVersion, errGoVersion := exec.Command("go", "list", "-m", "-f", "{{.GoVersion}}").Output()
56+
outGoVersion = bytes.TrimSpace(outGoVersion)
57+
if errGoVersion == nil && len(outGoVersion) > 0 {
58+
langVersion = string(outGoVersion)
59+
}
60+
}
61+
4962
output, err := format.Source(input, format.Options{
50-
ExtraRules: lintCtx.Settings().Gofumpt.ExtraRules,
63+
LangVersion: langVersion,
64+
ExtraRules: lintCtx.Settings().Gofumpt.ExtraRules,
5165
})
5266
if err != nil {
5367
return nil, fmt.Errorf("error while running gofumpt: %w", err)

0 commit comments

Comments
 (0)