github.com/elek/golangci-lint@v1.42.2-0.20211208090441-c05b7fcb3a9a/pkg/printers/tab.go (about)

     1  package printers
     2  
     3  import (
     4  	"context"
     5  	"fmt"
     6  	"io"
     7  	"text/tabwriter"
     8  
     9  	"github.com/fatih/color"
    10  
    11  	"github.com/elek/golangci-lint/pkg/logutils"
    12  	"github.com/elek/golangci-lint/pkg/result"
    13  )
    14  
    15  type Tab struct {
    16  	printLinterName bool
    17  	log             logutils.Log
    18  }
    19  
    20  func NewTab(printLinterName bool, log logutils.Log) *Tab {
    21  	return &Tab{
    22  		printLinterName: printLinterName,
    23  		log:             log,
    24  	}
    25  }
    26  
    27  func (p Tab) SprintfColored(ca color.Attribute, format string, args ...interface{}) string {
    28  	c := color.New(ca)
    29  	return c.Sprintf(format, args...)
    30  }
    31  
    32  func (p *Tab) Print(ctx context.Context, issues []result.Issue) error {
    33  	w := tabwriter.NewWriter(logutils.StdOut, 0, 0, 2, ' ', 0)
    34  
    35  	for i := range issues {
    36  		p.printIssue(&issues[i], w)
    37  	}
    38  
    39  	if err := w.Flush(); err != nil {
    40  		p.log.Warnf("Can't flush tab writer: %s", err)
    41  	}
    42  
    43  	return nil
    44  }
    45  
    46  func (p Tab) printIssue(i *result.Issue, w io.Writer) {
    47  	text := p.SprintfColored(color.FgRed, "%s", i.Text)
    48  	if p.printLinterName {
    49  		text = fmt.Sprintf("%s\t%s", i.FromLinter, text)
    50  	}
    51  
    52  	pos := p.SprintfColored(color.Bold, "%s:%d", i.FilePath(), i.Line())
    53  	if i.Pos.Column != 0 {
    54  		pos += fmt.Sprintf(":%d", i.Pos.Column)
    55  	}
    56  
    57  	fmt.Fprintf(w, "%s\t%s\n", pos, text)
    58  }