forked from golangci/golangci-lint
/
source_code.go
81 lines (65 loc) · 1.83 KB
/
source_code.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
package processors
import (
"bytes"
"fmt"
"io/ioutil"
"github.com/golangci/golangci-lint/pkg/logutils"
"github.com/golangci/golangci-lint/pkg/result"
)
type linesCache [][]byte
type filesLineCache map[string]linesCache
type SourceCode struct {
cache filesLineCache
log logutils.Log
}
var _ Processor = SourceCode{}
func NewSourceCode(log logutils.Log) *SourceCode {
return &SourceCode{
cache: filesLineCache{},
log: log,
}
}
func (p SourceCode) Name() string {
return "source_code"
}
func (p SourceCode) Process(issues []result.Issue) ([]result.Issue, error) {
return transformIssues(issues, func(i *result.Issue) *result.Issue {
lines, err := p.getFileLinesForIssue(i)
if err != nil {
p.log.Warnf("Failed to get lines for file %s: %s", i.FilePath(), err)
return i
}
newI := *i
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"))
newI.SourceLines = append(newI.SourceLines, lineStr)
}
return &newI
}), nil
}
func (p *SourceCode) 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 SourceCode) Finish() {}