-
-
Notifications
You must be signed in to change notification settings - Fork 1.4k
/
Copy pathfixer.go
248 lines (208 loc) · 6.91 KB
/
fixer.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
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
package processors
import (
"bytes"
"fmt"
"os"
"path/filepath"
"sort"
"strings"
"github.com/pkg/errors"
"github.com/golangci/golangci-lint/pkg/config"
"github.com/golangci/golangci-lint/pkg/fsutils"
"github.com/golangci/golangci-lint/pkg/logutils"
"github.com/golangci/golangci-lint/pkg/result"
"github.com/golangci/golangci-lint/pkg/timeutils"
)
type Fixer struct {
cfg *config.Config
log logutils.Log
fileCache *fsutils.FileCache
sw *timeutils.Stopwatch
}
func NewFixer(cfg *config.Config, log logutils.Log, fileCache *fsutils.FileCache) *Fixer {
return &Fixer{
cfg: cfg,
log: log,
fileCache: fileCache,
sw: timeutils.NewStopwatch("fixer", log),
}
}
func (f Fixer) printStat() {
f.sw.PrintStages()
}
func (f Fixer) Process(issues []result.Issue) []result.Issue {
if !f.cfg.Issues.NeedFix {
return issues
}
outIssues := make([]result.Issue, 0, len(issues))
issuesToFixPerFile := map[string][]result.Issue{}
for i := range issues {
issue := &issues[i]
if issue.Replacement == nil {
outIssues = append(outIssues, *issue)
continue
}
issuesToFixPerFile[issue.FilePath()] = append(issuesToFixPerFile[issue.FilePath()], *issue)
}
for file, issuesToFix := range issuesToFixPerFile {
var err error
f.sw.TrackStage("all", func() {
err = f.fixIssuesInFile(file, issuesToFix) //nolint:scopelint
})
if err != nil {
f.log.Errorf("Failed to fix issues in file %s: %s", file, err)
// show issues only if can't fix them
outIssues = append(outIssues, issuesToFix...)
}
}
f.printStat()
return outIssues
}
func (f Fixer) fixIssuesInFile(filePath string, issues []result.Issue) error {
// TODO: don't read the whole file into memory: read line by line;
// can't just use bufio.scanner: it has a line length limit
origFileData, err := f.fileCache.GetFileBytes(filePath)
if err != nil {
return errors.Wrapf(err, "failed to get file bytes for %s", filePath)
}
origFileLines := bytes.Split(origFileData, []byte("\n"))
tmpFileName := filepath.Join(filepath.Dir(filePath), fmt.Sprintf(".%s.golangci_fix", filepath.Base(filePath)))
tmpOutFile, err := os.Create(tmpFileName)
if err != nil {
return errors.Wrapf(err, "failed to make file %s", tmpFileName)
}
// merge multiple issues per line into one issue
issuesPerLine := map[int][]result.Issue{}
for i := range issues {
issue := &issues[i]
issuesPerLine[issue.Line()] = append(issuesPerLine[issue.Line()], *issue)
}
issues = issues[:0] // reuse the same memory
for line, lineIssues := range issuesPerLine {
if mergedIssue := f.mergeLineIssues(line, lineIssues, origFileLines); mergedIssue != nil {
issues = append(issues, *mergedIssue)
}
}
issues = f.findNotIntersectingIssues(issues)
if err = f.writeFixedFile(origFileLines, issues, tmpOutFile); err != nil {
tmpOutFile.Close()
os.Remove(tmpOutFile.Name())
return err
}
tmpOutFile.Close()
if err = os.Rename(tmpOutFile.Name(), filePath); err != nil {
os.Remove(tmpOutFile.Name())
return errors.Wrapf(err, "failed to rename %s -> %s", tmpOutFile.Name(), filePath)
}
return nil
}
func (f Fixer) mergeLineIssues(lineNum int, lineIssues []result.Issue, origFileLines [][]byte) *result.Issue {
origLine := origFileLines[lineNum-1] // lineNum is 1-based
if len(lineIssues) == 1 && lineIssues[0].Replacement.Inline == nil {
return &lineIssues[0]
}
// check issues first
for ind := range lineIssues {
i := &lineIssues[ind]
if i.LineRange != nil {
f.log.Infof("Line %d has multiple issues but at least one of them is ranged: %#v", lineNum, lineIssues)
return &lineIssues[0]
}
r := i.Replacement
if r.Inline == nil || len(r.NewLines) != 0 || r.NeedOnlyDelete {
f.log.Infof("Line %d has multiple issues but at least one of them isn't inline: %#v", lineNum, lineIssues)
return &lineIssues[0]
}
if r.Inline.StartCol < 0 || r.Inline.Length <= 0 || r.Inline.StartCol+r.Inline.Length > len(origLine) {
f.log.Warnf("Line %d (%q) has invalid inline fix: %#v, %#v", lineNum, origLine, i, r.Inline)
return nil
}
}
return f.applyInlineFixes(lineIssues, origLine, lineNum)
}
func (f Fixer) applyInlineFixes(lineIssues []result.Issue, origLine []byte, lineNum int) *result.Issue {
sort.Slice(lineIssues, func(i, j int) bool {
return lineIssues[i].Replacement.Inline.StartCol < lineIssues[j].Replacement.Inline.StartCol
})
var newLineBuf bytes.Buffer
newLineBuf.Grow(len(origLine))
//nolint:misspell
// example: origLine="it's becouse of them", StartCol=5, Length=7, NewString="because"
curOrigLinePos := 0
for i := range lineIssues {
fix := lineIssues[i].Replacement.Inline
if fix.StartCol < curOrigLinePos {
f.log.Warnf("Line %d has multiple intersecting issues: %#v", lineNum, lineIssues)
return nil
}
if curOrigLinePos != fix.StartCol {
newLineBuf.Write(origLine[curOrigLinePos:fix.StartCol])
}
newLineBuf.WriteString(fix.NewString)
curOrigLinePos = fix.StartCol + fix.Length
}
if curOrigLinePos != len(origLine) {
newLineBuf.Write(origLine[curOrigLinePos:])
}
mergedIssue := lineIssues[0] // use text from the first issue (it's not really used)
mergedIssue.Replacement = &result.Replacement{
NewLines: []string{newLineBuf.String()},
}
return &mergedIssue
}
func (f Fixer) findNotIntersectingIssues(issues []result.Issue) []result.Issue {
sort.SliceStable(issues, func(i, j int) bool {
a, b := issues[i], issues[j]
return a.Line() < b.Line()
})
var ret []result.Issue
var currentEnd int
for i := range issues {
issue := &issues[i]
rng := issue.GetLineRange()
if rng.From <= currentEnd {
f.log.Infof("Skip issue %#v: intersects with end %d", issue, currentEnd)
continue // skip intersecting issue
}
f.log.Infof("Fix issue %#v with range %v", issue, issue.GetLineRange())
ret = append(ret, *issue)
currentEnd = rng.To
}
return ret
}
func (f Fixer) writeFixedFile(origFileLines [][]byte, issues []result.Issue, tmpOutFile *os.File) error {
// issues aren't intersecting
nextIssueIndex := 0
for i := 0; i < len(origFileLines); i++ {
var outLine string
var nextIssue *result.Issue
if nextIssueIndex != len(issues) {
nextIssue = &issues[nextIssueIndex]
}
origFileLineNumber := i + 1
if nextIssue == nil || origFileLineNumber != nextIssue.GetLineRange().From {
outLine = string(origFileLines[i])
} else {
nextIssueIndex++
rng := nextIssue.GetLineRange()
if rng.From > rng.To {
// Maybe better decision is to skip such issues, re-evaluate if regressed.
f.log.Warnf("[fixer]: issue line range is probably invalid, fix can be incorrect (from=%d, to=%d, linter=%s)",
rng.From, rng.To, nextIssue.FromLinter,
)
}
i += rng.To - rng.From
if nextIssue.Replacement.NeedOnlyDelete {
continue
}
outLine = strings.Join(nextIssue.Replacement.NewLines, "\n")
}
if i < len(origFileLines)-1 {
outLine += "\n"
}
if _, err := tmpOutFile.WriteString(outLine); err != nil {
return errors.Wrap(err, "failed to write output line")
}
}
return nil
}