github.com/vanstinator/golangci-lint@v0.0.0-20240223191551-cc572f00d9d1/pkg/printers/github.go (about)

     1  package printers
     2  
     3  import (
     4  	"fmt"
     5  	"io"
     6  	"path/filepath"
     7  
     8  	"github.com/vanstinator/golangci-lint/pkg/result"
     9  )
    10  
    11  type github struct {
    12  	w io.Writer
    13  }
    14  
    15  const defaultGithubSeverity = "error"
    16  
    17  // NewGithub output format outputs issues according to GitHub actions format:
    18  // https://docs.github.com/en/actions/using-workflows/workflow-commands-for-github-actions#setting-an-error-message
    19  func NewGithub(w io.Writer) Printer {
    20  	return &github{w: w}
    21  }
    22  
    23  // print each line as: ::error file=app.js,line=10,col=15::Something went wrong
    24  func formatIssueAsGithub(issue *result.Issue) string {
    25  	severity := defaultGithubSeverity
    26  	if issue.Severity != "" {
    27  		severity = issue.Severity
    28  	}
    29  
    30  	// Convert backslashes to forward slashes.
    31  	// This is needed when running on windows.
    32  	// Otherwise, GitHub won't be able to show the annotations pointing to the file path with backslashes.
    33  	file := filepath.ToSlash(issue.FilePath())
    34  
    35  	ret := fmt.Sprintf("::%s file=%s,line=%d", severity, file, issue.Line())
    36  	if issue.Pos.Column != 0 {
    37  		ret += fmt.Sprintf(",col=%d", issue.Pos.Column)
    38  	}
    39  
    40  	ret += fmt.Sprintf("::%s (%s)", issue.Text, issue.FromLinter)
    41  	return ret
    42  }
    43  
    44  func (p *github) Print(issues []result.Issue) error {
    45  	for ind := range issues {
    46  		_, err := fmt.Fprintln(p.w, formatIssueAsGithub(&issues[ind]))
    47  		if err != nil {
    48  			return err
    49  		}
    50  	}
    51  	return nil
    52  }