github.com/chenfeining/golangci-lint@v1.0.2-0.20230730162517-14c6c67868df/pkg/golinters/thelper.go (about)

     1  package golinters
     2  
     3  import (
     4  	"strings"
     5  
     6  	"github.com/kulti/thelper/pkg/analyzer"
     7  	"golang.org/x/tools/go/analysis"
     8  
     9  	"github.com/chenfeining/golangci-lint/pkg/config"
    10  	"github.com/chenfeining/golangci-lint/pkg/golinters/goanalysis"
    11  )
    12  
    13  func NewThelper(cfg *config.ThelperSettings) *goanalysis.Linter {
    14  	a := analyzer.NewAnalyzer()
    15  
    16  	opts := map[string]struct{}{
    17  		"t_name":  {},
    18  		"t_begin": {},
    19  		"t_first": {},
    20  
    21  		"f_name":  {},
    22  		"f_begin": {},
    23  		"f_first": {},
    24  
    25  		"b_name":  {},
    26  		"b_begin": {},
    27  		"b_first": {},
    28  
    29  		"tb_name":  {},
    30  		"tb_begin": {},
    31  		"tb_first": {},
    32  	}
    33  
    34  	if cfg != nil {
    35  		applyTHelperOptions(cfg.Test, "t_", opts)
    36  		applyTHelperOptions(cfg.Fuzz, "f_", opts)
    37  		applyTHelperOptions(cfg.Benchmark, "b_", opts)
    38  		applyTHelperOptions(cfg.TB, "tb_", opts)
    39  	}
    40  
    41  	if len(opts) == 0 {
    42  		linterLogger.Fatalf("thelper: at least one option must be enabled")
    43  	}
    44  
    45  	var args []string
    46  	for k := range opts {
    47  		args = append(args, k)
    48  	}
    49  
    50  	cfgMap := map[string]map[string]any{
    51  		a.Name: {
    52  			"checks": strings.Join(args, ","),
    53  		},
    54  	}
    55  
    56  	return goanalysis.NewLinter(
    57  		"thelper",
    58  		"thelper detects Go test helpers without t.Helper() call and checks the consistency of test helpers",
    59  		[]*analysis.Analyzer{a},
    60  		cfgMap,
    61  	).WithLoadMode(goanalysis.LoadModeTypesInfo)
    62  }
    63  
    64  func applyTHelperOptions(o config.ThelperOptions, prefix string, opts map[string]struct{}) {
    65  	if o.Name != nil {
    66  		if !*o.Name {
    67  			delete(opts, prefix+"name")
    68  		}
    69  	}
    70  
    71  	if o.Begin != nil {
    72  		if !*o.Begin {
    73  			delete(opts, prefix+"begin")
    74  		}
    75  	}
    76  
    77  	if o.First != nil {
    78  		if !*o.First {
    79  			delete(opts, prefix+"first")
    80  		}
    81  	}
    82  }