github.com/nozzle/golangci-lint@v1.49.0-nz3/pkg/golinters/goanalysis/errors.go (about)

     1  package goanalysis
     2  
     3  import (
     4  	"fmt"
     5  
     6  	"github.com/pkg/errors"
     7  	"golang.org/x/tools/go/packages"
     8  
     9  	"github.com/golangci/golangci-lint/pkg/lint/linter"
    10  	libpackages "github.com/golangci/golangci-lint/pkg/packages"
    11  	"github.com/golangci/golangci-lint/pkg/result"
    12  )
    13  
    14  type IllTypedError struct {
    15  	Pkg *packages.Package
    16  }
    17  
    18  func (e *IllTypedError) Error() string {
    19  	return fmt.Sprintf("errors in package: %v", e.Pkg.Errors)
    20  }
    21  
    22  func buildIssuesFromIllTypedError(errs []error, lintCtx *linter.Context) ([]result.Issue, error) {
    23  	var issues []result.Issue
    24  	uniqReportedIssues := map[string]bool{}
    25  
    26  	var other error
    27  
    28  	for _, err := range errs {
    29  		err := err
    30  
    31  		var ill *IllTypedError
    32  		if !errors.As(err, &ill) {
    33  			if other == nil {
    34  				other = err
    35  			}
    36  			continue
    37  		}
    38  
    39  		for _, err := range libpackages.ExtractErrors(ill.Pkg) {
    40  			i, perr := parseError(err)
    41  			if perr != nil { // failed to parse
    42  				if uniqReportedIssues[err.Msg] {
    43  					continue
    44  				}
    45  				uniqReportedIssues[err.Msg] = true
    46  				lintCtx.Log.Errorf("typechecking error: %s", err.Msg)
    47  			} else {
    48  				i.Pkg = ill.Pkg // to save to cache later
    49  				issues = append(issues, *i)
    50  			}
    51  		}
    52  	}
    53  
    54  	if len(issues) == 0 && other != nil {
    55  		return nil, other
    56  	}
    57  
    58  	return issues, nil
    59  }
    60  
    61  func parseError(srcErr packages.Error) (*result.Issue, error) {
    62  	pos, err := libpackages.ParseErrorPosition(srcErr.Pos)
    63  	if err != nil {
    64  		return nil, err
    65  	}
    66  
    67  	return &result.Issue{
    68  		Pos:        *pos,
    69  		Text:       srcErr.Msg,
    70  		FromLinter: "typecheck",
    71  	}, nil
    72  }