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

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