* Since 6.5, plugins should no longer manipulate the project's structure.
*
* @since 2.9
+ * @deprecated since 7.6 use {@link org.sonar.api.scanner.fs.InputProject}
*/
+@Deprecated
public class ProjectDefinition {
public static final String SOURCES_PROPERTY = "sonar.sources";
/**
* Provides root project key with branch
+ * @deprecated since 7.6
*/
+@Deprecated
@FunctionalInterface
public interface ProjectKey {
String get();
*/
@Deprecated
@ScannerSide
-public class ProjectReactor implements ProjectKey {
+public class ProjectReactor {
private ProjectDefinition root;
return null;
}
- @Override
public String get() {
if (root != null) {
return root.getKeyWithBranch();
* @see InputFile
* @see InputDir
* @see InputModule
+ * @see org.sonar.api.scanner.fs.InputProject
*/
public interface InputComponent {
* Used to create issues and measures on modules. You can access InputModule using {@link SensorContext#module()}
*
* @since 5.2
+ * @deprecated since 7.6 modules are deprecated. Use {@link org.sonar.api.scanner.fs.InputProject} instead.
*/
+@Deprecated
@Immutable
public interface InputModule extends InputComponent {
}
--- /dev/null
+/*
+ * SonarQube
+ * Copyright (C) 2009-2018 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.api.batch.fs.internal;
+
+import java.io.File;
+import java.io.IOException;
+import java.nio.file.LinkOption;
+import java.nio.file.Path;
+import java.util.Collections;
+import java.util.HashMap;
+import java.util.Map;
+import javax.annotation.CheckForNull;
+import javax.annotation.concurrent.Immutable;
+import org.sonar.api.batch.bootstrap.ProjectDefinition;
+
+@Immutable
+public abstract class AbstractProjectOrModule extends DefaultInputComponent {
+ private final Path baseDir;
+ private final Path workDir;
+ private final String name;
+ private final String version;
+ private final String originalName;
+ private final String originalVersion;
+ private final String description;
+ private final String keyWithBranch;
+ private final String branch;
+ private final Map<String, String> properties;
+
+ private final String key;
+ private final ProjectDefinition definition;
+
+ /**
+ * For testing only!
+ */
+ public AbstractProjectOrModule(ProjectDefinition definition) {
+ this(definition, TestInputFileBuilder.nextBatchId());
+ }
+
+ public AbstractProjectOrModule(ProjectDefinition definition, int scannerComponentId) {
+ super(scannerComponentId);
+ this.baseDir = initBaseDir(definition);
+ this.workDir = initWorkingDir(definition);
+ this.name = definition.getName();
+ this.originalName = definition.getOriginalName();
+ this.version = definition.getVersion();
+ this.originalVersion = definition.getOriginalVersion();
+ this.description = definition.getDescription();
+ this.keyWithBranch = definition.getKeyWithBranch();
+ this.branch = definition.getBranch();
+ this.properties = Collections.unmodifiableMap(new HashMap<>(definition.properties()));
+
+ this.definition = definition;
+ this.key = definition.getKey();
+ }
+
+ private static Path initBaseDir(ProjectDefinition module) {
+ Path result;
+ try {
+ result = module.getBaseDir().toPath().toRealPath(LinkOption.NOFOLLOW_LINKS);
+ } catch (IOException e) {
+ throw new IllegalStateException("Unable to resolve module baseDir", e);
+ }
+ return result;
+ }
+
+ private static Path initWorkingDir(ProjectDefinition module) {
+ File workingDirAsFile = module.getWorkDir();
+ return workingDirAsFile.getAbsoluteFile().toPath().normalize();
+ }
+
+ /**
+ * Module key without branch
+ */
+ @Override
+ public String key() {
+ return key;
+ }
+
+ @Override
+ public boolean isFile() {
+ return false;
+ }
+
+ public ProjectDefinition definition() {
+ return definition;
+ }
+
+ public Path getBaseDir() {
+ return baseDir;
+ }
+
+ public Path getWorkDir() {
+ return workDir;
+ }
+
+ public String getKeyWithBranch() {
+ return keyWithBranch;
+ }
+
+ @CheckForNull
+ public String getBranch() {
+ return branch;
+ }
+
+ public Map<String, String> properties() {
+ return properties;
+ }
+
+ @CheckForNull
+ public String getOriginalVersion() {
+ return originalVersion;
+ }
+
+ public String getVersion() {
+ return version;
+ }
+
+ @CheckForNull
+ public String getOriginalName() {
+ return originalName;
+ }
+
+ public String getName() {
+ return name;
+ }
+
+ public String getDescription() {
+ return description;
+ }
+
+}
return key().equals(that.key());
}
- public int batchId() {
+ public int scannerId() {
return id;
}
// For testing
public DefaultInputFile(DefaultIndexedFile indexedFile, Consumer<DefaultInputFile> metadataGenerator, @Nullable String contents) {
- super(indexedFile.batchId());
+ super(indexedFile.scannerId());
this.indexedFile = indexedFile;
this.metadataGenerator = metadataGenerator;
this.metadata = null;
*/
package org.sonar.api.batch.fs.internal;
-import java.io.File;
-import java.io.IOException;
-import java.nio.file.LinkOption;
-import java.nio.file.Path;
-import java.util.Collections;
-import java.util.HashMap;
-import java.util.Map;
-import javax.annotation.CheckForNull;
import javax.annotation.concurrent.Immutable;
import org.sonar.api.batch.bootstrap.ProjectDefinition;
import org.sonar.api.batch.fs.InputModule;
-/**
- * @since 5.2
- */
@Immutable
-public class DefaultInputModule extends DefaultInputComponent implements InputModule {
- private final Path baseDir;
- private final Path workDir;
- private final String name;
- private final String version;
- private final String originalName;
- private final String originalVersion;
- private final String description;
- private final String keyWithBranch;
- private final String branch;
- private final Map<String, String> properties;
-
- private final String moduleKey;
- private final ProjectDefinition definition;
+public class DefaultInputModule extends AbstractProjectOrModule implements InputModule {
- /**
- * For testing only!
- */
public DefaultInputModule(ProjectDefinition definition) {
- this(definition, TestInputFileBuilder.nextBatchId());
- }
-
- public DefaultInputModule(ProjectDefinition definition, int batchId) {
- super(batchId);
- this.baseDir = initBaseDir(definition);
- this.workDir = initWorkingDir(definition);
- this.name = definition.getName();
- this.originalName = definition.getOriginalName();
- this.version = definition.getVersion();
- this.originalVersion = definition.getOriginalVersion();
- this.description = definition.getDescription();
- this.keyWithBranch = definition.getKeyWithBranch();
- this.branch = definition.getBranch();
- this.properties = Collections.unmodifiableMap(new HashMap<>(definition.properties()));
-
- this.definition = definition;
- this.moduleKey = definition.getKey();
- }
-
- private static Path initBaseDir(ProjectDefinition module) {
- Path result;
- try {
- result = module.getBaseDir().toPath().toRealPath(LinkOption.NOFOLLOW_LINKS);
- } catch (IOException e) {
- throw new IllegalStateException("Unable to resolve module baseDir", e);
- }
- return result;
- }
-
- private static Path initWorkingDir(ProjectDefinition module) {
- File workingDirAsFile = module.getWorkDir();
- return workingDirAsFile.getAbsoluteFile().toPath().normalize();
- }
-
- /**
- * Module key without branch
- */
- @Override
- public String key() {
- return moduleKey;
- }
-
- @Override
- public boolean isFile() {
- return false;
- }
-
- public ProjectDefinition definition() {
- return definition;
- }
-
- public Path getBaseDir() {
- return baseDir;
+ super(definition);
}
- public Path getWorkDir() {
- return workDir;
+ public DefaultInputModule(ProjectDefinition definition, int scannerComponentId) {
+ super(definition, scannerComponentId);
}
-
- public String getKeyWithBranch() {
- return keyWithBranch;
- }
-
- @CheckForNull
- public String getBranch() {
- return branch;
- }
-
- public Map<String, String> properties() {
- return properties;
- }
-
- @CheckForNull
- public String getOriginalVersion() {
- return originalVersion;
- }
-
- public String getVersion() {
- return version;
- }
-
- @CheckForNull
- public String getOriginalName() {
- return originalName;
- }
-
- public String getName() {
- return name;
- }
-
- public String getDescription() {
- return description;
- }
-
}
--- /dev/null
+/*
+ * SonarQube
+ * Copyright (C) 2009-2018 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.api.batch.fs.internal;
+
+import javax.annotation.concurrent.Immutable;
+import org.sonar.api.batch.bootstrap.ProjectDefinition;
+import org.sonar.api.scanner.fs.InputProject;
+
+@Immutable
+public class DefaultInputProject extends AbstractProjectOrModule implements InputProject {
+
+ public DefaultInputProject(ProjectDefinition definition) {
+ super(definition);
+ }
+
+ public DefaultInputProject(ProjectDefinition definition, int scannerComponentId) {
+ super(definition, scannerComponentId);
+ }
+}
package org.sonar.api.batch.fs.internal;
import java.util.Collection;
-
import javax.annotation.CheckForNull;
import javax.annotation.concurrent.Immutable;
-import org.sonar.api.batch.fs.InputModule;
-
@Immutable
public interface InputModuleHierarchy {
DefaultInputModule root();
- boolean isRoot(InputModule module);
+ boolean isRoot(DefaultInputModule module);
- Collection<DefaultInputModule> children(InputModule module);
+ Collection<DefaultInputModule> children(DefaultInputModule module);
@CheckForNull
- DefaultInputModule parent(InputModule module);
+ DefaultInputModule parent(DefaultInputModule module);
@CheckForNull
- String relativePath(InputModule module);
+ String relativePath(DefaultInputModule module);
}
return new DefaultInputModule(projectDefinition, TestInputFileBuilder.nextBatchId());
}
- public static DefaultInputModule newDefaultInputModule(DefaultInputModule parent, String key) throws IOException {
+ public static DefaultInputModule newDefaultInputModule(AbstractProjectOrModule parent, String key) throws IOException {
Path basedir = parent.getBaseDir().resolve(key);
Files.createDirectory(basedir);
return newDefaultInputModule(key, basedir.toFile());
}
- public static DefaultInputDir newDefaultInputDir(DefaultInputModule module, String relativePath) throws IOException {
+ public static DefaultInputProject newDefaultInputProject(String projectKey, File baseDir) {
+ ProjectDefinition definition = ProjectDefinition.create()
+ .setKey(projectKey)
+ .setBaseDir(baseDir)
+ .setWorkDir(new File(baseDir, ".sonar"));
+ return newDefaultInputProject(definition);
+ }
+
+ public static DefaultInputProject newDefaultInputProject(ProjectDefinition projectDefinition) {
+ return new DefaultInputProject(projectDefinition, TestInputFileBuilder.nextBatchId());
+ }
+
+ public static DefaultInputProject newDefaultInputProject(String key, Path baseDir) throws IOException {
+ Files.createDirectory(baseDir);
+ return newDefaultInputProject(key, baseDir.toFile());
+ }
+
+ public static DefaultInputDir newDefaultInputDir(AbstractProjectOrModule module, String relativePath) throws IOException {
Path basedir = module.getBaseDir().resolve(relativePath);
Files.createDirectory(basedir);
return new DefaultInputDir(module.key(), relativePath)
.setModuleBaseDir(module.getBaseDir());
}
- public static DefaultInputFile newDefaultInputFile(Path projectBaseDir, DefaultInputModule module, String relativePath) {
+ public static DefaultInputFile newDefaultInputFile(Path projectBaseDir, AbstractProjectOrModule module, String relativePath) {
return new TestInputFileBuilder(module.key(), relativePath)
.setStatus(InputFile.Status.SAME)
.setProjectBaseDir(projectBaseDir)
import org.sonar.api.batch.sensor.symbol.NewSymbolTable;
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;
/**
/**
* @since 5.5
+ * @deprecated since 7.6 modules are deprecated. Use {@link #project()} instead.
*/
+ @Deprecated
InputModule module();
+ /**
+ * The current project.
+ * @since 7.6
+ */
+ InputProject project();
+
/**
* Version of API at runtime, not at compilation time. It's a shortcut on
* {@code runtime().getApiVersion()} since 6.0.
import org.sonar.api.batch.fs.internal.DefaultFileSystem;
import org.sonar.api.batch.fs.internal.DefaultInputFile;
import org.sonar.api.batch.fs.internal.DefaultInputModule;
+import org.sonar.api.batch.fs.internal.DefaultInputProject;
import org.sonar.api.batch.fs.internal.DefaultTextPointer;
import org.sonar.api.batch.rule.ActiveRules;
import org.sonar.api.batch.rule.internal.ActiveRulesBuilder;
import org.sonar.api.internal.ApiVersion;
import org.sonar.api.internal.SonarRuntimeImpl;
import org.sonar.api.measures.Metric;
+import org.sonar.api.scanner.fs.InputProject;
import org.sonar.api.utils.System2;
import org.sonar.api.utils.Version;
/**
* Utility class to help testing {@link Sensor}. This is not an API and method signature may evolve.
- *
+ * <p>
* Usage: call {@link #create(File)} to create an "in memory" implementation of {@link SensorContext} with a filesystem initialized with provided baseDir.
* <p>
* You have to manually register inputFiles using:
* <pre>
* sensorContextTester.fileSystem().add(new DefaultInputFile("myProjectKey", "src/Foo.java")
- .setLanguage("java")
- .initMetadata("public class Foo {\n}"));
+ * .setLanguage("java")
+ * .initMetadata("public class Foo {\n}"));
* </pre>
* <p>
* Then pass it to your {@link Sensor}. You can then query elements provided by your sensor using methods {@link #allIssues()}, ...
- *
*/
public class SensorContextTester implements SensorContext {
private DefaultFileSystem fs;
private ActiveRules activeRules;
private InMemorySensorStorage sensorStorage;
+ private DefaultInputProject project;
private DefaultInputModule module;
private SonarRuntime runtime;
private boolean cancelled;
this.fs = new DefaultFileSystem(moduleBaseDir).setEncoding(Charset.defaultCharset());
this.activeRules = new ActiveRulesBuilder().build();
this.sensorStorage = new InMemorySensorStorage();
+ this.project = new DefaultInputProject(ProjectDefinition.create().setKey("projectKey").setBaseDir(moduleBaseDir.toFile()).setWorkDir(moduleBaseDir.resolve(".sonar").toFile()));
this.module = new DefaultInputModule(ProjectDefinition.create().setKey("projectKey").setBaseDir(moduleBaseDir.toFile()).setWorkDir(moduleBaseDir.resolve(".sonar").toFile()));
this.runtime = SonarRuntimeImpl.forSonarQube(ApiVersion.load(System2.INSTANCE), SonarQubeSide.SCANNER);
}
return module;
}
+ @Override
+ public InputProject project() {
+ return project;
+ }
+
@Override
public <G extends Serializable> NewMeasure<G> newMeasure() {
return new DefaultMeasure<>(sensorStorage);
@Override
public NewIssue newIssue() {
- return new DefaultIssue(module, sensorStorage);
+ return new DefaultIssue(project, sensorStorage);
}
public Collection<Issue> allIssues() {
@Override
public NewExternalIssue newExternalIssue() {
- return new DefaultExternalIssue(module, sensorStorage);
+ return new DefaultExternalIssue(project, sensorStorage);
}
@Override
/**
* Return list of syntax highlighting applied for a given position in a file. The result is a list because in theory you
* can apply several styles to the same range.
+ *
* @param componentKey Key of the file like 'myProjectKey:src/foo.php'
- * @param line Line you want to query
- * @param lineOffset Offset you want to query.
+ * @param line Line you want to query
+ * @param lineOffset Offset you want to query.
* @return List of styles applied to this position or empty list if there is no highlighting at this position.
*/
public List<TypeOfText> highlightingTypeAt(String componentKey, int line, int lineOffset) {
/**
* Return list of symbol references ranges for the symbol at a given position in a file.
+ *
* @param componentKey Key of the file like 'myProjectKey:src/foo.php'
- * @param line Line you want to query
- * @param lineOffset Offset you want to query.
+ * @param line Line you want to query
+ * @param lineOffset Offset you want to query.
* @return List of references for the symbol (potentially empty) or null if there is no symbol at this position.
*/
@CheckForNull
import org.sonar.api.batch.fs.InputComponent;
import org.sonar.api.batch.fs.internal.DefaultInputDir;
import org.sonar.api.batch.fs.internal.DefaultInputModule;
+import org.sonar.api.batch.fs.internal.DefaultInputProject;
import org.sonar.api.batch.sensor.internal.DefaultStorable;
import org.sonar.api.batch.sensor.internal.SensorStorage;
import org.sonar.api.batch.sensor.issue.Issue.Flow;
public abstract class AbstractDefaultIssue<T extends AbstractDefaultIssue> extends DefaultStorable {
protected IssueLocation primaryLocation;
protected List<List<IssueLocation>> flows = new ArrayList<>();
- protected DefaultInputModule projectRoot;
+ protected DefaultInputProject project;
- protected AbstractDefaultIssue(DefaultInputModule projectRoot) {
- this(projectRoot, null);
+ protected AbstractDefaultIssue(DefaultInputProject project) {
+ this(project, null);
}
- public AbstractDefaultIssue(DefaultInputModule projectRoot, @Nullable SensorStorage storage) {
+ public AbstractDefaultIssue(DefaultInputProject project, @Nullable SensorStorage storage) {
super(storage);
- this.projectRoot = projectRoot;
+ this.project = project;
}
public IssueLocation primaryLocation() {
if (component instanceof DefaultInputDir) {
DefaultInputDir dirComponent = (DefaultInputDir) component;
- dirOrModulePath = Optional.of(projectRoot.getBaseDir().relativize(dirComponent.path()));
- } else if (component instanceof DefaultInputModule && !Objects.equals(projectRoot.key(), component.key())) {
+ dirOrModulePath = Optional.of(project.getBaseDir().relativize(dirComponent.path()));
+ } else if (component instanceof DefaultInputModule && !Objects.equals(project.key(), component.key())) {
DefaultInputModule moduleComponent = (DefaultInputModule) component;
- dirOrModulePath = Optional.of(projectRoot.getBaseDir().relativize(moduleComponent.getBaseDir()));
+ dirOrModulePath = Optional.of(project.getBaseDir().relativize(moduleComponent.getBaseDir()));
}
if (dirOrModulePath.isPresent()) {
String path = PathUtils.sanitize(dirOrModulePath.get().toString());
DefaultIssueLocation fixedLocation = new DefaultIssueLocation();
- fixedLocation.on(projectRoot);
+ fixedLocation.on(project);
StringBuilder fullMessage = new StringBuilder();
if (!isNullOrEmpty(path)) {
fullMessage.append("[").append(path).append("] ");
import com.google.common.base.Preconditions;
import javax.annotation.Nullable;
-import org.sonar.api.batch.fs.internal.DefaultInputModule;
+import org.sonar.api.batch.fs.internal.DefaultInputProject;
import org.sonar.api.batch.rule.Severity;
import org.sonar.api.batch.sensor.internal.SensorStorage;
import org.sonar.api.batch.sensor.issue.ExternalIssue;
private String engineId;
private String ruleId;
- public DefaultExternalIssue(DefaultInputModule projectRoot) {
- this(projectRoot, null);
+ public DefaultExternalIssue(DefaultInputProject project) {
+ this(project, null);
}
- public DefaultExternalIssue(DefaultInputModule projectRoot, @Nullable SensorStorage storage) {
- super(projectRoot, storage);
+ public DefaultExternalIssue(DefaultInputProject project, @Nullable SensorStorage storage) {
+ super(project, storage);
}
@Override
import com.google.common.base.Preconditions;
import javax.annotation.Nullable;
-import org.sonar.api.batch.fs.internal.DefaultInputModule;
+import org.sonar.api.batch.fs.internal.DefaultInputProject;
import org.sonar.api.batch.rule.Severity;
import org.sonar.api.batch.sensor.internal.SensorStorage;
import org.sonar.api.batch.sensor.issue.Issue;
private Double gap;
private Severity overriddenSeverity;
- public DefaultIssue(DefaultInputModule projectRoot) {
- this(projectRoot, null);
+ public DefaultIssue(DefaultInputProject project) {
+ this(project, null);
}
- public DefaultIssue(DefaultInputModule projectRoot, @Nullable SensorStorage storage) {
- super(projectRoot, storage);
+ public DefaultIssue(DefaultInputProject project, @Nullable SensorStorage storage) {
+ super(project, storage);
}
public DefaultIssue forRule(RuleKey ruleKey) {
--- /dev/null
+/*
+ * 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.api.scanner.fs;
+
+
+import javax.annotation.concurrent.Immutable;
+import org.sonar.api.batch.fs.InputComponent;
+import org.sonar.api.batch.sensor.SensorContext;
+
+/**
+ * Used to create issues and measures on project. You can access InputProject using {@link SensorContext#project()}
+ *
+ * @since 7.6
+ */
+@Immutable
+public interface InputProject extends InputComponent {
+}
--- /dev/null
+/*
+ * 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.
+ */
+@javax.annotation.ParametersAreNonnullByDefault
+package org.sonar.api.scanner.fs;
+++ /dev/null
-/*
- * 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.api.batch.fs.internal;
-
-import java.io.File;
-import java.io.IOException;
-import org.junit.Rule;
-import org.junit.Test;
-import org.junit.rules.TemporaryFolder;
-import org.sonar.api.batch.bootstrap.ProjectDefinition;
-
-import static org.assertj.core.api.Assertions.assertThat;
-
-public class DefaultInputModuleTest {
-
- @Rule
- public TemporaryFolder temp = new TemporaryFolder();
-
- @Test
- public void testGetters() throws IOException {
- ProjectDefinition def = ProjectDefinition.create();
- def.setKey("projectKey");
- def.setName("projectName");
- File baseDir = temp.newFolder();
- def.setBaseDir(baseDir);
- def.setVersion("version");
- def.setDescription("desc");
- File workDir = temp.newFolder();
- def.setWorkDir(workDir);
- def.setSources("file1");
- def.setTests("test1");
- DefaultInputModule module = new DefaultInputModule(def);
-
- assertThat(module.key()).isEqualTo("projectKey");
- assertThat(module.getName()).isEqualTo("projectName");
- assertThat(module.getOriginalName()).isEqualTo("projectName");
- assertThat(module.definition()).isEqualTo(def);
- assertThat(module.getBranch()).isNull();
- assertThat(module.getBaseDir()).isEqualTo(baseDir.toPath());
- assertThat(module.getKeyWithBranch()).isEqualTo("projectKey");
- assertThat(module.getVersion()).isEqualTo("version");
- assertThat(module.getOriginalVersion()).isEqualTo("version");
- assertThat(module.getDescription()).isEqualTo("desc");
- assertThat(module.getWorkDir()).isEqualTo(workDir.toPath());
-
- assertThat(module.properties()).hasSize(6);
-
- assertThat(module.isFile()).isFalse();
- }
-
-}
--- /dev/null
+/*
+ * 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.api.batch.fs.internal;
+
+import java.io.File;
+import java.io.IOException;
+import org.junit.Rule;
+import org.junit.Test;
+import org.junit.rules.TemporaryFolder;
+import org.sonar.api.batch.bootstrap.ProjectDefinition;
+
+import static org.assertj.core.api.Assertions.assertThat;
+
+public class DefaultInputProjectTest {
+
+ @Rule
+ public TemporaryFolder temp = new TemporaryFolder();
+
+ @Test
+ public void testGetters() throws IOException {
+ ProjectDefinition def = ProjectDefinition.create();
+ def.setKey("projectKey");
+ def.setName("projectName");
+ File baseDir = temp.newFolder();
+ def.setBaseDir(baseDir);
+ def.setVersion("version");
+ def.setDescription("desc");
+ File workDir = temp.newFolder();
+ def.setWorkDir(workDir);
+ def.setSources("file1");
+ def.setTests("test1");
+ AbstractProjectOrModule module = new DefaultInputProject(def);
+
+ assertThat(module.key()).isEqualTo("projectKey");
+ assertThat(module.getName()).isEqualTo("projectName");
+ assertThat(module.getOriginalName()).isEqualTo("projectName");
+ assertThat(module.definition()).isEqualTo(def);
+ assertThat(module.getBranch()).isNull();
+ assertThat(module.getBaseDir()).isEqualTo(baseDir.toPath());
+ assertThat(module.getKeyWithBranch()).isEqualTo("projectKey");
+ assertThat(module.getVersion()).isEqualTo("version");
+ assertThat(module.getOriginalVersion()).isEqualTo("version");
+ assertThat(module.getDescription()).isEqualTo("desc");
+ assertThat(module.getWorkDir()).isEqualTo(workDir.toPath());
+
+ assertThat(module.properties()).hasSize(6);
+
+ assertThat(module.isFile()).isFalse();
+ }
+
+}
@Test
public void testCreateInputModule() throws IOException {
File baseDir = temp.newFolder();
- DefaultInputModule module = TestInputFileBuilder.newDefaultInputModule("key", baseDir);
+ AbstractProjectOrModule module = TestInputFileBuilder.newDefaultInputModule("key", baseDir);
assertThat(module.key()).isEqualTo("key");
assertThat(module.getBaseDir()).isEqualTo(baseDir.toPath());
}
import org.sonar.api.batch.bootstrap.ProjectDefinition;
import org.sonar.api.batch.fs.InputComponent;
import org.sonar.api.batch.fs.internal.DefaultInputFile;
-import org.sonar.api.batch.fs.internal.DefaultInputModule;
+import org.sonar.api.batch.fs.internal.DefaultInputProject;
import org.sonar.api.batch.fs.internal.TestInputFileBuilder;
import org.sonar.api.batch.rule.Severity;
import org.sonar.api.batch.sensor.internal.SensorStorage;
@Rule
public TemporaryFolder temp = new TemporaryFolder();
- private DefaultInputModule projectRoot;
+ private DefaultInputProject project;
@Before
public void setup() throws IOException {
- projectRoot = new DefaultInputModule(ProjectDefinition.create()
+ project = new DefaultInputProject(ProjectDefinition.create()
.setKey("foo")
.setBaseDir(temp.newFolder())
.setWorkDir(temp.newFolder()));
@Test
public void build_file_issue() {
SensorStorage storage = mock(SensorStorage.class);
- DefaultExternalIssue issue = new DefaultExternalIssue(projectRoot, storage)
+ DefaultExternalIssue issue = new DefaultExternalIssue(project, storage)
.at(new DefaultIssueLocation()
.on(inputFile)
.at(inputFile.selectLine(1))
@Test
public void fail_to_store_if_no_type() {
SensorStorage storage = mock(SensorStorage.class);
- DefaultExternalIssue issue = new DefaultExternalIssue(projectRoot, storage)
+ DefaultExternalIssue issue = new DefaultExternalIssue(project, storage)
.at(new DefaultIssueLocation()
.on(inputFile)
.at(inputFile.selectLine(1))
@Test
public void fail_to_store_if_primary_location_is_not_a_file() {
SensorStorage storage = mock(SensorStorage.class);
- DefaultExternalIssue issue = new DefaultExternalIssue(projectRoot, storage)
+ DefaultExternalIssue issue = new DefaultExternalIssue(project, storage)
.at(new DefaultIssueLocation()
.on(mock(InputComponent.class))
.message("Wrong way!"))
@Test
public void fail_to_store_if_primary_location_has_no_message() {
SensorStorage storage = mock(SensorStorage.class);
- DefaultExternalIssue issue = new DefaultExternalIssue(projectRoot, storage)
+ DefaultExternalIssue issue = new DefaultExternalIssue(project, storage)
.at(new DefaultIssueLocation()
.on(inputFile)
.at(inputFile.selectLine(1)))
@Test
public void fail_to_store_if_no_severity() {
SensorStorage storage = mock(SensorStorage.class);
- DefaultExternalIssue issue = new DefaultExternalIssue(projectRoot, storage)
+ DefaultExternalIssue issue = new DefaultExternalIssue(project, storage)
.at(new DefaultIssueLocation()
.on(inputFile)
.at(inputFile.selectLine(1))
import org.sonar.api.batch.fs.internal.DefaultInputDir;
import org.sonar.api.batch.fs.internal.DefaultInputFile;
import org.sonar.api.batch.fs.internal.DefaultInputModule;
+import org.sonar.api.batch.fs.internal.DefaultInputProject;
import org.sonar.api.batch.fs.internal.TestInputFileBuilder;
import org.sonar.api.batch.rule.Severity;
import org.sonar.api.batch.sensor.internal.SensorStorage;
@Rule
public TemporaryFolder temp = new TemporaryFolder();
- private DefaultInputModule projectRoot;
+ private DefaultInputProject project;
private DefaultInputFile inputFile = new TestInputFileBuilder("foo", "src/Foo.php")
.initMetadata("Foo\nBar\n")
@Before
public void prepare() throws IOException {
- projectRoot = new DefaultInputModule(ProjectDefinition.create()
+ project = new DefaultInputProject(ProjectDefinition.create()
.setKey("foo")
.setBaseDir(temp.newFolder())
.setWorkDir(temp.newFolder()));
@Test
public void build_file_issue() {
SensorStorage storage = mock(SensorStorage.class);
- DefaultIssue issue = new DefaultIssue(projectRoot, storage)
+ DefaultIssue issue = new DefaultIssue(project, storage)
.at(new DefaultIssueLocation()
.on(inputFile)
.at(inputFile.selectLine(1))
@Test
public void move_directory_issue_to_project_root() {
SensorStorage storage = mock(SensorStorage.class);
- DefaultIssue issue = new DefaultIssue(projectRoot, storage)
+ DefaultIssue issue = new DefaultIssue(project, storage)
.at(new DefaultIssueLocation()
- .on(new DefaultInputDir("foo", "src/main").setModuleBaseDir(projectRoot.getBaseDir()))
+ .on(new DefaultInputDir("foo", "src/main").setModuleBaseDir(project.getBaseDir()))
.message("Wrong way!"))
.forRule(RuleKey.of("repo", "rule"))
.overrideSeverity(Severity.BLOCKER);
- assertThat(issue.primaryLocation().inputComponent()).isEqualTo(projectRoot);
+ assertThat(issue.primaryLocation().inputComponent()).isEqualTo(project);
assertThat(issue.ruleKey()).isEqualTo(RuleKey.of("repo", "rule"));
assertThat(issue.primaryLocation().textRange()).isNull();
assertThat(issue.primaryLocation().message()).isEqualTo("[src/main] Wrong way!");
@Test
public void move_submodule_issue_to_project_root() {
- File subModuleDirectory = new File(projectRoot.getBaseDir().toString(), "bar");
+ File subModuleDirectory = new File(project.getBaseDir().toString(), "bar");
subModuleDirectory.mkdir();
ProjectDefinition subModuleDefinition = ProjectDefinition.create()
.setKey("foo/bar")
.setBaseDir(subModuleDirectory)
.setWorkDir(subModuleDirectory);
- projectRoot.definition().addSubProject(subModuleDefinition);
+ project.definition().addSubProject(subModuleDefinition);
DefaultInputModule subModule = new DefaultInputModule(subModuleDefinition);
SensorStorage storage = mock(SensorStorage.class);
- DefaultIssue issue = new DefaultIssue(projectRoot, storage)
+ DefaultIssue issue = new DefaultIssue(project, storage)
.at(new DefaultIssueLocation()
.on(subModule)
.message("Wrong way!"))
.forRule(RuleKey.of("repo", "rule"))
.overrideSeverity(Severity.BLOCKER);
- assertThat(issue.primaryLocation().inputComponent()).isEqualTo(projectRoot);
+ assertThat(issue.primaryLocation().inputComponent()).isEqualTo(project);
assertThat(issue.ruleKey()).isEqualTo(RuleKey.of("repo", "rule"));
assertThat(issue.primaryLocation().textRange()).isNull();
assertThat(issue.primaryLocation().message()).isEqualTo("[bar] Wrong way!");
public void build_project_issue() throws IOException {
SensorStorage storage = mock(SensorStorage.class);
DefaultInputModule inputModule = new DefaultInputModule(ProjectDefinition.create().setKey("foo").setBaseDir(temp.newFolder()).setWorkDir(temp.newFolder()));
- DefaultIssue issue = new DefaultIssue(projectRoot, storage)
+ DefaultIssue issue = new DefaultIssue(project, storage)
.at(new DefaultIssueLocation()
.on(inputModule)
.message("Wrong way!"))
import org.junit.rules.ExpectedException;
import org.junit.rules.TemporaryFolder;
import org.sonar.api.batch.bootstrap.ProjectDefinition;
-import org.sonar.api.batch.fs.internal.DefaultInputModule;
+import org.sonar.api.batch.fs.internal.AbstractProjectOrModule;
+import org.sonar.api.batch.fs.internal.DefaultInputProject;
import org.sonar.api.batch.fs.internal.TestInputFileBuilder;
import org.sonar.api.batch.sensor.internal.SensorStorage;
import org.sonar.api.measures.CoreMetrics;
@Test
public void build_project_measure() throws IOException {
SensorStorage storage = mock(SensorStorage.class);
- DefaultInputModule module = new DefaultInputModule(ProjectDefinition.create().setKey("foo").setBaseDir(temp.newFolder()).setWorkDir(temp.newFolder()));
+ AbstractProjectOrModule module = new DefaultInputProject(ProjectDefinition.create().setKey("foo").setBaseDir(temp.newFolder()).setWorkDir(temp.newFolder()));
DefaultMeasure<Integer> newMeasure = new DefaultMeasure<Integer>(storage)
.forMetric(CoreMetrics.LINES)
.on(module)
thrown.expect(IllegalStateException.class);
thrown.expectMessage("on() already called");
new DefaultMeasure<Integer>()
- .on(new DefaultInputModule(ProjectDefinition.create().setKey("foo").setBaseDir(temp.newFolder()).setWorkDir(temp.newFolder())))
+ .on(new DefaultInputProject(ProjectDefinition.create().setKey("foo").setBaseDir(temp.newFolder()).setWorkDir(temp.newFolder())))
.on(new TestInputFileBuilder("foo", "src/Foo.php").build())
.withValue(3)
.save();
*/
public final class Batch {
- private boolean started = false;
private LoggingConfiguration loggingConfig;
private List<Object> components;
- private Map<String, String> globalProperties = new HashMap<>();
+ private Map<String, String> scannerProperties = new HashMap<>();
private GlobalContainer bootstrapContainer;
private Batch(Builder builder) {
if (builder.environment != null) {
components.add(builder.environment);
}
- if (builder.globalProperties != null) {
- globalProperties.putAll(builder.globalProperties);
+ if (builder.scannerProperties != null) {
+ scannerProperties.putAll(builder.scannerProperties);
}
if (builder.isEnableLoggingConfiguration()) {
- loggingConfig = new LoggingConfiguration(builder.environment).setProperties(globalProperties);
+ loggingConfig = new LoggingConfiguration(builder.environment).setProperties(scannerProperties);
if (builder.logOutput != null) {
loggingConfig.setLogOutput(builder.logOutput);
configureLogging();
doStart();
try {
- doExecuteTask(globalProperties);
+ doExecute();
} finally {
doStop();
}
*/
@Deprecated
public synchronized Batch start() {
- if (started) {
- throw new IllegalStateException("Scanner Engine is already started");
- }
- configureLogging();
- return doStart();
+ return this;
}
private Batch doStart() {
try {
- bootstrapContainer = GlobalContainer.create(globalProperties, components);
+ bootstrapContainer = GlobalContainer.create(scannerProperties, components);
bootstrapContainer.startComponents();
} catch (RuntimeException e) {
throw handleException(e);
}
- this.started = true;
return this;
}
*/
@Deprecated
public Batch executeTask(Map<String, String> analysisProperties, Object... components) {
- checkStarted();
- configureTaskLogging(analysisProperties);
- return doExecuteTask(analysisProperties, components);
+ return execute();
}
- private Batch doExecuteTask(Map<String, String> analysisProperties, Object... components) {
+ private Batch doExecute(Object... components) {
try {
- bootstrapContainer.executeTask(analysisProperties, components);
+ bootstrapContainer.executeTask(scannerProperties, components);
} catch (RuntimeException e) {
throw handleException(e);
}
return this;
}
- private void checkStarted() {
- if (!started) {
- throw new IllegalStateException("Scanner engine is not started. Unable to execute task.");
- }
- }
-
private RuntimeException handleException(RuntimeException t) {
if (loggingConfig.isVerbose()) {
return t;
*/
@Deprecated
public synchronized void stop() {
- checkStarted();
- configureLogging();
- doStop();
}
private void doStop() {
} catch (RuntimeException e) {
throw handleException(e);
}
- this.started = false;
}
private void configureLogging() {
if (loggingConfig != null) {
- loggingConfig.setProperties(globalProperties);
- LoggingConfigurator.apply(loggingConfig);
- }
- }
-
- private void configureTaskLogging(Map<String, String> taskProperties) {
- if (loggingConfig != null) {
- loggingConfig.setProperties(taskProperties, globalProperties);
+ loggingConfig.setProperties(scannerProperties);
LoggingConfigurator.apply(loggingConfig);
}
}
}
public static final class Builder {
- private Map<String, String> globalProperties;
+ private Map<String, String> scannerProperties;
private EnvironmentInformation environment;
private List<Object> components = new ArrayList<>();
private boolean enableLoggingConfiguration = true;
return this;
}
- public Builder setGlobalProperties(Map<String, String> globalProperties) {
- this.globalProperties = globalProperties;
+ public Builder setScannerProperties(Map<String, String> scannerProperties) {
+ this.scannerProperties = scannerProperties;
return this;
}
/**
- * @deprecated since 6.6 use {@link #setGlobalProperties(Map)}
+ * @deprecated since 6.6 use {@link #setScannerProperties(Map)}
*/
@Deprecated
public Builder setBootstrapProperties(Map<String, String> bootstrapProperties) {
- this.globalProperties = bootstrapProperties;
+ this.scannerProperties = bootstrapProperties;
return this;
}
}
public LoggingConfiguration setProperties(Map<String, String> properties) {
- setVerbose(properties, null);
- return this;
- }
-
- public LoggingConfiguration setProperties(Map<String, String> properties, @Nullable Map<String, String> fallback) {
- setVerbose(properties, fallback);
+ setVerbose(properties);
return this;
}
return verbose;
}
- public LoggingConfiguration setVerbose(Map<String, String> props, @Nullable Map<String, String> fallback) {
- String logLevel = getFallback("sonar.log.level", props, fallback);
- String deprecatedProfilingLevel = getFallback("sonar.log.profilingLevel", props, fallback);
- verbose = "true".equals(getFallback("sonar.verbose", props, fallback)) ||
+ public LoggingConfiguration setVerbose(Map<String, String> props) {
+ String logLevel = props.get("sonar.log.level");
+ String deprecatedProfilingLevel = props.get("sonar.log.profilingLevel");
+ verbose = "true".equals(props.get("sonar.verbose")) ||
"DEBUG".equals(logLevel) || "TRACE".equals(logLevel) ||
"BASIC".equals(deprecatedProfilingLevel) || "FULL".equals(deprecatedProfilingLevel);
+++ /dev/null
-/*
- * 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.analysis;
-
-import java.util.Map;
-import javax.annotation.Nullable;
-import org.sonar.scanner.bootstrap.UserProperties;
-
-/**
- * Batch properties that are specific to an analysis (for example
- * coming from sonar-project.properties).
- */
-public class AnalysisProperties extends UserProperties {
- public AnalysisProperties(Map<String, String> properties) {
- this(properties, null);
-
- }
-
- public AnalysisProperties(Map<String, String> properties, @Nullable String pathToSecretKey) {
- super(properties, pathToSecretKey);
- }
-
-}
import org.picocontainer.ComponentLifecycle;
import org.picocontainer.PicoContainer;
import org.picocontainer.injectors.ProviderAdapter;
-import org.sonar.api.batch.fs.internal.InputModuleHierarchy;
+import org.sonar.api.batch.fs.internal.DefaultInputProject;
import org.sonar.api.utils.TempFolder;
import org.sonar.api.utils.internal.DefaultTempFolder;
private DefaultTempFolder projectTempFolder;
private boolean started = false;
- public TempFolder provide(InputModuleHierarchy moduleHierarchy) {
+ public TempFolder provide(DefaultInputProject project) {
if (projectTempFolder == null) {
- Path workingDir = moduleHierarchy.root().getWorkDir();
+ Path workingDir = project.getWorkDir();
Path tempDir = workingDir.normalize().resolve(TMP_NAME);
try {
Files.deleteIfExists(tempDir);
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.ScannerProperties;
@Immutable
public class DefaultAnalysisMode implements AnalysisMode {
private boolean scanAllFiles;
- public DefaultAnalysisMode(AnalysisProperties props, GlobalAnalysisMode analysisMode) {
+ public DefaultAnalysisMode(ScannerProperties props, GlobalAnalysisMode analysisMode) {
this.analysisMode = analysisMode;
this.analysisProps = props.properties();
load();
+++ /dev/null
-/*
- * 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.Map;
-import org.sonar.api.utils.log.Logger;
-import org.sonar.api.utils.log.Loggers;
-
-import static java.util.Objects.requireNonNull;
-
-public class DroppedPropertyChecker {
-
- private static final Logger LOG = Loggers.get(DroppedPropertyChecker.class);
-
- private final Map<String, String> settings;
- private final Map<String, String> properties;
-
- public DroppedPropertyChecker(Map<String, String> properties, Map<String, String> droppedPropertiesAndMsg) {
- this.settings = requireNonNull(properties);
- this.properties = requireNonNull(droppedPropertiesAndMsg);
- }
-
- public void checkDroppedProperties() {
- for (Map.Entry<String, String> entry : properties.entrySet()) {
- if (settings.containsKey(entry.getKey())) {
- LOG.warn("Property '{}' is not supported any more. {}", entry.getKey(), entry.getValue());
- }
- }
- }
-
-}
protected boolean issues;
protected boolean mediumTestMode;
- public GlobalAnalysisMode(GlobalProperties props) {
+ public GlobalAnalysisMode(ScannerProperties props) {
String mode = props.property(CoreProperties.ANALYSIS_MODE);
validate(mode);
issues = CoreProperties.ANALYSIS_MODE_ISSUES.equals(mode) || CoreProperties.ANALYSIS_MODE_PREVIEW.equals(mode);
*/
package org.sonar.scanner.bootstrap;
-import com.google.common.collect.ImmutableMap;
import java.util.Map;
import javax.annotation.concurrent.Immutable;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
-import org.sonar.api.CoreProperties;
import org.sonar.api.config.Encryption;
import org.sonar.api.config.PropertyDefinitions;
import org.sonar.scanner.config.DefaultConfiguration;
private static final Logger LOG = LoggerFactory.getLogger(GlobalConfiguration.class);
- private static final String JDBC_SPECIFIC_MESSAGE = "It will be ignored. There is no longer any DB connection to the SQ database.";
- /**
- * A map of dropped properties as key and specific message to display for that property
- * (what will happen, what should the user do, ...) as a value
- */
- private static final Map<String, String> DROPPED_PROPERTIES = ImmutableMap.of(
- "sonar.jdbc.url", JDBC_SPECIFIC_MESSAGE,
- "sonar.jdbc.username", JDBC_SPECIFIC_MESSAGE,
- "sonar.jdbc.password", JDBC_SPECIFIC_MESSAGE);
-
- private final Map<String, String> serverSideSettings;
-
public GlobalConfiguration(PropertyDefinitions propertyDefinitions, Encryption encryption, GlobalAnalysisMode mode,
- Map<String, String> settings, Map<String, String> serverSideSettings) {
+ Map<String, String> settings) {
super(propertyDefinitions, encryption, mode, settings);
- this.serverSideSettings = unmodifiableMapWithTrimmedValues(propertyDefinitions, serverSideSettings);
-
- get(CoreProperties.SERVER_ID).ifPresent(v -> LOG.info("Server id: {}", v));
- new DroppedPropertyChecker(getProperties(), DROPPED_PROPERTIES).checkDroppedProperties();
}
- public Map<String, String> getServerSideSettings() {
- return serverSideSettings;
- }
}
import java.util.Map;
import org.picocontainer.injectors.ProviderAdapter;
import org.sonar.api.config.PropertyDefinitions;
-import org.sonar.scanner.repository.settings.SettingsLoader;
public class GlobalConfigurationProvider extends ProviderAdapter {
- private GlobalConfiguration globalSettings;
+ private GlobalConfiguration globalConfig;
- public GlobalConfiguration provide(SettingsLoader loader, GlobalProperties globalProps, PropertyDefinitions propertyDefinitions, GlobalAnalysisMode mode) {
- if (globalSettings == null) {
+ public GlobalConfiguration provide(GlobalServerSettings globalServerSettings, ScannerProperties scannerProps, PropertyDefinitions propertyDefinitions, GlobalAnalysisMode mode) {
+ if (globalConfig == null) {
+ Map<String, String> mergedSettings = new LinkedHashMap<>();
+ mergedSettings.putAll(globalServerSettings.properties());
+ mergedSettings.putAll(scannerProps.properties());
- Map<String, String> serverSideSettings = loader.load(null);
-
- Map<String, String> settings = new LinkedHashMap<>();
- settings.putAll(serverSideSettings);
- settings.putAll(globalProps.properties());
-
- globalSettings = new GlobalConfiguration(propertyDefinitions, globalProps.getEncryption(), mode, settings, serverSideSettings);
+ globalConfig = new GlobalConfiguration(propertyDefinitions, scannerProps.getEncryption(), mode, mergedSettings);
}
- return globalSettings;
+ return globalConfig;
}
}
public class GlobalContainer extends ComponentContainer {
private static final Logger LOG = Loggers.get(GlobalContainer.class);
- private final Map<String, String> bootstrapProperties;
+ private final Map<String, String> scannerProperties;
- private GlobalContainer(Map<String, String> bootstrapProperties) {
+ private GlobalContainer(Map<String, String> scannerProperties) {
super();
- this.bootstrapProperties = bootstrapProperties;
+ this.scannerProperties = scannerProperties;
}
- public static GlobalContainer create(Map<String, String> bootstrapProperties, List<?> extensions) {
- GlobalContainer container = new GlobalContainer(bootstrapProperties);
+ public static GlobalContainer create(Map<String, String> scannerProperties, List<?> extensions) {
+ GlobalContainer container = new GlobalContainer(scannerProperties);
container.add(extensions);
return container;
}
@Override
protected void doBeforeStart() {
- GlobalProperties bootstrapProps = new GlobalProperties(bootstrapProperties);
- GlobalAnalysisMode globalMode = new GlobalAnalysisMode(bootstrapProps);
- add(bootstrapProps);
+ ScannerProperties scannerProps = new ScannerProperties(scannerProperties);
+ GlobalAnalysisMode globalMode = new GlobalAnalysisMode(scannerProps);
+ add(scannerProps);
add(globalMode);
addBootstrapComponents();
}
new SonarQubeVersion(apiVersion),
SonarRuntimeImpl.forSonarQube(apiVersion, SonarQubeSide.SCANNER),
StoragesManager.class,
- MutableGlobalSettings.class,
+ new GlobalServerSettingsProvider(),
new GlobalConfigurationProvider(),
new ScannerWsClientProvider(),
DefaultServer.class,
+++ /dev/null
-/*
- * 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.Map;
-import org.sonar.api.CoreProperties;
-
-/**
- * Immutable batch properties that are not specific to a task (for example
- * coming from global configuration file of sonar-runner).
- */
-public class GlobalProperties extends UserProperties {
-
- public GlobalProperties(Map<String, String> properties) {
- super(properties, properties.get(CoreProperties.ENCRYPTION_SECRET_KEY_PATH));
- }
-
-}
--- /dev/null
+/*
+ * 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.collect.ImmutableMap;
+import java.util.Map;
+import javax.annotation.concurrent.Immutable;
+
+/**
+ * Global properties coming from the server.
+ */
+@Immutable
+public class GlobalServerSettings {
+
+ private final Map<String, String> properties;
+
+ public GlobalServerSettings(Map<String, String> properties) {
+ this.properties = properties;
+ }
+
+ public Map<String, String> properties() {
+ return ImmutableMap.copyOf(properties);
+ }
+
+ public String property(String key) {
+ return properties.get(key);
+ }
+
+}
--- /dev/null
+/*
+ * 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.Map;
+import java.util.Optional;
+import org.picocontainer.injectors.ProviderAdapter;
+import org.sonar.api.CoreProperties;
+import org.sonar.api.utils.log.Logger;
+import org.sonar.api.utils.log.Loggers;
+import org.sonar.scanner.repository.settings.SettingsLoader;
+
+public class GlobalServerSettingsProvider extends ProviderAdapter {
+
+ private static final Logger LOG = Loggers.get(GlobalServerSettingsProvider.class);
+
+ private GlobalServerSettings singleton;
+
+ public GlobalServerSettings provide(SettingsLoader loader) {
+ if (singleton == null) {
+ Map<String, String> serverSideSettings = loader.load(null);
+ singleton = new GlobalServerSettings(serverSideSettings);
+ Optional.ofNullable(serverSideSettings.get(CoreProperties.SERVER_ID)).ifPresent(v -> LOG.info("Server id: {}", v));
+ }
+ return singleton;
+ }
+}
this.system = system;
}
- public TempFolder provide(GlobalProperties bootstrapProps) {
+ public TempFolder provide(ScannerProperties scannerProps) {
if (tempFolder == null) {
- String workingPathName = StringUtils.defaultIfBlank(bootstrapProps.property(CoreProperties.GLOBAL_WORKING_DIRECTORY), CoreProperties.GLOBAL_WORKING_DIRECTORY_DEFAULT_VALUE);
+ String workingPathName = StringUtils.defaultIfBlank(scannerProps.property(CoreProperties.GLOBAL_WORKING_DIRECTORY), CoreProperties.GLOBAL_WORKING_DIRECTORY_DEFAULT_VALUE);
Path workingPath = Paths.get(workingPathName);
if (!workingPath.isAbsolute()) {
- Path home = findSonarHome(bootstrapProps);
+ Path home = findSonarHome(scannerProps);
workingPath = home.resolve(workingPath).normalize();
}
try {
}
}
- private Path findSonarHome(GlobalProperties props) {
+ private Path findSonarHome(ScannerProperties props) {
String home = props.property("sonar.userHome");
if (home != null) {
return Paths.get(home).toAbsolutePath();
+++ /dev/null
-/*
- * 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 java.util.Optional;
-import org.sonar.api.config.Settings;
-import org.sonar.api.utils.MessageException;
-
-import static java.util.Objects.requireNonNull;
-
-/**
- * @deprecated since 6.5 {@link GlobalConfiguration} used to be mutable, so keep a mutable copy for backward compatibility.
- */
-@Deprecated
-public class MutableGlobalSettings extends Settings {
-
- private final GlobalAnalysisMode mode;
- private final Map<String, String> mutableProperties = new HashMap<>();
-
- public MutableGlobalSettings(GlobalConfiguration globalSettings) {
- super(globalSettings.getDefinitions(), globalSettings.getEncryption());
- this.mutableProperties.putAll(globalSettings.getProperties());
- this.mode = globalSettings.getMode();
- }
-
- @Override
- protected Optional<String> get(String key) {
- if (mode.isIssues() && key.endsWith(".secured") && !key.contains(".license")) {
- throw MessageException.of("Access to the secured property '" + key
- + "' is not possible in issues mode. The SonarQube plugin which requires this property must be deactivated in issues mode.");
- }
- return Optional.ofNullable(mutableProperties.get(key));
- }
-
- @Override
- public Map<String, String> getProperties() {
- return mutableProperties;
- }
-
- @Override
- protected void set(String key, String value) {
- mutableProperties.put(
- requireNonNull(key, "key can't be null"),
- requireNonNull(value, "value can't be null").trim());
- }
-
- @Override
- protected void remove(String key) {
- mutableProperties.remove(key);
- }
-}
--- /dev/null
+/*
+ * 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.collect.ImmutableMap;
+import java.util.HashMap;
+import java.util.Map;
+import javax.annotation.CheckForNull;
+import javax.annotation.concurrent.Immutable;
+import org.sonar.api.CoreProperties;
+import org.sonar.api.batch.bootstrap.ProjectKey;
+import org.sonar.api.config.Encryption;
+
+import static org.apache.commons.lang.StringUtils.trimToNull;
+
+/**
+ * Properties that are coming from scanner.
+ */
+@Immutable
+public class ScannerProperties implements ProjectKey {
+
+ private final Map<String, String> properties;
+ private final Encryption encryption;
+
+ public ScannerProperties(Map<String, String> properties) {
+ encryption = new Encryption(properties.get(CoreProperties.ENCRYPTION_SECRET_KEY_PATH));
+ Map<String, String> decryptedProps = new HashMap<>(properties.size());
+ for (Map.Entry<String, String> entry : properties.entrySet()) {
+ String value = entry.getValue();
+ if (value != null && encryption.isEncrypted(value)) {
+ try {
+ value = encryption.decrypt(value);
+ } catch (Exception e) {
+ throw new IllegalStateException("Fail to decrypt the property " + entry.getKey() + ". Please check your secret key.", e);
+ }
+ }
+ decryptedProps.put(entry.getKey(), value);
+ }
+ this.properties = decryptedProps;
+ }
+
+ public Encryption getEncryption() {
+ return encryption;
+ }
+
+ public Map<String, String> properties() {
+ return ImmutableMap.copyOf(properties);
+ }
+
+ public String property(String key) {
+ return properties.get(key);
+ }
+
+ @Override
+ public String get() {
+ return getKeyWithBranch();
+ }
+
+ private String getKey() {
+ return properties.get(CoreProperties.PROJECT_KEY_PROPERTY);
+ }
+
+ public String getKeyWithBranch() {
+ String branch = getBranch();
+ String projectKey = getKey();
+ if (branch == null) {
+ return projectKey;
+ }
+ return String.format("%s:%s", projectKey, branch);
+ }
+
+ @CheckForNull
+ private String getBranch() {
+ return trimToNull(properties.get(CoreProperties.PROJECT_BRANCH_PROPERTY));
+ }
+}
private ScannerWsClient wsClient;
- public synchronized ScannerWsClient provide(final GlobalProperties settings, final EnvironmentInformation env,
- GlobalAnalysisMode globalMode, System2 system) {
+ public synchronized ScannerWsClient provide(final ScannerProperties scannerProps, final EnvironmentInformation env,
+ GlobalAnalysisMode globalMode, System2 system) {
if (wsClient == null) {
- String url = defaultIfBlank(settings.property("sonar.host.url"), CoreProperties.SERVER_BASE_URL_DEFAULT_VALUE);
+ String url = defaultIfBlank(scannerProps.property("sonar.host.url"), CoreProperties.SERVER_BASE_URL_DEFAULT_VALUE);
HttpConnector.Builder connectorBuilder = HttpConnector.newBuilder();
- String timeoutSec = defaultIfBlank(settings.property(READ_TIMEOUT_SEC_PROPERTY), valueOf(DEFAULT_READ_TIMEOUT_SEC));
+ String timeoutSec = defaultIfBlank(scannerProps.property(READ_TIMEOUT_SEC_PROPERTY), valueOf(DEFAULT_READ_TIMEOUT_SEC));
String token = defaultIfBlank(system.envVariable("SONAR_TOKEN"), null);
- String login = defaultIfBlank(settings.property(CoreProperties.LOGIN), token);
+ String login = defaultIfBlank(scannerProps.property(CoreProperties.LOGIN), token);
connectorBuilder
.readTimeoutMilliseconds(parseInt(timeoutSec) * 1_000)
.connectTimeoutMilliseconds(CONNECT_TIMEOUT_MS)
.userAgent(env.toString())
.url(url)
- .credentials(login, settings.property(CoreProperties.PASSWORD));
+ .credentials(login, scannerProps.property(CoreProperties.PASSWORD));
// OkHttp detect 'http.proxyHost' java property, but credentials should be filled
final String proxyUser = System.getProperty("http.proxyUser", "");
+++ /dev/null
-/*
- * 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 javax.annotation.Nullable;
-import org.sonar.api.config.Encryption;
-
-/**
- * Properties that are coming from bootstrapper.
- */
-public abstract class UserProperties {
-
- private final Map<String, String> properties;
- private final Encryption encryption;
-
- public UserProperties(Map<String, String> properties, @Nullable String pathToSecretKey) {
- encryption = new Encryption(pathToSecretKey);
- Map<String, String> decryptedProps = new HashMap<>(properties.size());
- for (Map.Entry<String, String> entry : properties.entrySet()) {
- String value = entry.getValue();
- if (value != null && encryption.isEncrypted(value)) {
- try {
- value = encryption.decrypt(value);
- } catch (Exception e) {
- throw new IllegalStateException("Fail to decrypt the property " + entry.getKey() + ". Please check your secret key.", e);
- }
- }
- decryptedProps.put(entry.getKey(), value);
- }
- this.properties = decryptedProps;
- }
-
- public Encryption getEncryption() {
- return encryption;
- }
-
- public Map<String, String> properties() {
- return properties;
- }
-
- public String property(String key) {
- return properties.get(key);
- }
-
-}
}
})::iterator;
- publisher.getWriter().writeComponentDuplications(component.batchId(), reportDuplications);
+ publisher.getWriter().writeComponentDuplications(component.scannerId(), reportDuplications);
}
private Optional<FileBlocks> toFileBlocks(String componentKey, Collection<Block> fileBlocks) {
String componentKey = duplicate.getResourceId();
if (!component.key().equals(componentKey)) {
DefaultInputComponent sameProjectComponent = (DefaultInputComponent) componentStore.getByKey(componentKey);
- blockBuilder.setOtherFileRef(sameProjectComponent.batchId());
+ blockBuilder.setOtherFileRef(sameProjectComponent.scannerId());
}
dupBuilder.addDuplicate(blockBuilder
.setRange(ScannerReport.TextRange.newBuilder()
import org.apache.commons.lang.StringUtils;
import org.sonar.api.CoreProperties;
-import org.sonar.api.batch.fs.internal.InputModuleHierarchy;
+import org.sonar.api.batch.fs.internal.DefaultInputProject;
import org.sonar.api.config.Configuration;
import org.sonar.duplications.block.BlockChunker;
private final Configuration settings;
private final String branch;
- public CpdSettings(Configuration settings, InputModuleHierarchy hierarchy) {
- this.settings = settings;
- this.branch = hierarchy.root().getBranch();
+ public CpdSettings(Configuration config, DefaultInputProject project) {
+ this.settings = config;
+ this.branch = project.getBranch();
}
public boolean isCrossProjectDuplicationEnabled() {
public void insert(InputFile inputFile, Collection<Block> blocks) {
if (settings.isCrossProjectDuplicationEnabled()) {
- int id = ((DefaultInputFile) inputFile).batchId();
+ int id = ((DefaultInputFile) inputFile).scannerId();
if (publisher.getWriter().hasComponentData(FileStructure.Domain.CPD_TEXT_BLOCKS, id)) {
throw new UnsupportedOperationException("Trying to save CPD tokens twice for the same file is not supported: " + inputFile.absolutePath());
}
import org.apache.commons.lang.builder.ToStringStyle;
import org.sonar.api.batch.fs.InputModule;
import org.sonar.api.batch.fs.TextRange;
-import org.sonar.api.batch.fs.internal.DefaultInputModule;
+import org.sonar.api.batch.fs.internal.AbstractProjectOrModule;
import org.sonar.api.batch.fs.internal.DefaultTextPointer;
import org.sonar.api.batch.fs.internal.DefaultTextRange;
import org.sonar.api.rule.RuleKey;
private final Issue rawIssue;
private final ProjectAnalysisInfo projectAnalysisInfo;
private final String componentKey;
- private DefaultInputModule module;
+ private AbstractProjectOrModule module;
public DefaultFilterableIssue(InputModule module, ProjectAnalysisInfo projectAnalysisInfo, Issue rawIssue, String componentKey) {
- this.module = (DefaultInputModule) module;
+ this.module = (AbstractProjectOrModule) module;
this.projectAnalysisInfo = projectAnalysisInfo;
this.rawIssue = rawIssue;
this.componentKey = componentKey;
*/
package org.sonar.scanner.issue;
-import org.sonar.api.batch.fs.internal.DefaultInputModule;
+import org.sonar.api.batch.fs.InputModule;
import org.sonar.api.scan.issue.filter.FilterableIssue;
import org.sonar.api.scan.issue.filter.IssueFilter;
import org.sonar.api.scan.issue.filter.IssueFilterChain;
@Deprecated
public class ModuleIssueFilters {
private final IssueFilterChain filterChain;
- private final DefaultInputModule module;
+ private final InputModule module;
private final ProjectAnalysisInfo projectAnalysisInfo;
- public ModuleIssueFilters(DefaultInputModule module, ProjectAnalysisInfo projectAnalysisInfo, IssueFilter[] exclusionFilters) {
+ public ModuleIssueFilters(InputModule module, ProjectAnalysisInfo projectAnalysisInfo, IssueFilter[] exclusionFilters) {
this.module = module;
this.filterChain = new DefaultIssueFilterChain(exclusionFilters);
this.projectAnalysisInfo = projectAnalysisInfo;
}
- public ModuleIssueFilters(DefaultInputModule module, ProjectAnalysisInfo projectAnalysisInfo) {
+ public ModuleIssueFilters(InputModule module, ProjectAnalysisInfo projectAnalysisInfo) {
this(module, projectAnalysisInfo, new IssueFilter[0]);
}
return false;
}
- ScannerReport.Issue rawIssue = createReportIssue(issue, inputComponent.batchId(), activeRule.severity());
+ ScannerReport.Issue rawIssue = createReportIssue(issue, inputComponent.scannerId(), activeRule.severity());
if (filters.accept(inputComponent.key(), rawIssue)) {
- write(inputComponent.batchId(), rawIssue);
+ write(inputComponent.scannerId(), rawIssue);
return true;
}
return false;
public void initAndAddExternalIssue(ExternalIssue issue) {
DefaultInputComponent inputComponent = (DefaultInputComponent) issue.primaryLocation().inputComponent();
- ScannerReport.ExternalIssue rawExternalIssue = createReportExternalIssue(issue, inputComponent.batchId());
- write(inputComponent.batchId(), rawExternalIssue);
+ ScannerReport.ExternalIssue rawExternalIssue = createReportExternalIssue(issue, inputComponent.scannerId());
+ write(inputComponent.scannerId(), rawExternalIssue);
}
private static ScannerReport.Issue createReportIssue(Issue issue, int componentRef, String activeRuleSeverity) {
}
flowBuilder.clear();
for (org.sonar.api.batch.sensor.issue.IssueLocation location : flow.locations()) {
- int locationComponentRef = ((DefaultInputComponent) location.inputComponent()).batchId();
+ int locationComponentRef = ((DefaultInputComponent) location.inputComponent()).scannerId();
locationBuilder.clear();
locationBuilder.setComponentRef(locationComponentRef);
String message = location.message();
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.batchId())) {
+ try (CloseableIterator<ScannerReport.Issue> it = reader.readComponentIssues(component.scannerId())) {
while (it.hasNext()) {
rawIssues.add(it.next());
}
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.DefaultInputModule;
+import org.sonar.api.batch.fs.internal.AbstractProjectOrModule;
import org.sonar.api.batch.fs.internal.InputComponentTree;
import org.sonar.api.batch.rule.ActiveRule;
import org.sonar.api.batch.rule.ActiveRules;
private SourceHashHolder loadSourceHashes(InputComponent component) {
SourceHashHolder sourceHashHolder = null;
if (component.isFile()) {
- DefaultInputModule module = (DefaultInputModule) componentTree.getParent(componentTree.getParent(component));
+ AbstractProjectOrModule module = (AbstractProjectOrModule) componentTree.getParent(componentTree.getParent(component));
DefaultInputFile file = (DefaultInputFile) component;
sourceHashHolder = new SourceHashHolder(module, file, lastLineHashes);
}
import org.sonar.api.batch.InstantiationStrategy;
import org.sonar.api.batch.ScannerSide;
import org.sonar.api.batch.fs.InputComponent;
-import org.sonar.api.batch.fs.InputModule;
+import org.sonar.api.batch.fs.internal.AbstractProjectOrModule;
import org.sonar.api.batch.fs.internal.DefaultInputComponent;
-import org.sonar.api.batch.fs.internal.DefaultInputModule;
import org.sonar.api.utils.log.Logger;
import org.sonar.api.utils.log.Loggers;
import org.sonar.api.utils.log.Profiler;
private Storage<ServerIssue> issuesCache;
private final ServerIssuesLoader previousIssuesLoader;
private final InputComponentStore componentStore;
+ private final AbstractProjectOrModule project;
- public ServerIssueRepository(Storages caches, ServerIssuesLoader previousIssuesLoader, InputComponentStore componentStore) {
+ 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());
- DefaultInputModule root = (DefaultInputModule) componentStore.root();
- previousIssuesLoader.load(root.getKeyWithBranch(), this::store);
+ previousIssuesLoader.load(project.getKeyWithBranch(), this::store);
profiler.stopInfo();
}
public Iterable<ServerIssue> byComponent(InputComponent component) {
- return issuesCache.values(((DefaultInputComponent) component).batchId());
+ return issuesCache.values(((DefaultInputComponent) component).scannerId());
}
private void store(ServerIssue issue) {
String moduleKeyWithBranch = issue.getModuleKey();
- InputModule module = componentStore.getModule(moduleKeyWithBranch);
- if (module != null) {
- String componentKeyWithoutBranch = ComponentKeys.createEffectiveKey(module.key(), issue.hasPath() ? issue.getPath() : null);
+ 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.batchId(), issue.getKey(), issue);
+ issuesCache.put(r.scannerId(), issue.getKey(), issue);
return;
}
}
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.DefaultInputModule;
+import org.sonar.api.batch.fs.internal.AbstractProjectOrModule;
import org.sonar.core.component.ComponentKeys;
public class SourceHashHolder {
- private final DefaultInputModule module;
+ private final AbstractProjectOrModule module;
private final DefaultInputFile inputFile;
private final ServerLineHashesLoader lastSnapshots;
private FileHashes hashedReference;
private FileHashes hashedSource;
- public SourceHashHolder(DefaultInputModule module, DefaultInputFile inputFile, ServerLineHashesLoader lastSnapshots) {
+ public SourceHashHolder(AbstractProjectOrModule module, DefaultInputFile inputFile, ServerLineHashesLoader lastSnapshots) {
this.module = module;
this.inputFile = inputFile;
this.lastSnapshots = lastSnapshots;
--- /dev/null
+/*
+ * 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;
+
+import org.sonar.api.ExtensionPoint;
+import org.sonar.api.batch.ScannerSide;
+import org.sonar.scanner.scan.ProjectScanContainer;
+
+@ScannerSide
+@ExtensionPoint
+@FunctionalInterface
+public interface AnalysisObserver {
+
+ void analysisCompleted(ProjectScanContainer container);
+
+}
--- /dev/null
+/*
+ * 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;
+
+import org.sonar.scanner.scan.ProjectScanContainer;
+
+public class AnalysisObservers {
+
+ private AnalysisObserver[] observers;
+ private ProjectScanContainer projectScanContainer;
+
+ public AnalysisObservers(ProjectScanContainer projectScanContainer, AnalysisObserver... observers) {
+ this.projectScanContainer = projectScanContainer;
+ this.observers = observers;
+ }
+
+ public AnalysisObservers(ProjectScanContainer projectScanContainer) {
+ this(projectScanContainer, new AnalysisObserver[0]);
+ }
+
+ public void notifyEndOfScanTask() {
+ for (AnalysisObserver analysisObserver : observers) {
+ analysisObserver.analysisCompleted(projectScanContainer);
+ }
+ }
+
+}
--- /dev/null
+/*
+ * 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;
+
+import com.google.common.collect.Iterators;
+import com.google.common.collect.Lists;
+import java.io.InputStream;
+import java.util.ArrayList;
+import java.util.Collection;
+import java.util.Collections;
+import java.util.HashMap;
+import java.util.List;
+import java.util.Map;
+import javax.annotation.CheckForNull;
+import org.apache.commons.io.FileUtils;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+import org.sonar.api.batch.AnalysisMode;
+import org.sonar.api.batch.fs.InputComponent;
+import org.sonar.api.batch.fs.InputDir;
+import org.sonar.api.batch.fs.InputFile;
+import org.sonar.api.batch.fs.TextPointer;
+import org.sonar.api.batch.fs.TextRange;
+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.Metadata;
+import org.sonar.scanner.protocol.output.ScannerReport.Symbol;
+import org.sonar.scanner.protocol.output.ScannerReportReader;
+import org.sonar.scanner.report.ReportPublisher;
+import org.sonar.scanner.report.ScannerReportUtils;
+import org.sonar.scanner.scan.ProjectScanContainer;
+import org.sonar.scanner.scan.filesystem.InputComponentStore;
+
+import static org.apache.commons.lang.StringUtils.isNotEmpty;
+
+public class AnalysisResult implements AnalysisObserver {
+
+ private static final Logger LOG = LoggerFactory.getLogger(AnalysisResult.class);
+
+ private List<TrackedIssue> issues = new ArrayList<>();
+ private Map<String, InputFile> inputFiles = new HashMap<>();
+ private Map<String, Component> reportComponents = new HashMap<>();
+ private Map<String, InputDir> inputDirs = new HashMap<>();
+ private InputProject project;
+ private ScannerReportReader reader;
+
+ @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());
+ if (!container.getComponentByType(AnalysisMode.class).isIssues()) {
+ Metadata readMetadata = getReportReader().readMetadata();
+ int rootComponentRef = readMetadata.getRootComponentRef();
+ storeReportComponents(rootComponentRef, null);
+ project = container.getComponentByType(InputProject.class);
+ }
+
+ storeFs(container);
+
+ }
+
+ private void storeReportComponents(int componentRef, String parentModuleKey) {
+ Component component = getReportReader().readComponent(componentRef);
+ if (isNotEmpty(component.getKey())) {
+ reportComponents.put(component.getKey(), component);
+ } else {
+ reportComponents.put(parentModuleKey + ":" + component.getPath(), component);
+ }
+ for (int childId : component.getChildRefList()) {
+ storeReportComponents(childId, isNotEmpty(component.getKey()) ? component.getKey() : parentModuleKey);
+ }
+
+ }
+
+ public ScannerReportReader getReportReader() {
+ return reader;
+ }
+
+ private void storeFs(ProjectScanContainer container) {
+ InputComponentStore inputFileCache = container.getComponentByType(InputComponentStore.class);
+ for (InputFile inputPath : inputFileCache.allFiles()) {
+ inputFiles.put(((DefaultInputFile) inputPath).getProjectRelativePath(), inputPath);
+ }
+ for (InputDir inputPath : inputFileCache.allDirs()) {
+ inputDirs.put(inputPath.relativePath(), inputPath);
+ }
+ }
+
+ public List<TrackedIssue> trackedIssues() {
+ return issues;
+ }
+
+ public Component getReportComponent(String key) {
+ return reportComponents.get(key);
+ }
+
+ public List<ScannerReport.Issue> issuesFor(InputComponent inputComponent) {
+ int ref = reportComponents.get(inputComponent.key()).getRef();
+ return issuesFor(ref);
+ }
+
+ public List<ScannerReport.ExternalIssue> externalIssuesFor(InputComponent inputComponent) {
+ int ref = reportComponents.get(inputComponent.key()).getRef();
+ return externalIssuesFor(ref);
+ }
+
+ public List<ScannerReport.Issue> issuesFor(Component reportComponent) {
+ int ref = reportComponent.getRef();
+ return issuesFor(ref);
+ }
+
+ private List<ScannerReport.Issue> issuesFor(int ref) {
+ List<ScannerReport.Issue> result = Lists.newArrayList();
+ try (CloseableIterator<ScannerReport.Issue> it = reader.readComponentIssues(ref)) {
+ while (it.hasNext()) {
+ result.add(it.next());
+ }
+ }
+ return result;
+ }
+
+ private List<ScannerReport.ExternalIssue> externalIssuesFor(int ref) {
+ List<ScannerReport.ExternalIssue> result = Lists.newArrayList();
+ try (CloseableIterator<ScannerReport.ExternalIssue> it = reader.readComponentExternalIssues(ref)) {
+ while (it.hasNext()) {
+ result.add(it.next());
+ }
+ }
+ return result;
+ }
+
+ public InputProject project() {
+ return project;
+ }
+
+ public Collection<InputFile> inputFiles() {
+ return inputFiles.values();
+ }
+
+ @CheckForNull
+ public InputFile inputFile(String relativePath) {
+ return inputFiles.get(relativePath);
+ }
+
+ public Collection<InputDir> inputDirs() {
+ return inputDirs.values();
+ }
+
+ @CheckForNull
+ public InputDir inputDir(String relativePath) {
+ return inputDirs.get(relativePath);
+ }
+
+ public Map<String, List<ScannerReport.Measure>> allMeasures() {
+ Map<String, List<ScannerReport.Measure>> result = new HashMap<>();
+ for (Map.Entry<String, Component> component : reportComponents.entrySet()) {
+ List<ScannerReport.Measure> measures = new ArrayList<>();
+ try (CloseableIterator<ScannerReport.Measure> it = reader.readComponentMeasures(component.getValue().getRef())) {
+ Iterators.addAll(measures, it);
+ }
+ result.put(component.getKey(), measures);
+ }
+ return result;
+ }
+
+ /**
+ * Get highlighting types at a given position in an inputfile
+ * @param lineOffset 0-based offset in file
+ */
+ public List<TypeOfText> highlightingTypeFor(InputFile file, int line, int lineOffset) {
+ int ref = reportComponents.get(file.key()).getRef();
+ if (!reader.hasSyntaxHighlighting(ref)) {
+ return Collections.emptyList();
+ }
+ TextPointer pointer = file.newPointer(line, lineOffset);
+ List<TypeOfText> result = new ArrayList<>();
+ try (CloseableIterator<ScannerReport.SyntaxHighlightingRule> it = reader.readComponentSyntaxHighlighting(ref)) {
+ while (it.hasNext()) {
+ ScannerReport.SyntaxHighlightingRule rule = it.next();
+ TextRange ruleRange = toRange(file, rule.getRange());
+ if (ruleRange.start().compareTo(pointer) <= 0 && ruleRange.end().compareTo(pointer) > 0) {
+ result.add(ScannerReportUtils.toBatchType(rule.getType()));
+ }
+ }
+ } catch (Exception e) {
+ throw new IllegalStateException("Can't read syntax highlighting for " + file, e);
+ }
+ return result;
+ }
+
+ private static TextRange toRange(InputFile file, ScannerReport.TextRange reportRange) {
+ return file.newRange(file.newPointer(reportRange.getStartLine(), reportRange.getStartOffset()), file.newPointer(reportRange.getEndLine(), reportRange.getEndOffset()));
+ }
+
+ /**
+ * Get list of all start positions of a symbol in an inputfile
+ * @param symbolStartLine 0-based start offset for the symbol in file
+ * @param symbolStartLineOffset 0-based end offset for the symbol in file
+ */
+ @CheckForNull
+ public List<ScannerReport.TextRange> symbolReferencesFor(InputFile file, int symbolStartLine, int symbolStartLineOffset) {
+ int ref = reportComponents.get(file.key()).getRef();
+ try (CloseableIterator<Symbol> symbols = getReportReader().readComponentSymbols(ref)) {
+ while (symbols.hasNext()) {
+ Symbol symbol = symbols.next();
+ if (symbol.getDeclaration().getStartLine() == symbolStartLine && symbol.getDeclaration().getStartOffset() == symbolStartLineOffset) {
+ return symbol.getReferenceList();
+ }
+ }
+ }
+ return Collections.emptyList();
+ }
+
+ public List<ScannerReport.Duplication> duplicationsFor(InputFile file) {
+ List<ScannerReport.Duplication> result = new ArrayList<>();
+ int ref = reportComponents.get(file.key()).getRef();
+ try (CloseableIterator<ScannerReport.Duplication> it = getReportReader().readComponentDuplications(ref)) {
+ while (it.hasNext()) {
+ result.add(it.next());
+ }
+ } catch (Exception e) {
+ throw new IllegalStateException(e);
+ }
+ return result;
+ }
+
+ public List<ScannerReport.CpdTextBlock> duplicationBlocksFor(InputFile file) {
+ List<ScannerReport.CpdTextBlock> result = new ArrayList<>();
+ int ref = reportComponents.get(file.key()).getRef();
+ try (CloseableIterator<ScannerReport.CpdTextBlock> it = getReportReader().readCpdTextBlocks(ref)) {
+ while (it.hasNext()) {
+ result.add(it.next());
+ }
+ } catch (Exception e) {
+ throw new IllegalStateException(e);
+ }
+ return result;
+ }
+
+ @CheckForNull
+ public ScannerReport.LineCoverage coverageFor(InputFile file, int line) {
+ int ref = reportComponents.get(file.key()).getRef();
+ try (CloseableIterator<ScannerReport.LineCoverage> it = getReportReader().readComponentCoverage(ref)) {
+ while (it.hasNext()) {
+ ScannerReport.LineCoverage coverage = it.next();
+ if (coverage.getLine() == line) {
+ return coverage;
+ }
+ }
+ } catch (Exception e) {
+ throw new IllegalStateException(e);
+ }
+ return null;
+ }
+
+ public ScannerReport.Test firstTestExecutionForName(InputFile testFile, String testName) {
+ int ref = reportComponents.get(testFile.key()).getRef();
+ try (InputStream inputStream = FileUtils.openInputStream(getReportReader().readTests(ref))) {
+ ScannerReport.Test test = ScannerReport.Test.parser().parseDelimitedFrom(inputStream);
+ while (test != null) {
+ if (test.getName().equals(testName)) {
+ return test;
+ }
+ test = ScannerReport.Test.parser().parseDelimitedFrom(inputStream);
+ }
+ } catch (Exception e) {
+ throw new IllegalStateException(e);
+ }
+ return null;
+ }
+
+ public ScannerReport.CoverageDetail coveragePerTestFor(InputFile testFile, String testName) {
+ int ref = reportComponents.get(testFile.key()).getRef();
+ try (InputStream inputStream = FileUtils.openInputStream(getReportReader().readCoverageDetails(ref))) {
+ ScannerReport.CoverageDetail details = ScannerReport.CoverageDetail.parser().parseDelimitedFrom(inputStream);
+ while (details != null) {
+ if (details.getTestName().equals(testName)) {
+ return details;
+ }
+ details = ScannerReport.CoverageDetail.parser().parseDelimitedFrom(inputStream);
+ }
+ } catch (Exception e) {
+ throw new IllegalStateException(e);
+ }
+ return null;
+ }
+
+ public List<ScannerReport.AdHocRule> adHocRules() {
+ List<ScannerReport.AdHocRule> result = new ArrayList<>();
+ try (CloseableIterator<ScannerReport.AdHocRule> it = getReportReader().readAdHocRules()) {
+ while (it.hasNext()) {
+ result.add(it.next());
+ }
+ } catch (Exception e) {
+ throw new IllegalStateException(e);
+ }
+ return result;
+ }
+}
+++ /dev/null
-/*
- * 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;
-
-import org.sonar.api.ExtensionPoint;
-import org.sonar.api.batch.ScannerSide;
-import org.sonar.scanner.scan.ProjectScanContainer;
-
-@ScannerSide
-@ExtensionPoint
-@FunctionalInterface
-public interface ScanTaskObserver {
-
- void scanTaskCompleted(ProjectScanContainer container);
-
-}
+++ /dev/null
-/*
- * 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;
-
-import org.sonar.scanner.scan.ProjectScanContainer;
-
-public class ScanTaskObservers {
-
- private ScanTaskObserver[] observers;
- private ProjectScanContainer projectScanContainer;
-
- public ScanTaskObservers(ProjectScanContainer projectScanContainer, ScanTaskObserver... observers) {
- this.projectScanContainer = projectScanContainer;
- this.observers = observers;
- }
-
- public ScanTaskObservers(ProjectScanContainer projectScanContainer) {
- this(projectScanContainer, new ScanTaskObserver[0]);
- }
-
- public void notifyEndOfScanTask() {
- for (ScanTaskObserver scanTaskObserver : observers) {
- scanTaskObserver.scanTaskCompleted(projectScanContainer);
- }
- }
-
-}
+++ /dev/null
-/*
- * 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;
-
-import com.google.common.collect.Iterators;
-import com.google.common.collect.Lists;
-import java.io.InputStream;
-import java.util.ArrayList;
-import java.util.Collection;
-import java.util.Collections;
-import java.util.HashMap;
-import java.util.List;
-import java.util.Map;
-import javax.annotation.CheckForNull;
-import org.apache.commons.io.FileUtils;
-import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
-import org.sonar.api.batch.AnalysisMode;
-import org.sonar.api.batch.fs.InputComponent;
-import org.sonar.api.batch.fs.InputDir;
-import org.sonar.api.batch.fs.InputFile;
-import org.sonar.api.batch.fs.InputModule;
-import org.sonar.api.batch.fs.TextPointer;
-import org.sonar.api.batch.fs.TextRange;
-import org.sonar.api.batch.fs.internal.DefaultInputFile;
-import org.sonar.api.batch.sensor.highlighting.TypeOfText;
-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.Metadata;
-import org.sonar.scanner.protocol.output.ScannerReport.Symbol;
-import org.sonar.scanner.protocol.output.ScannerReportReader;
-import org.sonar.scanner.report.ReportPublisher;
-import org.sonar.scanner.report.ScannerReportUtils;
-import org.sonar.scanner.scan.ProjectScanContainer;
-import org.sonar.scanner.scan.filesystem.InputComponentStore;
-
-import static org.apache.commons.lang.StringUtils.isNotEmpty;
-
-public class TaskResult implements org.sonar.scanner.mediumtest.ScanTaskObserver {
-
- private static final Logger LOG = LoggerFactory.getLogger(TaskResult.class);
-
- private List<TrackedIssue> issues = new ArrayList<>();
- private Map<String, InputFile> inputFiles = new HashMap<>();
- private Map<String, Component> reportComponents = new HashMap<>();
- private Map<String, InputDir> inputDirs = new HashMap<>();
- private InputModule root;
- private ScannerReportReader reader;
-
- @Override
- public void scanTaskCompleted(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());
- if (!container.getComponentByType(AnalysisMode.class).isIssues()) {
- Metadata readMetadata = getReportReader().readMetadata();
- int rootComponentRef = readMetadata.getRootComponentRef();
- storeReportComponents(rootComponentRef, null);
- InputComponentStore inputFileCache = container.getComponentByType(InputComponentStore.class);
- root = inputFileCache.root();
- }
-
- storeFs(container);
-
- }
-
- private void storeReportComponents(int componentRef, String parentModuleKey) {
- Component component = getReportReader().readComponent(componentRef);
- if (isNotEmpty(component.getKey())) {
- reportComponents.put(component.getKey(), component);
- } else {
- reportComponents.put(parentModuleKey + ":" + component.getPath(), component);
- }
- for (int childId : component.getChildRefList()) {
- storeReportComponents(childId, isNotEmpty(component.getKey()) ? component.getKey() : parentModuleKey);
- }
-
- }
-
- public ScannerReportReader getReportReader() {
- return reader;
- }
-
- private void storeFs(ProjectScanContainer container) {
- InputComponentStore inputFileCache = container.getComponentByType(InputComponentStore.class);
- for (InputFile inputPath : inputFileCache.allFiles()) {
- inputFiles.put(((DefaultInputFile) inputPath).getProjectRelativePath(), inputPath);
- }
- for (InputDir inputPath : inputFileCache.allDirs()) {
- inputDirs.put(inputPath.relativePath(), inputPath);
- }
- }
-
- public List<TrackedIssue> trackedIssues() {
- return issues;
- }
-
- public Component getReportComponent(String key) {
- return reportComponents.get(key);
- }
-
- public List<ScannerReport.Issue> issuesFor(InputComponent inputComponent) {
- int ref = reportComponents.get(inputComponent.key()).getRef();
- return issuesFor(ref);
- }
-
- public List<ScannerReport.ExternalIssue> externalIssuesFor(InputComponent inputComponent) {
- int ref = reportComponents.get(inputComponent.key()).getRef();
- return externalIssuesFor(ref);
- }
-
- public List<ScannerReport.Issue> issuesFor(Component reportComponent) {
- int ref = reportComponent.getRef();
- return issuesFor(ref);
- }
-
- private List<ScannerReport.Issue> issuesFor(int ref) {
- List<ScannerReport.Issue> result = Lists.newArrayList();
- try (CloseableIterator<ScannerReport.Issue> it = reader.readComponentIssues(ref)) {
- while (it.hasNext()) {
- result.add(it.next());
- }
- }
- return result;
- }
-
- private List<ScannerReport.ExternalIssue> externalIssuesFor(int ref) {
- List<ScannerReport.ExternalIssue> result = Lists.newArrayList();
- try (CloseableIterator<ScannerReport.ExternalIssue> it = reader.readComponentExternalIssues(ref)) {
- while (it.hasNext()) {
- result.add(it.next());
- }
- }
- return result;
- }
-
- public InputModule root() {
- return root;
- }
-
- public Collection<InputFile> inputFiles() {
- return inputFiles.values();
- }
-
- @CheckForNull
- public InputFile inputFile(String relativePath) {
- return inputFiles.get(relativePath);
- }
-
- public Collection<InputDir> inputDirs() {
- return inputDirs.values();
- }
-
- @CheckForNull
- public InputDir inputDir(String relativePath) {
- return inputDirs.get(relativePath);
- }
-
- public Map<String, List<ScannerReport.Measure>> allMeasures() {
- Map<String, List<ScannerReport.Measure>> result = new HashMap<>();
- for (Map.Entry<String, Component> component : reportComponents.entrySet()) {
- List<ScannerReport.Measure> measures = new ArrayList<>();
- try (CloseableIterator<ScannerReport.Measure> it = reader.readComponentMeasures(component.getValue().getRef())) {
- Iterators.addAll(measures, it);
- }
- result.put(component.getKey(), measures);
- }
- return result;
- }
-
- /**
- * Get highlighting types at a given position in an inputfile
- * @param lineOffset 0-based offset in file
- */
- public List<TypeOfText> highlightingTypeFor(InputFile file, int line, int lineOffset) {
- int ref = reportComponents.get(file.key()).getRef();
- if (!reader.hasSyntaxHighlighting(ref)) {
- return Collections.emptyList();
- }
- TextPointer pointer = file.newPointer(line, lineOffset);
- List<TypeOfText> result = new ArrayList<>();
- try (CloseableIterator<ScannerReport.SyntaxHighlightingRule> it = reader.readComponentSyntaxHighlighting(ref)) {
- while (it.hasNext()) {
- ScannerReport.SyntaxHighlightingRule rule = it.next();
- TextRange ruleRange = toRange(file, rule.getRange());
- if (ruleRange.start().compareTo(pointer) <= 0 && ruleRange.end().compareTo(pointer) > 0) {
- result.add(ScannerReportUtils.toBatchType(rule.getType()));
- }
- }
- } catch (Exception e) {
- throw new IllegalStateException("Can't read syntax highlighting for " + file, e);
- }
- return result;
- }
-
- private static TextRange toRange(InputFile file, ScannerReport.TextRange reportRange) {
- return file.newRange(file.newPointer(reportRange.getStartLine(), reportRange.getStartOffset()), file.newPointer(reportRange.getEndLine(), reportRange.getEndOffset()));
- }
-
- /**
- * Get list of all start positions of a symbol in an inputfile
- * @param symbolStartLine 0-based start offset for the symbol in file
- * @param symbolStartLineOffset 0-based end offset for the symbol in file
- */
- @CheckForNull
- public List<ScannerReport.TextRange> symbolReferencesFor(InputFile file, int symbolStartLine, int symbolStartLineOffset) {
- int ref = reportComponents.get(file.key()).getRef();
- try (CloseableIterator<Symbol> symbols = getReportReader().readComponentSymbols(ref)) {
- while (symbols.hasNext()) {
- Symbol symbol = symbols.next();
- if (symbol.getDeclaration().getStartLine() == symbolStartLine && symbol.getDeclaration().getStartOffset() == symbolStartLineOffset) {
- return symbol.getReferenceList();
- }
- }
- }
- return Collections.emptyList();
- }
-
- public List<ScannerReport.Duplication> duplicationsFor(InputFile file) {
- List<ScannerReport.Duplication> result = new ArrayList<>();
- int ref = reportComponents.get(file.key()).getRef();
- try (CloseableIterator<ScannerReport.Duplication> it = getReportReader().readComponentDuplications(ref)) {
- while (it.hasNext()) {
- result.add(it.next());
- }
- } catch (Exception e) {
- throw new IllegalStateException(e);
- }
- return result;
- }
-
- public List<ScannerReport.CpdTextBlock> duplicationBlocksFor(InputFile file) {
- List<ScannerReport.CpdTextBlock> result = new ArrayList<>();
- int ref = reportComponents.get(file.key()).getRef();
- try (CloseableIterator<ScannerReport.CpdTextBlock> it = getReportReader().readCpdTextBlocks(ref)) {
- while (it.hasNext()) {
- result.add(it.next());
- }
- } catch (Exception e) {
- throw new IllegalStateException(e);
- }
- return result;
- }
-
- @CheckForNull
- public ScannerReport.LineCoverage coverageFor(InputFile file, int line) {
- int ref = reportComponents.get(file.key()).getRef();
- try (CloseableIterator<ScannerReport.LineCoverage> it = getReportReader().readComponentCoverage(ref)) {
- while (it.hasNext()) {
- ScannerReport.LineCoverage coverage = it.next();
- if (coverage.getLine() == line) {
- return coverage;
- }
- }
- } catch (Exception e) {
- throw new IllegalStateException(e);
- }
- return null;
- }
-
- public ScannerReport.Test firstTestExecutionForName(InputFile testFile, String testName) {
- int ref = reportComponents.get(testFile.key()).getRef();
- try (InputStream inputStream = FileUtils.openInputStream(getReportReader().readTests(ref))) {
- ScannerReport.Test test = ScannerReport.Test.parser().parseDelimitedFrom(inputStream);
- while (test != null) {
- if (test.getName().equals(testName)) {
- return test;
- }
- test = ScannerReport.Test.parser().parseDelimitedFrom(inputStream);
- }
- } catch (Exception e) {
- throw new IllegalStateException(e);
- }
- return null;
- }
-
- public ScannerReport.CoverageDetail coveragePerTestFor(InputFile testFile, String testName) {
- int ref = reportComponents.get(testFile.key()).getRef();
- try (InputStream inputStream = FileUtils.openInputStream(getReportReader().readCoverageDetails(ref))) {
- ScannerReport.CoverageDetail details = ScannerReport.CoverageDetail.parser().parseDelimitedFrom(inputStream);
- while (details != null) {
- if (details.getTestName().equals(testName)) {
- return details;
- }
- details = ScannerReport.CoverageDetail.parser().parseDelimitedFrom(inputStream);
- }
- } catch (Exception e) {
- throw new IllegalStateException(e);
- }
- return null;
- }
-
- public List<ScannerReport.AdHocRule> adHocRules() {
- List<ScannerReport.AdHocRule> result = new ArrayList<>();
- try (CloseableIterator<ScannerReport.AdHocRule> it = getReportReader().readAdHocRules()) {
- while (it.hasNext()) {
- result.add(it.next());
- }
- } catch (Exception e) {
- throw new IllegalStateException(e);
- }
- return result;
- }
-}
import org.sonar.api.CoreProperties;
import org.sonar.api.batch.fs.InputFile;
import org.sonar.api.batch.fs.internal.DefaultInputFile;
+import org.sonar.api.batch.fs.internal.AbstractProjectOrModule;
import org.sonar.api.batch.fs.internal.DefaultInputModule;
import org.sonar.api.batch.fs.internal.InputModuleHierarchy;
import org.sonar.api.notifications.AnalysisWarnings;
}
}
- private void evaluateCoverageExclusions(DefaultInputModule module) {
+ private void evaluateCoverageExclusions(AbstractProjectOrModule module) {
if (!Arrays.equals(moduleCoverageExclusions.getCoverageExclusionConfig(), projectCoverageExclusions.getCoverageExclusionConfig())) {
moduleCoverageExclusions.log();
}
import javax.annotation.concurrent.Immutable;
import org.sonar.api.batch.fs.internal.DefaultInputFile;
-import org.sonar.api.config.Configuration;
+import org.sonar.scanner.scan.ModuleConfiguration;
@Immutable
public class ModuleCoverageExclusions extends AbstractCoverageExclusions {
- public ModuleCoverageExclusions(Configuration config) {
+ public ModuleCoverageExclusions(ModuleConfiguration config) {
super(config, DefaultInputFile::getModuleRelativePath);
}
}
import javax.annotation.concurrent.Immutable;
import org.sonar.api.batch.fs.internal.DefaultInputFile;
-import org.sonar.api.config.Configuration;
+import org.sonar.scanner.scan.ProjectConfiguration;
@Immutable
public class ProjectCoverageExclusions extends AbstractCoverageExclusions {
- public ProjectCoverageExclusions(Configuration projectConfig) {
+ public ProjectCoverageExclusions(ProjectConfiguration projectConfig) {
super(projectConfig, DefaultInputFile::getProjectRelativePath);
log();
}
private final boolean isRoot;
public SensorsExecutor(ScannerExtensionDictionnary selector, DefaultInputModule module, InputModuleHierarchy hierarchy,
- SensorStrategy strategy, ScannerPluginRepository pluginRepo) {
+ SensorStrategy strategy, ScannerPluginRepository pluginRepo) {
this.selector = selector;
this.strategy = strategy;
this.pluginRepo = pluginRepo;
import org.sonar.api.CoreProperties;
import org.sonar.api.SonarRuntime;
import org.sonar.api.batch.ScannerSide;
-import org.sonar.api.config.Settings;
+import org.sonar.api.config.Configuration;
import org.sonar.api.platform.Server;
import org.sonar.api.utils.DateUtils;
import org.sonar.scanner.bootstrap.ScannerWsClient;
@ScannerSide
public class DefaultServer extends Server {
- private final Settings settings;
+ private final Configuration settings;
private final ScannerWsClient client;
private final SonarRuntime runtime;
- public DefaultServer(Settings settings, ScannerWsClient client, SonarRuntime runtime) {
+ public DefaultServer(Configuration settings, ScannerWsClient client, SonarRuntime runtime) {
this.settings = settings;
this.client = client;
this.runtime = runtime;
@Override
public String getId() {
- return settings.getString(CoreProperties.SERVER_ID);
+ return settings.get(CoreProperties.SERVER_ID).orElseThrow(() -> new IllegalStateException("Mandatory"));
}
@Override
@Override
public Date getStartedAt() {
- String dateString = settings.getString(CoreProperties.SERVER_STARTTIME);
+ String dateString = settings.get(CoreProperties.SERVER_STARTTIME).orElseThrow(() -> new IllegalStateException("Mandatory"));
return DateUtils.parseDateTime(dateString);
}
@Override
public String getPublicRootUrl() {
- String baseUrl = trimToEmpty(settings.getString(CoreProperties.SERVER_BASE_URL));
+ String baseUrl = trimToEmpty(settings.get(CoreProperties.SERVER_BASE_URL).orElse(""));
if (baseUrl.isEmpty()) {
// If server base URL was not configured in Sonar server then is is better to take URL configured on batch side
baseUrl = client.baseUrl();
import org.sonar.api.CoreProperties;
import org.sonar.api.batch.AnalysisMode;
import org.sonar.api.batch.ScannerSide;
+import org.sonar.api.batch.fs.internal.AbstractProjectOrModule;
import org.sonar.api.batch.fs.internal.DefaultInputModule;
import org.sonar.api.batch.fs.internal.InputModuleHierarchy;
import org.sonar.api.utils.System2;
import org.sonar.api.utils.log.Logger;
import org.sonar.api.utils.log.Loggers;
import org.sonar.core.platform.PluginInfo;
-import org.sonar.scanner.bootstrap.GlobalConfiguration;
+import org.sonar.scanner.bootstrap.GlobalServerSettings;
import org.sonar.scanner.bootstrap.ScannerPluginRepository;
import org.sonar.scanner.protocol.output.ScannerReportWriter;
import org.sonar.scanner.repository.ProjectRepositories;
private final AnalysisMode mode;
private final System2 system;
private final ProjectRepositories projectRepos;
- private final GlobalConfiguration globalSettings;
+ private final GlobalServerSettings globalServerSettings;
private final InputModuleHierarchy hierarchy;
private ScannerReportWriter writer;
public AnalysisContextReportPublisher(AnalysisMode mode, ScannerPluginRepository pluginRepo, System2 system,
- ProjectRepositories projectRepos, GlobalConfiguration globalSettings, InputModuleHierarchy hierarchy) {
+ ProjectRepositories projectRepos, GlobalServerSettings globalServerSettings, InputModuleHierarchy hierarchy) {
this.mode = mode;
this.pluginRepo = pluginRepo;
this.system = system;
this.projectRepos = projectRepos;
- this.globalSettings = globalSettings;
+ this.globalServerSettings = globalServerSettings;
this.hierarchy = hierarchy;
}
private void writeGlobalSettings(BufferedWriter fileWriter) throws IOException {
fileWriter.append("Global properties:\n");
- Map<String, String> props = globalSettings.getServerSideSettings();
+ Map<String, String> props = globalServerSettings.properties();
for (String prop : new TreeSet<>(props.keySet())) {
dumpPropIfNotSensitive(fileWriter, prop, props.get(prop));
}
if (projectRepos.moduleExists(module.getKeyWithBranch())) {
moduleSpecificProps.putAll(projectRepos.settings(module.getKeyWithBranch()));
}
- DefaultInputModule parent = hierarchy.parent(module);
+ AbstractProjectOrModule parent = hierarchy.parent(module);
if (parent == null) {
moduleSpecificProps.putAll(module.properties());
} else {
import java.util.stream.Collectors;
import java.util.stream.StreamSupport;
import org.sonar.api.batch.fs.internal.DefaultInputFile;
-import org.sonar.api.batch.fs.internal.InputModuleHierarchy;
+import org.sonar.api.batch.fs.internal.DefaultInputProject;
import org.sonar.api.batch.scm.ScmProvider;
import org.sonar.api.utils.log.Logger;
import org.sonar.api.utils.log.Loggers;
private static final String LOG_MSG = "SCM writing changed lines";
private final ScmConfiguration scmConfiguration;
- private final InputModuleHierarchy inputModuleHierarchy;
+ private final DefaultInputProject project;
private final InputComponentStore inputComponentStore;
private final BranchConfiguration branchConfiguration;
- public ChangedLinesPublisher(ScmConfiguration scmConfiguration, InputModuleHierarchy inputModuleHierarchy, InputComponentStore inputComponentStore,
+ public ChangedLinesPublisher(ScmConfiguration scmConfiguration, DefaultInputProject project, InputComponentStore inputComponentStore,
BranchConfiguration branchConfiguration) {
this.scmConfiguration = scmConfiguration;
- this.inputModuleHierarchy = inputModuleHierarchy;
+ this.project = project;
this.inputComponentStore = inputComponentStore;
this.branchConfiguration = branchConfiguration;
}
- @Override public void publish(ScannerReportWriter writer) {
+ @Override
+ public void publish(ScannerReportWriter writer) {
String targetScmBranch = branchConfiguration.targetScmBranch();
if (scmConfiguration.isDisabled() || !branchConfiguration.isShortOrPullRequest() || targetScmBranch == null) {
return;
}
private int writeChangedLines(ScmProvider provider, ScannerReportWriter writer, String targetScmBranch) {
- Path rootBaseDir = inputModuleHierarchy.root().getBaseDir();
+ Path rootBaseDir = project.getBaseDir();
Map<Path, DefaultInputFile> changedFiles = StreamSupport.stream(inputComponentStore.allChangedFilesToPublish().spliterator(), false)
.collect(Collectors.toMap(DefaultInputFile::path, f -> f));
LOG.warn("File '{}' was detected as changed but without having changed lines", e.getKey().toAbsolutePath());
}
count++;
- writeChangedLines(writer, e.getValue().batchId(), changedLines);
+ writeChangedLines(writer, e.getValue().scannerId(), changedLines);
}
return count;
}
import org.sonar.api.batch.fs.InputModule;
import org.sonar.api.batch.fs.internal.DefaultInputComponent;
import org.sonar.api.batch.fs.internal.DefaultInputFile;
+import org.sonar.api.batch.fs.internal.AbstractProjectOrModule;
import org.sonar.api.batch.fs.internal.DefaultInputModule;
import org.sonar.api.batch.fs.internal.InputComponentTree;
import org.sonar.api.batch.fs.internal.InputModuleHierarchy;
ScannerReport.Component.Builder builder = ScannerReport.Component.newBuilder();
// non-null fields
- builder.setRef(component.batchId());
+ builder.setRef(component.scannerId());
builder.setType(getType(component));
// Don't set key on directories and files to save space since it can be deduced from path
}
for (InputComponent child : children) {
- builder.addChildRef(((DefaultInputComponent) child).batchId());
+ builder.addChildRef(((DefaultInputComponent) child).scannerId());
}
writeLinks(component, builder);
writer.writeComponent(builder.build());
private boolean shouldSkipComponent(DefaultInputComponent component, Collection<InputComponent> children) {
if (component instanceof InputModule && children.isEmpty() && (branchConfiguration.isShortOrPullRequest())) {
// no children on a module in short branch analysis -> skip it (except root)
- return !moduleHierarchy.isRoot((InputModule) component);
+ return !moduleHierarchy.isRoot((DefaultInputModule) component);
} else if (component instanceof InputDir && children.isEmpty()) {
- try (CloseableIterator<Issue> componentIssuesIt = reader.readComponentIssues(component.batchId())) {
+ try (CloseableIterator<Issue> componentIssuesIt = reader.readComponentIssues(component.scannerId())) {
if (!componentIssuesIt.hasNext()) {
// no files to publish on a directory without issues -> skip it
return true;
return inputPath.relativePath();
}
} else if (component instanceof InputModule) {
- InputModule module = (InputModule) component;
+ DefaultInputModule module = (DefaultInputModule) component;
return moduleHierarchy.relativePath(module);
}
throw new IllegalStateException("Unknown component: " + component.getClass());
return PathUtils.sanitize(projectBaseDir.relativize(inputDir.path()).toString());
}
if (component instanceof InputModule) {
- DefaultInputModule module = (DefaultInputModule) component;
+ AbstractProjectOrModule module = (AbstractProjectOrModule) component;
return PathUtils.sanitize(projectBaseDir.relativize(module.getBaseDir()).toString());
}
throw new IllegalStateException("Unknown component: " + component.getClass());
private static void writeLinks(InputComponent c, ScannerReport.Component.Builder builder) {
if (c instanceof InputModule) {
- DefaultInputModule inputModule = (DefaultInputModule) c;
+ AbstractProjectOrModule inputModule = (AbstractProjectOrModule) c;
ProjectDefinition def = inputModule.definition();
ComponentLink.Builder linkBuilder = ComponentLink.newBuilder();
}
@CheckForNull
- private static String getName(DefaultInputModule module) {
+ private static String getName(AbstractProjectOrModule module) {
if (StringUtils.isNotEmpty(module.definition().getBranch())) {
return module.definition().getName() + " " + module.definition().getBranch();
} else {
}
@CheckForNull
- private static String getDescription(DefaultInputModule module) {
+ private static String getDescription(AbstractProjectOrModule module) {
return module.definition().getDescription();
}
return ComponentType.FILE;
} else if (r instanceof InputDir) {
return ComponentType.DIRECTORY;
- } else if ((r instanceof InputModule) && moduleHierarchy.isRoot((InputModule) r)) {
+ } else if ((r instanceof InputModule) && moduleHierarchy.isRoot((DefaultInputModule) r)) {
return ComponentType.PROJECT;
} else if (r instanceof InputModule) {
return ComponentType.MODULE;
applyLineMeasure(inputFile.key(), lineCount, CoreMetrics.COVERED_CONDITIONS_BY_LINE_KEY, coveragePerLine,
(value, builder) -> builder.setCoveredConditions(Integer.parseInt(value)));
- writer.writeComponentCoverage(inputFile.batchId(), coveragePerLine.values().stream().map(BuildCoverage.INSTANCE).collect(Collectors.toList()));
+ writer.writeComponentCoverage(inputFile.scannerId(), coveragePerLine.values().stream().map(BuildCoverage.INSTANCE).collect(Collectors.toList()));
}
}
Iterable<DefaultMeasure<?>> scannerMeasures = measureCache.byComponentKey(component.key());
if (scannerMeasures.iterator().hasNext()) {
- writer.writeComponentMeasures(component.batchId(), StreamSupport.stream(scannerMeasures.spliterator(), false)
+ writer.writeComponentMeasures(component.scannerId(), StreamSupport.stream(scannerMeasures.spliterator(), false)
.map(input -> {
if (input.value() == null) {
throw new IllegalArgumentException(
import java.util.Optional;
import java.util.regex.Pattern;
import javax.annotation.Nullable;
-import org.sonar.api.batch.fs.internal.DefaultInputModule;
+import org.sonar.api.batch.fs.internal.AbstractProjectOrModule;
import org.sonar.api.batch.fs.internal.InputModuleHierarchy;
import org.sonar.api.batch.scm.ScmProvider;
import org.sonar.api.utils.log.Logger;
import org.sonar.scanner.protocol.output.ScannerReport;
import org.sonar.scanner.protocol.output.ScannerReport.Metadata.BranchType;
import org.sonar.scanner.protocol.output.ScannerReportWriter;
-import org.sonar.scanner.rule.QualityProfiles;
import org.sonar.scanner.rule.QProfile;
+import org.sonar.scanner.rule.QualityProfiles;
import org.sonar.scanner.scan.ScanProperties;
import org.sonar.scanner.scan.branch.BranchConfiguration;
import org.sonar.scanner.scm.ScmConfiguration;
@Override
public void publish(ScannerReportWriter writer) {
- DefaultInputModule rootProject = moduleHierarchy.root();
+ AbstractProjectOrModule rootProject = moduleHierarchy.root();
ScannerReport.Metadata.Builder builder = ScannerReport.Metadata.newBuilder()
.setAnalysisDate(projectAnalysisInfo.analysisDate().getTime())
// Here we want key without branch
.setProjectKey(rootProject.key())
.setCrossProjectDuplicationActivated(cpdSettings.isCrossProjectDuplicationEnabled())
- .setRootComponentRef(rootProject.batchId());
+ .setRootComponentRef(rootProject.scannerId());
properties.organizationKey().ifPresent(builder::setOrganizationKey);
@Override
public void publish(ScannerReportWriter writer) {
for (final DefaultInputFile inputFile : componentCache.allChangedFilesToPublish()) {
- File iofile = writer.getSourceFile(inputFile.batchId());
+ File iofile = writer.getSourceFile(inputFile.scannerId());
try (OutputStream output = new BufferedOutputStream(new FileOutputStream(iofile));
InputStream in = inputFile.inputStream();
final Set<String> testNamesWithCoverage = new HashSet<>();
- writer.writeTests(component.batchId(),
+ writer.writeTests(component.scannerId(),
StreamSupport.stream(testPlan.testCases().spliterator(), false)
.map(testCase -> toProtobufTest(testBuilder, testNamesWithCoverage, testCase))
.collect(toList()));
- writer.writeCoverageDetails(component.batchId(), testNamesWithCoverage.stream()
+ writer.writeCoverageDetails(component.scannerId(), testNamesWithCoverage.stream()
.map(testName -> toProtobufCoverageDetails(builder, coveredBuilder, testPlan, testName))
.collect(toList()));
}
for (CoverageBlock block : testCase.coverageBlocks()) {
coveredBuilder.clear();
DefaultInputComponent c = (DefaultInputComponent) componentStore.getByKey(((DefaultTestable) block.testable()).inputFile().key());
- coveredBuilder.setFileRef(c.batchId());
+ coveredBuilder.setFileRef(c.scannerId());
for (int line : block.lines()) {
coveredBuilder.addCoveredLine(line);
}
package org.sonar.scanner.repository;
import org.picocontainer.injectors.ProviderAdapter;
-import org.sonar.api.batch.bootstrap.ProjectKey;
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.ScannerProperties;
import org.sonar.scanner.scan.branch.BranchConfiguration;
public class ProjectRepositoriesProvider extends ProviderAdapter {
private static final String LOG_MSG = "Load project repositories";
private ProjectRepositories project = null;
- public ProjectRepositories provide(ProjectRepositoriesLoader loader, ProjectKey projectKey, GlobalAnalysisMode mode, BranchConfiguration branchConfig) {
+ public ProjectRepositories provide(ProjectRepositoriesLoader loader, ScannerProperties scannerProperties, GlobalAnalysisMode mode, BranchConfiguration branchConfig) {
if (project == null) {
boolean isIssuesMode = mode.isIssues();
Profiler profiler = Profiler.create(LOG).startInfo(LOG_MSG);
- project = loader.load(projectKey.get(), isIssuesMode, branchConfig.longLivingSonarReferenceBranch());
+ project = loader.load(scannerProperties.getKeyWithBranch(), isIssuesMode, branchConfig.longLivingSonarReferenceBranch());
checkProject(isIssuesMode);
profiler.stopInfo();
}
import java.util.List;
import javax.annotation.CheckForNull;
import org.picocontainer.injectors.ProviderAdapter;
-import org.sonar.api.batch.bootstrap.ProjectKey;
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.analysis.AnalysisProperties;
+import org.sonar.scanner.bootstrap.ScannerProperties;
import org.sonar.scanner.rule.QualityProfiles;
import org.sonarqube.ws.Qualityprofiles.SearchWsResponse.QualityProfile;
private static final String LOG_MSG = "Load quality profiles";
private QualityProfiles profiles = null;
- public QualityProfiles provide(ProjectKey projectKey, QualityProfileLoader loader, ProjectRepositories projectRepositories, AnalysisProperties props) {
+ public QualityProfiles provide(QualityProfileLoader loader, ProjectRepositories projectRepositories, ScannerProperties props) {
if (this.profiles == null) {
List<QualityProfile> profileList;
Profiler profiler = Profiler.create(LOG).startInfo(LOG_MSG);
if (!projectRepositories.exists()) {
profileList = loader.loadDefault(getSonarProfile(props));
} else {
- profileList = loader.load(projectKey.get(), getSonarProfile(props));
+ profileList = loader.load(props.getKeyWithBranch(), getSonarProfile(props));
}
profiler.stopInfo();
profiles = new QualityProfiles(profileList);
}
@CheckForNull
- private static String getSonarProfile(AnalysisProperties props) {
+ private static String getSonarProfile(ScannerProperties props) {
String profile = props.property(QualityProfiles.SONAR_PROFILE_PROP);
if (profile != null) {
LOG.warn("Ability to set quality profile from command line using '" + QualityProfiles.SONAR_PROFILE_PROP
import java.util.Map;
import javax.annotation.CheckForNull;
import javax.annotation.concurrent.Immutable;
-import org.sonar.api.batch.fs.InputModule;
+import org.sonar.api.batch.fs.internal.AbstractProjectOrModule;
import org.sonar.api.batch.fs.internal.DefaultInputModule;
import org.sonar.api.batch.fs.internal.InputModuleHierarchy;
import org.sonar.api.scan.filesystem.PathResolver;
private final Map<DefaultInputModule, DefaultInputModule> parents;
private final ImmutableMultimap<DefaultInputModule, DefaultInputModule> children;
- public DefaultInputModuleHierarchy(DefaultInputModule parent, DefaultInputModule child) {
- this(Collections.singletonMap(child, parent));
- }
-
public DefaultInputModuleHierarchy(DefaultInputModule root) {
this.children = new ImmutableMultimap.Builder<DefaultInputModule, DefaultInputModule>().build();
this.parents = Collections.emptyMap();
/**
* Map of child->parent. Neither the Keys or values can be null.
*/
- public DefaultInputModuleHierarchy(Map<DefaultInputModule, DefaultInputModule> parents) {
+ public DefaultInputModuleHierarchy(DefaultInputModule root, Map<DefaultInputModule, DefaultInputModule> parents) {
ImmutableMultimap.Builder<DefaultInputModule, DefaultInputModule> childrenBuilder = new ImmutableMultimap.Builder<>();
for (Map.Entry<DefaultInputModule, DefaultInputModule> e : parents.entrySet()) {
this.children = childrenBuilder.build();
this.parents = Collections.unmodifiableMap(new HashMap<>(parents));
- this.root = findRoot(parents);
- }
-
- private static DefaultInputModule findRoot(Map<DefaultInputModule, DefaultInputModule> parents) {
- DefaultInputModule r = null;
- for (DefaultInputModule parent : parents.values()) {
- if (!parents.containsKey(parent)) {
- if (r != null && r != parent) {
- throw new IllegalStateException(String.format("Found two modules without parent: '%s' and '%s'", r.key(), parent.key()));
- }
- r = parent;
- }
- }
- if (r == null) {
- throw new IllegalStateException("Found no root module");
- }
- return r;
+ this.root = root;
}
@Override
}
@Override
- public Collection<DefaultInputModule> children(InputModule component) {
- return children.get((DefaultInputModule) component);
+ public Collection<DefaultInputModule> children(DefaultInputModule component) {
+ return children.get(component);
}
@Override
- public DefaultInputModule parent(InputModule component) {
+ public DefaultInputModule parent(DefaultInputModule component) {
return parents.get(component);
}
@Override
- public boolean isRoot(InputModule module) {
+ public boolean isRoot(DefaultInputModule module) {
return root.equals(module);
}
@Override
@CheckForNull
- public String relativePath(InputModule module) {
- DefaultInputModule parent = parent(module);
+ public String relativePath(DefaultInputModule module) {
+ AbstractProjectOrModule parent = parent(module);
if (parent == null) {
return null;
}
import java.util.HashMap;
import java.util.Map;
-
import org.picocontainer.injectors.ProviderAdapter;
import org.sonar.api.batch.bootstrap.ProjectDefinition;
-import org.sonar.api.batch.bootstrap.ProjectReactor;
import org.sonar.api.batch.fs.internal.DefaultInputModule;
-import org.sonar.scanner.scan.filesystem.BatchIdGenerator;
+import org.sonar.api.batch.fs.internal.DefaultInputProject;
+import org.sonar.scanner.scan.filesystem.ScannerComponentIdGenerator;
public class InputModuleHierarchyProvider extends ProviderAdapter {
private DefaultInputModuleHierarchy hierarchy = null;
- public DefaultInputModuleHierarchy provide(ProjectBuildersExecutor projectBuildersExecutor, ProjectReactorValidator validator,
- ProjectReactor projectReactor, BatchIdGenerator batchIdGenerator) {
+ public DefaultInputModuleHierarchy provide(ScannerComponentIdGenerator scannerComponentIdGenerator, DefaultInputProject project) {
if (hierarchy == null) {
- // 1 Apply project builders
- projectBuildersExecutor.execute(projectReactor);
-
- // 2 Validate final reactor
- validator.validate(projectReactor);
-
- // 3 Create modules and the hierarchy
- DefaultInputModule root = new DefaultInputModule(projectReactor.getRoot(), batchIdGenerator.getAsInt());
- Map<DefaultInputModule, DefaultInputModule> parents = createChildren(root, batchIdGenerator, new HashMap<>());
+ DefaultInputModule root = new DefaultInputModule(project.definition(), project.scannerId());
+ Map<DefaultInputModule, DefaultInputModule> parents = createChildren(root, scannerComponentIdGenerator, new HashMap<>());
if (parents.isEmpty()) {
hierarchy = new DefaultInputModuleHierarchy(root);
} else {
- hierarchy = new DefaultInputModuleHierarchy(parents);
+ hierarchy = new DefaultInputModuleHierarchy(root, parents);
}
}
return hierarchy;
}
- private static Map<DefaultInputModule, DefaultInputModule> createChildren(DefaultInputModule parent, BatchIdGenerator batchIdGenerator,
- Map<DefaultInputModule, DefaultInputModule> parents) {
+ private static Map<DefaultInputModule, DefaultInputModule> createChildren(DefaultInputModule parent, ScannerComponentIdGenerator scannerComponentIdGenerator,
+ Map<DefaultInputModule, DefaultInputModule> parents) {
for (ProjectDefinition def : parent.definition().getSubProjects()) {
- DefaultInputModule child = new DefaultInputModule(def, batchIdGenerator.getAsInt());
+ DefaultInputModule child = new DefaultInputModule(def, scannerComponentIdGenerator.getAsInt());
parents.put(child, parent);
- createChildren(child, batchIdGenerator, parents);
+ createChildren(child, scannerComponentIdGenerator, parents);
}
return parents;
}
--- /dev/null
+/*
+ * SonarQube
+ * Copyright (C) 2009-2018 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;
+
+import org.picocontainer.injectors.ProviderAdapter;
+import org.sonar.api.batch.bootstrap.ProjectReactor;
+import org.sonar.api.batch.fs.internal.DefaultInputProject;
+import org.sonar.scanner.scan.filesystem.ScannerComponentIdGenerator;
+
+public class InputProjectProvider extends ProviderAdapter {
+
+ private DefaultInputProject project = null;
+
+ public DefaultInputProject provide(ProjectBuildersExecutor projectBuildersExecutor, ProjectReactorValidator validator,
+ ProjectReactor projectReactor, ScannerComponentIdGenerator scannerComponentIdGenerator) {
+ if (project == null) {
+ // 1 Apply project builders
+ projectBuildersExecutor.execute(projectReactor);
+
+ // 2 Validate final reactor
+ validator.validate(projectReactor);
+
+ // 3 Create modules and the hierarchy
+ project = new DefaultInputProject(projectReactor.getRoot(), scannerComponentIdGenerator.getAsInt());
+ }
+ return project;
+ }
+}
if (moduleConfiguration == null) {
Map<String, String> settings = new LinkedHashMap<>();
- settings.putAll(globalConfig.getProperties());
settings.putAll(addServerSidePropertiesIfModuleExists(projectRepos, module.definition()));
addScannerSideProperties(settings, module.definition());
contextReportPublisher.dumpModuleSettings(module);
package org.sonar.scanner.scan;
import org.picocontainer.Startable;
+import org.sonar.api.batch.fs.internal.AbstractProjectOrModule;
import org.sonar.api.batch.fs.internal.DefaultInputModule;
import org.sonar.api.batch.fs.internal.InputModuleHierarchy;
import org.sonar.scanner.scan.filesystem.InputComponentStore;
/**
- * Indexes all modules into {@link DefaultComponentTree}, {@link DefaultInputModuleHierarchy) and {@link InputComponentStore}, using the
+ * Indexes all modules into {@link DefaultComponentTree}, {@link DefaultInputModuleHierarchy) and {@link InputComponentStore}, using the
* project definitions provided by the {@link ImmutableProjectReactor}.
*/
public class ModuleIndexer implements Startable {
@Override
public void start() {
DefaultInputModule root = moduleHierarchy.root();
+ componentStore.put(root);
indexChildren(root);
}
import org.sonar.api.batch.bootstrap.ProjectDefinition;
import org.sonar.api.config.Settings;
import org.sonar.api.utils.MessageException;
-import org.sonar.scanner.bootstrap.MutableGlobalSettings;
+import org.sonar.scanner.bootstrap.GlobalConfiguration;
import org.sonar.scanner.repository.ProjectRepositories;
import static java.util.Objects.requireNonNull;
private final AnalysisMode analysisMode;
private final Map<String, String> properties = new HashMap<>();
- public MutableModuleSettings(MutableGlobalSettings batchSettings, ProjectDefinition moduleDefinition, ProjectRepositories projectSettingsRepo,
- AnalysisMode analysisMode) {
- super(batchSettings.getDefinitions(), batchSettings.getEncryption());
+ public MutableModuleSettings(GlobalConfiguration globalConfig, ProjectDefinition moduleDefinition, ProjectRepositories projectSettingsRepo,
+ AnalysisMode analysisMode) {
+ super(globalConfig.getDefinitions(), globalConfig.getEncryption());
this.projectRepos = projectSettingsRepo;
this.analysisMode = analysisMode;
- init(moduleDefinition, batchSettings);
+ init(moduleDefinition, globalConfig);
}
- private MutableModuleSettings init(ProjectDefinition moduleDefinition, MutableGlobalSettings batchSettings) {
- addProjectProperties(moduleDefinition, batchSettings);
+ private MutableModuleSettings init(ProjectDefinition moduleDefinition, GlobalConfiguration globalConfig) {
+ addProjectProperties(moduleDefinition, globalConfig);
addBuildProperties(moduleDefinition);
return this;
}
- private void addProjectProperties(ProjectDefinition def, MutableGlobalSettings batchSettings) {
- addProperties(batchSettings.getProperties());
+ private void addProjectProperties(ProjectDefinition def, GlobalConfiguration globalConfig) {
+ addProperties(globalConfig.getProperties());
do {
if (projectRepos.moduleExists(def.getKeyWithBranch())) {
addProperties(projectRepos.settings(def.getKeyWithBranch()));
import org.sonar.api.config.Settings;
import org.sonar.api.utils.MessageException;
import org.sonar.scanner.bootstrap.GlobalAnalysisMode;
-import org.sonar.scanner.bootstrap.MutableGlobalSettings;
+import org.sonar.scanner.bootstrap.GlobalConfiguration;
import org.sonar.scanner.repository.ProjectRepositories;
import static java.util.Objects.requireNonNull;
private final GlobalAnalysisMode mode;
private final Map<String, String> properties = new HashMap<>();
- public MutableProjectSettings(ProjectReactor reactor, MutableGlobalSettings mutableGlobalSettings, ProjectRepositories projectRepositories, GlobalAnalysisMode mode) {
- super(mutableGlobalSettings.getDefinitions(), mutableGlobalSettings.getEncryption());
+ public MutableProjectSettings(ProjectReactor reactor, GlobalConfiguration globalConfig, ProjectRepositories projectRepositories, GlobalAnalysisMode mode) {
+ super(globalConfig.getDefinitions(), globalConfig.getEncryption());
this.mode = mode;
- addProperties(mutableGlobalSettings.getProperties());
+ addProperties(globalConfig.getProperties());
addProperties(projectRepositories.settings(reactor.getRoot().getKeyWithBranch()));
addProperties(reactor.getRoot().properties());
}
import java.util.LinkedHashMap;
import java.util.Map;
import org.picocontainer.injectors.ProviderAdapter;
-import org.sonar.api.batch.bootstrap.ProjectReactor;
+import org.sonar.api.batch.fs.internal.AbstractProjectOrModule;
import org.sonar.scanner.bootstrap.GlobalAnalysisMode;
import org.sonar.scanner.bootstrap.GlobalConfiguration;
+import org.sonar.scanner.bootstrap.GlobalServerSettings;
import org.sonar.scanner.repository.ProjectRepositories;
public class ProjectConfigurationProvider extends ProviderAdapter {
private ProjectConfiguration projectConfig;
- public ProjectConfiguration provide(ProjectReactor reactor, GlobalConfiguration globalSettings, ProjectRepositories projectRepositories, GlobalAnalysisMode mode) {
+ public ProjectConfiguration provide(GlobalServerSettings globalServerSettings, AbstractProjectOrModule project,
+ GlobalConfiguration globalConfig, ProjectRepositories projectRepositories, GlobalAnalysisMode mode) {
if (projectConfig == null) {
Map<String, String> settings = new LinkedHashMap<>();
- settings.putAll(globalSettings.getProperties());
- settings.putAll(projectRepositories.settings(reactor.getRoot().getKeyWithBranch()));
- settings.putAll(reactor.getRoot().properties());
+ settings.putAll(globalServerSettings.properties());
+ settings.putAll(projectRepositories.settings(project.getKeyWithBranch()));
+ settings.putAll(project.properties());
- projectConfig = new ProjectConfiguration(globalSettings.getDefinitions(), globalSettings.getEncryption(), mode, settings);
+ projectConfig = new ProjectConfiguration(globalConfig.getDefinitions(), globalConfig.getEncryption(), mode, settings);
}
return projectConfig;
}
import java.nio.file.Files;
import java.nio.file.Path;
import org.picocontainer.Startable;
-import org.sonar.api.batch.fs.internal.InputModuleHierarchy;
+import org.sonar.api.batch.fs.internal.AbstractProjectOrModule;
public class ProjectLock implements Startable {
private final DirectoryLock lock;
- public ProjectLock(InputModuleHierarchy moduleHierarchy) {
- Path directory = moduleHierarchy.root().getWorkDir();
+ public ProjectLock(AbstractProjectOrModule project) {
+ Path directory = project.getWorkDir();
try {
if (!directory.toFile().exists()) {
Files.createDirectories(directory);
package org.sonar.scanner.scan;
import com.google.common.annotations.VisibleForTesting;
-import com.google.common.collect.ImmutableMap;
import com.google.common.collect.Lists;
import java.io.File;
import java.nio.file.Path;
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.analysis.AnalysisProperties;
-import org.sonar.scanner.bootstrap.DroppedPropertyChecker;
+import org.sonar.scanner.bootstrap.ScannerProperties;
import org.sonar.scanner.util.ScannerUtils;
import static org.sonar.core.config.MultivalueProperty.parseAsCsv;
private static final String INVALID_VALUE_OF_X_FOR_Y = "Invalid value of {0} for {1}";
- /**
- * A map of dropped properties as key and specific message to display for that property
- * (what will happen, what should the user do, ...) as a value
- */
- private static final Map<String, String> DROPPED_PROPERTIES = ImmutableMap.of(
- "sonar.qualitygate", "It will be ignored.");
-
private static final Logger LOG = Loggers.get(ProjectReactorBuilder.class);
/**
private static final List<String> NON_HERITED_PROPERTIES_FOR_CHILD = Lists.newArrayList(PROPERTY_PROJECT_BASEDIR, CoreProperties.WORKING_DIRECTORY, PROPERTY_MODULES,
CoreProperties.PROJECT_DESCRIPTION_PROPERTY);
- private final AnalysisProperties analysisProps;
+ private final ScannerProperties scannerProps;
private File rootProjectWorkDir;
- public ProjectReactorBuilder(AnalysisProperties props) {
- this.analysisProps = props;
+ public ProjectReactorBuilder(ScannerProperties props) {
+ this.scannerProps = props;
}
public ProjectReactor execute() {
Profiler profiler = Profiler.create(LOG).startInfo("Process project properties");
- new DroppedPropertyChecker(analysisProps.properties(), DROPPED_PROPERTIES).checkDroppedProperties();
Map<String, Map<String, String>> propertiesByModuleIdPath = new HashMap<>();
- extractPropertiesByModule(propertiesByModuleIdPath, "", "", analysisProps.properties());
- ProjectDefinition rootProject = defineRootProject(propertiesByModuleIdPath.get(""), null);
+ extractPropertiesByModule(propertiesByModuleIdPath, "", "", new HashMap<>(scannerProps.properties()));
+ ProjectDefinition rootProject = createModuleDefinition(propertiesByModuleIdPath.get(""), null);
rootProjectWorkDir = rootProject.getWorkDir();
defineChildren(rootProject, propertiesByModuleIdPath, "");
cleanAndCheckProjectDefinitions(rootProject);
- // Since task properties are now empty we should add root module properties
- analysisProps.properties().putAll(propertiesByModuleIdPath.get(""));
profiler.stopDebug();
return new ProjectReactor(rootProject);
}
private static void extractPropertiesByModule(Map<String, Map<String, String>> propertiesByModuleIdPath, String currentModuleId, String currentModuleIdPath,
- Map<String, String> parentProperties) {
+ Map<String, String> parentProperties) {
if (propertiesByModuleIdPath.containsKey(currentModuleIdPath)) {
throw MessageException.of(String.format("Two modules have the same id: '%s'. Each module must have a unique id.", currentModuleId));
}
}
}
- protected ProjectDefinition defineRootProject(Map<String, String> rootProperties, @Nullable ProjectDefinition parent) {
- if (rootProperties.containsKey(PROPERTY_MODULES)) {
- checkMandatoryProperties(rootProperties, MANDATORY_PROPERTIES_FOR_MULTIMODULE_PROJECT);
+ protected ProjectDefinition createModuleDefinition(Map<String, String> moduleProperties, @Nullable ProjectDefinition parent) {
+ if (moduleProperties.containsKey(PROPERTY_MODULES)) {
+ checkMandatoryProperties(moduleProperties, MANDATORY_PROPERTIES_FOR_MULTIMODULE_PROJECT);
} else {
- checkMandatoryProperties(rootProperties, MANDATORY_PROPERTIES_FOR_SIMPLE_PROJECT);
+ checkMandatoryProperties(moduleProperties, MANDATORY_PROPERTIES_FOR_SIMPLE_PROJECT);
}
- File baseDir = new File(rootProperties.get(PROPERTY_PROJECT_BASEDIR));
- final String projectKey = rootProperties.get(CoreProperties.PROJECT_KEY_PROPERTY);
+ File baseDir = new File(moduleProperties.get(PROPERTY_PROJECT_BASEDIR));
+ final String projectKey = moduleProperties.get(CoreProperties.PROJECT_KEY_PROPERTY);
File workDir;
if (parent == null) {
- validateDirectories(rootProperties, baseDir, projectKey);
- workDir = initRootProjectWorkDir(baseDir, rootProperties);
+ validateDirectories(moduleProperties, baseDir, projectKey);
+ workDir = initRootProjectWorkDir(baseDir, moduleProperties);
} else {
- workDir = initModuleWorkDir(baseDir, rootProperties);
+ workDir = initModuleWorkDir(baseDir, moduleProperties);
}
- return ProjectDefinition.create().setProperties(rootProperties)
+ return ProjectDefinition.create().setProperties(moduleProperties)
.setBaseDir(baseDir)
.setWorkDir(workDir)
- .setBuildDir(initModuleBuildDir(baseDir, rootProperties));
+ .setBuildDir(initModuleBuildDir(baseDir, moduleProperties));
}
@VisibleForTesting
mergeParentProperties(moduleProps, parentProject.properties());
- return defineRootProject(moduleProps, parentProject);
+ return createModuleDefinition(moduleProps, parentProject);
}
@VisibleForTesting
/**
* Transforms a comma-separated list String property in to a array of trimmed strings.
- *
+ * <p>
* This works even if they are separated by whitespace characters (space char, EOL, ...)
- *
*/
static String[] getListFromProperty(Map<String, String> properties, String key) {
String propValue = properties.get(key);
import org.sonar.core.metric.ScannerMetrics;
import org.sonar.core.platform.ComponentContainer;
import org.sonar.scanner.ProjectAnalysisInfo;
-import org.sonar.scanner.analysis.AnalysisProperties;
import org.sonar.scanner.analysis.AnalysisTempFolderProvider;
import org.sonar.scanner.analysis.DefaultAnalysisMode;
import org.sonar.scanner.bootstrap.ExtensionInstaller;
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.ScanTaskObservers;
+import org.sonar.scanner.mediumtest.AnalysisObservers;
import org.sonar.scanner.notifications.DefaultAnalysisWarnings;
import org.sonar.scanner.phases.ProjectCoverageExclusions;
import org.sonar.scanner.report.ActiveRulesPublisher;
import org.sonar.scanner.scan.branch.BranchType;
import org.sonar.scanner.scan.branch.ProjectBranchesProvider;
import org.sonar.scanner.scan.branch.ProjectPullRequestsProvider;
-import org.sonar.scanner.scan.filesystem.BatchIdGenerator;
-import org.sonar.scanner.scan.filesystem.InputComponentStoreProvider;
+import org.sonar.scanner.scan.filesystem.InputComponentStore;
+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;
private static final Logger LOG = Loggers.get(ProjectScanContainer.class);
- private final AnalysisProperties props;
-
- public ProjectScanContainer(ComponentContainer globalContainer, AnalysisProperties props) {
+ public ProjectScanContainer(ComponentContainer globalContainer) {
super(globalContainer);
- this.props = props;
}
@Override
private void addScannerComponents() {
add(
- props,
ProjectReactorBuilder.class,
ScanProperties.class,
WorkDirectoriesInitializer.class,
// file system
ModuleIndexer.class,
- new InputComponentStoreProvider(),
+ InputComponentStore.class,
PathResolver.class,
+ new InputProjectProvider(),
new InputModuleHierarchyProvider(),
DefaultComponentTree.class,
- BatchIdGenerator.class,
+ ScannerComponentIdGenerator.class,
new ScmChangedFilesProvider(),
StatusDetection.class,
SonarCpdBlockIndex.class,
JavaCpdBlockIndexerSensor.class,
- ScanTaskObservers.class);
+ AnalysisObservers.class);
addIfMissing(DefaultRulesLoader.class, RulesLoader.class);
addIfMissing(DefaultActiveRulesLoader.class, ActiveRulesLoader.class);
scanRecursively(tree, tree.root(), analysisMode);
if (analysisMode.isMediumTest()) {
- getComponentByType(ScanTaskObservers.class).notifyEndOfScanTask();
+ getComponentByType(AnalysisObservers.class).notifyEndOfScanTask();
}
}
import java.nio.file.Paths;
import java.util.Optional;
import org.sonar.api.batch.ScannerSide;
-import org.sonar.api.batch.fs.internal.InputModuleHierarchy;
+import org.sonar.api.batch.fs.internal.DefaultInputProject;
import org.sonar.api.config.Configuration;
import org.sonar.api.utils.MessageException;
public static final String FORCE_RELOAD_KEY = "sonar.scm.forceReloadAll";
private final Configuration configuration;
- private final InputModuleHierarchy moduleHierarchy;
+ private final DefaultInputProject project;
- public ScanProperties(Configuration configuration, InputModuleHierarchy moduleHierarchy) {
+ public ScanProperties(Configuration configuration, DefaultInputProject project) {
this.configuration = configuration;
- this.moduleHierarchy = moduleHierarchy;
+ this.project = project;
}
public boolean shouldKeepReport() {
if (!metadataPath.isAbsolute()) {
throw MessageException.of(String.format("Property '%s' must point to an absolute path: %s", METADATA_FILE_PATH_KEY, metadataFilePath.get()));
}
- return moduleHierarchy.root().getBaseDir().resolve(metadataPath);
+ return project.getBaseDir().resolve(metadataPath);
} else {
- return moduleHierarchy.root().getWorkDir().resolve(METADATA_DUMP_FILENAME);
+ return project.getWorkDir().resolve(METADATA_DUMP_FILENAME);
}
}
+++ /dev/null
-/*
- * 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.concurrent.atomic.AtomicInteger;
-import java.util.function.IntSupplier;
-
-import javax.annotation.concurrent.ThreadSafe;
-
-import org.sonar.api.batch.fs.InputComponent;
-
-/**
- * Generates unique IDs for any {@link InputComponent}.
- * The IDs must be unique among all types of components and for all modules in the project.
- * The ID should never be 0, as it is sometimes used to indicate invalid components.
- */
-@ThreadSafe
-public class BatchIdGenerator implements IntSupplier {
- private AtomicInteger nextBatchId = new AtomicInteger(1);
-
- @Override
- public int getAsInt() {
- return nextBatchId.getAndIncrement();
- }
-}
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.api.batch.fs.internal.AbstractProjectOrModule;
import org.sonar.scanner.analysis.DefaultAnalysisMode;
public class DefaultModuleFileSystem extends DefaultFileSystem {
- public DefaultModuleFileSystem(ModuleInputComponentStore moduleInputFileCache, DefaultInputModule module, ModuleFileSystemInitializer initializer, DefaultAnalysisMode mode,
- StatusDetection statusDetection) {
+ public DefaultModuleFileSystem(ModuleInputComponentStore moduleInputFileCache, AbstractProjectOrModule module, ModuleFileSystemInitializer initializer, DefaultAnalysisMode mode,
+ StatusDetection statusDetection) {
super(module.getBaseDir(), moduleInputFileCache);
setFields(module, initializer, mode, statusDetection);
}
@VisibleForTesting
- public DefaultModuleFileSystem(DefaultInputModule module, ModuleFileSystemInitializer initializer, DefaultAnalysisMode mode, StatusDetection statusDetection) {
+ public DefaultModuleFileSystem(AbstractProjectOrModule module, ModuleFileSystemInitializer initializer, DefaultAnalysisMode mode, StatusDetection statusDetection) {
super(module.getBaseDir());
setFields(module, initializer, mode, statusDetection);
}
- private void setFields(DefaultInputModule module, ModuleFileSystemInitializer initializer, DefaultAnalysisMode mode, StatusDetection statusDetection) {
+ private void setFields(AbstractProjectOrModule module, ModuleFileSystemInitializer initializer, DefaultAnalysisMode mode, StatusDetection statusDetection) {
setWorkDir(module.getWorkDir());
setEncoding(initializer.defaultEncoding());
import org.sonar.api.batch.fs.InputFile;
import org.sonar.api.batch.fs.InputFile.Type;
import org.sonar.api.batch.fs.InputFileFilter;
+import org.sonar.api.batch.fs.InputModule;
import org.sonar.api.batch.fs.internal.DefaultInputDir;
import org.sonar.api.batch.fs.internal.DefaultInputFile;
-import org.sonar.api.batch.fs.internal.DefaultInputModule;
+import org.sonar.api.batch.fs.internal.AbstractProjectOrModule;
import org.sonar.api.scan.filesystem.PathResolver;
import org.sonar.api.utils.MessageException;
import org.sonar.scanner.scan.DefaultComponentTree;
private final ExclusionFilters exclusionFilters;
private final InputFileBuilder inputFileBuilder;
private final DefaultComponentTree componentTree;
- private final DefaultInputModule module;
- private final BatchIdGenerator batchIdGenerator;
+ private final AbstractProjectOrModule module;
+ private final ScannerComponentIdGenerator scannerComponentIdGenerator;
private final InputComponentStore componentStore;
private final ModuleFileSystemInitializer moduleFileSystemInitializer;
private ExecutorService executorService;
private ProgressReport progressReport;
- public FileIndexer(BatchIdGenerator batchIdGenerator, InputComponentStore componentStore, DefaultInputModule module, ExclusionFilters exclusionFilters,
- DefaultComponentTree componentTree, InputFileBuilder inputFileBuilder, ModuleFileSystemInitializer initializer, DefaultModuleFileSystem defaultModuleFileSystem,
- LanguageDetection languageDetection,
- InputFileFilter[] filters) {
- this.batchIdGenerator = batchIdGenerator;
+ public FileIndexer(ScannerComponentIdGenerator scannerComponentIdGenerator, InputComponentStore componentStore, InputModule module, ExclusionFilters exclusionFilters,
+ DefaultComponentTree componentTree, InputFileBuilder inputFileBuilder, ModuleFileSystemInitializer initializer, DefaultModuleFileSystem defaultModuleFileSystem,
+ LanguageDetection languageDetection,
+ InputFileFilter[] filters) {
+ this.scannerComponentIdGenerator = scannerComponentIdGenerator;
this.componentStore = componentStore;
- this.module = module;
+ this.module = (AbstractProjectOrModule) module;
this.componentTree = componentTree;
this.inputFileBuilder = inputFileBuilder;
this.moduleFileSystemInitializer = initializer;
this.tasks = new ArrayList<>();
}
- public FileIndexer(BatchIdGenerator batchIdGenerator, InputComponentStore componentStore, DefaultInputModule module, ExclusionFilters exclusionFilters,
- DefaultComponentTree componentTree, InputFileBuilder inputFileBuilder, ModuleFileSystemInitializer initializer, DefaultModuleFileSystem defaultModuleFileSystem,
- LanguageDetection languageDetection) {
- this(batchIdGenerator, componentStore, module, exclusionFilters, componentTree, inputFileBuilder, initializer, defaultModuleFileSystem, languageDetection,
+ public FileIndexer(ScannerComponentIdGenerator scannerComponentIdGenerator, InputComponentStore componentStore, InputModule module, ExclusionFilters exclusionFilters,
+ DefaultComponentTree componentTree, InputFileBuilder inputFileBuilder, ModuleFileSystemInitializer initializer, DefaultModuleFileSystem defaultModuleFileSystem,
+ LanguageDetection languageDetection) {
+ this(scannerComponentIdGenerator, componentStore, module, exclusionFilters, componentTree, inputFileBuilder, initializer, defaultModuleFileSystem, languageDetection,
new InputFileFilter[0]);
}
private void indexFileAndParentDir(InputFile inputFile, String parentRelativePath) {
DefaultInputDir inputDir = (DefaultInputDir) componentStore.getDir(module.key(), parentRelativePath);
if (inputDir == null) {
- inputDir = new DefaultInputDir(module.key(), parentRelativePath, batchIdGenerator.getAsInt());
+ inputDir = new DefaultInputDir(module.key(), parentRelativePath, scannerComponentIdGenerator.getAsInt());
inputDir.setModuleBaseDir(module.getBaseDir());
componentTree.index(inputDir, module);
defaultModuleFileSystem.add(inputDir);
import java.util.TreeSet;
import java.util.stream.Stream;
import javax.annotation.CheckForNull;
-import org.sonar.api.batch.ScannerSide;
import org.sonar.api.batch.fs.InputComponent;
import org.sonar.api.batch.fs.InputDir;
import org.sonar.api.batch.fs.InputFile;
-import org.sonar.api.batch.fs.InputModule;
+import org.sonar.api.batch.fs.internal.AbstractProjectOrModule;
import org.sonar.api.batch.fs.internal.DefaultInputDir;
import org.sonar.api.batch.fs.internal.DefaultInputFile;
-import org.sonar.api.batch.fs.internal.DefaultInputModule;
import org.sonar.api.batch.fs.internal.FileExtensionPredicate;
import org.sonar.api.scan.filesystem.PathResolver;
+import org.sonar.api.scanner.fs.InputProject;
import org.sonar.scanner.scan.branch.BranchConfiguration;
/**
- * Store of all files and dirs. This cache is shared amongst all project modules. Inclusion and
+ * Store of all files and dirs. Inclusion and
* exclusion patterns are already applied.
*/
-@ScannerSide
public class InputComponentStore {
private final SortedSet<String> globalLanguagesCache = new TreeSet<>();
private final Map<String, InputDir> globalInputDirCache = new HashMap<>();
private final Table<String, String, InputDir> inputDirCache = TreeBasedTable.create();
// indexed by key with branch
- private final Map<String, InputModule> inputModuleCache = new HashMap<>();
+ private final Map<String, AbstractProjectOrModule> inputModuleCache = new HashMap<>();
private final Map<String, InputComponent> inputComponents = new HashMap<>();
private final SetMultimap<String, InputFile> filesByNameCache = LinkedHashMultimap.create();
private final SetMultimap<String, InputFile> filesByExtensionCache = LinkedHashMultimap.create();
- private final InputModule root;
+ private final InputProject project;
private final BranchConfiguration branchConfiguration;
- public InputComponentStore(DefaultInputModule root, BranchConfiguration branchConfiguration) {
- this.root = root;
+ public InputComponentStore(InputProject project, BranchConfiguration branchConfiguration) {
+ this.project = project;
this.branchConfiguration = branchConfiguration;
- this.put(root);
}
public Collection<InputComponent> all() {
return inputComponents.get(key);
}
- public InputModule root() {
- return root;
- }
-
public Iterable<InputFile> filesByModule(String moduleKey) {
return inputFileCache.row(moduleKey).values();
}
}
private Path getProjectBaseDir() {
- return ((DefaultInputModule) root).getBaseDir();
+ return ((AbstractProjectOrModule) project).getBaseDir();
}
@CheckForNull
}
@CheckForNull
- public InputModule getModule(String moduleKeyWithBranch) {
+ public AbstractProjectOrModule getModule(String moduleKeyWithBranch) {
return inputModuleCache.get(moduleKeyWithBranch);
}
- public void put(DefaultInputModule inputModule) {
+ public void put(AbstractProjectOrModule inputModule) {
String key = inputModule.key();
String keyWithBranch = inputModule.getKeyWithBranch();
Preconditions.checkNotNull(inputModule);
+++ /dev/null
-/*
- * 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 org.picocontainer.injectors.ProviderAdapter;
-import org.sonar.api.batch.fs.internal.InputModuleHierarchy;
-import org.sonar.scanner.scan.branch.BranchConfiguration;
-
-public class InputComponentStoreProvider extends ProviderAdapter {
- private InputComponentStore store;
-
- public InputComponentStore provide(InputModuleHierarchy hierarchy, BranchConfiguration branchConfiguration) {
- if (store == null) {
- store = new InputComponentStore(hierarchy.root(), branchConfiguration);
- }
- return store;
- }
-}
import java.nio.file.Path;
import javax.annotation.Nullable;
-
import org.sonar.api.batch.fs.InputFile;
+import org.sonar.api.batch.fs.InputModule;
import org.sonar.api.batch.fs.internal.DefaultIndexedFile;
import org.sonar.api.batch.fs.internal.DefaultInputFile;
-import org.sonar.api.batch.fs.internal.DefaultInputModule;
+import org.sonar.api.batch.fs.internal.AbstractProjectOrModule;
import org.sonar.api.batch.fs.internal.InputModuleHierarchy;
import org.sonar.api.batch.fs.internal.SensorStrategy;
import org.sonar.scanner.scan.ScanProperties;
public class InputFileBuilder {
private final String moduleKey;
private final Path moduleBaseDir;
- private final BatchIdGenerator idGenerator;
+ private final ScannerComponentIdGenerator idGenerator;
private final MetadataGenerator metadataGenerator;
private final boolean preloadMetadata;
private final ModuleFileSystemInitializer moduleFileSystemInitializer;
private final Path projectBaseDir;
private final SensorStrategy sensorStrategy;
- public InputFileBuilder(DefaultInputModule module, MetadataGenerator metadataGenerator,
- BatchIdGenerator idGenerator, ScanProperties properties, ModuleFileSystemInitializer moduleFileSystemInitializer, InputModuleHierarchy hierarchy,
- SensorStrategy sensorStrategy) {
+ public InputFileBuilder(InputModule module, MetadataGenerator metadataGenerator,
+ ScannerComponentIdGenerator idGenerator, ScanProperties properties, ModuleFileSystemInitializer moduleFileSystemInitializer, InputModuleHierarchy hierarchy,
+ SensorStrategy sensorStrategy) {
this.sensorStrategy = sensorStrategy;
this.projectBaseDir = hierarchy.root().getBaseDir();
this.moduleFileSystemInitializer = moduleFileSystemInitializer;
this.moduleKey = module.key();
- this.moduleBaseDir = module.getBaseDir();
+ this.moduleBaseDir = ((AbstractProjectOrModule) module).getBaseDir();
this.metadataGenerator = metadataGenerator;
this.idGenerator = idGenerator;
this.preloadMetadata = properties.preloadFileMetadata();
import org.sonar.api.CoreProperties;
import org.sonar.api.batch.ScannerSide;
import org.sonar.api.batch.bootstrap.ProjectDefinition;
-import org.sonar.api.batch.fs.internal.DefaultInputModule;
+import org.sonar.api.batch.fs.InputModule;
+import org.sonar.api.batch.fs.internal.AbstractProjectOrModule;
import org.sonar.api.scan.filesystem.PathResolver;
import org.sonar.api.utils.log.Logger;
import org.sonar.api.utils.log.Loggers;
private final List<Path> testDirsOrFiles;
private final Charset encoding;
- public ModuleFileSystemInitializer(DefaultInputModule inputModule) {
- logDir("Base dir: ", inputModule.getBaseDir());
- logDir("Working dir: ", inputModule.getWorkDir());
- sourceDirsOrFiles = initSources(inputModule, ProjectDefinition.SOURCES_PROPERTY, "Source paths: ");
- testDirsOrFiles = initSources(inputModule, ProjectDefinition.TESTS_PROPERTY, "Test paths: ");
- encoding = initEncoding(inputModule);
+ public ModuleFileSystemInitializer(InputModule inputModule) {
+ AbstractProjectOrModule inputModuleCasted = (AbstractProjectOrModule) inputModule;
+ logDir("Base dir: ", inputModuleCasted.getBaseDir());
+ logDir("Working dir: ", inputModuleCasted.getWorkDir());
+ sourceDirsOrFiles = initSources(inputModuleCasted, ProjectDefinition.SOURCES_PROPERTY, "Source paths: ");
+ testDirsOrFiles = initSources(inputModuleCasted, ProjectDefinition.TESTS_PROPERTY, "Test paths: ");
+ encoding = initEncoding(inputModuleCasted);
}
- private static List<Path> initSources(DefaultInputModule module, String propertyKey, String logLabel) {
+ private static List<Path> initSources(AbstractProjectOrModule module, String propertyKey, String logLabel) {
List<Path> result = new ArrayList<>();
PathResolver pathResolver = new PathResolver();
String srcPropValue = module.properties().get(propertyKey);
return result;
}
- private static Charset initEncoding(DefaultInputModule module) {
+ private static Charset initEncoding(AbstractProjectOrModule module) {
String encodingStr = module.properties().get(CoreProperties.ENCODING_PROPERTY);
Charset result;
if (StringUtils.isNotEmpty(encodingStr)) {
--- /dev/null
+/*
+ * 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.concurrent.atomic.AtomicInteger;
+import java.util.function.IntSupplier;
+
+import javax.annotation.concurrent.ThreadSafe;
+
+import org.sonar.api.batch.fs.InputComponent;
+
+/**
+ * Generates unique IDs for any {@link InputComponent}.
+ * The IDs must be unique among all types of components (project, files) in the project.
+ * The ID should never be 0, as it is sometimes used to indicate invalid components.
+ */
+@ThreadSafe
+public class ScannerComponentIdGenerator implements IntSupplier {
+ private AtomicInteger nextId = new AtomicInteger(1);
+
+ @Override
+ public int getAsInt() {
+ return nextId.getAndIncrement();
+ }
+}
import org.sonar.api.batch.fs.InputDir;
import org.sonar.api.batch.fs.InputPath;
import org.sonar.api.batch.fs.internal.DefaultInputFile;
+import org.sonar.api.batch.fs.internal.AbstractProjectOrModule;
import org.sonar.api.batch.fs.internal.DefaultInputModule;
import org.sonar.api.batch.fs.internal.InputComponentTree;
import org.sonar.api.batch.fs.internal.InputModuleHierarchy;
private final InputComponentTree inputComponentTree;
public JSONReport(InputModuleHierarchy moduleHierarchy, Configuration settings, FileSystem fileSystem, Server server, Rules rules, IssueCache issueCache,
- DefaultInputModule rootModule, InputComponentStore componentStore, InputComponentTree inputComponentTree) {
+ DefaultInputModule rootModule, InputComponentStore componentStore, InputComponentTree inputComponentTree) {
this.moduleHierarchy = moduleHierarchy;
this.settings = settings;
this.fileSystem = fileSystem;
json.endArray();
}
- private DefaultInputModule getModule(InputComponent component) {
+ private AbstractProjectOrModule getModule(InputComponent component) {
if (component.isFile()) {
- return (DefaultInputModule) inputComponentTree.getParent(inputComponentTree.getParent(component));
+ return (AbstractProjectOrModule) inputComponentTree.getParent(inputComponentTree.getParent(component));
}
if (component instanceof InputDir) {
- return (DefaultInputModule) inputComponentTree.getParent(component);
+ return (AbstractProjectOrModule) inputComponentTree.getParent(component);
}
- return (DefaultInputModule) component;
+ return (AbstractProjectOrModule) component;
}
private void writeJsonComponents(JsonWriter json) {
json.endArray();
}
- private void writeJsonModuleComponents(JsonWriter json, DefaultInputModule module) {
+ private void writeJsonModuleComponents(JsonWriter json, DefaultInputModule moduleOrProject) {
json
.beginObject()
- .prop("key", module.definition().getKeyWithBranch())
- .prop("path", moduleHierarchy.relativePath(module))
+ .prop("key", moduleOrProject.definition().getKeyWithBranch())
+ .prop("path", moduleHierarchy.relativePath(moduleOrProject))
.endObject();
- for (DefaultInputModule subModule : moduleHierarchy.children(module)) {
+ for (DefaultInputModule subModule : moduleHierarchy.children(moduleOrProject)) {
writeJsonModuleComponents(json, subModule);
}
}
Builder scmBuilder = ScannerReport.Changesets.newBuilder();
DefaultInputFile inputFile = (DefaultInputFile) file;
- scmBuilder.setComponentRef(inputFile.batchId());
+ scmBuilder.setComponentRef(inputFile.scannerId());
Map<String, Integer> changesetsIdByRevision = new HashMap<>();
int lineId = 1;
import javax.annotation.CheckForNull;
import org.picocontainer.annotations.Nullable;
import org.picocontainer.injectors.ProviderAdapter;
-import org.sonar.api.batch.fs.internal.InputModuleHierarchy;
+import org.sonar.api.batch.fs.internal.DefaultInputProject;
import org.sonar.api.batch.scm.ScmProvider;
import org.sonar.api.utils.log.Logger;
import org.sonar.api.utils.log.Loggers;
/*
* ScmConfiguration is not available in issues mode
*/
- public ScmChangedFiles provide(@Nullable ScmConfiguration scmConfiguration, BranchConfiguration branchConfiguration, InputModuleHierarchy inputModuleHierarchy) {
+ public ScmChangedFiles provide(@Nullable ScmConfiguration scmConfiguration, BranchConfiguration branchConfiguration, DefaultInputProject project) {
if (scmBranchChangedFiles == null) {
if (scmConfiguration == null) {
scmBranchChangedFiles = new ScmChangedFiles(null);
} else {
- Path rootBaseDir = inputModuleHierarchy.root().getBaseDir();
+ Path rootBaseDir = project.getBaseDir();
Collection<Path> changedFiles = loadChangedFilesIfNeeded(scmConfiguration, branchConfiguration, rootBaseDir);
validatePaths(changedFiles);
scmBranchChangedFiles = new ScmChangedFiles(changedFiles);
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.DefaultInputModule;
+import org.sonar.api.batch.fs.internal.AbstractProjectOrModule;
import org.sonar.api.batch.scm.ScmProvider;
import org.sonar.api.utils.log.Logger;
import org.sonar.api.utils.log.Loggers;
private static final Logger LOG = Loggers.get(ScmPublisher.class);
- private final DefaultInputModule inputModule;
+ private final AbstractProjectOrModule inputModule;
private final ScmConfiguration configuration;
private final ProjectRepositories projectRepositories;
private final ModuleInputComponentStore componentStore;
private final ScannerReportWriter writer;
private final BranchConfiguration branchConfiguration;
- public ScmPublisher(DefaultInputModule inputModule, ScmConfiguration configuration, ProjectRepositories projectRepositories,
- ModuleInputComponentStore componentStore, DefaultModuleFileSystem fs, ReportPublisher reportPublisher, BranchConfiguration branchConfiguration) {
+ public ScmPublisher(AbstractProjectOrModule inputModule, ScmConfiguration configuration, ProjectRepositories projectRepositories,
+ ModuleInputComponentStore componentStore, DefaultModuleFileSystem fs, ReportPublisher reportPublisher, BranchConfiguration branchConfiguration) {
this.inputModule = inputModule;
this.configuration = configuration;
this.projectRepositories = projectRepositories;
private static void askToCopyDataFromPreviousAnalysis(DefaultInputFile f, ScannerReportWriter writer) {
Builder scmBuilder = ScannerReport.Changesets.newBuilder();
- scmBuilder.setComponentRef(f.batchId());
+ scmBuilder.setComponentRef(f.scannerId());
scmBuilder.setCopyFromPrevious(true);
writer.writeComponentChangesets(scmBuilder.build());
}
import org.sonar.api.batch.fs.InputFile;
import org.sonar.api.batch.fs.InputModule;
import org.sonar.api.batch.fs.internal.DefaultInputFile;
-import org.sonar.api.batch.fs.internal.InputModuleHierarchy;
+import org.sonar.api.batch.fs.internal.DefaultInputProject;
import org.sonar.api.batch.rule.ActiveRules;
import org.sonar.api.batch.sensor.SensorContext;
import org.sonar.api.batch.sensor.code.NewSignificantCode;
import org.sonar.api.batch.sensor.symbol.internal.DefaultSymbolTable;
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;
private final ActiveRules activeRules;
private final SensorStorage sensorStorage;
private final AnalysisMode analysisMode;
+ private final DefaultInputProject project;
private final InputModule module;
private final SonarRuntime sonarRuntime;
private final Configuration config;
- private final InputModuleHierarchy hierarchy;
- public DefaultSensorContext(InputModule module, Configuration config, Settings mutableSettings, FileSystem fs, ActiveRules activeRules,
- AnalysisMode analysisMode, SensorStorage sensorStorage, SonarRuntime sonarRuntime, InputModuleHierarchy hierarchy) {
+ public DefaultSensorContext(DefaultInputProject project, InputModule module, Configuration config, Settings mutableSettings, FileSystem fs, ActiveRules activeRules,
+ AnalysisMode analysisMode, SensorStorage sensorStorage, SonarRuntime sonarRuntime) {
+ this.project = project;
this.module = module;
this.config = config;
this.mutableSettings = mutableSettings;
this.analysisMode = analysisMode;
this.sensorStorage = sensorStorage;
this.sonarRuntime = sonarRuntime;
- this.hierarchy = hierarchy;
}
@Override
return module;
}
+ @Override
+ public InputProject project() {
+ return project;
+ }
+
@Override
public Version getSonarQubeVersion() {
return sonarRuntime.getApiVersion();
@Override
public NewIssue newIssue() {
- return new DefaultIssue(hierarchy.root(), sensorStorage);
+ return new DefaultIssue(project, sensorStorage);
}
@Override
if (analysisMode.isIssues()) {
return NO_OP_NEW_EXTERNAL_ISSUE;
}
- return new DefaultExternalIssue(hierarchy.root(), sensorStorage);
+ return new DefaultExternalIssue(project, sensorStorage);
}
@Override
return;
}
inputFile.setPublished(true);
- int componentRef = inputFile.batchId();
+ int componentRef = inputFile.scannerId();
if (writer.hasComponentData(FileStructure.Domain.SYNTAX_HIGHLIGHTINGS, componentRef)) {
throw new UnsupportedOperationException("Trying to save highlighting twice for the same file is not supported: " + inputFile);
}
return;
}
inputFile.setPublished(true);
- int componentRef = inputFile.batchId();
+ int componentRef = inputFile.scannerId();
if (writer.hasComponentData(FileStructure.Domain.SYMBOLS, componentRef)) {
throw new UnsupportedOperationException("Trying to save symbol table twice for the same file is not supported: " + symbolTable.inputFile());
}
return;
}
inputFile.setPublished(true);
- int componentRef = inputFile.batchId();
+ int componentRef = inputFile.scannerId();
if (writer.hasComponentData(FileStructure.Domain.SGNIFICANT_CODE, componentRef)) {
throw new UnsupportedOperationException(
"Trying to save significant code information twice for the same file is not supported: " + significantCode.inputFile());
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
-import org.sonar.api.batch.ScannerSide;
import org.sonar.api.batch.fs.FilePredicate;
import org.sonar.api.batch.fs.FileSystem;
import org.sonar.api.batch.rule.ActiveRules;
import org.sonar.api.batch.sensor.internal.DefaultSensorDescriptor;
import org.sonar.api.config.Configuration;
-@ScannerSide
public class SensorOptimizer {
private static final Logger LOG = LoggerFactory.getLogger(SensorOptimizer.class);
this.context = context;
this.descriptor = new DefaultSensorDescriptor();
newSensor.describe(this.descriptor);
+ if (descriptor.name() == null) {
+ descriptor.name(newSensor.getClass().getName());
+ }
}
public boolean shouldExecute() {
@Override
public String toString() {
- if (descriptor.name() != null) {
- return descriptor.name();
- } else {
- return wrappedSensor.getClass().getName();
- }
+ return descriptor.name();
}
public boolean isGlobal() {
import org.sonar.api.task.Task;
import org.sonar.api.task.TaskDefinition;
import org.sonar.core.platform.ComponentContainer;
-import org.sonar.scanner.analysis.AnalysisProperties;
import org.sonar.scanner.scan.ProjectScanContainer;
public class ScanTask implements Task {
.build();
private final ComponentContainer taskContainer;
- private final TaskProperties taskProps;
- public ScanTask(TaskContainer taskContainer, TaskProperties taskProps) {
+ public ScanTask(TaskContainer taskContainer) {
this.taskContainer = taskContainer;
- this.taskProps = taskProps;
}
@Override
public void execute() {
- AnalysisProperties props = new AnalysisProperties(taskProps.properties(), taskProps.property(CoreProperties.ENCRYPTION_SECRET_KEY_PATH));
- ProjectScanContainer scanContainer = new ProjectScanContainer(taskContainer, props);
- scanContainer.execute();
+ new ProjectScanContainer(taskContainer).execute();
}
}
import org.sonar.core.extension.CoreExtensionsInstaller;
import org.sonar.core.platform.ComponentContainer;
import org.sonar.scanner.bootstrap.ExtensionInstaller;
-import org.sonar.scanner.bootstrap.GlobalProperties;
import static org.sonar.api.batch.InstantiationStrategy.PER_TASK;
import static org.sonar.core.extension.CoreExtensionsInstaller.noExtensionFilter;
@Override
protected void doBeforeStart() {
addTaskExtensions();
- addCoreComponents();
for (Object component : components) {
add(component);
}
}
- private void addCoreComponents() {
- add(new TaskProperties(taskProperties, getParent().getComponentByType(GlobalProperties.class).property(CoreProperties.ENCRYPTION_SECRET_KEY_PATH)));
- }
-
private void addTaskExtensions() {
getComponentByType(CoreExtensionsInstaller.class)
.install(this, noExtensionFilter(), t -> isInstantiationStrategy(t, PER_TASK));
+++ /dev/null
-/*
- * 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.task;
-
-import java.util.Map;
-import javax.annotation.Nullable;
-import org.sonar.scanner.bootstrap.UserProperties;
-
-/**
- * Batch properties that are specific to a task (for example
- * coming from sonar-project.properties).
- */
-public class TaskProperties extends UserProperties {
-
- public TaskProperties(Map<String, String> properties, @Nullable String pathToSecretKey) {
- super(properties, pathToSecretKey);
- }
-
-}
@Test
public void testSetVerboseAnalysis() {
- Map<String, String> globalProps = Maps.newHashMap();
- LoggingConfiguration conf = new LoggingConfiguration(null).setProperties(globalProps);
+ Map<String, String> props = Maps.newHashMap();
+ LoggingConfiguration conf = new LoggingConfiguration(null).setProperties(props);
assertThat(conf.getSubstitutionVariable(LoggingConfiguration.PROPERTY_ROOT_LOGGER_LEVEL)).isEqualTo(LoggingConfiguration.LEVEL_ROOT_DEFAULT);
- Map<String, String> analysisProperties = Maps.newHashMap();
- analysisProperties.put("sonar.verbose", "true");
-
- conf.setProperties(analysisProperties, globalProps);
- assertThat(conf.getSubstitutionVariable(LoggingConfiguration.PROPERTY_ROOT_LOGGER_LEVEL)).isEqualTo(LoggingConfiguration.LEVEL_ROOT_VERBOSE);
- }
-
- @Test
- public void testOverrideVerbose() {
- Map<String, String> globalProps = Maps.newHashMap();
- globalProps.put("sonar.verbose", "true");
- LoggingConfiguration conf = new LoggingConfiguration(null).setProperties(globalProps);
+ props.put("sonar.verbose", "true");
+ conf.setProperties(props);
assertThat(conf.getSubstitutionVariable(LoggingConfiguration.PROPERTY_ROOT_LOGGER_LEVEL)).isEqualTo(LoggingConfiguration.LEVEL_ROOT_VERBOSE);
-
- Map<String, String> analysisProperties = Maps.newHashMap();
- analysisProperties.put("sonar.verbose", "false");
-
- conf.setProperties(analysisProperties, globalProps);
- assertThat(conf.getSubstitutionVariable(LoggingConfiguration.PROPERTY_ROOT_LOGGER_LEVEL)).isEqualTo(LoggingConfiguration.LEVEL_ROOT_DEFAULT);
}
@Test
import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.TemporaryFolder;
-import org.sonar.api.batch.fs.internal.DefaultInputModule;
-import org.sonar.api.batch.fs.internal.InputModuleHierarchy;
+import org.sonar.api.batch.fs.internal.DefaultInputProject;
import org.sonar.api.utils.TempFolder;
import static org.assertj.core.api.Assertions.assertThat;
public TemporaryFolder temp = new TemporaryFolder();
private AnalysisTempFolderProvider tempFolderProvider;
- private InputModuleHierarchy moduleHierarchy;
+ DefaultInputProject project = mock(DefaultInputProject.class);
@Before
public void setUp() {
tempFolderProvider = new AnalysisTempFolderProvider();
- moduleHierarchy = mock(InputModuleHierarchy.class);
- DefaultInputModule module = mock(DefaultInputModule.class);
- when(moduleHierarchy.root()).thenReturn(module);
- when(module.getWorkDir()).thenReturn(temp.getRoot().toPath());
+ when(project.getWorkDir()).thenReturn(temp.getRoot().toPath());
}
@Test
public void createTempFolder() throws IOException {
File defaultDir = new File(temp.getRoot(), AnalysisTempFolderProvider.TMP_NAME);
- TempFolder tempFolder = tempFolderProvider.provide(moduleHierarchy);
+ TempFolder tempFolder = tempFolderProvider.provide(project);
tempFolder.newDir();
tempFolder.newFile();
assertThat(defaultDir).exists();
import org.junit.Test;
import org.junit.rules.ExpectedException;
import org.sonar.scanner.bootstrap.GlobalAnalysisMode;
+import org.sonar.scanner.bootstrap.ScannerProperties;
import static org.assertj.core.api.Assertions.assertThat;
import static org.mockito.Mockito.mock;
@Test
public void scan_all_even_on_short_lived_branch() {
- AnalysisProperties analysisProps = new AnalysisProperties(Collections.singletonMap("sonar.scanAllFiles", "true"));
+ ScannerProperties analysisProps = new ScannerProperties(Collections.singletonMap("sonar.scanAllFiles", "true"));
DefaultAnalysisMode mode = createmode(analysisProps);
assertThat(mode.scanAllFiles()).isTrue();
when(globalMode.isIssues()).thenReturn(true);
when(globalMode.isPublish()).thenReturn(true);
when(globalMode.isPreview()).thenReturn(true);
- DefaultAnalysisMode mode = createmode(new AnalysisProperties(Collections.emptyMap()));
+ DefaultAnalysisMode mode = createmode(new ScannerProperties(Collections.emptyMap()));
assertThat(mode.isIssues()).isTrue();
assertThat(mode.isPublish()).isTrue();
@Test
public void scan_all_if_publish() {
when(globalMode.isIssues()).thenReturn(false);
- DefaultAnalysisMode mode = createmode(new AnalysisProperties(Collections.emptyMap()));
+ DefaultAnalysisMode mode = createmode(new ScannerProperties(Collections.emptyMap()));
assertThat(mode.scanAllFiles()).isTrue();
}
@Test
public void scan_all_if_property_set() {
- AnalysisProperties analysisProps = new AnalysisProperties(Collections.singletonMap("sonar.scanAllFiles", "true"));
+ ScannerProperties analysisProps = new ScannerProperties(Collections.singletonMap("sonar.scanAllFiles", "true"));
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 AnalysisProperties(Collections.emptyMap()));
+ DefaultAnalysisMode mode = createmode(new ScannerProperties(Collections.emptyMap()));
assertThat(mode.scanAllFiles()).isFalse();
}
- private DefaultAnalysisMode createmode(AnalysisProperties analysisProps) {
+ private DefaultAnalysisMode createmode(ScannerProperties analysisProps) {
return new DefaultAnalysisMode(analysisProps, globalMode);
}
+++ /dev/null
-/*
- * 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.collect.ImmutableMap;
-import org.junit.Rule;
-import org.junit.Test;
-import org.sonar.api.utils.log.LogTester;
-import org.sonar.api.utils.log.LoggerLevel;
-
-import static org.assertj.core.api.Assertions.assertThat;
-
-public class DroppedPropertyCheckerTest {
- private static final String SOME_VALUE = "some value";
- private static final String DROPPED_PROPERTY_1 = "I'm dropped";
- private static final String DROPPED_PROPERTY_MSG_1 = "blablabla!";
-
- @Rule
- public LogTester logTester = new LogTester();
-
- @Test
- public void no_log_if_no_dropped_property() {
- new DroppedPropertyChecker(ImmutableMap.of(DROPPED_PROPERTY_1, SOME_VALUE), ImmutableMap.<String, String>of()).checkDroppedProperties();
-
- assertThat(logTester.logs()).isEmpty();
- }
-
- @Test
- public void no_log_if_settings_does_not_contain_any_dropped_property() {
- new DroppedPropertyChecker(ImmutableMap.<String, String>of(), ImmutableMap.of(DROPPED_PROPERTY_1, DROPPED_PROPERTY_MSG_1)).checkDroppedProperties();
-
- assertThat(logTester.logs()).isEmpty();
- }
-
- @Test
- public void warn_log_if_settings_contains_any_dropped_property() {
- new DroppedPropertyChecker(ImmutableMap.of(DROPPED_PROPERTY_1, SOME_VALUE), ImmutableMap.of(DROPPED_PROPERTY_1, DROPPED_PROPERTY_MSG_1)).checkDroppedProperties();
-
- assertThat(logTester.logs(LoggerLevel.ERROR)).isEmpty();
- assertThat(logTester.logs(LoggerLevel.WARN)).containsOnly("Property '" + DROPPED_PROPERTY_1 + "' is not supported any more. " + DROPPED_PROPERTY_MSG_1);
- assertThat(logTester.logs(LoggerLevel.INFO)).isEmpty();
- assertThat(logTester.logs(LoggerLevel.DEBUG)).isEmpty();
- assertThat(logTester.logs(LoggerLevel.TRACE)).isEmpty();
- }
-}
if (key != null) {
map.put(key, value);
}
- GlobalProperties props = new GlobalProperties(map);
+ ScannerProperties props = new ScannerProperties(map);
return new GlobalAnalysisMode(props);
}
}
import org.junit.rules.ExpectedException;
import org.sonar.api.config.PropertyDefinitions;
import org.sonar.api.utils.log.LogTester;
-import org.sonar.api.utils.log.LoggerLevel;
-import org.sonar.scanner.repository.settings.SettingsLoader;
import static org.assertj.core.api.Assertions.assertThat;
import static org.mockito.Mockito.mock;
@Rule
public LogTester logTester = new LogTester();
- SettingsLoader settingsLoader;
- GlobalProperties bootstrapProps;
+ GlobalServerSettings globalServerSettings;
+ ScannerProperties scannerProps;
private GlobalAnalysisMode mode;
@Before
public void prepare() {
- settingsLoader = mock(SettingsLoader.class);
- bootstrapProps = new GlobalProperties(Collections.<String, String>emptyMap());
+ globalServerSettings = mock(GlobalServerSettings.class);
+ scannerProps = new ScannerProperties(Collections.<String, String>emptyMap());
mode = mock(GlobalAnalysisMode.class);
}
@Test
public void should_load_global_settings() {
- when(settingsLoader.load(null)).thenReturn(ImmutableMap.of("sonar.cpd.cross", "true"));
+ when(globalServerSettings.properties()).thenReturn(ImmutableMap.of("sonar.cpd.cross", "true"));
- GlobalConfiguration globalConfig = new GlobalConfigurationProvider().provide(settingsLoader, bootstrapProps, new PropertyDefinitions(), mode);
+ GlobalConfiguration globalConfig = new GlobalConfigurationProvider().provide(globalServerSettings, scannerProps, new PropertyDefinitions(), mode);
assertThat(globalConfig.get("sonar.cpd.cross")).hasValue("true");
}
-
- @Test
- public void should_log_warn_msg_for_each_jdbc_property_if_present() {
- when(settingsLoader.load(null)).thenReturn(ImmutableMap.of("sonar.jdbc.url", SOME_VALUE,
- "sonar.jdbc.username", SOME_VALUE,
- "sonar.jdbc.password", SOME_VALUE));
-
- new GlobalConfigurationProvider().provide(settingsLoader, bootstrapProps, new PropertyDefinitions(), mode);
-
- assertThat(logTester.logs(LoggerLevel.WARN)).containsOnly(
- "Property 'sonar.jdbc.url' is not supported any more. It will be ignored. There is no longer any DB connection to the SQ database.",
- "Property 'sonar.jdbc.username' is not supported any more. It will be ignored. There is no longer any DB connection to the SQ database.",
- "Property 'sonar.jdbc.password' is not supported any more. It will be ignored. There is no longer any DB connection to the SQ database.");
- }
}
+++ /dev/null
-/*
- * 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.collect.Maps;
-import java.util.Map;
-import org.junit.Test;
-
-import static org.assertj.core.api.Assertions.assertThat;
-import static org.assertj.core.api.Assertions.entry;
-
-public class GlobalPropertiesTest {
- @Test
- public void test_copy_of_properties() {
- Map<String, String> map = Maps.newHashMap();
- map.put("foo", "bar");
-
- GlobalProperties wrapper = new GlobalProperties(map);
- assertThat(wrapper.properties()).containsOnly(entry("foo", "bar"));
- assertThat(wrapper.properties()).isNotSameAs(map);
-
- map.put("put", "after_copy");
- assertThat(wrapper.properties()).hasSize(1);
- }
-}
File workingDir = temp.newFolder();
workingDir.delete();
- TempFolder tempFolder = tempFolderProvider.provide(new GlobalProperties(ImmutableMap.of(CoreProperties.GLOBAL_WORKING_DIRECTORY, workingDir.getAbsolutePath())));
+ TempFolder tempFolder = tempFolderProvider.provide(new ScannerProperties(ImmutableMap.of(CoreProperties.GLOBAL_WORKING_DIRECTORY, workingDir.getAbsolutePath())));
tempFolder.newDir();
tempFolder.newFile();
assertThat(getCreatedTempDir(workingDir)).exists();
setFileCreationDate(tmp, creationTime);
}
- tempFolderProvider.provide(new GlobalProperties(ImmutableMap.of(CoreProperties.GLOBAL_WORKING_DIRECTORY, workingDir.getAbsolutePath())));
+ tempFolderProvider.provide(new ScannerProperties(ImmutableMap.of(CoreProperties.GLOBAL_WORKING_DIRECTORY, workingDir.getAbsolutePath())));
// this also checks that all other temps were deleted
assertThat(getCreatedTempDir(workingDir)).exists();
File sonarHome = temp.newFolder();
File workingDir = new File(sonarHome, CoreProperties.GLOBAL_WORKING_DIRECTORY_DEFAULT_VALUE).getAbsoluteFile();
- TempFolder tempFolder = tempFolderProvider.provide(new GlobalProperties(ImmutableMap.of("sonar.userHome", sonarHome.getAbsolutePath())));
+ TempFolder tempFolder = tempFolderProvider.provide(new ScannerProperties(ImmutableMap.of("sonar.userHome", sonarHome.getAbsolutePath())));
tempFolder.newDir();
tempFolder.newFile();
assertThat(getCreatedTempDir(workingDir)).exists();
File defaultSonarHome = new File(userHome.getAbsolutePath(), ".sonar");
File workingDir = new File(defaultSonarHome, CoreProperties.GLOBAL_WORKING_DIRECTORY_DEFAULT_VALUE).getAbsoluteFile();
try {
- TempFolder tempFolder = tempFolderProvider.provide(new GlobalProperties(Collections.<String, String>emptyMap()));
+ TempFolder tempFolder = tempFolderProvider.provide(new ScannerProperties(Collections.<String, String>emptyMap()));
tempFolder.newDir();
tempFolder.newFile();
assertThat(getCreatedTempDir(workingDir)).exists();
public void dotWorkingDir() throws IOException {
File sonarHome = temp.getRoot();
String globalWorkDir = ".";
- GlobalProperties globalProperties = new GlobalProperties(ImmutableMap.of("sonar.userHome", sonarHome.getAbsolutePath(),
+ ScannerProperties globalProperties = new ScannerProperties(ImmutableMap.of("sonar.userHome", sonarHome.getAbsolutePath(),
CoreProperties.GLOBAL_WORKING_DIRECTORY, globalWorkDir));
TempFolder tempFolder = tempFolderProvider.provide(globalProperties);
File symlink = temp.newFolder();
symlink.delete();
Files.createSymbolicLink(symlink.toPath(), realSonarHome.toPath());
- GlobalProperties globalProperties = new GlobalProperties(ImmutableMap.of("sonar.userHome", symlink.getAbsolutePath()));
+ ScannerProperties globalProperties = new ScannerProperties(ImmutableMap.of("sonar.userHome", symlink.getAbsolutePath()));
TempFolder tempFolder = tempFolderProvider.provide(globalProperties);
File newFile = tempFolder.newFile();
@Before
public void setUp() throws Exception {
HttpConnector connector = HttpConnector.newBuilder().url(server.url("/").toString()).build();
- GlobalAnalysisMode analysisMode = new GlobalAnalysisMode(new GlobalProperties(Collections.emptyMap()));
+ GlobalAnalysisMode analysisMode = new GlobalAnalysisMode(new ScannerProperties(Collections.emptyMap()));
ScannerWsClient wsClient = new ScannerWsClient(WsClientFactories.getDefault().newClient(connector), false, analysisMode);
userHome = temp.newFolder();
--- /dev/null
+/*
+ * 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.collect.Maps;
+import java.util.Map;
+import org.junit.Test;
+
+import static org.assertj.core.api.Assertions.assertThat;
+import static org.assertj.core.api.Assertions.entry;
+
+public class ScannerPropertiesTest {
+ @Test
+ public void test_copy_of_properties() {
+ Map<String, String> map = Maps.newHashMap();
+ map.put("foo", "bar");
+
+ ScannerProperties underTest = new ScannerProperties(map);
+ assertThat(underTest.properties()).containsOnly(entry("foo", "bar"));
+ assertThat(underTest.properties()).isNotSameAs(map);
+
+ map.put("put", "after_copy");
+ assertThat(underTest.properties()).hasSize(1);
+ }
+}
@Test
public void provide_client_with_default_settings() {
- GlobalProperties settings = new GlobalProperties(new HashMap<>());
+ ScannerProperties settings = new ScannerProperties(new HashMap<>());
- ScannerWsClient client = underTest.provide(settings, env, new GlobalAnalysisMode(new GlobalProperties(Collections.emptyMap())), mock(System2.class));
+ ScannerWsClient client = underTest.provide(settings, env, new GlobalAnalysisMode(new ScannerProperties(Collections.emptyMap())), mock(System2.class));
assertThat(client).isNotNull();
assertThat(client.baseUrl()).isEqualTo("http://localhost:9000/");
props.put("sonar.login", "theLogin");
props.put("sonar.password", "thePassword");
props.put("sonar.ws.timeout", "42");
- GlobalProperties settings = new GlobalProperties(props);
+ ScannerProperties settings = new ScannerProperties(props);
- ScannerWsClient client = underTest.provide(settings, env, new GlobalAnalysisMode(new GlobalProperties(Collections.emptyMap())), mock(System2.class));
+ ScannerWsClient client = underTest.provide(settings, env, new GlobalAnalysisMode(new ScannerProperties(Collections.emptyMap())), mock(System2.class));
assertThat(client).isNotNull();
HttpConnector httpConnector = (HttpConnector) client.wsConnector();
public void build_singleton() {
System2 system = mock(System2.class);
- GlobalProperties settings = new GlobalProperties(new HashMap<>());
- ScannerWsClient first = underTest.provide(settings, env, new GlobalAnalysisMode(new GlobalProperties(Collections.emptyMap())), system);
- ScannerWsClient second = underTest.provide(settings, env, new GlobalAnalysisMode(new GlobalProperties(Collections.emptyMap())), system);
+ ScannerProperties settings = new ScannerProperties(new HashMap<>());
+ ScannerWsClient first = underTest.provide(settings, env, new GlobalAnalysisMode(new ScannerProperties(Collections.emptyMap())), system);
+ ScannerWsClient second = underTest.provide(settings, env, new GlobalAnalysisMode(new ScannerProperties(Collections.emptyMap())), system);
assertThat(first).isSameAs(second);
}
}
when(wsClient.wsConnector().call(request)).thenReturn(response);
logTester.setLevel(LoggerLevel.DEBUG);
- ScannerWsClient underTest = new ScannerWsClient(wsClient, false, new GlobalAnalysisMode(new GlobalProperties(Collections.emptyMap())));
+ ScannerWsClient underTest = new ScannerWsClient(wsClient, false, new GlobalAnalysisMode(new ScannerProperties(Collections.emptyMap())));
WsResponse result = underTest.call(request);
WsResponse response = newResponse().setCode(401);
when(wsClient.wsConnector().call(request)).thenReturn(response);
- new ScannerWsClient(wsClient, false, new GlobalAnalysisMode(new GlobalProperties(Collections.emptyMap()))).call(request);
+ new ScannerWsClient(wsClient, false, new GlobalAnalysisMode(new ScannerProperties(Collections.emptyMap()))).call(request);
}
@Test
WsResponse response = newResponse().setCode(401);
when(wsClient.wsConnector().call(request)).thenReturn(response);
- new ScannerWsClient(wsClient, /* credentials are configured */true, new GlobalAnalysisMode(new GlobalProperties(Collections.emptyMap()))).call(request);
+ new ScannerWsClient(wsClient, /* credentials are configured */true, new GlobalAnalysisMode(new ScannerProperties(Collections.emptyMap()))).call(request);
}
@Test
.setContent("{\"errors\":[{\"msg\":\"missing scan permission\"}, {\"msg\":\"missing another permission\"}]}");
when(wsClient.wsConnector().call(request)).thenReturn(response);
- new ScannerWsClient(wsClient, true, new GlobalAnalysisMode(new GlobalProperties(Collections.emptyMap()))).call(request);
+ new ScannerWsClient(wsClient, true, new GlobalAnalysisMode(new ScannerProperties(Collections.emptyMap()))).call(request);
}
@Test
.setContent("{\"errors\":[{\"msg\":\"Boo! bad request! bad!\"}]}");
when(wsClient.wsConnector().call(request)).thenReturn(response);
- new ScannerWsClient(wsClient, true, new GlobalAnalysisMode(new GlobalProperties(Collections.emptyMap()))).call(request);
+ new ScannerWsClient(wsClient, true, new GlobalAnalysisMode(new ScannerProperties(Collections.emptyMap()))).call(request);
}
private MockWsResponse newResponse() {
import org.junit.rules.TemporaryFolder;
import org.mockito.ArgumentMatchers;
import org.sonar.api.batch.fs.internal.DefaultInputFile;
-import org.sonar.api.batch.fs.internal.DefaultInputModule;
+import org.sonar.api.batch.fs.internal.DefaultInputProject;
import org.sonar.api.batch.fs.internal.TestInputFileBuilder;
import org.sonar.api.utils.log.LogTester;
import org.sonar.api.utils.log.LoggerLevel;
baseDir = temp.newFolder();
when(publisher.getWriter()).thenReturn(new ScannerReportWriter(outputDir));
- DefaultInputModule inputModule = TestInputFileBuilder.newDefaultInputModule("foo", baseDir);
- componentStore = new InputComponentStore(inputModule, mock(BranchConfiguration.class));
+ DefaultInputProject project = TestInputFileBuilder.newDefaultInputProject("foo", baseDir);
+ componentStore = new InputComponentStore(project, mock(BranchConfiguration.class));
executor = new CpdExecutor(settings, index, publisher, componentStore, executorService);
reader = new ScannerReportReader(outputDir);
@Test
public void dont_fail_if_nothing_to_save() {
executor.saveDuplications(batchComponent1, Collections.<CloneGroup>emptyList());
- assertThat(reader.readComponentDuplications(batchComponent1.batchId())).hasSize(0);
+ assertThat(reader.readComponentDuplications(batchComponent1.scannerId())).hasSize(0);
}
@Test
executor.saveDuplications(batchComponent1, groups);
Duplication[] dups = readDuplications(1);
- assertDuplication(dups[0], 2, 4, batchComponent2.batchId(), 15, 17);
+ assertDuplication(dups[0], 2, 4, batchComponent2.scannerId(), 15, 17);
}
@Test
}
executor.saveDuplications(batchComponent1, dups);
- assertThat(reader.readComponentDuplications(batchComponent1.batchId())).hasSize(CpdExecutor.MAX_CLONE_GROUP_PER_FILE);
+ assertThat(reader.readComponentDuplications(batchComponent1.scannerId())).hasSize(CpdExecutor.MAX_CLONE_GROUP_PER_FILE);
assertThat(logTester.logs(LoggerLevel.WARN))
.contains("Too many duplication groups on file " + batchComponent1 + ". Keep only the first " + CpdExecutor.MAX_CLONE_GROUP_PER_FILE + " groups.");
Duplication[] dups = readDuplications(1);
assertDuplication(dups[0], 5, 204, 2);
- assertDuplicate(dups[0].getDuplicate(0), batchComponent2.batchId(), 15, 214);
- assertDuplicate(dups[0].getDuplicate(1), batchComponent3.batchId(), 25, 224);
+ assertDuplicate(dups[0].getDuplicate(0), batchComponent2.scannerId(), 15, 214);
+ assertDuplicate(dups[0].getDuplicate(1), batchComponent3.scannerId(), 25, 224);
}
@Test
executor.saveDuplications(batchComponent1, groups);
Duplication[] dups = readDuplications(2);
- assertDuplication(dups[0], 5, 204, batchComponent2.batchId(), 15, 214);
- assertDuplication(dups[1], 15, 214, batchComponent3.batchId(), 15, 214);
+ assertDuplication(dups[0], 5, 204, batchComponent2.scannerId(), 15, 214);
+ assertDuplication(dups[1], 15, 214, batchComponent3.scannerId(), 15, 214);
}
@Test
}
private Duplication[] readDuplications(DefaultInputFile file, int expected) {
- assertThat(reader.readComponentDuplications(file.batchId())).hasSize(expected);
+ assertThat(reader.readComponentDuplications(file.scannerId())).hasSize(expected);
Duplication[] duplications = new Duplication[expected];
- CloseableIterator<Duplication> dups = reader.readComponentDuplications(file.batchId());
+ CloseableIterator<Duplication> dups = reader.readComponentDuplications(file.scannerId());
for (int i = 0; i < expected; i++) {
duplications[i] = dups.next();
import java.util.Optional;
import org.junit.Before;
import org.junit.Test;
-import org.sonar.api.batch.fs.internal.DefaultInputModule;
-import org.sonar.api.batch.fs.internal.InputModuleHierarchy;
+import org.sonar.api.batch.fs.internal.DefaultInputProject;
import org.sonar.api.config.Configuration;
import static org.assertj.core.api.Assertions.assertThat;
public class CpdSettingsTest {
private CpdSettings cpdSettings;
private Configuration configuration;
- private DefaultInputModule module;
+ private DefaultInputProject project;
@Before
public void setUp() {
- module = mock(DefaultInputModule.class);
- InputModuleHierarchy hierarchy = mock(InputModuleHierarchy.class);
- when(hierarchy.root()).thenReturn(module);
+ project = mock(DefaultInputProject.class);
configuration = mock(Configuration.class);
- cpdSettings = new CpdSettings(configuration, hierarchy);
+ cpdSettings = new CpdSettings(configuration, project);
}
@Test
import org.junit.ClassRule;
import org.junit.rules.TemporaryFolder;
import org.sonar.api.CoreProperties;
-import org.sonar.scanner.bootstrap.GlobalProperties;
import org.sonar.scanner.bootstrap.GlobalTempFolderProvider;
+import org.sonar.scanner.bootstrap.ScannerProperties;
import org.sonar.scanner.storage.Storages;
import org.sonar.scanner.storage.StoragesManager;
Map<String, String> props = ImmutableMap.of(CoreProperties.WORKING_DIRECTORY, temp.getRoot().getAbsolutePath(),
CoreProperties.GLOBAL_WORKING_DIRECTORY, temp.getRoot().getAbsolutePath());
- return new StoragesManager(new GlobalTempFolderProvider().provide(new GlobalProperties(props)));
+ return new StoragesManager(new GlobalTempFolderProvider().provide(new ScannerProperties(props)));
}
@BeforeClass
import org.mockito.runners.MockitoJUnitRunner;
import org.sonar.api.batch.bootstrap.ProjectDefinition;
import org.sonar.api.batch.fs.internal.DefaultInputFile;
-import org.sonar.api.batch.fs.internal.DefaultInputModule;
+import org.sonar.api.batch.fs.internal.DefaultInputProject;
import org.sonar.api.batch.fs.internal.TestInputFileBuilder;
import org.sonar.api.batch.rule.internal.ActiveRulesBuilder;
import org.sonar.api.batch.rule.internal.NewActiveRule;
static final String SQUID_RULE_NAME = "Avoid Cycle";
private static final RuleKey NOSONAR_RULE_KEY = RuleKey.of("squid", "NoSonarCheck");
- private DefaultInputModule projectRoot;
+ private DefaultInputProject project;
@Rule
public TemporaryFolder temp = new TemporaryFolder();
@Before
public void prepare() throws IOException {
- projectRoot = new DefaultInputModule(ProjectDefinition.create()
+ project = new DefaultInputProject(ProjectDefinition.create()
.setKey("foo")
.setBaseDir(temp.newFolder())
.setWorkDir(temp.newFolder()));
public void ignore_null_active_rule() {
ruleBuilder.add(SQUID_RULE_KEY).setName(SQUID_RULE_NAME);
initModuleIssues();
- DefaultIssue issue = new DefaultIssue(projectRoot)
+ DefaultIssue issue = new DefaultIssue(project)
.at(new DefaultIssueLocation().on(file).at(file.selectLine(3)).message("Foo"))
.forRule(SQUID_RULE_KEY);
boolean added = moduleIssues.initAndAddIssue(issue);
activeRulesBuilder.addRule(new NewActiveRule.Builder().setRuleKey(SQUID_RULE_KEY).setQProfileKey("qp-1").build());
initModuleIssues();
- DefaultIssue issue = new DefaultIssue(projectRoot)
+ DefaultIssue issue = new DefaultIssue(project)
.at(new DefaultIssueLocation().on(file).at(file.selectLine(3)).message("Foo"))
.forRule(SQUID_RULE_KEY);
boolean added = moduleIssues.initAndAddIssue(issue);
.build());
initModuleIssues();
- DefaultIssue issue = new DefaultIssue(projectRoot)
+ DefaultIssue issue = new DefaultIssue(project)
.at(new DefaultIssueLocation().on(file).at(file.selectLine(3)).message("Foo"))
.forRule(SQUID_RULE_KEY)
.overrideSeverity(org.sonar.api.batch.rule.Severity.CRITICAL);
assertThat(added).isTrue();
ArgumentCaptor<ScannerReport.Issue> argument = ArgumentCaptor.forClass(ScannerReport.Issue.class);
- verify(reportPublisher.getWriter()).appendComponentIssue(eq(file.batchId()), argument.capture());
+ verify(reportPublisher.getWriter()).appendComponentIssue(eq(file.scannerId()), argument.capture());
assertThat(argument.getValue().getSeverity()).isEqualTo(org.sonar.scanner.protocol.Constants.Severity.CRITICAL);
}
ruleBuilder.add(SQUID_RULE_KEY).setName(SQUID_RULE_NAME);
initModuleIssues();
- DefaultExternalIssue issue = new DefaultExternalIssue(projectRoot)
+ DefaultExternalIssue issue = new DefaultExternalIssue(project)
.at(new DefaultIssueLocation().on(file).at(file.selectLine(3)).message("Foo"))
.type(RuleType.BUG)
.forRule(SQUID_RULE_KEY)
moduleIssues.initAndAddExternalIssue(issue);
ArgumentCaptor<ScannerReport.ExternalIssue> argument = ArgumentCaptor.forClass(ScannerReport.ExternalIssue.class);
- verify(reportPublisher.getWriter()).appendComponentExternalIssue(eq(file.batchId()), argument.capture());
+ verify(reportPublisher.getWriter()).appendComponentExternalIssue(eq(file.scannerId()), argument.capture());
assertThat(argument.getValue().getSeverity()).isEqualTo(org.sonar.scanner.protocol.Constants.Severity.CRITICAL);
}
.build());
initModuleIssues();
- DefaultIssue issue = new DefaultIssue(projectRoot)
+ DefaultIssue issue = new DefaultIssue(project)
.at(new DefaultIssueLocation().on(file).at(file.selectLine(3)).message("Foo"))
.forRule(SQUID_RULE_KEY);
when(filters.accept(anyString(), any(ScannerReport.Issue.class))).thenReturn(true);
moduleIssues.initAndAddIssue(issue);
ArgumentCaptor<ScannerReport.Issue> argument = ArgumentCaptor.forClass(ScannerReport.Issue.class);
- verify(reportPublisher.getWriter()).appendComponentIssue(eq(file.batchId()), argument.capture());
+ verify(reportPublisher.getWriter()).appendComponentIssue(eq(file.scannerId()), argument.capture());
assertThat(argument.getValue().getSeverity()).isEqualTo(org.sonar.scanner.protocol.Constants.Severity.INFO);
}
.build());
initModuleIssues();
- DefaultIssue issue = new DefaultIssue(projectRoot)
+ DefaultIssue issue = new DefaultIssue(project)
.at(new DefaultIssueLocation().on(file).at(file.selectLine(3)).message(""))
.forRule(SQUID_RULE_KEY);
.build());
initModuleIssues();
- DefaultIssue issue = new DefaultIssue(projectRoot)
+ DefaultIssue issue = new DefaultIssue(project)
.at(new DefaultIssueLocation().on(file).at(file.selectLine(3)).message(""))
.forRule(SQUID_RULE_KEY);
file.noSonarAt(new HashSet<>(Collections.singletonList(3)));
- DefaultIssue issue = new DefaultIssue(projectRoot)
+ DefaultIssue issue = new DefaultIssue(project)
.at(new DefaultIssueLocation().on(file).at(file.selectLine(3)).message(""))
.forRule(NOSONAR_RULE_KEY);
boolean added = moduleIssues.initAndAddIssue(issue);
assertThat(added).isTrue();
- verify(reportPublisher.getWriter()).appendComponentIssue(eq(file.batchId()), any());
+ verify(reportPublisher.getWriter()).appendComponentIssue(eq(file.scannerId()), any());
}
/**
}
}
- public TaskBuilder newTask() {
- return new TaskBuilder(this);
+ public AnalysisBuilder newAnalysis() {
+ return new AnalysisBuilder(this);
}
- public TaskBuilder newScanTask(File sonarProps) {
+ public AnalysisBuilder newAnalysis(File sonarProps) {
Properties prop = new Properties();
try (Reader reader = new InputStreamReader(new FileInputStream(sonarProps), StandardCharsets.UTF_8)) {
prop.load(reader);
} catch (Exception e) {
throw new IllegalStateException("Unable to read configuration file", e);
}
- TaskBuilder builder = new TaskBuilder(this);
+ AnalysisBuilder builder = new AnalysisBuilder(this);
builder.property("sonar.projectBaseDir", sonarProps.getParentFile().getAbsolutePath());
for (Map.Entry<Object, Object> entry : prop.entrySet()) {
builder.property(entry.getKey().toString(), entry.getValue().toString());
return builder;
}
- public static class TaskBuilder {
+ public static class AnalysisBuilder {
private final Map<String, String> taskProperties = new HashMap<>();
private ScannerMediumTester tester;
- public TaskBuilder(ScannerMediumTester tester) {
+ public AnalysisBuilder(ScannerMediumTester tester) {
this.tester = tester;
}
- public TaskResult execute() {
- TaskResult result = new TaskResult();
+ public AnalysisResult execute() {
+ AnalysisResult result = new AnalysisResult();
Map<String, String> props = new HashMap<>();
props.putAll(tester.globalProperties);
props.putAll(taskProperties);
Batch.builder()
- .setGlobalProperties(props)
+ .setScannerProperties(props)
.setEnableLoggingConfiguration(true)
.addComponents(new EnvironmentInformation("mediumTest", "1.0"),
tester.pluginInstaller,
return result;
}
- public TaskBuilder properties(Map<String, String> props) {
+ public AnalysisBuilder properties(Map<String, String> props) {
taskProperties.putAll(props);
return this;
}
- public TaskBuilder property(String key, String value) {
+ public AnalysisBuilder property(String key, String value) {
taskProperties.put(key, value);
return this;
}
import org.junit.rules.TemporaryFolder;
import org.sonar.api.batch.fs.internal.FileMetadata;
import org.sonar.scanner.mediumtest.ScannerMediumTester;
-import org.sonar.scanner.mediumtest.TaskResult;
+import org.sonar.scanner.mediumtest.AnalysisResult;
import org.sonar.scanner.protocol.output.ScannerReport;
import org.sonar.scanner.repository.FileData;
import org.sonar.scanner.scan.branch.BranchType;
@Test
public void should_not_skip_report_for_unchanged_files_in_short_branch() {
// sanity check, normally report gets generated
- TaskResult result = getResult(tester);
+ AnalysisResult result = getResult(tester);
assertThat(getResult(tester).getReportComponent(result.inputFile(FILE_PATH).key())).isNotNull();
int fileId = 2;
assertThat(result.getReportReader().readChangesets(fileId)).isNotNull();
assertThat(result.getReportReader().readFileSource(fileId)).isNotNull();
// file is not skipped for short branches (need coverage, duplications coming soon)
- TaskResult result2 = getResult(tester.setBranchType(BranchType.SHORT));
+ AnalysisResult result2 = getResult(tester.setBranchType(BranchType.SHORT));
assertThat(result2.getReportComponent(result2.inputFile(FILE_PATH).key())).isNotNull();
assertThat(result2.getReportReader().readChangesets(fileId)).isNull();
assertThat(result2.getReportReader().hasCoverage(fileId)).isTrue();
String branchName = "feature";
String branchTarget = "branch-1.x";
- TaskResult result = getResult(tester
+ AnalysisResult result = getResult(tester
.setBranchName(branchName)
.setBranchTarget(branchTarget)
.setLongLivingSonarReferenceBranch(branchTarget)
assertThat(metadata.getMergeBranchName()).isEqualTo(branchTarget);
}
- private TaskResult getResult(ScannerMediumTester tester) {
+ private AnalysisResult getResult(ScannerMediumTester tester) {
return tester
- .newTask()
+ .newAnalysis()
.properties(ImmutableMap.<String, String>builder()
.put("sonar.task", "scan")
.put("sonar.projectBaseDir", baseDir.getAbsolutePath())
import org.junit.rules.TemporaryFolder;
import org.sonar.api.batch.fs.internal.DefaultInputFile;
import org.sonar.scanner.mediumtest.ScannerMediumTester;
-import org.sonar.scanner.mediumtest.TaskResult;
+import org.sonar.scanner.mediumtest.AnalysisResult;
import org.sonar.xoo.XooPlugin;
import org.sonar.xoo.rule.XooRulesDefinition;
File xooFile = new File(srcDir, "sample.xoo");
FileUtils.write(xooFile, "Sample xoo\ncontent");
- TaskResult result = tester.newTask()
+ AnalysisResult result = tester.newAnalysis()
.properties(ImmutableMap.<String, String>builder()
.putAll(commonProps)
.put("sonar.branch", "branch")
assertThat(result.inputFile("src/sample.xoo").key()).isEqualTo("com.foo.project:src/sample.xoo");
DefaultInputFile inputfile = (DefaultInputFile) result.inputFile("src/sample.xoo");
- assertThat(result.getReportReader().readComponent(inputfile.batchId()).getPath()).isEqualTo("src/sample.xoo");
+ assertThat(result.getReportReader().readComponent(inputfile.scannerId()).getPath()).isEqualTo("src/sample.xoo");
assertThat(result.getReportReader().readMetadata().getDeprecatedBranch()).isEqualTo("branch");
- result = tester.newTask()
+ result = tester.newAnalysis()
.properties(ImmutableMap.<String, String>builder()
.putAll(commonProps)
.put("sonar.branch", "")
File xooFile = new File(srcDir.toFile(), "sample.xoo");
FileUtils.write(xooFile, "Sample xoo\ncontent");
- TaskResult result = tester.newTask()
+ AnalysisResult result = tester.newAnalysis()
.properties(ImmutableMap.<String, String>builder()
.putAll(commonProps)
.put("sonar.branch", "branch")
// no branch in the report
DefaultInputFile inputfile = (DefaultInputFile) result.inputFile("moduleA/src/sample.xoo");
- assertThat(result.getReportReader().readComponent(inputfile.batchId()).getPath()).isEqualTo("src/sample.xoo");
+ assertThat(result.getReportReader().readComponent(inputfile.scannerId()).getPath()).isEqualTo("src/sample.xoo");
// no branch in InputModule's key or in report
assertThat(result.getReportComponent("com.foo.project:moduleA").getKey()).isEqualTo("com.foo.project:moduleA");
assertThat(result.getReportReader().readMetadata().getDeprecatedBranch()).isEqualTo("branch");
- result = tester.newTask()
+ result = tester.newAnalysis()
.properties(ImmutableMap.<String, String>builder()
.putAll(commonProps)
.put("sonar.branch", "")
import java.io.File;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
-import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import org.apache.commons.io.FileUtils;
import org.junit.rules.TemporaryFolder;
import org.sonar.api.batch.fs.InputFile;
import org.sonar.api.measures.CoreMetrics;
+import org.sonar.api.utils.log.LogTester;
+import org.sonar.api.utils.log.LoggerLevel;
import org.sonar.scanner.mediumtest.ScannerMediumTester;
-import org.sonar.scanner.mediumtest.TaskResult;
+import org.sonar.scanner.mediumtest.AnalysisResult;
import org.sonar.xoo.XooPlugin;
import static org.assertj.core.api.Assertions.assertThat;
public class CoverageMediumTest {
- private final List<String> logs = new ArrayList<>();
+ @Rule
+ public LogTester logTester = new LogTester();
@Rule
public TemporaryFolder temp = new TemporaryFolder();
@Rule
public ScannerMediumTester tester = new ScannerMediumTester()
- .setLogOutput((msg, level) -> logs.add(msg))
.registerPlugin("xoo", new XooPlugin())
.addDefaultQProfile("xoo", "Sonar Way");
FileUtils.write(xooFile, "function foo() {\n if (a && b) {\nalert('hello');\n}\n}", StandardCharsets.UTF_8);
FileUtils.write(xooUtCoverageFile, "2:2:2:1\n3:1", StandardCharsets.UTF_8);
- TaskResult result = tester.newTask()
+ AnalysisResult result = tester.newAnalysis()
.properties(ImmutableMap.<String, String>builder()
.put("sonar.task", "scan")
.put("sonar.projectBaseDir", baseDir.getAbsolutePath())
File xooItCoverageFile = new File(srcDir, "sample.xoo.itcoverage");
FileUtils.write(xooItCoverageFile, "2:2:2:1\n3:1\n5:0", StandardCharsets.UTF_8);
- TaskResult result = tester.newTask()
+ AnalysisResult result = tester.newAnalysis()
.properties(ImmutableMap.<String, String>builder()
.put("sonar.task", "scan")
.put("sonar.projectBaseDir", baseDir.getAbsolutePath())
FileUtils.write(xooFile, "function foo() {\n if (a && b) {\nalert('hello');\n}\n}", StandardCharsets.UTF_8);
FileUtils.write(xooUtCoverageFile, "2:2:2:1\n3:1", StandardCharsets.UTF_8);
- TaskResult result = tester.newTask()
+ AnalysisResult result = tester.newAnalysis()
.properties(ImmutableMap.<String, String>builder()
.put("sonar.task", "scan")
.put("sonar.projectBaseDir", baseDir.getAbsolutePath())
FileUtils.write(xooFileB, "function foo() {\n if (a && b) {\nalert('hello');\n}\n}", StandardCharsets.UTF_8);
FileUtils.write(xooUtCoverageFileB, "2:2:2:1\n3:1", StandardCharsets.UTF_8);
- TaskResult result = tester.newTask()
+ AnalysisResult result = tester.newAnalysis()
.properties(ImmutableMap.<String, String>builder()
.put("sonar.task", "scan")
.put("sonar.projectBaseDir", baseDir.getAbsolutePath())
InputFile fileB = result.inputFile("moduleB/src/sample.xoo");
assertThat(result.coverageFor(fileB, 2)).isNull();
- assertThat(logs).contains("File 'moduleA/src/sample.xoo' was excluded from coverage because patterns are still " +
+ assertThat(logTester.logs(LoggerLevel.WARN)).contains("File 'moduleA/src/sample.xoo' was excluded from coverage because patterns are still " +
"evaluated using module relative paths but this is deprecated. Please update 'sonar.coverage.exclusions' " +
"configuration so that patterns refer to project relative paths");
}
FileUtils.write(xooFileB, "function foo() {\n if (a && b) {\nalert('hello');\n}\n}", StandardCharsets.UTF_8);
FileUtils.write(xooUtCoverageFileB, "2:2:2:1\n3:1", StandardCharsets.UTF_8);
- TaskResult result = tester.newTask()
+ AnalysisResult result = tester.newAnalysis()
.properties(ImmutableMap.<String, String>builder()
.put("sonar.task", "scan")
.put("sonar.projectBaseDir", baseDir.getAbsolutePath())
InputFile fileB = result.inputFile("moduleB/src/sample.xoo");
assertThat(result.coverageFor(fileB, 2)).isNull();
- assertThat(logs).contains("Defining coverage exclusions at module level is deprecated. " +
+ assertThat(logTester.logs(LoggerLevel.WARN)).contains("Defining coverage exclusions at module level is deprecated. " +
"Move 'sonar.coverage.exclusions' from module 'moduleB' " +
- "to the root project and update patterns to refer to project relative paths");
+ "to the root project and update patterns to refer to project relative paths");
}
@Test
FileUtils.write(xooFile, "function foo() {\n if (a && b) {\nalert('hello');\n}\n}", StandardCharsets.UTF_8);
FileUtils.write(measuresFile, "executable_lines_data:2=1;3=1;4=0", StandardCharsets.UTF_8);
- TaskResult result = tester.newTask()
+ AnalysisResult result = tester.newAnalysis()
.properties(ImmutableMap.<String, String>builder()
.put("sonar.task", "scan")
.put("sonar.projectBaseDir", baseDir.getAbsolutePath())
FileUtils.write(xooFile2, "function foo() {\n if (a && b) {\nalert('hello');\n}\n}", StandardCharsets.UTF_8);
FileUtils.write(measuresFile2, "executable_lines_data:2=1;3=1;4=0", StandardCharsets.UTF_8);
- TaskResult result = tester.newTask()
+ AnalysisResult result = tester.newAnalysis()
.properties(ImmutableMap.<String, String>builder()
.put("sonar.task", "scan")
.put("sonar.projectBaseDir", baseDir.getAbsolutePath())
import org.sonar.api.batch.fs.InputFile;
import org.sonar.api.measures.CoreMetrics;
import org.sonar.scanner.mediumtest.ScannerMediumTester;
-import org.sonar.scanner.mediumtest.TaskResult;
+import org.sonar.scanner.mediumtest.AnalysisResult;
import org.sonar.xoo.XooPlugin;
import static org.assertj.core.api.Assertions.assertThat;
File projectDir = new File("test-resources/mediumtest/xoo/sample-generic-coverage");
- TaskResult result = tester
+ AnalysisResult result = tester
.setLogOutput((msg, level) -> logs.add(msg))
- .newScanTask(new File(projectDir, "sonar-project.properties"))
+ .newAnalysis(new File(projectDir, "sonar-project.properties"))
.property("sonar.coverageReportPaths", "coverage.xml")
.execute();
tester
.setLogOutput((msg, level) -> logs.add(msg))
- .newScanTask(new File(projectDir, "sonar-project.properties"))
+ .newAnalysis(new File(projectDir, "sonar-project.properties"))
.property("sonar.genericcoverage.reportPath", "coverage.xml")
.execute();
File projectDir = new File("test-resources/mediumtest/xoo/sample-generic-coverage");
- TaskResult result = tester
+ AnalysisResult result = tester
.setLogOutput((msg, level) -> logs.add(msg))
- .newScanTask(new File(projectDir, "sonar-project.properties"))
+ .newAnalysis(new File(projectDir, "sonar-project.properties"))
.property("sonar.coverageReportPaths", "coverage.xml,coverage2.xml")
.execute();
import org.junit.rules.ExpectedException;
import org.junit.rules.TemporaryFolder;
import org.sonar.api.batch.fs.InputFile;
-import org.sonar.scanner.mediumtest.LogOutputRecorder;
+import org.sonar.api.utils.log.LogTester;
import org.sonar.scanner.mediumtest.ScannerMediumTester;
-import org.sonar.scanner.mediumtest.TaskResult;
+import org.sonar.scanner.mediumtest.AnalysisResult;
import org.sonar.scanner.protocol.output.ScannerReport;
import org.sonar.xoo.XooPlugin;
import org.sonar.xoo.rule.XooRulesDefinition;
@Rule
public ExpectedException thrown = ExpectedException.none();
- private LogOutputRecorder logRecorder = new LogOutputRecorder();
+ @Rule
+ public LogTester logTester = new LogTester();
+
private File baseDir;
@Rule
.addDefaultQProfile("xoo", "Sonar Way")
.addRules(new XooRulesDefinition())
// active a rule just to be sure that xoo files are published
- .addActiveRule("xoo", "xoo:OneIssuePerFile", null, "One Issue Per File", null, null, null)
- .setLogOutput(logRecorder);
+ .addActiveRule("xoo", "xoo:OneIssuePerFile", null, "One Issue Per File", null, null, null);
private ImmutableMap.Builder<String, String> builder;
@Before
public void prepare() {
baseDir = temp.getRoot();
- logRecorder.getAll().clear();
builder = ImmutableMap.<String, String>builder()
.put("sonar.task", "scan")
File xooFile2 = new File(module2Dir, "sample2.xoo");
FileUtils.write(xooFile2, duplicatedStuff);
- TaskResult result = tester.newTask().properties(builder.build()).execute();
+ AnalysisResult result = tester.newAnalysis().properties(builder.build()).execute();
assertThat(result.inputFiles()).hasSize(2);
File xooFile2 = new File(srcDir, "sample2.xoo");
FileUtils.write(xooFile2, duplicatedStuff, StandardCharsets.UTF_8);
- TaskResult result = tester.newTask()
+ AnalysisResult result = tester.newAnalysis()
.properties(builder
.put("sonar.sources", "src")
.put("sonar.cpd.xoo.minimumTokens", "10")
File xooFile2 = new File(srcDir, "sample2.xoo");
FileUtils.write(xooFile2, file2, StandardCharsets.UTF_8);
- TaskResult result = tester.newTask()
+ AnalysisResult result = tester.newAnalysis()
.properties(builder
.put("sonar.sources", "src")
.put("sonar.cpd.xoo.minimumTokens", "10")
assertThat(result.inputFiles()).hasSize(2);
- assertThat(logRecorder.getAllAsString()).contains("Not enough content in 'src/sample2.xoo' to have CPD blocks");
- assertThat(logRecorder.getAllAsString()).contains("1 file had no CPD blocks");
+ assertThat(logTester.logs()).contains("Not enough content in 'src/sample2.xoo' to have CPD blocks, it will not be part of the duplication detection");
+ assertThat(logTester.logs()).contains("1 file had no CPD blocks");
}
File xooFile2 = new File(srcDir, "sample2.xoo");
FileUtils.write(xooFile2, duplicatedStuff);
- TaskResult result = tester.newTask()
+ AnalysisResult result = tester.newAnalysis()
.properties(builder
.put("sonar.sources", "src")
.put("sonar.cpd.xoo.minimumTokens", "10")
File xooFile1 = new File(srcDir, "sample1.xoo");
FileUtils.write(xooFile1, duplicatedStuff);
- TaskResult result = tester.newTask()
+ AnalysisResult result = tester.newAnalysis()
.properties(builder
.put("sonar.sources", "src")
.put("sonar.cpd.xoo.minimumTokens", "1")
File xooFile = new File(srcDir, "sample.xoo");
FileUtils.write(xooFile, content);
- TaskResult result = tester.newTask()
+ AnalysisResult result = tester.newAnalysis()
.properties(builder
.put("sonar.sources", "src")
.put("sonar.cpd.xoo.minimumTokens", "2")
import org.junit.rules.TemporaryFolder;
import org.sonar.api.batch.fs.InputDir;
import org.sonar.api.batch.fs.InputFile;
-import org.sonar.api.batch.fs.InputModule;
import org.sonar.api.batch.fs.internal.DefaultInputFile;
+import org.sonar.api.scanner.fs.InputProject;
import org.sonar.api.utils.MessageException;
import org.sonar.api.utils.System2;
+import org.sonar.scanner.mediumtest.AnalysisResult;
import org.sonar.scanner.mediumtest.LogOutputRecorder;
import org.sonar.scanner.mediumtest.ScannerMediumTester;
-import org.sonar.scanner.mediumtest.TaskResult;
import org.sonar.xoo.XooPlugin;
import org.sonar.xoo.global.GlobalSensor;
import org.sonar.xoo.rule.XooRulesDefinition;
File xooFile = new File(srcDir, "sample.xoo");
FileUtils.write(xooFile, "Sample xoo\ncontent");
- TaskResult result = tester.newTask()
+ AnalysisResult result = tester.newAnalysis()
.properties(builder
.put("sonar.sources", "src")
.build())
File xooFile = new File(srcDir, "sample.xoo");
FileUtils.write(xooFile, "Sample xoo\ncontent");
- tester.newTask()
+ tester.newAnalysis()
.properties(builder
.put("sonar.sources", "src")
.build())
File xooFile = new File(srcDir, "sample.xoo");
FileUtils.write(xooFile, "Sample xoo\ncontent");
- tester.newTask()
+ tester.newAnalysis()
.properties(builder
.put("sonar.sources", "src")
.build())
// the fail-fast mechanism in the scanner should have prevented reaching this point.
thrown.expect(IllegalStateException.class);
- tester.newTask()
+ tester.newAnalysis()
.properties(builder
.put("sonar.sources", "src")
.build())
File xooFile = new File(srcDir, "sample.xoo");
FileUtils.write(xooFile, "Sample xoo\ncontent");
- tester.newTask()
+ tester.newAnalysis()
.properties(builder
.put("sonar.sources", "src")
.build())
File javaFile = new File(srcDir, "sample.java");
FileUtils.write(javaFile, "Sample xoo\ncontent");
- tester.newTask()
+ tester.newAnalysis()
.properties(builder
.put("sonar.sources", "src")
.build())
File javaFile = new File(srcDir, "sample.java");
FileUtils.write(javaFile, "Sample xoo\ncontent");
- tester.newTask()
+ tester.newAnalysis()
.properties(builder
.put("sonar.sources", "src")
.build())
Path javaFile = mainDir.resolve("sample.java");
Files.write(javaFile, "Sample xoo\ncontent".getBytes(StandardCharsets.UTF_8));
- TaskResult result = tester.newTask()
+ AnalysisResult result = tester.newAnalysis()
.properties(builder
.put("sonar.sources", "src/main")
.put("sonar.tests", "src/test")
File xooFile = new File(srcDir, "sample.unknown");
FileUtils.write(xooFile, "Sample xoo\ncontent");
- TaskResult result = tester.newTask()
+ AnalysisResult result = tester.newAnalysis()
.properties(builder
.put("sonar.sources", "src")
.build())
new Random().nextBytes(b);
FileUtils.writeByteArrayToFile(unknownFile, b);
- tester.newTask()
+ tester.newAnalysis()
.properties(builder
.put("sonar.sources", "src")
.build())
File unknownFile = new File(srcDir, "myfile.binary");
FileUtils.write(unknownFile, "some text");
- tester.newTask()
+ tester.newAnalysis()
.properties(builder
.put("sonar.sources", "src")
.build())
File xooFile = new File(srcDir, "sample.xoo");
FileUtils.write(xooFile, "Sample xoo\ncontent");
- TaskResult result = tester.newTask()
+ AnalysisResult result = tester.newAnalysis()
.properties(builder
.put("sonar.sources", "src")
.build())
Path emptyDirRelative = Paths.get("src", "emptydir");
Files.createDirectories(emptyDirRelative);
- TaskResult result = tester.newTask()
+ AnalysisResult result = tester.newAnalysis()
.properties(builder
.put("sonar.sources", "src")
.build())
.execute();
DefaultInputFile unknownInputFile = (DefaultInputFile) result.inputFile("src/unknown/file.notanalyzed");
- InputModule root = result.root();
+ InputProject project = result.project();
assertThat(unknownInputFile.isPublished()).isFalse();
- assertThat(result.getReportComponent(root.key())).isNotNull();
+ assertThat(result.getReportComponent(project.key())).isNotNull();
// no issues on empty dir
InputDir emptyInputDir = result.inputDir(emptyDirRelative.toString());
File xooFile = new File(srcDir, "sample.xoo");
FileUtils.write(xooFile, "Sample xoo\ncontent");
- TaskResult result = tester.newTask()
+ AnalysisResult result = tester.newAnalysis()
.properties(builder
.put("sonar.sources", "src")
.build())
FileUtils.write(xooFile, StringUtils.repeat(StringUtils.repeat("a", 100) + "\n", ruleCount / 1000));
}
- TaskResult result = tester.newTask()
+ AnalysisResult result = tester.newAnalysis()
.properties(builder
.put("sonar.sources", "src")
.build())
File xooFile = new File(test, "sampleTest.xoo");
FileUtils.write(xooFile, "Sample test xoo\ncontent");
- TaskResult result = tester.newTask()
+ AnalysisResult result = tester.newAnalysis()
.properties(builder
.put("sonar.sources", "")
.put("sonar.tests", "test")
File xooTestFile2 = new File(testDir, "sampleTest.xoo");
FileUtils.write(xooTestFile2, "Sample test xoo 2\ncontent");
- TaskResult result = tester.newTask()
+ AnalysisResult result = tester.newAnalysis()
.properties(builder
.put("sonar.sources", "src,another.xoo")
.put("sonar.tests", "test,sampleTest2.xoo")
File xooTestFile2 = new File(testDir, "sampleTest.xoo");
FileUtils.write(xooTestFile2, "Sample test xoo 2\ncontent");
- TaskResult result = tester.newTask()
+ AnalysisResult result = tester.newAnalysis()
.properties(builder
.put("sonar.sources", "src,another.xoo")
.put("sonar.tests", "test,sampleTest2.xoo")
thrown.expect(MessageException.class);
thrown.expectMessage("File src/sample.xoo can't be indexed twice. Please check that inclusion/exclusion patterns produce disjoint sets for main and test files");
- tester.newTask()
+ tester.newAnalysis()
.properties(builder
.put("sonar.sources", "src,src/sample.xoo")
.build())
thrown.expect(MessageException.class);
thrown.expectMessage("File module1/src/sample.xoo can't be indexed twice. Please check that inclusion/exclusion patterns produce disjoint sets for main and test files");
- tester.newTask()
+ tester.newAnalysis()
.properties(builder
.put("sonar.sources", "module1/src")
.put("sonar.modules", "module1")
public void scanProjectWithSourceSymlink() {
assumeTrue(!System2.INSTANCE.isOsWindows());
File projectDir = new File("test-resources/mediumtest/xoo/sample-with-symlink");
- TaskResult result = tester
- .newScanTask(new File(projectDir, "sonar-project.properties"))
+ AnalysisResult result = tester
+ .newAnalysis(new File(projectDir, "sonar-project.properties"))
.execute();
assertThat(result.inputFiles()).hasSize(3);
// To please the quality gate, don't use assumeTrue, or the test will be reported as skipped
if (System2.INSTANCE.isOsWindows()) {
File projectDir = new File("test-resources/mediumtest/xoo/sample");
- TaskResult result = tester
- .newScanTask(new File(projectDir, "sonar-project.properties"))
+ AnalysisResult result = tester
+ .newAnalysis(new File(projectDir, "sonar-project.properties"))
.property("sonar.sources", "XOURCES")
.property("sonar.tests", "TESTX")
.execute();
File otherFile = new File(srcDir, "sample.other");
FileUtils.write(otherFile, "Sample other\ncontent");
- TaskResult result = tester.newTask()
+ AnalysisResult result = tester.newAnalysis()
.properties(builder
.put("sonar.sources", "src")
.build())
@Test
public void scanMultiModuleProject() {
File projectDir = new File("test-resources/mediumtest/xoo/multi-modules-sample");
- TaskResult result = tester
- .newScanTask(new File(projectDir, "sonar-project.properties"))
+ AnalysisResult result = tester
+ .newAnalysis(new File(projectDir, "sonar-project.properties"))
.execute();
assertThat(result.inputFiles()).hasSize(4);
@Test
public void global_sensor_should_see_project_relative_paths() {
File projectDir = new File("test-resources/mediumtest/xoo/multi-modules-sample");
- TaskResult result = tester
- .newScanTask(new File(projectDir, "sonar-project.properties"))
+ AnalysisResult result = tester
+ .newAnalysis(new File(projectDir, "sonar-project.properties"))
.property(GlobalSensor.ENABLE_PROP, "true")
.execute();
File xooTestFile2 = new File(baseDir, "sampleTest,2.xoo");
FileUtils.write(xooTestFile2, "Sample test xoo 2\ncontent");
- TaskResult result = tester.newTask()
+ AnalysisResult result = tester.newAnalysis()
.properties(builder
.put("sonar.sources", "src,\"another,2.xoo\"")
.put("sonar.tests", "\"test\",\"sampleTest,2.xoo\"")
File xooFile2 = new File(srcDir, "sample.xoo2");
FileUtils.write(xooFile2, "Sample xoo 2\ncontent");
- TaskResult result = tester.newTask()
+ AnalysisResult result = tester.newAnalysis()
.properties(builder
.put("sonar.sources", "src")
.build())
assertThat(result.inputFiles()).hasSize(2);
try {
- result = tester.newTask()
+ result = tester.newAnalysis()
.properties(builder
.put("sonar.lang.patterns.xoo2", "**/*.xoo")
.build())
}
// SONAR-9561
- result = tester.newTask()
+ result = tester.newAnalysis()
.properties(builder
.put("sonar.exclusions", "**/sample.xoo")
.build())
exception.expectMessage("No language plugins are installed");
tester
- .newScanTask(new File(projectDir, "sonar-project.properties"))
+ .newAnalysis(new File(projectDir, "sonar-project.properties"))
.execute();
}
import org.sonar.api.batch.bootstrap.ProjectBuilder;
import org.sonar.api.utils.MessageException;
import org.sonar.scanner.mediumtest.ScannerMediumTester;
-import org.sonar.scanner.mediumtest.TaskResult;
+import org.sonar.scanner.mediumtest.AnalysisResult;
import org.sonar.scanner.protocol.output.ScannerReport.Issue;
import org.sonar.xoo.XooPlugin;
import org.sonar.xoo.rule.XooRulesDefinition;
}
});
- tester.newTask()
+ tester.newAnalysis()
.properties(ImmutableMap.<String, String>builder()
.put("sonar.task", "scan")
.put("sonar.projectBaseDir", baseDir.getAbsolutePath())
public void testProjectBuilder() throws IOException {
File baseDir = prepareProject();
- TaskResult result = tester.newTask()
+ AnalysisResult result = tester.newAnalysis()
.properties(ImmutableMap.<String, String>builder()
.put("sonar.task", "scan")
.put("sonar.projectBaseDir", baseDir.getAbsolutePath())
exception.expect(MessageException.class);
exception.expectMessage("is not a valid branch name");
- tester.newTask()
+ tester.newAnalysis()
.properties(ImmutableMap.<String, String>builder()
.put("sonar.task", "scan")
.put("sonar.projectBaseDir", baseDir.getAbsolutePath())
public void testProjectBuilderWithBranch() throws IOException {
File baseDir = prepareProject();
- TaskResult result = tester.newTask()
+ AnalysisResult result = tester.newAnalysis()
.properties(ImmutableMap.<String, String>builder()
.put("sonar.task", "scan")
.put("sonar.projectBaseDir", baseDir.getAbsolutePath())
import org.sonar.api.batch.fs.InputFile;
import org.sonar.api.batch.sensor.highlighting.TypeOfText;
import org.sonar.scanner.mediumtest.ScannerMediumTester;
-import org.sonar.scanner.mediumtest.TaskResult;
+import org.sonar.scanner.mediumtest.AnalysisResult;
import org.sonar.xoo.XooPlugin;
import static org.assertj.core.api.Assertions.assertThat;
FileUtils.write(xooFile, "Sample xoo\ncontent plop");
FileUtils.write(xoohighlightingFile, "0:10:s\n11:18:k");
- TaskResult result = tester.newTask()
+ AnalysisResult result = tester.newAnalysis()
.properties(ImmutableMap.<String, String>builder()
.put("sonar.projectBaseDir", baseDir.getAbsolutePath())
.put("sonar.projectKey", "com.foo.project")
exception.expect(UnsupportedOperationException.class);
exception.expectMessage("Trying to save highlighting twice for the same file is not supported");
- tester.newTask()
+ tester.newAnalysis()
.properties(ImmutableMap.<String, String>builder()
.put("sonar.projectBaseDir", baseDir.getAbsolutePath())
.put("sonar.projectKey", "com.foo.project")
}
});
- tester.newTask()
+ tester.newAnalysis()
.properties(ImmutableMap.<String, String>builder()
.put("sonar.projectBaseDir", baseDir.getAbsolutePath())
.put("sonar.projectKey", "com.foo.project")
import org.junit.rules.TemporaryFolder;
import org.sonar.api.rule.RuleKey;
import org.sonar.scanner.mediumtest.ScannerMediumTester;
-import org.sonar.scanner.mediumtest.TaskResult;
+import org.sonar.scanner.mediumtest.AnalysisResult;
import org.sonar.scanner.protocol.output.ScannerReport.Issue;
import org.sonar.scanner.rule.LoadedActiveRule;
import org.sonar.xoo.XooPlugin;
File xooFile = new File(srcDir, "sample.xoo");
FileUtils.write(xooFile, "foo\nbar");
- TaskResult result = tester.newTask()
+ AnalysisResult result = tester.newAnalysis()
.properties(ImmutableMap.<String, String>builder()
.put("sonar.task", "scan")
.put("sonar.projectBaseDir", baseDir.getAbsolutePath())
import org.junit.rules.TemporaryFolder;
import org.sonar.api.utils.log.LogTester;
import org.sonar.scanner.mediumtest.ScannerMediumTester;
-import org.sonar.scanner.mediumtest.TaskResult;
+import org.sonar.scanner.mediumtest.AnalysisResult;
import org.sonar.scanner.protocol.Constants.Severity;
import org.sonar.scanner.protocol.output.ScannerReport;
import org.sonar.scanner.protocol.output.ScannerReport.ExternalIssue;
File tmpDir = temp.newFolder();
FileUtils.copyDirectory(projectDir, tmpDir);
- TaskResult result = tester
- .newScanTask(new File(tmpDir, "sonar-project.properties"))
+ AnalysisResult result = tester
+ .newAnalysis(new File(tmpDir, "sonar-project.properties"))
.property(OneExternalIssuePerLineSensor.ACTIVATE, "true")
.execute();
File tmpDir = temp.newFolder();
FileUtils.copyDirectory(projectDir, tmpDir);
- TaskResult result = tester
- .newScanTask(new File(tmpDir, "sonar-project.properties"))
+ AnalysisResult result = tester
+ .newAnalysis(new File(tmpDir, "sonar-project.properties"))
.property(OneExternalIssuePerLineSensor.ACTIVATE, "true")
.property(OneExternalIssuePerLineSensor.REGISTER_AD_HOC_RULE, "true")
.execute();
File tmpDir = temp.newFolder();
FileUtils.copyDirectory(projectDir, tmpDir);
- TaskResult result = tester
- .newScanTask(new File(tmpDir, "sonar-project.properties"))
+ AnalysisResult result = tester
+ .newAnalysis(new File(tmpDir, "sonar-project.properties"))
.property("sonar.externalIssuesReportPaths", "externalIssues.json")
.execute();
import org.junit.Test;
import org.junit.rules.TemporaryFolder;
import org.sonar.scanner.mediumtest.ScannerMediumTester;
-import org.sonar.scanner.mediumtest.TaskResult;
+import org.sonar.scanner.mediumtest.AnalysisResult;
import org.sonar.scanner.protocol.output.ScannerReport.ExternalIssue;
import org.sonar.scanner.protocol.output.ScannerReport.Issue;
import org.sonar.xoo.XooPlugin;
File tmpDir = temp.newFolder();
FileUtils.copyDirectory(projectDir, tmpDir);
- TaskResult result = tester
- .newScanTask(new File(tmpDir, "sonar-project.properties"))
+ AnalysisResult result = tester
+ .newAnalysis(new File(tmpDir, "sonar-project.properties"))
.execute();
List<Issue> issues = result.issuesFor(result.inputFile("xources/hello/HelloJava.xoo"));
File tmpDir = temp.newFolder();
FileUtils.copyDirectory(projectDir, tmpDir);
- TaskResult result = tester
- .newScanTask(new File(tmpDir, "sonar-project.properties"))
+ AnalysisResult result = tester
+ .newAnalysis(new File(tmpDir, "sonar-project.properties"))
.property(OneExternalIssuePerLineSensor.ACTIVATE, "true")
.execute();
File tmpDir = temp.newFolder();
FileUtils.copyDirectory(projectDir, tmpDir);
- TaskResult result = tester
- .newScanTask(new File(tmpDir, "sonar-project.properties"))
+ AnalysisResult result = tester
+ .newAnalysis(new File(tmpDir, "sonar-project.properties"))
.property("sonar.xoo.internalKey", "OneIssuePerLine.internal")
.execute();
File tmpDir = temp.newFolder();
FileUtils.copyDirectory(projectDir, tmpDir);
- TaskResult result = tester
- .newScanTask(new File(tmpDir, "sonar-project.properties"))
+ AnalysisResult result = tester
+ .newAnalysis(new File(tmpDir, "sonar-project.properties"))
.property("sonar.oneIssuePerLine.forceSeverity", "CRITICAL")
.execute();
File tmpDir = temp.newFolder();
FileUtils.copyDirectory(projectDir, tmpDir);
- TaskResult result = tester
- .newScanTask(new File(tmpDir, "sonar-project.properties"))
+ AnalysisResult result = tester
+ .newAnalysis(new File(tmpDir, "sonar-project.properties"))
.property("sonar.issue.ignore.allfile", "1")
.property("sonar.issue.ignore.allfile.1.fileRegexp", "object")
.execute();
File xooFile = new File(srcDir, "sample.xoo");
FileUtils.write(xooFile, "1\n2\n3\n4\n5\n6\n7\n8\n9\n10");
- TaskResult result = tester.newTask()
+ AnalysisResult result = tester.newAnalysis()
.properties(ImmutableMap.<String, String>builder()
.put("sonar.task", "scan")
.put("sonar.projectBaseDir", baseDir.getAbsolutePath())
@Test
public void testIssueFilter() throws Exception {
- File projectDir = new File(IssuesMediumTest.class.getResource("/mediumtest/xoo/sample").toURI());
+ File projectDir = new File("test-resources/mediumtest/xoo/sample");
File tmpDir = temp.newFolder();
FileUtils.copyDirectory(projectDir, tmpDir);
- TaskResult result = tester
- .newScanTask(new File(tmpDir, "sonar-project.properties"))
+ AnalysisResult result = tester
+ .newAnalysis(new File(tmpDir, "sonar-project.properties"))
.property("sonar.xoo.excludeAllIssuesOnOddLines", "true")
.execute();
import org.junit.Test;
import org.junit.rules.TemporaryFolder;
import org.sonar.scanner.mediumtest.ScannerMediumTester;
-import org.sonar.scanner.mediumtest.TaskResult;
+import org.sonar.scanner.mediumtest.AnalysisResult;
import org.sonar.xoo.XooPlugin;
import org.sonar.xoo.rule.XooRulesDefinition;
File xooFile2 = new File(srcDir, "sample2.xoo");
FileUtils.write(xooFile2, "Sample2 xoo\ncontent");
- TaskResult result = tester.newTask()
+ AnalysisResult result = tester.newAnalysis()
.properties(ImmutableMap.<String, String>builder()
.put("sonar.task", "scan")
.put("sonar.projectBaseDir", baseDir.getAbsolutePath())
.execute();
assertThat(result.issuesFor(result.inputDir("src"))).hasSize(0);
- assertThat(result.issuesFor(result.root())).hasSize(2);
+ assertThat(result.issuesFor(result.project())).hasSize(2);
}
@Test
File xooFile2 = new File(baseDir, "sample2.xoo");
FileUtils.write(xooFile2, "Sample2 xoo\ncontent");
- TaskResult result = tester.newTask()
+ AnalysisResult result = tester.newAnalysis()
.properties(ImmutableMap.<String, String>builder()
.put("sonar.task", "scan")
.put("sonar.projectBaseDir", baseDir.getAbsolutePath())
.execute();
assertThat(result.issuesFor(result.inputDir(""))).hasSize(0);
- assertThat(result.issuesFor(result.root())).hasSize(2);
+ assertThat(result.issuesFor(result.project())).hasSize(2);
}
}
import org.junit.Test;
import org.junit.rules.TemporaryFolder;
import org.sonar.scanner.mediumtest.ScannerMediumTester;
-import org.sonar.scanner.mediumtest.TaskResult;
+import org.sonar.scanner.mediumtest.AnalysisResult;
import org.sonar.xoo.XooPlugin;
import org.sonar.xoo.rule.XooRulesDefinition;
File xooFile1 = new File(srcDir, "sample1.xoo");
FileUtils.write(xooFile1, "Sample1 xoo\ncontent");
- TaskResult result = tester.newTask()
+ AnalysisResult result = tester.newAnalysis()
.properties(ImmutableMap.<String, String>builder()
.put("sonar.task", "scan")
.put("sonar.projectBaseDir", baseDir.getAbsolutePath())
import org.junit.Test;
import org.junit.rules.TemporaryFolder;
import org.sonar.scanner.mediumtest.ScannerMediumTester;
-import org.sonar.scanner.mediumtest.TaskResult;
+import org.sonar.scanner.mediumtest.AnalysisResult;
import org.sonar.scanner.protocol.output.ScannerReport.Flow;
import org.sonar.scanner.protocol.output.ScannerReport.Issue;
import org.sonar.scanner.protocol.output.ScannerReport.IssueLocation;
.addDefaultQProfile("xoo", "Sonar Way")
.addActiveRule("xoo", "MultilineIssue", null, "Multinile Issue", "MAJOR", null, "xoo");
- private TaskResult result;
+ private AnalysisResult result;
@Before
public void prepare() throws Exception {
FileUtils.copyDirectory(projectDir, tmpDir);
result = tester
- .newScanTask(new File(tmpDir, "sonar-project.properties"))
+ .newAnalysis(new File(tmpDir, "sonar-project.properties"))
.execute();
}
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.TaskResult;
+import org.sonar.scanner.mediumtest.AnalysisResult;
import org.sonar.xoo.XooPlugin;
import org.sonar.xoo.rule.XooRulesDefinition;
public void testIssueTrackingWithIssueOnEmptyFile() throws Exception {
File projectDir = copyProject("test-resources/mediumtest/xoo/sample-with-empty-file");
- TaskResult result = tester
- .newScanTask(new File(projectDir, "sonar-project.properties"))
+ AnalysisResult result = tester
+ .newAnalysis(new File(projectDir, "sonar-project.properties"))
.property("sonar.xoo.internalKey", "my/internal/key")
.execute();
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.TaskResult;
+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;
public void testIssueTracking() throws Exception {
File projectDir = copyProject("test-resources/mediumtest/xoo/sample");
- TaskResult result = tester
- .newScanTask(new File(projectDir, "sonar-project.properties"))
+ AnalysisResult result = tester
+ .newAnalysis(new File(projectDir, "sonar-project.properties"))
.execute();
int newIssues = 0;
File projectDir = copyProject("test-resources/mediumtest/xoo/sample");
tester
- .newScanTask(new File(projectDir, "sonar-project.properties"))
+ .newAnalysis(new File(projectDir, "sonar-project.properties"))
.property("sonar.xoo.enablePostJob", "true")
.execute();
FileUtils.write(xooFile, "Sample xoo\ncontent plop");
FileUtils.write(xoohighlightingFile, "0:10:s\n11:18:k");
- TaskResult result = tester.newTask()
+ AnalysisResult result = tester.newAnalysis()
.properties(ImmutableMap.<String, String>builder()
.put("sonar.projectBaseDir", baseDir.getAbsolutePath())
.put("sonar.projectKey", "com.foo.project")
import org.sonar.api.CoreProperties;
import org.sonar.api.utils.log.LogTester;
import org.sonar.scanner.mediumtest.ScannerMediumTester;
-import org.sonar.scanner.mediumtest.TaskResult;
+import org.sonar.scanner.mediumtest.AnalysisResult;
import org.sonar.xoo.XooPlugin;
import org.sonar.xoo.rule.XooRulesDefinition;
public void testIssueTrackingWithIssueOnEmptyFile() throws Exception {
File projectDir = copyProject("test-resources/mediumtest/xoo/sample");
- TaskResult result = tester
- .newScanTask(new File(projectDir, "sonar-project.properties"))
+ AnalysisResult result = tester
+ .newAnalysis(new File(projectDir, "sonar-project.properties"))
.execute();
assertThat(result.trackedIssues()).hasSize(14);
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.ScannerMediumTester.TaskBuilder;
-import org.sonar.scanner.mediumtest.TaskResult;
+import org.sonar.scanner.mediumtest.ScannerMediumTester.AnalysisBuilder;
+import org.sonar.scanner.mediumtest.AnalysisResult;
import org.sonar.scanner.protocol.Constants.Severity;
import org.sonar.scanner.protocol.input.ScannerInput.ServerIssue;
import org.sonar.scanner.repository.FileData;
public void testScanOnlyChangedFiles() throws Exception {
File projectDir = copyProject("test-resources/mediumtest/xoo/sample");
- TaskBuilder taskBuilder = tester
- .newScanTask(new File(projectDir, "sonar-project.properties"))
+ AnalysisBuilder analysisBuilder = tester
+ .newAnalysis(new File(projectDir, "sonar-project.properties"))
.property("sonar.report.export.path", "report.json");
if (branch) {
- taskBuilder.property("sonar.branch", "branch");
+ analysisBuilder.property("sonar.branch", "branch");
} else {
- taskBuilder.property("sonar.projectKey", projectKey);
+ analysisBuilder.property("sonar.projectKey", projectKey);
}
- TaskResult result = taskBuilder.execute();
+ AnalysisResult result = analysisBuilder.execute();
/*
* We have:
* 6 new issues per line (open) in helloscala.xoo
public void testScanAll() throws Exception {
File projectDir = copyProject("test-resources/mediumtest/xoo/sample");
- TaskBuilder taskBuilder = tester
- .newScanTask(new File(projectDir, "sonar-project.properties"))
+ AnalysisBuilder analysisBuilder = tester
+ .newAnalysis(new File(projectDir, "sonar-project.properties"))
.property("sonar.scanAllFiles", "true");
if (branch) {
- taskBuilder.property("sonar.branch", "branch");
+ analysisBuilder.property("sonar.branch", "branch");
} else {
- taskBuilder.property("sonar.projectKey", projectKey);
+ analysisBuilder.property("sonar.projectKey", projectKey);
}
- TaskResult result = taskBuilder.execute();
+ AnalysisResult result = analysisBuilder.execute();
assertNumberIssues(result, 16, 2, 0);
assertNumberIssuesOnFile(result, "HelloJava.xoo", 8);
}
- private static void assertNumberIssuesOnFile(TaskResult result, final String fileNameEndsWith, int issues) {
+ 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) {
});
}
- private static void assertNumberIssues(TaskResult result, int expectedNew, int expectedOpen, int expectedResolved) {
+ private static void assertNumberIssues(AnalysisResult result, int expectedNew, int expectedOpen, int expectedResolved) {
int newIssues = 0;
int openIssues = 0;
int resolvedIssue = 0;
thrown.expectMessage("Error loading settings");
thrown.expectCause(CoreMatchers.nullValue(Throwable.class));
- batch.start();
+ batch.execute();
}
@Test
}
});
- batch.start();
+ batch.execute();
}
@Test
setUp(true);
thrown.expect(IllegalStateException.class);
thrown.expectMessage("Unable to load component class");
- batch.start();
+ batch.execute();
}
private static class ErrorSettingsLoader implements SettingsLoader {
File xooFile = new File(srcDir, "sample.xoo");
FileUtils.write(xooFile, "Sample xoo\ncontent");
- tester.newTask()
+ tester.newAnalysis()
.properties(builder
.put("sonar.sources", "src")
.put("sonar.verbose", "true")
File xooFile = new File(srcDir, "sample.xoo");
FileUtils.write(xooFile, "Sample xoo\ncontent");
- tester.newTask()
+ tester.newAnalysis()
.properties(builder
.put("sonar.sources", "src")
.build())
File xooFile = new File(srcDir, "sample.xoo");
FileUtils.write(xooFile, "Sample xoo\ncontent");
- tester.newTask()
+ tester.newAnalysis()
.properties(builder
.put("sonar.sources", "src")
.build())
FileUtils.write(xooFileMeasure, "foo:bar");
try {
- tester.newTask()
+ tester.newAnalysis()
.properties(builder
.put("sonar.sources", "src")
.build())
import org.sonar.api.utils.log.LogTester;
import org.sonar.api.utils.log.LoggerLevel;
import org.sonar.scanner.mediumtest.ScannerMediumTester;
-import org.sonar.scanner.mediumtest.TaskResult;
+import org.sonar.scanner.mediumtest.AnalysisResult;
import org.sonar.scanner.protocol.output.ScannerReport.Measure;
import org.sonar.xoo.XooPlugin;
File measures = new File(srcDir, "sample.xoo.measures");
FileUtils.write(measures, "lines_to_cover:2");
- TaskResult result = tester.newTask()
+ AnalysisResult result = tester.newAnalysis()
.properties(ImmutableMap.<String, String>builder()
.put("sonar.task", "scan")
.put("sonar.projectBaseDir", baseDir.getAbsolutePath())
assertThat(allMeasures.get("com.foo.project:src/sample.xoo")).extracting("metricKey", "intValue.value")
.containsOnly(tuple("lines_to_cover", 2));
- result = tester.newTask()
+ result = tester.newAnalysis()
.properties(ImmutableMap.<String, String>builder()
.put("sonar.task", "scan")
.put("sonar.projectBaseDir", baseDir.getAbsolutePath())
File measures = new File(srcDir, "sample.xoo.measures");
FileUtils.write(measures, "it_lines_to_cover:2");
- TaskResult result = tester.newTask()
+ AnalysisResult result = tester.newAnalysis()
.properties(ImmutableMap.<String, String>builder()
.put("sonar.task", "scan")
.put("sonar.projectBaseDir", baseDir.getAbsolutePath())
FileUtils.write(measures, "new_lines:2");
try {
- tester.newTask()
+ tester.newAnalysis()
.properties(ImmutableMap.<String, String>builder()
.put("sonar.task", "scan")
.put("sonar.projectBaseDir", baseDir.getAbsolutePath())
File lineMeasures = new File(srcDir, "sample.xoo.linemeasures");
FileUtils.write(lineMeasures, "ncloc_data:1=1;2=0;4=1");
- TaskResult result = tester.newTask()
+ AnalysisResult result = tester.newAnalysis()
.properties(ImmutableMap.<String, String>builder()
.put("sonar.task", "scan")
.put("sonar.projectBaseDir", baseDir.getAbsolutePath())
File projectMeasures = new File(baseDir, "module.measures");
FileUtils.write(projectMeasures, "tests:10");
- TaskResult result = tester.newTask()
+ AnalysisResult result = tester.newAnalysis()
.properties(ImmutableMap.<String, String>builder()
.put("sonar.task", "scan")
.put("sonar.projectBaseDir", baseDir.getAbsolutePath())
import org.junit.rules.TemporaryFolder;
import org.sonar.api.utils.log.LogTester;
import org.sonar.scanner.mediumtest.ScannerMediumTester;
-import org.sonar.scanner.mediumtest.ScannerMediumTester.TaskBuilder;
+import org.sonar.scanner.mediumtest.ScannerMediumTester.AnalysisBuilder;
import org.sonar.scanner.protocol.output.ScannerReport;
import org.sonar.scanner.protocol.output.ScannerReport.Changesets.Changeset;
import org.sonar.scanner.protocol.output.ScannerReport.Component;
public void testScmMeasure() throws IOException, URISyntaxException {
File baseDir = prepareProject();
- tester.newTask()
+ tester.newAnalysis()
.properties(ImmutableMap.<String, String>builder()
.put("sonar.task", "scan")
.put("sonar.projectBaseDir", baseDir.getAbsolutePath())
// Clear file content
FileUtils.write(new File(baseDir, "src/sample.xoo"), "");
- tester.newTask()
+ tester.newAnalysis()
.properties(ImmutableMap.<String, String>builder()
.put("sonar.task", "scan")
.put("sonar.projectBaseDir", baseDir.getAbsolutePath())
File xooFileWithoutBlame = new File(baseDir, "src/sample_no_blame.xoo");
FileUtils.write(xooFileWithoutBlame, "Sample xoo\ncontent\n3\n4\n5");
- tester.newTask()
+ tester.newAnalysis()
.properties(ImmutableMap.<String, String>builder()
.put("sonar.task", "scan")
.put("sonar.projectBaseDir", baseDir.getAbsolutePath())
"1,foo,2013-01-04\n" +
"1,bar,2013-01-04\n");
- tester.newTask()
+ tester.newAnalysis()
.properties(ImmutableMap.<String, String>builder()
.put("sonar.task", "scan")
.put("sonar.projectBaseDir", baseDir.getAbsolutePath())
"1,foo,2013-01-04\n" +
"1,bar,2013-01-04\n");
- TaskBuilder taskBuilder = tester.newTask()
+ AnalysisBuilder analysisBuilder = tester.newAnalysis()
.properties(ImmutableMap.<String, String>builder()
.put("sonar.task", "scan")
.put("sonar.projectBaseDir", baseDir.getAbsolutePath())
.put("sonar.scm.forceReloadAll", "true")
.build());
- taskBuilder.execute();
+ analysisBuilder.execute();
ScannerReport.Changesets file1Scm = getChangesets(baseDir, "src/sample.xoo");
assertThat(file1Scm).isNotNull();
File baseDir = prepareProject();
- tester.newTask()
+ tester.newAnalysis()
.properties(ImmutableMap.<String, String>builder()
.put("sonar.task", "scan")
.put("sonar.projectBaseDir", baseDir.getAbsolutePath())
File baseDir = prepareProject();
new File(baseDir, ".xoo").createNewFile();
- tester.newTask()
+ tester.newAnalysis()
.properties(ImmutableMap.<String, String>builder()
.put("sonar.task", "scan")
.put("sonar.projectBaseDir", baseDir.getAbsolutePath())
File baseDir = prepareProject();
- tester.newTask()
+ tester.newAnalysis()
.properties(ImmutableMap.<String, String>builder()
.put("sonar.task", "scan")
.put("sonar.projectBaseDir", baseDir.getAbsolutePath())
import org.junit.rules.TemporaryFolder;
import org.sonar.api.batch.fs.InputFile;
import org.sonar.scanner.mediumtest.ScannerMediumTester;
-import org.sonar.scanner.mediumtest.TaskResult;
+import org.sonar.scanner.mediumtest.AnalysisResult;
import org.sonar.scanner.protocol.output.ScannerReport;
import org.sonar.xoo.XooPlugin;
// Highlight xoo symbol
FileUtils.write(xooSymbolFile, "7:10,27");
- TaskResult result = tester.newTask()
+ AnalysisResult result = tester.newAnalysis()
.properties(ImmutableMap.<String, String>builder()
.put("sonar.task", "scan")
.put("sonar.projectBaseDir", baseDir.getAbsolutePath())
// Highlight xoo symbol
FileUtils.write(xooSymbolFile, "7:10,27:32");
- TaskResult result = tester.newTask()
+ AnalysisResult result = tester.newAnalysis()
.properties(ImmutableMap.<String, String>builder()
.put("sonar.task", "scan")
.put("sonar.projectBaseDir", baseDir.getAbsolutePath())
@Test
public void listTasksIncludingBroken() throws Exception {
- tester.newTask()
+ tester.newAnalysis()
.properties(ImmutableMap.<String, String>builder()
.put("sonar.task", "list").build())
.execute();
thrown.expectMessage(
"Unable to load component class org.sonar.scanner.mediumtest.tasks.TasksMediumTest$BrokenTask");
- tester.newTask()
+ tester.newAnalysis()
.properties(ImmutableMap.<String, String>builder()
.put("sonar.task", "broken").build())
.execute();
@Test(expected = MessageException.class)
public void unsupportedTask() throws Exception {
- tester.newTask()
+ tester.newAnalysis()
.properties(ImmutableMap.<String, String>builder()
.put("sonar.task", "foo").build())
.execute();
import org.junit.rules.TemporaryFolder;
import org.sonar.api.batch.fs.InputFile;
import org.sonar.scanner.mediumtest.ScannerMediumTester;
-import org.sonar.scanner.mediumtest.TaskResult;
+import org.sonar.scanner.mediumtest.AnalysisResult;
import org.sonar.xoo.XooPlugin;
import static org.assertj.core.api.Assertions.assertThat;
FileUtils.write(xooCoveragePerTestFile, "some test;src/sample.xoo,10,11;src/sample2.xoo,1,2\n" +
"another test;src/sample.xoo,10,20\n", StandardCharsets.UTF_8);
- TaskResult result = runTask(baseDir);
+ AnalysisResult result = runTask(baseDir);
InputFile file = result.inputFile("test/sampleTest.xoo");
org.sonar.scanner.protocol.output.ScannerReport.CoverageDetail someTest = result.coveragePerTestFor(file, "some test");
assertThat(anotherTest.getCoveredFile(0).getCoveredLineList()).containsExactly(10, 20);
}
- private TaskResult runTask(File baseDir) {
- return tester.newTask()
+ private AnalysisResult runTask(File baseDir) {
+ return tester.newAnalysis()
.properties(ImmutableMap.<String, String>builder()
.put("sonar.task", "scan")
.put("sonar.projectBaseDir", baseDir.getAbsolutePath())
import org.sonar.api.batch.fs.InputFile;
import org.sonar.api.measures.CoreMetrics;
import org.sonar.scanner.mediumtest.ScannerMediumTester;
-import org.sonar.scanner.mediumtest.TaskResult;
+import org.sonar.scanner.mediumtest.AnalysisResult;
import org.sonar.scanner.protocol.output.ScannerReport;
import org.sonar.scanner.protocol.output.ScannerReport.Test.TestStatus;
import org.sonar.xoo.XooPlugin;
"error:2:Error:The stack:ERROR:UNIT\n" +
"success:4:::OK:INTEGRATION", StandardCharsets.UTF_8);
- TaskResult result = tester
- .newTask()
+ AnalysisResult result = tester
+ .newAnalysis()
.properties(ImmutableMap.<String, String>builder()
.put("sonar.task", "scan")
.put("sonar.projectBaseDir", baseDir.getAbsolutePath())
File projectDir = new File("test-resources/mediumtest/xoo/sample-generic-test-exec");
- TaskResult result = tester
+ AnalysisResult result = tester
.setLogOutput((msg, level) -> logs.add(msg))
- .newScanTask(new File(projectDir, "sonar-project.properties"))
+ .newAnalysis(new File(projectDir, "sonar-project.properties"))
.property("sonar.testExecutionReportPaths", "unittest.xml")
.execute();
File projectDir = new File("test-resources/mediumtest/xoo/sample-generic-test-exec");
- TaskResult result = tester
+ AnalysisResult result = tester
.setLogOutput((msg, level) -> logs.add(msg))
- .newScanTask(new File(projectDir, "sonar-project.properties"))
+ .newAnalysis(new File(projectDir, "sonar-project.properties"))
.property("sonar.testExecutionReportPaths", "unittest.xml,unittest2.xml")
.execute();
import org.junit.rules.TemporaryFolder;
import org.sonar.api.batch.fs.InputFile;
import org.sonar.scanner.mediumtest.ScannerMediumTester;
-import org.sonar.scanner.mediumtest.TaskResult;
+import org.sonar.scanner.mediumtest.AnalysisResult;
import org.sonar.scanner.protocol.output.ScannerReport.Test.TestStatus;
import org.sonar.xoo.XooPlugin;
"error:2:Error:The stack:ERROR:UNIT\n" +
"success:4:::OK:INTEGRATION");
- TaskResult result = tester.newTask()
+ AnalysisResult result = tester.newAnalysis()
.properties(ImmutableMap.<String, String>builder()
.put("sonar.task", "scan")
.put("sonar.projectBaseDir", baseDir.getAbsolutePath())
import org.junit.rules.TemporaryFolder;
import org.sonar.api.batch.fs.internal.DefaultInputFile;
import org.sonar.api.batch.fs.internal.TestInputFileBuilder;
-import org.sonar.api.config.PropertyDefinitions;
-import org.sonar.api.config.internal.MapSettings;
-import org.sonar.core.config.ExclusionProperties;
+import org.sonar.scanner.scan.ModuleConfiguration;
import static org.assertj.core.api.Assertions.assertThat;
+import static org.mockito.Mockito.mock;
+import static org.mockito.Mockito.when;
public class ModuleCoverageExclusionsTest {
@Rule
public TemporaryFolder temp = new TemporaryFolder();
- private MapSettings settings;
private ModuleCoverageExclusions coverageExclusions;
private File baseDir;
@Before
public void prepare() throws Exception {
- settings = new MapSettings(new PropertyDefinitions(ExclusionProperties.all()));
baseDir = temp.newFolder();
}
DefaultInputFile file = TestInputFileBuilder.create("foo", new File(baseDir, "moduleA"), new File(baseDir, "moduleA/src/org/polop/File.php"))
.setProjectBaseDir(baseDir.toPath())
.build();
- settings.setProperty("sonar.coverage.exclusions", "src/org/polop/*");
- coverageExclusions = new ModuleCoverageExclusions(settings.asConfig());
+ coverageExclusions = new ModuleCoverageExclusions(mockConfig("src/org/polop/*"));
assertThat(coverageExclusions.isExcluded(file)).isTrue();
}
DefaultInputFile file = TestInputFileBuilder.create("foo", new File(baseDir, "moduleA"), new File(baseDir, "moduleA/src/org/polop/File.php"))
.setProjectBaseDir(baseDir.toPath())
.build();
- settings.setProperty("sonar.coverage.exclusions", "src/org/other/*");
- coverageExclusions = new ModuleCoverageExclusions(settings.asConfig());
+ coverageExclusions = new ModuleCoverageExclusions(mockConfig("src/org/other/*"));
assertThat(coverageExclusions.isExcluded(file)).isFalse();
}
+
+ private ModuleConfiguration mockConfig(String... values) {
+ ModuleConfiguration config = mock(ModuleConfiguration.class);
+ when(config.getStringArray("sonar.coverage.exclusions")).thenReturn(values);
+ return config;
+ }
}
import org.junit.rules.TemporaryFolder;
import org.sonar.api.batch.fs.internal.DefaultInputFile;
import org.sonar.api.batch.fs.internal.TestInputFileBuilder;
-import org.sonar.api.config.PropertyDefinitions;
-import org.sonar.api.config.internal.MapSettings;
-import org.sonar.core.config.ExclusionProperties;
+import org.sonar.scanner.scan.ProjectConfiguration;
import static org.assertj.core.api.Assertions.assertThat;
+import static org.mockito.Mockito.mock;
+import static org.mockito.Mockito.when;
public class ProjectCoverageExclusionsTest {
@Rule
public TemporaryFolder temp = new TemporaryFolder();
- private MapSettings settings;
private ProjectCoverageExclusions coverageExclusions;
private File baseDir;
@Before
public void prepare() throws Exception {
- settings = new MapSettings(new PropertyDefinitions(ExclusionProperties.all()));
baseDir = temp.newFolder();
}
DefaultInputFile file = TestInputFileBuilder.create("foo", new File(baseDir, "moduleA"), new File(baseDir, "moduleA/src/org/polop/File.php"))
.setProjectBaseDir(baseDir.toPath())
.build();
- settings.setProperty("sonar.coverage.exclusions", "moduleA/src/org/polop/*");
- coverageExclusions = new ProjectCoverageExclusions(settings.asConfig());
+ coverageExclusions = new ProjectCoverageExclusions(mockConfig("moduleA/src/org/polop/*"));
assertThat(coverageExclusions.isExcluded(file)).isTrue();
}
DefaultInputFile file = TestInputFileBuilder.create("foo", new File(baseDir, "moduleA"), new File(baseDir, "moduleA/src/org/polop/File.php"))
.setProjectBaseDir(baseDir.toPath())
.build();
- settings.setProperty("sonar.coverage.exclusions", "moduleA/src/org/other/*");
- coverageExclusions = new ProjectCoverageExclusions(settings.asConfig());
+ coverageExclusions = new ProjectCoverageExclusions(mockConfig("moduleA/src/org/other/*"));
assertThat(coverageExclusions.isExcluded(file)).isFalse();
}
+
+ private ProjectConfiguration mockConfig(String... values) {
+ ProjectConfiguration config = mock(ProjectConfiguration.class);
+ when(config.getStringArray("sonar.coverage.exclusions")).thenReturn(values);
+ return config;
+ }
+
}
ScannerWsClient client = mock(ScannerWsClient.class);
when(client.baseUrl()).thenReturn("http://foo.com");
- DefaultServer metadata = new DefaultServer(settings, client, SonarRuntimeImpl.forSonarQube(Version.parse("2.2"), SonarQubeSide.SCANNER));
+ DefaultServer metadata = new DefaultServer(((MapSettings) settings).asConfig(), client, SonarRuntimeImpl.forSonarQube(Version.parse("2.2"), SonarQubeSide.SCANNER));
assertThat(metadata.getId()).isEqualTo("123");
assertThat(metadata.getVersion()).isEqualTo("2.2");
Settings settings = new MapSettings();
ScannerWsClient client = mock(ScannerWsClient.class);
when(client.baseUrl()).thenReturn("http://foo.com/");
- DefaultServer metadata = new DefaultServer(settings, client, null);
+ DefaultServer metadata = new DefaultServer(((MapSettings) settings).asConfig(), client, null);
settings.setProperty(CoreProperties.SERVER_BASE_URL, "http://server.com/");
assertThat(metadata.getPublicRootUrl()).isEqualTo("http://server.com");
Settings settings = new MapSettings();
settings.setProperty(CoreProperties.SERVER_STARTTIME, "invalid");
ScannerWsClient client = mock(ScannerWsClient.class);
- DefaultServer metadata = new DefaultServer(settings, client, null);
+ DefaultServer metadata = new DefaultServer(((MapSettings) settings).asConfig(), client, null);
metadata.getStartedAt();
}
}
import org.junit.Test;
import org.junit.rules.TemporaryFolder;
import org.sonar.api.batch.AnalysisMode;
-import org.sonar.api.batch.fs.internal.DefaultInputModule;
+import org.sonar.api.batch.fs.internal.DefaultInputProject;
import org.sonar.api.batch.fs.internal.TestInputFileBuilder;
import org.sonar.api.batch.postjob.issue.PostJobIssue;
import org.sonar.api.batch.rule.Severity;
@Before
public void setUp() throws IOException {
issueCache = mock(IssueCache.class);
- DefaultInputModule rootModule = TestInputFileBuilder.newDefaultInputModule("foo", temp.newFolder());
- componentStore = new InputComponentStore(rootModule, mock(BranchConfiguration.class));
+ DefaultInputProject project = TestInputFileBuilder.newDefaultInputProject("foo", temp.newFolder());
+ componentStore = new InputComponentStore(project, mock(BranchConfiguration.class));
settings = new MapSettings();
analysisMode = mock(AnalysisMode.class);
context = new DefaultPostJobContext(settings.asConfig(), settings, issueCache, componentStore, analysisMode);
import org.sonar.api.utils.log.LogTester;
import org.sonar.api.utils.log.LoggerLevel;
import org.sonar.core.platform.PluginInfo;
-import org.sonar.scanner.bootstrap.GlobalConfiguration;
+import org.sonar.scanner.bootstrap.GlobalServerSettings;
import org.sonar.scanner.bootstrap.ScannerPluginRepository;
import org.sonar.scanner.protocol.output.ScannerReportWriter;
import org.sonar.scanner.repository.ProjectRepositories;
private AnalysisMode analysisMode = mock(AnalysisMode.class);
private System2 system2;
private ProjectRepositories projectRepos;
- private GlobalConfiguration globalSettings;
+ private GlobalServerSettings globalServerSettings;
private InputModuleHierarchy hierarchy;
@Before
system2 = mock(System2.class);
when(system2.properties()).thenReturn(new Properties());
projectRepos = mock(ProjectRepositories.class);
- globalSettings = mock(GlobalConfiguration.class);
+ globalServerSettings = mock(GlobalServerSettings.class);
hierarchy = mock(InputModuleHierarchy.class);
- publisher = new AnalysisContextReportPublisher(analysisMode, pluginRepo, system2, projectRepos, globalSettings, hierarchy);
+ publisher = new AnalysisContextReportPublisher(analysisMode, pluginRepo, system2, projectRepos, globalServerSettings, hierarchy);
}
@Test
public void dumpServerSideGlobalProps() throws Exception {
logTester.setLevel(LoggerLevel.DEBUG);
ScannerReportWriter writer = new ScannerReportWriter(temp.newFolder());
- when(globalSettings.getServerSideSettings()).thenReturn(ImmutableMap.of(COM_FOO, "bar", SONAR_SKIP, "true"));
+ when(globalServerSettings.properties()).thenReturn(ImmutableMap.of(COM_FOO, "bar", SONAR_SKIP, "true"));
publisher.init(writer);
@Test
public void shouldNotDumpSensitiveGlobalProperties() throws Exception {
ScannerReportWriter writer = new ScannerReportWriter(temp.newFolder());
- when(globalSettings.getServerSideSettings()).thenReturn(ImmutableMap.of("sonar.login", "my_token", "sonar.password", "azerty", "sonar.cpp.license.secured", "AZERTY"));
+ when(globalServerSettings.properties()).thenReturn(ImmutableMap.of("sonar.login", "my_token", "sonar.password", "azerty", "sonar.cpp.license.secured", "AZERTY"));
publisher.init(writer);
import org.junit.Test;
import org.junit.rules.TemporaryFolder;
import org.sonar.api.batch.fs.internal.DefaultInputFile;
-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.fs.internal.TestInputFileBuilder;
import org.sonar.api.batch.scm.ScmProvider;
private BranchConfiguration branchConfiguration = mock(BranchConfiguration.class);
private ScannerReportWriter writer;
private ScmProvider provider = mock(ScmProvider.class);
+ private DefaultInputProject project = mock(DefaultInputProject.class);
@Rule
public TemporaryFolder temp = new TemporaryFolder();
- private ChangedLinesPublisher publisher = new ChangedLinesPublisher(scmConfiguration, inputModuleHierarchy, inputComponentStore, branchConfiguration);
+ private ChangedLinesPublisher publisher = new ChangedLinesPublisher(scmConfiguration, project, inputComponentStore, branchConfiguration);
@Before
public void setUp() {
when(scmConfiguration.isDisabled()).thenReturn(false);
when(scmConfiguration.provider()).thenReturn(provider);
when(branchConfiguration.targetScmBranch()).thenReturn(TARGET_BRANCH);
- DefaultInputModule root = mock(DefaultInputModule.class);
- when(root.getBaseDir()).thenReturn(BASE_DIR);
- when(inputModuleHierarchy.root()).thenReturn(root);
+ when(project.getBaseDir()).thenReturn(BASE_DIR);
}
@Test
}
private void assertPublished(DefaultInputFile file, Set<Integer> lines) {
- assertThat(new File(temp.getRoot(), "changed-lines-" + file.batchId() + ".pb")).exists();
+ assertThat(new File(temp.getRoot(), "changed-lines-" + file.scannerId() + ".pb")).exists();
ScannerReportReader reader = new ScannerReportReader(temp.getRoot());
- assertThat(reader.readComponentChangedLines(file.batchId()).getLineList()).containsExactlyElementsOf(lines);
+ assertThat(reader.readComponentChangedLines(file.scannerId()).getLineList()).containsExactlyElementsOf(lines);
}
private void assertNotPublished(DefaultInputFile file) {
- assertThat(new File(temp.getRoot(), "changed-lines-" + file.batchId() + ".pb")).doesNotExist();
+ assertThat(new File(temp.getRoot(), "changed-lines-" + file.scannerId() + ".pb")).doesNotExist();
}
private void assertNotPublished() {
Map<DefaultInputModule, DefaultInputModule> modules = new HashMap<>();
modules.put(module2, module1);
modules.put(module1, root);
- moduleHierarchy = new DefaultInputModuleHierarchy(modules);
+ moduleHierarchy = new DefaultInputModuleHierarchy(root, modules);
tree.index(module2, module1);
tree.index(module1, root);
ComponentsPublisher publisher = new ComponentsPublisher(moduleHierarchy, tree, branchConfiguration);
DefaultInputFile mod1_mod2_dir_file = newDefaultInputFile(root.getBaseDir(), mod1_mod2, "dir/Foo.java");
tree.index(mod1_mod2_dir_file, mod1_mod2_dir);
- moduleHierarchy = new DefaultInputModuleHierarchy(parents);
+ moduleHierarchy = new DefaultInputModuleHierarchy(root, parents);
ComponentsPublisher publisher = new ComponentsPublisher(moduleHierarchy, tree, branchConfiguration);
publisher.publish(writer);
ScannerReportReader reader = new ScannerReportReader(outputDir);
// project root
- assertThat(reader.readComponent(root.batchId()).getPath()).isEmpty();
- assertThat(reader.readComponent(root.batchId()).getProjectRelativePath()).isEmpty();
+ assertThat(reader.readComponent(root.scannerId()).getPath()).isEmpty();
+ assertThat(reader.readComponent(root.scannerId()).getProjectRelativePath()).isEmpty();
// file in root
- assertThat(reader.readComponent(file.batchId()).getPath()).isEqualTo("Foo.java");
- assertThat(reader.readComponent(file.batchId()).getProjectRelativePath()).isEqualTo("Foo.java");
+ assertThat(reader.readComponent(file.scannerId()).getPath()).isEqualTo("Foo.java");
+ assertThat(reader.readComponent(file.scannerId()).getProjectRelativePath()).isEqualTo("Foo.java");
// dir in root
- assertThat(reader.readComponent(dir1.batchId()).getPath()).isEqualTo("dir1");
- assertThat(reader.readComponent(dir1.batchId()).getProjectRelativePath()).isEqualTo("dir1");
+ assertThat(reader.readComponent(dir1.scannerId()).getPath()).isEqualTo("dir1");
+ assertThat(reader.readComponent(dir1.scannerId()).getProjectRelativePath()).isEqualTo("dir1");
// file in dir in root
- assertThat(reader.readComponent(dir1_file.batchId()).getPath()).isEqualTo("dir1/Foo.java");
- assertThat(reader.readComponent(dir1_file.batchId()).getProjectRelativePath()).isEqualTo("dir1/Foo.java");
+ assertThat(reader.readComponent(dir1_file.scannerId()).getPath()).isEqualTo("dir1/Foo.java");
+ assertThat(reader.readComponent(dir1_file.scannerId()).getProjectRelativePath()).isEqualTo("dir1/Foo.java");
// dir in dir in root
- assertThat(reader.readComponent(dir1_dir1.batchId()).getPath()).isEqualTo("dir1/dir1");
- assertThat(reader.readComponent(dir1_dir1.batchId()).getProjectRelativePath()).isEqualTo("dir1/dir1");
+ assertThat(reader.readComponent(dir1_dir1.scannerId()).getPath()).isEqualTo("dir1/dir1");
+ assertThat(reader.readComponent(dir1_dir1.scannerId()).getProjectRelativePath()).isEqualTo("dir1/dir1");
// module in root
- assertThat(reader.readComponent(mod1.batchId()).getPath()).isEqualTo("mod1");
- assertThat(reader.readComponent(mod1.batchId()).getProjectRelativePath()).isEqualTo("mod1");
+ assertThat(reader.readComponent(mod1.scannerId()).getPath()).isEqualTo("mod1");
+ assertThat(reader.readComponent(mod1.scannerId()).getProjectRelativePath()).isEqualTo("mod1");
// dir in module in root
- assertThat(reader.readComponent(mod1_dir2.batchId()).getPath()).isEqualTo("dir2");
- assertThat(reader.readComponent(mod1_dir2.batchId()).getProjectRelativePath()).isEqualTo("mod1/dir2");
+ assertThat(reader.readComponent(mod1_dir2.scannerId()).getPath()).isEqualTo("dir2");
+ assertThat(reader.readComponent(mod1_dir2.scannerId()).getProjectRelativePath()).isEqualTo("mod1/dir2");
// file in dir in module in root
- assertThat(reader.readComponent(mod1_dir2_file.batchId()).getPath()).isEqualTo("dir2/Foo.java");
- assertThat(reader.readComponent(mod1_dir2_file.batchId()).getProjectRelativePath()).isEqualTo("mod1/dir2/Foo.java");
+ assertThat(reader.readComponent(mod1_dir2_file.scannerId()).getPath()).isEqualTo("dir2/Foo.java");
+ assertThat(reader.readComponent(mod1_dir2_file.scannerId()).getProjectRelativePath()).isEqualTo("mod1/dir2/Foo.java");
// module in module
- assertThat(reader.readComponent(mod1_mod2.batchId()).getPath()).isEqualTo("mod2");
- assertThat(reader.readComponent(mod1_mod2.batchId()).getProjectRelativePath()).isEqualTo("mod1/mod2");
+ assertThat(reader.readComponent(mod1_mod2.scannerId()).getPath()).isEqualTo("mod2");
+ assertThat(reader.readComponent(mod1_mod2.scannerId()).getProjectRelativePath()).isEqualTo("mod1/mod2");
// file in module in module
- assertThat(reader.readComponent(mod1_mod2_file.batchId()).getPath()).isEqualTo("Foo.java");
- assertThat(reader.readComponent(mod1_mod2_file.batchId()).getProjectRelativePath()).isEqualTo("mod1/mod2/Foo.java");
+ assertThat(reader.readComponent(mod1_mod2_file.scannerId()).getPath()).isEqualTo("Foo.java");
+ assertThat(reader.readComponent(mod1_mod2_file.scannerId()).getProjectRelativePath()).isEqualTo("mod1/mod2/Foo.java");
// dir in module in module
- assertThat(reader.readComponent(mod1_mod2_dir.batchId()).getPath()).isEqualTo("dir");
- assertThat(reader.readComponent(mod1_mod2_dir.batchId()).getProjectRelativePath()).isEqualTo("mod1/mod2/dir");
+ assertThat(reader.readComponent(mod1_mod2_dir.scannerId()).getPath()).isEqualTo("dir");
+ assertThat(reader.readComponent(mod1_mod2_dir.scannerId()).getProjectRelativePath()).isEqualTo("mod1/mod2/dir");
// file in dir in module in module
- assertThat(reader.readComponent(mod1_mod2_dir_file.batchId()).getPath()).isEqualTo("dir/Foo.java");
- assertThat(reader.readComponent(mod1_mod2_dir_file.batchId()).getProjectRelativePath()).isEqualTo("mod1/mod2/dir/Foo.java");
+ assertThat(reader.readComponent(mod1_mod2_dir_file.scannerId()).getPath()).isEqualTo("dir/Foo.java");
+ assertThat(reader.readComponent(mod1_mod2_dir_file.scannerId()).getProjectRelativePath()).isEqualTo("mod1/mod2/dir/Foo.java");
}
}
import org.junit.Test;
import org.junit.rules.TemporaryFolder;
import org.sonar.api.batch.fs.internal.DefaultInputFile;
-import org.sonar.api.batch.fs.internal.DefaultInputModule;
+import org.sonar.api.batch.fs.internal.DefaultInputProject;
import org.sonar.api.batch.fs.internal.TestInputFileBuilder;
import org.sonar.api.batch.sensor.measure.internal.DefaultMeasure;
import org.sonar.api.measures.CoreMetrics;
public void prepare() throws IOException {
String moduleKey = "foo";
inputFile = new TestInputFileBuilder(moduleKey, "src/Foo.php").setLines(5).build();
- DefaultInputModule rootModule = TestInputFileBuilder.newDefaultInputModule(moduleKey, temp.newFolder());
+ DefaultInputProject rootModule = TestInputFileBuilder.newDefaultInputProject(moduleKey, temp.newFolder());
InputComponentStore componentCache = new InputComponentStore(rootModule, mock(BranchConfiguration.class));
componentCache.put(inputFile);
publisher.publish(writer);
- try (CloseableIterator<LineCoverage> it = new ScannerReportReader(outputDir).readComponentCoverage(inputFile.batchId())) {
+ try (CloseableIterator<LineCoverage> it = new ScannerReportReader(outputDir).readComponentCoverage(inputFile.scannerId())) {
assertThat(it.next()).isEqualTo(LineCoverage.newBuilder()
.setLine(2)
.setHits(true)
import org.junit.rules.ExpectedException;
import org.junit.rules.TemporaryFolder;
import org.sonar.api.batch.fs.internal.DefaultInputFile;
-import org.sonar.api.batch.fs.internal.DefaultInputModule;
+import org.sonar.api.batch.fs.internal.DefaultInputProject;
import org.sonar.api.batch.fs.internal.TestInputFileBuilder;
import org.sonar.api.batch.sensor.measure.internal.DefaultMeasure;
import org.sonar.api.measures.CoreMetrics;
private File outputDir;
private ScannerReportWriter writer;
private DefaultInputFile inputFile;
- private DefaultInputModule inputModule;
+ private DefaultInputProject project;
@Before
public void prepare() throws IOException {
- String moduleKey = "foo";
- inputModule = TestInputFileBuilder.newDefaultInputModule(moduleKey, temp.newFolder());
- inputFile = new TestInputFileBuilder(moduleKey, "src/Foo.php").setPublish(true).build();
- InputComponentStore componentCache = new InputComponentStore(inputModule, mock(BranchConfiguration.class));
+ String projectKey = "foo";
+ project = TestInputFileBuilder.newDefaultInputProject(projectKey, temp.newFolder());
+ inputFile = new TestInputFileBuilder(projectKey, "src/Foo.php").setPublish(true).build();
+ InputComponentStore componentCache = new InputComponentStore(project, mock(BranchConfiguration.class));
componentCache.put(inputFile);
measureCache = mock(MeasureCache.class);
when(measureCache.byComponentKey(anyString())).thenReturn(Collections.<DefaultMeasure<?>>emptyList());
publisher.publish(writer);
ScannerReportReader reader = new ScannerReportReader(outputDir);
- assertThat(reader.readComponentMeasures(inputModule.batchId())).hasSize(0);
- try (CloseableIterator<ScannerReport.Measure> componentMeasures = reader.readComponentMeasures(inputFile.batchId())) {
+ assertThat(reader.readComponentMeasures(project.scannerId())).hasSize(0);
+ try (CloseableIterator<ScannerReport.Measure> componentMeasures = reader.readComponentMeasures(inputFile.scannerId())) {
assertThat(componentMeasures).hasSize(2);
}
}
import org.sonar.scanner.protocol.output.ScannerReport;
import org.sonar.scanner.protocol.output.ScannerReportReader;
import org.sonar.scanner.protocol.output.ScannerReportWriter;
-import org.sonar.scanner.rule.QualityProfiles;
import org.sonar.scanner.rule.QProfile;
+import org.sonar.scanner.rule.QualityProfiles;
import org.sonar.scanner.scan.ScanProperties;
import org.sonar.scanner.scan.branch.BranchConfiguration;
import org.sonar.scanner.scan.branch.BranchType;
import org.junit.Test;
import org.junit.rules.TemporaryFolder;
import org.sonar.api.batch.fs.internal.DefaultInputFile;
-import org.sonar.api.batch.fs.internal.DefaultInputModule;
+import org.sonar.api.batch.fs.internal.DefaultInputProject;
import org.sonar.api.batch.fs.internal.TestInputFileBuilder;
import org.sonar.scanner.protocol.output.ScannerReportWriter;
import org.sonar.scanner.scan.branch.BranchConfiguration;
.setCharset(StandardCharsets.ISO_8859_1)
.build();
- DefaultInputModule rootModule = TestInputFileBuilder.newDefaultInputModule(moduleKey, baseDir);
- InputComponentStore componentStore = new InputComponentStore(rootModule, mock(BranchConfiguration.class));
+ DefaultInputProject rootProject = TestInputFileBuilder.newDefaultInputProject(moduleKey, baseDir);
+ InputComponentStore componentStore = new InputComponentStore(rootProject, mock(BranchConfiguration.class));
componentStore.put(inputFile);
publisher = new SourcePublisher(componentStore);
publisher.publish(writer);
- File out = writer.getSourceFile(inputFile.batchId());
+ File out = writer.getSourceFile(inputFile.scannerId());
assertThat(FileUtils.readFileToString(out, StandardCharsets.UTF_8)).isEqualTo("");
}
publisher.publish(writer);
- File out = writer.getSourceFile(inputFile.batchId());
+ File out = writer.getSourceFile(inputFile.scannerId());
assertThat(FileUtils.readFileToString(out, StandardCharsets.UTF_8)).isEqualTo("1\n2\n3\n4\n");
}
publisher.publish(writer);
- File out = writer.getSourceFile(inputFile.batchId());
+ File out = writer.getSourceFile(inputFile.scannerId());
assertThat(FileUtils.readFileToString(out, StandardCharsets.UTF_8)).isEqualTo("1\n2\n3\n4\n");
}
publisher.publish(writer);
- File out = writer.getSourceFile(inputFile.batchId());
+ File out = writer.getSourceFile(inputFile.scannerId());
assertThat(FileUtils.readFileToString(out, StandardCharsets.UTF_8)).isEqualTo("1\n2\n3\n4\n5");
}
publisher.publish(writer);
- File out = writer.getSourceFile(inputFile.batchId());
+ File out = writer.getSourceFile(inputFile.scannerId());
assertThat(FileUtils.readFileToString(out, StandardCharsets.UTF_8)).isEqualTo("\n2\n3\n4\n5");
}
import org.junit.Test;
import org.mockito.Mock;
import org.mockito.MockitoAnnotations;
-import org.sonar.api.batch.bootstrap.ProjectKey;
import org.sonar.scanner.bootstrap.GlobalAnalysisMode;
+import org.sonar.scanner.bootstrap.ScannerProperties;
import org.sonar.scanner.scan.branch.BranchConfiguration;
import static org.assertj.core.api.Assertions.assertThat;
@Mock
private ProjectRepositoriesLoader loader;
@Mock
- private ProjectKey projectKey;
+ private ScannerProperties props;
@Mock
private GlobalAnalysisMode mode;
@Mock
project = new ProjectRepositories(t1, t2, new Date());
provider = new ProjectRepositoriesProvider();
- when(projectKey.get()).thenReturn("key");
+ when(props.getKeyWithBranch()).thenReturn("key");
}
@Test
when(mode.isIssues()).thenReturn(true);
when(loader.load(eq("key"), eq(true), any())).thenReturn(project);
- provider.provide(loader, projectKey, mode, branchConfiguration);
+ provider.provide(loader, props, mode, branchConfiguration);
}
@Test
when(mode.isIssues()).thenReturn(false);
when(loader.load(eq("key"), eq(false), any())).thenReturn(project);
- ProjectRepositories repo = provider.provide(loader, projectKey, mode, branchConfiguration);
+ ProjectRepositories repo = provider.provide(loader, props, mode, branchConfiguration);
assertThat(repo.exists()).isEqualTo(true);
assertThat(repo.lastAnalysisDate()).isNotNull();
verify(mode, times(1)).isIssues();
- verify(projectKey).get();
+ verify(props).getKeyWithBranch();
verify(loader).load(eq("key"), eq(false), eq(null));
- verifyNoMoreInteractions(loader, projectKey, mode);
+ verifyNoMoreInteractions(loader, props, mode);
}
}
import org.junit.Test;
import org.mockito.Mock;
import org.mockito.MockitoAnnotations;
-import org.sonar.api.batch.bootstrap.ProjectKey;
import org.sonar.api.utils.DateUtils;
import org.sonar.api.utils.log.LogTester;
import org.sonar.api.utils.log.LoggerLevel;
-import org.sonar.scanner.analysis.AnalysisProperties;
+import org.sonar.scanner.bootstrap.ScannerProperties;
import org.sonar.scanner.rule.QualityProfiles;
import org.sonarqube.ws.Qualityprofiles.SearchWsResponse.QualityProfile;
@Mock
private QualityProfileLoader loader;
@Mock
- private AnalysisProperties props;
- @Mock
- private ProjectKey key;
+ private ScannerProperties props;
@Mock
private ProjectRepositories projectRepo;
MockitoAnnotations.initMocks(this);
qualityProfileProvider = new QualityProfilesProvider();
- when(key.get()).thenReturn("project");
+ when(props.getKeyWithBranch()).thenReturn("project");
when(projectRepo.exists()).thenReturn(true);
response = new ArrayList<>(1);
@Test
public void testProvide() {
when(loader.load("project", null)).thenReturn(response);
- QualityProfiles qps = qualityProfileProvider.provide(key, loader, projectRepo, props);
+ QualityProfiles qps = qualityProfileProvider.provide(loader, projectRepo, props);
assertResponse(qps);
verify(loader).load("project", null);
when(projectRepo.exists()).thenReturn(false);
when(loader.loadDefault(anyString())).thenReturn(response);
when(props.property(QualityProfiles.SONAR_PROFILE_PROP)).thenReturn("profile");
- QualityProfiles qps = qualityProfileProvider.provide(key, loader, projectRepo, props);
+ QualityProfiles qps = qualityProfileProvider.provide(loader, projectRepo, props);
assertResponse(qps);
verify(loader).loadDefault(anyString());
when(props.property(QualityProfiles.SONAR_PROFILE_PROP)).thenReturn("custom");
when(props.properties()).thenReturn(ImmutableMap.of(QualityProfiles.SONAR_PROFILE_PROP, "custom"));
- QualityProfiles qps = qualityProfileProvider.provide(key, loader, projectRepo, props);
+ QualityProfiles qps = qualityProfileProvider.provide(loader, projectRepo, props);
assertResponse(qps);
verify(loader).load(eq("project"), eq("custom"));
when(props.property(QualityProfiles.SONAR_PROFILE_PROP)).thenReturn("custom");
when(props.properties()).thenReturn(ImmutableMap.of(QualityProfiles.SONAR_PROFILE_PROP, "custom"));
- QualityProfiles qps = qualityProfileProvider.provide(key, loader, projectRepo, props);
+ QualityProfiles qps = qualityProfileProvider.provide(loader, projectRepo, props);
assertResponse(qps);
verify(loader).loadDefault(eq("custom"));
import org.junit.Test;
import org.junit.rules.TemporaryFolder;
import org.sonar.api.batch.bootstrap.ProjectDefinition;
-import org.sonar.api.batch.fs.internal.DefaultInputComponent;
import org.sonar.api.batch.fs.internal.DefaultInputModule;
+import org.sonar.api.batch.fs.internal.DefaultInputProject;
import static org.assertj.core.api.Assertions.assertThat;
@Test
public void test() throws IOException {
- DefaultInputComponent root = new DefaultInputModule(ProjectDefinition.create().setKey("root").setBaseDir(temp.newFolder()).setWorkDir(temp.newFolder()));
- DefaultInputComponent mod1 = new DefaultInputModule(ProjectDefinition.create().setKey("mod1").setBaseDir(temp.newFolder()).setWorkDir(temp.newFolder()));
- DefaultInputComponent mod2 = new DefaultInputModule(ProjectDefinition.create().setKey("mod2").setBaseDir(temp.newFolder()).setWorkDir(temp.newFolder()));
- DefaultInputComponent mod3 = new DefaultInputModule(ProjectDefinition.create().setKey("mod3").setBaseDir(temp.newFolder()).setWorkDir(temp.newFolder()));
- DefaultInputComponent mod4 = new DefaultInputModule(ProjectDefinition.create().setKey("mod4").setBaseDir(temp.newFolder()).setWorkDir(temp.newFolder()));
+ DefaultInputProject root = new DefaultInputProject(ProjectDefinition.create().setKey("root").setBaseDir(temp.newFolder()).setWorkDir(temp.newFolder()));
+ DefaultInputModule mod1 = new DefaultInputModule(ProjectDefinition.create().setKey("mod1").setBaseDir(temp.newFolder()).setWorkDir(temp.newFolder()));
+ DefaultInputModule mod2 = new DefaultInputModule(ProjectDefinition.create().setKey("mod2").setBaseDir(temp.newFolder()).setWorkDir(temp.newFolder()));
+ DefaultInputModule mod3 = new DefaultInputModule(ProjectDefinition.create().setKey("mod3").setBaseDir(temp.newFolder()).setWorkDir(temp.newFolder()));
+ DefaultInputModule mod4 = new DefaultInputModule(ProjectDefinition.create().setKey("mod4").setBaseDir(temp.newFolder()).setWorkDir(temp.newFolder()));
tree.index(mod1, root);
tree.index(mod2, mod1);
parents.put(mod3, root);
parents.put(mod4, root);
- moduleHierarchy = new DefaultInputModuleHierarchy(parents);
+ moduleHierarchy = new DefaultInputModuleHierarchy(root, parents);
assertThat(moduleHierarchy.children(root)).containsOnly(mod1, mod3, mod4);
assertThat(moduleHierarchy.children(mod4)).isEmpty();
assertThat(moduleHierarchy.parent(root)).isNull();
assertThat(moduleHierarchy.root()).isEqualTo(root);
}
-
- @Test
- public void testParentChild() throws IOException {
- DefaultInputModule root = new DefaultInputModule(ProjectDefinition.create().setKey("root").setBaseDir(temp.newFolder()).setWorkDir(temp.newFolder()));
- DefaultInputModule mod1 = new DefaultInputModule(ProjectDefinition.create().setKey("mod1").setBaseDir(temp.newFolder()).setWorkDir(temp.newFolder()));
- moduleHierarchy = new DefaultInputModuleHierarchy(root, mod1);
-
- assertThat(moduleHierarchy.children(root)).containsOnly(mod1);
- assertThat(moduleHierarchy.children(mod1)).isEmpty();
-
- assertThat(moduleHierarchy.parent(mod1)).isEqualTo(root);
- assertThat(moduleHierarchy.parent(root)).isNull();
- assertThat(moduleHierarchy.root()).isEqualTo(root);
- }
}
import java.util.Arrays;
import org.junit.Test;
import org.sonar.api.batch.bootstrap.ProjectDefinition;
-import org.sonar.api.batch.fs.InputModule;
import org.sonar.api.batch.fs.internal.DefaultInputModule;
+import org.sonar.api.batch.fs.internal.DefaultInputProject;
import org.sonar.scanner.scan.branch.BranchConfiguration;
import org.sonar.scanner.scan.filesystem.InputComponentStore;
private DefaultInputModuleHierarchy moduleHierarchy;
private InputComponentStore componentStore;
- public void createIndexer(DefaultInputModule rootModule) {
- componentStore = new InputComponentStore(rootModule, mock(BranchConfiguration.class));
+ public void createIndexer(DefaultInputProject rootProject) {
+ componentStore = new InputComponentStore(rootProject, mock(BranchConfiguration.class));
tree = new DefaultComponentTree();
moduleHierarchy = mock(DefaultInputModuleHierarchy.class);
indexer = new ModuleIndexer(tree, componentStore, moduleHierarchy);
when(mod2.definition()).thenReturn(def);
when(mod3.definition()).thenReturn(def);
- createIndexer(root);
+ createIndexer(mock(DefaultInputProject.class));
when(moduleHierarchy.root()).thenReturn(root);
when(moduleHierarchy.children(root)).thenReturn(Arrays.asList(mod1, mod2, mod3));
indexer.start();
- InputModule rootModule = moduleHierarchy.root();
+ DefaultInputModule rootModule = moduleHierarchy.root();
assertThat(rootModule).isNotNull();
assertThat(moduleHierarchy.children(rootModule)).hasSize(3);
assertThat(tree.getChildren(rootModule)).hasSize(3);
import org.sonar.api.batch.bootstrap.ProjectDefinition;
import org.sonar.api.config.PropertyDefinitions;
import org.sonar.api.utils.MessageException;
+import org.sonar.scanner.bootstrap.GlobalAnalysisMode;
import org.sonar.scanner.bootstrap.GlobalConfiguration;
import org.sonar.scanner.bootstrap.GlobalConfigurationProvider;
-import org.sonar.scanner.bootstrap.GlobalAnalysisMode;
-import org.sonar.scanner.bootstrap.GlobalProperties;
-import org.sonar.scanner.bootstrap.MutableGlobalSettings;
+import org.sonar.scanner.bootstrap.GlobalServerSettings;
+import org.sonar.scanner.bootstrap.ScannerProperties;
import org.sonar.scanner.repository.FileData;
import org.sonar.scanner.repository.ProjectRepositories;
-import org.sonar.scanner.repository.settings.SettingsLoader;
import static org.assertj.core.api.Assertions.assertThat;
import static org.mockito.Mockito.mock;
@Test
public void test_loading_of_module_settings() {
- GlobalConfiguration globalSettings = newGlobalSettings(ImmutableMap.of(
+ GlobalConfiguration globalConfig = newGlobalConfig(ImmutableMap.of(
"overridding", "batch",
"on-batch", "true"));
ProjectDefinition module = ProjectDefinition.create().setKey("struts-core");
- MutableModuleSettings moduleSettings = new MutableModuleSettings(new MutableGlobalSettings(globalSettings), module, projRepos, mode);
+ MutableModuleSettings moduleSettings = new MutableModuleSettings(globalConfig, module, projRepos, mode);
assertThat(moduleSettings.getString("overridding")).isEqualTo("module");
assertThat(moduleSettings.getString("on-batch")).isEqualTo("true");
// SONAR-6386
@Test
public void test_loading_of_parent_module_settings_for_new_module() {
- GlobalConfiguration globalSettings = newGlobalSettings(ImmutableMap.of(
+ GlobalConfiguration globalConfig = newGlobalConfig(ImmutableMap.of(
"overridding", "batch",
"on-batch", "true"));
ProjectDefinition module = ProjectDefinition.create().setKey("struts-core");
ProjectDefinition.create().setKey("struts").addSubProject(module);
- MutableModuleSettings moduleSettings = new MutableModuleSettings(new MutableGlobalSettings(globalSettings), module, projRepos, mode);
+ MutableModuleSettings moduleSettings = new MutableModuleSettings(globalConfig, module, projRepos, mode);
assertThat(moduleSettings.getString("overridding")).isEqualTo("module");
assertThat(moduleSettings.getString("on-batch")).isEqualTo("true");
@Test
public void should_not_fail_when_accessing_secured_properties() {
- GlobalConfiguration globalSettings = newGlobalSettings(ImmutableMap.of("sonar.foo.secured", "bar"));
+ GlobalConfiguration globalConfig = newGlobalConfig(ImmutableMap.of("sonar.foo.secured", "bar"));
ProjectRepositories projSettingsRepo = createSettings("struts-core", ImmutableMap.of("sonar.foo.license.secured", "bar2"));
ProjectDefinition module = ProjectDefinition.create().setKey("struts-core");
- MutableModuleSettings moduleSettings = new MutableModuleSettings(new MutableGlobalSettings(globalSettings), module, projSettingsRepo, mode);
+ MutableModuleSettings moduleSettings = new MutableModuleSettings(globalConfig, module, projSettingsRepo, mode);
assertThat(moduleSettings.getString("sonar.foo.license.secured")).isEqualTo("bar2");
assertThat(moduleSettings.getString("sonar.foo.secured")).isEqualTo("bar");
@Test
public void should_fail_when_accessing_secured_properties_in_issues() {
- GlobalConfiguration globalSettings = newGlobalSettings(ImmutableMap.of(
+ GlobalConfiguration globalConfig = newGlobalConfig(ImmutableMap.of(
"sonar.foo.secured", "bar"));
ProjectRepositories projSettingsRepo = createSettings("struts-core", ImmutableMap.of("sonar.foo.license.secured", "bar2"));
ProjectDefinition module = ProjectDefinition.create().setKey("struts-core");
- MutableModuleSettings moduleSettings = new MutableModuleSettings(new MutableGlobalSettings(globalSettings), module, projSettingsRepo, mode);
+ MutableModuleSettings moduleSettings = new MutableModuleSettings(globalConfig, module, projSettingsRepo, mode);
assertThat(moduleSettings.getString("sonar.foo.license.secured")).isEqualTo("bar2");
moduleSettings.getString("sonar.foo.secured");
}
- private GlobalConfiguration newGlobalSettings(Map<String, String> props) {
- GlobalProperties globalProps = new GlobalProperties(props);
- return new GlobalConfigurationProvider().provide(mock(SettingsLoader.class), globalProps, new PropertyDefinitions(),
- new GlobalAnalysisMode(globalProps));
+ private GlobalConfiguration newGlobalConfig(Map<String, String> props) {
+ ScannerProperties scannerProps = new ScannerProperties(props);
+ return new GlobalConfigurationProvider().provide(mock(GlobalServerSettings.class), scannerProps, new PropertyDefinitions(),
+ new GlobalAnalysisMode(scannerProps));
}
}
import org.sonar.api.config.PropertyDefinitions;
import org.sonar.api.utils.MessageException;
import org.sonar.api.utils.log.LogTester;
+import org.sonar.scanner.bootstrap.GlobalAnalysisMode;
import org.sonar.scanner.bootstrap.GlobalConfiguration;
import org.sonar.scanner.bootstrap.GlobalConfigurationProvider;
-import org.sonar.scanner.bootstrap.GlobalAnalysisMode;
-import org.sonar.scanner.bootstrap.GlobalProperties;
-import org.sonar.scanner.bootstrap.MutableGlobalSettings;
+import org.sonar.scanner.bootstrap.GlobalServerSettings;
+import org.sonar.scanner.bootstrap.ScannerProperties;
import org.sonar.scanner.repository.FileData;
import org.sonar.scanner.repository.ProjectRepositories;
-import org.sonar.scanner.repository.settings.SettingsLoader;
import static org.assertj.core.api.Assertions.assertThat;
import static org.mockito.Mockito.mock;
private ProjectRepositories projectRef;
private ProjectDefinition project;
- private GlobalConfiguration bootstrapProps;
+ private GlobalConfiguration globalConfig;
private Table<String, String, FileData> emptyFileData;
private Table<String, String, String> emptySettings;
emptySettings = ImmutableTable.of();
project = ProjectDefinition.create().setKey("struts");
globalMode = mock(GlobalAnalysisMode.class);
- bootstrapProps = new GlobalConfigurationProvider().provide(mock(SettingsLoader.class), new GlobalProperties(Collections.<String, String>emptyMap()), new PropertyDefinitions(),
+ globalConfig = new GlobalConfigurationProvider().provide(mock(GlobalServerSettings.class), new ScannerProperties(Collections.<String, String>emptyMap()), new PropertyDefinitions(),
globalMode);
}
project.setProperty("project.prop", "project");
projectRef = new ProjectRepositories(emptySettings, emptyFileData, null);
- MutableProjectSettings batchSettings = new MutableProjectSettings(new ProjectReactor(project), new MutableGlobalSettings(bootstrapProps), projectRef, globalMode);
+ MutableProjectSettings batchSettings = new MutableProjectSettings(new ProjectReactor(project), globalConfig, projectRef, globalMode);
assertThat(batchSettings.getString("project.prop")).isEqualTo("project");
}
settings.put("struts", "sonar.java.coveragePlugin", "jacoco");
projectRef = new ProjectRepositories(settings, emptyFileData, null);
- MutableProjectSettings batchSettings = new MutableProjectSettings(new ProjectReactor(project), new MutableGlobalSettings(bootstrapProps), projectRef, globalMode);
+ MutableProjectSettings batchSettings = new MutableProjectSettings(new ProjectReactor(project), globalConfig, projectRef, globalMode);
assertThat(batchSettings.getString("sonar.java.coveragePlugin")).isEqualTo("jacoco");
}
projectRef = new ProjectRepositories(settings, emptyFileData, null);
- MutableProjectSettings batchSettings = new MutableProjectSettings(new ProjectReactor(project), new MutableGlobalSettings(bootstrapProps), projectRef, globalMode);
+ MutableProjectSettings batchSettings = new MutableProjectSettings(new ProjectReactor(project), globalConfig, projectRef, globalMode);
assertThat(batchSettings.getString("sonar.java.coveragePlugin")).isEqualTo("jacoco");
}
settings.put("struts", "sonar.foo.license.secured", "bar2");
projectRef = new ProjectRepositories(settings, emptyFileData, null);
- MutableProjectSettings batchSettings = new MutableProjectSettings(new ProjectReactor(project), new MutableGlobalSettings(bootstrapProps), projectRef, globalMode);
+ MutableProjectSettings batchSettings = new MutableProjectSettings(new ProjectReactor(project), globalConfig, projectRef, globalMode);
assertThat(batchSettings.getString("sonar.foo.license.secured")).isEqualTo("bar2");
assertThat(batchSettings.getString("sonar.foo.secured")).isEqualTo("bar");
when(globalMode.isIssues()).thenReturn(true);
projectRef = new ProjectRepositories(settings, emptyFileData, null);
- MutableProjectSettings batchSettings = new MutableProjectSettings(new ProjectReactor(project), new MutableGlobalSettings(bootstrapProps), projectRef, globalMode);
+ MutableProjectSettings batchSettings = new MutableProjectSettings(new ProjectReactor(project), globalConfig, projectRef, globalMode);
assertThat(batchSettings.getString("sonar.foo.license.secured")).isEqualTo("bar2");
thrown.expect(MessageException.class);
package org.sonar.scanner.scan;
import java.io.File;
+import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import org.junit.Before;
import org.junit.Test;
import org.junit.rules.ExpectedException;
import org.junit.rules.TemporaryFolder;
-import org.sonar.api.batch.fs.internal.DefaultInputModule;
-import org.sonar.api.batch.fs.internal.InputModuleHierarchy;
+import org.sonar.api.batch.bootstrap.ProjectDefinition;
+import org.sonar.api.batch.fs.internal.DefaultInputProject;
import static org.assertj.core.api.Assertions.assertThat;
-import static org.mockito.Mockito.mock;
-import static org.mockito.Mockito.when;
public class ProjectLockTest {
@Rule
@Rule
public ExpectedException exception = ExpectedException.none();
private ProjectLock lock;
+ private File baseDir;
+ private File worDir;
@Before
- public void setUp() {
- lock = setUpTest(tempFolder.getRoot());
- }
-
- private ProjectLock setUpTest(File file) {
- InputModuleHierarchy hierarchy = mock(InputModuleHierarchy.class);
- DefaultInputModule root = mock(DefaultInputModule.class);
- when(hierarchy.root()).thenReturn(root);
- when(root.getWorkDir()).thenReturn(file.toPath());
-
- return new ProjectLock(hierarchy);
+ public void setUp() throws IOException {
+ baseDir = tempFolder.newFolder();
+ worDir = new File(baseDir, ".sonar");
+ lock = new ProjectLock(new DefaultInputProject(ProjectDefinition.create().setBaseDir(baseDir).setWorkDir(worDir)));
}
@Test
public void tryLock() {
- Path lockFilePath = tempFolder.getRoot().toPath().resolve(DirectoryLock.LOCK_FILE_NAME);
+ Path lockFilePath = worDir.toPath().resolve(DirectoryLock.LOCK_FILE_NAME);
lock.tryLock();
assertThat(Files.exists(lockFilePath)).isTrue();
assertThat(Files.isRegularFile(lockFilePath)).isTrue();
import org.sonar.api.batch.bootstrap.ProjectReactor;
import org.sonar.api.utils.MessageException;
import org.sonar.api.utils.log.LogTester;
-import org.sonar.api.utils.log.LoggerLevel;
-import org.sonar.scanner.analysis.AnalysisProperties;
+import org.sonar.scanner.bootstrap.ScannerProperties;
import static org.assertj.core.api.Assertions.assertThat;
assertThat(module12.properties().get("sonar.profile")).isEqualTo("Foo");
}
- @Test
- public void shouldRemoveModulePropertiesFromTaskProperties() {
- Map<String, String> props = loadProps("big-multi-module-definitions-all-in-root");
-
- AnalysisProperties taskProperties = new AnalysisProperties(props, null);
- assertThat(taskProperties.property("module1.module11.property")).isEqualTo("My module11 property");
-
- new ProjectReactorBuilder(taskProperties).execute();
-
- assertThat(taskProperties.property("module1.module11.property")).isNull();
- }
-
@Test
public void shouldFailIfMandatoryPropertiesAreNotPresent() {
Map<String, String> props = new HashMap<>();
@Test
public void shouldInitRootWorkDir() {
- ProjectReactorBuilder builder = new ProjectReactorBuilder(new AnalysisProperties(Maps.<String, String>newHashMap(), null));
+ ProjectReactorBuilder builder = new ProjectReactorBuilder(new ScannerProperties(Maps.<String, String>newHashMap()));
File baseDir = new File("target/tmp/baseDir");
File workDir = builder.initRootProjectWorkDir(baseDir, Maps.<String, String>newHashMap());
public void shouldInitWorkDirWithCustomRelativeFolder() {
Map<String, String> props = Maps.<String, String>newHashMap();
props.put("sonar.working.directory", ".foo");
- ProjectReactorBuilder builder = new ProjectReactorBuilder(new AnalysisProperties(props, null));
+ ProjectReactorBuilder builder = new ProjectReactorBuilder(new ScannerProperties(props));
File baseDir = new File("target/tmp/baseDir");
File workDir = builder.initRootProjectWorkDir(baseDir, props);
public void shouldInitRootWorkDirWithCustomAbsoluteFolder() {
Map<String, String> props = Maps.<String, String>newHashMap();
props.put("sonar.working.directory", new File("src").getAbsolutePath());
- ProjectReactorBuilder builder = new ProjectReactorBuilder(new AnalysisProperties(props, null));
+ ProjectReactorBuilder builder = new ProjectReactorBuilder(new ScannerProperties(props));
File baseDir = new File("target/tmp/baseDir");
File workDir = builder.initRootProjectWorkDir(baseDir, props);
private ProjectDefinition loadProjectDefinition(String projectFolder) {
Map<String, String> props = loadProps(projectFolder);
- AnalysisProperties bootstrapProps = new AnalysisProperties(props, null);
+ ScannerProperties bootstrapProps = new ScannerProperties(props);
ProjectReactor projectReactor = new ProjectReactorBuilder(bootstrapProps).execute();
return projectReactor.getRoot();
}
.isEqualTo(new File(getResource(this.getClass(), "multi-module-definitions-same-prefix"), ".sonar/com.foo.project_com.foo.project.module1.feature"));
}
- @Test
- public void should_log_a_warning_when_a_dropped_property_is_present() {
- Map<String, String> props = loadProps("simple-project");
- props.put("sonar.qualitygate", "somevalue");
- AnalysisProperties bootstrapProps = new AnalysisProperties(props, null);
- new ProjectReactorBuilder(bootstrapProps).execute();
-
- assertThat(logTester.logs(LoggerLevel.WARN)).containsOnly("Property 'sonar.qualitygate' is not supported any more. It will be ignored.");
- }
-
private Map<String, String> loadPropsFromFile(String filePath) throws IOException {
Properties props = new Properties();
try (FileInputStream fileInputStream = new FileInputStream(getResource(this.getClass(), filePath))) {
import org.junit.Test;
import org.junit.rules.ExpectedException;
import org.junit.rules.TemporaryFolder;
-import org.sonar.api.batch.fs.internal.DefaultInputModule;
-import org.sonar.api.batch.fs.internal.InputModuleHierarchy;
+import org.sonar.api.batch.fs.internal.DefaultInputProject;
import org.sonar.api.config.internal.MapSettings;
import org.sonar.api.utils.MessageException;
public class ScanPropertiesTest {
private MapSettings settings = new MapSettings();
- private InputModuleHierarchy inputModuleHierarchy = mock(InputModuleHierarchy.class);
- private ScanProperties underTest = new ScanProperties(settings.asConfig(), inputModuleHierarchy);
+ private DefaultInputProject project = mock(DefaultInputProject.class);
+ private ScanProperties underTest = new ScanProperties(settings.asConfig(), project);
@Rule
public TemporaryFolder temp = new TemporaryFolder();
-
+
@Rule
public ExpectedException exception = ExpectedException.none();
@Before
public void setUp() throws IOException {
- DefaultInputModule root = mock(DefaultInputModule.class);
- when(root.getBaseDir()).thenReturn(temp.newFolder().toPath());
- when(root.getWorkDir()).thenReturn(temp.newFolder().toPath());
- when(inputModuleHierarchy.root()).thenReturn(root);
+ when(project.getBaseDir()).thenReturn(temp.newFolder().toPath());
+ when(project.getWorkDir()).thenReturn(temp.newFolder().toPath());
}
@Test
assertThat(underTest.organizationKey()).isEmpty();
assertThat(underTest.preloadFileMetadata()).isFalse();
assertThat(underTest.shouldKeepReport()).isFalse();
- assertThat(underTest.metadataFilePath()).isEqualTo(inputModuleHierarchy.root().getWorkDir().resolve("report-task.txt"));
+ assertThat(underTest.metadataFilePath()).isEqualTo(project.getWorkDir().resolve("report-task.txt"));
underTest.validate();
}
settings.setProperty("sonar.organization", "org");
assertThat(underTest.organizationKey()).isEqualTo(Optional.of("org"));
}
-
+
@Test
public void should_define_branch_name() {
settings.setProperty("sonar.branch.name", "name");
assertThat(underTest.branch()).isEqualTo(Optional.of("name"));
}
-
+
@Test
public void should_define_preload_file_metadata() {
settings.setProperty("sonar.preloadFileMetadata", "true");
assertThat(underTest.preloadFileMetadata()).isTrue();
}
-
+
@Test
public void should_define_keep_report() {
settings.setProperty("sonar.scanner.keepReport", "true");
assertThat(underTest.shouldKeepReport()).isTrue();
}
-
+
@Test
public void should_define_metadata_file_path() throws IOException {
Path path = temp.newFolder().toPath().resolve("report");
settings.setProperty("sonar.scanner.metadataFilePath", path.toString());
assertThat(underTest.metadataFilePath()).isEqualTo(path);
}
-
+
@Test
public void validate_fails_if_metadata_file_location_is_not_absolute() {
settings.setProperty("sonar.scanner.metadataFilePath", "relative");
import org.sonar.api.batch.fs.InputPath;
import org.sonar.api.batch.fs.internal.DefaultInputFile;
import org.sonar.api.batch.fs.internal.DefaultInputModule;
+import org.sonar.api.batch.fs.internal.DefaultInputProject;
import org.sonar.api.batch.fs.internal.TestInputFileBuilder;
import org.sonar.scanner.scan.branch.BranchConfiguration;
ProjectDefinition rootDef = ProjectDefinition.create()
.setKey(rootModuleKey).setBaseDir(rootBaseDir).setWorkDir(temp.newFolder()).addSubProject(moduleDef);
- DefaultInputModule rootModule = TestInputFileBuilder.newDefaultInputModule(rootDef);
+ DefaultInputProject rootProject = TestInputFileBuilder.newDefaultInputProject(rootDef);
DefaultInputModule subModule = TestInputFileBuilder.newDefaultInputModule(moduleDef);
- InputComponentStore cache = new InputComponentStore(rootModule, mock(BranchConfiguration.class));
+ InputComponentStore cache = new InputComponentStore(rootProject, mock(BranchConfiguration.class));
cache.put(subModule);
DefaultInputFile fooFile = new TestInputFileBuilder(rootModuleKey, "src/main/java/Foo.java")
static class InputComponentStoreTester extends InputComponentStore {
InputComponentStoreTester() throws IOException {
- super(TestInputFileBuilder.newDefaultInputModule("root", temp.newFolder()), mock(BranchConfiguration.class));
+ super(TestInputFileBuilder.newDefaultInputProject("root", temp.newFolder()), mock(BranchConfiguration.class));
}
InputFile addFile(String moduleKey, String relpath, String language) {
import org.sonar.api.batch.fs.internal.DefaultInputFile;
import org.sonar.api.batch.fs.internal.DefaultInputModule;
import org.sonar.api.batch.fs.internal.SensorStrategy;
-import org.sonar.api.config.internal.MapSettings;
import org.sonar.scanner.scan.DefaultInputModuleHierarchy;
import org.sonar.scanner.scan.ScanProperties;
.setKey("module1"), 0);
MetadataGenerator metadataGenerator = mock(MetadataGenerator.class);
- BatchIdGenerator idGenerator = new BatchIdGenerator();
+ ScannerComponentIdGenerator idGenerator = new ScannerComponentIdGenerator();
ScanProperties properties = mock(ScanProperties.class);
ModuleFileSystemInitializer moduleFileSystemInitializer = mock(ModuleFileSystemInitializer.class);
when(moduleFileSystemInitializer.defaultEncoding()).thenReturn(StandardCharsets.UTF_8);
import org.junit.rules.TemporaryFolder;
import org.sonar.api.batch.fs.InputFile;
import org.sonar.api.batch.fs.InputModule;
-import org.sonar.api.batch.fs.internal.DefaultInputModule;
+import org.sonar.api.batch.fs.internal.DefaultInputProject;
import org.sonar.api.batch.fs.internal.SensorStrategy;
import org.sonar.api.batch.fs.internal.TestInputFileBuilder;
import org.sonar.scanner.scan.branch.BranchConfiguration;
private InputComponentStore componentStore;
- private final String moduleKey = "dummy key";
+ private final String projectKey = "dummy key";
@Before
public void setUp() throws IOException {
- DefaultInputModule root = TestInputFileBuilder.newDefaultInputModule(moduleKey, temp.newFolder());
+ DefaultInputProject root = TestInputFileBuilder.newDefaultInputProject(projectKey, temp.newFolder());
componentStore = new InputComponentStore(root, mock(BranchConfiguration.class));
}
ModuleInputComponentStore store = newModuleInputComponentStore();
String filename = "some name";
- InputFile inputFile1 = new TestInputFileBuilder(moduleKey, "some/path/" + filename).build();
+ InputFile inputFile1 = new TestInputFileBuilder(projectKey, "some/path/" + filename).build();
store.doAdd(inputFile1);
- InputFile inputFile2 = new TestInputFileBuilder(moduleKey, "other/path/" + filename).build();
+ InputFile inputFile2 = new TestInputFileBuilder(projectKey, "other/path/" + filename).build();
store.doAdd(inputFile2);
- InputFile dummyInputFile = new TestInputFileBuilder(moduleKey, "some/path/Dummy.java").build();
+ InputFile dummyInputFile = new TestInputFileBuilder(projectKey, "some/path/Dummy.java").build();
store.doAdd(dummyInputFile);
assertThat(store.getFilesByName(filename)).containsExactlyInAnyOrder(inputFile1, inputFile2);
public void should_cache_files_by_extension() throws IOException {
ModuleInputComponentStore store = newModuleInputComponentStore();
- InputFile inputFile1 = new TestInputFileBuilder(moduleKey, "some/path/Program.java").build();
+ InputFile inputFile1 = new TestInputFileBuilder(projectKey, "some/path/Program.java").build();
store.doAdd(inputFile1);
- InputFile inputFile2 = new TestInputFileBuilder(moduleKey, "other/path/Utils.java").build();
+ InputFile inputFile2 = new TestInputFileBuilder(projectKey, "other/path/Utils.java").build();
store.doAdd(inputFile2);
- InputFile dummyInputFile = new TestInputFileBuilder(moduleKey, "some/path/NotJava.cpp").build();
+ InputFile dummyInputFile = new TestInputFileBuilder(projectKey, "some/path/NotJava.cpp").build();
store.doAdd(dummyInputFile);
assertThat(store.getFilesByExtension("java")).containsExactlyInAnyOrder(inputFile1, inputFile2);
String ext = "java";
String filename = "Program." + ext;
- InputFile inputFile = new TestInputFileBuilder(moduleKey, "some/path/" + filename).build();
+ InputFile inputFile = new TestInputFileBuilder(projectKey, "some/path/" + filename).build();
store.doAdd(inputFile);
store.doAdd(inputFile);
store.doAdd(inputFile);
String ext = "java";
String filename = "Program." + ext;
- InputFile inputFile = new TestInputFileBuilder(moduleKey, "some/path/" + filename).build();
+ InputFile inputFile = new TestInputFileBuilder(projectKey, "some/path/" + filename).build();
store.doAdd(inputFile);
assertThat(store.getFilesByName("nonexistent")).isEmpty();
import org.sonar.api.batch.fs.internal.DefaultInputDir;
import org.sonar.api.batch.fs.internal.DefaultInputFile;
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.fs.internal.TestInputFileBuilder;
import org.sonar.api.batch.rule.Rules;
DefaultComponentTree inputComponentTree = new DefaultComponentTree();
ProjectDefinition def = ProjectDefinition.create().setBaseDir(projectBaseDir).setWorkDir(temp.newFolder()).setKey("struts");
+ DefaultInputProject project = new DefaultInputProject(def, 1);
DefaultInputModule rootModule = new DefaultInputModule(def, 1);
- InputComponentStore inputComponentStore = new InputComponentStore(rootModule, mock(BranchConfiguration.class));
+ InputComponentStore inputComponentStore = new InputComponentStore(project, mock(BranchConfiguration.class));
DefaultInputModule moduleA = new DefaultInputModule(ProjectDefinition.create().setKey("struts-core").setBaseDir(temp.newFolder()).setWorkDir(temp.newFolder()));
inputComponentTree.index(moduleA, rootModule);
import org.junit.rules.ExpectedException;
import org.mockito.Mock;
import org.mockito.MockitoAnnotations;
-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.scm.ScmProvider;
import org.sonar.scanner.scan.branch.BranchConfiguration;
private Path rootBaseDir = Paths.get("root");
private ScmChangedFilesProvider provider;
+ private DefaultInputProject project = mock(DefaultInputProject.class);
@Before
public void setUp() {
MockitoAnnotations.initMocks(this);
- DefaultInputModule root = mock(DefaultInputModule.class);
- when(root.getBaseDir()).thenReturn(rootBaseDir);
- when(inputModuleHierarchy.root()).thenReturn(root);
+ when(project.getBaseDir()).thenReturn(rootBaseDir);
provider = new ScmChangedFilesProvider();
}
when(branchConfiguration.isShortOrPullRequest()).thenReturn(true);
when(branchConfiguration.targetScmBranch()).thenReturn("target");
- ScmChangedFiles scmChangedFiles = provider.provide(scmConfiguration, branchConfiguration, inputModuleHierarchy);
+ ScmChangedFiles scmChangedFiles = provider.provide(scmConfiguration, branchConfiguration, project);
assertThat(scmChangedFiles.get()).isNull();
verify(scmConfiguration).provider();
exception.expect(IllegalStateException.class);
exception.expectMessage("changed file with a relative path");
- provider.provide(scmConfiguration, branchConfiguration, inputModuleHierarchy);
+ provider.provide(scmConfiguration, branchConfiguration, project);
}
@Test
when(branchConfiguration.isShortOrPullRequest()).thenReturn(true);
when(scmConfiguration.provider()).thenReturn(scmProvider);
when(scmProvider.branchChangedFiles("target", rootBaseDir)).thenReturn(null);
- ScmChangedFiles scmChangedFiles = provider.provide(scmConfiguration, branchConfiguration, inputModuleHierarchy);
+ ScmChangedFiles scmChangedFiles = provider.provide(scmConfiguration, branchConfiguration, project);
assertThat(scmChangedFiles.get()).isNull();
verify(scmProvider).branchChangedFiles("target", rootBaseDir);
@Test
public void testNoOpInNonShortLivedBranch() {
when(branchConfiguration.isShortOrPullRequest()).thenReturn(false);
- ScmChangedFiles scmChangedFiles = provider.provide(scmConfiguration, branchConfiguration, inputModuleHierarchy);
+ ScmChangedFiles scmChangedFiles = provider.provide(scmConfiguration, branchConfiguration, project);
assertThat(scmChangedFiles.get()).isNull();
verifyZeroInteractions(scmConfiguration);
when(branchConfiguration.isShortOrPullRequest()).thenReturn(true);
when(branchConfiguration.targetScmBranch()).thenReturn("target");
- ScmChangedFiles scmChangedFiles = provider.provide(scmConfiguration, branchConfiguration, inputModuleHierarchy);
+ ScmChangedFiles scmChangedFiles = provider.provide(scmConfiguration, branchConfiguration, project);
assertThat(scmChangedFiles.get()).isNull();
verify(scmConfiguration).provider();
when(branchConfiguration.isShortOrPullRequest()).thenReturn(true);
when(scmConfiguration.provider()).thenReturn(scmProvider);
when(scmProvider.branchChangedFiles("target", rootBaseDir)).thenReturn(Collections.singleton(Paths.get("changedFile").toAbsolutePath()));
- ScmChangedFiles scmChangedFiles = provider.provide(scmConfiguration, branchConfiguration, inputModuleHierarchy);
+ ScmChangedFiles scmChangedFiles = provider.provide(scmConfiguration, branchConfiguration, project);
assertThat(scmChangedFiles.get()).containsOnly(Paths.get("changedFile").toAbsolutePath());
verify(scmProvider).branchChangedFiles("target", rootBaseDir);
@Test
public void testCacheObject() {
- provider.provide(scmConfiguration, branchConfiguration, inputModuleHierarchy);
- provider.provide(scmConfiguration, branchConfiguration, inputModuleHierarchy);
+ provider.provide(scmConfiguration, branchConfiguration, project);
+ provider.provide(scmConfiguration, branchConfiguration, project);
verify(branchConfiguration).isShortOrPullRequest();
}
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.config.internal.MapSettings;
import org.sonar.api.internal.SonarRuntimeImpl;
import org.sonar.api.measures.CoreMetrics;
+import org.sonar.api.scanner.fs.InputProject;
import org.sonar.api.utils.Version;
import org.sonar.scanner.scan.DefaultInputModuleHierarchy;
hierarchy = new DefaultInputModuleHierarchy(new DefaultInputModule(ProjectDefinition.create()
.setWorkDir(temp.newFolder())
.setBaseDir(temp.newFolder()).setKey("foo")));
- adaptor = new DefaultSensorContext(mock(InputModule.class), settings.asConfig(), settings, fs, activeRules, analysisMode, sensorStorage, runtime, hierarchy);
+ adaptor = new DefaultSensorContext(mock(DefaultInputProject.class), mock(InputModule.class), settings.asConfig(), settings, fs, activeRules, analysisMode, sensorStorage, runtime);
}
@Test
import org.sonar.api.batch.fs.InputFile;
import org.sonar.api.batch.fs.internal.DefaultInputFile;
import org.sonar.api.batch.fs.internal.DefaultInputModule;
+import org.sonar.api.batch.fs.internal.DefaultInputProject;
import org.sonar.api.batch.fs.internal.TestInputFileBuilder;
import org.sonar.api.batch.measure.MetricFinder;
import org.sonar.api.batch.sensor.code.internal.DefaultSignificantCode;
private ScannerReportWriter reportWriter;
private ContextPropertiesCache contextPropertiesCache = new ContextPropertiesCache();
private BranchConfiguration branchConfiguration;
- private DefaultInputModule projectRoot;
+ private DefaultInputProject project;
@Before
public void prepare() throws Exception {
moduleIssues, settings.asConfig(), reportPublisher, measureCache,
mock(SonarCpdBlockIndex.class), contextPropertiesCache, new ScannerMetrics(), branchConfiguration);
- projectRoot = new DefaultInputModule(ProjectDefinition.create()
+ project = new DefaultInputProject(ProjectDefinition.create()
.setKey("foo")
.setBaseDir(temp.newFolder())
.setWorkDir(temp.newFolder()));
public void should_save_issue() {
InputFile file = new TestInputFileBuilder("foo", "src/Foo.php").build();
- DefaultIssue issue = new DefaultIssue(projectRoot).at(new DefaultIssueLocation().on(file));
+ DefaultIssue issue = new DefaultIssue(project).at(new DefaultIssueLocation().on(file));
underTest.store(issue);
ArgumentCaptor<Issue> argumentCaptor = ArgumentCaptor.forClass(Issue.class);
public void should_save_external_issue() {
InputFile file = new TestInputFileBuilder("foo", "src/Foo.php").build();
- DefaultExternalIssue externalIssue = new DefaultExternalIssue(projectRoot).at(new DefaultIssueLocation().on(file));
+ DefaultExternalIssue externalIssue = new DefaultExternalIssue(project).at(new DefaultIssueLocation().on(file));
underTest.store(externalIssue);
ArgumentCaptor<ExternalIssue> argumentCaptor = ArgumentCaptor.forClass(ExternalIssue.class);
InputFile file = new TestInputFileBuilder("foo", "src/Foo.php").setStatus(InputFile.Status.SAME).build();
when(branchConfiguration.isShortOrPullRequest()).thenReturn(true);
- DefaultIssue issue = new DefaultIssue(projectRoot).at(new DefaultIssueLocation().on(file));
+ DefaultIssue issue = new DefaultIssue(project).at(new DefaultIssueLocation().on(file));
underTest.store(issue);
verifyZeroInteractions(moduleIssues);
DefaultHighlighting highlighting = new DefaultHighlighting(underTest).onFile(file).highlight(0, 1, TypeOfText.KEYWORD);
underTest.store(highlighting);
- assertThat(reportWriter.hasComponentData(FileStructure.Domain.SYNTAX_HIGHLIGHTINGS, file.batchId())).isTrue();
+ assertThat(reportWriter.hasComponentData(FileStructure.Domain.SYNTAX_HIGHLIGHTINGS, file.scannerId())).isTrue();
}
@Test
DefaultHighlighting highlighting = new DefaultHighlighting(underTest).onFile(file).highlight(0, 1, TypeOfText.KEYWORD);
underTest.store(highlighting);
- assertThat(reportWriter.hasComponentData(FileStructure.Domain.SYNTAX_HIGHLIGHTINGS, file.batchId())).isFalse();
+ assertThat(reportWriter.hasComponentData(FileStructure.Domain.SYNTAX_HIGHLIGHTINGS, file.scannerId())).isFalse();
}
@Test
.onFile(file)
.addRange(file.selectLine(1)));
- assertThat(reportWriter.hasComponentData(FileStructure.Domain.SGNIFICANT_CODE, file.batchId())).isFalse();
+ assertThat(reportWriter.hasComponentData(FileStructure.Domain.SGNIFICANT_CODE, file.scannerId())).isFalse();
}
@Test
.onFile(file)
.addRange(file.selectLine(1)));
- assertThat(reportWriter.hasComponentData(FileStructure.Domain.SGNIFICANT_CODE, file.batchId())).isTrue();
+ assertThat(reportWriter.hasComponentData(FileStructure.Domain.SGNIFICANT_CODE, file.scannerId())).isTrue();
}
@Test