Denis Isaev 9181ca7175 Fix #78: log all warnings
1. Log all warnings, don't hide none of them
2. Write fatal messages (stop analysis) with error log level
3. Remove ugly timestamp counter from logrus output
4. Print nested module prefix in log
5. Make logger abstraction: no global logging anymore
6. Refactor config reading to config.FileReader struct to avoid passing
logger into every function
7. Replace exit codes hardcoding with constants in exitcodes package
8. Fail test if any warning was logged
9. Fix calculation of relative path if we analyze parent dir ../
10. Move Runner initialization from Executor to NewRunner func
11. Log every AST parsing error
12. Properly print used config file path in verbose mode
13. Print package files if only 1 package is analyzedin verbose mode,
  print not compiling packages in verbose mode
14. Forbid usage of github.com/sirupsen/logrus by DepGuard linter
15. Add default ignore pattern to folint: "comment on exported const"
2018-06-14 23:09:04 +03:00

154 lines
3.6 KiB
Go

package printers
import (
"bytes"
"context"
"fmt"
"io/ioutil"
"strings"
"time"
"github.com/fatih/color"
"github.com/golangci/golangci-lint/pkg/logutils"
"github.com/golangci/golangci-lint/pkg/result"
)
type linesCache [][]byte
type filesCache map[string]linesCache
type Text struct {
printIssuedLine bool
useColors bool
printLinterName bool
cache filesCache
log logutils.Log
}
func NewText(printIssuedLine, useColors, printLinterName bool, log logutils.Log) *Text {
return &Text{
printIssuedLine: printIssuedLine,
useColors: useColors,
printLinterName: printLinterName,
cache: filesCache{},
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) getFileLinesForIssue(i *result.Issue) (linesCache, error) {
fc := p.cache[i.FilePath()]
if fc != nil {
return fc, nil
}
// TODO: make more optimal algorithm: don't load all files into memory
fileBytes, err := ioutil.ReadFile(i.FilePath())
if err != nil {
return nil, fmt.Errorf("can't read file %s for printing issued line: %s", i.FilePath(), err)
}
lines := bytes.Split(fileBytes, []byte("\n")) // TODO: what about \r\n?
fc = lines
p.cache[i.FilePath()] = fc
return fc, nil
}
func (p *Text) Print(ctx context.Context, issues <-chan result.Issue) (bool, error) {
var issuedLineExtractingDuration time.Duration
defer func() {
p.log.Infof("Extracting issued lines took %s", issuedLineExtractingDuration)
}()
issuesN := 0
for i := range issues {
issuesN++
p.printIssue(&i)
if !p.printIssuedLine {
continue
}
startedAt := time.Now()
lines, err := p.getFileLinesForIssue(&i)
if err != nil {
return false, err
}
issuedLineExtractingDuration += time.Since(startedAt)
p.printIssuedLines(&i, lines)
if i.Line()-1 < len(lines) {
p.printUnderLinePointer(&i, string(lines[i.Line()-1]))
}
}
if issuesN != 0 {
p.log.Infof("Found %d issues", issuesN)
} else if ctx.Err() == nil { // don't print "congrats" if timeouted
outStr := p.SprintfColored(color.FgGreen, "Congrats! No issues were found.")
fmt.Fprintln(StdOut, outStr)
}
return issuesN != 0, nil
}
func (p Text) printIssue(i *result.Issue) {
text := p.SprintfColored(color.FgRed, "%s", 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(StdOut, "%s: %s\n", pos, text)
}
func (p Text) printIssuedLines(i *result.Issue, lines linesCache) {
lineRange := i.GetLineRange()
var lineStr string
for line := lineRange.From; line <= lineRange.To; line++ {
if line == 0 { // some linters, e.g. gas can do it: it really means first line
line = 1
}
zeroIndexedLine := line - 1
if zeroIndexedLine >= len(lines) {
p.log.Warnf("No line %d in file %s", line, i.FilePath())
break
}
lineStr = string(bytes.Trim(lines[zeroIndexedLine], "\r"))
fmt.Fprintln(StdOut, lineStr)
}
}
func (p Text) printUnderLinePointer(i *result.Issue, line string) {
lineRange := i.GetLineRange()
if lineRange.From != lineRange.To || i.Pos.Column == 0 {
return
}
var j int
for ; j < len(line) && line[j] == '\t'; j++ {
}
tabsCount := j
spacesCount := i.Pos.Column - 1 - tabsCount
prefix := ""
if tabsCount != 0 {
prefix += strings.Repeat("\t", tabsCount)
}
if spacesCount != 0 {
prefix += strings.Repeat(" ", spacesCount)
}
fmt.Fprintf(StdOut, "%s%s\n", prefix, p.SprintfColored(color.FgYellow, "^"))
}