-
Notifications
You must be signed in to change notification settings - Fork 176
/
AnalysisProcessor.java
378 lines (338 loc) · 13.3 KB
/
AnalysisProcessor.java
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
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
/*
* SonarQube JavaScript Plugin
* Copyright (C) 2011-2024 SonarSource SA
* mailto:info AT sonarsource DOT com
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 3 of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this program; if not, write to the Free Software Foundation,
* Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*/
package org.sonar.plugins.javascript.bridge;
import static org.sonar.plugins.javascript.JavaScriptFilePredicate.isTypeScriptFile;
import static org.sonar.plugins.javascript.api.CustomRuleRepository.Language.JAVASCRIPT;
import static org.sonar.plugins.javascript.api.CustomRuleRepository.Language.TYPESCRIPT;
import static org.sonar.plugins.javascript.bridge.BridgeServer.Issue;
import static org.sonar.plugins.javascript.bridge.BridgeServer.IssueLocation;
import static org.sonar.plugins.javascript.bridge.QuickFixSupport.addQuickFixes;
import static org.sonar.plugins.javascript.utils.UnicodeEscape.unicodeEscape;
import java.io.Serializable;
import java.util.Arrays;
import java.util.HashSet;
import java.util.List;
import java.util.stream.Collectors;
import org.sonar.api.batch.fs.InputFile;
import org.sonar.api.batch.sensor.SensorContext;
import org.sonar.api.batch.sensor.cpd.NewCpdTokens;
import org.sonar.api.batch.sensor.highlighting.NewHighlighting;
import org.sonar.api.batch.sensor.highlighting.TypeOfText;
import org.sonar.api.batch.sensor.issue.NewIssue;
import org.sonar.api.batch.sensor.issue.NewIssueLocation;
import org.sonar.api.batch.sensor.symbol.NewSymbol;
import org.sonar.api.batch.sensor.symbol.NewSymbolTable;
import org.sonar.api.issue.NoSonarFilter;
import org.sonar.api.measures.CoreMetrics;
import org.sonar.api.measures.FileLinesContext;
import org.sonar.api.measures.FileLinesContextFactory;
import org.sonar.api.measures.Metric;
import org.sonar.api.rule.RuleKey;
import org.sonar.api.scanner.ScannerSide;
import org.sonar.api.utils.Version;
import org.sonar.api.utils.log.Logger;
import org.sonar.api.utils.log.Loggers;
import org.sonar.plugins.javascript.bridge.BridgeServer.AnalysisResponse;
import org.sonar.plugins.javascript.bridge.cache.CacheAnalysis;
import org.sonarsource.api.sonarlint.SonarLintSide;
import org.sonarsource.sonarlint.plugin.api.SonarLintRuntime;
import org.sonarsource.sonarlint.plugin.api.issue.NewSonarLintIssue;
@ScannerSide
@SonarLintSide
public class AnalysisProcessor {
private static final Logger LOG = Loggers.get(AnalysisProcessor.class);
private static final Version SONARLINT_6_3 = Version.create(6, 3);
private final NoSonarFilter noSonarFilter;
private final FileLinesContextFactory fileLinesContextFactory;
private SensorContext context;
private ContextUtils contextUtils;
private InputFile file;
private JsTsChecks checks;
HashSet<String> uniqueParsingErrors;
public AnalysisProcessor(
NoSonarFilter noSonarFilter,
FileLinesContextFactory fileLinesContextFactory
) {
this.noSonarFilter = noSonarFilter;
this.fileLinesContextFactory = fileLinesContextFactory;
this.uniqueParsingErrors = new HashSet<>();
}
void processResponse(
SensorContext context,
JsTsChecks checks,
InputFile file,
AnalysisResponse response
) {
this.context = context;
contextUtils = new ContextUtils(context);
this.checks = checks;
this.file = file;
if (response.parsingError != null) {
uniqueParsingErrors.add(file.absolutePath());
processParsingError(response.parsingError);
return;
}
if (
YamlSensor.LANGUAGE.equals(file.language()) || HtmlSensor.LANGUAGE.equals(file.language())
) {
// SonarQube expects that there is a single analyzer that saves analysis data like metrics, highlighting,
// and symbols. There is an exception for issues, though. Since sonar-iac saves such data for YAML files
// from Cloudformation configurations, we can only save issues for these files. Same applies for HTML and
// sonar-html plugin.
saveIssues(response.issues);
} else {
// it's important to have an order here:
// saving metrics should be done before saving issues so that NO SONAR lines with issues are indeed ignored
saveMetrics(response.metrics);
saveIssues(response.issues);
saveHighlights(response.highlights);
saveHighlightedSymbols(response.highlightedSymbols);
saveCpd(response.cpdTokens);
}
}
public int parsingErrorFilesCount() {
return uniqueParsingErrors.size();
}
void processCacheAnalysis(SensorContext context, InputFile file, CacheAnalysis cacheAnalysis) {
this.context = context;
contextUtils = new ContextUtils(context);
this.file = file;
if (
YamlSensor.LANGUAGE.equals(file.language()) || HtmlSensor.LANGUAGE.equals(file.language())
) {
// SonarQube expects that there is a single analyzer that saves analysis data like metrics, highlighting,
// and symbols. There is an exception for issues, though. Since sonar-iac saves such data for YAML files
// from Cloudformation configurations, we can only save issues for these files. Same applies for HTML and
// sonar-html plugin.
LOG.debug(
"Skipping processing of the analysis extracted from cache because the javascript plugin doesn't save analysis data of YAML files"
);
} else {
saveCpd(cacheAnalysis.getCpdTokens());
}
}
private void processParsingError(BridgeServer.ParsingError parsingError) {
Integer line = parsingError.line;
String message = parsingError.message;
if (line != null) {
LOG.warn("Failed to parse file [{}] at line {}: {}", file, line, message);
} else if (parsingError.code == BridgeServer.ParsingErrorCode.FAILING_TYPESCRIPT) {
LOG.error("Failed to analyze file [{}] from TypeScript: {}", file, message);
} else {
LOG.error("Failed to analyze file [{}]: {}", file, message);
if (contextUtils.failFast()) {
throw new IllegalStateException("Failed to analyze file " + file);
}
}
var parsingErrorRuleKey = checks.parsingErrorRuleKey();
if (parsingErrorRuleKey != null) {
NewIssue newIssue = context.newIssue();
NewIssueLocation primaryLocation = newIssue.newLocation().message(message).on(file);
if (line != null) {
primaryLocation.at(file.selectLine(line));
}
newIssue.forRule(parsingErrorRuleKey).at(primaryLocation).save();
}
context
.newAnalysisError()
.onFile(file)
.at(file.newPointer(line != null ? line : 1, 0))
.message(message)
.save();
}
private void saveIssues(List<Issue> issues) {
for (Issue issue : issues) {
LOG.debug(
"Saving issue for rule {} on file {} at line {}",
issue.ruleId,
file.absolutePath(),
issue.line
);
saveIssue(issue);
}
}
private void saveHighlights(BridgeServer.Highlight[] highlights) {
NewHighlighting highlighting = context.newHighlighting().onFile(file);
for (BridgeServer.Highlight highlight : highlights) {
try {
highlighting.highlight(
highlight.location.toTextRange(file),
TypeOfText.valueOf(highlight.textType)
);
} catch (IllegalArgumentException e) {
LOG.warn("Failed to save highlight in {} at {}", file.uri(), highlight.location);
LOG.warn("Exception cause", e);
// continue processing other highlights
}
}
highlighting.save();
}
private void saveHighlightedSymbols(BridgeServer.HighlightedSymbol[] highlightedSymbols) {
NewSymbolTable symbolTable = context.newSymbolTable().onFile(file);
for (BridgeServer.HighlightedSymbol highlightedSymbol : highlightedSymbols) {
BridgeServer.Location declaration = highlightedSymbol.declaration;
NewSymbol newSymbol;
try {
newSymbol =
symbolTable.newSymbol(
declaration.startLine,
declaration.startCol,
declaration.endLine,
declaration.endCol
);
} catch (IllegalArgumentException e) {
LOG.warn("Failed to create symbol declaration in {} at {}", file.uri(), declaration);
continue;
}
for (BridgeServer.Location reference : highlightedSymbol.references) {
try {
newSymbol.newReference(
reference.startLine,
reference.startCol,
reference.endLine,
reference.endCol
);
} catch (IllegalArgumentException e) {
LOG.warn("Failed to create symbol reference in {} at {}", file.uri(), reference);
}
}
}
symbolTable.save();
}
private void saveMetrics(BridgeServer.Metrics metrics) {
if (file.type() == InputFile.Type.TEST || contextUtils.isSonarLint()) {
noSonarFilter.noSonarInFile(
file,
Arrays.stream(metrics.nosonarLines).boxed().collect(Collectors.toSet())
);
return;
}
saveMetric(file, CoreMetrics.FUNCTIONS, metrics.functions);
saveMetric(file, CoreMetrics.STATEMENTS, metrics.statements);
saveMetric(file, CoreMetrics.CLASSES, metrics.classes);
saveMetric(file, CoreMetrics.NCLOC, metrics.ncloc.length);
saveMetric(file, CoreMetrics.COMMENT_LINES, metrics.commentLines.length);
saveMetric(file, CoreMetrics.COMPLEXITY, metrics.complexity);
saveMetric(file, CoreMetrics.COGNITIVE_COMPLEXITY, metrics.cognitiveComplexity);
noSonarFilter.noSonarInFile(
file,
Arrays.stream(metrics.nosonarLines).boxed().collect(Collectors.toSet())
);
FileLinesContext fileLinesContext = fileLinesContextFactory.createFor(file);
for (int line : metrics.ncloc) {
fileLinesContext.setIntValue(CoreMetrics.NCLOC_DATA_KEY, line, 1);
}
for (int line : metrics.executableLines) {
fileLinesContext.setIntValue(CoreMetrics.EXECUTABLE_LINES_DATA_KEY, line, 1);
}
fileLinesContext.save();
}
private <T extends Serializable> void saveMetric(InputFile file, Metric<T> metric, T value) {
context.<T>newMeasure().withValue(value).forMetric(metric).on(file).save();
}
private void saveCpd(BridgeServer.CpdToken[] cpdTokens) {
if (file.type().equals(InputFile.Type.TEST) || contextUtils.isSonarLint()) {
// even providing empty 'NewCpdTokens' will trigger duplication computation so skipping
return;
}
NewCpdTokens newCpdTokens = context.newCpdTokens().onFile(file);
for (BridgeServer.CpdToken cpdToken : cpdTokens) {
newCpdTokens.addToken(cpdToken.location.toTextRange(file), cpdToken.image);
}
newCpdTokens.save();
}
void saveIssue(BridgeServer.Issue issue) {
var newIssue = context.newIssue();
var location = newIssue.newLocation().on(file);
if (issue.message != null) {
var escapedMsg = unicodeEscape(issue.message);
location.message(escapedMsg);
}
if (issue.endLine != null) {
location.at(file.newRange(issue.line, issue.column, issue.endLine, issue.endColumn));
} else {
if (issue.line != 0) {
location.at(file.selectLine(issue.line));
}
}
issue.secondaryLocations.forEach(secondary -> {
NewIssueLocation newIssueLocation = newSecondaryLocation(file, newIssue, secondary);
if (newIssueLocation != null) {
newIssue.addLocation(newIssueLocation);
}
});
if (issue.cost != null) {
newIssue.gap(issue.cost);
}
if (issue.quickFixes != null && !issue.quickFixes.isEmpty()) {
if (isSqQuickFixCompatible()) {
newIssue.setQuickFixAvailable(true);
}
if (isQuickFixCompatible()) {
addQuickFixes(issue, (NewSonarLintIssue) newIssue, file);
}
}
var ruleKey = findRuleKey(issue);
if (ruleKey != null) {
newIssue.at(location).forRule(ruleKey).save();
}
}
private RuleKey findRuleKey(Issue issue) {
return checks.ruleKeyByEslintKey(
issue.ruleId,
isTypeScriptFile(file) ? TYPESCRIPT : JAVASCRIPT
);
}
private boolean isSqQuickFixCompatible() {
return (
contextUtils.isSonarQube() &&
context.runtime().getApiVersion().isGreaterThanOrEqual(Version.create(9, 2))
);
}
private boolean isQuickFixCompatible() {
return (
contextUtils.isSonarLint() &&
((SonarLintRuntime) context.runtime()).getSonarLintPluginApiVersion()
.isGreaterThanOrEqual(SONARLINT_6_3)
);
}
private static NewIssueLocation newSecondaryLocation(
InputFile inputFile,
NewIssue issue,
IssueLocation location
) {
NewIssueLocation newIssueLocation = issue.newLocation().on(inputFile);
if (
location.line != null &&
location.endLine != null &&
location.column != null &&
location.endColumn != null
) {
newIssueLocation.at(
inputFile.newRange(location.line, location.column, location.endLine, location.endColumn)
);
if (location.message != null) {
newIssueLocation.message(unicodeEscape(location.message));
}
return newIssueLocation;
}
return null;
}
}