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.

SensorContextTester.java 14KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407
  1. /*
  2. * SonarQube
  3. * Copyright (C) 2009-2020 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.api.batch.sensor.internal;
  21. import java.io.File;
  22. import java.io.Serializable;
  23. import java.nio.charset.Charset;
  24. import java.nio.file.Path;
  25. import java.util.ArrayList;
  26. import java.util.Collection;
  27. import java.util.Collections;
  28. import java.util.List;
  29. import java.util.Map;
  30. import java.util.Objects;
  31. import java.util.Set;
  32. import java.util.stream.Stream;
  33. import javax.annotation.CheckForNull;
  34. import javax.annotation.Nullable;
  35. import org.sonar.api.SonarQubeSide;
  36. import org.sonar.api.SonarRuntime;
  37. import org.sonar.api.batch.bootstrap.ProjectDefinition;
  38. import org.sonar.api.batch.fs.InputFile;
  39. import org.sonar.api.batch.fs.InputModule;
  40. import org.sonar.api.batch.fs.TextRange;
  41. import org.sonar.api.batch.fs.internal.DefaultFileSystem;
  42. import org.sonar.api.batch.fs.internal.DefaultInputFile;
  43. import org.sonar.api.batch.fs.internal.DefaultInputModule;
  44. import org.sonar.api.batch.fs.internal.DefaultInputProject;
  45. import org.sonar.api.batch.fs.internal.DefaultTextPointer;
  46. import org.sonar.api.batch.rule.ActiveRules;
  47. import org.sonar.api.batch.rule.internal.ActiveRulesBuilder;
  48. import org.sonar.api.batch.sensor.Sensor;
  49. import org.sonar.api.batch.sensor.SensorContext;
  50. import org.sonar.api.batch.sensor.code.NewSignificantCode;
  51. import org.sonar.api.batch.sensor.code.internal.DefaultSignificantCode;
  52. import org.sonar.api.batch.sensor.coverage.NewCoverage;
  53. import org.sonar.api.batch.sensor.coverage.internal.DefaultCoverage;
  54. import org.sonar.api.batch.sensor.cpd.NewCpdTokens;
  55. import org.sonar.api.batch.sensor.cpd.internal.DefaultCpdTokens;
  56. import org.sonar.api.batch.sensor.cpd.internal.TokensLine;
  57. import org.sonar.api.batch.sensor.error.AnalysisError;
  58. import org.sonar.api.batch.sensor.error.NewAnalysisError;
  59. import org.sonar.api.batch.sensor.error.internal.DefaultAnalysisError;
  60. import org.sonar.api.batch.sensor.highlighting.NewHighlighting;
  61. import org.sonar.api.batch.sensor.highlighting.TypeOfText;
  62. import org.sonar.api.batch.sensor.highlighting.internal.DefaultHighlighting;
  63. import org.sonar.api.batch.sensor.highlighting.internal.SyntaxHighlightingRule;
  64. import org.sonar.api.batch.sensor.issue.ExternalIssue;
  65. import org.sonar.api.batch.sensor.issue.Issue;
  66. import org.sonar.api.batch.sensor.issue.NewExternalIssue;
  67. import org.sonar.api.batch.sensor.issue.NewIssue;
  68. import org.sonar.api.batch.sensor.issue.internal.DefaultExternalIssue;
  69. import org.sonar.api.batch.sensor.issue.internal.DefaultIssue;
  70. import org.sonar.api.batch.sensor.measure.Measure;
  71. import org.sonar.api.batch.sensor.measure.NewMeasure;
  72. import org.sonar.api.batch.sensor.measure.internal.DefaultMeasure;
  73. import org.sonar.api.batch.sensor.rule.AdHocRule;
  74. import org.sonar.api.batch.sensor.rule.NewAdHocRule;
  75. import org.sonar.api.batch.sensor.rule.internal.DefaultAdHocRule;
  76. import org.sonar.api.batch.sensor.symbol.NewSymbolTable;
  77. import org.sonar.api.batch.sensor.symbol.internal.DefaultSymbolTable;
  78. import org.sonar.api.config.Configuration;
  79. import org.sonar.api.config.internal.ConfigurationBridge;
  80. import org.sonar.api.config.internal.MapSettings;
  81. import org.sonar.api.internal.MetadataLoader;
  82. import org.sonar.api.internal.SonarRuntimeImpl;
  83. import org.sonar.api.measures.Metric;
  84. import org.sonar.api.scanner.fs.InputProject;
  85. import org.sonar.api.utils.System2;
  86. import org.sonar.api.utils.Version;
  87. import static java.util.Collections.unmodifiableMap;
  88. /**
  89. * Utility class to help testing {@link Sensor}. This is not an API and method signature may evolve.
  90. * <p>
  91. * Usage: call {@link #create(File)} to create an "in memory" implementation of {@link SensorContext} with a filesystem initialized with provided baseDir.
  92. * <p>
  93. * You have to manually register inputFiles using:
  94. * <pre>
  95. * sensorContextTester.fileSystem().add(new DefaultInputFile("myProjectKey", "src/Foo.java")
  96. * .setLanguage("java")
  97. * .initMetadata("public class Foo {\n}"));
  98. * </pre>
  99. * <p>
  100. * Then pass it to your {@link Sensor}. You can then query elements provided by your sensor using methods {@link #allIssues()}, ...
  101. */
  102. public class SensorContextTester implements SensorContext {
  103. private MapSettings settings;
  104. private DefaultFileSystem fs;
  105. private ActiveRules activeRules;
  106. private InMemorySensorStorage sensorStorage;
  107. private DefaultInputProject project;
  108. private DefaultInputModule module;
  109. private SonarRuntime runtime;
  110. private boolean cancelled;
  111. private SensorContextTester(Path moduleBaseDir) {
  112. this.settings = new MapSettings();
  113. this.fs = new DefaultFileSystem(moduleBaseDir).setEncoding(Charset.defaultCharset());
  114. this.activeRules = new ActiveRulesBuilder().build();
  115. this.sensorStorage = new InMemorySensorStorage();
  116. this.project = new DefaultInputProject(ProjectDefinition.create().setKey("projectKey").setBaseDir(moduleBaseDir.toFile()).setWorkDir(moduleBaseDir.resolve(".sonar").toFile()));
  117. this.module = new DefaultInputModule(ProjectDefinition.create().setKey("projectKey").setBaseDir(moduleBaseDir.toFile()).setWorkDir(moduleBaseDir.resolve(".sonar").toFile()));
  118. this.runtime = SonarRuntimeImpl.forSonarQube(MetadataLoader.loadVersion(System2.INSTANCE), SonarQubeSide.SCANNER, MetadataLoader.loadEdition(System2.INSTANCE));
  119. }
  120. public static SensorContextTester create(File moduleBaseDir) {
  121. return new SensorContextTester(moduleBaseDir.toPath());
  122. }
  123. public static SensorContextTester create(Path moduleBaseDir) {
  124. return new SensorContextTester(moduleBaseDir);
  125. }
  126. public MapSettings settings() {
  127. return settings;
  128. }
  129. @Override
  130. public Configuration config() {
  131. return new ConfigurationBridge(settings);
  132. }
  133. public SensorContextTester setSettings(MapSettings settings) {
  134. this.settings = settings;
  135. return this;
  136. }
  137. @Override
  138. public DefaultFileSystem fileSystem() {
  139. return fs;
  140. }
  141. public SensorContextTester setFileSystem(DefaultFileSystem fs) {
  142. this.fs = fs;
  143. return this;
  144. }
  145. @Override
  146. public ActiveRules activeRules() {
  147. return activeRules;
  148. }
  149. public SensorContextTester setActiveRules(ActiveRules activeRules) {
  150. this.activeRules = activeRules;
  151. return this;
  152. }
  153. /**
  154. * Default value is the version of this API at compilation time. You can override it
  155. * using {@link #setRuntime(SonarRuntime)} to test your Sensor behaviour.
  156. */
  157. @Override
  158. public Version getSonarQubeVersion() {
  159. return runtime().getApiVersion();
  160. }
  161. /**
  162. * @see #setRuntime(SonarRuntime) to override defaults (SonarQube scanner with version
  163. * of this API as used at compilation time).
  164. */
  165. @Override
  166. public SonarRuntime runtime() {
  167. return runtime;
  168. }
  169. public SensorContextTester setRuntime(SonarRuntime runtime) {
  170. this.runtime = runtime;
  171. return this;
  172. }
  173. @Override
  174. public boolean isCancelled() {
  175. return cancelled;
  176. }
  177. public void setCancelled(boolean cancelled) {
  178. this.cancelled = cancelled;
  179. }
  180. @Override
  181. public InputModule module() {
  182. return module;
  183. }
  184. @Override
  185. public InputProject project() {
  186. return project;
  187. }
  188. @Override
  189. public <G extends Serializable> NewMeasure<G> newMeasure() {
  190. return new DefaultMeasure<>(sensorStorage);
  191. }
  192. public Collection<Measure> measures(String componentKey) {
  193. return sensorStorage.measuresByComponentAndMetric.getOrDefault(componentKey, Collections.emptyMap()).values();
  194. }
  195. public <G extends Serializable> Measure<G> measure(String componentKey, Metric<G> metric) {
  196. return measure(componentKey, metric.key());
  197. }
  198. public <G extends Serializable> Measure<G> measure(String componentKey, String metricKey) {
  199. return sensorStorage.measuresByComponentAndMetric.getOrDefault(componentKey, Collections.emptyMap()).get(metricKey);
  200. }
  201. @Override
  202. public NewIssue newIssue() {
  203. return new DefaultIssue(project, sensorStorage);
  204. }
  205. public Collection<Issue> allIssues() {
  206. return sensorStorage.allIssues;
  207. }
  208. @Override
  209. public NewExternalIssue newExternalIssue() {
  210. return new DefaultExternalIssue(project, sensorStorage);
  211. }
  212. @Override
  213. public NewAdHocRule newAdHocRule() {
  214. return new DefaultAdHocRule(sensorStorage);
  215. }
  216. public Collection<ExternalIssue> allExternalIssues() {
  217. return sensorStorage.allExternalIssues;
  218. }
  219. public Collection<AdHocRule> allAdHocRules() {
  220. return sensorStorage.allAdHocRules;
  221. }
  222. public Collection<AnalysisError> allAnalysisErrors() {
  223. return sensorStorage.allAnalysisErrors;
  224. }
  225. @CheckForNull
  226. public Integer lineHits(String fileKey, int line) {
  227. return sensorStorage.coverageByComponent.getOrDefault(fileKey, Collections.emptyList()).stream()
  228. .map(c -> c.hitsByLine().get(line))
  229. .flatMap(Stream::of)
  230. .filter(Objects::nonNull)
  231. .reduce(null, SensorContextTester::sumOrNull);
  232. }
  233. @CheckForNull
  234. public static Integer sumOrNull(@Nullable Integer o1, @Nullable Integer o2) {
  235. return o1 == null ? o2 : (o1 + o2);
  236. }
  237. @CheckForNull
  238. public Integer conditions(String fileKey, int line) {
  239. return sensorStorage.coverageByComponent.getOrDefault(fileKey, Collections.emptyList()).stream()
  240. .map(c -> c.conditionsByLine().get(line))
  241. .flatMap(Stream::of)
  242. .filter(Objects::nonNull)
  243. .reduce(null, SensorContextTester::maxOrNull);
  244. }
  245. @CheckForNull
  246. public Integer coveredConditions(String fileKey, int line) {
  247. return sensorStorage.coverageByComponent.getOrDefault(fileKey, Collections.emptyList()).stream()
  248. .map(c -> c.coveredConditionsByLine().get(line))
  249. .flatMap(Stream::of)
  250. .filter(Objects::nonNull)
  251. .reduce(null, SensorContextTester::maxOrNull);
  252. }
  253. @CheckForNull
  254. public TextRange significantCodeTextRange(String fileKey, int line) {
  255. if (sensorStorage.significantCodePerComponent.containsKey(fileKey)) {
  256. return sensorStorage.significantCodePerComponent.get(fileKey)
  257. .significantCodePerLine()
  258. .get(line);
  259. }
  260. return null;
  261. }
  262. @CheckForNull
  263. public static Integer maxOrNull(@Nullable Integer o1, @Nullable Integer o2) {
  264. return o1 == null ? o2 : Math.max(o1, o2);
  265. }
  266. @CheckForNull
  267. public List<TokensLine> cpdTokens(String componentKey) {
  268. DefaultCpdTokens defaultCpdTokens = sensorStorage.cpdTokensByComponent.get(componentKey);
  269. return defaultCpdTokens != null ? defaultCpdTokens.getTokenLines() : null;
  270. }
  271. @Override
  272. public NewHighlighting newHighlighting() {
  273. return new DefaultHighlighting(sensorStorage);
  274. }
  275. @Override
  276. public NewCoverage newCoverage() {
  277. return new DefaultCoverage(sensorStorage);
  278. }
  279. @Override
  280. public NewCpdTokens newCpdTokens() {
  281. return new DefaultCpdTokens(sensorStorage);
  282. }
  283. @Override
  284. public NewSymbolTable newSymbolTable() {
  285. return new DefaultSymbolTable(sensorStorage);
  286. }
  287. @Override
  288. public NewAnalysisError newAnalysisError() {
  289. return new DefaultAnalysisError(sensorStorage);
  290. }
  291. /**
  292. * Return list of syntax highlighting applied for a given position in a file. The result is a list because in theory you
  293. * can apply several styles to the same range.
  294. *
  295. * @param componentKey Key of the file like 'myProjectKey:src/foo.php'
  296. * @param line Line you want to query
  297. * @param lineOffset Offset you want to query.
  298. * @return List of styles applied to this position or empty list if there is no highlighting at this position.
  299. */
  300. public List<TypeOfText> highlightingTypeAt(String componentKey, int line, int lineOffset) {
  301. DefaultHighlighting syntaxHighlightingData = (DefaultHighlighting) sensorStorage.highlightingByComponent.get(componentKey);
  302. if (syntaxHighlightingData == null) {
  303. return Collections.emptyList();
  304. }
  305. List<TypeOfText> result = new ArrayList<>();
  306. DefaultTextPointer location = new DefaultTextPointer(line, lineOffset);
  307. for (SyntaxHighlightingRule sortedRule : syntaxHighlightingData.getSyntaxHighlightingRuleSet()) {
  308. if (sortedRule.range().start().compareTo(location) <= 0 && sortedRule.range().end().compareTo(location) > 0) {
  309. result.add(sortedRule.getTextType());
  310. }
  311. }
  312. return result;
  313. }
  314. /**
  315. * Return list of symbol references ranges for the symbol at a given position in a file.
  316. *
  317. * @param componentKey Key of the file like 'myProjectKey:src/foo.php'
  318. * @param line Line you want to query
  319. * @param lineOffset Offset you want to query.
  320. * @return List of references for the symbol (potentially empty) or null if there is no symbol at this position.
  321. */
  322. @CheckForNull
  323. public Collection<TextRange> referencesForSymbolAt(String componentKey, int line, int lineOffset) {
  324. DefaultSymbolTable symbolTable = sensorStorage.symbolsPerComponent.get(componentKey);
  325. if (symbolTable == null) {
  326. return null;
  327. }
  328. DefaultTextPointer location = new DefaultTextPointer(line, lineOffset);
  329. for (Map.Entry<TextRange, Set<TextRange>> symbol : symbolTable.getReferencesBySymbol().entrySet()) {
  330. if (symbol.getKey().start().compareTo(location) <= 0 && symbol.getKey().end().compareTo(location) > 0) {
  331. return symbol.getValue();
  332. }
  333. }
  334. return null;
  335. }
  336. @Override
  337. public void addContextProperty(String key, String value) {
  338. sensorStorage.storeProperty(key, value);
  339. }
  340. /**
  341. * @return an immutable map of the context properties defined with {@link SensorContext#addContextProperty(String, String)}.
  342. * @since 6.1
  343. */
  344. public Map<String, String> getContextProperties() {
  345. return unmodifiableMap(sensorStorage.contextProperties);
  346. }
  347. @Override
  348. public void markForPublishing(InputFile inputFile) {
  349. DefaultInputFile file = (DefaultInputFile) inputFile;
  350. file.setPublished(true);
  351. }
  352. @Override
  353. public NewSignificantCode newSignificantCode() {
  354. return new DefaultSignificantCode(sensorStorage);
  355. }
  356. }