-
Notifications
You must be signed in to change notification settings - Fork 724
Expand file tree
/
Copy pathSonarComponents.java
More file actions
695 lines (615 loc) · 27 KB
/
Copy pathSonarComponents.java
File metadata and controls
695 lines (615 loc) · 27 KB
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
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
/*
* SonarQube Java
* Copyright (C) SonarSource Sàrl
* mailto:info AT sonarsource DOT com
*
* You can redistribute and/or modify this program under the terms of
* the Sonar Source-Available License Version 1, as published by SonarSource Sàrl.
*
* 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 Sonar Source-Available License for more details.
*
* You should have received a copy of the Sonar Source-Available License
* along with this program; if not, see https://sonarsource.com/license/ssal/
*/
package org.sonar.java;
import com.sonar.sslr.api.RecognitionException;
import java.io.File;
import java.io.IOException;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.net.URISyntaxException;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Comparator;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.Optional;
import java.util.Set;
import java.util.TreeSet;
import java.util.function.LongSupplier;
import java.util.function.UnaryOperator;
import java.util.stream.Collectors;
import java.util.stream.Stream;
import javax.annotation.CheckForNull;
import javax.annotation.Nullable;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.sonar.api.SonarProduct;
import org.sonar.api.batch.ScannerSide;
import org.sonar.api.batch.bootstrap.ProjectDefinition;
import org.sonar.api.batch.fs.FileSystem;
import org.sonar.api.batch.fs.InputComponent;
import org.sonar.api.batch.fs.InputFile;
import org.sonar.api.batch.rule.ActiveRules;
import org.sonar.api.batch.rule.CheckFactory;
import org.sonar.api.batch.rule.Checks;
import org.sonar.api.batch.sensor.SensorContext;
import org.sonar.api.batch.sensor.highlighting.NewHighlighting;
import org.sonar.api.batch.sensor.symbol.NewSymbolTable;
import org.sonar.api.config.Configuration;
import org.sonar.api.measures.FileLinesContext;
import org.sonar.api.measures.FileLinesContextFactory;
import org.sonar.api.rule.RuleKey;
import org.sonar.api.rule.RuleScope;
import org.sonar.api.utils.Version;
import org.sonar.java.annotations.VisibleForTesting;
import org.sonar.java.caching.ContentHashCache;
import org.sonar.java.classpath.ClasspathForMain;
import org.sonar.java.classpath.ClasspathForTest;
import org.sonar.java.exceptions.ApiMismatchException;
import org.sonar.java.model.GeneratedFile;
import org.sonar.java.model.JProblem;
import org.sonar.java.model.LineUtils;
import org.sonar.java.reporting.AnalyzerMessage;
import org.sonar.java.reporting.JavaIssue;
import org.sonar.java.utils.ModuleMetadataUtils;
import org.sonar.plugins.java.api.CheckRegistrar;
import org.sonar.plugins.java.api.JavaCheck;
import org.sonar.plugins.java.api.JavaFileScanner;
import org.sonar.plugins.java.api.JspCodeVisitor;
import org.sonar.plugins.java.api.caching.SonarLintCache;
import org.sonarsource.api.sonarlint.SonarLintSide;
import org.sonarsource.sonarlint.plugin.api.SonarLintRuntime;
@ScannerSide
@SonarLintSide
public class SonarComponents extends CheckRegistrar.RegistrarContext {
private static final Logger LOG = LoggerFactory.getLogger(SonarComponents.class);
private static final int LOGGED_MAX_NUMBER_UNDEFINED_TYPES = 50;
public static final String FAIL_ON_EXCEPTION_KEY = "sonar.internal.analysis.failFast";
public static final String SONAR_BATCH_MODE_KEY = "sonar.java.internal.batchMode";
public static final String SONAR_AUTOSCAN = "sonar.internal.analysis.autoscan";
public static final String SONAR_AUTOSCAN_CHECK_FILTERING = "sonar.internal.analysis.autoscan.filtering";
public static final String SONAR_BATCH_SIZE_KEY = "sonar.java.experimental.batchModeSizeInKB";
public static final String SONAR_FILE_BY_FILE = "sonar.java.fileByFile";
/**
* Describes if an optimized analysis of unchanged by skipping some rules is enabled.
* By default, the property is not set (null), leaving SQ/SC to decide whether to enable this behavior.
* Setting it to true or false, forces the behavior from the analyzer independently of the server.
*/
public static final String SONAR_CAN_SKIP_UNCHANGED_FILES_KEY = "sonar.java.skipUnchanged";
/**
* Describes whether input files should be parsed while ignoring unnamed split modules.
* In practice, enabling this parameter should help developers in the Android ecosystem and those
* relying on (transitive) dependencies that do not respect modularization as defined by the JLS.
*/
public static final String SONAR_IGNORE_UNNAMED_MODULE_FOR_SPLIT_PACKAGE = "sonar.java.ignoreUnnamedModuleForSplitPackage";
/**
* Describes whether the analysis should fail and halt when a StackOverflowError is encountered.
* True by default, we still want to give the possibility to disable this behavior in case of large projects
* for which it is costly to run a whole analysis to then just fail at the end and lose all findings.
*/
public static final String SONAR_FAIL_ON_STACKOVERFLOW = "sonar.java.internal.failOnStackOverflow";
private static final Version SONARLINT_6_3 = Version.parse("6.3");
private static final Version SONARQUBE_9_2 = Version.parse("9.2");
@VisibleForTesting
static LongSupplier maxMemoryInBytesProvider = () -> Runtime.getRuntime().maxMemory();
private final FileLinesContextFactory fileLinesContextFactory;
private final ClasspathForMain javaClasspath;
private final ClasspathForTest javaTestClasspath;
private final Map<JProblem, List<String>> problemsToFilePaths = new HashMap<>();
private final CheckFactory checkFactory;
private final ActiveRules activeRules;
@Nullable
private final ProjectDefinition projectDefinition;
@Nullable
private final SonarLintCache sonarLintCache;
private final FileSystem fs;
private final List<JavaCheck> mainChecks;
private final List<JavaCheck> testChecks;
private final List<JavaCheck> jspChecks;
private final List<Checks<JavaCheck>> allChecks;
private SensorContext context;
private UnaryOperator<List<JavaCheck>> checkFilter = UnaryOperator.identity();
private final Set<RuleKey> additionalAutoScanCompatibleRuleKeys;
private boolean alreadyLoggedSkipStatus = false;
public SonarComponents(FileLinesContextFactory fileLinesContextFactory, FileSystem fs,
ClasspathForMain javaClasspath, ClasspathForTest javaTestClasspath,
CheckFactory checkFactory, ActiveRules activeRules) {
this(fileLinesContextFactory, fs, javaClasspath, javaTestClasspath, checkFactory, activeRules, null, null, null);
}
/**
* Can be called in SonarLint context when custom rules are present.
*/
public SonarComponents(FileLinesContextFactory fileLinesContextFactory, FileSystem fs,
ClasspathForMain javaClasspath, ClasspathForTest javaTestClasspath, CheckFactory checkFactory,
ActiveRules activeRules, @Nullable CheckRegistrar[] checkRegistrars) {
this(fileLinesContextFactory, fs, javaClasspath, javaTestClasspath, checkFactory, activeRules, checkRegistrars, null, null);
}
/**
* Will *only* be called in SonarLint context and when custom rules are present.
* <p>
* This is because {@link SonarLintCache} is only added as an extension in a SonarLint context.
* See also {@code JavaPlugin#define} in the {@code sonar-java-plugin} module.
* <p>
* {@code SonarLintCache} is used only by newer custom rules, e.g. DBD.
* Thus, for this constructor, we can also assume the presence of {@code CheckRegistrar} instances.
*/
public SonarComponents(FileLinesContextFactory fileLinesContextFactory, FileSystem fs,
ClasspathForMain javaClasspath, ClasspathForTest javaTestClasspath, CheckFactory checkFactory,
ActiveRules activeRules, @Nullable CheckRegistrar[] checkRegistrars, SonarLintCache sonarLintCache) {
this(fileLinesContextFactory, fs, javaClasspath, javaTestClasspath, checkFactory, activeRules, checkRegistrars, null, sonarLintCache);
}
/**
* Will be called in SonarScanner context when no custom rules are present.
* May be called in some SonarLint contexts, but not others, since ProjectDefinition might not be available.
*/
public SonarComponents(FileLinesContextFactory fileLinesContextFactory, FileSystem fs,
ClasspathForMain javaClasspath, ClasspathForTest javaTestClasspath, CheckFactory checkFactory,
ActiveRules activeRules, @Nullable ProjectDefinition projectDefinition) {
this(fileLinesContextFactory, fs, javaClasspath, javaTestClasspath, checkFactory, activeRules, null, projectDefinition, null);
}
/**
* May be called in some SonarLint contexts, but not others, since ProjectDefinition might not be available.
*/
public SonarComponents(FileLinesContextFactory fileLinesContextFactory, FileSystem fs,
ClasspathForMain javaClasspath, ClasspathForTest javaTestClasspath, CheckFactory checkFactory,
ActiveRules activeRules, @Nullable CheckRegistrar[] checkRegistrars,
@Nullable ProjectDefinition projectDefinition) {
this(
fileLinesContextFactory,
fs,
javaClasspath,
javaTestClasspath,
checkFactory,
activeRules,
checkRegistrars,
projectDefinition,
null
);
}
/**
* All other constructors delegate to this one.
* <p>
* It will also be called directly when constructing a SonarComponents instance for injection if all parameters are available.
* This is for example the case for SonarLint in IntelliJ when DBD is present
* (because ProjectDefinition can be available in recent SonarLint versions, and DBD provides a CheckRegistrar.)
*/
public SonarComponents(FileLinesContextFactory fileLinesContextFactory, FileSystem fs,
ClasspathForMain javaClasspath, ClasspathForTest javaTestClasspath, CheckFactory checkFactory,
ActiveRules activeRules, @Nullable CheckRegistrar[] checkRegistrars,
@Nullable ProjectDefinition projectDefinition, @Nullable SonarLintCache sonarLintCache) {
this.fileLinesContextFactory = fileLinesContextFactory;
this.fs = fs;
this.javaClasspath = javaClasspath;
this.javaTestClasspath = javaTestClasspath;
this.checkFactory = checkFactory;
this.activeRules = activeRules;
this.projectDefinition = projectDefinition;
this.sonarLintCache = sonarLintCache;
this.mainChecks = new ArrayList<>();
this.testChecks = new ArrayList<>();
this.jspChecks = new ArrayList<>();
this.allChecks = new ArrayList<>();
this.additionalAutoScanCompatibleRuleKeys = new TreeSet<>();
if (checkRegistrars != null) {
for (CheckRegistrar registrar : checkRegistrars) {
registrar.register(this, checkFactory);
}
}
}
public void setSensorContext(SensorContext context) {
this.context = context;
}
public void setCheckFilter(UnaryOperator<List<JavaCheck>> checkFilter) {
this.checkFilter = checkFilter;
}
public FileLinesContext fileLinesContextFor(InputFile inputFile) {
return fileLinesContextFactory.createFor(inputFile);
}
public NewSymbolTable symbolizableFor(InputFile inputFile) {
return context.newSymbolTable().onFile(inputFile);
}
public NewHighlighting highlightableFor(InputFile inputFile) {
Objects.requireNonNull(context);
return context.newHighlighting().onFile(inputFile);
}
public List<File> getJavaClasspath() {
if (javaClasspath == null) {
return new ArrayList<>();
}
return javaClasspath.getElements();
}
public boolean inAndroidContext() {
return javaClasspath.inAndroidContext();
}
public List<File> getJavaTestClasspath() {
return javaTestClasspath.getElements();
}
public List<File> getJspClasspath() {
List<File> jspClasspath = new ArrayList<>();
// sonar-java jar is added to classpath in order to have semantic information on code generated from JSP files
jspClasspath.add(findPluginJar());
jspClasspath.addAll(getJavaClasspath());
return jspClasspath;
}
/**
* @return the jar of sonar-java plugin
*/
private static File findPluginJar() {
try {
return new File(SonarComponents.class.getProtectionDomain().getCodeSource().getLocation().toURI());
} catch (URISyntaxException e) {
// this should not happen under normal circumstances, and if it does we want to be aware of it
throw new IllegalStateException("Failed to obtain plugin jar.", e);
}
}
@Override
public void registerMainChecks(String repositoryKey, Collection<?> javaCheckClassesAndInstances) {
registerCheckClasses(mainChecks, getCreatedCheckFromFactory(repositoryKey, javaCheckClassesAndInstances), javaCheckClassesAndInstances);
}
@Override
public void registerMainChecks(Checks<JavaCheck> checks, Collection<?> javaCheckClassesAndInstances) {
registerCheckClasses(mainChecks, checks, javaCheckClassesAndInstances);
}
@Override
public void registerTestChecks(String repositoryKey, Collection<?> javaCheckClassesAndInstances) {
registerCheckClasses(testChecks, getCreatedCheckFromFactory(repositoryKey, javaCheckClassesAndInstances), javaCheckClassesAndInstances);
}
@Override
public void registerMainSharedCheck(JavaCheck check, Collection<RuleKey> ruleKeys) {
if (hasAtLeastOneActiveRule(ruleKeys)) {
mainChecks.add(check);
}
}
@Override
public void registerTestSharedCheck(JavaCheck check, Collection<RuleKey> ruleKeys) {
if (hasAtLeastOneActiveRule(ruleKeys)) {
testChecks.add(check);
}
}
@Override
public void registerCustomFileScanner(RuleScope ruleScope, JavaFileScanner scanner) {
if (ruleScope == RuleScope.MAIN || ruleScope == RuleScope.ALL) {
mainChecks.add(scanner);
}
if (ruleScope == RuleScope.TEST || ruleScope == RuleScope.ALL) {
testChecks.add(scanner);
}
}
@Override
public void registerAutoScanCompatibleRules(Collection<RuleKey> ruleKeys) {
additionalAutoScanCompatibleRuleKeys.addAll(ruleKeys);
}
public Set<RuleKey> getAdditionalAutoScanCompatibleRuleKeys() {
return additionalAutoScanCompatibleRuleKeys;
}
private boolean hasAtLeastOneActiveRule(Collection<RuleKey> ruleKeys) {
return ruleKeys.stream().anyMatch(ruleKey -> activeRules.find(ruleKey) != null);
}
private Checks<JavaCheck> getCreatedCheckFromFactory(String repositoryKey, Collection<?> javaCheckClassesAndInstances) {
return checkFactory.<JavaCheck>create(repositoryKey).addAnnotatedChecks(javaCheckClassesAndInstances);
}
private void registerCheckClasses(List<JavaCheck> destinationList, Checks<JavaCheck> createdChecks, Collection<?> javaCheckClassesAndInstances) {
allChecks.add(createdChecks);
Map<Class<? extends JavaCheck>, Integer> classIndexes = new HashMap<>();
int i = 0;
for (Object javaCheckClassOrInstance : javaCheckClassesAndInstances) {
if (javaCheckClassOrInstance instanceof Class) {
classIndexes.put((Class<? extends JavaCheck>) javaCheckClassOrInstance, i);
} else {
classIndexes.put(((JavaCheck) javaCheckClassOrInstance).getClass(), i);
}
i++;
}
List<? extends JavaCheck> orderedChecks = createdChecks.all().stream()
.sorted(Comparator.comparing(check -> classIndexes.getOrDefault(check.getClass(), Integer.MAX_VALUE)))
.toList();
destinationList.addAll(orderedChecks);
if (LOG.isDebugEnabled()) {
LOG.debug("Registered check: [{}]",
orderedChecks.stream()
.map(c -> c.getClass().getSimpleName() + " (" + createdChecks.ruleKey(c) + ")")
.collect(Collectors.joining(", ")));
}
jspChecks.addAll(orderedChecks.stream().filter(JspCodeVisitor.class::isInstance).toList());
}
public List<JavaCheck> mainChecks() {
return checkFilter.apply(mainChecks);
}
public List<JavaCheck> testChecks() {
return checkFilter.apply(testChecks);
}
public List<JavaCheck> jspChecks() {
return checkFilter.apply(jspChecks);
}
public Optional<RuleKey> getRuleKey(JavaCheck check) {
return allChecks.stream()
.map(sonarChecks -> sonarChecks.ruleKey(check))
.filter(Objects::nonNull)
.findFirst();
}
public void addIssue(InputComponent inputComponent, JavaCheck check, int line, String message, @Nullable Integer cost) {
reportIssue(new AnalyzerMessage(check, inputComponent, line, message, cost != null ? cost.intValue() : 0));
}
public void reportIssue(AnalyzerMessage analyzerMessage) {
JavaCheck check = analyzerMessage.getCheck();
Objects.requireNonNull(check);
Objects.requireNonNull(analyzerMessage.getMessage());
getRuleKey(check).ifPresent(key -> {
InputComponent inputComponent = analyzerMessage.getInputComponent();
if (inputComponent == null) {
return;
}
Double cost = analyzerMessage.getCost();
reportIssue(analyzerMessage, key, inputComponent, cost);
});
}
@VisibleForTesting
void reportIssue(AnalyzerMessage analyzerMessage, RuleKey key, InputComponent fileOrProject, @Nullable Double cost) {
Objects.requireNonNull(context);
JavaIssue issue = JavaIssue.create(context, key, cost);
AnalyzerMessage.TextSpan textSpan = analyzerMessage.primaryLocation();
if (textSpan == null) {
// either an issue at file or project level
issue.setPrimaryLocationOnComponent(fileOrProject, analyzerMessage.getMessage());
} else {
if (!textSpan.onLine()) {
Preconditions.checkState(!textSpan.isEmpty(), "Issue location should not be empty");
}
issue.setPrimaryLocation((InputFile) fileOrProject, analyzerMessage.getMessage(), textSpan.startLine, textSpan.startCharacter,
textSpan.endLine, textSpan.endCharacter);
}
if (!analyzerMessage.flows.isEmpty()) {
issue.addFlow((InputFile) analyzerMessage.getInputComponent(), analyzerMessage.flows);
}
issue.save();
}
public boolean reportAnalysisError(RecognitionException re, InputFile inputFile) {
reportAnalysisError(inputFile, re.getMessage());
return isSonarLintContext();
}
private void reportAnalysisError(InputFile inputFile, String message) {
context.newAnalysisError()
.onFile(inputFile)
.message(message)
.save();
}
public boolean isSonarLintContext() {
return context.runtime().getProduct() == SonarProduct.SONARLINT;
}
public boolean isQuickFixCompatible() {
return isSonarLintContext() && ((SonarLintRuntime) context.runtime()).getSonarLintPluginApiVersion().isGreaterThanOrEqual(SONARLINT_6_3);
}
public boolean isSetQuickFixAvailableCompatible() {
return context.runtime().getProduct() == SonarProduct.SONARQUBE && context.runtime().getApiVersion().isGreaterThanOrEqual(SONARQUBE_9_2);
}
public List<String> fileLines(InputFile inputFile) {
return LineUtils.splitLines(inputFileContents(inputFile));
}
public String inputFileContents(InputFile inputFile) {
try {
return inputFile.contents();
} catch (IOException e) {
throw new AnalysisException(String.format("Unable to read file '%s'", inputFile), e);
}
}
public boolean analysisCancelled() {
return context.isCancelled();
}
public boolean shouldFailAnalysisOnException() {
return context.config().getBoolean(FAIL_ON_EXCEPTION_KEY).orElse(false);
}
public boolean isFileByFileEnabled() {
return context.config().getBoolean(SONAR_FILE_BY_FILE).orElse(false);
}
public boolean isAutoScan() {
return (context.config().getBoolean(SONAR_BATCH_MODE_KEY).orElse(false) ||
context.config().getBoolean(SONAR_AUTOSCAN).orElse(false)) &&
!context.config().hasKey(SONAR_BATCH_SIZE_KEY);
}
public boolean isAutoScanCheckFiltering() {
return isAutoScan() && context.config().getBoolean(SONAR_AUTOSCAN_CHECK_FILTERING).orElse(true);
}
/**
* Returns the batch mode size as read from configuration, in Kilo Bytes. If not value can be found, compute dynamically an ideal value.
*
* @return the batch mode size or a default value of -1L.
*/
public long getBatchModeSizeInKB() {
Configuration config = context.config();
if (isAutoScan()) {
return -1L;
}
return config.getLong(SONAR_BATCH_SIZE_KEY).orElse(computeIdealBatchSize());
}
public boolean shouldIgnoreUnnamedModuleForSplitPackage() {
return context.config().getBoolean(SONAR_IGNORE_UNNAMED_MODULE_FOR_SPLIT_PACKAGE).orElse(false);
}
public boolean shouldFailOnStackOverflow() {
return context.config().getBoolean(SONAR_FAIL_ON_STACKOVERFLOW).orElse(true);
}
private static long computeIdealBatchSize() {
// We take a fraction of the total memory available though -Xmx.
// If we assume that the average size of a file is 5KB and the average CI should have 1GB of memory,
// it will be able to analyze 10 files in batch.
// We max the value to 500KB (100 files) because there is only little advantages to go further.
return Math.min(500L, ((long) (maxMemoryInBytesProvider.getAsLong() * 0.00005)) / 1000L);
}
public File projectLevelWorkDir() {
var root = ModuleMetadataUtils.getRootProject(projectDefinition);
if (root != null) {
return root.getWorkDir();
} else {
return fs.workDir();
}
}
/**
* Returns an OS-independent key that should identify the module within the project
*
* @return A key representing the module
*/
public String getModuleKey() {
return ModuleMetadataUtils.getModuleKey(projectDefinition);
}
/**
* Returns an OS-independent key that should identify the module and its hierarchy within the project
*
* @return A fully-qualified key representing the module
*/
public Optional<String> getFullyQualifiedModuleKey() {
return ModuleMetadataUtils.getFullyQualifiedModuleKey(projectDefinition);
}
public boolean canSkipUnchangedFiles() throws ApiMismatchException {
if (context == null) {
return false;
} else {
var overrideSkipFlag = context.config() == null ? null : context.config().getBoolean(SONAR_CAN_SKIP_UNCHANGED_FILES_KEY).orElse(null);
try {
if (overrideSkipFlag != null) {
return overrideSkipFlag;
}
Method canSkipUnchangedFiles = context.getClass().getMethod("canSkipUnchangedFiles");
return (Boolean) canSkipUnchangedFiles.invoke(context);
} catch (NoSuchMethodError | NoSuchMethodException error) {
throw new ApiMismatchException(error);
} catch (InvocationTargetException | IllegalAccessException error) {
Throwable cause = error.getCause();
if (cause instanceof NoSuchMethodError) {
throw new ApiMismatchException(cause);
}
throw new ApiMismatchException(error);
}
}
}
public boolean fileCanBeSkipped(InputFile inputFile) {
var contentHashCache = new ContentHashCache(this);
if (inputFile instanceof GeneratedFile) {
// Generated files should not be skipped as we cannot assess the change status of the source file
return false;
}
boolean canSkipInContext;
try {
canSkipInContext = canSkipUnchangedFiles();
if (!alreadyLoggedSkipStatus) {
if (canSkipInContext) {
LOG.info("The Java analyzer is running in a context where unchanged files can be skipped. Full analysis is performed " +
"for changed files, optimized analysis for unchanged files.");
} else {
LOG.info("The Java analyzer cannot skip unchanged files in this context. A full analysis is performed for all files.");
}
alreadyLoggedSkipStatus = true;
}
} catch (ApiMismatchException e) {
if (!alreadyLoggedSkipStatus) {
LOG.info(
"Cannot determine whether the context allows skipping unchanged files: canSkipUnchangedFiles not part of sonar-plugin-api. " +
"Not skipping. {}",
e.getCause().getMessage()
);
alreadyLoggedSkipStatus = true;
}
contentHashCache.writeToCache(inputFile);
return false;
}
if (!canSkipInContext || inputFile.status() != InputFile.Status.SAME) {
contentHashCache.writeToCache(inputFile);
return false;
}
return contentHashCache.hasSameHashCached(inputFile);
}
public InputComponent project() {
return context.project();
}
public void collectUndefinedTypes(String pathToFile, Set<JProblem> undefinedTypes) {
undefinedTypes.forEach(problem -> {
List<String> filesAffectedByProblem = problemsToFilePaths.computeIfAbsent(problem, key -> new ArrayList<>());
filesAffectedByProblem.add(pathToFile);
});
}
public void logUndefinedTypes() {
if (problemsToFilePaths.isEmpty()) {
return;
}
javaClasspath.logClasspathWarnings();
if (!isAutoScan()) {
// In autoscan, test + main code are analyzed in the same batch, and we do not make the distinction between
// test and main libraries, everything is inside "sonar.java.libraries", it is expected to let the test property empty.
javaTestClasspath.logClasspathWarnings();
}
logUndefinedTypes(LOGGED_MAX_NUMBER_UNDEFINED_TYPES);
// clear the set so only new undefined types will be logged
problemsToFilePaths.clear();
}
private void logUndefinedTypes(int maxLines) {
logParserMessages(
problemsToFilePaths.entrySet().stream()
.filter(entry -> entry.getKey().type() == JProblem.Type.UNDEFINED_TYPE),
maxLines,
"Unresolved imports/types have been detected during analysis. Enable DEBUG mode to see them.",
"Unresolved imports/types:"
);
logParserMessages(
problemsToFilePaths.entrySet().stream()
.filter(entry -> entry.getKey().type() == JProblem.Type.PREVIEW_FEATURE_USED),
maxLines,
"Use of preview features have been detected during analysis. Enable DEBUG mode to see them.",
"Use of preview features:"
);
}
private static void logParserMessages(Stream<Map.Entry<JProblem, List<String>>> messages, int maxProblems, String warningMessage,
String debugMessage) {
String problemDelimiter = System.lineSeparator() + "- ";
List<List<String>> messagesList = messages
.sorted(Comparator.comparing(entry -> entry.getKey().toString()))
// We only consider the first `maxProblems` elements. We keep an extra one to know if we passed the threshold in later tests.
.limit(maxProblems + 1L)
.map(entry -> {
List<String> paths = entry.getValue();
List<String> problemAndPaths = new ArrayList<>(paths.size() + 1);
problemAndPaths.add(problemDelimiter + entry.getKey().toString());
paths.forEach(path -> problemAndPaths.add(" * " + path));
return problemAndPaths;
})
.toList();
if (messagesList.isEmpty()) {
return;
}
LOG.warn(warningMessage);
if (LOG.isDebugEnabled()) {
boolean moreThanMax = messagesList.size() > maxProblems;
String firstLine = moreThanMax ? (debugMessage + " (Limited to " + maxProblems + ")") : debugMessage;
String lastLine = moreThanMax ? (System.lineSeparator() + problemDelimiter + "...") : "";
LOG.debug(messagesList
.stream()
.limit(maxProblems)
.flatMap(List::stream)
.collect(Collectors.joining(System.lineSeparator(), firstLine, lastLine))
);
}
}
public SensorContext context() {
return context;
}
@CheckForNull
public SonarLintCache sonarLintCache() {
return sonarLintCache;
}
public Configuration getConfiguration() {
return context.config();
}
}