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 13KB

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