forked from golangci/golangci-lint
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathtext.go
108 lines (89 loc) · 2.53 KB
/
text.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
package printers
import (
"context"
"fmt"
"strings"
"github.com/fatih/color"
"github.com/golangci/golangci-lint/pkg/logutils"
"github.com/golangci/golangci-lint/pkg/result"
)
type Text struct {
printIssuedLine bool
useColors bool
printLinterName bool
log logutils.Log
}
func NewText(printIssuedLine, useColors, printLinterName bool, log logutils.Log) *Text {
return &Text{
printIssuedLine: printIssuedLine,
useColors: useColors,
printLinterName: printLinterName,
log: log,
}
}
func (p Text) SprintfColored(ca color.Attribute, format string, args ...interface{}) string {
if !p.useColors {
return fmt.Sprintf(format, args...)
}
c := color.New(ca)
return c.Sprintf(format, args...)
}
func (p *Text) Print(ctx context.Context, issues []result.Issue) error {
for i := range issues {
p.printIssue(&issues[i])
if !p.printIssuedLine {
continue
}
p.printSourceCode(&issues[i])
p.printUnderLinePointer(&issues[i])
p.printSuggestedEdits(&issues[i])
}
return nil
}
func (p Text) printIssue(i *result.Issue) {
text := p.SprintfColored(color.FgRed, "%s", strings.TrimSpace(i.Text))
if p.printLinterName {
text += fmt.Sprintf(" (%s)", i.FromLinter)
}
pos := p.SprintfColored(color.Bold, "%s:%d", i.FilePath(), i.Line())
if i.Pos.Column != 0 {
pos += fmt.Sprintf(":%d", i.Pos.Column)
}
fmt.Fprintf(logutils.StdOut, "%s: %s\n", pos, text)
}
func (p Text) printSourceCode(i *result.Issue) {
for _, line := range i.SourceLines {
fmt.Fprintln(logutils.StdOut, line)
}
}
func (p Text) printUnderLinePointer(i *result.Issue) {
// if column == 0 it means column is unknown (e.g. for gosec)
if len(i.SourceLines) != 1 || i.Pos.Column == 0 {
return
}
col0 := i.Pos.Column - 1
line := i.SourceLines[0]
prefixRunes := make([]rune, 0, len(line))
for j := 0; j < len(line) && j < col0; j++ {
if line[j] == '\t' {
prefixRunes = append(prefixRunes, '\t')
} else {
prefixRunes = append(prefixRunes, ' ')
}
}
fmt.Fprintf(logutils.StdOut, "%s%s\n", string(prefixRunes), p.SprintfColored(color.FgYellow, "^"))
}
func (p Text) printSuggestedEdits(i *result.Issue) {
var text string
if len(i.SuggestedFixes) > 0 {
for _, fix := range i.SuggestedFixes {
text += p.SprintfColored(color.FgRed, "%s\n", strings.TrimSpace(fix.Message))
var suggestedEdits []string
for _, textEdit := range fix.TextEdits {
suggestedEdits = append(suggestedEdits, strings.TrimSpace(textEdit.NewText))
}
text += strings.Join(suggestedEdits, "\n") + "\n"
}
}
fmt.Fprintln(logutils.StdOut, text)
}