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