diff options
author | Julien HENRY <julien.henry@sonarsource.com> | 2019-02-21 15:42:14 +0100 |
---|---|---|
committer | SonarTech <sonartech@sonarsource.com> | 2019-02-21 20:21:18 +0100 |
commit | 857c27b744321ddbdd7dbc12e761ee11b83e6288 (patch) | |
tree | 4eae0535df1e1a438c3cb727cc030c8cecaf1274 /sonar-scanner-engine/src | |
parent | c193b6d4082eea8bb8a96096456dd4183c2e4569 (diff) | |
download | sonarqube-857c27b744321ddbdd7dbc12e761ee11b83e6288.tar.gz sonarqube-857c27b744321ddbdd7dbc12e761ee11b83e6288.zip |
SONAR-11670 Drop preview mode
Diffstat (limited to 'sonar-scanner-engine/src')
82 files changed, 182 insertions, 4952 deletions
diff --git a/sonar-scanner-engine/src/main/java/org/sonar/scanner/analysis/DefaultAnalysisMode.java b/sonar-scanner-engine/src/main/java/org/sonar/scanner/analysis/DefaultAnalysisMode.java index abfc2727df2..6193b261436 100644 --- a/sonar-scanner-engine/src/main/java/org/sonar/scanner/analysis/DefaultAnalysisMode.java +++ b/sonar-scanner-engine/src/main/java/org/sonar/scanner/analysis/DefaultAnalysisMode.java @@ -19,58 +19,24 @@ */ package org.sonar.scanner.analysis; -import java.util.Map; import javax.annotation.concurrent.Immutable; import org.sonar.api.batch.AnalysisMode; -import org.sonar.api.utils.log.Logger; -import org.sonar.api.utils.log.Loggers; -import org.sonar.scanner.bootstrap.GlobalAnalysisMode; -import org.sonar.scanner.bootstrap.ProcessedScannerProperties; @Immutable public class DefaultAnalysisMode implements AnalysisMode { - private static final Logger LOG = Loggers.get(DefaultAnalysisMode.class); - private static final String KEY_SCAN_ALL = "sonar.scanAllFiles"; - - private final Map<String, String> analysisProps; - private final GlobalAnalysisMode analysisMode; - - private boolean scanAllFiles; - - public DefaultAnalysisMode(ProcessedScannerProperties props, GlobalAnalysisMode analysisMode) { - this.analysisMode = analysisMode; - this.analysisProps = props.properties(); - load(); - printFlags(); - } - - public boolean scanAllFiles() { - return scanAllFiles; - } - - private void printFlags() { - if (!scanAllFiles) { - LOG.info("Scanning only changed files"); - } - } - - private void load() { - String scanAllStr = analysisProps.get(KEY_SCAN_ALL); - scanAllFiles = !analysisMode.isIssues() || "true".equals(scanAllStr); - } @Override public boolean isPreview() { - return analysisMode.isPreview(); + return false; } @Override public boolean isIssues() { - return analysisMode.isIssues(); + return false; } @Override public boolean isPublish() { - return analysisMode.isPublish(); + return true; } } diff --git a/sonar-scanner-engine/src/main/java/org/sonar/scanner/bootstrap/BatchComponents.java b/sonar-scanner-engine/src/main/java/org/sonar/scanner/bootstrap/BatchComponents.java index e9005b92353..479304d2587 100644 --- a/sonar-scanner-engine/src/main/java/org/sonar/scanner/bootstrap/BatchComponents.java +++ b/sonar-scanner-engine/src/main/java/org/sonar/scanner/bootstrap/BatchComponents.java @@ -24,14 +24,10 @@ import java.util.Collection; import java.util.List; import org.sonar.core.component.DefaultResourceTypes; import org.sonar.core.config.CorePropertyDefinitions; -import org.sonar.core.issue.tracking.Tracker; import org.sonar.scanner.cpd.JavaCpdBlockIndexerSensor; import org.sonar.scanner.externalissue.ExternalIssuesImportSensor; import org.sonar.scanner.genericcoverage.GenericCoverageSensor; import org.sonar.scanner.genericcoverage.GenericTestExecutionSensor; -import org.sonar.scanner.issue.tracking.ServerIssueFromWs; -import org.sonar.scanner.issue.tracking.TrackedIssue; -import org.sonar.scanner.scan.report.JSONReport; import org.sonar.scanner.source.ZeroCoverageSensor; public class BatchComponents { @@ -39,29 +35,23 @@ public class BatchComponents { // only static stuff } - public static Collection<Object> all(GlobalAnalysisMode analysisMode) { + public static Collection<Object> all() { List<Object> components = Lists.newArrayList( DefaultResourceTypes.get()); components.addAll(CorePropertyDefinitions.all()); - if (!analysisMode.isIssues()) { - components.add(ZeroCoverageSensor.class); - components.add(JavaCpdBlockIndexerSensor.class); + components.add(ZeroCoverageSensor.class); + components.add(JavaCpdBlockIndexerSensor.class); - // Generic coverage - components.add(GenericCoverageSensor.class); - components.addAll(GenericCoverageSensor.properties()); - components.add(GenericTestExecutionSensor.class); - components.addAll(GenericTestExecutionSensor.properties()); + // Generic coverage + components.add(GenericCoverageSensor.class); + components.addAll(GenericCoverageSensor.properties()); + components.add(GenericTestExecutionSensor.class); + components.addAll(GenericTestExecutionSensor.properties()); - // External issues - components.add(ExternalIssuesImportSensor.class); - components.add(ExternalIssuesImportSensor.properties()); + // External issues + components.add(ExternalIssuesImportSensor.class); + components.add(ExternalIssuesImportSensor.properties()); - } else { - // Issues tracking - components.add(new Tracker<TrackedIssue, ServerIssueFromWs>()); - components.add(JSONReport.class); - } return components; } } diff --git a/sonar-scanner-engine/src/main/java/org/sonar/scanner/bootstrap/ExtensionInstaller.java b/sonar-scanner-engine/src/main/java/org/sonar/scanner/bootstrap/ExtensionInstaller.java index 9be1dfa5013..cf39ff12cdf 100644 --- a/sonar-scanner-engine/src/main/java/org/sonar/scanner/bootstrap/ExtensionInstaller.java +++ b/sonar-scanner-engine/src/main/java/org/sonar/scanner/bootstrap/ExtensionInstaller.java @@ -34,21 +34,18 @@ public class ExtensionInstaller { private final SonarRuntime sonarRuntime; private final PluginRepository pluginRepository; - private final GlobalAnalysisMode analysisMode; private final Configuration bootConfiguration; - public ExtensionInstaller(SonarRuntime sonarRuntime, PluginRepository pluginRepository, GlobalAnalysisMode analysisMode, - Configuration bootConfiguration) { + public ExtensionInstaller(SonarRuntime sonarRuntime, PluginRepository pluginRepository, Configuration bootConfiguration) { this.sonarRuntime = sonarRuntime; this.pluginRepository = pluginRepository; - this.analysisMode = analysisMode; this.bootConfiguration = bootConfiguration; } public ExtensionInstaller install(ComponentContainer container, ExtensionMatcher matcher) { // core components - for (Object o : BatchComponents.all(analysisMode)) { + for (Object o : BatchComponents.all()) { doInstall(container, matcher, null, o); } diff --git a/sonar-scanner-engine/src/main/java/org/sonar/scanner/bootstrap/GlobalAnalysisMode.java b/sonar-scanner-engine/src/main/java/org/sonar/scanner/bootstrap/GlobalAnalysisMode.java index 26aced1fb60..ca3947de2d3 100644 --- a/sonar-scanner-engine/src/main/java/org/sonar/scanner/bootstrap/GlobalAnalysisMode.java +++ b/sonar-scanner-engine/src/main/java/org/sonar/scanner/bootstrap/GlobalAnalysisMode.java @@ -19,64 +19,25 @@ */ package org.sonar.scanner.bootstrap; -import java.util.Arrays; import javax.annotation.concurrent.Immutable; -import org.apache.commons.lang.StringUtils; import org.slf4j.Logger; import org.slf4j.LoggerFactory; -import org.sonar.api.CoreProperties; @Immutable public class GlobalAnalysisMode { public static final String MEDIUM_TEST_ENABLED = "sonar.mediumTest.enabled"; private static final Logger LOG = LoggerFactory.getLogger(GlobalAnalysisMode.class); - private static final String[] VALID_MODES = {CoreProperties.ANALYSIS_MODE_PREVIEW, CoreProperties.ANALYSIS_MODE_PUBLISH, CoreProperties.ANALYSIS_MODE_ISSUES}; - protected boolean preview; - protected boolean issues; protected boolean mediumTestMode; public GlobalAnalysisMode(RawScannerProperties props) { - String mode = props.property(CoreProperties.ANALYSIS_MODE); - validate(mode); - issues = CoreProperties.ANALYSIS_MODE_ISSUES.equals(mode) || CoreProperties.ANALYSIS_MODE_PREVIEW.equals(mode); mediumTestMode = "true".equals(props.property(MEDIUM_TEST_ENABLED)); - if (preview) { - LOG.info("Preview mode"); - LOG.warn("The use of the preview mode (sonar.analysis.mode=preview) is deprecated. This mode will be dropped in the future."); - } else if (issues) { - LOG.info("Issues mode"); - LOG.warn("The use of the issues mode (sonar.analysis.mode=issues) is deprecated. This mode will be dropped in the future."); - } if (mediumTestMode) { LOG.info("Medium test mode"); } } - public boolean isPreview() { - return preview; - } - - public boolean isIssues() { - return issues; - } - - public boolean isPublish() { - return !preview && !issues; - } - public boolean isMediumTest() { return mediumTestMode; } - - protected static void validate(String mode) { - if (StringUtils.isEmpty(mode)) { - return; - } - - if (!Arrays.asList(VALID_MODES).contains(mode)) { - throw new IllegalStateException("Invalid analysis mode: " + mode + "."); - } - - } } diff --git a/sonar-scanner-engine/src/main/java/org/sonar/scanner/bootstrap/GlobalContainer.java b/sonar-scanner-engine/src/main/java/org/sonar/scanner/bootstrap/GlobalContainer.java index 4211ab99cfe..4857692b80c 100644 --- a/sonar-scanner-engine/src/main/java/org/sonar/scanner/bootstrap/GlobalContainer.java +++ b/sonar-scanner-engine/src/main/java/org/sonar/scanner/bootstrap/GlobalContainer.java @@ -86,7 +86,6 @@ public class GlobalContainer extends ComponentContainer { PluginLoader.class, PluginClassloaderFactory.class, ScannerPluginJarExploder.class, - ScannerPluginPredicate.class, ExtensionInstaller.class, new SonarQubeVersion(apiVersion), @@ -123,6 +122,11 @@ public class GlobalContainer extends ComponentContainer { } else if (!taskKey.equals(CoreProperties.SCAN_TASK)) { throw MessageException.of("Tasks support was removed in SonarQube 7.6."); } + String analysisMode = StringUtils.defaultIfEmpty(scannerProperties.get("sonar.analysis.mode"), "publish"); + if (!analysisMode.equals("publish")) { + throw MessageException.of("The preview mode, along with the 'sonar.analysis.mode' parameter, is no more supported. You should stop using this parameter."); + } + new ProjectScanContainer(this).execute(); LOG.info("Analysis total time: {}", formatTime(System.currentTimeMillis() - startTime)); diff --git a/sonar-scanner-engine/src/main/java/org/sonar/scanner/bootstrap/ScannerPluginInstaller.java b/sonar-scanner-engine/src/main/java/org/sonar/scanner/bootstrap/ScannerPluginInstaller.java index 13d0c2bcdfa..db02b02d440 100644 --- a/sonar-scanner-engine/src/main/java/org/sonar/scanner/bootstrap/ScannerPluginInstaller.java +++ b/sonar-scanner-engine/src/main/java/org/sonar/scanner/bootstrap/ScannerPluginInstaller.java @@ -45,12 +45,10 @@ public class ScannerPluginInstaller implements PluginInstaller { private static final String PLUGINS_WS_URL = "api/plugins/installed"; private final PluginFiles pluginFiles; - private final ScannerPluginPredicate pluginPredicate; private final ScannerWsClient wsClient; - public ScannerPluginInstaller(PluginFiles pluginFiles, ScannerPluginPredicate pluginPredicate, ScannerWsClient wsClient) { + public ScannerPluginInstaller(PluginFiles pluginFiles, ScannerWsClient wsClient) { this.pluginFiles = pluginFiles; - this.pluginPredicate = pluginPredicate; this.wsClient = wsClient; } @@ -76,15 +74,13 @@ public class ScannerPluginInstaller implements PluginInstaller { private Loaded loadPlugins(Map<String, ScannerPlugin> result) { for (InstalledPlugin plugin : listInstalledPlugins()) { - if (pluginPredicate.apply(plugin.key)) { - Optional<File> jarFile = pluginFiles.get(plugin); - if (!jarFile.isPresent()) { - return new Loaded(false, plugin.key); - } - - PluginInfo info = PluginInfo.create(jarFile.get()); - result.put(info.getKey(), new ScannerPlugin(plugin.key, plugin.updatedAt, info)); + Optional<File> jarFile = pluginFiles.get(plugin); + if (!jarFile.isPresent()) { + return new Loaded(false, plugin.key); } + + PluginInfo info = PluginInfo.create(jarFile.get()); + result.put(info.getKey(), new ScannerPlugin(plugin.key, plugin.updatedAt, info)); } return new Loaded(true, null); } diff --git a/sonar-scanner-engine/src/main/java/org/sonar/scanner/bootstrap/ScannerPluginPredicate.java b/sonar-scanner-engine/src/main/java/org/sonar/scanner/bootstrap/ScannerPluginPredicate.java deleted file mode 100644 index 70b918071c1..00000000000 --- a/sonar-scanner-engine/src/main/java/org/sonar/scanner/bootstrap/ScannerPluginPredicate.java +++ /dev/null @@ -1,94 +0,0 @@ -/* - * SonarQube - * Copyright (C) 2009-2019 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.scanner.bootstrap; - -import com.google.common.base.Joiner; -import com.google.common.base.Predicate; -import com.google.common.base.Splitter; -import java.util.HashSet; -import java.util.List; -import java.util.Set; -import java.util.stream.Collectors; -import java.util.stream.StreamSupport; -import javax.annotation.Nonnull; -import org.sonar.api.CoreProperties; -import org.sonar.api.config.Configuration; -import org.sonar.api.utils.log.Logger; -import org.sonar.api.utils.log.Loggers; - -/** - * Filters the plugins to be enabled during analysis - */ -public class ScannerPluginPredicate implements Predicate<String> { - - private static final Logger LOG = Loggers.get(ScannerPluginPredicate.class); - - private static final String BUILDBREAKER_PLUGIN_KEY = "buildbreaker"; - private static final Joiner COMMA_JOINER = Joiner.on(", "); - - private final Set<String> whites = new HashSet<>(); - private final Set<String> blacks = new HashSet<>(); - private final GlobalAnalysisMode mode; - - public ScannerPluginPredicate(Configuration settings, GlobalAnalysisMode mode) { - this.mode = mode; - if (mode.isPreview() || mode.isIssues()) { - // These default values are not supported by Settings because the class CorePlugin - // is not loaded yet. - whites.addAll(propertyValues(settings, - CoreProperties.PREVIEW_INCLUDE_PLUGINS, CoreProperties.PREVIEW_INCLUDE_PLUGINS_DEFAULT_VALUE)); - blacks.addAll(propertyValues(settings, - CoreProperties.PREVIEW_EXCLUDE_PLUGINS, CoreProperties.PREVIEW_EXCLUDE_PLUGINS_DEFAULT_VALUE)); - } - if (!whites.isEmpty()) { - LOG.info("Include plugins: " + COMMA_JOINER.join(whites)); - } - if (!blacks.isEmpty()) { - LOG.info("Exclude plugins: " + COMMA_JOINER.join(blacks)); - } - } - - @Override - public boolean apply(@Nonnull String pluginKey) { - if (BUILDBREAKER_PLUGIN_KEY.equals(pluginKey) && mode.isPreview()) { - LOG.info("Build Breaker plugin is no more supported in preview mode"); - return false; - } - - if (whites.isEmpty()) { - return blacks.isEmpty() || !blacks.contains(pluginKey); - } - return whites.contains(pluginKey); - } - - Set<String> getWhites() { - return whites; - } - - Set<String> getBlacks() { - return blacks; - } - - private static List<String> propertyValues(Configuration settings, String key, String defaultValue) { - String s = settings.get(key).orElse(defaultValue); - return StreamSupport.stream(Splitter.on(",").trimResults().omitEmptyStrings().split(s).spliterator(), false) - .collect(Collectors.toList()); - } -} diff --git a/sonar-scanner-engine/src/main/java/org/sonar/scanner/issue/DefaultProjectIssues.java b/sonar-scanner-engine/src/main/java/org/sonar/scanner/issue/DefaultProjectIssues.java deleted file mode 100644 index 3de2f036b42..00000000000 --- a/sonar-scanner-engine/src/main/java/org/sonar/scanner/issue/DefaultProjectIssues.java +++ /dev/null @@ -1,74 +0,0 @@ -/* - * SonarQube - * Copyright (C) 2009-2019 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.scanner.issue; - -import java.util.function.Predicate; -import java.util.stream.Collectors; -import java.util.stream.StreamSupport; -import javax.annotation.Nullable; -import org.sonar.api.issue.Issue; -import org.sonar.api.issue.ProjectIssues; -import org.sonar.scanner.issue.tracking.TrackedIssue; - -/** - * Expose list of issues for the current project - * @since 4.0 - */ -public class DefaultProjectIssues implements ProjectIssues { - private static final Predicate<TrackedIssue> RESOLVED = new ResolvedPredicate(true); - private static final Predicate<TrackedIssue> NOT_RESOLVED = new ResolvedPredicate(false); - private final IssueCache cache; - - public DefaultProjectIssues(IssueCache cache) { - this.cache = cache; - } - - @Override - public Iterable<Issue> issues() { - return StreamSupport.stream(cache.all().spliterator(), false) - .filter(NOT_RESOLVED) - .map(TrackedIssueAdapter::new) - .collect(Collectors.toList()); - } - - @Override - public Iterable<Issue> resolvedIssues() { - return StreamSupport.stream(cache.all().spliterator(), false) - .filter(RESOLVED) - .map(TrackedIssueAdapter::new) - .collect(Collectors.toList()); - } - - private static class ResolvedPredicate implements Predicate<TrackedIssue> { - private final boolean resolved; - - private ResolvedPredicate(boolean resolved) { - this.resolved = resolved; - } - - @Override - public boolean test(@Nullable TrackedIssue issue) { - if (issue != null) { - return resolved ? (issue.resolution() != null) : (issue.resolution() == null); - } - return false; - } - } -} diff --git a/sonar-scanner-engine/src/main/java/org/sonar/scanner/issue/IssueCache.java b/sonar-scanner-engine/src/main/java/org/sonar/scanner/issue/IssueCache.java deleted file mode 100644 index 8ff0a0f5526..00000000000 --- a/sonar-scanner-engine/src/main/java/org/sonar/scanner/issue/IssueCache.java +++ /dev/null @@ -1,59 +0,0 @@ -/* - * SonarQube - * Copyright (C) 2009-2019 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.scanner.issue; - -import java.util.Collection; -import org.sonar.scanner.issue.tracking.TrackedIssue; -import org.sonar.scanner.storage.Storage; -import org.sonar.scanner.storage.Storages; - -/** - * Shared issues among all project modules - */ -public class IssueCache { - - // component key -> issue key -> issue - private final Storage<TrackedIssue> cache; - - public IssueCache(Storages caches) { - cache = caches.createCache("issues"); - } - - public Iterable<TrackedIssue> byComponent(String componentKey) { - return cache.values(componentKey); - } - - public Iterable<TrackedIssue> all() { - return cache.values(); - } - - public Collection<Object> componentKeys() { - return cache.keySet(); - } - - public IssueCache put(TrackedIssue issue) { - cache.put(issue.componentKey(), issue.key(), issue); - return this; - } - - public void clear(String componentKey) { - cache.clear(componentKey); - } -} diff --git a/sonar-scanner-engine/src/main/java/org/sonar/scanner/issue/IssueTransformer.java b/sonar-scanner-engine/src/main/java/org/sonar/scanner/issue/IssueTransformer.java deleted file mode 100644 index 2d2a1cf61b9..00000000000 --- a/sonar-scanner-engine/src/main/java/org/sonar/scanner/issue/IssueTransformer.java +++ /dev/null @@ -1,116 +0,0 @@ -/* - * SonarQube - * Copyright (C) 2009-2019 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.scanner.issue; - -import com.google.common.base.Preconditions; -import java.util.ArrayList; -import java.util.Collection; -import java.util.Date; -import java.util.List; -import javax.annotation.Nullable; -import org.apache.commons.lang.StringUtils; -import org.sonar.api.batch.fs.InputComponent; -import org.sonar.api.issue.Issue; -import org.sonar.api.rule.RuleKey; -import org.sonar.core.util.Uuids; -import org.sonar.scanner.issue.tracking.SourceHashHolder; -import org.sonar.scanner.issue.tracking.TrackedIssue; -import org.sonar.scanner.protocol.input.ScannerInput.ServerIssue; -import org.sonar.scanner.protocol.output.ScannerReport; -import org.sonar.scanner.protocol.output.ScannerReport.TextRange; - -public class IssueTransformer { - private IssueTransformer() { - // static only - } - - public static TrackedIssue toTrackedIssue(ServerIssue serverIssue, String componentKey) { - TrackedIssue issue = new TrackedIssue(); - issue.setKey(serverIssue.getKey()); - issue.setStatus(serverIssue.getStatus()); - issue.setResolution(serverIssue.hasResolution() ? serverIssue.getResolution() : null); - issue.setMessage(serverIssue.hasMsg() ? serverIssue.getMsg() : null); - issue.setStartLine(serverIssue.hasLine() ? serverIssue.getLine() : null); - issue.setEndLine(serverIssue.hasLine() ? serverIssue.getLine() : null); - issue.setSeverity(serverIssue.getSeverity().name()); - issue.setAssignee(serverIssue.hasAssigneeLogin() ? serverIssue.getAssigneeLogin() : null); - // key in serverIssue might have branch, so don't use it - issue.setComponentKey(componentKey); - issue.setCreationDate(new Date(serverIssue.getCreationDate())); - issue.setRuleKey(RuleKey.of(serverIssue.getRuleRepository(), serverIssue.getRuleKey())); - issue.setNew(false); - return issue; - } - - public static void close(TrackedIssue issue) { - issue.setStatus(Issue.STATUS_CLOSED); - issue.setStartLine(null); - issue.setEndLine(null); - issue.setResolution(Issue.RESOLUTION_FIXED); - } - - public static void resolveRemove(TrackedIssue issue) { - issue.setStatus(Issue.STATUS_CLOSED); - issue.setStartLine(null); - issue.setEndLine(null); - issue.setResolution(Issue.RESOLUTION_REMOVED); - } - - public static Collection<TrackedIssue> toTrackedIssue(InputComponent component, Collection<ScannerReport.Issue> rawIssues, @Nullable SourceHashHolder hashes) { - List<TrackedIssue> issues = new ArrayList<>(rawIssues.size()); - - for (ScannerReport.Issue issue : rawIssues) { - issues.add(toTrackedIssue(component, issue, hashes)); - } - - return issues; - } - - public static TrackedIssue toTrackedIssue(InputComponent component, ScannerReport.Issue rawIssue, @Nullable SourceHashHolder hashes) { - RuleKey ruleKey = RuleKey.of(rawIssue.getRuleRepository(), rawIssue.getRuleKey()); - - Preconditions.checkNotNull(component.key(), "Component key must be set"); - Preconditions.checkNotNull(ruleKey, "Rule key must be set"); - - TrackedIssue issue = new TrackedIssue(hashes != null ? hashes.getHashedSource() : null); - - issue.setKey(Uuids.createFast()); - issue.setComponentKey(component.key()); - issue.setRuleKey(ruleKey); - issue.setGap(rawIssue.getGap() != 0 ? rawIssue.getGap() : null); - issue.setSeverity(rawIssue.getSeverity().name()); - issue.setMessage(StringUtils.trimToNull(rawIssue.getMsg())); - issue.setResolution(null); - issue.setStatus(Issue.STATUS_OPEN); - issue.setNew(true); - - if (rawIssue.hasTextRange()) { - TextRange r = rawIssue.getTextRange(); - - issue.setStartLine(r.getStartLine()); - issue.setStartLineOffset(r.getStartOffset()); - issue.setEndLine(r.getEndLine()); - issue.setEndLineOffset(r.getEndOffset()); - } - - return issue; - } - -} diff --git a/sonar-scanner-engine/src/main/java/org/sonar/scanner/issue/TrackedIssueAdapter.java b/sonar-scanner-engine/src/main/java/org/sonar/scanner/issue/TrackedIssueAdapter.java deleted file mode 100644 index d93ebb7c341..00000000000 --- a/sonar-scanner-engine/src/main/java/org/sonar/scanner/issue/TrackedIssueAdapter.java +++ /dev/null @@ -1,179 +0,0 @@ -/* - * SonarQube - * Copyright (C) 2009-2019 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.scanner.issue; - -import java.util.ArrayList; -import java.util.Collection; -import java.util.Date; -import java.util.HashMap; -import java.util.List; -import java.util.Map; -import org.sonar.api.issue.Issue; -import org.sonar.api.issue.IssueComment; -import org.sonar.api.rule.RuleKey; -import org.sonar.api.utils.Duration; -import org.sonar.scanner.issue.tracking.TrackedIssue; - -public class TrackedIssueAdapter implements Issue { - private TrackedIssue issue; - - public TrackedIssueAdapter(TrackedIssue issue) { - this.issue = issue; - } - - @Override - public String key() { - return issue.key(); - } - - @Override - public String componentKey() { - return issue.componentKey(); - } - - @Override - public RuleKey ruleKey() { - return issue.getRuleKey(); - } - - @Override - public String severity() { - return issue.severity(); - } - - @Override - public String message() { - return issue.getMessage(); - } - - @Override - public Integer line() { - return issue.startLine(); - } - - @Override - public Double gap() { - return issue.gap(); - } - - @Override - public String status() { - return issue.status(); - } - - @Override - public String resolution() { - return issue.resolution(); - } - - @Override - public String assignee() { - return issue.assignee(); - } - - @Override - public boolean isNew() { - return issue.isNew(); - } - - @Override - public boolean isCopied() { - return false; - } - - @Override - public Map<String, String> attributes() { - return new HashMap<>(); - } - - @Override - public Date creationDate() { - return issue.getCreationDate(); - } - - @Override - public String language() { - return null; - } - - @Override - public Date updateDate() { - return null; - } - - @Override - public Date closeDate() { - return null; - } - - @Override - public String attribute(String key) { - return attributes().get(key); - } - - @Override - public String authorLogin() { - return null; - } - - @Override - public List<IssueComment> comments() { - return new ArrayList<>(); - } - - @Override - public Duration effort() { - return null; - } - - @Override - public String projectKey() { - return null; - } - - @Override - public String projectUuid() { - return null; - } - - @Override - public String componentUuid() { - return null; - } - - @Override - public Collection<String> tags() { - return new ArrayList<>(); - } - - @Override - public boolean equals(Object o) { - if (o == null || !(o instanceof Issue)) { - return false; - } - Issue that = (Issue) o; - return !(issue.key() != null ? !issue.key().equals(that.key()) : (that.key() != null)); - } - - @Override - public int hashCode() { - return issue.key() != null ? issue.key().hashCode() : 0; - } -} diff --git a/sonar-scanner-engine/src/main/java/org/sonar/scanner/issue/tracking/DefaultServerLineHashesLoader.java b/sonar-scanner-engine/src/main/java/org/sonar/scanner/issue/tracking/DefaultServerLineHashesLoader.java deleted file mode 100644 index 45be7dea4e8..00000000000 --- a/sonar-scanner-engine/src/main/java/org/sonar/scanner/issue/tracking/DefaultServerLineHashesLoader.java +++ /dev/null @@ -1,61 +0,0 @@ -/* - * SonarQube - * Copyright (C) 2009-2019 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.scanner.issue.tracking; - -import com.google.common.base.Splitter; -import com.google.common.collect.Iterators; -import java.io.IOException; -import java.io.Reader; -import org.apache.commons.io.IOUtils; -import org.sonar.api.utils.log.Loggers; -import org.sonar.api.utils.log.Profiler; -import org.sonar.scanner.bootstrap.ScannerWsClient; -import org.sonar.scanner.util.ScannerUtils; -import org.sonarqube.ws.client.GetRequest; - -public class DefaultServerLineHashesLoader implements ServerLineHashesLoader { - private ScannerWsClient wsClient; - - public DefaultServerLineHashesLoader(ScannerWsClient wsClient) { - this.wsClient = wsClient; - } - - @Override - public String[] getLineHashes(String fileKey) { - String hashesFromWs = loadHashesFromWs(fileKey); - return Iterators.toArray(Splitter.on('\n').split(hashesFromWs).iterator(), String.class); - } - - private String loadHashesFromWs(String fileKey) { - Profiler profiler = Profiler.createIfDebug(Loggers.get(getClass())) - .addContext("file", fileKey) - .startDebug("Load line hashes"); - - GetRequest getRequest = new GetRequest("/api/sources/hash?key=" + ScannerUtils.encodeForUrl(fileKey)); - Reader reader = wsClient.call(getRequest).contentReader(); - try { - return IOUtils.toString(reader); - } catch (IOException e) { - throw new IllegalStateException(e); - } finally { - profiler.stopDebug(); - } - } -} diff --git a/sonar-scanner-engine/src/main/java/org/sonar/scanner/issue/tracking/FileHashes.java b/sonar-scanner-engine/src/main/java/org/sonar/scanner/issue/tracking/FileHashes.java deleted file mode 100644 index 74263c119b2..00000000000 --- a/sonar-scanner-engine/src/main/java/org/sonar/scanner/issue/tracking/FileHashes.java +++ /dev/null @@ -1,86 +0,0 @@ -/* - * SonarQube - * Copyright (C) 2009-2019 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.scanner.issue.tracking; - -import com.google.common.collect.LinkedHashMultimap; -import com.google.common.collect.Multimap; -import java.util.Collection; -import org.apache.commons.codec.binary.Hex; -import org.apache.commons.lang.ObjectUtils; -import org.sonar.api.batch.fs.InputFile; -import org.sonar.api.batch.fs.internal.FileMetadata; - -/** - * Wraps a {@link Sequence} to assign hash codes to elements. - */ -public final class FileHashes { - - private final String[] hashes; - private final Multimap<String, Integer> linesByHash; - - private FileHashes(String[] hashes, Multimap<String, Integer> linesByHash) { - this.hashes = hashes; - this.linesByHash = linesByHash; - } - - public static FileHashes create(String[] hashes) { - int size = hashes.length; - Multimap<String, Integer> linesByHash = LinkedHashMultimap.create(); - for (int i = 0; i < size; i++) { - // indices in array are shifted one line before - linesByHash.put(hashes[i], i + 1); - } - return new FileHashes(hashes, linesByHash); - } - - public static FileHashes create(InputFile f) { - final byte[][] hashes = new byte[f.lines()][]; - FileMetadata.computeLineHashesForIssueTracking(f, - (lineIdx, hash) -> hashes[lineIdx - 1] = hash); - - int size = hashes.length; - Multimap<String, Integer> linesByHash = LinkedHashMultimap.create(); - String[] hexHashes = new String[size]; - for (int i = 0; i < size; i++) { - String hash = hashes[i] != null ? Hex.encodeHexString(hashes[i]) : ""; - hexHashes[i] = hash; - // indices in array are shifted one line before - linesByHash.put(hash, i + 1); - } - return new FileHashes(hexHashes, linesByHash); - } - - public int length() { - return hashes.length; - } - - public Collection<Integer> getLinesForHash(String hash) { - return linesByHash.get(hash); - } - - public String[] hashes() { - return hashes; - } - - public String getHash(int line) { - // indices in array are shifted one line before - return (String) ObjectUtils.defaultIfNull(hashes[line - 1], ""); - } -} diff --git a/sonar-scanner-engine/src/main/java/org/sonar/scanner/issue/tracking/IssueTrackingInput.java b/sonar-scanner-engine/src/main/java/org/sonar/scanner/issue/tracking/IssueTrackingInput.java deleted file mode 100644 index 34af4d55c56..00000000000 --- a/sonar-scanner-engine/src/main/java/org/sonar/scanner/issue/tracking/IssueTrackingInput.java +++ /dev/null @@ -1,56 +0,0 @@ -/* - * SonarQube - * Copyright (C) 2009-2019 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.scanner.issue.tracking; - -import java.util.Collection; -import java.util.List; -import org.sonar.core.issue.tracking.BlockHashSequence; -import org.sonar.core.issue.tracking.Input; -import org.sonar.core.issue.tracking.LineHashSequence; -import org.sonar.core.issue.tracking.Trackable; - -public class IssueTrackingInput<T extends Trackable> implements Input<T> { - - private final Collection<T> issues; - private final LineHashSequence lineHashes; - private final BlockHashSequence blockHashes; - - public IssueTrackingInput(Collection<T> issues, List<String> hashes) { - this.issues = issues; - this.lineHashes = new LineHashSequence(hashes); - this.blockHashes = BlockHashSequence.create(lineHashes); - } - - @Override - public LineHashSequence getLineHashSequence() { - return lineHashes; - } - - @Override - public BlockHashSequence getBlockHashSequence() { - return blockHashes; - } - - @Override - public Collection<T> getIssues() { - return issues; - } - -} diff --git a/sonar-scanner-engine/src/main/java/org/sonar/scanner/issue/tracking/IssueTransition.java b/sonar-scanner-engine/src/main/java/org/sonar/scanner/issue/tracking/IssueTransition.java deleted file mode 100644 index a111c51f503..00000000000 --- a/sonar-scanner-engine/src/main/java/org/sonar/scanner/issue/tracking/IssueTransition.java +++ /dev/null @@ -1,121 +0,0 @@ -/* - * SonarQube - * Copyright (C) 2009-2019 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.scanner.issue.tracking; - -import java.util.ArrayList; -import java.util.Date; -import java.util.LinkedList; -import java.util.List; -import java.util.concurrent.TimeUnit; -import javax.annotation.Nullable; -import org.sonar.api.batch.fs.InputComponent; -import org.sonar.api.batch.fs.internal.DefaultInputComponent; -import org.sonar.core.util.CloseableIterator; -import org.sonar.scanner.ProjectInfo; -import org.sonar.scanner.issue.IssueCache; -import org.sonar.scanner.issue.IssueTransformer; -import org.sonar.scanner.protocol.output.ScannerReport; -import org.sonar.scanner.protocol.output.ScannerReportReader; -import org.sonar.scanner.report.ReportPublisher; -import org.sonar.scanner.scan.filesystem.InputComponentStore; -import org.sonar.scanner.util.ProgressReport; - -public class IssueTransition { - private final IssueCache issueCache; - private final InputComponentStore inputComponentStore; - private final ReportPublisher reportPublisher; - private final Date analysisDate; - @Nullable - private final LocalIssueTracking localIssueTracking; - - public IssueTransition(InputComponentStore inputComponentCache, ProjectInfo projectInfo, IssueCache issueCache, ReportPublisher reportPublisher, - @Nullable LocalIssueTracking localIssueTracking) { - this.inputComponentStore = inputComponentCache; - this.issueCache = issueCache; - this.reportPublisher = reportPublisher; - this.localIssueTracking = localIssueTracking; - this.analysisDate = projectInfo.getAnalysisDate(); - } - - public IssueTransition(InputComponentStore inputComponentCache, ProjectInfo projectInfo, IssueCache issueCache, ReportPublisher reportPublisher) { - this(inputComponentCache, projectInfo, issueCache, reportPublisher, null); - } - - public void execute() { - if (localIssueTracking != null) { - localIssueTracking.init(); - } - - ScannerReportReader reader = new ScannerReportReader(reportPublisher.getReportDir().toFile()); - int nbComponents = inputComponentStore.all().size(); - - if (nbComponents == 0) { - return; - } - - ProgressReport progressReport = new ProgressReport("issue-tracking-report", TimeUnit.SECONDS.toMillis(10)); - progressReport.start("Performing issue tracking"); - int count = 0; - - try { - for (InputComponent component : inputComponentStore.all()) { - trackIssues(reader, (DefaultInputComponent) component); - count++; - progressReport.message(count + "/" + nbComponents + " components tracked"); - } - } finally { - progressReport.stop(count + "/" + nbComponents + " components tracked"); - } - } - - public void trackIssues(ScannerReportReader reader, DefaultInputComponent component) { - // raw issues = all the issues created by rule engines during this module scan and not excluded by filters - List<ScannerReport.Issue> rawIssues = new LinkedList<>(); - try (CloseableIterator<ScannerReport.Issue> it = reader.readComponentIssues(component.scannerId())) { - while (it.hasNext()) { - rawIssues.add(it.next()); - } - } catch (Exception e) { - throw new IllegalStateException("Can't read issues for " + component.key(), e); - } - - List<TrackedIssue> trackedIssues; - if (localIssueTracking != null) { - trackedIssues = localIssueTracking.trackIssues(component, rawIssues, analysisDate); - } else { - trackedIssues = doTransition(rawIssues, component); - } - - for (TrackedIssue issue : trackedIssues) { - issueCache.put(issue); - } - } - - private static List<TrackedIssue> doTransition(List<ScannerReport.Issue> rawIssues, InputComponent component) { - List<TrackedIssue> issues = new ArrayList<>(rawIssues.size()); - - for (ScannerReport.Issue issue : rawIssues) { - issues.add(IssueTransformer.toTrackedIssue(component, issue, null)); - } - - return issues; - } - -} diff --git a/sonar-scanner-engine/src/main/java/org/sonar/scanner/issue/tracking/LocalIssueTracking.java b/sonar-scanner-engine/src/main/java/org/sonar/scanner/issue/tracking/LocalIssueTracking.java deleted file mode 100644 index 7e496fd478b..00000000000 --- a/sonar-scanner-engine/src/main/java/org/sonar/scanner/issue/tracking/LocalIssueTracking.java +++ /dev/null @@ -1,241 +0,0 @@ -/* - * SonarQube - * Copyright (C) 2009-2019 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.scanner.issue.tracking; - -import com.google.common.annotations.VisibleForTesting; -import com.google.common.base.Preconditions; -import java.util.ArrayList; -import java.util.Arrays; -import java.util.Collection; -import java.util.Date; -import java.util.LinkedList; -import java.util.List; -import java.util.Map; -import java.util.stream.Stream; -import javax.annotation.CheckForNull; -import javax.annotation.Nullable; -import org.sonar.api.batch.fs.InputComponent; -import org.sonar.api.batch.fs.InputFile; -import org.sonar.api.batch.fs.InputFile.Status; -import org.sonar.api.batch.fs.InputModule; -import org.sonar.api.batch.fs.internal.DefaultInputFile; -import org.sonar.api.batch.fs.internal.DefaultInputProject; -import org.sonar.api.batch.rule.ActiveRule; -import org.sonar.api.batch.rule.ActiveRules; -import org.sonar.core.issue.tracking.Input; -import org.sonar.core.issue.tracking.Tracker; -import org.sonar.core.issue.tracking.Tracking; -import org.sonar.scanner.analysis.DefaultAnalysisMode; -import org.sonar.scanner.issue.IssueTransformer; -import org.sonar.scanner.protocol.output.ScannerReport; -import org.sonar.scanner.repository.ProjectRepositories; - -public class LocalIssueTracking { - private final DefaultInputProject project; - private final Tracker<TrackedIssue, ServerIssueFromWs> tracker; - private final ServerLineHashesLoader lastLineHashes; - private final ActiveRules activeRules; - private final ServerIssueRepository serverIssueRepository; - private final DefaultAnalysisMode mode; - - private boolean hasServerAnalysis; - - public LocalIssueTracking(DefaultInputProject project, Tracker<TrackedIssue, ServerIssueFromWs> tracker, ServerLineHashesLoader lastLineHashes, - ActiveRules activeRules, ServerIssueRepository serverIssueRepository, ProjectRepositories projectRepositories, DefaultAnalysisMode mode) { - this.project = project; - this.tracker = tracker; - this.lastLineHashes = lastLineHashes; - this.serverIssueRepository = serverIssueRepository; - this.mode = mode; - this.activeRules = activeRules; - this.hasServerAnalysis = projectRepositories.lastAnalysisDate() != null; - } - - public void init() { - if (hasServerAnalysis) { - serverIssueRepository.load(); - } - } - - public List<TrackedIssue> trackIssues(InputComponent component, Collection<ScannerReport.Issue> reportIssues, Date analysisDate) { - List<TrackedIssue> trackedIssues = new LinkedList<>(); - if (hasServerAnalysis) { - // all the issues that are not closed in db before starting this module scan, including manual issues - Collection<ServerIssueFromWs> serverIssues = loadServerIssues(component); - - if (shouldCopyServerIssues(component)) { - // raw issues should be empty, we just need to deal with server issues (SONAR-6931) - copyServerIssues(serverIssues, trackedIssues, component.key()); - } else { - - SourceHashHolder sourceHashHolder = loadSourceHashes(component); - Collection<TrackedIssue> rIssues = IssueTransformer.toTrackedIssue(component, reportIssues, sourceHashHolder); - - Input<ServerIssueFromWs> baseIssues = createBaseInput(serverIssues, sourceHashHolder); - Input<TrackedIssue> rawIssues = createRawInput(rIssues, sourceHashHolder); - - Tracking<TrackedIssue, ServerIssueFromWs> track = tracker.trackNonClosed(rawIssues, baseIssues); - - addUnmatchedFromServer(track.getUnmatchedBases(), trackedIssues, component.key()); - mergeMatched(track, trackedIssues, rIssues); - addUnmatchedFromReport(track.getUnmatchedRaws(), trackedIssues, analysisDate); - } - } - - if (hasServerAnalysis && !component.isFile()) { - Preconditions.checkState(component instanceof InputModule, "Object without parent is of type: " + component.getClass()); - // issues that relate to deleted components - addIssuesOnDeletedComponents(trackedIssues, component.key()); - } - - return trackedIssues; - } - - private static Input<ServerIssueFromWs> createBaseInput(Collection<ServerIssueFromWs> serverIssues, @Nullable SourceHashHolder sourceHashHolder) { - List<String> refHashes; - - if (sourceHashHolder != null && sourceHashHolder.getHashedReference() != null) { - refHashes = Arrays.asList(sourceHashHolder.getHashedReference().hashes()); - } else { - refHashes = new ArrayList<>(0); - } - - return new IssueTrackingInput<>(serverIssues, refHashes); - } - - private static Input<TrackedIssue> createRawInput(Collection<TrackedIssue> rIssues, @Nullable SourceHashHolder sourceHashHolder) { - List<String> baseHashes; - if (sourceHashHolder != null && sourceHashHolder.getHashedSource() != null) { - baseHashes = Arrays.asList(sourceHashHolder.getHashedSource().hashes()); - } else { - baseHashes = new ArrayList<>(0); - } - - return new IssueTrackingInput<>(rIssues, baseHashes); - } - - private boolean shouldCopyServerIssues(InputComponent component) { - if (!mode.scanAllFiles() && component.isFile()) { - InputFile inputFile = (InputFile) component; - if (inputFile.status() == Status.SAME) { - return true; - } - } - return false; - } - - private void copyServerIssues(Collection<ServerIssueFromWs> serverIssues, List<TrackedIssue> trackedIssues, String componentKey) { - for (ServerIssueFromWs serverIssue : serverIssues) { - org.sonar.scanner.protocol.input.ScannerInput.ServerIssue unmatchedPreviousIssue = serverIssue.getDto(); - TrackedIssue unmatched = IssueTransformer.toTrackedIssue(unmatchedPreviousIssue, componentKey); - - ActiveRule activeRule = activeRules.find(unmatched.getRuleKey()); - unmatched.setNew(false); - - if (activeRule == null) { - // rule removed - IssueTransformer.resolveRemove(unmatched); - } - - trackedIssues.add(unmatched); - } - } - - @CheckForNull - private SourceHashHolder loadSourceHashes(InputComponent component) { - SourceHashHolder sourceHashHolder = null; - if (component.isFile()) { - DefaultInputFile file = (DefaultInputFile) component; - sourceHashHolder = new SourceHashHolder(project, file, lastLineHashes); - } - return sourceHashHolder; - } - - private Collection<ServerIssueFromWs> loadServerIssues(InputComponent component) { - Collection<ServerIssueFromWs> serverIssues = new ArrayList<>(); - for (org.sonar.scanner.protocol.input.ScannerInput.ServerIssue previousIssue : serverIssueRepository.byComponent(component)) { - serverIssues.add(new ServerIssueFromWs(previousIssue)); - } - return serverIssues; - } - - @VisibleForTesting - protected void mergeMatched(Tracking<TrackedIssue, ServerIssueFromWs> result, Collection<TrackedIssue> mergeTo, Collection<TrackedIssue> rawIssues) { - for (Map.Entry<TrackedIssue, ServerIssueFromWs> e : result.getMatchedRaws().entrySet()) { - org.sonar.scanner.protocol.input.ScannerInput.ServerIssue dto = e.getValue().getDto(); - TrackedIssue tracked = e.getKey(); - - // invariant fields - tracked.setKey(dto.getKey()); - - // non-persisted fields - tracked.setNew(false); - - // fields to update with old values - tracked.setResolution(dto.hasResolution() ? dto.getResolution() : null); - tracked.setStatus(dto.getStatus()); - tracked.setAssignee(dto.hasAssigneeLogin() ? dto.getAssigneeLogin() : null); - tracked.setCreationDate(new Date(dto.getCreationDate())); - - if (dto.getManualSeverity()) { - // Severity overridden by user - tracked.setSeverity(dto.getSeverity().name()); - } - mergeTo.add(tracked); - } - } - - private void addUnmatchedFromServer(Stream<ServerIssueFromWs> unmatchedIssues, Collection<TrackedIssue> mergeTo, String componentKey) { - unmatchedIssues.forEach(unmatchedIssue -> { - org.sonar.scanner.protocol.input.ScannerInput.ServerIssue unmatchedPreviousIssue = unmatchedIssue.getDto(); - TrackedIssue unmatched = IssueTransformer.toTrackedIssue(unmatchedPreviousIssue, componentKey); - updateUnmatchedIssue(unmatched); - mergeTo.add(unmatched); - }); - } - - private static void addUnmatchedFromReport(Stream<TrackedIssue> rawIssues, Collection<TrackedIssue> trackedIssues, Date analysisDate) { - rawIssues.forEach(rawIssue -> { - rawIssue.setCreationDate(analysisDate); - trackedIssues.add(rawIssue); - }); - } - - private void addIssuesOnDeletedComponents(Collection<TrackedIssue> issues, String componentKey) { - for (org.sonar.scanner.protocol.input.ScannerInput.ServerIssue previous : serverIssueRepository.issuesOnMissingComponents()) { - TrackedIssue dead = IssueTransformer.toTrackedIssue(previous, componentKey); - updateUnmatchedIssue(dead); - issues.add(dead); - } - } - - private void updateUnmatchedIssue(TrackedIssue issue) { - ActiveRule activeRule = activeRules.find(issue.getRuleKey()); - issue.setNew(false); - - boolean isRemovedRule = activeRule == null; - - if (isRemovedRule) { - IssueTransformer.resolveRemove(issue); - } else { - IssueTransformer.close(issue); - } - } -} diff --git a/sonar-scanner-engine/src/main/java/org/sonar/scanner/issue/tracking/RollingFileHashes.java b/sonar-scanner-engine/src/main/java/org/sonar/scanner/issue/tracking/RollingFileHashes.java deleted file mode 100644 index 61d8ad79e3f..00000000000 --- a/sonar-scanner-engine/src/main/java/org/sonar/scanner/issue/tracking/RollingFileHashes.java +++ /dev/null @@ -1,89 +0,0 @@ -/* - * SonarQube - * Copyright (C) 2009-2019 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.scanner.issue.tracking; - -/** - * Compute hashes of block around each line - */ -public class RollingFileHashes { - - final int[] rollingHashes; - - private RollingFileHashes(int[] hashes) { - this.rollingHashes = hashes; - } - - public static RollingFileHashes create(FileHashes hashes, int halfBlockSize) { - int size = hashes.length(); - int[] rollingHashes = new int[size]; - - RollingHashCalculator hashCalulator = new RollingHashCalculator(halfBlockSize * 2 + 1); - for (int i = 1; i <= Math.min(size, halfBlockSize + 1); i++) { - hashCalulator.add(hashes.getHash(i).hashCode()); - } - for (int i = 1; i <= size; i++) { - rollingHashes[i - 1] = hashCalulator.getHash(); - if (i - halfBlockSize > 0) { - hashCalulator.remove(hashes.getHash(i - halfBlockSize).hashCode()); - } - if (i + 1 + halfBlockSize <= size) { - hashCalulator.add(hashes.getHash(i + 1 + halfBlockSize).hashCode()); - } else { - hashCalulator.add(0); - } - } - - return new RollingFileHashes(rollingHashes); - } - - public int getHash(int line) { - return rollingHashes[line - 1]; - } - - private static class RollingHashCalculator { - - private static final int PRIME_BASE = 31; - - private final int power; - private int hash; - - public RollingHashCalculator(int size) { - int pow = 1; - for (int i = 0; i < size - 1; i++) { - pow = pow * PRIME_BASE; - } - this.power = pow; - } - - public void add(int value) { - hash = hash * PRIME_BASE + value; - } - - public void remove(int value) { - hash = hash - power * value; - } - - public int getHash() { - return hash; - } - - } - -} diff --git a/sonar-scanner-engine/src/main/java/org/sonar/scanner/issue/tracking/ServerIssueFromWs.java b/sonar-scanner-engine/src/main/java/org/sonar/scanner/issue/tracking/ServerIssueFromWs.java deleted file mode 100644 index f59503acc89..00000000000 --- a/sonar-scanner-engine/src/main/java/org/sonar/scanner/issue/tracking/ServerIssueFromWs.java +++ /dev/null @@ -1,78 +0,0 @@ -/* - * SonarQube - * Copyright (C) 2009-2019 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.scanner.issue.tracking; - -import java.util.Date; -import javax.annotation.CheckForNull; -import org.sonar.api.rule.RuleKey; -import org.sonar.api.utils.DateUtils; -import org.sonar.core.issue.tracking.Trackable; - -import static org.apache.commons.lang.StringUtils.trim; - -public class ServerIssueFromWs implements Trackable { - - private org.sonar.scanner.protocol.input.ScannerInput.ServerIssue dto; - - public ServerIssueFromWs(org.sonar.scanner.protocol.input.ScannerInput.ServerIssue dto) { - this.dto = dto; - } - - public org.sonar.scanner.protocol.input.ScannerInput.ServerIssue getDto() { - return dto; - } - - public String key() { - return dto.getKey(); - } - - @Override - public RuleKey getRuleKey() { - return RuleKey.of(dto.getRuleRepository(), dto.getRuleKey()); - } - - @Override - @CheckForNull - public String getLineHash() { - return dto.hasChecksum() ? dto.getChecksum() : null; - } - - @Override - @CheckForNull - public Integer getLine() { - return dto.hasLine() ? dto.getLine() : null; - } - - @Override - public String getMessage() { - return dto.hasMsg() ? trim(dto.getMsg()) : ""; - } - - @Override - public String getStatus() { - return dto.getStatus(); - } - - @Override - public Date getCreationDate() { - return DateUtils.longToDate(dto.getCreationDate()); - } - -} diff --git a/sonar-scanner-engine/src/main/java/org/sonar/scanner/issue/tracking/ServerIssueRepository.java b/sonar-scanner-engine/src/main/java/org/sonar/scanner/issue/tracking/ServerIssueRepository.java deleted file mode 100644 index 96acb3c1d94..00000000000 --- a/sonar-scanner-engine/src/main/java/org/sonar/scanner/issue/tracking/ServerIssueRepository.java +++ /dev/null @@ -1,83 +0,0 @@ -/* - * SonarQube - * Copyright (C) 2009-2019 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.scanner.issue.tracking; - -import org.sonar.api.batch.fs.InputComponent; -import org.sonar.api.batch.fs.internal.AbstractProjectOrModule; -import org.sonar.api.batch.fs.internal.DefaultInputComponent; -import org.sonar.api.utils.log.Logger; -import org.sonar.api.utils.log.Loggers; -import org.sonar.api.utils.log.Profiler; -import org.sonar.core.component.ComponentKeys; -import org.sonar.scanner.protocol.input.ScannerInput.ServerIssue; -import org.sonar.scanner.repository.ServerIssuesLoader; -import org.sonar.scanner.scan.filesystem.InputComponentStore; -import org.sonar.scanner.storage.Storage; -import org.sonar.scanner.storage.Storages; - -public class ServerIssueRepository { - - private static final Logger LOG = Loggers.get(ServerIssueRepository.class); - private static final String LOG_MSG = "Load server issues"; - - private final Storages caches; - private Storage<ServerIssue> issuesCache; - private final ServerIssuesLoader previousIssuesLoader; - private final InputComponentStore componentStore; - private final AbstractProjectOrModule project; - - public ServerIssueRepository(Storages caches, ServerIssuesLoader previousIssuesLoader, InputComponentStore componentStore, AbstractProjectOrModule project) { - this.caches = caches; - this.previousIssuesLoader = previousIssuesLoader; - this.componentStore = componentStore; - this.project = project; - } - - public void load() { - Profiler profiler = Profiler.create(LOG).startInfo(LOG_MSG); - this.issuesCache = caches.createCache("previousIssues"); - caches.registerValueCoder(ServerIssue.class, new ServerIssueValueCoder()); - previousIssuesLoader.load(project.getKeyWithBranch(), this::store); - profiler.stopInfo(); - } - - public Iterable<ServerIssue> byComponent(InputComponent component) { - return issuesCache.values(((DefaultInputComponent) component).scannerId()); - } - - private void store(ServerIssue issue) { - String moduleKeyWithBranch = issue.getModuleKey(); - AbstractProjectOrModule moduleOrProject = componentStore.getModule(moduleKeyWithBranch); - if (moduleOrProject != null) { - String componentKeyWithoutBranch = ComponentKeys.createEffectiveKey(moduleOrProject.key(), issue.hasPath() ? issue.getPath() : null); - DefaultInputComponent r = (DefaultInputComponent) componentStore.getByKey(componentKeyWithoutBranch); - if (r != null) { - issuesCache.put(r.scannerId(), issue.getKey(), issue); - return; - } - } - // Deleted resource - issuesCache.put(0, issue.getKey(), issue); - } - - public Iterable<ServerIssue> issuesOnMissingComponents() { - return issuesCache.values(0); - } -} diff --git a/sonar-scanner-engine/src/main/java/org/sonar/scanner/issue/tracking/ServerIssueValueCoder.java b/sonar-scanner-engine/src/main/java/org/sonar/scanner/issue/tracking/ServerIssueValueCoder.java deleted file mode 100644 index c6ef859329e..00000000000 --- a/sonar-scanner-engine/src/main/java/org/sonar/scanner/issue/tracking/ServerIssueValueCoder.java +++ /dev/null @@ -1,45 +0,0 @@ -/* - * SonarQube - * Copyright (C) 2009-2019 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.scanner.issue.tracking; - -import com.persistit.Value; -import com.persistit.encoding.CoderContext; -import com.persistit.encoding.ValueCoder; -import java.io.IOException; -import org.sonar.scanner.protocol.input.ScannerInput.ServerIssue; - -public class ServerIssueValueCoder implements ValueCoder { - - @Override - public void put(Value value, Object object, CoderContext context) { - ServerIssue issue = (ServerIssue) object; - value.putByteArray(issue.toByteArray()); - } - - @Override - public Object get(Value value, Class<?> clazz, CoderContext context) { - try { - return ServerIssue.parseFrom(value.getByteArray()); - } catch (IOException e) { - throw new IllegalStateException("Unable to read issue from cache", e); - } - } - -} diff --git a/sonar-scanner-engine/src/main/java/org/sonar/scanner/issue/tracking/ServerLineHashesLoader.java b/sonar-scanner-engine/src/main/java/org/sonar/scanner/issue/tracking/ServerLineHashesLoader.java deleted file mode 100644 index 717e27b0c1e..00000000000 --- a/sonar-scanner-engine/src/main/java/org/sonar/scanner/issue/tracking/ServerLineHashesLoader.java +++ /dev/null @@ -1,25 +0,0 @@ -/* - * SonarQube - * Copyright (C) 2009-2019 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.scanner.issue.tracking; - -public interface ServerLineHashesLoader { - - String[] getLineHashes(String fileKey); -} diff --git a/sonar-scanner-engine/src/main/java/org/sonar/scanner/issue/tracking/SourceHashHolder.java b/sonar-scanner-engine/src/main/java/org/sonar/scanner/issue/tracking/SourceHashHolder.java deleted file mode 100644 index 48721f3cbdd..00000000000 --- a/sonar-scanner-engine/src/main/java/org/sonar/scanner/issue/tracking/SourceHashHolder.java +++ /dev/null @@ -1,70 +0,0 @@ -/* - * SonarQube - * Copyright (C) 2009-2019 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.scanner.issue.tracking; - -import javax.annotation.CheckForNull; -import org.sonar.api.batch.fs.InputFile.Status; -import org.sonar.api.batch.fs.internal.DefaultInputFile; -import org.sonar.api.batch.fs.internal.DefaultInputProject; -import org.sonar.core.component.ComponentKeys; - -public class SourceHashHolder { - - private final DefaultInputProject project; - private final DefaultInputFile inputFile; - private final ServerLineHashesLoader lastSnapshots; - - private FileHashes hashedReference; - private FileHashes hashedSource; - - public SourceHashHolder(DefaultInputProject project, DefaultInputFile inputFile, ServerLineHashesLoader lastSnapshots) { - this.project = project; - this.inputFile = inputFile; - this.lastSnapshots = lastSnapshots; - } - - private void initHashes() { - if (hashedSource == null) { - hashedSource = FileHashes.create(inputFile); - Status status = inputFile.status(); - if (status == Status.ADDED) { - hashedReference = null; - } else if (status == Status.SAME) { - hashedReference = hashedSource; - } else { - // Need key with branch - String serverSideKey = ComponentKeys.createEffectiveKey(project.getKeyWithBranch(), inputFile); - String[] lineHashes = lastSnapshots.getLineHashes(serverSideKey); - hashedReference = lineHashes != null ? FileHashes.create(lineHashes) : null; - } - } - } - - @CheckForNull - public FileHashes getHashedReference() { - initHashes(); - return hashedReference; - } - - public FileHashes getHashedSource() { - initHashes(); - return hashedSource; - } -} diff --git a/sonar-scanner-engine/src/main/java/org/sonar/scanner/issue/tracking/TrackedIssue.java b/sonar-scanner-engine/src/main/java/org/sonar/scanner/issue/tracking/TrackedIssue.java deleted file mode 100644 index 6fb370a5465..00000000000 --- a/sonar-scanner-engine/src/main/java/org/sonar/scanner/issue/tracking/TrackedIssue.java +++ /dev/null @@ -1,265 +0,0 @@ -/* - * SonarQube - * Copyright (C) 2009-2019 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.scanner.issue.tracking; - -import com.google.common.base.Preconditions; -import java.io.Serializable; -import java.util.Date; -import javax.annotation.CheckForNull; -import javax.annotation.Nullable; -import org.apache.commons.lang.builder.ToStringBuilder; -import org.apache.commons.lang.builder.ToStringStyle; -import org.sonar.api.rule.RuleKey; -import org.sonar.core.issue.tracking.Trackable; - -public class TrackedIssue implements Trackable, Serializable { - private static final long serialVersionUID = -1755017079070964287L; - - private RuleKey ruleKey; - private String key; - private String severity; - private Integer startLine; - private Integer startLineOffset; - private Integer endLine; - private Integer endLineOffset; - private Double gap; - private boolean isNew; - private Date creationDate; - private String resolution; - private String status; - private String assignee; - private String componentKey; - private String message; - - private transient FileHashes hashes; - - public TrackedIssue() { - hashes = null; - } - - public TrackedIssue(@Nullable FileHashes hashes) { - this.hashes = hashes; - } - - @Override - @CheckForNull - public String getLineHash() { - if (getLine() == null || hashes == null) { - return null; - } - - int line = getLine(); - Preconditions.checkState(line <= hashes.length(), "Invalid line number for issue %s. File has only %s line(s)", this, hashes.length()); - - return hashes.getHash(line); - } - - @Override - public String getMessage() { - return message; - } - - public TrackedIssue setMessage(String message) { - this.message = message; - return this; - } - - /** - * Component key shared by all part of SonarQube (batch, server, WS...). - * It doesn't include the branch. - */ - public String componentKey() { - return componentKey; - } - - /** - * Component key shared by all part of SonarQube (batch, server, WS...). - * It doesn't include the branch. - */ - public TrackedIssue setComponentKey(String componentKey) { - this.componentKey = componentKey; - return this; - } - - public String key() { - return key; - } - - public Integer startLine() { - return startLine; - } - - @Override - public Integer getLine() { - return startLine; - } - - public TrackedIssue setStartLine(Integer startLine) { - this.startLine = startLine; - return this; - } - - public Integer startLineOffset() { - return startLineOffset; - } - - public TrackedIssue setStartLineOffset(Integer startLineOffset) { - this.startLineOffset = startLineOffset; - return this; - } - - public Integer endLine() { - return endLine; - } - - public TrackedIssue setEndLine(Integer endLine) { - this.endLine = endLine; - return this; - } - - public Integer endLineOffset() { - return endLineOffset; - } - - public TrackedIssue setEndLineOffset(Integer endLineOffset) { - this.endLineOffset = endLineOffset; - return this; - } - - public TrackedIssue setKey(String key) { - this.key = key; - return this; - } - - public String assignee() { - return assignee; - } - - public TrackedIssue setAssignee(String assignee) { - this.assignee = assignee; - return this; - } - - public String resolution() { - return resolution; - } - - public TrackedIssue setResolution(String resolution) { - this.resolution = resolution; - return this; - } - - public String status() { - return status; - } - - public TrackedIssue setStatus(String status) { - this.status = status; - return this; - } - - @Override - public RuleKey getRuleKey() { - return ruleKey; - } - - @Override - public String getStatus() { - return status; - } - - public String severity() { - return severity; - } - - public Double gap() { - return gap; - } - - public Date getCreationDate() { - return creationDate; - } - - public boolean isNew() { - return isNew; - } - - public TrackedIssue setNew(boolean isNew) { - this.isNew = isNew; - return this; - } - - public Date creationDate() { - return creationDate; - } - - public TrackedIssue setCreationDate(Date creationDate) { - this.creationDate = creationDate; - return this; - } - - public TrackedIssue setRuleKey(RuleKey ruleKey) { - this.ruleKey = ruleKey; - return this; - } - - public TrackedIssue setSeverity(String severity) { - this.severity = severity; - return this; - } - - public TrackedIssue setGap(Double gap) { - this.gap = gap; - return this; - } - - @Override - public int hashCode() { - final int PRIME = 31; - int result = 1; - result = PRIME * result + ((key == null) ? 0 : key.hashCode()); - return result; - } - - @Override - public boolean equals(Object obj) { - if (obj == null) { - return false; - } - if (getClass() != obj.getClass()) { - return false; - } - TrackedIssue other = (TrackedIssue) obj; - if (key == null) { - if (other.key != null) { - return false; - } - } else if (!key.equals(other.key)) { - return false; - } - return true; - } - - @Override - public String toString() { - return ToStringBuilder.reflectionToString(this, ToStringStyle.SHORT_PREFIX_STYLE); - } - -} diff --git a/sonar-scanner-engine/src/main/java/org/sonar/scanner/issue/tracking/package-info.java b/sonar-scanner-engine/src/main/java/org/sonar/scanner/issue/tracking/package-info.java deleted file mode 100644 index cc91d38564b..00000000000 --- a/sonar-scanner-engine/src/main/java/org/sonar/scanner/issue/tracking/package-info.java +++ /dev/null @@ -1,23 +0,0 @@ -/* - * SonarQube - * Copyright (C) 2009-2019 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. - */ -@ParametersAreNonnullByDefault -package org.sonar.scanner.issue.tracking; - -import javax.annotation.ParametersAreNonnullByDefault; diff --git a/sonar-scanner-engine/src/main/java/org/sonar/scanner/mediumtest/AnalysisResult.java b/sonar-scanner-engine/src/main/java/org/sonar/scanner/mediumtest/AnalysisResult.java index 202c36149db..cd9f6f67421 100644 --- a/sonar-scanner-engine/src/main/java/org/sonar/scanner/mediumtest/AnalysisResult.java +++ b/sonar-scanner-engine/src/main/java/org/sonar/scanner/mediumtest/AnalysisResult.java @@ -39,8 +39,6 @@ import org.sonar.api.batch.fs.internal.DefaultInputFile; import org.sonar.api.batch.sensor.highlighting.TypeOfText; import org.sonar.api.scanner.fs.InputProject; import org.sonar.core.util.CloseableIterator; -import org.sonar.scanner.issue.IssueCache; -import org.sonar.scanner.issue.tracking.TrackedIssue; import org.sonar.scanner.protocol.output.ScannerReport; import org.sonar.scanner.protocol.output.ScannerReport.Component; import org.sonar.scanner.protocol.output.ScannerReport.Symbol; @@ -54,7 +52,6 @@ public class AnalysisResult implements AnalysisObserver { private static final Logger LOG = LoggerFactory.getLogger(AnalysisResult.class); - private List<TrackedIssue> issues = new ArrayList<>(); private Map<String, InputFile> inputFilesByKeys = new HashMap<>(); private InputProject project; private ScannerReportReader reader; @@ -62,10 +59,6 @@ public class AnalysisResult implements AnalysisObserver { @Override public void analysisCompleted(ProjectScanContainer container) { LOG.info("Store analysis results in memory for later assertions in medium test"); - for (TrackedIssue issue : container.getComponentByType(IssueCache.class).all()) { - issues.add(issue); - } - ReportPublisher reportPublisher = container.getComponentByType(ReportPublisher.class); reader = new ScannerReportReader(reportPublisher.getReportDir().toFile()); project = container.getComponentByType(InputProject.class); @@ -85,10 +78,6 @@ public class AnalysisResult implements AnalysisObserver { } } - public List<TrackedIssue> trackedIssues() { - return issues; - } - public Component getReportComponent(InputComponent inputComponent) { return getReportReader().readComponent(((DefaultInputComponent) inputComponent).scannerId()); } diff --git a/sonar-scanner-engine/src/main/java/org/sonar/scanner/postjob/DefaultPostJobContext.java b/sonar-scanner-engine/src/main/java/org/sonar/scanner/postjob/DefaultPostJobContext.java index c98ae6dcf38..6c7ac4361bf 100644 --- a/sonar-scanner-engine/src/main/java/org/sonar/scanner/postjob/DefaultPostJobContext.java +++ b/sonar-scanner-engine/src/main/java/org/sonar/scanner/postjob/DefaultPostJobContext.java @@ -19,36 +19,21 @@ */ package org.sonar.scanner.postjob; -import java.util.function.Predicate; -import java.util.stream.Collectors; -import java.util.stream.StreamSupport; -import javax.annotation.Nullable; import org.sonar.api.batch.AnalysisMode; -import org.sonar.api.batch.fs.InputComponent; import org.sonar.api.batch.postjob.PostJobContext; import org.sonar.api.batch.postjob.issue.PostJobIssue; -import org.sonar.api.batch.rule.Severity; import org.sonar.api.config.Configuration; import org.sonar.api.config.Settings; -import org.sonar.api.rule.RuleKey; -import org.sonar.scanner.issue.IssueCache; -import org.sonar.scanner.issue.tracking.TrackedIssue; -import org.sonar.scanner.scan.filesystem.InputComponentStore; public class DefaultPostJobContext implements PostJobContext { private final Configuration config; - private final IssueCache cache; private final AnalysisMode analysisMode; - private InputComponentStore inputComponentStore; private final Settings mutableSettings; - public DefaultPostJobContext(Configuration config, Settings mutableSettings, IssueCache cache, InputComponentStore inputComponentStore, - AnalysisMode analysisMode) { + public DefaultPostJobContext(Configuration config, Settings mutableSettings, AnalysisMode analysisMode) { this.config = config; this.mutableSettings = mutableSettings; - this.cache = cache; - this.inputComponentStore = inputComponentStore; this.analysisMode = analysisMode; } @@ -69,89 +54,12 @@ public class DefaultPostJobContext implements PostJobContext { @Override public Iterable<PostJobIssue> issues() { - if (!analysisMode.isIssues()) { - throw new UnsupportedOperationException("Issues are only available to PostJobs in 'issues' mode."); - } - return StreamSupport.stream(cache.all().spliterator(), false) - .filter(new ResolvedPredicate(false)) - .map(DefaultIssueWrapper::new) - .collect(Collectors.toList()); + throw new UnsupportedOperationException("Preview mode was dropped."); } @Override public Iterable<PostJobIssue> resolvedIssues() { - if (!analysisMode.isIssues()) { - throw new UnsupportedOperationException("Resolved issues are only available to PostJobs in 'issues' mode."); - } - return StreamSupport.stream(cache.all().spliterator(), false) - .filter(new ResolvedPredicate(true)) - .map(DefaultIssueWrapper::new) - .collect(Collectors.toList()); - } - - private class DefaultIssueWrapper implements PostJobIssue { - - private final TrackedIssue wrapped; - - public DefaultIssueWrapper(TrackedIssue wrapped) { - this.wrapped = wrapped; - } - - @Override - public String key() { - return wrapped.key(); - } - - @Override - public RuleKey ruleKey() { - return wrapped.getRuleKey(); - } - - @Override - public String componentKey() { - return wrapped.componentKey(); - } - - @Override - public InputComponent inputComponent() { - return inputComponentStore.getByKey(wrapped.componentKey()); - } - - @Override - public Integer line() { - return wrapped.startLine(); - } - - @Override - public String message() { - return wrapped.getMessage(); - } - - @Override - public Severity severity() { - return Severity.valueOf(wrapped.severity()); - } - - @Override - public boolean isNew() { - return wrapped.isNew(); - } - } - - private static class ResolvedPredicate implements Predicate<TrackedIssue> { - private final boolean resolved; - - private ResolvedPredicate(boolean resolved) { - this.resolved = resolved; - } - - @Override - public boolean test(@Nullable TrackedIssue issue) { - if (issue != null) { - return resolved ? issue.resolution() != null : issue.resolution() == null; - } - return false; - } + throw new UnsupportedOperationException("Preview mode was dropped."); } } diff --git a/sonar-scanner-engine/src/main/java/org/sonar/scanner/report/ReportPublisher.java b/sonar-scanner-engine/src/main/java/org/sonar/scanner/report/ReportPublisher.java index 22a2905e1f0..2843699a626 100644 --- a/sonar-scanner-engine/src/main/java/org/sonar/scanner/report/ReportPublisher.java +++ b/sonar-scanner-engine/src/main/java/org/sonar/scanner/report/ReportPublisher.java @@ -103,7 +103,7 @@ public class ReportPublisher implements Startable { writer = new ScannerReportWriter(reportDir.toFile()); contextPublisher.init(writer); - if (!analysisMode.isIssues() && !analysisMode.isMediumTest()) { + if (!analysisMode.isMediumTest()) { String publicUrl = server.getPublicRootUrl(); if (HttpUrl.parse(publicUrl) == null) { throw MessageException.of("Failed to parse public URL set in SonarQube server: " + publicUrl); diff --git a/sonar-scanner-engine/src/main/java/org/sonar/scanner/repository/DefaultProjectRepositoriesLoader.java b/sonar-scanner-engine/src/main/java/org/sonar/scanner/repository/DefaultProjectRepositoriesLoader.java index 85e71d87100..658939da426 100644 --- a/sonar-scanner-engine/src/main/java/org/sonar/scanner/repository/DefaultProjectRepositoriesLoader.java +++ b/sonar-scanner-engine/src/main/java/org/sonar/scanner/repository/DefaultProjectRepositoriesLoader.java @@ -23,7 +23,6 @@ import com.google.common.base.Throwables; import java.io.IOException; import java.io.InputStream; import java.net.HttpURLConnection; -import java.util.Date; import java.util.HashMap; import java.util.Map; import javax.annotation.Nullable; @@ -47,8 +46,8 @@ public class DefaultProjectRepositoriesLoader implements ProjectRepositoriesLoad } @Override - public ProjectRepositories load(String projectKey, boolean issuesMode, @Nullable String branchBase) { - GetRequest request = new GetRequest(getUrl(projectKey, issuesMode, branchBase)); + public ProjectRepositories load(String projectKey, @Nullable String branchBase) { + GetRequest request = new GetRequest(getUrl(projectKey, branchBase)); try (WsResponse response = wsClient.call(request)) { try (InputStream is = response.contentStream()) { return processStream(is); @@ -65,14 +64,11 @@ public class DefaultProjectRepositoriesLoader implements ProjectRepositoriesLoad } } - private static String getUrl(String projectKey, boolean issuesMode, @Nullable String branchBase) { + private static String getUrl(String projectKey, @Nullable String branchBase) { StringBuilder builder = new StringBuilder(); builder.append(BATCH_PROJECT_URL) .append("?key=").append(ScannerUtils.encodeForUrl(projectKey)); - if (issuesMode) { - builder.append("&issues_mode=true"); - } if (branchBase != null) { builder.append("&branch=").append(branchBase); } @@ -96,15 +92,15 @@ public class DefaultProjectRepositoriesLoader implements ProjectRepositoriesLoad private static ProjectRepositories processStream(InputStream is) throws IOException { WsProjectResponse response = WsProjectResponse.parseFrom(is); if (response.getFileDataByModuleAndPathCount() == 0) { - return new SingleProjectRepository(constructFileDataMap(response.getFileDataByPathMap()), new Date(response.getLastAnalysisDate())); + return new SingleProjectRepository(constructFileDataMap(response.getFileDataByPathMap())); } else { final Map<String, SingleProjectRepository> repositoriesPerModule = new HashMap<>(); response.getFileDataByModuleAndPathMap().keySet().forEach(moduleKey -> { WsProjectResponse.FileDataByPath filePaths = response.getFileDataByModuleAndPathMap().get(moduleKey); repositoriesPerModule.put(moduleKey, new SingleProjectRepository( - constructFileDataMap(filePaths.getFileDataByPathMap()), new Date(response.getLastAnalysisDate()))); + constructFileDataMap(filePaths.getFileDataByPathMap()))); }); - return new MultiModuleProjectRepository(repositoriesPerModule, new Date(response.getLastAnalysisDate())); + return new MultiModuleProjectRepository(repositoriesPerModule); } } diff --git a/sonar-scanner-engine/src/main/java/org/sonar/scanner/repository/DefaultServerIssuesLoader.java b/sonar-scanner-engine/src/main/java/org/sonar/scanner/repository/DefaultServerIssuesLoader.java deleted file mode 100644 index d802dec531b..00000000000 --- a/sonar-scanner-engine/src/main/java/org/sonar/scanner/repository/DefaultServerIssuesLoader.java +++ /dev/null @@ -1,59 +0,0 @@ -/* - * SonarQube - * Copyright (C) 2009-2019 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.scanner.repository; - -import java.io.IOException; -import java.io.InputStream; -import java.util.function.Consumer; -import org.apache.commons.io.IOUtils; -import org.sonar.scanner.bootstrap.ScannerWsClient; -import org.sonar.scanner.protocol.input.ScannerInput.ServerIssue; -import org.sonar.scanner.util.ScannerUtils; -import org.sonarqube.ws.client.GetRequest; - -public class DefaultServerIssuesLoader implements ServerIssuesLoader { - - private final ScannerWsClient wsClient; - - public DefaultServerIssuesLoader(ScannerWsClient wsClient) { - this.wsClient = wsClient; - } - - @Override - public void load(String componentKey, Consumer<ServerIssue> consumer) { - GetRequest getRequest = new GetRequest("/batch/issues.protobuf?key=" + ScannerUtils.encodeForUrl(componentKey)); - InputStream is = wsClient.call(getRequest).contentStream(); - parseIssues(is, consumer); - } - - private static void parseIssues(InputStream is, Consumer<ServerIssue> consumer) { - try { - ServerIssue previousIssue = ServerIssue.parseDelimitedFrom(is); - while (previousIssue != null) { - consumer.accept(previousIssue); - previousIssue = ServerIssue.parseDelimitedFrom(is); - } - } catch (IOException e) { - throw new IllegalStateException("Unable to get previous issues", e); - } finally { - IOUtils.closeQuietly(is); - } - } -} diff --git a/sonar-scanner-engine/src/main/java/org/sonar/scanner/repository/MultiModuleProjectRepository.java b/sonar-scanner-engine/src/main/java/org/sonar/scanner/repository/MultiModuleProjectRepository.java index d005f4d621e..0f33e38d1c7 100644 --- a/sonar-scanner-engine/src/main/java/org/sonar/scanner/repository/MultiModuleProjectRepository.java +++ b/sonar-scanner-engine/src/main/java/org/sonar/scanner/repository/MultiModuleProjectRepository.java @@ -20,10 +20,8 @@ package org.sonar.scanner.repository; import com.google.common.collect.ImmutableMap; -import java.util.Date; import java.util.Map; import javax.annotation.CheckForNull; -import javax.annotation.Nullable; import javax.annotation.concurrent.Immutable; @Immutable @@ -31,8 +29,8 @@ public class MultiModuleProjectRepository extends ProjectRepositories { private Map<String, SingleProjectRepository> repositoriesPerModule; - public MultiModuleProjectRepository(Map<String, SingleProjectRepository> repositoriesPerModule, @Nullable Date lastAnalysisDate) { - super(lastAnalysisDate, true); + public MultiModuleProjectRepository(Map<String, SingleProjectRepository> repositoriesPerModule) { + super(true); this.repositoriesPerModule = ImmutableMap.copyOf(repositoriesPerModule); } diff --git a/sonar-scanner-engine/src/main/java/org/sonar/scanner/repository/ProjectRepositories.java b/sonar-scanner-engine/src/main/java/org/sonar/scanner/repository/ProjectRepositories.java index e4cce89c392..7ca0913805c 100644 --- a/sonar-scanner-engine/src/main/java/org/sonar/scanner/repository/ProjectRepositories.java +++ b/sonar-scanner-engine/src/main/java/org/sonar/scanner/repository/ProjectRepositories.java @@ -19,19 +19,15 @@ */ package org.sonar.scanner.repository; -import java.util.Date; import javax.annotation.CheckForNull; -import javax.annotation.Nullable; import javax.annotation.concurrent.Immutable; import org.sonar.api.batch.fs.internal.DefaultInputFile; @Immutable public abstract class ProjectRepositories { - private final Date lastAnalysisDate; private final boolean exists; - public ProjectRepositories(@Nullable Date lastAnalysisDate, boolean exists) { - this.lastAnalysisDate = lastAnalysisDate; + public ProjectRepositories(boolean exists) { this.exists = exists; } @@ -48,8 +44,4 @@ public abstract class ProjectRepositories { } } - @CheckForNull - public Date lastAnalysisDate() { - return lastAnalysisDate; - } } diff --git a/sonar-scanner-engine/src/main/java/org/sonar/scanner/repository/ProjectRepositoriesLoader.java b/sonar-scanner-engine/src/main/java/org/sonar/scanner/repository/ProjectRepositoriesLoader.java index 488f7187790..613739e969c 100644 --- a/sonar-scanner-engine/src/main/java/org/sonar/scanner/repository/ProjectRepositoriesLoader.java +++ b/sonar-scanner-engine/src/main/java/org/sonar/scanner/repository/ProjectRepositoriesLoader.java @@ -22,5 +22,5 @@ package org.sonar.scanner.repository; import javax.annotation.Nullable; public interface ProjectRepositoriesLoader { - ProjectRepositories load(String projectKeyWithBranch, boolean issuesMode, @Nullable String branchBase); + ProjectRepositories load(String projectKeyWithBranch, @Nullable String branchBase); } diff --git a/sonar-scanner-engine/src/main/java/org/sonar/scanner/repository/ProjectRepositoriesProvider.java b/sonar-scanner-engine/src/main/java/org/sonar/scanner/repository/ProjectRepositoriesProvider.java index b6fae284f48..d2f7bfeb1af 100644 --- a/sonar-scanner-engine/src/main/java/org/sonar/scanner/repository/ProjectRepositoriesProvider.java +++ b/sonar-scanner-engine/src/main/java/org/sonar/scanner/repository/ProjectRepositoriesProvider.java @@ -23,7 +23,6 @@ import org.picocontainer.injectors.ProviderAdapter; import org.sonar.api.utils.log.Logger; import org.sonar.api.utils.log.Loggers; import org.sonar.api.utils.log.Profiler; -import org.sonar.scanner.bootstrap.GlobalAnalysisMode; import org.sonar.scanner.bootstrap.ProcessedScannerProperties; import org.sonar.scanner.scan.branch.BranchConfiguration; @@ -32,25 +31,13 @@ public class ProjectRepositoriesProvider extends ProviderAdapter { private static final String LOG_MSG = "Load project repositories"; private ProjectRepositories project = null; - public ProjectRepositories provide(ProjectRepositoriesLoader loader, ProcessedScannerProperties scannerProperties, GlobalAnalysisMode mode, BranchConfiguration branchConfig) { + public ProjectRepositories provide(ProjectRepositoriesLoader loader, ProcessedScannerProperties scannerProperties, BranchConfiguration branchConfig) { if (project == null) { - boolean isIssuesMode = mode.isIssues(); Profiler profiler = Profiler.create(LOG).startInfo(LOG_MSG); - project = loader.load(scannerProperties.getKeyWithBranch(), isIssuesMode, branchConfig.longLivingSonarReferenceBranch()); - checkProject(isIssuesMode); + project = loader.load(scannerProperties.getKeyWithBranch(), branchConfig.longLivingSonarReferenceBranch()); profiler.stopInfo(); } return project; } - - private void checkProject(boolean isIssueMode) { - if (isIssueMode) { - if (!project.exists()) { - LOG.warn("Project doesn't exist on the server. All issues will be marked as 'new'."); - } else if (project.lastAnalysisDate() == null) { - LOG.warn("No analysis has been found on the server for this project. All issues will be marked as 'new'."); - } - } - } } diff --git a/sonar-scanner-engine/src/main/java/org/sonar/scanner/repository/ServerIssuesLoader.java b/sonar-scanner-engine/src/main/java/org/sonar/scanner/repository/ServerIssuesLoader.java deleted file mode 100644 index 751a628cec0..00000000000 --- a/sonar-scanner-engine/src/main/java/org/sonar/scanner/repository/ServerIssuesLoader.java +++ /dev/null @@ -1,29 +0,0 @@ -/* - * SonarQube - * Copyright (C) 2009-2019 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.scanner.repository; - -import java.util.function.Consumer; -import org.sonar.scanner.protocol.input.ScannerInput.ServerIssue; - -public interface ServerIssuesLoader { - - void load(String componentKey, Consumer<ServerIssue> consumer); - -} diff --git a/sonar-scanner-engine/src/main/java/org/sonar/scanner/repository/SingleProjectRepository.java b/sonar-scanner-engine/src/main/java/org/sonar/scanner/repository/SingleProjectRepository.java index 6330b2176c0..bc0bc325a5b 100644 --- a/sonar-scanner-engine/src/main/java/org/sonar/scanner/repository/SingleProjectRepository.java +++ b/sonar-scanner-engine/src/main/java/org/sonar/scanner/repository/SingleProjectRepository.java @@ -20,10 +20,8 @@ package org.sonar.scanner.repository; import com.google.common.collect.ImmutableMap; -import java.util.Date; import java.util.Map; import javax.annotation.CheckForNull; -import javax.annotation.Nullable; import javax.annotation.concurrent.Immutable; @Immutable @@ -32,13 +30,12 @@ public class SingleProjectRepository extends ProjectRepositories { private final ImmutableMap<String, FileData> fileDataByPath; public SingleProjectRepository() { - super(null, false); + super(false); this.fileDataByPath = ImmutableMap.<String, FileData>builder().build(); } - public SingleProjectRepository(Map<String, FileData> fileDataByPath, - @Nullable Date lastAnalysisDate) { - super(lastAnalysisDate, true); + public SingleProjectRepository(Map<String, FileData> fileDataByPath) { + super(true); this.fileDataByPath = ImmutableMap.copyOf(fileDataByPath); } diff --git a/sonar-scanner-engine/src/main/java/org/sonar/scanner/scan/ProjectScanContainer.java b/sonar-scanner-engine/src/main/java/org/sonar/scanner/scan/ProjectScanContainer.java index 540b88c4cac..b18e5db8fae 100644 --- a/sonar-scanner-engine/src/main/java/org/sonar/scanner/scan/ProjectScanContainer.java +++ b/sonar-scanner-engine/src/main/java/org/sonar/scanner/scan/ProjectScanContainer.java @@ -51,8 +51,6 @@ import org.sonar.scanner.cpd.CpdSettings; import org.sonar.scanner.cpd.index.SonarCpdBlockIndex; import org.sonar.scanner.deprecated.test.TestPlanBuilder; import org.sonar.scanner.deprecated.test.TestableBuilder; -import org.sonar.scanner.issue.DefaultProjectIssues; -import org.sonar.scanner.issue.IssueCache; import org.sonar.scanner.issue.IssueFilters; import org.sonar.scanner.issue.IssuePublisher; import org.sonar.scanner.issue.ignore.EnforceIssuesFilter; @@ -60,11 +58,6 @@ import org.sonar.scanner.issue.ignore.IgnoreIssuesFilter; import org.sonar.scanner.issue.ignore.pattern.IssueExclusionPatternInitializer; import org.sonar.scanner.issue.ignore.pattern.IssueInclusionPatternInitializer; import org.sonar.scanner.issue.ignore.scanner.IssueExclusionsLoader; -import org.sonar.scanner.issue.tracking.DefaultServerLineHashesLoader; -import org.sonar.scanner.issue.tracking.IssueTransition; -import org.sonar.scanner.issue.tracking.LocalIssueTracking; -import org.sonar.scanner.issue.tracking.ServerIssueRepository; -import org.sonar.scanner.issue.tracking.ServerLineHashesLoader; import org.sonar.scanner.mediumtest.AnalysisObservers; import org.sonar.scanner.notifications.DefaultAnalysisWarnings; import org.sonar.scanner.postjob.DefaultPostJobContext; @@ -84,13 +77,10 @@ import org.sonar.scanner.report.SourcePublisher; import org.sonar.scanner.repository.ContextPropertiesCache; import org.sonar.scanner.repository.DefaultProjectRepositoriesLoader; import org.sonar.scanner.repository.DefaultQualityProfileLoader; -import org.sonar.scanner.repository.DefaultServerIssuesLoader; -import org.sonar.scanner.repository.ProjectRepositories; import org.sonar.scanner.repository.ProjectRepositoriesLoader; import org.sonar.scanner.repository.ProjectRepositoriesProvider; import org.sonar.scanner.repository.QualityProfileLoader; import org.sonar.scanner.repository.QualityProfilesProvider; -import org.sonar.scanner.repository.ServerIssuesLoader; import org.sonar.scanner.repository.language.DefaultLanguagesRepository; import org.sonar.scanner.repository.settings.DefaultProjectSettingsLoader; import org.sonar.scanner.repository.settings.ProjectSettingsLoader; @@ -118,7 +108,6 @@ import org.sonar.scanner.scan.filesystem.ScannerComponentIdGenerator; import org.sonar.scanner.scan.filesystem.StatusDetection; import org.sonar.scanner.scan.measure.DefaultMetricFinder; import org.sonar.scanner.scan.measure.MeasureCache; -import org.sonar.scanner.scan.report.JSONReport; import org.sonar.scanner.scm.ScmChangedFilesProvider; import org.sonar.scanner.scm.ScmConfiguration; import org.sonar.scanner.scm.ScmPublisher; @@ -150,13 +139,6 @@ public class ProjectScanContainer extends ComponentContainer { ProjectLock lock = getComponentByType(ProjectLock.class); lock.tryLock(); getComponentByType(WorkDirectoriesInitializer.class).execute(); - - if (!isIssuesMode()) { - addReportPublishSteps(); - } else if (isTherePreviousAnalysis()) { - addIssueTrackingComponents(); - } - } private void addScannerComponents() { @@ -208,9 +190,6 @@ public class ProjectScanContainer extends ComponentContainer { QProfileVerifier.class, // issues - IssueCache.class, - DefaultProjectIssues.class, - IssueTransition.class, NoSonarFilter.class, IssueFilters.class, IssuePublisher.class, @@ -257,6 +236,11 @@ public class ProjectScanContainer extends ComponentContainer { MetadataPublisher.class, ActiveRulesPublisher.class, AnalysisWarningsPublisher.class, + ComponentsPublisher.class, + MeasuresPublisher.class, + CoveragePublisher.class, + SourcePublisher.class, + ChangedLinesPublisher.class, // Cpd CpdExecutor.class, @@ -293,31 +277,6 @@ public class ProjectScanContainer extends ComponentContainer { addIfMissing(DefaultProjectRepositoriesLoader.class, ProjectRepositoriesLoader.class); } - private void addReportPublishSteps() { - add( - ComponentsPublisher.class, - MeasuresPublisher.class, - CoveragePublisher.class, - SourcePublisher.class, - ChangedLinesPublisher.class); - } - - private void addIssueTrackingComponents() { - add( - LocalIssueTracking.class, - ServerIssueRepository.class); - addIfMissing(DefaultServerIssuesLoader.class, ServerIssuesLoader.class); - addIfMissing(DefaultServerLineHashesLoader.class, ServerLineHashesLoader.class); - } - - private boolean isTherePreviousAnalysis() { - return getComponentByType(ProjectRepositories.class).lastAnalysisDate() != null; - } - - private boolean isIssuesMode() { - return getComponentByType(GlobalAnalysisMode.class).isIssues(); - } - private void addScannerExtensions() { getComponentByType(CoreExtensionsInstaller.class) .install(this, noExtensionFilter(), extension -> getScannerProjectExtensionsFilter().accept(extension)); @@ -370,14 +329,8 @@ public class ProjectScanContainer extends ComponentContainer { getComponentByType(ScmPublisher.class).publish(); - if (analysisMode.isIssues()) { - getComponentByType(IssueTransition.class).execute(); - getComponentByType(JSONReport.class).execute(); - LOG.info("ANALYSIS SUCCESSFUL"); - } else { - getComponentByType(CpdExecutor.class).execute(); - getComponentByType(ReportPublisher.class).execute(); - } + getComponentByType(CpdExecutor.class).execute(); + getComponentByType(ReportPublisher.class).execute(); getComponentByType(PostJobsExecutor.class).execute(); diff --git a/sonar-scanner-engine/src/main/java/org/sonar/scanner/scan/filesystem/DefaultModuleFileSystem.java b/sonar-scanner-engine/src/main/java/org/sonar/scanner/scan/filesystem/DefaultModuleFileSystem.java index 3a962530f8b..dd13c11c1b3 100644 --- a/sonar-scanner-engine/src/main/java/org/sonar/scanner/scan/filesystem/DefaultModuleFileSystem.java +++ b/sonar-scanner-engine/src/main/java/org/sonar/scanner/scan/filesystem/DefaultModuleFileSystem.java @@ -22,30 +22,23 @@ package org.sonar.scanner.scan.filesystem; import com.google.common.annotations.VisibleForTesting; import org.sonar.api.batch.fs.internal.DefaultFileSystem; import org.sonar.api.batch.fs.internal.DefaultInputModule; -import org.sonar.scanner.analysis.DefaultAnalysisMode; public class DefaultModuleFileSystem extends DefaultFileSystem { - public DefaultModuleFileSystem(ModuleInputComponentStore moduleInputFileCache, DefaultInputModule module, DefaultAnalysisMode mode, - StatusDetection statusDetection) { + public DefaultModuleFileSystem(ModuleInputComponentStore moduleInputFileCache, DefaultInputModule module) { super(module.getBaseDir(), moduleInputFileCache); - setFields(module, mode, statusDetection); + initFields(module); } @VisibleForTesting - public DefaultModuleFileSystem(DefaultInputModule module, DefaultAnalysisMode mode, StatusDetection statusDetection) { + public DefaultModuleFileSystem(DefaultInputModule module) { super(module.getBaseDir()); - setFields(module, mode, statusDetection); + initFields(module); } - private void setFields(DefaultInputModule module, DefaultAnalysisMode mode, StatusDetection statusDetection) { + private void initFields(DefaultInputModule module) { setWorkDir(module.getWorkDir()); setEncoding(module.getEncoding()); - - // filter the files sensors have access to - if (!mode.scanAllFiles()) { - setDefaultPredicate(p -> new SameInputFilePredicate(p, statusDetection, module.definition().getKeyWithBranch())); - } } } diff --git a/sonar-scanner-engine/src/main/java/org/sonar/scanner/scan/filesystem/DefaultProjectFileSystem.java b/sonar-scanner-engine/src/main/java/org/sonar/scanner/scan/filesystem/DefaultProjectFileSystem.java index b0c05e14eff..f81ccc42432 100644 --- a/sonar-scanner-engine/src/main/java/org/sonar/scanner/scan/filesystem/DefaultProjectFileSystem.java +++ b/sonar-scanner-engine/src/main/java/org/sonar/scanner/scan/filesystem/DefaultProjectFileSystem.java @@ -22,30 +22,23 @@ package org.sonar.scanner.scan.filesystem; import com.google.common.annotations.VisibleForTesting; import org.sonar.api.batch.fs.internal.DefaultFileSystem; import org.sonar.api.batch.fs.internal.DefaultInputProject; -import org.sonar.scanner.analysis.DefaultAnalysisMode; public class DefaultProjectFileSystem extends DefaultFileSystem { - public DefaultProjectFileSystem(InputComponentStore inputComponentStore, DefaultInputProject project, DefaultAnalysisMode mode, - StatusDetection statusDetection) { + public DefaultProjectFileSystem(InputComponentStore inputComponentStore, DefaultInputProject project) { super(project.getBaseDir(), inputComponentStore); - setFields(project, mode, statusDetection); + setFields(project); } @VisibleForTesting - public DefaultProjectFileSystem(DefaultInputProject project, DefaultAnalysisMode mode, StatusDetection statusDetection) { + public DefaultProjectFileSystem(DefaultInputProject project) { super(project.getBaseDir()); - setFields(project, mode, statusDetection); + setFields(project); } - private void setFields(DefaultInputProject project, DefaultAnalysisMode mode, StatusDetection statusDetection) { + private void setFields(DefaultInputProject project) { setWorkDir(project.getWorkDir()); setEncoding(project.getEncoding()); - - // filter the files sensors have access to - if (!mode.scanAllFiles()) { - setDefaultPredicate(p -> new SameInputFilePredicate(p, statusDetection, project.definition().getKeyWithBranch())); - } } } diff --git a/sonar-scanner-engine/src/main/java/org/sonar/scanner/scan/filesystem/SameInputFilePredicate.java b/sonar-scanner-engine/src/main/java/org/sonar/scanner/scan/filesystem/SameInputFilePredicate.java deleted file mode 100644 index 0fd77d9891c..00000000000 --- a/sonar-scanner-engine/src/main/java/org/sonar/scanner/scan/filesystem/SameInputFilePredicate.java +++ /dev/null @@ -1,68 +0,0 @@ -/* - * SonarQube - * Copyright (C) 2009-2019 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.scanner.scan.filesystem; - -import java.util.function.Predicate; -import org.sonar.api.batch.fs.FilePredicate; -import org.sonar.api.batch.fs.InputFile; -import org.sonar.api.batch.fs.InputFile.Status; -import org.sonar.api.batch.fs.internal.DefaultInputFile; -import org.sonar.api.batch.fs.internal.OperatorPredicate; -import org.sonar.api.batch.fs.internal.StatusPredicate; - -public class SameInputFilePredicate implements Predicate<InputFile> { - private final StatusDetection statusDetection; - private final String moduleKeyWithBranch; - private final FilePredicate currentPredicate; - - public SameInputFilePredicate(FilePredicate currentPredicate, StatusDetection statusDetection, String moduleKeyWithBranch) { - this.currentPredicate = currentPredicate; - this.statusDetection = statusDetection; - this.moduleKeyWithBranch = moduleKeyWithBranch; - } - - @Override - public boolean test(InputFile inputFile) { - if (hasExplicitFilterOnStatus(currentPredicate)) { - // If user explicitly requested a given status, don't change the result - return true; - } - - // TODO: the inputFile could try to calculate the status itself without generating metadata - Status status = statusDetection.getStatusWithoutMetadata(moduleKeyWithBranch, (DefaultInputFile) inputFile); - if (status != null) { - return status != Status.SAME; - } - - // this will trigger computation of metadata - return inputFile.status() != Status.SAME; - } - - static boolean hasExplicitFilterOnStatus(FilePredicate predicate) { - if (predicate instanceof StatusPredicate) { - return true; - } - if (predicate instanceof OperatorPredicate) { - return ((OperatorPredicate) predicate).operands().stream().anyMatch(SameInputFilePredicate::hasExplicitFilterOnStatus); - } - return false; - } - -} diff --git a/sonar-scanner-engine/src/main/java/org/sonar/scanner/scan/filesystem/StatusDetection.java b/sonar-scanner-engine/src/main/java/org/sonar/scanner/scan/filesystem/StatusDetection.java index dedb65043c7..8f33e02ea2c 100644 --- a/sonar-scanner-engine/src/main/java/org/sonar/scanner/scan/filesystem/StatusDetection.java +++ b/sonar-scanner-engine/src/main/java/org/sonar/scanner/scan/filesystem/StatusDetection.java @@ -19,7 +19,6 @@ */ package org.sonar.scanner.scan.filesystem; -import javax.annotation.CheckForNull; import javax.annotation.concurrent.Immutable; import org.apache.commons.lang.StringUtils; import org.sonar.api.batch.fs.InputFile; @@ -57,24 +56,6 @@ public class StatusDetection { return checkChanged(CHANGED, inputFile); } - /** - * If possible, get the status of the provided file without initializing metadata of the file. - * - * @return null if it was not possible to get the status without calculating metadata - */ - @CheckForNull - public InputFile.Status getStatusWithoutMetadata(String moduleKeyWithBranch, DefaultInputFile inputFile) { - FileData fileDataPerPath = projectRepositories.fileData(moduleKeyWithBranch, inputFile); - if (fileDataPerPath == null) { - return checkChanged(ADDED, inputFile); - } - String previousHash = fileDataPerPath.hash(); - if (StringUtils.isEmpty(previousHash)) { - return checkChanged(ADDED, inputFile); - } - return null; - } - private InputFile.Status checkChanged(InputFile.Status status, DefaultInputFile inputFile) { if (!scmChangedFiles.verifyChanged(inputFile.path())) { return SAME; diff --git a/sonar-scanner-engine/src/main/java/org/sonar/scanner/scan/report/JSONReport.java b/sonar-scanner-engine/src/main/java/org/sonar/scanner/scan/report/JSONReport.java deleted file mode 100644 index 50f53f047bf..00000000000 --- a/sonar-scanner-engine/src/main/java/org/sonar/scanner/scan/report/JSONReport.java +++ /dev/null @@ -1,214 +0,0 @@ -/* - * SonarQube - * Copyright (C) 2009-2019 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.scanner.scan.report; - -import com.google.common.annotations.VisibleForTesting; -import java.io.BufferedWriter; -import java.io.File; -import java.io.FileOutputStream; -import java.io.IOException; -import java.io.OutputStreamWriter; -import java.io.Writer; -import java.nio.charset.StandardCharsets; -import java.util.Collection; -import java.util.LinkedHashSet; -import java.util.Set; -import org.apache.commons.lang.StringUtils; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; -import org.sonar.api.Properties; -import org.sonar.api.Property; -import org.sonar.api.PropertyType; -import org.sonar.api.batch.fs.FileSystem; -import org.sonar.api.batch.fs.InputComponent; -import org.sonar.api.batch.fs.internal.DefaultInputFile; -import org.sonar.api.batch.fs.internal.DefaultInputProject; -import org.sonar.api.batch.rule.Rule; -import org.sonar.api.batch.rule.Rules; -import org.sonar.api.config.Configuration; -import org.sonar.api.platform.Server; -import org.sonar.api.rule.RuleKey; -import org.sonar.api.scanner.ScannerSide; -import org.sonar.api.utils.text.JsonWriter; -import org.sonar.core.component.ComponentKeys; -import org.sonar.scanner.issue.IssueCache; -import org.sonar.scanner.issue.tracking.TrackedIssue; -import org.sonar.scanner.scan.filesystem.InputComponentStore; - -@Properties({ - @Property( - key = JSONReport.SONAR_REPORT_EXPORT_PATH, - name = "Report Results Export File", - type = PropertyType.STRING, - global = false, project = false)}) -@ScannerSide -public class JSONReport { - - static final String SONAR_REPORT_EXPORT_PATH = "sonar.report.export.path"; - private static final Logger LOG = LoggerFactory.getLogger(JSONReport.class); - private final Configuration settings; - private final FileSystem fileSystem; - private final Server server; - private final Rules rules; - private final IssueCache issueCache; - private final InputComponentStore componentStore; - private final DefaultInputProject project; - - public JSONReport(Configuration settings, FileSystem fileSystem, Server server, Rules rules, IssueCache issueCache, - DefaultInputProject project, InputComponentStore componentStore) { - this.settings = settings; - this.fileSystem = fileSystem; - this.server = server; - this.rules = rules; - this.issueCache = issueCache; - this.project = project; - this.componentStore = componentStore; - } - - public void execute() { - settings.get(SONAR_REPORT_EXPORT_PATH).ifPresent(this::exportResults); - } - - private void exportResults(String exportPath) { - File exportFile = new File(fileSystem.workDir(), exportPath); - - LOG.info("Export issues to {}", exportFile.getAbsolutePath()); - try (FileOutputStream fos = new FileOutputStream(exportFile)) { - writeJson(new BufferedWriter(new OutputStreamWriter(fos, StandardCharsets.UTF_8))); - } catch (IOException e) { - throw new IllegalStateException("Unable to write report results in file " + exportFile.getAbsolutePath(), e); - } - } - - @VisibleForTesting - void writeJson(Writer writer) { - try (JsonWriter json = JsonWriter.of(writer)) { - json.beginObject(); - json.prop("version", server.getVersion()); - - Set<RuleKey> ruleKeys = new LinkedHashSet<>(); - Set<String> userLogins = new LinkedHashSet<>(); - writeJsonIssues(json, ruleKeys, userLogins); - writeJsonComponents(json); - writeJsonRules(json, ruleKeys); - writeUsers(json, userLogins); - json.endObject(); - } - } - - private void writeJsonIssues(JsonWriter json, Set<RuleKey> ruleKeys, Set<String> logins) { - json.name("issues").beginArray(); - for (TrackedIssue issue : getIssues()) { - if (issue.resolution() == null) { - InputComponent component = componentStore.getByKey(issue.componentKey()); - String componentKeyWithBranch = project.getKeyWithBranch(); - if (component.isFile()) { - componentKeyWithBranch = ComponentKeys.createEffectiveKey(componentKeyWithBranch, (DefaultInputFile) component); - } - json - .beginObject() - .prop("key", issue.key()) - .prop("component", componentKeyWithBranch) - .prop("line", issue.startLine()) - .prop("startLine", issue.startLine()) - .prop("startOffset", issue.startLineOffset()) - .prop("endLine", issue.endLine()) - .prop("endOffset", issue.endLineOffset()) - .prop("message", issue.getMessage()) - .prop("severity", issue.severity()) - .prop("rule", issue.getRuleKey().toString()) - .prop("status", issue.status()) - .prop("resolution", issue.resolution()) - .prop("isNew", issue.isNew()) - .prop("assignee", issue.assignee()) - .prop("effortToFix", issue.gap()) - .propDateTime("creationDate", issue.creationDate()); - if (!StringUtils.isEmpty(issue.assignee())) { - logins.add(issue.assignee()); - } - json.endObject(); - ruleKeys.add(issue.getRuleKey()); - } - } - json.endArray(); - } - - private void writeJsonComponents(JsonWriter json) { - json.name("components").beginArray(); - // Dump modules - writeJsonProject(json); - for (DefaultInputFile inputFile : componentStore.allFilesToPublish()) { - String projectKey = project.getKeyWithBranch(); - String key = ComponentKeys.createEffectiveKey(projectKey, inputFile); - json - .beginObject() - .prop("key", key) - .prop("path", inputFile.relativePath()) - .prop("status", inputFile.status().name()) - .endObject(); - } - json.endArray(); - } - - private void writeJsonProject(JsonWriter json) { - json - .beginObject() - .prop("key", project.definition().getKeyWithBranch()) - .endObject(); - } - - private void writeJsonRules(JsonWriter json, Set<RuleKey> ruleKeys) { - json.name("rules").beginArray(); - for (RuleKey ruleKey : ruleKeys) { - json - .beginObject() - .prop("key", ruleKey.toString()) - .prop("rule", ruleKey.rule()) - .prop("repository", ruleKey.repository()) - .prop("name", getRuleName(ruleKey)) - .endObject(); - } - json.endArray(); - } - - private static void writeUsers(JsonWriter json, Collection<String> userLogins) { - json.name("users").beginArray(); - - // for compatiblity with programs that parse the json report. We no longer get the name for logins. - for (String user : userLogins) { - json - .beginObject() - .prop("login", user) - .prop("name", user) - .endObject(); - } - json.endArray(); - } - - private String getRuleName(RuleKey ruleKey) { - Rule rule = rules.find(ruleKey); - return rule != null ? rule.name() : null; - } - - @VisibleForTesting - Iterable<TrackedIssue> getIssues() { - return issueCache.all(); - } -} diff --git a/sonar-scanner-engine/src/main/java/org/sonar/scanner/scan/report/package-info.java b/sonar-scanner-engine/src/main/java/org/sonar/scanner/scan/report/package-info.java deleted file mode 100644 index 404b9162b34..00000000000 --- a/sonar-scanner-engine/src/main/java/org/sonar/scanner/scan/report/package-info.java +++ /dev/null @@ -1,23 +0,0 @@ -/* - * SonarQube - * Copyright (C) 2009-2019 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. - */ -@ParametersAreNonnullByDefault -package org.sonar.scanner.scan.report; - -import javax.annotation.ParametersAreNonnullByDefault; diff --git a/sonar-scanner-engine/src/main/java/org/sonar/scanner/sensor/ModuleSensorContext.java b/sonar-scanner-engine/src/main/java/org/sonar/scanner/sensor/ModuleSensorContext.java index d05cea7e914..76aa74d3bf0 100644 --- a/sonar-scanner-engine/src/main/java/org/sonar/scanner/sensor/ModuleSensorContext.java +++ b/sonar-scanner-engine/src/main/java/org/sonar/scanner/sensor/ModuleSensorContext.java @@ -21,7 +21,6 @@ package org.sonar.scanner.sensor; import javax.annotation.concurrent.ThreadSafe; import org.sonar.api.SonarRuntime; -import org.sonar.api.batch.AnalysisMode; import org.sonar.api.batch.fs.FileSystem; import org.sonar.api.batch.fs.InputModule; import org.sonar.api.batch.fs.internal.DefaultInputProject; @@ -36,8 +35,8 @@ public class ModuleSensorContext extends ProjectSensorContext { private final InputModule module; public ModuleSensorContext(DefaultInputProject project, InputModule module, Configuration config, Settings mutableSettings, FileSystem fs, ActiveRules activeRules, - AnalysisMode analysisMode, SensorStorage sensorStorage, SonarRuntime sonarRuntime) { - super(project, config, mutableSettings, fs, activeRules, analysisMode, sensorStorage, sonarRuntime); + SensorStorage sensorStorage, SonarRuntime sonarRuntime) { + super(project, config, mutableSettings, fs, activeRules, sensorStorage, sonarRuntime); this.module = module; } diff --git a/sonar-scanner-engine/src/main/java/org/sonar/scanner/sensor/ProjectSensorContext.java b/sonar-scanner-engine/src/main/java/org/sonar/scanner/sensor/ProjectSensorContext.java index 3e06892cf84..0fe743dfbe2 100644 --- a/sonar-scanner-engine/src/main/java/org/sonar/scanner/sensor/ProjectSensorContext.java +++ b/sonar-scanner-engine/src/main/java/org/sonar/scanner/sensor/ProjectSensorContext.java @@ -22,7 +22,6 @@ package org.sonar.scanner.sensor; import java.io.Serializable; import javax.annotation.concurrent.ThreadSafe; import org.sonar.api.SonarRuntime; -import org.sonar.api.batch.AnalysisMode; import org.sonar.api.batch.fs.FileSystem; import org.sonar.api.batch.fs.InputFile; import org.sonar.api.batch.fs.InputModule; @@ -54,42 +53,28 @@ import org.sonar.api.config.Configuration; import org.sonar.api.config.Settings; import org.sonar.api.scanner.fs.InputProject; import org.sonar.api.utils.Version; -import org.sonar.scanner.sensor.noop.NoOpNewAdHocRule; import org.sonar.scanner.sensor.noop.NoOpNewAnalysisError; -import org.sonar.scanner.sensor.noop.NoOpNewCpdTokens; -import org.sonar.scanner.sensor.noop.NoOpNewExternalIssue; -import org.sonar.scanner.sensor.noop.NoOpNewHighlighting; -import org.sonar.scanner.sensor.noop.NoOpNewSignificantCode; -import org.sonar.scanner.sensor.noop.NoOpNewSymbolTable; @ThreadSafe public class ProjectSensorContext implements SensorContext { - static final NoOpNewHighlighting NO_OP_NEW_HIGHLIGHTING = new NoOpNewHighlighting(); - static final NoOpNewSymbolTable NO_OP_NEW_SYMBOL_TABLE = new NoOpNewSymbolTable(); - static final NoOpNewCpdTokens NO_OP_NEW_CPD_TOKENS = new NoOpNewCpdTokens(); static final NoOpNewAnalysisError NO_OP_NEW_ANALYSIS_ERROR = new NoOpNewAnalysisError(); - static final NoOpNewExternalIssue NO_OP_NEW_EXTERNAL_ISSUE = new NoOpNewExternalIssue(); - static final NoOpNewAdHocRule NO_OP_NEW_AD_HOC_RULE = new NoOpNewAdHocRule(); - static final NoOpNewSignificantCode NO_OP_NEW_SIGNIFICANT_CODE = new NoOpNewSignificantCode(); private final Settings mutableSettings; private final FileSystem fs; private final ActiveRules activeRules; private final SensorStorage sensorStorage; - private final AnalysisMode analysisMode; private final DefaultInputProject project; private final SonarRuntime sonarRuntime; private final Configuration config; public ProjectSensorContext(DefaultInputProject project, Configuration config, Settings mutableSettings, FileSystem fs, ActiveRules activeRules, - AnalysisMode analysisMode, SensorStorage sensorStorage, SonarRuntime sonarRuntime) { + SensorStorage sensorStorage, SonarRuntime sonarRuntime) { this.project = project; this.config = config; this.mutableSettings = mutableSettings; this.fs = fs; this.activeRules = activeRules; - this.analysisMode = analysisMode; this.sensorStorage = sensorStorage; this.sonarRuntime = sonarRuntime; } @@ -146,33 +131,21 @@ public class ProjectSensorContext implements SensorContext { @Override public NewExternalIssue newExternalIssue() { - if (analysisMode.isIssues()) { - return NO_OP_NEW_EXTERNAL_ISSUE; - } return new DefaultExternalIssue(project, sensorStorage); } @Override public NewAdHocRule newAdHocRule() { - if (analysisMode.isIssues()) { - return NO_OP_NEW_AD_HOC_RULE; - } return new DefaultAdHocRule(sensorStorage); } @Override public NewHighlighting newHighlighting() { - if (analysisMode.isIssues()) { - return NO_OP_NEW_HIGHLIGHTING; - } return new DefaultHighlighting(sensorStorage); } @Override public NewSymbolTable newSymbolTable() { - if (analysisMode.isIssues()) { - return NO_OP_NEW_SYMBOL_TABLE; - } return new DefaultSymbolTable(sensorStorage); } @@ -183,9 +156,6 @@ public class ProjectSensorContext implements SensorContext { @Override public NewCpdTokens newCpdTokens() { - if (analysisMode.isIssues()) { - return NO_OP_NEW_CPD_TOKENS; - } return new DefaultCpdTokens(sensorStorage); } @@ -212,9 +182,6 @@ public class ProjectSensorContext implements SensorContext { @Override public NewSignificantCode newSignificantCode() { - if (analysisMode.isIssues()) { - return NO_OP_NEW_SIGNIFICANT_CODE; - } return new DefaultSignificantCode(sensorStorage); } } diff --git a/sonar-scanner-engine/src/main/java/org/sonar/scanner/sensor/noop/NoOpNewAdHocRule.java b/sonar-scanner-engine/src/main/java/org/sonar/scanner/sensor/noop/NoOpNewAdHocRule.java deleted file mode 100644 index 27e2f0d8ddd..00000000000 --- a/sonar-scanner-engine/src/main/java/org/sonar/scanner/sensor/noop/NoOpNewAdHocRule.java +++ /dev/null @@ -1,69 +0,0 @@ -/* - * SonarQube - * Copyright (C) 2009-2019 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.scanner.sensor.noop; - -import org.sonar.api.batch.rule.Severity; -import org.sonar.api.batch.sensor.rule.NewAdHocRule; -import org.sonar.api.rules.RuleType; - -public class NoOpNewAdHocRule implements NewAdHocRule { - - @Override - public NoOpNewAdHocRule engineId(String engineId) { - // no op - return this; - } - - @Override - public NoOpNewAdHocRule ruleId(String ruleId) { - // no op - return this; - } - - @Override - public NewAdHocRule name(String name) { - // no op - return this; - } - - @Override - public NewAdHocRule description(String description) { - // no op - return this; - } - - @Override - public NoOpNewAdHocRule type(RuleType type) { - // no op - return this; - } - - @Override - public NoOpNewAdHocRule severity(Severity severity) { - // no op - return this; - } - - @Override - public void save() { - // no op - } - -} diff --git a/sonar-scanner-engine/src/main/java/org/sonar/scanner/sensor/noop/NoOpNewCpdTokens.java b/sonar-scanner-engine/src/main/java/org/sonar/scanner/sensor/noop/NoOpNewCpdTokens.java deleted file mode 100644 index f8dd9d8104d..00000000000 --- a/sonar-scanner-engine/src/main/java/org/sonar/scanner/sensor/noop/NoOpNewCpdTokens.java +++ /dev/null @@ -1,49 +0,0 @@ -/* - * SonarQube - * Copyright (C) 2009-2019 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.scanner.sensor.noop; - -import org.sonar.api.batch.fs.InputFile; -import org.sonar.api.batch.fs.TextRange; -import org.sonar.api.batch.sensor.cpd.NewCpdTokens; - -public class NoOpNewCpdTokens implements NewCpdTokens { - @Override - public void save() { - // Do nothing - } - - @Override - public NoOpNewCpdTokens onFile(InputFile inputFile) { - // Do nothing - return this; - } - - @Override - public NewCpdTokens addToken(TextRange range, String image) { - // Do nothing - return this; - } - - @Override - public NewCpdTokens addToken(int startLine, int startLineOffset, int endLine, int endLineOffset, String image) { - // Do nothing - return this; - } -} diff --git a/sonar-scanner-engine/src/main/java/org/sonar/scanner/sensor/noop/NoOpNewExternalIssue.java b/sonar-scanner-engine/src/main/java/org/sonar/scanner/sensor/noop/NoOpNewExternalIssue.java deleted file mode 100644 index ae12f7fb77c..00000000000 --- a/sonar-scanner-engine/src/main/java/org/sonar/scanner/sensor/noop/NoOpNewExternalIssue.java +++ /dev/null @@ -1,96 +0,0 @@ -/* - * SonarQube - * Copyright (C) 2009-2019 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.scanner.sensor.noop; - -import org.sonar.api.batch.rule.Severity; -import org.sonar.api.batch.sensor.issue.NewExternalIssue; -import org.sonar.api.batch.sensor.issue.NewIssueLocation; -import org.sonar.api.batch.sensor.issue.internal.DefaultIssueLocation; -import org.sonar.api.rule.RuleKey; -import org.sonar.api.rules.RuleType; - -public class NoOpNewExternalIssue implements NewExternalIssue { - - @Override - public NewExternalIssue forRule(RuleKey ruleKey) { - // no op - return this; - } - - @Override - public NewExternalIssue engineId(String engineId) { - // no op - return this; - } - - @Override - public NewExternalIssue ruleId(String ruleId) { - // no op - return this; - } - - @Override - public NewExternalIssue type(RuleType type) { - // no op - return this; - } - - @Override - public NewExternalIssue remediationEffortMinutes(Long effort) { - // no op - return this; - } - - @Override - public NewExternalIssue severity(Severity severity) { - // no op - return this; - } - - @Override - public NewExternalIssue at(NewIssueLocation primaryLocation) { - // no op - return this; - } - - @Override - public NewExternalIssue addLocation(NewIssueLocation secondaryLocation) { - // no op - return this; - } - - @Override - public NewExternalIssue addFlow(Iterable<NewIssueLocation> flowLocations) { - // no op - return this; - } - - @Override - public NewIssueLocation newLocation() { - // no op - return new DefaultIssueLocation(); - } - - @Override - public void save() { - // no op - } - -} diff --git a/sonar-scanner-engine/src/main/java/org/sonar/scanner/sensor/noop/NoOpNewHighlighting.java b/sonar-scanner-engine/src/main/java/org/sonar/scanner/sensor/noop/NoOpNewHighlighting.java deleted file mode 100644 index 8eb72753f7b..00000000000 --- a/sonar-scanner-engine/src/main/java/org/sonar/scanner/sensor/noop/NoOpNewHighlighting.java +++ /dev/null @@ -1,56 +0,0 @@ -/* - * SonarQube - * Copyright (C) 2009-2019 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.scanner.sensor.noop; - -import org.sonar.api.batch.fs.InputFile; -import org.sonar.api.batch.fs.TextRange; -import org.sonar.api.batch.sensor.highlighting.NewHighlighting; -import org.sonar.api.batch.sensor.highlighting.TypeOfText; - -public class NoOpNewHighlighting implements NewHighlighting { - @Override - public void save() { - // Do nothing - } - - @Override - public NoOpNewHighlighting onFile(InputFile inputFile) { - // Do nothing - return this; - } - - @Override - public NoOpNewHighlighting highlight(int startOffset, int endOffset, TypeOfText typeOfText) { - // Do nothing - return this; - } - - @Override - public NoOpNewHighlighting highlight(int startLine, int startLineOffset, int endLine, int endLineOffset, TypeOfText typeOfText) { - // Do nothing - return this; - } - - @Override - public NoOpNewHighlighting highlight(TextRange range, TypeOfText typeOfText) { - // Do nothing - return this; - } -} diff --git a/sonar-scanner-engine/src/main/java/org/sonar/scanner/sensor/noop/NoOpNewSignificantCode.java b/sonar-scanner-engine/src/main/java/org/sonar/scanner/sensor/noop/NoOpNewSignificantCode.java deleted file mode 100644 index 3a400ec50cd..00000000000 --- a/sonar-scanner-engine/src/main/java/org/sonar/scanner/sensor/noop/NoOpNewSignificantCode.java +++ /dev/null @@ -1,45 +0,0 @@ -/* - * SonarQube - * Copyright (C) 2009-2019 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.scanner.sensor.noop; - -import org.sonar.api.batch.fs.InputFile; -import org.sonar.api.batch.fs.TextRange; -import org.sonar.api.batch.sensor.code.NewSignificantCode; - -public class NoOpNewSignificantCode implements NewSignificantCode { - - @Override - public NewSignificantCode onFile(InputFile file) { - // no op - return this; - } - - @Override - public NewSignificantCode addRange(TextRange range) { - // no op - return this; - } - - @Override - public void save() { - // no op - } - -} diff --git a/sonar-scanner-engine/src/main/java/org/sonar/scanner/sensor/noop/NoOpNewSymbolTable.java b/sonar-scanner-engine/src/main/java/org/sonar/scanner/sensor/noop/NoOpNewSymbolTable.java deleted file mode 100644 index 0173e2a58d3..00000000000 --- a/sonar-scanner-engine/src/main/java/org/sonar/scanner/sensor/noop/NoOpNewSymbolTable.java +++ /dev/null @@ -1,75 +0,0 @@ -/* - * SonarQube - * Copyright (C) 2009-2019 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.scanner.sensor.noop; - -import org.sonar.api.batch.fs.InputFile; -import org.sonar.api.batch.fs.TextRange; -import org.sonar.api.batch.sensor.symbol.NewSymbol; -import org.sonar.api.batch.sensor.symbol.NewSymbolTable; - -public class NoOpNewSymbolTable implements NewSymbolTable, NewSymbol { - @Override - public void save() { - // Do nothing - } - - @Override - public NoOpNewSymbolTable onFile(InputFile inputFile) { - // Do nothing - return this; - } - - @Override - public NewSymbol newSymbol(int startOffset, int endOffset) { - // Do nothing - return this; - } - - @Override - public NewSymbol newSymbol(int startLine, int startLineOffset, int endLine, int endLineOffset) { - // Do nothing - return this; - } - - @Override - public NewSymbol newSymbol(TextRange range) { - // Do nothing - return this; - } - - @Override - public NewSymbol newReference(int startLine, int startLineOffset, int endLine, int endLineOffset) { - // Do nothing - return this; - } - - @Override - public NewSymbol newReference(int startOffset, int endOffset) { - // Do nothing - return this; - } - - @Override - public NewSymbol newReference(TextRange range) { - // Do nothing - return this; - } - -} diff --git a/sonar-scanner-engine/src/test/java/org/sonar/scanner/analysis/DefaultAnalysisModeTest.java b/sonar-scanner-engine/src/test/java/org/sonar/scanner/analysis/DefaultAnalysisModeTest.java index 4e678fcd44d..8598601c528 100644 --- a/sonar-scanner-engine/src/test/java/org/sonar/scanner/analysis/DefaultAnalysisModeTest.java +++ b/sonar-scanner-engine/src/test/java/org/sonar/scanner/analysis/DefaultAnalysisModeTest.java @@ -19,82 +19,18 @@ */ package org.sonar.scanner.analysis; -import java.util.Collections; -import org.junit.Before; -import org.junit.Rule; import org.junit.Test; -import org.junit.rules.ExpectedException; -import org.sonar.scanner.bootstrap.GlobalAnalysisMode; -import org.sonar.scanner.bootstrap.RawScannerProperties; -import org.sonar.scanner.bootstrap.ProcessedScannerProperties; -import org.sonar.scanner.scan.EmptyExternalProjectKeyAndOrganization; import static org.assertj.core.api.Assertions.assertThat; -import static org.mockito.Mockito.mock; -import static org.mockito.Mockito.when; public class DefaultAnalysisModeTest { - private GlobalAnalysisMode globalMode; - - @Before - public void setUp() { - globalMode = mock(GlobalAnalysisMode.class); - } - - @Rule - public ExpectedException thrown = ExpectedException.none(); @Test - public void scan_all_even_on_short_lived_branch() { - ProcessedScannerProperties analysisProps = new ProcessedScannerProperties( - new RawScannerProperties(Collections.singletonMap("sonar.scanAllFiles", "true")), new EmptyExternalProjectKeyAndOrganization()); - DefaultAnalysisMode mode = createmode(analysisProps); - - assertThat(mode.scanAllFiles()).isTrue(); - } - - @Test - public void reuse_global_mode() { - when(globalMode.isIssues()).thenReturn(true); - when(globalMode.isPublish()).thenReturn(true); - when(globalMode.isPreview()).thenReturn(true); - DefaultAnalysisMode mode = createmode(new ProcessedScannerProperties( - new RawScannerProperties(Collections.emptyMap()), new EmptyExternalProjectKeyAndOrganization())); - - assertThat(mode.isIssues()).isTrue(); + public void test() { + DefaultAnalysisMode mode = new DefaultAnalysisMode(); assertThat(mode.isPublish()).isTrue(); - assertThat(mode.isPreview()).isTrue(); - } - - @Test - public void scan_all_if_publish() { - when(globalMode.isIssues()).thenReturn(false); - DefaultAnalysisMode mode = createmode(new ProcessedScannerProperties( - new RawScannerProperties(Collections.emptyMap()), new EmptyExternalProjectKeyAndOrganization())); - - assertThat(mode.scanAllFiles()).isTrue(); - } - - @Test - public void scan_all_if_property_set() { - ProcessedScannerProperties analysisProps = new ProcessedScannerProperties( - new RawScannerProperties(Collections.singletonMap("sonar.scanAllFiles", "true")), new EmptyExternalProjectKeyAndOrganization()); - DefaultAnalysisMode mode = createmode(analysisProps); - - assertThat(mode.scanAllFiles()).isTrue(); - } - - @Test - public void dont_scan_all_if_issues_mode() { - when(globalMode.isIssues()).thenReturn(true); - DefaultAnalysisMode mode = createmode(new ProcessedScannerProperties( - new RawScannerProperties(Collections.emptyMap()), new EmptyExternalProjectKeyAndOrganization())); - - assertThat(mode.scanAllFiles()).isFalse(); - } - - private DefaultAnalysisMode createmode(ProcessedScannerProperties analysisProps) { - return new DefaultAnalysisMode(analysisProps, globalMode); + assertThat(mode.isIssues()).isFalse(); + assertThat(mode.isPreview()).isFalse(); } } diff --git a/sonar-scanner-engine/src/test/java/org/sonar/scanner/bootstrap/ExtensionInstallerTest.java b/sonar-scanner-engine/src/test/java/org/sonar/scanner/bootstrap/ExtensionInstallerTest.java index 41b5f0a1d5d..d060367750d 100644 --- a/sonar-scanner-engine/src/test/java/org/sonar/scanner/bootstrap/ExtensionInstallerTest.java +++ b/sonar-scanner-engine/src/test/java/org/sonar/scanner/bootstrap/ExtensionInstallerTest.java @@ -37,7 +37,6 @@ import static org.mockito.Mockito.when; public class ExtensionInstallerTest { private MapSettings settings = new MapSettings(); - private GlobalAnalysisMode mode = mock(GlobalAnalysisMode.class); private ScannerPluginRepository pluginRepository = mock(ScannerPluginRepository.class); private static Plugin newPluginInstance(final Object... extensions) { @@ -50,7 +49,7 @@ public class ExtensionInstallerTest { when(pluginRepository.getPluginInstance("foo")).thenReturn(newPluginInstance(Foo.class, Bar.class)); ComponentContainer container = new ComponentContainer(); - ExtensionInstaller installer = new ExtensionInstaller(mock(SonarRuntime.class), pluginRepository, mode, settings.asConfig()); + ExtensionInstaller installer = new ExtensionInstaller(mock(SonarRuntime.class), pluginRepository, settings.asConfig()); installer.install(container, new FooMatcher()); assertThat(container.getComponentByType(Foo.class)).isNotNull(); @@ -62,7 +61,7 @@ public class ExtensionInstallerTest { when(pluginRepository.getPluginInfos()).thenReturn(Arrays.asList(new PluginInfo("foo"))); when(pluginRepository.getPluginInstance("foo")).thenReturn(newPluginInstance(new FooProvider(), new BarProvider())); ComponentContainer container = new ComponentContainer(); - ExtensionInstaller installer = new ExtensionInstaller(mock(SonarRuntime.class), pluginRepository, mode, settings.asConfig()); + ExtensionInstaller installer = new ExtensionInstaller(mock(SonarRuntime.class), pluginRepository, settings.asConfig()); installer.install(container, new FooMatcher()); @@ -75,7 +74,7 @@ public class ExtensionInstallerTest { when(pluginRepository.getPluginInfos()).thenReturn(Arrays.asList(new PluginInfo("foo"))); when(pluginRepository.getPluginInstance("foo")).thenReturn(newPluginInstance(new FooBarProvider())); ComponentContainer container = new ComponentContainer(); - ExtensionInstaller installer = new ExtensionInstaller(mock(SonarRuntime.class), pluginRepository, mode, settings.asConfig()); + ExtensionInstaller installer = new ExtensionInstaller(mock(SonarRuntime.class), pluginRepository, settings.asConfig()); installer.install(container, new TrueMatcher()); diff --git a/sonar-scanner-engine/src/test/java/org/sonar/scanner/bootstrap/GlobalAnalysisModeTest.java b/sonar-scanner-engine/src/test/java/org/sonar/scanner/bootstrap/GlobalAnalysisModeTest.java deleted file mode 100644 index bfcf46179d9..00000000000 --- a/sonar-scanner-engine/src/test/java/org/sonar/scanner/bootstrap/GlobalAnalysisModeTest.java +++ /dev/null @@ -1,88 +0,0 @@ -/* - * SonarQube - * Copyright (C) 2009-2019 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.scanner.bootstrap; - -import java.util.HashMap; -import java.util.Map; -import org.junit.Rule; -import org.junit.Test; -import org.junit.rules.ExpectedException; -import org.sonar.api.CoreProperties; - -import static org.assertj.core.api.Assertions.assertThat; - -public class GlobalAnalysisModeTest { - @Rule - public ExpectedException thrown = ExpectedException.none(); - - @Test - public void invalidate_mode() { - thrown.expect(IllegalStateException.class); - thrown.expectMessage("Invalid analysis mode: invalid."); - - createMode(CoreProperties.ANALYSIS_MODE, "invalid"); - } - - @Test - public void testOtherProperty() { - GlobalAnalysisMode mode = createMode(CoreProperties.ANALYSIS_MODE, CoreProperties.ANALYSIS_MODE_PUBLISH); - assertThat(mode.isPreview()).isFalse(); - assertThat(mode.isIssues()).isFalse(); - assertThat(mode.isPublish()).isTrue(); - } - - @Test - public void testIssuesMode() { - GlobalAnalysisMode mode = createMode(CoreProperties.ANALYSIS_MODE, CoreProperties.ANALYSIS_MODE_ISSUES); - assertThat(mode.isPreview()).isFalse(); - assertThat(mode.isIssues()).isTrue(); - assertThat(mode.isPublish()).isFalse(); - } - - @Test - public void preview_mode_fallback_issues() { - GlobalAnalysisMode mode = createMode(CoreProperties.ANALYSIS_MODE, CoreProperties.ANALYSIS_MODE_PREVIEW); - - assertThat(mode.isIssues()).isTrue(); - assertThat(mode.isPreview()).isFalse(); - } - - @Test - public void testDefault() { - GlobalAnalysisMode mode = createMode(null, null); - assertThat(mode.isPreview()).isFalse(); - assertThat(mode.isIssues()).isFalse(); - assertThat(mode.isPublish()).isTrue(); - } - - @Test(expected = IllegalStateException.class) - public void testInvalidMode() { - createMode(CoreProperties.ANALYSIS_MODE, CoreProperties.ANALYSIS_MODE_ANALYSIS); - } - - private GlobalAnalysisMode createMode(String key, String value) { - Map<String, String> map = new HashMap<>(); - if (key != null) { - map.put(key, value); - } - RawScannerProperties props = new RawScannerProperties(map); - return new GlobalAnalysisMode(props); - } -} diff --git a/sonar-scanner-engine/src/test/java/org/sonar/scanner/bootstrap/ScannerPluginInstallerTest.java b/sonar-scanner-engine/src/test/java/org/sonar/scanner/bootstrap/ScannerPluginInstallerTest.java index 4332ff74983..fe6720aca89 100644 --- a/sonar-scanner-engine/src/test/java/org/sonar/scanner/bootstrap/ScannerPluginInstallerTest.java +++ b/sonar-scanner-engine/src/test/java/org/sonar/scanner/bootstrap/ScannerPluginInstallerTest.java @@ -36,13 +36,9 @@ import org.junit.rules.TemporaryFolder; import org.sonar.scanner.WsTestUtil; import static org.assertj.core.api.Assertions.assertThat; -import static org.mockito.ArgumentMatchers.any; import static org.mockito.ArgumentMatchers.argThat; import static org.mockito.Mockito.doReturn; import static org.mockito.Mockito.mock; -import static org.mockito.Mockito.times; -import static org.mockito.Mockito.verify; -import static org.mockito.Mockito.when; public class ScannerPluginInstallerTest { @@ -51,17 +47,15 @@ public class ScannerPluginInstallerTest { @Rule public ExpectedException expectedException = ExpectedException.none(); - private ScannerPluginPredicate pluginPredicate = mock(ScannerPluginPredicate.class); private PluginFiles pluginFiles = mock(PluginFiles.class); private ScannerWsClient wsClient = mock(ScannerWsClient.class); - private ScannerPluginInstaller underTest = new ScannerPluginInstaller(pluginFiles, pluginPredicate, wsClient); + private ScannerPluginInstaller underTest = new ScannerPluginInstaller(pluginFiles, wsClient); @Test public void download_installed_plugins() throws IOException { WsTestUtil.mockReader(wsClient, "api/plugins/installed", new InputStreamReader(getClass().getResourceAsStream("ScannerPluginInstallerTest/installed-plugins-ws.json"))); enqueueDownload("scmgit", "abc"); enqueueDownload("java", "def"); - when(pluginPredicate.apply(any())).thenReturn(true); Map<String, ScannerPlugin> result = underTest.installRemotes(); @@ -78,20 +72,6 @@ public class ScannerPluginInstallerTest { } @Test - public void filter_blacklisted_plugins() throws IOException { - WsTestUtil.mockReader(wsClient, "api/plugins/installed", new InputStreamReader(getClass().getResourceAsStream("ScannerPluginInstallerTest/installed-plugins-ws.json"))); - enqueueDownload("scmgit", "abc"); - enqueueDownload("java", "def"); - when(pluginPredicate.apply("scmgit")).thenReturn(true); - when(pluginPredicate.apply("java")).thenReturn(false); - - Map<String, ScannerPlugin> result = underTest.installRemotes(); - - assertThat(result.keySet()).containsExactlyInAnyOrder("scmgit"); - verify(pluginFiles, times(1)).get(any()); - } - - @Test public void fail_if_json_of_installed_plugins_is_not_valid() { WsTestUtil.mockReader(wsClient, "api/plugins/installed", new StringReader("not json")); @@ -109,7 +89,6 @@ public class ScannerPluginInstallerTest { enqueueNotFoundDownload("scmgit", "abc"); enqueueDownload("java", "def"); enqueueDownload("cobol", "ghi"); - when(pluginPredicate.apply(any())).thenReturn(true); Map<String, ScannerPlugin> result = underTest.installRemotes(); @@ -124,7 +103,6 @@ public class ScannerPluginInstallerTest { enqueueDownload("scmgit", "abc"); enqueueDownload("cobol", "ghi"); enqueueNotFoundDownload("java", "def"); - when(pluginPredicate.apply(any())).thenReturn(true); expectedException.expect(IllegalStateException.class); expectedException.expectMessage("Fail to download plugin [java]. Not found."); diff --git a/sonar-scanner-engine/src/test/java/org/sonar/scanner/bootstrap/ScannerPluginPredicateTest.java b/sonar-scanner-engine/src/test/java/org/sonar/scanner/bootstrap/ScannerPluginPredicateTest.java deleted file mode 100644 index 0b41a6abd88..00000000000 --- a/sonar-scanner-engine/src/test/java/org/sonar/scanner/bootstrap/ScannerPluginPredicateTest.java +++ /dev/null @@ -1,104 +0,0 @@ -/* - * SonarQube - * Copyright (C) 2009-2019 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.scanner.bootstrap; - -import org.junit.Test; -import org.sonar.api.CoreProperties; -import org.sonar.api.config.internal.MapSettings; - -import static org.assertj.core.api.Assertions.assertThat; -import static org.mockito.Mockito.mock; -import static org.mockito.Mockito.when; - -public class ScannerPluginPredicateTest { - - private MapSettings settings = new MapSettings(); - private GlobalAnalysisMode mode = mock(GlobalAnalysisMode.class); - - @Test - public void accept_if_no_inclusions_nor_exclusions() { - ScannerPluginPredicate predicate = new ScannerPluginPredicate(settings.asConfig(), mode); - assertThat(predicate.getWhites()).isEmpty(); - assertThat(predicate.getBlacks()).isEmpty(); - assertThat(predicate.apply("pmd")).isTrue(); - assertThat(predicate.apply("buildbreaker")).isTrue(); - } - - @Test - public void exclude_buildbreaker_in_preview_mode() { - when(mode.isPreview()).thenReturn(true); - ScannerPluginPredicate predicate = new ScannerPluginPredicate(settings.asConfig(), mode); - assertThat(predicate.apply("buildbreaker")).isFalse(); - } - - @Test - public void inclusions_take_precedence_over_exclusions() { - when(mode.isPreview()).thenReturn(true); - settings - .setProperty(CoreProperties.PREVIEW_INCLUDE_PLUGINS, "checkstyle,pmd,findbugs") - .setProperty(CoreProperties.PREVIEW_EXCLUDE_PLUGINS, "cobertura,pmd"); - ScannerPluginPredicate predicate = new ScannerPluginPredicate(settings.asConfig(), mode); - assertThat(predicate.apply("pmd")).isTrue(); - } - - @Test - public void verify_both_inclusions_and_exclusions() { - when(mode.isPreview()).thenReturn(true); - settings - .setProperty(CoreProperties.PREVIEW_INCLUDE_PLUGINS, "checkstyle,pmd,findbugs") - .setProperty(CoreProperties.PREVIEW_EXCLUDE_PLUGINS, "cobertura"); - ScannerPluginPredicate predicate = new ScannerPluginPredicate(settings.asConfig(), mode); - assertThat(predicate.apply("checkstyle")).isTrue(); - assertThat(predicate.apply("pmd")).isTrue(); - assertThat(predicate.apply("cobertura")).isFalse(); - } - - @Test - public void verify_both_inclusions_and_exclusions_issues() { - when(mode.isIssues()).thenReturn(true); - settings - .setProperty(CoreProperties.PREVIEW_INCLUDE_PLUGINS, "checkstyle,pmd,findbugs") - .setProperty(CoreProperties.PREVIEW_EXCLUDE_PLUGINS, "cobertura"); - ScannerPluginPredicate predicate = new ScannerPluginPredicate(settings.asConfig(), mode); - assertThat(predicate.apply("checkstyle")).isTrue(); - assertThat(predicate.apply("pmd")).isTrue(); - assertThat(predicate.apply("cobertura")).isFalse(); - } - - @Test - public void test_exclusions_without_any_inclusions() { - when(mode.isPreview()).thenReturn(true); - settings.setProperty(CoreProperties.PREVIEW_EXCLUDE_PLUGINS, "checkstyle,pmd,findbugs"); - ScannerPluginPredicate predicate = new ScannerPluginPredicate(settings.asConfig(), mode); - assertThat(predicate.apply("checkstyle")).isFalse(); - assertThat(predicate.apply("pmd")).isFalse(); - assertThat(predicate.apply("cobertura")).isTrue(); - } - - @Test - public void trim_inclusions_and_exclusions() { - settings - .setProperty(CoreProperties.PREVIEW_INCLUDE_PLUGINS, "checkstyle, pmd, findbugs") - .setProperty(CoreProperties.PREVIEW_EXCLUDE_PLUGINS, "cobertura, pmd"); - ScannerPluginPredicate predicate = new ScannerPluginPredicate(settings.asConfig(), mode); - assertThat(predicate.apply("pmd")).isTrue(); - } - -} diff --git a/sonar-scanner-engine/src/test/java/org/sonar/scanner/issue/DefaultProjectIssuesTest.java b/sonar-scanner-engine/src/test/java/org/sonar/scanner/issue/DefaultProjectIssuesTest.java deleted file mode 100644 index cc8e8806a49..00000000000 --- a/sonar-scanner-engine/src/test/java/org/sonar/scanner/issue/DefaultProjectIssuesTest.java +++ /dev/null @@ -1,76 +0,0 @@ -/* - * SonarQube - * Copyright (C) 2009-2019 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.scanner.issue; - -import com.google.common.collect.Lists; -import java.util.Arrays; -import java.util.List; -import org.junit.Test; -import org.sonar.api.issue.Issue; -import org.sonar.api.rule.RuleKey; -import org.sonar.api.rule.Severity; -import org.sonar.core.issue.DefaultIssue; -import org.sonar.scanner.issue.tracking.TrackedIssue; - -import static org.assertj.core.api.Assertions.assertThat; -import static org.mockito.Mockito.mock; -import static org.mockito.Mockito.when; - -public class DefaultProjectIssuesTest { - - static final RuleKey SQUID_RULE_KEY = RuleKey.of("squid", "AvoidCycle"); - - IssueCache cache = mock(IssueCache.class); - DefaultProjectIssues projectIssues = new DefaultProjectIssues(cache); - - @Test - public void should_get_all_issues() { - DefaultIssue issueOnModule = new DefaultIssue().setKey("1").setRuleKey(SQUID_RULE_KEY).setComponentKey("org.apache:struts-core"); - DefaultIssue issueInModule = new DefaultIssue().setKey("2").setRuleKey(SQUID_RULE_KEY).setComponentKey("org.apache:struts-core:Action"); - DefaultIssue resolvedIssueInModule = new DefaultIssue().setKey("3").setRuleKey(SQUID_RULE_KEY).setComponentKey("org.apache:struts-core:Action") - .setResolution(Issue.RESOLUTION_FIXED); - - DefaultIssue issueOnRoot = new DefaultIssue().setKey("4").setRuleKey(SQUID_RULE_KEY).setSeverity(Severity.CRITICAL).setComponentKey("org.apache:struts"); - DefaultIssue issueInRoot = new DefaultIssue().setKey("5").setRuleKey(SQUID_RULE_KEY).setSeverity(Severity.CRITICAL).setComponentKey("org.apache:struts:FileInRoot"); - when(cache.all()).thenReturn(Arrays.<TrackedIssue>asList( - toTrackedIssue(issueOnRoot), toTrackedIssue(issueInRoot), - toTrackedIssue(issueOnModule), toTrackedIssue(issueInModule), toTrackedIssue(resolvedIssueInModule) - )); - - // unresolved issues - List<Issue> issues = Lists.newArrayList(projectIssues.issues()); - assertThat(issues).containsOnly(issueOnRoot, issueInRoot, issueInModule, issueOnModule); - - List<Issue> resolvedIssues = Lists.newArrayList(projectIssues.resolvedIssues()); - assertThat(resolvedIssues).containsOnly(resolvedIssueInModule); - } - - private TrackedIssue toTrackedIssue(DefaultIssue issue) { - TrackedIssue trackedIssue = new TrackedIssue(); - - trackedIssue.setKey(issue.key()); - trackedIssue.setRuleKey(issue.ruleKey()); - trackedIssue.setComponentKey(issue.componentKey()); - trackedIssue.setSeverity(issue.severity()); - trackedIssue.setResolution(issue.resolution()); - - return trackedIssue; - } -} diff --git a/sonar-scanner-engine/src/test/java/org/sonar/scanner/issue/IssueCacheTest.java b/sonar-scanner-engine/src/test/java/org/sonar/scanner/issue/IssueCacheTest.java deleted file mode 100644 index 9cf44b19354..00000000000 --- a/sonar-scanner-engine/src/test/java/org/sonar/scanner/issue/IssueCacheTest.java +++ /dev/null @@ -1,95 +0,0 @@ -/* - * SonarQube - * Copyright (C) 2009-2019 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.scanner.issue; - -import com.google.common.base.Function; -import com.google.common.collect.Collections2; -import com.google.common.collect.ImmutableList; -import java.util.Collection; -import java.util.List; -import javax.annotation.Nullable; -import org.junit.Test; -import org.sonar.api.rule.Severity; -import org.sonar.scanner.index.AbstractCachesTest; -import org.sonar.scanner.issue.tracking.TrackedIssue; - -import static org.assertj.core.api.Assertions.assertThat; - -public class IssueCacheTest extends AbstractCachesTest { - - @Test - public void should_add_new_issue() { - IssueCache cache = new IssueCache(caches); - TrackedIssue issue1 = createIssue("111", "org.struts.Action", null); - TrackedIssue issue2 = createIssue("222", "org.struts.Action", null); - TrackedIssue issue3 = createIssue("333", "org.struts.Filter", null); - issue3.setAssignee("foo"); - cache.put(issue1).put(issue2).put(issue3); - - assertThat(issueKeys(cache.byComponent("org.struts.Action"))).containsOnly("111", "222"); - assertThat(issueKeys(cache.byComponent("org.struts.Filter"))).containsOnly("333"); - assertThat(cache.byComponent("org.struts.Filter").iterator().next().assignee()).isEqualTo("foo"); - } - - @Test - public void should_update_existing_issue() { - IssueCache cache = new IssueCache(caches); - TrackedIssue issue = createIssue("111", "org.struts.Action", Severity.BLOCKER); - cache.put(issue); - - issue.setSeverity(Severity.MINOR); - cache.put(issue); - - List<TrackedIssue> issues = ImmutableList.copyOf(cache.byComponent("org.struts.Action")); - assertThat(issues).hasSize(1); - TrackedIssue reloaded = issues.iterator().next(); - assertThat(reloaded.key()).isEqualTo("111"); - assertThat(reloaded.severity()).isEqualTo(Severity.MINOR); - } - - @Test - public void should_get_all_issues() { - IssueCache cache = new IssueCache(caches); - TrackedIssue issue1 = createIssue("111", "org.struts.Action", Severity.BLOCKER); - TrackedIssue issue2 = createIssue("222", "org.struts.Filter", Severity.INFO); - cache.put(issue1).put(issue2); - - List<TrackedIssue> issues = ImmutableList.copyOf(cache.all()); - assertThat(issues).containsOnly(issue1, issue2); - } - - private Collection<String> issueKeys(Iterable<TrackedIssue> issues) { - return Collections2.transform(ImmutableList.copyOf(issues), new Function<TrackedIssue, String>() { - @Override - public String apply(@Nullable TrackedIssue issue) { - return issue.key(); - } - }); - } - - private TrackedIssue createIssue(String key, String componentKey, String severity) { - TrackedIssue issue = new TrackedIssue(); - issue.setKey(key); - issue.setComponentKey(componentKey); - issue.setSeverity(severity); - - return issue; - } -} diff --git a/sonar-scanner-engine/src/test/java/org/sonar/scanner/issue/TrackedIssueAdapterTest.java b/sonar-scanner-engine/src/test/java/org/sonar/scanner/issue/TrackedIssueAdapterTest.java deleted file mode 100644 index cd792332e59..00000000000 --- a/sonar-scanner-engine/src/test/java/org/sonar/scanner/issue/TrackedIssueAdapterTest.java +++ /dev/null @@ -1,81 +0,0 @@ -/* - * SonarQube - * Copyright (C) 2009-2019 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.scanner.issue; - -import java.util.Date; -import org.junit.Test; -import org.sonar.api.issue.Issue; -import org.sonar.api.rule.RuleKey; -import org.sonar.scanner.issue.tracking.TrackedIssue; - -import static org.assertj.core.api.Assertions.assertThat; - -public class TrackedIssueAdapterTest { - - @Test - public void improve_coverage() { - Date creationDate = new Date(); - TrackedIssue trackedIssue = new TrackedIssue() - .setKey("XYZ123") - .setComponentKey("foo") - .setRuleKey(RuleKey.of("repo", "rule")) - .setSeverity("MAJOR") - .setMessage("msg") - .setStartLine(1) - .setGap(2.0) - .setStatus("RESOLVED") - .setResolution("FIXED") - .setAssignee("tata") - .setNew(true) - .setCreationDate(creationDate); - Issue issue = new TrackedIssueAdapter(trackedIssue); - assertThat(issue.key()).isEqualTo("XYZ123"); - assertThat(issue.componentKey()).isEqualTo("foo"); - assertThat(issue.ruleKey()).isEqualTo(RuleKey.of("repo", "rule")); - assertThat(issue.severity()).isEqualTo("MAJOR"); - assertThat(issue.message()).isEqualTo("msg"); - assertThat(issue.line()).isEqualTo(1); - assertThat(issue.gap()).isEqualTo(2.0); - assertThat(issue.status()).isEqualTo("RESOLVED"); - assertThat(issue.resolution()).isEqualTo("FIXED"); - assertThat(issue.assignee()).isEqualTo("tata"); - assertThat(issue.isNew()).isTrue(); - assertThat(issue.attribute("foo")).isNull(); - assertThat(issue.creationDate()).isEqualTo(creationDate); - assertThat(issue.language()).isNull(); - assertThat(issue.updateDate()).isNull(); - assertThat(issue.closeDate()).isNull(); - assertThat(issue.authorLogin()).isNull(); - assertThat(issue.comments()).isEmpty(); - assertThat(issue.effort()).isNull(); - assertThat(issue.projectKey()).isNull(); - assertThat(issue.projectUuid()).isNull(); - assertThat(issue.componentUuid()).isNull(); - assertThat(issue.tags()).isEmpty(); - - assertThat(issue).isNotEqualTo(null); - assertThat(issue).isNotEqualTo("Foo"); - assertThat(issue).isEqualTo(new TrackedIssueAdapter(trackedIssue)); - assertThat(issue.hashCode()).isEqualTo(trackedIssue.key().hashCode()); - assertThat(issue).isNotEqualTo(new TrackedIssueAdapter(new TrackedIssue() - .setKey("another"))); - } - -} diff --git a/sonar-scanner-engine/src/test/java/org/sonar/scanner/issue/tracking/DefaultServerLineHashesLoaderTest.java b/sonar-scanner-engine/src/test/java/org/sonar/scanner/issue/tracking/DefaultServerLineHashesLoaderTest.java deleted file mode 100644 index 940db1a4fa6..00000000000 --- a/sonar-scanner-engine/src/test/java/org/sonar/scanner/issue/tracking/DefaultServerLineHashesLoaderTest.java +++ /dev/null @@ -1,76 +0,0 @@ -/* - * SonarQube - * Copyright (C) 2009-2019 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.scanner.issue.tracking; - -import java.io.StringReader; -import java.net.URI; -import java.net.URISyntaxException; -import org.junit.Before; -import org.junit.Rule; -import org.junit.Test; -import org.junit.rules.ExpectedException; -import org.sonar.api.utils.HttpDownloader; -import org.sonar.scanner.WsTestUtil; -import org.sonar.scanner.bootstrap.ScannerWsClient; - -import static org.assertj.core.api.Assertions.assertThat; -import static org.mockito.Mockito.mock; - -public class DefaultServerLineHashesLoaderTest { - private ScannerWsClient wsClient; - - @Rule - public ExpectedException thrown = ExpectedException.none(); - - @Before - public void before() { - wsClient = mock(ScannerWsClient.class); - } - - @Test - public void should_download_source_from_ws_if_preview_mode() { - WsTestUtil.mockReader(wsClient, new StringReader("ae12\n\n43fb")); - ServerLineHashesLoader lastSnapshots = new DefaultServerLineHashesLoader(wsClient); - - String[] hashes = lastSnapshots.getLineHashes("myproject:org/foo/Bar.c"); - assertThat(hashes).containsOnly("ae12", "", "43fb"); - WsTestUtil.verifyCall(wsClient, "/api/sources/hash?key=myproject%3Aorg%2Ffoo%2FBar.c"); - } - - @Test - public void should_download_source_with_space_from_ws_if_preview_mode() { - WsTestUtil.mockReader(wsClient, new StringReader("ae12\n\n43fb")); - ServerLineHashesLoader lastSnapshots = new DefaultServerLineHashesLoader(wsClient); - - String[] hashes = lastSnapshots.getLineHashes("myproject:org/foo/Foo Bar.c"); - assertThat(hashes).containsOnly("ae12", "", "43fb"); - WsTestUtil.verifyCall(wsClient, "/api/sources/hash?key=myproject%3Aorg%2Ffoo%2FFoo+Bar.c"); - } - - @Test - public void should_fail_to_download_source_from_ws() throws URISyntaxException { - WsTestUtil.mockException(wsClient, new HttpDownloader.HttpException(new URI(""), 500)); - ServerLineHashesLoader lastSnapshots = new DefaultServerLineHashesLoader(wsClient); - - thrown.expect(HttpDownloader.HttpException.class); - lastSnapshots.getLineHashes("foo"); - } - -} diff --git a/sonar-scanner-engine/src/test/java/org/sonar/scanner/issue/tracking/RollingFileHashesTest.java b/sonar-scanner-engine/src/test/java/org/sonar/scanner/issue/tracking/RollingFileHashesTest.java deleted file mode 100644 index 6221576206b..00000000000 --- a/sonar-scanner-engine/src/test/java/org/sonar/scanner/issue/tracking/RollingFileHashesTest.java +++ /dev/null @@ -1,43 +0,0 @@ -/* - * SonarQube - * Copyright (C) 2009-2019 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.scanner.issue.tracking; - -import org.junit.Test; - -import static org.apache.commons.codec.digest.DigestUtils.md5Hex; -import static org.assertj.core.api.Assertions.assertThat; - -public class RollingFileHashesTest { - - @Test - public void test_equals() { - RollingFileHashes a = RollingFileHashes.create(FileHashes.create(new String[] {md5Hex("line0"), md5Hex("line1"), md5Hex("line2")}), 1); - RollingFileHashes b = RollingFileHashes.create(FileHashes.create(new String[] {md5Hex("line0"), md5Hex("line1"), md5Hex("line2"), md5Hex("line3")}), 1); - - assertThat(a.getHash(1) == b.getHash(1)).isTrue(); - assertThat(a.getHash(2) == b.getHash(2)).isTrue(); - assertThat(a.getHash(3) == b.getHash(3)).isFalse(); - - RollingFileHashes c = RollingFileHashes.create(FileHashes.create(new String[] {md5Hex("line-1"), md5Hex("line0"), md5Hex("line1"), md5Hex("line2"), md5Hex("line3")}), 1); - assertThat(a.getHash(1) == c.getHash(2)).isFalse(); - assertThat(a.getHash(2) == c.getHash(3)).isTrue(); - } - -} diff --git a/sonar-scanner-engine/src/test/java/org/sonar/scanner/issue/tracking/SourceHashHolderTest.java b/sonar-scanner-engine/src/test/java/org/sonar/scanner/issue/tracking/SourceHashHolderTest.java deleted file mode 100644 index 590d4119282..00000000000 --- a/sonar-scanner-engine/src/test/java/org/sonar/scanner/issue/tracking/SourceHashHolderTest.java +++ /dev/null @@ -1,139 +0,0 @@ -/* - * SonarQube - * Copyright (C) 2009-2019 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.scanner.issue.tracking; - -import java.io.File; -import java.nio.charset.StandardCharsets; -import java.nio.file.Files; -import org.apache.commons.io.FileUtils; -import org.junit.Before; -import org.junit.Rule; -import org.junit.Test; -import org.junit.rules.TemporaryFolder; -import org.mockito.Mockito; -import org.sonar.api.batch.fs.InputFile; -import org.sonar.api.batch.fs.internal.DefaultInputFile; -import org.sonar.api.batch.fs.internal.DefaultInputProject; - -import static org.apache.commons.codec.digest.DigestUtils.md5Hex; -import static org.assertj.core.api.Assertions.assertThat; -import static org.mockito.Mockito.mock; -import static org.mockito.Mockito.verify; -import static org.mockito.Mockito.when; - -public class SourceHashHolderTest { - - @Rule - public TemporaryFolder temp = new TemporaryFolder(); - - SourceHashHolder sourceHashHolder; - - ServerLineHashesLoader lastSnapshots; - DefaultInputFile file; - - private File ioFile; - private DefaultInputProject project; - - @Before - public void setUp() throws Exception { - lastSnapshots = mock(ServerLineHashesLoader.class); - file = mock(DefaultInputFile.class); - ioFile = temp.newFile(); - when(file.file()).thenReturn(ioFile); - when(file.path()).thenReturn(ioFile.toPath()); - when(file.inputStream()).thenAnswer(i -> Files.newInputStream(ioFile.toPath())); - when(file.lines()).thenReturn(1); - when(file.charset()).thenReturn(StandardCharsets.UTF_8); - - project = mock(DefaultInputProject.class); - sourceHashHolder = new SourceHashHolder(project, file, lastSnapshots); - } - - @Test - public void should_lazy_load_line_hashes() throws Exception { - final String source = "source"; - FileUtils.write(ioFile, source + "\n", StandardCharsets.UTF_8); - when(file.lines()).thenReturn(2); - - assertThat(sourceHashHolder.getHashedSource().getHash(1)).isEqualTo(md5Hex(source)); - assertThat(sourceHashHolder.getHashedSource().getHash(2)).isEqualTo(""); - - assertThat(sourceHashHolder.getHashedSource().getHash(1)).isEqualTo(md5Hex(source)); - } - - @Test - public void should_lazy_load_reference_hashes_when_status_changed() throws Exception { - final String source = "source"; - FileUtils.write(ioFile, source, StandardCharsets.UTF_8); - when(project.getKeyWithBranch()).thenReturn("foo"); - when(file.getProjectRelativePath()).thenReturn("src/Foo.java"); - String key = "foo:src/Foo.java"; - when(file.status()).thenReturn(InputFile.Status.CHANGED); - when(lastSnapshots.getLineHashes(key)).thenReturn(new String[] {md5Hex(source)}); - - assertThat(sourceHashHolder.getHashedReference().getHash(1)).isEqualTo(md5Hex(source)); - verify(lastSnapshots).getLineHashes(key); - - assertThat(sourceHashHolder.getHashedReference().getHash(1)).isEqualTo(md5Hex(source)); - Mockito.verifyNoMoreInteractions(lastSnapshots); - } - - @Test - public void should_lazy_load_reference_hashes_when_status_changed_on_branch() throws Exception { - final String source = "source"; - FileUtils.write(ioFile, source, StandardCharsets.UTF_8); - when(project.getKeyWithBranch()).thenReturn("foo:myBranch"); - when(file.getProjectRelativePath()).thenReturn("src/Foo.java"); - String key = "foo:myBranch:src/Foo.java"; - when(file.status()).thenReturn(InputFile.Status.CHANGED); - when(lastSnapshots.getLineHashes(key)).thenReturn(new String[] {md5Hex(source)}); - - assertThat(sourceHashHolder.getHashedReference().getHash(1)).isEqualTo(md5Hex(source)); - verify(lastSnapshots).getLineHashes(key); - - assertThat(sourceHashHolder.getHashedReference().getHash(1)).isEqualTo(md5Hex(source)); - Mockito.verifyNoMoreInteractions(lastSnapshots); - } - - @Test - public void should_not_load_reference_hashes_when_status_same() throws Exception { - final String source = "source"; - String key = "foo:src/Foo.java"; - FileUtils.write(ioFile, source, StandardCharsets.UTF_8); - when(file.key()).thenReturn(key); - when(file.status()).thenReturn(InputFile.Status.SAME); - - assertThat(sourceHashHolder.getHashedReference().getHash(1)).isEqualTo(md5Hex(source)); - Mockito.verifyNoMoreInteractions(lastSnapshots); - } - - @Test - public void no_reference_hashes_when_status_added() throws Exception { - final String source = "source"; - String key = "foo:src/Foo.java"; - FileUtils.write(ioFile, source, StandardCharsets.UTF_8); - when(file.key()).thenReturn(key); - when(file.status()).thenReturn(InputFile.Status.ADDED); - - assertThat(sourceHashHolder.getHashedReference()).isNull(); - Mockito.verifyNoMoreInteractions(lastSnapshots); - } - -} diff --git a/sonar-scanner-engine/src/test/java/org/sonar/scanner/issue/tracking/TrackedIssueTest.java b/sonar-scanner-engine/src/test/java/org/sonar/scanner/issue/tracking/TrackedIssueTest.java deleted file mode 100644 index 8ce90570187..00000000000 --- a/sonar-scanner-engine/src/test/java/org/sonar/scanner/issue/tracking/TrackedIssueTest.java +++ /dev/null @@ -1,47 +0,0 @@ -/* - * SonarQube - * Copyright (C) 2009-2019 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.scanner.issue.tracking; - -import org.junit.Test; - -import static org.assertj.core.api.Assertions.assertThat; - -public class TrackedIssueTest { - @Test - public void round_trip() { - TrackedIssue issue = new TrackedIssue(); - issue.setStartLine(15); - - assertThat(issue.getLine()).isEqualTo(15); - assertThat(issue.startLine()).isEqualTo(15); - } - - @Test - public void hashes() { - String[] hashArr = new String[] { - "hash1", "hash2", "hash3" - }; - - FileHashes hashes = FileHashes.create(hashArr); - TrackedIssue issue = new TrackedIssue(hashes); - issue.setStartLine(1); - assertThat(issue.getLineHash()).isEqualTo("hash1"); - } -} diff --git a/sonar-scanner-engine/src/test/java/org/sonar/scanner/mediumtest/ScannerMediumTester.java b/sonar-scanner-engine/src/test/java/org/sonar/scanner/mediumtest/ScannerMediumTester.java index cbae1f9c0ba..22fbca0205b 100644 --- a/sonar-scanner-engine/src/test/java/org/sonar/scanner/mediumtest/ScannerMediumTester.java +++ b/sonar-scanner-engine/src/test/java/org/sonar/scanner/mediumtest/ScannerMediumTester.java @@ -35,7 +35,6 @@ import java.util.LinkedList; import java.util.List; import java.util.Map; import java.util.Properties; -import java.util.function.Consumer; import java.util.function.Supplier; import javax.annotation.CheckForNull; import javax.annotation.Nullable; @@ -52,15 +51,12 @@ import org.sonar.batch.bootstrapper.Batch; import org.sonar.batch.bootstrapper.EnvironmentInformation; import org.sonar.batch.bootstrapper.LogOutput; import org.sonar.scanner.bootstrap.GlobalAnalysisMode; -import org.sonar.scanner.issue.tracking.ServerLineHashesLoader; -import org.sonar.scanner.protocol.input.ScannerInput.ServerIssue; import org.sonar.scanner.repository.FileData; import org.sonar.scanner.repository.MetricsRepository; import org.sonar.scanner.repository.MetricsRepositoryLoader; import org.sonar.scanner.repository.ProjectRepositories; import org.sonar.scanner.repository.ProjectRepositoriesLoader; import org.sonar.scanner.repository.QualityProfileLoader; -import org.sonar.scanner.repository.ServerIssuesLoader; import org.sonar.scanner.repository.SingleProjectRepository; import org.sonar.scanner.repository.settings.GlobalSettingsLoader; import org.sonar.scanner.repository.settings.ProjectSettingsLoader; @@ -89,10 +85,8 @@ public class ScannerMediumTester extends ExternalResource { private final FakeBranchConfiguration branchConfiguration = new FakeBranchConfiguration(); private final FakeProjectRepositoriesLoader projectRefProvider = new FakeProjectRepositoriesLoader(); private final FakePluginInstaller pluginInstaller = new FakePluginInstaller(); - private final FakeServerIssuesLoader serverIssues = new FakeServerIssuesLoader(); private final FakeGlobalSettingsLoader globalSettingsLoader = new FakeGlobalSettingsLoader(); private final FakeProjectSettingsLoader projectSettingsLoader = new FakeProjectSettingsLoader(); - private final FakeServerLineHashesLoader serverLineHashes = new FakeServerLineHashesLoader(); private final FakeRulesLoader rulesLoader = new FakeRulesLoader(); private final FakeQualityProfileLoader qualityProfiles = new FakeQualityProfileLoader(); private final FakeActiveRulesLoader activeRules = new FakeActiveRulesLoader(); @@ -186,11 +180,6 @@ public class ScannerMediumTester extends ExternalResource { return this; } - public ScannerMediumTester setPreviousAnalysisDate(Date previousAnalysis) { - projectRefProvider.setLastAnalysisDate(previousAnalysis); - return this; - } - public ScannerMediumTester bootstrapProperties(Map<String, String> props) { globalProperties.putAll(props); return this; @@ -221,16 +210,6 @@ public class ScannerMediumTester extends ExternalResource { return this; } - public ScannerMediumTester setLastBuildDate(Date d) { - projectRefProvider.setLastAnalysisDate(d); - return this; - } - - public ScannerMediumTester mockServerIssue(ServerIssue issue) { - serverIssues.getServerIssues().add(issue); - return this; - } - public ScannerMediumTester addGlobalServerSettings(String key, String value) { globalSettingsLoader.getGlobalSettings().put(key, value); return this; @@ -241,11 +220,6 @@ public class ScannerMediumTester extends ExternalResource { return this; } - public ScannerMediumTester mockLineHashes(String fileKey, String[] lineHashes) { - serverLineHashes.byKey.put(fileKey, lineHashes); - return this; - } - @Override protected void before() throws Throwable { try { @@ -312,7 +286,6 @@ public class ScannerMediumTester extends ExternalResource { tester.branchConfigurationLoader, tester.projectRefProvider, tester.activeRules, - tester.serverIssues, tester.globalSettingsLoader, tester.projectSettingsLoader, result) @@ -383,11 +356,10 @@ public class ScannerMediumTester extends ExternalResource { private static class FakeProjectRepositoriesLoader implements ProjectRepositoriesLoader { private Map<String, FileData> fileDataMap = Maps.newHashMap(); - private Date lastAnalysisDate; @Override - public ProjectRepositories load(String projectKey, boolean isIssuesMode, @Nullable String branchBase) { - return new SingleProjectRepository(fileDataMap, lastAnalysisDate); + public ProjectRepositories load(String projectKey, @Nullable String branchBase) { + return new SingleProjectRepository(fileDataMap); } public FakeProjectRepositoriesLoader addFileData(String path, FileData fileData) { @@ -395,11 +367,6 @@ public class ScannerMediumTester extends ExternalResource { return this; } - public FakeProjectRepositoriesLoader setLastAnalysisDate(Date d) { - lastAnalysisDate = d; - return this; - } - } private static class FakeBranchConfiguration implements BranchConfiguration { @@ -489,22 +456,6 @@ public class ScannerMediumTester extends ExternalResource { } } - private static class FakeServerIssuesLoader implements ServerIssuesLoader { - - private List<ServerIssue> serverIssues = new ArrayList<>(); - - public List<ServerIssue> getServerIssues() { - return serverIssues; - } - - @Override - public void load(String componentKey, Consumer<ServerIssue> consumer) { - for (ServerIssue serverIssue : serverIssues) { - consumer.accept(serverIssue); - } - } - } - private static class FakeGlobalSettingsLoader implements GlobalSettingsLoader { private Map<String, String> globalSettings = new HashMap<>(); @@ -533,16 +484,4 @@ public class ScannerMediumTester extends ExternalResource { } } - private static class FakeServerLineHashesLoader implements ServerLineHashesLoader { - private Map<String, String[]> byKey = new HashMap<>(); - - @Override - public String[] getLineHashes(String fileKey) { - if (byKey.containsKey(fileKey)) { - return byKey.get(fileKey); - } else { - throw new IllegalStateException("You forgot to mock line hashes for " + fileKey); - } - } - } } diff --git a/sonar-scanner-engine/src/test/java/org/sonar/scanner/mediumtest/fs/NoLanguagesPluginsMediumTest.java b/sonar-scanner-engine/src/test/java/org/sonar/scanner/mediumtest/fs/NoLanguagesPluginsMediumTest.java index ab3baf428fc..78a6cb14dcc 100644 --- a/sonar-scanner-engine/src/test/java/org/sonar/scanner/mediumtest/fs/NoLanguagesPluginsMediumTest.java +++ b/sonar-scanner-engine/src/test/java/org/sonar/scanner/mediumtest/fs/NoLanguagesPluginsMediumTest.java @@ -36,8 +36,7 @@ public class NoLanguagesPluginsMediumTest { public ExpectedException exception = ExpectedException.none(); @Rule - public ScannerMediumTester tester = new ScannerMediumTester() - .setPreviousAnalysisDate(null); + public ScannerMediumTester tester = new ScannerMediumTester(); @Test public void testNoLanguagePluginsInstalled() throws Exception { diff --git a/sonar-scanner-engine/src/test/java/org/sonar/scanner/mediumtest/fs/ProjectBuilderMediumTest.java b/sonar-scanner-engine/src/test/java/org/sonar/scanner/mediumtest/fs/ProjectBuilderMediumTest.java index 4a2beacd4dc..f61411b4898 100644 --- a/sonar-scanner-engine/src/test/java/org/sonar/scanner/mediumtest/fs/ProjectBuilderMediumTest.java +++ b/sonar-scanner-engine/src/test/java/org/sonar/scanner/mediumtest/fs/ProjectBuilderMediumTest.java @@ -22,7 +22,6 @@ package org.sonar.scanner.mediumtest.fs; import com.google.common.collect.ImmutableMap; import java.io.File; import java.io.IOException; -import java.util.Date; import java.util.List; import org.apache.commons.io.FileUtils; import org.hamcrest.BaseMatcher; @@ -33,8 +32,8 @@ import org.junit.rules.ExpectedException; import org.junit.rules.TemporaryFolder; import org.sonar.api.batch.bootstrap.ProjectBuilder; import org.sonar.api.utils.MessageException; -import org.sonar.scanner.mediumtest.ScannerMediumTester; import org.sonar.scanner.mediumtest.AnalysisResult; +import org.sonar.scanner.mediumtest.ScannerMediumTester; import org.sonar.scanner.protocol.output.ScannerReport.Issue; import org.sonar.xoo.XooPlugin; import org.sonar.xoo.rule.XooRulesDefinition; @@ -60,7 +59,6 @@ public class ProjectBuilderMediumTest { .registerPlugin("xoo", new XooPluginWithBuilder(projectBuilder)) .addRules(new XooRulesDefinition()) .addDefaultQProfile("xoo", "Sonar Way") - .setPreviousAnalysisDate(new Date()) .addActiveRule("xoo", "OneIssuePerLine", null, "One issue per line", "MAJOR", "OneIssuePerLine.internal", "xoo"); private class XooPluginWithBuilder extends XooPlugin { @@ -102,12 +100,8 @@ public class ProjectBuilderMediumTest { tester.newAnalysis() .properties(ImmutableMap.<String, String>builder() - .put("sonar.task", "scan") .put("sonar.projectBaseDir", baseDir.getAbsolutePath()) .put("sonar.projectKey", "com.foo.project") - .put("sonar.projectName", "Foo Project") - .put("sonar.projectVersion", "1.0-SNAPSHOT") - .put("sonar.projectDescription", "Description of Foo Project") .put("sonar.sources", ".") .put("sonar.xoo.enableProjectBuilder", "true") .build()) @@ -121,12 +115,8 @@ public class ProjectBuilderMediumTest { AnalysisResult result = tester.newAnalysis() .properties(ImmutableMap.<String, String>builder() - .put("sonar.task", "scan") .put("sonar.projectBaseDir", baseDir.getAbsolutePath()) .put("sonar.projectKey", "com.foo.project") - .put("sonar.projectName", "Foo Project") - .put("sonar.projectVersion", "1.0-SNAPSHOT") - .put("sonar.projectDescription", "Description of Foo Project") .put("sonar.sources", ".") .put("sonar.verbose", "true") .put("sonar.xoo.enableProjectBuilder", "true") @@ -150,13 +140,9 @@ public class ProjectBuilderMediumTest { exception.expectMessage("is not a valid branch name"); tester.newAnalysis() .properties(ImmutableMap.<String, String>builder() - .put("sonar.task", "scan") .put("sonar.projectBaseDir", baseDir.getAbsolutePath()) .put("sonar.projectKey", "com.foo.project") - .put("sonar.projectName", "Foo Project") .put("sonar.branch", "branch\n") - .put("sonar.projectVersion", "1.0-SNAPSHOT") - .put("sonar.projectDescription", "Description of Foo Project") .put("sonar.sources", ".") .put("sonar.xoo.enableProjectBuilder", "true") .build()) @@ -169,12 +155,8 @@ public class ProjectBuilderMediumTest { AnalysisResult result = tester.newAnalysis() .properties(ImmutableMap.<String, String>builder() - .put("sonar.task", "scan") .put("sonar.projectBaseDir", baseDir.getAbsolutePath()) .put("sonar.projectKey", "com.foo.project") - .put("sonar.projectName", "Foo Project") - .put("sonar.projectVersion", "1.0-SNAPSHOT") - .put("sonar.projectDescription", "Description of Foo Project") .put("sonar.branch", "my-branch") .put("sonar.sources", ".") .put("sonar.xoo.enableProjectBuilder", "true") diff --git a/sonar-scanner-engine/src/test/java/org/sonar/scanner/mediumtest/issues/PreviewMediumTest.java b/sonar-scanner-engine/src/test/java/org/sonar/scanner/mediumtest/issues/PreviewMediumTest.java new file mode 100644 index 00000000000..3427e32fc0f --- /dev/null +++ b/sonar-scanner-engine/src/test/java/org/sonar/scanner/mediumtest/issues/PreviewMediumTest.java @@ -0,0 +1,70 @@ +/* + * SonarQube + * Copyright (C) 2009-2019 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.scanner.mediumtest.issues; + +import com.google.common.collect.ImmutableMap; +import org.junit.Rule; +import org.junit.Test; +import org.junit.rules.ExpectedException; +import org.sonar.api.utils.MessageException; +import org.sonar.api.utils.log.LogTester; +import org.sonar.scanner.mediumtest.ScannerMediumTester; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.fail; + +public class PreviewMediumTest { + + @Rule + public ExpectedException thrown = ExpectedException.none(); + + @Rule + public LogTester logTester = new LogTester(); + + @Rule + public ScannerMediumTester tester = new ScannerMediumTester(); + + @Test + public void failWhenUsingPreviewMode() throws Exception { + try { + tester.newAnalysis() + .properties(ImmutableMap.<String, String>builder() + .put("sonar.analysis.mode", "preview").build()) + .execute(); + fail("Expected exception"); + } catch (Exception e) { + assertThat(e).isInstanceOf(MessageException.class).hasMessage("The preview mode, along with the 'sonar.analysis.mode' parameter, is no more supported. You should stop using this parameter."); + } + } + + @Test + public void failWhenUsingIssuesMode() throws Exception { + try { + tester.newAnalysis() + .properties(ImmutableMap.<String, String>builder() + .put("sonar.analysis.mode", "issues").build()) + .execute(); + fail("Expected exception"); + } catch (Exception e) { + assertThat(e).isInstanceOf(MessageException.class).hasMessage("The preview mode, along with the 'sonar.analysis.mode' parameter, is no more supported. You should stop using this parameter."); + } + } + +} diff --git a/sonar-scanner-engine/src/test/java/org/sonar/scanner/mediumtest/issuesmode/EmptyFileTest.java b/sonar-scanner-engine/src/test/java/org/sonar/scanner/mediumtest/issuesmode/EmptyFileTest.java deleted file mode 100644 index b87d034afed..00000000000 --- a/sonar-scanner-engine/src/test/java/org/sonar/scanner/mediumtest/issuesmode/EmptyFileTest.java +++ /dev/null @@ -1,80 +0,0 @@ -/* - * SonarQube - * Copyright (C) 2009-2019 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.scanner.mediumtest.issuesmode; - -import com.google.common.collect.ImmutableMap; -import java.io.File; -import java.util.Date; -import org.apache.commons.io.FileUtils; -import org.apache.commons.io.filefilter.FileFilterUtils; -import org.junit.Rule; -import org.junit.Test; -import org.junit.rules.TemporaryFolder; -import org.sonar.api.CoreProperties; -import org.sonar.api.utils.log.LogTester; -import org.sonar.scanner.issue.tracking.TrackedIssue; -import org.sonar.scanner.mediumtest.ScannerMediumTester; -import org.sonar.scanner.mediumtest.AnalysisResult; -import org.sonar.xoo.XooPlugin; -import org.sonar.xoo.rule.XooRulesDefinition; - -import static org.assertj.core.api.Assertions.assertThat; - -public class EmptyFileTest { - - @Rule - public TemporaryFolder temp = new TemporaryFolder(); - - @Rule - public LogTester logTester = new LogTester(); - - @Rule - public ScannerMediumTester tester = new ScannerMediumTester() - .bootstrapProperties(ImmutableMap.of(CoreProperties.ANALYSIS_MODE, CoreProperties.ANALYSIS_MODE_ISSUES)) - .registerPlugin("xoo", new XooPlugin()) - .addRules(new XooRulesDefinition()) - .addDefaultQProfile("xoo", "Sonar Way") - .addActiveRule("xoo", "OneIssuePerLine", null, "One issue per line", "MAJOR", "my/internal/key", "xoo") - .setPreviousAnalysisDate(new Date()); - - @Test - public void testIssueTrackingWithIssueOnEmptyFile() throws Exception { - File projectDir = copyProject("test-resources/mediumtest/xoo/sample-with-empty-file"); - - AnalysisResult result = tester - .newAnalysis(new File(projectDir, "sonar-project.properties")) - .property("sonar.xoo.internalKey", "my/internal/key") - .execute(); - - for (TrackedIssue i : result.trackedIssues()) { - System.out.println(i.startLine() + " " + i.getMessage()); - } - - assertThat(result.trackedIssues()).hasSize(11); - } - - private File copyProject(String path) throws Exception { - File projectDir = temp.newFolder(); - File originalProjectDir = new File(path); - FileUtils.copyDirectory(originalProjectDir, projectDir, FileFilterUtils.notFileFilter(FileFilterUtils.nameFileFilter(".sonar"))); - return projectDir; - } - -} diff --git a/sonar-scanner-engine/src/test/java/org/sonar/scanner/mediumtest/issuesmode/IssueModeAndReportsMediumTest.java b/sonar-scanner-engine/src/test/java/org/sonar/scanner/mediumtest/issuesmode/IssueModeAndReportsMediumTest.java deleted file mode 100644 index 2e58d577288..00000000000 --- a/sonar-scanner-engine/src/test/java/org/sonar/scanner/mediumtest/issuesmode/IssueModeAndReportsMediumTest.java +++ /dev/null @@ -1,204 +0,0 @@ -/* - * SonarQube - * Copyright (C) 2009-2019 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.scanner.mediumtest.issuesmode; - -import com.google.common.collect.ImmutableMap; -import java.io.File; -import java.io.IOException; -import java.text.ParseException; -import java.text.SimpleDateFormat; -import java.util.Date; -import org.apache.commons.codec.digest.DigestUtils; -import org.apache.commons.io.FileUtils; -import org.apache.commons.io.filefilter.FileFilterUtils; -import org.apache.commons.lang.StringUtils; -import org.assertj.core.api.Condition; -import org.junit.Rule; -import org.junit.Test; -import org.junit.rules.TemporaryFolder; -import org.sonar.api.CoreProperties; -import org.sonar.api.utils.log.LogTester; -import org.sonar.api.utils.log.LoggerLevel; -import org.sonar.scanner.issue.tracking.TrackedIssue; -import org.sonar.scanner.mediumtest.ScannerMediumTester; -import org.sonar.scanner.mediumtest.AnalysisResult; -import org.sonar.scanner.protocol.Constants.Severity; -import org.sonar.scanner.protocol.input.ScannerInput.ServerIssue; -import org.sonar.xoo.XooPlugin; -import org.sonar.xoo.rule.XooRulesDefinition; - -import static org.assertj.core.api.Assertions.assertThat; - -public class IssueModeAndReportsMediumTest { - - @org.junit.Rule - public TemporaryFolder temp = new TemporaryFolder(); - - @org.junit.Rule - public LogTester logTester = new LogTester(); - - private static SimpleDateFormat sdf = new SimpleDateFormat("dd/MM/yyyy"); - - private static Long date(String date) { - try { - return sdf.parse(date).getTime(); - } catch (ParseException e) { - throw new IllegalStateException(e); - } - } - - @Rule - public ScannerMediumTester tester = new ScannerMediumTester() - .bootstrapProperties(ImmutableMap.of(CoreProperties.ANALYSIS_MODE, CoreProperties.ANALYSIS_MODE_ISSUES)) - .registerPlugin("xoo", new XooPlugin()) - .addDefaultQProfile("xoo", "Sonar Way") - .addRules(new XooRulesDefinition()) - .addActiveRule("xoo", "OneIssuePerLine", null, "One issue per line", "MAJOR", null, "xoo") - .addActiveRule("xoo", "OneIssueOnDirPerFile", null, "OneIssueOnDirPerFile", "MAJOR", null, "xoo") - .addActiveRule("xoo", "OneIssuePerModule", null, "OneIssuePerModule", "MAJOR", null, "xoo") - .setPreviousAnalysisDate(new Date()) - // Existing issue that is still detected - .mockServerIssue(ServerIssue.newBuilder().setKey("xyz") - .setModuleKey("sample") - .setPath("xources/hello/HelloJava.xoo") - .setRuleRepository("xoo") - .setRuleKey("OneIssuePerLine") - .setLine(1) - .setSeverity(Severity.MAJOR) - .setCreationDate(date("14/03/2004")) - .setChecksum(DigestUtils.md5Hex("packagehello;")) - .setStatus("OPEN") - .build()) - // Existing issue that is no more detected (will be closed) - .mockServerIssue(ServerIssue.newBuilder().setKey("resolved") - .setModuleKey("sample") - .setPath("xources/hello/HelloJava.xoo") - .setRuleRepository("xoo") - .setRuleKey("OneIssuePerLine") - .setLine(1) - .setSeverity(Severity.MAJOR) - .setCreationDate(date("14/03/2004")) - .setChecksum(DigestUtils.md5Hex("dontexist")) - .setStatus("OPEN") - .build()) - // Existing issue on project that is still detected - .mockServerIssue(ServerIssue.newBuilder().setKey("resolved-on-project") - .setModuleKey("sample") - .setRuleRepository("xoo") - .setRuleKey("OneIssuePerModule") - .setSeverity(Severity.CRITICAL) - .setCreationDate(date("14/03/2004")) - .setStatus("OPEN") - .build()); - - private File copyProject(String path) throws Exception { - File projectDir = temp.newFolder(); - File originalProjectDir = new File(path); - FileUtils.copyDirectory(originalProjectDir, projectDir, FileFilterUtils.notFileFilter(FileFilterUtils.nameFileFilter(".sonar"))); - return projectDir; - } - - @Test - public void testIssueTracking() throws Exception { - File projectDir = copyProject("test-resources/mediumtest/xoo/sample"); - - AnalysisResult result = tester - .newAnalysis(new File(projectDir, "sonar-project.properties")) - .execute(); - - int newIssues = 0; - int openIssues = 0; - int resolvedIssue = 0; - for (TrackedIssue issue : result.trackedIssues()) { - System.out - .println(issue.getMessage() + " " + issue.key() + " " + issue.getRuleKey() + " " + issue.isNew() + " " + issue.resolution() + " " + issue.componentKey() + " " - + issue.startLine()); - if (issue.isNew()) { - newIssues++; - } else if (issue.resolution() != null) { - resolvedIssue++; - } else { - openIssues++; - } - } - System.out.println("new: " + newIssues + " open: " + openIssues + " resolved " + resolvedIssue); - assertThat(newIssues).isEqualTo(16); - assertThat(openIssues).isEqualTo(2); - assertThat(resolvedIssue).isEqualTo(1); - - // progress report - String logs = StringUtils.join(logTester.logs(LoggerLevel.INFO), "\n"); - - assertThat(logs).contains("Performing issue tracking"); - assertThat(logs).contains("4/4 components tracked"); - - // assert that original fields of a matched issue are kept - assertThat(result.trackedIssues()).haveExactly(1, new Condition<TrackedIssue>() { - @Override - public boolean matches(TrackedIssue value) { - return value.isNew() == false - && "resolved-on-project".equals(value.key()) - && "OPEN".equals(value.status()) - && new Date(date("14/03/2004")).equals(value.creationDate()); - } - }); - } - - @Test - public void testPostJob() throws Exception { - File projectDir = copyProject("test-resources/mediumtest/xoo/sample"); - - tester - .newAnalysis(new File(projectDir, "sonar-project.properties")) - .property("sonar.xoo.enablePostJob", "true") - .execute(); - - assertThat(logTester.logs()).contains("Resolved issues: 1", "Open issues: 18"); - } - - @Test - public void noSyntaxHighlightingInIssuesMode() throws IOException { - - File baseDir = temp.newFolder(); - File srcDir = new File(baseDir, "src"); - srcDir.mkdir(); - - File xooFile = new File(srcDir, "sample.xoo"); - File xoohighlightingFile = new File(srcDir, "sample.xoo.highlighting"); - FileUtils.write(xooFile, "Sample xoo\ncontent plop"); - FileUtils.write(xoohighlightingFile, "0:10:s\n11:18:k"); - - AnalysisResult result = tester.newAnalysis() - .properties(ImmutableMap.<String, String>builder() - .put("sonar.projectBaseDir", baseDir.getAbsolutePath()) - .put("sonar.projectKey", "com.foo.project") - .put("sonar.projectName", "Foo Project") - .put("sonar.projectVersion", "1.0-SNAPSHOT") - .put("sonar.projectDescription", "Description of Foo Project") - .put("sonar.sources", "src") - .build()) - .execute(); - - assertThat(result.getReportReader().hasSyntaxHighlighting(1)).isFalse(); - assertThat(result.getReportReader().hasSyntaxHighlighting(2)).isFalse(); - assertThat(result.getReportReader().hasSyntaxHighlighting(3)).isFalse(); - } - -} diff --git a/sonar-scanner-engine/src/test/java/org/sonar/scanner/mediumtest/issuesmode/NoPreviousAnalysisTest.java b/sonar-scanner-engine/src/test/java/org/sonar/scanner/mediumtest/issuesmode/NoPreviousAnalysisTest.java deleted file mode 100644 index 8a113d8382e..00000000000 --- a/sonar-scanner-engine/src/test/java/org/sonar/scanner/mediumtest/issuesmode/NoPreviousAnalysisTest.java +++ /dev/null @@ -1,72 +0,0 @@ -/* - * SonarQube - * Copyright (C) 2009-2019 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.scanner.mediumtest.issuesmode; - -import com.google.common.collect.ImmutableMap; -import java.io.File; -import org.apache.commons.io.FileUtils; -import org.apache.commons.io.filefilter.FileFilterUtils; -import org.junit.Rule; -import org.junit.Test; -import org.junit.rules.TemporaryFolder; -import org.sonar.api.CoreProperties; -import org.sonar.api.utils.log.LogTester; -import org.sonar.scanner.mediumtest.ScannerMediumTester; -import org.sonar.scanner.mediumtest.AnalysisResult; -import org.sonar.xoo.XooPlugin; -import org.sonar.xoo.rule.XooRulesDefinition; - -import static org.assertj.core.api.Assertions.assertThat; - -public class NoPreviousAnalysisTest { - @Rule - public TemporaryFolder temp = new TemporaryFolder(); - - @Rule - public LogTester logTester = new LogTester(); - - @Rule - public ScannerMediumTester tester = new ScannerMediumTester() - .bootstrapProperties(ImmutableMap.of(CoreProperties.ANALYSIS_MODE, CoreProperties.ANALYSIS_MODE_ISSUES)) - .registerPlugin("xoo", new XooPlugin()) - .addRules(new XooRulesDefinition()) - .addDefaultQProfile("xoo", "Sonar Way") - .addActiveRule("xoo", "OneIssuePerLine", null, "One issue per line", "MAJOR", "my/internal/key", "xoo") - .setPreviousAnalysisDate(null); - - @Test - public void testIssueTrackingWithIssueOnEmptyFile() throws Exception { - File projectDir = copyProject("test-resources/mediumtest/xoo/sample"); - - AnalysisResult result = tester - .newAnalysis(new File(projectDir, "sonar-project.properties")) - .execute(); - - assertThat(result.trackedIssues()).hasSize(14); - - } - - private File copyProject(String path) throws Exception { - File projectDir = temp.newFolder(); - File originalProjectDir = new File(path); - FileUtils.copyDirectory(originalProjectDir, projectDir, FileFilterUtils.notFileFilter(FileFilterUtils.nameFileFilter(".sonar"))); - return projectDir; - } -} diff --git a/sonar-scanner-engine/src/test/java/org/sonar/scanner/mediumtest/issuesmode/ScanOnlyChangedTest.java b/sonar-scanner-engine/src/test/java/org/sonar/scanner/mediumtest/issuesmode/ScanOnlyChangedTest.java deleted file mode 100644 index 1c31872a3a8..00000000000 --- a/sonar-scanner-engine/src/test/java/org/sonar/scanner/mediumtest/issuesmode/ScanOnlyChangedTest.java +++ /dev/null @@ -1,230 +0,0 @@ -/* - * SonarQube - * Copyright (C) 2009-2019 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.scanner.mediumtest.issuesmode; - -import com.google.common.collect.ImmutableMap; -import java.io.File; -import java.io.IOException; -import java.nio.charset.StandardCharsets; -import java.nio.file.Files; -import java.nio.file.Path; -import java.nio.file.Paths; -import java.text.ParseException; -import java.text.SimpleDateFormat; -import java.util.Arrays; -import java.util.Collection; -import java.util.Date; -import org.apache.commons.codec.digest.DigestUtils; -import org.apache.commons.io.FileUtils; -import org.apache.commons.io.filefilter.FileFilterUtils; -import org.assertj.core.api.Condition; -import org.junit.Before; -import org.junit.Rule; -import org.junit.Test; -import org.junit.rules.TemporaryFolder; -import org.junit.runner.RunWith; -import org.junit.runners.Parameterized; -import org.junit.runners.Parameterized.Parameter; -import org.junit.runners.Parameterized.Parameters; -import org.sonar.api.CoreProperties; -import org.sonar.api.batch.fs.internal.FileMetadata; -import org.sonar.api.utils.log.LogTester; -import org.sonar.scanner.issue.tracking.TrackedIssue; -import org.sonar.scanner.mediumtest.AnalysisResult; -import org.sonar.scanner.mediumtest.ScannerMediumTester; -import org.sonar.scanner.mediumtest.ScannerMediumTester.AnalysisBuilder; -import org.sonar.scanner.protocol.Constants.Severity; -import org.sonar.scanner.protocol.input.ScannerInput.ServerIssue; -import org.sonar.scanner.repository.FileData; -import org.sonar.xoo.XooPlugin; -import org.sonar.xoo.rule.XooRulesDefinition; - -import static org.assertj.core.api.Assertions.assertThat; - -@RunWith(Parameterized.class) -public class ScanOnlyChangedTest { - private static SimpleDateFormat sdf = new SimpleDateFormat("dd/MM/yyyy"); - - /* - * Run with branch too to reproduce SONAR-9141 and SONAR-9160 - */ - @Parameters(name = "branch enabled:{0} projectKey: {1}") - public static Collection<Object[]> data() { - return Arrays.asList(new Object[][] { - {false, "sample"}, {true, "sample:branch"}, {false, "sample:project"} - }); - } - - @Parameter(0) - public boolean branch; - - @Parameter(1) - public String projectKey; - - @Rule - public TemporaryFolder temp = new TemporaryFolder(); - - @Rule - public LogTester logTester = new LogTester(); - - @Rule - public ScannerMediumTester tester = new ScannerMediumTester() - .bootstrapProperties(ImmutableMap.of(CoreProperties.ANALYSIS_MODE, CoreProperties.ANALYSIS_MODE_ISSUES)) - .registerPlugin("xoo", new XooPlugin()) - .addDefaultQProfile("xoo", "Sonar Way") - .addRules(new XooRulesDefinition()) - .addActiveRule("xoo", "OneIssuePerLine", null, "One issue per line", "MAJOR", null, "xoo") - .addActiveRule("xoo", "OneIssueOnDirPerFile", null, "OneIssueOnDirPerFile", "MAJOR", null, "xoo") - .addActiveRule("xoo", "OneIssuePerModule", null, "OneIssuePerModule", "MAJOR", null, "xoo"); - - @Before - public void prepare() throws IOException { - String filePath = "xources/hello/HelloJava.xoo"; - Path path = Paths.get("test-resources/mediumtest/xoo/sample/" + filePath); - String md5sum = new FileMetadata() - .readMetadata(Files.newInputStream(path), StandardCharsets.UTF_8, filePath) - .hash(); - - tester - // this will cause the file to have status==SAME - .addFileData(filePath, new FileData(md5sum, null)) - .setPreviousAnalysisDate(new Date()) - // Existing issue that is copied - .mockServerIssue(ServerIssue.newBuilder().setKey("xyz") - .setModuleKey(projectKey) - .setMsg("One issue per Line copied") - .setPath("xources/hello/HelloJava.xoo") - .setRuleRepository("xoo") - .setRuleKey("OneIssuePerLine") - .setLine(1) - .setSeverity(Severity.MAJOR) - .setCreationDate(date("14/03/2004")) - .setChecksum(DigestUtils.md5Hex("packagehello;")) - .setStatus("OPEN") - .build()) - // Existing issue on project that is still detected - .mockServerIssue(ServerIssue.newBuilder().setKey("resolved-on-project") - .setModuleKey(projectKey) - .setRuleRepository("xoo") - .setRuleKey("OneIssuePerModule") - .setSeverity(Severity.CRITICAL) - .setCreationDate(date("14/03/2004")) - .setStatus("OPEN") - .build()); - } - - private File copyProject(String path) throws Exception { - File projectDir = temp.newFolder(); - File originalProjectDir = new File(path); - FileUtils.copyDirectory(originalProjectDir, projectDir, FileFilterUtils.notFileFilter(FileFilterUtils.nameFileFilter(".sonar"))); - return projectDir; - } - - @Test - public void testScanOnlyChangedFiles() throws Exception { - File projectDir = copyProject("test-resources/mediumtest/xoo/sample"); - - AnalysisBuilder analysisBuilder = tester - .newAnalysis(new File(projectDir, "sonar-project.properties")) - .property("sonar.report.export.path", "report.json"); - if (branch) { - analysisBuilder.property("sonar.branch", "branch"); - } else { - analysisBuilder.property("sonar.projectKey", projectKey); - } - - AnalysisResult result = analysisBuilder.execute(); - /* - * We have: - * 6 new issues per line (open) in helloscala.xoo - * 2 new issues per file in helloscala.xoo / ClassOneTest.xoo - * 1 server issue (open, not new) copied from server in HelloJava.xoo (this file is unchanged) - * 1 manual issue (open, not new) in HelloJava.xoo - * 1 existing issue on the project (open, not new) - */ - assertNumberIssues(result, 8, 2, 0); - - // should only have server issues (HelloJava.xoo should not have been analyzed) - assertNumberIssuesOnFile(result, "HelloJava.xoo", 1); - } - - @Test - public void testScanAll() throws Exception { - File projectDir = copyProject("test-resources/mediumtest/xoo/sample"); - - AnalysisBuilder analysisBuilder = tester - .newAnalysis(new File(projectDir, "sonar-project.properties")) - .property("sonar.scanAllFiles", "true"); - if (branch) { - analysisBuilder.property("sonar.branch", "branch"); - } else { - analysisBuilder.property("sonar.projectKey", projectKey); - } - - AnalysisResult result = analysisBuilder.execute(); - - assertNumberIssues(result, 16, 2, 0); - - /* - * 8 new per line - */ - assertNumberIssuesOnFile(result, "HelloJava.xoo", 8); - } - - private static void assertNumberIssuesOnFile(AnalysisResult result, final String fileNameEndsWith, int issues) { - assertThat(result.trackedIssues()).haveExactly(issues, new Condition<TrackedIssue>() { - @Override - public boolean matches(TrackedIssue value) { - return value.componentKey().endsWith(fileNameEndsWith); - } - }); - } - - private static void assertNumberIssues(AnalysisResult result, int expectedNew, int expectedOpen, int expectedResolved) { - int newIssues = 0; - int openIssues = 0; - int resolvedIssue = 0; - for (TrackedIssue issue : result.trackedIssues()) { - System.out - .println(issue.getMessage() + " " + issue.key() + " " + issue.getRuleKey() + " " + issue.isNew() + " " + issue.resolution() + " " + issue.componentKey() + " " - + issue.startLine()); - if (issue.isNew()) { - newIssues++; - } else if (issue.resolution() != null) { - resolvedIssue++; - } else { - openIssues++; - } - } - - System.out.println("new: " + newIssues + " open: " + openIssues + " resolved " + resolvedIssue); - assertThat(newIssues).isEqualTo(expectedNew); - assertThat(openIssues).isEqualTo(expectedOpen); - assertThat(resolvedIssue).isEqualTo(expectedResolved); - } - - private static Long date(String date) { - try { - return sdf.parse(date).getTime(); - } catch (ParseException e) { - throw new IllegalStateException(e); - } - } -} diff --git a/sonar-scanner-engine/src/test/java/org/sonar/scanner/postjob/DefaultPostJobContextTest.java b/sonar-scanner-engine/src/test/java/org/sonar/scanner/postjob/DefaultPostJobContextTest.java index b9a9e561c0e..6399495c410 100644 --- a/sonar-scanner-engine/src/test/java/org/sonar/scanner/postjob/DefaultPostJobContextTest.java +++ b/sonar-scanner-engine/src/test/java/org/sonar/scanner/postjob/DefaultPostJobContextTest.java @@ -20,68 +20,39 @@ package org.sonar.scanner.postjob; import java.io.IOException; -import java.util.Arrays; import org.junit.Before; import org.junit.Test; import org.sonar.api.batch.AnalysisMode; -import org.sonar.api.batch.fs.internal.TestInputFileBuilder; -import org.sonar.api.batch.postjob.issue.PostJobIssue; -import org.sonar.api.batch.rule.Severity; import org.sonar.api.config.internal.MapSettings; -import org.sonar.scanner.issue.IssueCache; -import org.sonar.scanner.issue.tracking.TrackedIssue; -import org.sonar.scanner.scan.branch.BranchConfiguration; -import org.sonar.scanner.scan.filesystem.InputComponentStore; import static org.assertj.core.api.Assertions.assertThat; import static org.mockito.Mockito.mock; -import static org.mockito.Mockito.when; public class DefaultPostJobContextTest { - private IssueCache issueCache; - private InputComponentStore componentStore; private DefaultPostJobContext context; private MapSettings settings; private AnalysisMode analysisMode; @Before public void setUp() throws IOException { - issueCache = mock(IssueCache.class); - componentStore = new InputComponentStore(mock(BranchConfiguration.class)); settings = new MapSettings(); analysisMode = mock(AnalysisMode.class); - context = new DefaultPostJobContext(settings.asConfig(), settings, issueCache, componentStore, analysisMode); + context = new DefaultPostJobContext(settings.asConfig(), settings, analysisMode); } @Test - public void testIssues() throws IOException { - when(analysisMode.isIssues()).thenReturn(true); - + public void testSettings() { assertThat(context.settings()).isSameAs(settings); + } - TrackedIssue defaultIssue = new TrackedIssue(); - defaultIssue.setComponentKey("foo:src/Foo.php"); - defaultIssue.setGap(2.0); - defaultIssue.setNew(true); - defaultIssue.setKey("xyz"); - defaultIssue.setStartLine(1); - defaultIssue.setMessage("msg"); - defaultIssue.setSeverity("BLOCKER"); - when(issueCache.all()).thenReturn(Arrays.asList(defaultIssue)); - - PostJobIssue issue = context.issues().iterator().next(); - assertThat(issue.componentKey()).isEqualTo("foo:src/Foo.php"); - assertThat(issue.isNew()).isTrue(); - assertThat(issue.key()).isEqualTo("xyz"); - assertThat(issue.line()).isEqualTo(1); - assertThat(issue.message()).isEqualTo("msg"); - assertThat(issue.severity()).isEqualTo(Severity.BLOCKER); - assertThat(issue.inputComponent()).isNull(); - - String moduleKey = "foo"; - componentStore.put(moduleKey, new TestInputFileBuilder(moduleKey, "src/Foo.php").build()); - assertThat(issue.inputComponent()).isNotNull(); + @Test(expected=UnsupportedOperationException.class) + public void testIssues() { + context.issues(); + } + @Test(expected=UnsupportedOperationException.class) + public void testResolvedIssues() { + context.resolvedIssues(); } } diff --git a/sonar-scanner-engine/src/test/java/org/sonar/scanner/repository/DefaultProjectRepositoriesLoaderTest.java b/sonar-scanner-engine/src/test/java/org/sonar/scanner/repository/DefaultProjectRepositoriesLoaderTest.java index fff3d8a7830..6448b845c96 100644 --- a/sonar-scanner-engine/src/test/java/org/sonar/scanner/repository/DefaultProjectRepositoriesLoaderTest.java +++ b/sonar-scanner-engine/src/test/java/org/sonar/scanner/repository/DefaultProjectRepositoriesLoaderTest.java @@ -60,7 +60,7 @@ public class DefaultProjectRepositoriesLoaderTest { @Test public void continueOnError() { when(wsClient.call(any(WsRequest.class))).thenThrow(IllegalStateException.class); - ProjectRepositories proj = loader.load(PROJECT_KEY, false, null); + ProjectRepositories proj = loader.load(PROJECT_KEY, null); assertThat(proj.exists()).isEqualTo(false); } @@ -69,7 +69,7 @@ public class DefaultProjectRepositoriesLoaderTest { InputStream is = mock(InputStream.class); when(is.read()).thenThrow(IOException.class); WsTestUtil.mockStream(wsClient, "/batch/project.protobuf?key=foo%3F", is); - loader.load(PROJECT_KEY, false, null); + loader.load(PROJECT_KEY, null); } @Test(expected = IllegalStateException.class) @@ -77,7 +77,7 @@ public class DefaultProjectRepositoriesLoaderTest { HttpException http = new HttpException("url", 403, null); IllegalStateException e = new IllegalStateException("http error", http); WsTestUtil.mockException(wsClient, e); - loader.load(PROJECT_KEY, false, null); + loader.load(PROJECT_KEY, null); } @Test @@ -88,26 +88,17 @@ public class DefaultProjectRepositoriesLoaderTest { HttpException http = new HttpException("uri", 403, null); MessageException e = MessageException.of("http error", http); WsTestUtil.mockException(wsClient, e); - loader.load(PROJECT_KEY, false, null); - } - - @Test - public void passIssuesModeParameter() { - loader.load(PROJECT_KEY, false, null); - WsTestUtil.verifyCall(wsClient, "/batch/project.protobuf?key=foo%3F"); - - loader.load(PROJECT_KEY, true, null); - WsTestUtil.verifyCall(wsClient, "/batch/project.protobuf?key=foo%3F&issues_mode=true"); + loader.load(PROJECT_KEY, null); } @Test public void deserializeResponse() throws IOException { - loader.load(PROJECT_KEY, false, null); + loader.load(PROJECT_KEY, null); } @Test public void passAndEncodeProjectKeyParameter() { - loader.load(PROJECT_KEY, false, null); + loader.load(PROJECT_KEY, null); WsTestUtil.verifyCall(wsClient, "/batch/project.protobuf?key=foo%3F"); } @@ -123,12 +114,12 @@ public class DefaultProjectRepositoriesLoaderTest { @Test public void readRealResponse() throws IOException { InputStream is = getTestResource("project.protobuf"); - WsTestUtil.mockStream(wsClient, "/batch/project.protobuf?key=org.sonarsource.github%3Asonar-github-plugin&issues_mode=true", is); + WsTestUtil.mockStream(wsClient, "/batch/project.protobuf?key=org.sonarsource.github%3Asonar-github-plugin", is); DefaultInputFile file = mock(DefaultInputFile.class); when(file.getModuleRelativePath()).thenReturn("src/test/java/org/sonar/plugins/github/PullRequestIssuePostJobTest.java"); - ProjectRepositories proj = loader.load("org.sonarsource.github:sonar-github-plugin", true, null); + ProjectRepositories proj = loader.load("org.sonarsource.github:sonar-github-plugin", null); FileData fd = proj.fileData("org.sonarsource.github:sonar-github-plugin", file); assertThat(fd.revision()).isEqualTo("27bf2c54633d05c5df402bbe09471fe43bd9e2e5"); diff --git a/sonar-scanner-engine/src/test/java/org/sonar/scanner/repository/DefaultServerIssuesLoaderTest.java b/sonar-scanner-engine/src/test/java/org/sonar/scanner/repository/DefaultServerIssuesLoaderTest.java deleted file mode 100644 index 11c0a2bdbb6..00000000000 --- a/sonar-scanner-engine/src/test/java/org/sonar/scanner/repository/DefaultServerIssuesLoaderTest.java +++ /dev/null @@ -1,76 +0,0 @@ -/* - * SonarQube - * Copyright (C) 2009-2019 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.scanner.repository; - -import java.io.ByteArrayInputStream; -import java.io.ByteArrayOutputStream; -import java.io.IOException; -import java.io.InputStream; -import java.util.ArrayList; -import java.util.List; -import java.util.function.Consumer; -import org.junit.Before; -import org.junit.Test; -import org.sonar.scanner.WsTestUtil; -import org.sonar.scanner.bootstrap.ScannerWsClient; -import org.sonar.scanner.protocol.input.ScannerInput.ServerIssue; - -import static org.assertj.core.api.Assertions.assertThat; -import static org.mockito.Mockito.mock; -import static org.mockito.Mockito.when; - -public class DefaultServerIssuesLoaderTest { - private DefaultServerIssuesLoader loader; - private ScannerWsClient wsClient; - - @Before - public void prepare() { - wsClient = mock(ScannerWsClient.class); - loader = new DefaultServerIssuesLoader(wsClient); - } - - @Test - public void loadFromWs() throws Exception { - ByteArrayOutputStream bos = new ByteArrayOutputStream(); - - ServerIssue.newBuilder().setKey("ab1").build() - .writeDelimitedTo(bos); - ServerIssue.newBuilder().setKey("ab2").build() - .writeDelimitedTo(bos); - - InputStream is = new ByteArrayInputStream(bos.toByteArray()); - WsTestUtil.mockStream(wsClient, "/batch/issues.protobuf?key=foo", is); - - final List<ServerIssue> result = new ArrayList<>(); - loader.load("foo", issue -> { - result.add(issue); - }); - - assertThat(result).extracting("key").containsExactly("ab1", "ab2"); - } - - @Test(expected = IllegalStateException.class) - public void testError() throws IOException { - InputStream is = mock(InputStream.class); - when(is.read()).thenThrow(IOException.class); - WsTestUtil.mockStream(wsClient, "/batch/issues.protobuf?key=foo", is); - loader.load("foo", mock(Consumer.class)); - } -} diff --git a/sonar-scanner-engine/src/test/java/org/sonar/scanner/repository/MultiModuleProjectRepositoryTest.java b/sonar-scanner-engine/src/test/java/org/sonar/scanner/repository/MultiModuleProjectRepositoryTest.java index 443a2c96bfe..06335c3af97 100644 --- a/sonar-scanner-engine/src/test/java/org/sonar/scanner/repository/MultiModuleProjectRepositoryTest.java +++ b/sonar-scanner-engine/src/test/java/org/sonar/scanner/repository/MultiModuleProjectRepositoryTest.java @@ -19,7 +19,6 @@ */ package org.sonar.scanner.repository; -import java.util.Date; import java.util.Map; import org.assertj.core.util.Maps; import org.junit.Before; @@ -34,13 +33,12 @@ public class MultiModuleProjectRepositoryTest { @Before public void setUp() { - Date lastAnalysisDate = new Date(); - SingleProjectRepository repository1 = new SingleProjectRepository(Maps.newHashMap("/Abc.java", new FileData("123", "456")), lastAnalysisDate); - SingleProjectRepository repository2 = new SingleProjectRepository(Maps.newHashMap("/Def.java", new FileData("567", "321")), lastAnalysisDate); + SingleProjectRepository repository1 = new SingleProjectRepository(Maps.newHashMap("/Abc.java", new FileData("123", "456"))); + SingleProjectRepository repository2 = new SingleProjectRepository(Maps.newHashMap("/Def.java", new FileData("567", "321"))); Map<String, SingleProjectRepository> moduleRepositories = Maps.newHashMap("module1", repository1); moduleRepositories.put("module2", repository2); - repository = new MultiModuleProjectRepository(moduleRepositories, lastAnalysisDate); + repository = new MultiModuleProjectRepository(moduleRepositories); } @Test diff --git a/sonar-scanner-engine/src/test/java/org/sonar/scanner/repository/ProjectRepositoriesProviderTest.java b/sonar-scanner-engine/src/test/java/org/sonar/scanner/repository/ProjectRepositoriesProviderTest.java index fced08351f1..2fb5056e0c9 100644 --- a/sonar-scanner-engine/src/test/java/org/sonar/scanner/repository/ProjectRepositoriesProviderTest.java +++ b/sonar-scanner-engine/src/test/java/org/sonar/scanner/repository/ProjectRepositoriesProviderTest.java @@ -20,20 +20,17 @@ package org.sonar.scanner.repository; import com.google.common.collect.Maps; -import java.util.Date; import java.util.Map; import org.junit.Before; import org.junit.Test; import org.mockito.Mock; import org.mockito.MockitoAnnotations; -import org.sonar.scanner.bootstrap.GlobalAnalysisMode; import org.sonar.scanner.bootstrap.ProcessedScannerProperties; import org.sonar.scanner.scan.branch.BranchConfiguration; import static org.assertj.core.api.Assertions.assertThat; import static org.mockito.ArgumentMatchers.any; import static org.mockito.ArgumentMatchers.eq; -import static org.mockito.Mockito.times; import static org.mockito.Mockito.verify; import static org.mockito.Mockito.verifyNoMoreInteractions; import static org.mockito.Mockito.when; @@ -47,8 +44,6 @@ public class ProjectRepositoriesProviderTest { @Mock private ProcessedScannerProperties props; @Mock - private GlobalAnalysisMode mode; - @Mock private BranchConfiguration branchConfiguration; @Before @@ -57,7 +52,7 @@ public class ProjectRepositoriesProviderTest { Map<String, FileData> fileMap = Maps.newHashMap(); - project = new SingleProjectRepository(fileMap, new Date()); + project = new SingleProjectRepository(fileMap); provider = new ProjectRepositoriesProvider(); when(props.getKeyWithBranch()).thenReturn("key"); @@ -65,25 +60,21 @@ public class ProjectRepositoriesProviderTest { @Test public void testValidation() { - when(mode.isIssues()).thenReturn(true); - when(loader.load(eq("key"), eq(true), any())).thenReturn(project); + when(loader.load(eq("key"), any())).thenReturn(project); - provider.provide(loader, props, mode, branchConfiguration); + provider.provide(loader, props, branchConfiguration); } @Test public void testAssociated() { - when(mode.isIssues()).thenReturn(false); - when(loader.load(eq("key"), eq(false), any())).thenReturn(project); + when(loader.load(eq("key"), any())).thenReturn(project); - ProjectRepositories repo = provider.provide(loader, props, mode, branchConfiguration); + ProjectRepositories repo = provider.provide(loader, props, branchConfiguration); assertThat(repo.exists()).isEqualTo(true); - assertThat(repo.lastAnalysisDate()).isNotNull(); - verify(mode, times(1)).isIssues(); verify(props).getKeyWithBranch(); - verify(loader).load(eq("key"), eq(false), eq(null)); - verifyNoMoreInteractions(loader, props, mode); + verify(loader).load(eq("key"), eq(null)); + verifyNoMoreInteractions(loader, props); } } diff --git a/sonar-scanner-engine/src/test/java/org/sonar/scanner/repository/SingleProjectRepositoryTest.java b/sonar-scanner-engine/src/test/java/org/sonar/scanner/repository/SingleProjectRepositoryTest.java index 11059f5d5f4..747e292c044 100644 --- a/sonar-scanner-engine/src/test/java/org/sonar/scanner/repository/SingleProjectRepositoryTest.java +++ b/sonar-scanner-engine/src/test/java/org/sonar/scanner/repository/SingleProjectRepositoryTest.java @@ -34,7 +34,7 @@ public class SingleProjectRepositoryTest { @Before public void setUp() { Date lastAnalysisDate = new Date(); - repository = new SingleProjectRepository(Maps.newHashMap("/Abc.java", new FileData("123", "456")), lastAnalysisDate); + repository = new SingleProjectRepository(Maps.newHashMap("/Abc.java", new FileData("123", "456"))); } @Test diff --git a/sonar-scanner-engine/src/test/java/org/sonar/scanner/scan/filesystem/SameInputFilePredicateTest.java b/sonar-scanner-engine/src/test/java/org/sonar/scanner/scan/filesystem/SameInputFilePredicateTest.java deleted file mode 100644 index 15398b42a08..00000000000 --- a/sonar-scanner-engine/src/test/java/org/sonar/scanner/scan/filesystem/SameInputFilePredicateTest.java +++ /dev/null @@ -1,52 +0,0 @@ -/* - * SonarQube - * Copyright (C) 2009-2019 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.scanner.scan.filesystem; - -import java.io.IOException; -import org.junit.Before; -import org.junit.Rule; -import org.junit.Test; -import org.junit.rules.TemporaryFolder; -import org.sonar.api.batch.fs.FilePredicates; -import org.sonar.api.batch.fs.InputFile; -import org.sonar.api.batch.fs.internal.DefaultFilePredicates; - -import static org.assertj.core.api.Assertions.assertThat; - -public class SameInputFilePredicateTest { - - @Rule - public TemporaryFolder temp = new TemporaryFolder(); - - FilePredicates predicates; - - @Before - public void before() throws IOException { - predicates = new DefaultFilePredicates(temp.newFolder().toPath()); - } - - @Test - public void testHasExplicitFilterOnStatus() { - assertThat(SameInputFilePredicate.hasExplicitFilterOnStatus(predicates.all())).isFalse(); - assertThat(SameInputFilePredicate.hasExplicitFilterOnStatus(predicates.hasStatus(InputFile.Status.ADDED))).isTrue(); - assertThat(SameInputFilePredicate.hasExplicitFilterOnStatus(predicates.hasAnyStatus())).isTrue(); - assertThat(SameInputFilePredicate.hasExplicitFilterOnStatus(predicates.and(predicates.all(), predicates.hasStatus(InputFile.Status.ADDED)))).isTrue(); - } -} diff --git a/sonar-scanner-engine/src/test/java/org/sonar/scanner/scan/filesystem/StatusDetectionTest.java b/sonar-scanner-engine/src/test/java/org/sonar/scanner/scan/filesystem/StatusDetectionTest.java index c73f303965b..b5ed22c270f 100644 --- a/sonar-scanner-engine/src/test/java/org/sonar/scanner/scan/filesystem/StatusDetectionTest.java +++ b/sonar-scanner-engine/src/test/java/org/sonar/scanner/scan/filesystem/StatusDetectionTest.java @@ -32,15 +32,11 @@ import org.sonar.scanner.repository.SingleProjectRepository; import org.sonar.scanner.scm.ScmChangedFiles; import static org.assertj.core.api.Assertions.assertThat; -import static org.mockito.Mockito.mock; -import static org.mockito.Mockito.verify; -import static org.mockito.Mockito.verifyNoMoreInteractions; -import static org.mockito.Mockito.when; public class StatusDetectionTest { @Test public void detect_status() { - SingleProjectRepository ref = new SingleProjectRepository(createFileDataPerPathMap(), null); + SingleProjectRepository ref = new SingleProjectRepository(createFileDataPerPathMap()); ScmChangedFiles changedFiles = new ScmChangedFiles(null); StatusDetection statusDetection = new StatusDetection(ref, changedFiles); @@ -51,7 +47,7 @@ public class StatusDetectionTest { @Test public void detect_status_branches_exclude() { - SingleProjectRepository ref = new SingleProjectRepository(createFileDataPerPathMap(), null); + SingleProjectRepository ref = new SingleProjectRepository(createFileDataPerPathMap()); ScmChangedFiles changedFiles = new ScmChangedFiles(Collections.emptyList()); StatusDetection statusDetection = new StatusDetection(ref, changedFiles); @@ -63,25 +59,8 @@ public class StatusDetectionTest { } @Test - public void detect_status_without_metadata() { - DefaultInputFile mockedFile = mock(DefaultInputFile.class); - when(mockedFile.getProjectRelativePath()).thenReturn("module/src/Foo.java"); - when(mockedFile.path()).thenReturn(Paths.get("module", "src", "Foo.java")); - - SingleProjectRepository ref = new SingleProjectRepository(createFileDataPerPathMap(), null); - ScmChangedFiles changedFiles = new ScmChangedFiles(Collections.singletonList(Paths.get("module", "src", "Foo.java"))); - StatusDetection statusDetection = new StatusDetection(ref, changedFiles); - - assertThat(statusDetection.getStatusWithoutMetadata("foo", mockedFile)).isEqualTo(InputFile.Status.ADDED); - - verify(mockedFile).path(); - verify(mockedFile).getProjectRelativePath(); - verifyNoMoreInteractions(mockedFile); - } - - @Test public void detect_status_branches_confirm() { - SingleProjectRepository ref = new SingleProjectRepository(createFileDataPerPathMap(), null); + SingleProjectRepository ref = new SingleProjectRepository(createFileDataPerPathMap()); ScmChangedFiles changedFiles = new ScmChangedFiles(Collections.singletonList(Paths.get("module", "src", "Foo.java"))); StatusDetection statusDetection = new StatusDetection(ref, changedFiles); diff --git a/sonar-scanner-engine/src/test/java/org/sonar/scanner/scan/report/JSONReportTest.java b/sonar-scanner-engine/src/test/java/org/sonar/scanner/scan/report/JSONReportTest.java deleted file mode 100644 index d018ad2c300..00000000000 --- a/sonar-scanner-engine/src/test/java/org/sonar/scanner/scan/report/JSONReportTest.java +++ /dev/null @@ -1,165 +0,0 @@ -/* - * SonarQube - * Copyright (C) 2009-2019 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.scanner.scan.report; - -import java.io.File; -import java.io.IOException; -import java.io.StringWriter; -import java.text.SimpleDateFormat; -import java.util.Collections; -import java.util.TimeZone; -import org.apache.commons.io.IOUtils; -import org.junit.Before; -import org.junit.Rule; -import org.junit.Test; -import org.junit.rules.TemporaryFolder; -import org.sonar.api.batch.bootstrap.ProjectDefinition; -import org.sonar.api.batch.fs.InputFile; -import org.sonar.api.batch.fs.internal.DefaultFileSystem; -import org.sonar.api.batch.fs.internal.DefaultInputFile; -import org.sonar.api.batch.fs.internal.DefaultInputProject; -import org.sonar.api.batch.fs.internal.InputModuleHierarchy; -import org.sonar.api.batch.fs.internal.TestInputFileBuilder; -import org.sonar.api.batch.rule.Rules; -import org.sonar.api.batch.rule.internal.RulesBuilder; -import org.sonar.api.config.internal.MapSettings; -import org.sonar.api.issue.Issue; -import org.sonar.api.platform.Server; -import org.sonar.api.rule.RuleKey; -import org.sonar.scanner.issue.IssueCache; -import org.sonar.scanner.issue.tracking.TrackedIssue; -import org.sonar.scanner.scan.branch.BranchConfiguration; -import org.sonar.scanner.scan.filesystem.InputComponentStore; - -import static net.javacrumbs.jsonunit.assertj.JsonAssert.assertThatJson; -import static org.assertj.core.api.Assertions.assertThat; -import static org.mockito.Mockito.mock; -import static org.mockito.Mockito.verifyZeroInteractions; -import static org.mockito.Mockito.when; - -public class JSONReportTest { - - private SimpleDateFormat SIMPLE_DATE_FORMAT = new SimpleDateFormat("yyyy-MM-dd"); - - @Rule - public TemporaryFolder temp = new TemporaryFolder(); - - private JSONReport jsonReport; - private DefaultFileSystem fs; - private Server server = mock(Server.class); - private Rules rules = mock(Rules.class); - private MapSettings settings = new MapSettings(); - private IssueCache issueCache = mock(IssueCache.class); - private InputModuleHierarchy moduleHierarchy; - - @Before - public void before() throws Exception { - moduleHierarchy = mock(InputModuleHierarchy.class); - File projectBaseDir = temp.newFolder(); - fs = new DefaultFileSystem(projectBaseDir.toPath()); - SIMPLE_DATE_FORMAT.setTimeZone(TimeZone.getTimeZone("GMT+02:00")); - when(server.getVersion()).thenReturn("3.6"); - - ProjectDefinition def = ProjectDefinition.create().setBaseDir(projectBaseDir).setWorkDir(temp.newFolder()).setKey("struts"); - DefaultInputProject project = new DefaultInputProject(def, 1); - InputComponentStore inputComponentStore = new InputComponentStore(mock(BranchConfiguration.class)); - - DefaultInputFile inputFile = new TestInputFileBuilder("struts", "src/main/java/org/apache/struts/Action.java") - .setModuleBaseDir(projectBaseDir.toPath()).build(); - inputFile.setStatus(InputFile.Status.CHANGED); - inputFile.setPublished(true); - inputComponentStore.put("struts", inputFile); - - RulesBuilder builder = new RulesBuilder(); - builder.add(RuleKey.of("squid", "AvoidCycles")).setName("Avoid Cycles"); - rules = builder.build(); - jsonReport = new JSONReport(settings.asConfig(), fs, server, rules, issueCache, project, inputComponentStore); - } - - @Test - public void should_write_json() throws Exception { - TrackedIssue issue = new TrackedIssue(); - issue.setKey("200"); - issue.setComponentKey("struts:src/main/java/org/apache/struts/Action.java"); - issue.setRuleKey(RuleKey.of("squid", "AvoidCycles")); - issue.setMessage("There are 2 cycles"); - issue.setSeverity("MINOR"); - issue.setStatus(Issue.STATUS_OPEN); - issue.setResolution(null); - issue.setStartLine(1); - issue.setEndLine(2); - issue.setStartLineOffset(3); - issue.setEndLineOffset(4); - issue.setGap(3.14); - issue.setAssignee("simon"); - issue.setCreationDate(SIMPLE_DATE_FORMAT.parse("2013-04-24")); - issue.setNew(false); - when(issueCache.all()).thenReturn(Collections.singleton(issue)); - - StringWriter writer = new StringWriter(); - jsonReport.writeJson(writer); - - assertThatJson(writer.toString()).isEqualTo(IOUtils.toString(this.getClass().getResource(this.getClass().getSimpleName() + "/report.json"))); - } - - @Test - public void should_exclude_resolved_issues() throws Exception { - RuleKey ruleKey = RuleKey.of("squid", "AvoidCycles"); - TrackedIssue issue = new TrackedIssue(); - issue.setKey("200"); - issue.setComponentKey("struts:src/main/java/org/apache/struts/Action.java"); - issue.setRuleKey(ruleKey); - issue.setStatus(Issue.STATUS_CLOSED); - issue.setResolution(Issue.RESOLUTION_FIXED); - issue.setCreationDate(SIMPLE_DATE_FORMAT.parse("2013-04-24")); - issue.setNew(false); - when(issueCache.all()).thenReturn(Collections.singleton(issue)); - - StringWriter writer = new StringWriter(); - jsonReport.writeJson(writer); - - assertThatJson(writer.toString()).isEqualTo(IOUtils.toString(this.getClass().getResource(this.getClass().getSimpleName() + "/report-without-resolved-issues.json"))); - } - - @Test - public void should_not_export_by_default() throws IOException { - File workDir = temp.newFolder("sonar"); - fs.setWorkDir(workDir.toPath()); - - jsonReport.execute(); - - verifyZeroInteractions(issueCache); - } - - @Test - public void should_export_issues_to_file() throws IOException { - File workDir = temp.newFolder("sonar"); - fs.setWorkDir(workDir.toPath()); - - when(issueCache.all()).thenReturn(Collections.<TrackedIssue>emptyList()); - - settings.setProperty("sonar.report.export.path", "output.json"); - - jsonReport.execute(); - - assertThat(new File(workDir, "output.json")).exists(); - } - -} diff --git a/sonar-scanner-engine/src/test/java/org/sonar/scanner/sensor/ModuleSensorContextTest.java b/sonar-scanner-engine/src/test/java/org/sonar/scanner/sensor/ModuleSensorContextTest.java index 3a939bd3f7b..e34193358b2 100644 --- a/sonar-scanner-engine/src/test/java/org/sonar/scanner/sensor/ModuleSensorContextTest.java +++ b/sonar-scanner-engine/src/test/java/org/sonar/scanner/sensor/ModuleSensorContextTest.java @@ -26,13 +26,9 @@ import org.junit.rules.ExpectedException; import org.junit.rules.TemporaryFolder; import org.sonar.api.SonarQubeSide; import org.sonar.api.SonarRuntime; -import org.sonar.api.batch.AnalysisMode; -import org.sonar.api.batch.bootstrap.ProjectDefinition; import org.sonar.api.batch.fs.InputModule; import org.sonar.api.batch.fs.internal.DefaultFileSystem; -import org.sonar.api.batch.fs.internal.DefaultInputModule; import org.sonar.api.batch.fs.internal.DefaultInputProject; -import org.sonar.api.batch.fs.internal.InputModuleHierarchy; import org.sonar.api.batch.measure.MetricFinder; import org.sonar.api.batch.rule.ActiveRules; import org.sonar.api.batch.rule.internal.ActiveRulesBuilder; @@ -41,7 +37,6 @@ import org.sonar.api.config.internal.MapSettings; import org.sonar.api.internal.SonarRuntimeImpl; import org.sonar.api.measures.CoreMetrics; import org.sonar.api.utils.Version; -import org.sonar.scanner.scan.DefaultInputModuleHierarchy; import static org.assertj.core.api.Assertions.assertThat; import static org.mockito.Mockito.mock; @@ -60,9 +55,7 @@ public class ModuleSensorContextTest { private ModuleSensorContext adaptor; private MapSettings settings; private SensorStorage sensorStorage; - private AnalysisMode analysisMode; private SonarRuntime runtime; - private InputModuleHierarchy hierarchy; @Before public void prepare() throws Exception { @@ -73,12 +66,8 @@ public class ModuleSensorContextTest { when(metricFinder.<String>findByKey(CoreMetrics.FUNCTION_COMPLEXITY_DISTRIBUTION_KEY)).thenReturn(CoreMetrics.FUNCTION_COMPLEXITY_DISTRIBUTION); settings = new MapSettings(); sensorStorage = mock(SensorStorage.class); - analysisMode = mock(AnalysisMode.class); runtime = SonarRuntimeImpl.forSonarQube(Version.parse("5.5"), SonarQubeSide.SCANNER); - hierarchy = new DefaultInputModuleHierarchy(new DefaultInputModule(ProjectDefinition.create() - .setWorkDir(temp.newFolder()) - .setBaseDir(temp.newFolder()).setKey("foo"))); - adaptor = new ModuleSensorContext(mock(DefaultInputProject.class), mock(InputModule.class), settings.asConfig(), settings, fs, activeRules, analysisMode, sensorStorage, runtime); + adaptor = new ModuleSensorContext(mock(DefaultInputProject.class), mock(InputModule.class), settings.asConfig(), settings, fs, activeRules, sensorStorage, runtime); } @Test @@ -98,27 +87,4 @@ public class ModuleSensorContextTest { assertThat(adaptor.newSignificantCode()).isNotNull(); } - @Test - public void shouldSkipSignificantCodeOnPreviewMode() { - when(analysisMode.isIssues()).thenReturn(true); - assertThat(adaptor.newSignificantCode()).isEqualTo(ModuleSensorContext.NO_OP_NEW_SIGNIFICANT_CODE); - - } - - @Test - public void shouldSkipSeveralObjectsInPreviewMode() { - when(analysisMode.isIssues()).thenReturn(true); - when(analysisMode.isPreview()).thenReturn(true); - assertThat(adaptor.newCpdTokens()).isEqualTo(ModuleSensorContext.NO_OP_NEW_CPD_TOKENS); - assertThat(adaptor.newSymbolTable()).isEqualTo(ModuleSensorContext.NO_OP_NEW_SYMBOL_TABLE); - assertThat(adaptor.newExternalIssue()).isEqualTo(ModuleSensorContext.NO_OP_NEW_EXTERNAL_ISSUE); - assertThat(adaptor.newAdHocRule()).isEqualTo(ModuleSensorContext.NO_OP_NEW_AD_HOC_RULE); - assertThat(adaptor.newHighlighting()).isEqualTo(ModuleSensorContext.NO_OP_NEW_HIGHLIGHTING); - } - - @Test - public void shouldSkipDupsOnIssuesMode() { - when(analysisMode.isIssues()).thenReturn(true); - assertThat(adaptor.newCpdTokens()).isEqualTo(ModuleSensorContext.NO_OP_NEW_CPD_TOKENS); - } } diff --git a/sonar-scanner-engine/src/test/resources/org/sonar/scanner/scan/report/JSONReportTest/report-without-resolved-issues.json b/sonar-scanner-engine/src/test/resources/org/sonar/scanner/scan/report/JSONReportTest/report-without-resolved-issues.json deleted file mode 100644 index 8238d2eae85..00000000000 --- a/sonar-scanner-engine/src/test/resources/org/sonar/scanner/scan/report/JSONReportTest/report-without-resolved-issues.json +++ /dev/null @@ -1,14 +0,0 @@ -{ - "version": "3.6", - "issues": [], - "components": [ - {"key": "struts"}, - { - "key": "struts:src/main/java/org/apache/struts/Action.java", - "path": "src/main/java/org/apache/struts/Action.java", - "status": "CHANGED" - } - ], - "rules": [], - "users": [] -} diff --git a/sonar-scanner-engine/src/test/resources/org/sonar/scanner/scan/report/JSONReportTest/report.json b/sonar-scanner-engine/src/test/resources/org/sonar/scanner/scan/report/JSONReportTest/report.json deleted file mode 100644 index f80eadc890c..00000000000 --- a/sonar-scanner-engine/src/test/resources/org/sonar/scanner/scan/report/JSONReportTest/report.json +++ /dev/null @@ -1,46 +0,0 @@ -{ - "version": "3.6", - "issues": [ - { - "key": "200", - "component": "struts:src/main/java/org/apache/struts/Action.java", - "line": 1, - "startLine": 1, - "startOffset": 3, - "endLine": 2, - "endOffset": 4, - "message": "There are 2 cycles", - "severity": "MINOR", - "rule": "squid:AvoidCycles", - "status": "OPEN", - "isNew": false, - "assignee": "simon", - "effortToFix": 3.14, - "creationDate": "${json-unit.ignore}" - } - ], - "components": [ - { - "key": "struts" - }, - { - "key": "struts:src/main/java/org/apache/struts/Action.java", - "path": "src/main/java/org/apache/struts/Action.java", - "status": "CHANGED" - } - ], - "rules": [ - { - "key": "squid:AvoidCycles", - "rule": "AvoidCycles", - "repository": "squid", - "name": "Avoid Cycles" - } - ], - "users": [ - { - "login": "simon", - "name": "simon" - } - ] -} |