You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

TaskResult.java 12KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328
  1. /*
  2. * SonarQube
  3. * Copyright (C) 2009-2019 SonarSource SA
  4. * mailto:info AT sonarsource DOT com
  5. *
  6. * This program is free software; you can redistribute it and/or
  7. * modify it under the terms of the GNU Lesser General Public
  8. * License as published by the Free Software Foundation; either
  9. * version 3 of the License, or (at your option) any later version.
  10. *
  11. * This program is distributed in the hope that it will be useful,
  12. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  13. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
  14. * Lesser General Public License for more details.
  15. *
  16. * You should have received a copy of the GNU Lesser General Public License
  17. * along with this program; if not, write to the Free Software Foundation,
  18. * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
  19. */
  20. package org.sonar.scanner.mediumtest;
  21. import com.google.common.collect.Iterators;
  22. import com.google.common.collect.Lists;
  23. import java.io.InputStream;
  24. import java.util.ArrayList;
  25. import java.util.Collection;
  26. import java.util.Collections;
  27. import java.util.HashMap;
  28. import java.util.List;
  29. import java.util.Map;
  30. import javax.annotation.CheckForNull;
  31. import org.apache.commons.io.FileUtils;
  32. import org.slf4j.Logger;
  33. import org.slf4j.LoggerFactory;
  34. import org.sonar.api.batch.AnalysisMode;
  35. import org.sonar.api.batch.fs.InputComponent;
  36. import org.sonar.api.batch.fs.InputDir;
  37. import org.sonar.api.batch.fs.InputFile;
  38. import org.sonar.api.batch.fs.InputModule;
  39. import org.sonar.api.batch.fs.TextPointer;
  40. import org.sonar.api.batch.fs.TextRange;
  41. import org.sonar.api.batch.fs.internal.DefaultInputFile;
  42. import org.sonar.api.batch.sensor.highlighting.TypeOfText;
  43. import org.sonar.core.util.CloseableIterator;
  44. import org.sonar.scanner.issue.IssueCache;
  45. import org.sonar.scanner.issue.tracking.TrackedIssue;
  46. import org.sonar.scanner.protocol.output.ScannerReport;
  47. import org.sonar.scanner.protocol.output.ScannerReport.Component;
  48. import org.sonar.scanner.protocol.output.ScannerReport.Metadata;
  49. import org.sonar.scanner.protocol.output.ScannerReport.Symbol;
  50. import org.sonar.scanner.protocol.output.ScannerReportReader;
  51. import org.sonar.scanner.report.ReportPublisher;
  52. import org.sonar.scanner.report.ScannerReportUtils;
  53. import org.sonar.scanner.scan.ProjectScanContainer;
  54. import org.sonar.scanner.scan.filesystem.InputComponentStore;
  55. import static org.apache.commons.lang.StringUtils.isNotEmpty;
  56. public class TaskResult implements org.sonar.scanner.mediumtest.ScanTaskObserver {
  57. private static final Logger LOG = LoggerFactory.getLogger(TaskResult.class);
  58. private List<TrackedIssue> issues = new ArrayList<>();
  59. private Map<String, InputFile> inputFiles = new HashMap<>();
  60. private Map<String, Component> reportComponents = new HashMap<>();
  61. private Map<String, InputDir> inputDirs = new HashMap<>();
  62. private InputModule root;
  63. private ScannerReportReader reader;
  64. @Override
  65. public void scanTaskCompleted(ProjectScanContainer container) {
  66. LOG.info("Store analysis results in memory for later assertions in medium test");
  67. for (TrackedIssue issue : container.getComponentByType(IssueCache.class).all()) {
  68. issues.add(issue);
  69. }
  70. ReportPublisher reportPublisher = container.getComponentByType(ReportPublisher.class);
  71. reader = new ScannerReportReader(reportPublisher.getReportDir().toFile());
  72. if (!container.getComponentByType(AnalysisMode.class).isIssues()) {
  73. Metadata readMetadata = getReportReader().readMetadata();
  74. int rootComponentRef = readMetadata.getRootComponentRef();
  75. storeReportComponents(rootComponentRef, null);
  76. InputComponentStore inputFileCache = container.getComponentByType(InputComponentStore.class);
  77. root = inputFileCache.root();
  78. }
  79. storeFs(container);
  80. }
  81. private void storeReportComponents(int componentRef, String parentModuleKey) {
  82. Component component = getReportReader().readComponent(componentRef);
  83. if (isNotEmpty(component.getKey())) {
  84. reportComponents.put(component.getKey(), component);
  85. } else {
  86. reportComponents.put(parentModuleKey + ":" + component.getPath(), component);
  87. }
  88. for (int childId : component.getChildRefList()) {
  89. storeReportComponents(childId, isNotEmpty(component.getKey()) ? component.getKey() : parentModuleKey);
  90. }
  91. }
  92. public ScannerReportReader getReportReader() {
  93. return reader;
  94. }
  95. private void storeFs(ProjectScanContainer container) {
  96. InputComponentStore inputFileCache = container.getComponentByType(InputComponentStore.class);
  97. for (InputFile inputPath : inputFileCache.allFiles()) {
  98. inputFiles.put(((DefaultInputFile) inputPath).getProjectRelativePath(), inputPath);
  99. }
  100. for (InputDir inputPath : inputFileCache.allDirs()) {
  101. inputDirs.put(inputPath.relativePath(), inputPath);
  102. }
  103. }
  104. public List<TrackedIssue> trackedIssues() {
  105. return issues;
  106. }
  107. public Component getReportComponent(String key) {
  108. return reportComponents.get(key);
  109. }
  110. public List<ScannerReport.Issue> issuesFor(InputComponent inputComponent) {
  111. int ref = reportComponents.get(inputComponent.key()).getRef();
  112. return issuesFor(ref);
  113. }
  114. public List<ScannerReport.ExternalIssue> externalIssuesFor(InputComponent inputComponent) {
  115. int ref = reportComponents.get(inputComponent.key()).getRef();
  116. return externalIssuesFor(ref);
  117. }
  118. public List<ScannerReport.Issue> issuesFor(Component reportComponent) {
  119. int ref = reportComponent.getRef();
  120. return issuesFor(ref);
  121. }
  122. private List<ScannerReport.Issue> issuesFor(int ref) {
  123. List<ScannerReport.Issue> result = Lists.newArrayList();
  124. try (CloseableIterator<ScannerReport.Issue> it = reader.readComponentIssues(ref)) {
  125. while (it.hasNext()) {
  126. result.add(it.next());
  127. }
  128. }
  129. return result;
  130. }
  131. private List<ScannerReport.ExternalIssue> externalIssuesFor(int ref) {
  132. List<ScannerReport.ExternalIssue> result = Lists.newArrayList();
  133. try (CloseableIterator<ScannerReport.ExternalIssue> it = reader.readComponentExternalIssues(ref)) {
  134. while (it.hasNext()) {
  135. result.add(it.next());
  136. }
  137. }
  138. return result;
  139. }
  140. public InputModule root() {
  141. return root;
  142. }
  143. public Collection<InputFile> inputFiles() {
  144. return inputFiles.values();
  145. }
  146. @CheckForNull
  147. public InputFile inputFile(String relativePath) {
  148. return inputFiles.get(relativePath);
  149. }
  150. public Collection<InputDir> inputDirs() {
  151. return inputDirs.values();
  152. }
  153. @CheckForNull
  154. public InputDir inputDir(String relativePath) {
  155. return inputDirs.get(relativePath);
  156. }
  157. public Map<String, List<ScannerReport.Measure>> allMeasures() {
  158. Map<String, List<ScannerReport.Measure>> result = new HashMap<>();
  159. for (Map.Entry<String, Component> component : reportComponents.entrySet()) {
  160. List<ScannerReport.Measure> measures = new ArrayList<>();
  161. try (CloseableIterator<ScannerReport.Measure> it = reader.readComponentMeasures(component.getValue().getRef())) {
  162. Iterators.addAll(measures, it);
  163. }
  164. result.put(component.getKey(), measures);
  165. }
  166. return result;
  167. }
  168. /**
  169. * Get highlighting types at a given position in an inputfile
  170. * @param lineOffset 0-based offset in file
  171. */
  172. public List<TypeOfText> highlightingTypeFor(InputFile file, int line, int lineOffset) {
  173. int ref = reportComponents.get(file.key()).getRef();
  174. if (!reader.hasSyntaxHighlighting(ref)) {
  175. return Collections.emptyList();
  176. }
  177. TextPointer pointer = file.newPointer(line, lineOffset);
  178. List<TypeOfText> result = new ArrayList<>();
  179. try (CloseableIterator<ScannerReport.SyntaxHighlightingRule> it = reader.readComponentSyntaxHighlighting(ref)) {
  180. while (it.hasNext()) {
  181. ScannerReport.SyntaxHighlightingRule rule = it.next();
  182. TextRange ruleRange = toRange(file, rule.getRange());
  183. if (ruleRange.start().compareTo(pointer) <= 0 && ruleRange.end().compareTo(pointer) > 0) {
  184. result.add(ScannerReportUtils.toBatchType(rule.getType()));
  185. }
  186. }
  187. } catch (Exception e) {
  188. throw new IllegalStateException("Can't read syntax highlighting for " + file, e);
  189. }
  190. return result;
  191. }
  192. private static TextRange toRange(InputFile file, ScannerReport.TextRange reportRange) {
  193. return file.newRange(file.newPointer(reportRange.getStartLine(), reportRange.getStartOffset()), file.newPointer(reportRange.getEndLine(), reportRange.getEndOffset()));
  194. }
  195. /**
  196. * Get list of all start positions of a symbol in an inputfile
  197. * @param symbolStartLine 0-based start offset for the symbol in file
  198. * @param symbolStartLineOffset 0-based end offset for the symbol in file
  199. */
  200. @CheckForNull
  201. public List<ScannerReport.TextRange> symbolReferencesFor(InputFile file, int symbolStartLine, int symbolStartLineOffset) {
  202. int ref = reportComponents.get(file.key()).getRef();
  203. try (CloseableIterator<Symbol> symbols = getReportReader().readComponentSymbols(ref)) {
  204. while (symbols.hasNext()) {
  205. Symbol symbol = symbols.next();
  206. if (symbol.getDeclaration().getStartLine() == symbolStartLine && symbol.getDeclaration().getStartOffset() == symbolStartLineOffset) {
  207. return symbol.getReferenceList();
  208. }
  209. }
  210. }
  211. return Collections.emptyList();
  212. }
  213. public List<ScannerReport.Duplication> duplicationsFor(InputFile file) {
  214. List<ScannerReport.Duplication> result = new ArrayList<>();
  215. int ref = reportComponents.get(file.key()).getRef();
  216. try (CloseableIterator<ScannerReport.Duplication> it = getReportReader().readComponentDuplications(ref)) {
  217. while (it.hasNext()) {
  218. result.add(it.next());
  219. }
  220. } catch (Exception e) {
  221. throw new IllegalStateException(e);
  222. }
  223. return result;
  224. }
  225. public List<ScannerReport.CpdTextBlock> duplicationBlocksFor(InputFile file) {
  226. List<ScannerReport.CpdTextBlock> result = new ArrayList<>();
  227. int ref = reportComponents.get(file.key()).getRef();
  228. try (CloseableIterator<ScannerReport.CpdTextBlock> it = getReportReader().readCpdTextBlocks(ref)) {
  229. while (it.hasNext()) {
  230. result.add(it.next());
  231. }
  232. } catch (Exception e) {
  233. throw new IllegalStateException(e);
  234. }
  235. return result;
  236. }
  237. @CheckForNull
  238. public ScannerReport.LineCoverage coverageFor(InputFile file, int line) {
  239. int ref = reportComponents.get(file.key()).getRef();
  240. try (CloseableIterator<ScannerReport.LineCoverage> it = getReportReader().readComponentCoverage(ref)) {
  241. while (it.hasNext()) {
  242. ScannerReport.LineCoverage coverage = it.next();
  243. if (coverage.getLine() == line) {
  244. return coverage;
  245. }
  246. }
  247. } catch (Exception e) {
  248. throw new IllegalStateException(e);
  249. }
  250. return null;
  251. }
  252. public ScannerReport.Test firstTestExecutionForName(InputFile testFile, String testName) {
  253. int ref = reportComponents.get(testFile.key()).getRef();
  254. try (InputStream inputStream = FileUtils.openInputStream(getReportReader().readTests(ref))) {
  255. ScannerReport.Test test = ScannerReport.Test.parser().parseDelimitedFrom(inputStream);
  256. while (test != null) {
  257. if (test.getName().equals(testName)) {
  258. return test;
  259. }
  260. test = ScannerReport.Test.parser().parseDelimitedFrom(inputStream);
  261. }
  262. } catch (Exception e) {
  263. throw new IllegalStateException(e);
  264. }
  265. return null;
  266. }
  267. public ScannerReport.CoverageDetail coveragePerTestFor(InputFile testFile, String testName) {
  268. int ref = reportComponents.get(testFile.key()).getRef();
  269. try (InputStream inputStream = FileUtils.openInputStream(getReportReader().readCoverageDetails(ref))) {
  270. ScannerReport.CoverageDetail details = ScannerReport.CoverageDetail.parser().parseDelimitedFrom(inputStream);
  271. while (details != null) {
  272. if (details.getTestName().equals(testName)) {
  273. return details;
  274. }
  275. details = ScannerReport.CoverageDetail.parser().parseDelimitedFrom(inputStream);
  276. }
  277. } catch (Exception e) {
  278. throw new IllegalStateException(e);
  279. }
  280. return null;
  281. }
  282. public List<ScannerReport.AdHocRule> adHocRules() {
  283. List<ScannerReport.AdHocRule> result = new ArrayList<>();
  284. try (CloseableIterator<ScannerReport.AdHocRule> it = getReportReader().readAdHocRules()) {
  285. while (it.hasNext()) {
  286. result.add(it.next());
  287. }
  288. } catch (Exception e) {
  289. throw new IllegalStateException(e);
  290. }
  291. return result;
  292. }
  293. }