-
Notifications
You must be signed in to change notification settings - Fork 5
/
analyzer.go
257 lines (219 loc) · 6.02 KB
/
analyzer.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
249
250
251
252
253
254
255
256
257
package gometalint
import (
"context"
"fmt"
"io"
"io/ioutil"
"math"
"os"
"path"
"strconv"
"strings"
types "github.com/gogo/protobuf/types"
log "gopkg.in/src-d/go-log.v1"
"gopkg.in/src-d/lookout-sdk.v0/pb"
)
const artificialSep = "___.___"
// Analyzer for the lookout
type Analyzer struct {
Version string
DataClient pb.DataClient
Args []string
}
var _ pb.AnalyzerServer = &Analyzer{}
// function to convert pb.types.Value to string argument
type argumentConstructor func(logger log.Logger, v *types.Value) string
// map of linters with options and argument constructors
var lintersOptions = map[string]map[string]argumentConstructor{
"lll": map[string]argumentConstructor{
"maxLen": func(logger log.Logger, v *types.Value) string {
var number int
switch v.GetKind().(type) {
case *types.Value_StringValue:
n, err := strconv.Atoi(v.GetStringValue())
if err != nil {
logger.Warningf("wrong type for lll:maxLen argument")
return ""
}
number = n
case *types.Value_NumberValue:
intpart, frac := math.Modf(v.GetNumberValue())
if frac != 0 {
logger.Warningf("wrong type for lll:maxLen argument")
return ""
}
number = int(intpart)
default:
logger.Warningf("wrong type for lll:maxLen argument")
return ""
}
if number < 1 {
return ""
}
return fmt.Sprintf("--line-length=%d", number)
},
},
}
func (a *Analyzer) NotifyReviewEvent(ctx context.Context, e *pb.ReviewEvent) (
*pb.EventResponse, error) {
logger := log.With(log.Fields(pb.GetLogFields(ctx)))
changes, err := a.DataClient.GetChanges(ctx, &pb.ChangesRequest{
Head: &e.Head,
Base: &e.Base,
WantContents: true,
WantUAST: false,
ExcludeVendored: true,
IncludeLanguages: []string{"go"},
})
if err != nil {
logger.Errorf(err, "failed to GetChanges from a DataService")
return nil, err
}
tmp, err := ioutil.TempDir("", "gometalint")
if err != nil {
logger.Errorf(err, "cannot create tmp dir in %s", os.TempDir())
return nil, err
}
defer os.RemoveAll(tmp)
logger.Debugf("Saving files to '%s'", tmp)
found, saved := 0, 0
for {
change, err := changes.Recv()
if err == io.EOF {
break
}
if err != nil {
logger.Errorf(err, "failed to get a file from DataServer")
continue
}
if change.Head == nil {
continue
}
file := change.Head
if err = saveTo(file, tmp); err != nil {
logger.Errorf(err, "failed to write file %q", file.Path)
} else {
saved++
}
found++
}
if saved < found {
logger.Warningf("%d/%d Golang files saved. analyzer won't run on non-saved ones", saved, found)
}
if saved == 0 {
logger.Debugf("no Golang files to work on. skip running gometalinter")
return &pb.EventResponse{AnalyzerVersion: a.Version}, nil
}
logger.Debugf("%d Golang files to work on. running gometalinter", saved)
withArgs := append(append(a.Args, tmp), a.linterArguments(logger, e.Configuration)...)
comments := RunGometalinter(withArgs)
var allComments []*pb.Comment
for _, comment := range comments {
origPathFile := revertOriginalPath(comment.file, tmp)
origPathText := revertOriginalPathIn(comment.text, tmp)
newComment := pb.Comment{
File: origPathFile,
Line: comment.lino,
Text: origPathText,
}
allComments = append(allComments, &newComment)
logger.Debugf("Get comment %v", newComment)
}
logger.Infof("%d comments created", len(allComments))
return &pb.EventResponse{
AnalyzerVersion: a.Version,
Comments: allComments,
}, nil
}
// flattenPath flattens relative path and puts it inside tmp.
func flattenPath(file string, tmp string) string {
nFile := strings.Join(strings.Split(file, string(os.PathSeparator)), artificialSep)
nPath := path.Join(tmp, nFile)
return nPath
}
// revertOriginalPath reverses origina path from a flat one.
func revertOriginalPath(file string, tmp string) string {
//TrimLeft(, tmp) but works for rel paths
noTmpfile := file[strings.Index(file, tmp)+len(tmp):]
origPathFile := strings.TrimLeft(
path.Join(strings.Split(noTmpfile, artificialSep)...),
string(os.PathSeparator))
return origPathFile
}
// revertOriginalPathIn a given text, recovers original path in words
// that have 'artificialSep'.
func revertOriginalPathIn(text string, tmp string) string {
if strings.LastIndex(text, artificialSep) < 0 {
return text
}
var words []string
for _, word := range strings.Fields(text) {
if strings.Index(word, artificialSep) >= 0 {
word = revertOriginalPath(word, tmp)
}
words = append(words, word)
}
return strings.Join(words, " ")
}
// saveTo saves a file to given dir, preserving it's original path.
// In case of error it is returned. All files saved this way will
// be in the root of the same dir.
func saveTo(file *pb.File, tmp string) error {
flatPath := flattenPath(file.Path, tmp)
return ioutil.WriteFile(flatPath, file.Content, 0644)
}
func (a *Analyzer) NotifyPushEvent(ctx context.Context, e *pb.PushEvent) (*pb.EventResponse, error) {
return &pb.EventResponse{}, nil
}
func (a *Analyzer) linterArguments(logger log.Logger, s types.Struct) []string {
config := s.GetFields()
if config == nil {
return nil
}
clStruct, ok := config["linters"]
if !ok || clStruct == nil {
return nil
}
lintersListValue := clStruct.GetListValue()
if lintersListValue == nil {
return nil
}
var args []string
for _, v := range lintersListValue.GetValues() {
if v == nil {
continue
}
sv := v.GetStructValue()
if sv == nil {
continue
}
fields := sv.GetFields()
nameV, ok := fields["name"]
if !ok || nameV == nil {
continue
}
name := nameV.GetStringValue()
correctLinter := false
for linter := range lintersOptions {
if name == linter {
correctLinter = true
}
}
if !correctLinter {
logger.Warningf("unknown linter %s", name)
continue
}
linterOpts := lintersOptions[name]
for optionName := range linterOpts {
optV, ok := fields[optionName]
if !ok || optV == nil {
continue
}
arg := linterOpts[optionName](logger, optV)
if arg != "" {
args = append(args, arg)
}
}
}
return args
}