github.com/shulhan/golangci-lint@v1.10.1/pkg/golinters/goconst.go (about)

     1  package golinters
     2  
     3  import (
     4  	"context"
     5  	"fmt"
     6  
     7  	goconstAPI "github.com/golangci/goconst"
     8  	"github.com/golangci/golangci-lint/pkg/lint/linter"
     9  	"github.com/golangci/golangci-lint/pkg/result"
    10  )
    11  
    12  type Goconst struct{}
    13  
    14  func (Goconst) Name() string {
    15  	return "goconst"
    16  }
    17  
    18  func (Goconst) Desc() string {
    19  	return "Finds repeated strings that could be replaced by a constant"
    20  }
    21  
    22  func (lint Goconst) Run(ctx context.Context, lintCtx *linter.Context) ([]result.Issue, error) {
    23  	var goconstIssues []goconstAPI.Issue
    24  	cfg := goconstAPI.Config{
    25  		MatchWithConstants: true,
    26  		MinStringLength:    lintCtx.Settings().Goconst.MinStringLen,
    27  		MinOccurrences:     lintCtx.Settings().Goconst.MinOccurrencesCount,
    28  	}
    29  	for _, pkg := range lintCtx.PkgProgram.Packages() {
    30  		files, fset, err := getASTFilesForPkg(lintCtx, &pkg)
    31  		if err != nil {
    32  			return nil, err
    33  		}
    34  
    35  		issues, err := goconstAPI.Run(files, fset, &cfg)
    36  		if err != nil {
    37  			return nil, err
    38  		}
    39  
    40  		goconstIssues = append(goconstIssues, issues...)
    41  	}
    42  	if len(goconstIssues) == 0 {
    43  		return nil, nil
    44  	}
    45  
    46  	res := make([]result.Issue, 0, len(goconstIssues))
    47  	for _, i := range goconstIssues {
    48  		textBegin := fmt.Sprintf("string %s has %d occurrences", formatCode(i.Str, lintCtx.Cfg), i.OccurencesCount)
    49  		var textEnd string
    50  		if i.MatchingConst == "" {
    51  			textEnd = ", make it a constant"
    52  		} else {
    53  			textEnd = fmt.Sprintf(", but such constant %s already exists", formatCode(i.MatchingConst, lintCtx.Cfg))
    54  		}
    55  		res = append(res, result.Issue{
    56  			Pos:        i.Pos,
    57  			Text:       textBegin + textEnd,
    58  			FromLinter: lint.Name(),
    59  		})
    60  	}
    61  
    62  	return res, nil
    63  }