golangci-lint/pkg/config/config.go

111 lines
2.4 KiB
Go
Raw Permalink Normal View History

package config
import (
"os"
2024-03-02 21:43:28 +01:00
"regexp"
"strings"
hcversion "github.com/hashicorp/go-version"
"github.com/ldez/gomoddirectives"
)
2024-02-23 20:38:42 +01:00
// Config encapsulates the config data specified in the golangci-lint yaml config file.
2019-10-03 12:34:19 -04:00
type Config struct {
2024-02-23 20:38:42 +01:00
cfgDir string // The directory containing the golangci-lint config file.
2018-05-05 09:24:37 +03:00
2024-02-23 20:38:42 +01:00
Run Run `mapstructure:"run"`
Output Output `mapstructure:"output"`
LintersSettings LintersSettings `mapstructure:"linters-settings"`
2024-02-23 20:38:42 +01:00
Linters Linters `mapstructure:"linters"`
Issues Issues `mapstructure:"issues"`
Severity Severity `mapstructure:"severity"`
InternalCmdTest bool // Option is used only for testing golangci-lint command, don't use it
2021-02-20 18:55:11 -06:00
InternalTest bool // Option is used only for testing golangci-lint code, don't use it
}
2018-06-28 22:39:23 +03:00
// GetConfigDir returns the directory that contains golangci config file.
func (c *Config) GetConfigDir() string {
return c.cfgDir
}
2024-02-27 00:03:48 +01:00
func (c *Config) Validate() error {
2024-03-02 21:43:28 +01:00
validators := []func() error{
c.Run.Validate,
c.Output.Validate,
2024-03-02 21:43:28 +01:00
c.LintersSettings.Validate,
c.Linters.Validate,
c.Issues.Validate,
c.Severity.Validate,
2024-02-27 00:03:48 +01:00
}
2024-03-02 21:43:28 +01:00
for _, v := range validators {
if err := v(); err != nil {
return err
2024-02-27 00:03:48 +01:00
}
}
return nil
}
2018-06-28 22:39:23 +03:00
func NewDefault() *Config {
return &Config{
LintersSettings: defaultLintersSettings,
}
}
type Version struct {
Format string `mapstructure:"format"`
Debug bool `mapstructure:"debug"`
}
func IsGoGreaterThanOrEqual(current, limit string) bool {
v1, err := hcversion.NewVersion(strings.TrimPrefix(current, "go"))
if err != nil {
return false
}
l, err := hcversion.NewVersion(limit)
if err != nil {
return false
}
return v1.GreaterThanOrEqual(l)
}
2024-02-27 00:03:48 +01:00
func detectGoVersion() string {
file, _ := gomoddirectives.GetModuleFile()
if file != nil && file.Go != nil && file.Go.Version != "" {
return file.Go.Version
}
v := os.Getenv("GOVERSION")
if v != "" {
return v
}
return "1.17"
}
2024-03-02 21:43:28 +01:00
// Trims the Go version to keep only M.m.
// Since Go 1.21 the version inside the go.mod can be a patched version (ex: 1.21.0).
// The version can also include information which we want to remove (ex: 1.21alpha1)
// https://go.dev/doc/toolchain#versions
// This a problem with staticcheck and gocritic.
func trimGoVersion(v string) string {
if v == "" {
return ""
}
exp := regexp.MustCompile(`(\d\.\d+)(?:\.\d+|[a-z]+\d)`)
if exp.MatchString(v) {
return exp.FindStringSubmatch(v)[1]
}
return v
}