repo stringlengths 1 191 ⌀ | file stringlengths 23 351 | code stringlengths 0 5.32M | file_length int64 0 5.32M | avg_line_length float64 0 2.9k | max_line_length int64 0 288k | extension_type stringclasses 1 value |
|---|---|---|---|---|---|---|
sonarqube | sonarqube-master/sonar-scanner-engine/src/main/java/org/sonar/scanner/scm/ScmPublisher.java | /*
* SonarQube
* Copyright (C) 2009-2023 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.scm;
import java.util.LinkedList;
import java.util.List;
import org.apache.commons.lang.StringUtils;
import org.sonar.api.CoreProperties;
import org.sonar.api.batch.fs.FileSystem;
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.scm.ScmProvider;
import org.sonar.api.notifications.AnalysisWarnings;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.sonar.core.documentation.DocumentationLinkGenerator;
import org.sonar.scanner.protocol.output.ScannerReport;
import org.sonar.scanner.protocol.output.ScannerReport.Changesets.Builder;
import org.sonar.scanner.protocol.output.ScannerReportWriter;
import org.sonar.scanner.report.ReportPublisher;
import org.sonar.scanner.repository.FileData;
import org.sonar.scanner.repository.ProjectRepositories;
import org.sonar.scanner.scan.branch.BranchConfiguration;
import org.sonar.scanner.scan.filesystem.InputComponentStore;
public final class ScmPublisher {
private static final Logger LOG = LoggerFactory.getLogger(ScmPublisher.class);
private final ScmConfiguration configuration;
private final ProjectRepositories projectRepositories;
private final InputComponentStore componentStore;
private final FileSystem fs;
private final ScannerReportWriter writer;
private final AnalysisWarnings analysisWarnings;
private final BranchConfiguration branchConfiguration;
private final DocumentationLinkGenerator documentationLinkGenerator;
public ScmPublisher(ScmConfiguration configuration, ProjectRepositories projectRepositories, InputComponentStore componentStore, FileSystem fs,
ReportPublisher reportPublisher, BranchConfiguration branchConfiguration, AnalysisWarnings analysisWarnings, DocumentationLinkGenerator documentationLinkGenerator) {
this.configuration = configuration;
this.projectRepositories = projectRepositories;
this.componentStore = componentStore;
this.fs = fs;
this.branchConfiguration = branchConfiguration;
this.writer = reportPublisher.getWriter();
this.analysisWarnings = analysisWarnings;
this.documentationLinkGenerator = documentationLinkGenerator;
}
public void publish() {
if (configuration.isDisabled()) {
LOG.info("SCM Publisher is disabled");
return;
}
ScmProvider provider = configuration.provider();
if (provider == null) {
LOG.info("SCM Publisher No SCM system was detected. You can use the '" + CoreProperties.SCM_PROVIDER_KEY + "' property to explicitly specify it.");
return;
}
List<InputFile> filesToBlame = collectFilesToBlame(writer);
if (!filesToBlame.isEmpty()) {
String key = provider.key();
LOG.info("SCM Publisher SCM provider for this project is: " + key);
DefaultBlameOutput output = new DefaultBlameOutput(writer, analysisWarnings, filesToBlame, documentationLinkGenerator);
try {
provider.blameCommand().blame(new DefaultBlameInput(fs, filesToBlame), output);
} catch (Exception e) {
output.finish(false);
throw e;
}
output.finish(true);
}
}
private List<InputFile> collectFilesToBlame(ScannerReportWriter writer) {
if (configuration.forceReloadAll()) {
LOG.warn("Forced reloading of SCM data for all files.");
}
List<InputFile> filesToBlame = new LinkedList<>();
for (DefaultInputFile f : componentStore.allFilesToPublish()) {
if (configuration.forceReloadAll() || f.status() != Status.SAME) {
addIfNotEmpty(filesToBlame, f);
} else if (!branchConfiguration.isPullRequest()) {
FileData fileData = projectRepositories.fileData(componentStore.findModule(f).key(), f);
if (fileData == null || StringUtils.isEmpty(fileData.revision())) {
addIfNotEmpty(filesToBlame, f);
} else {
askToCopyDataFromPreviousAnalysis(f, writer);
}
}
}
return filesToBlame;
}
private static void askToCopyDataFromPreviousAnalysis(DefaultInputFile f, ScannerReportWriter writer) {
Builder scmBuilder = ScannerReport.Changesets.newBuilder();
scmBuilder.setComponentRef(f.scannerId());
scmBuilder.setCopyFromPrevious(true);
writer.writeComponentChangesets(scmBuilder.build());
}
private static void addIfNotEmpty(List<InputFile> filesToBlame, InputFile f) {
if (!f.isEmpty()) {
filesToBlame.add(f);
}
}
}
| 5,324 | 39.961538 | 169 | java |
sonarqube | sonarqube-master/sonar-scanner-engine/src/main/java/org/sonar/scanner/scm/ScmRevision.java | /*
* SonarQube
* Copyright (C) 2009-2023 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.scm;
import java.util.Optional;
import org.sonar.api.scanner.ScannerSide;
/**
* The SCM revision that triggered the analysis. It may be different than
* the effective revision checked-out on disk, as provided by {@link org.sonar.api.batch.scm.ScmProvider}.
*
* For instance on pull requests it's not the merge-commit that some CI services check out. It is
* the commit that was pushed by user to the branch.
*/
@ScannerSide
public interface ScmRevision {
Optional<String> get();
}
| 1,362 | 34.868421 | 106 | java |
sonarqube | sonarqube-master/sonar-scanner-engine/src/main/java/org/sonar/scanner/scm/ScmRevisionImpl.java | /*
* SonarQube
* Copyright (C) 2009-2023 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.scm;
import java.util.Optional;
import org.sonar.api.batch.scm.ScmProvider;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.sonar.scanner.bootstrap.ScannerProperties;
import org.sonar.scanner.ci.CiConfiguration;
import org.sonar.scanner.fs.InputModuleHierarchy;
import static org.apache.commons.lang.StringUtils.isBlank;
import static org.sonar.scanner.scan.ScanProperties.SCM_REVISION;
public class ScmRevisionImpl implements ScmRevision {
private static final Logger LOG = LoggerFactory.getLogger(ScmRevisionImpl.class);
private final CiConfiguration ciConfiguration;
private final ScannerProperties scannerConfiguration;
private final ScmConfiguration scmConfiguration;
private final InputModuleHierarchy moduleHierarchy;
public ScmRevisionImpl(CiConfiguration ciConfiguration, ScannerProperties scannerConfiguration, ScmConfiguration scmConfiguration, InputModuleHierarchy moduleHierarchy) {
this.ciConfiguration = ciConfiguration;
this.scannerConfiguration = scannerConfiguration;
this.scmConfiguration = scmConfiguration;
this.moduleHierarchy = moduleHierarchy;
}
@Override
public Optional<String> get() {
Optional<String> revision = Optional.ofNullable(scannerConfiguration.property(SCM_REVISION));
if (isSet(revision)) {
return revision;
}
revision = ciConfiguration.getScmRevision();
if (isSet(revision)) {
return revision;
}
ScmProvider scmProvider = scmConfiguration.provider();
if (scmProvider != null) {
try {
revision = Optional.ofNullable(scmProvider.revisionId(moduleHierarchy.root().getBaseDir()));
} catch (UnsupportedOperationException e) {
LOG.debug(e.getMessage());
revision = Optional.empty();
}
}
if (isSet(revision)) {
return revision;
}
return Optional.empty();
}
private static boolean isSet(Optional<String> opt) {
return opt.isPresent() && !isBlank(opt.get());
}
}
| 2,842 | 35.448718 | 172 | java |
sonarqube | sonarqube-master/sonar-scanner-engine/src/main/java/org/sonar/scanner/scm/package-info.java | /*
* SonarQube
* Copyright (C) 2009-2023 SonarSource SA
* mailto:info AT sonarsource DOT com
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 3 of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this program; if not, write to the Free Software Foundation,
* Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*/
@ParametersAreNonnullByDefault
package org.sonar.scanner.scm;
import javax.annotation.ParametersAreNonnullByDefault;
| 961 | 39.083333 | 75 | java |
sonarqube | sonarqube-master/sonar-scanner-engine/src/main/java/org/sonar/scanner/sensor/AbstractSensorOptimizer.java | /*
* SonarQube
* Copyright (C) 2009-2023 SonarSource SA
* mailto:info AT sonarsource DOT com
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 3 of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this program; if not, write to the Free Software Foundation,
* Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*/
package org.sonar.scanner.sensor;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
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.config.Configuration;
import org.sonar.api.batch.sensor.internal.DefaultSensorDescriptor;
public abstract class AbstractSensorOptimizer {
private static final Logger LOG = LoggerFactory.getLogger(AbstractSensorOptimizer.class);
private final FileSystem fs;
private final ActiveRules activeRules;
private final Configuration config;
public AbstractSensorOptimizer(FileSystem fs, ActiveRules activeRules, Configuration config) {
this.fs = fs;
this.activeRules = activeRules;
this.config = config;
}
/**
* Decide if the given Sensor should be executed.
*/
public boolean shouldExecute(DefaultSensorDescriptor descriptor) {
if (!fsCondition(descriptor)) {
LOG.debug("'{}' skipped because there is no related file in current project", descriptor.name());
return false;
}
if (!activeRulesCondition(descriptor)) {
LOG.debug("'{}' skipped because there is no related rule activated in the quality profile", descriptor.name());
return false;
}
if (!settingsCondition(descriptor)) {
LOG.debug("'{}' skipped because one of the required properties is missing", descriptor.name());
return false;
}
return true;
}
private boolean settingsCondition(DefaultSensorDescriptor descriptor) {
if (descriptor.configurationPredicate() != null) {
return descriptor.configurationPredicate().test(config);
}
return true;
}
private boolean activeRulesCondition(DefaultSensorDescriptor descriptor) {
if (!descriptor.ruleRepositories().isEmpty()) {
for (String repoKey : descriptor.ruleRepositories()) {
if (!activeRules.findByRepository(repoKey).isEmpty()) {
return true;
}
}
return false;
}
return true;
}
private boolean fsCondition(DefaultSensorDescriptor descriptor) {
if (!descriptor.languages().isEmpty() || descriptor.type() != null) {
FilePredicate langPredicate = descriptor.languages().isEmpty() ? fs.predicates().all() : fs.predicates().hasLanguages(descriptor.languages());
FilePredicate typePredicate = descriptor.type() == null ? fs.predicates().all() : fs.predicates().hasType(descriptor.type());
return fs.hasFiles(fs.predicates().and(langPredicate, typePredicate));
}
return true;
}
}
| 3,388 | 35.44086 | 148 | java |
sonarqube | sonarqube-master/sonar-scanner-engine/src/main/java/org/sonar/scanner/sensor/AbstractSensorWrapper.java | /*
* SonarQube
* Copyright (C) 2009-2023 SonarSource SA
* mailto:info AT sonarsource DOT com
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 3 of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this program; if not, write to the Free Software Foundation,
* Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*/
package org.sonar.scanner.sensor;
import org.sonar.api.batch.sensor.SensorContext;
import org.sonar.api.batch.sensor.internal.DefaultSensorDescriptor;
import org.sonar.api.scanner.sensor.ProjectSensor;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.sonar.scanner.scan.branch.BranchConfiguration;
import org.sonar.scanner.scan.branch.BranchType;
import org.sonar.scanner.scan.filesystem.MutableFileSystem;
public abstract class AbstractSensorWrapper<G extends ProjectSensor> {
private static final Logger LOGGER = LoggerFactory.getLogger(AbstractSensorWrapper.class);
private final G wrappedSensor;
private final SensorContext context;
private final MutableFileSystem fileSystem;
private final DefaultSensorDescriptor descriptor;
private final AbstractSensorOptimizer optimizer;
private final boolean isPullRequest;
public AbstractSensorWrapper(G sensor, SensorContext context, AbstractSensorOptimizer optimizer, MutableFileSystem fileSystem, BranchConfiguration branchConfiguration) {
this.wrappedSensor = sensor;
this.optimizer = optimizer;
this.context = context;
this.descriptor = new DefaultSensorDescriptor();
this.fileSystem = fileSystem;
this.isPullRequest = branchConfiguration.branchType() == BranchType.PULL_REQUEST;
sensor.describe(this.descriptor);
if (descriptor.name() == null) {
descriptor.name(sensor.getClass().getName());
}
}
public boolean shouldExecute() {
return optimizer.shouldExecute(descriptor);
}
public void analyse() {
boolean sensorIsRestricted = descriptor.isProcessesFilesIndependently() && isPullRequest;
if (sensorIsRestricted) {
LOGGER.info("Sensor {} is restricted to changed files only", descriptor.name());
}
fileSystem.setRestrictToChangedFiles(sensorIsRestricted);
wrappedSensor.execute(context);
}
public G wrappedSensor() {
return wrappedSensor;
}
@Override
public String toString() {
return descriptor.name();
}
public boolean isGlobal() {
return descriptor.isGlobal();
}
}
| 2,913 | 35.425 | 171 | java |
sonarqube | sonarqube-master/sonar-scanner-engine/src/main/java/org/sonar/scanner/sensor/DefaultSensorStorage.java | /*
* SonarQube
* Copyright (C) 2009-2023 SonarSource SA
* mailto:info AT sonarsource DOT com
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 3 of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this program; if not, write to the Free Software Foundation,
* Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*/
package org.sonar.scanner.sensor;
import java.io.Serializable;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.SortedMap;
import java.util.TreeMap;
import java.util.stream.Collectors;
import javax.annotation.Nullable;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
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.TextRange;
import org.sonar.api.batch.fs.internal.DefaultInputComponent;
import org.sonar.api.batch.fs.internal.DefaultInputFile;
import org.sonar.api.batch.fs.internal.DefaultInputModule;
import org.sonar.api.batch.measure.Metric;
import org.sonar.api.batch.measure.MetricFinder;
import org.sonar.api.batch.sensor.code.NewSignificantCode;
import org.sonar.api.batch.sensor.code.internal.DefaultSignificantCode;
import org.sonar.api.batch.sensor.coverage.NewCoverage;
import org.sonar.api.batch.sensor.coverage.internal.DefaultCoverage;
import org.sonar.api.batch.sensor.cpd.NewCpdTokens;
import org.sonar.api.batch.sensor.cpd.internal.DefaultCpdTokens;
import org.sonar.api.batch.sensor.error.AnalysisError;
import org.sonar.api.batch.sensor.highlighting.NewHighlighting;
import org.sonar.api.batch.sensor.highlighting.internal.DefaultHighlighting;
import org.sonar.api.batch.sensor.internal.SensorStorage;
import org.sonar.api.batch.sensor.issue.ExternalIssue;
import org.sonar.api.batch.sensor.issue.Issue;
import org.sonar.api.batch.sensor.measure.Measure;
import org.sonar.api.batch.sensor.measure.internal.DefaultMeasure;
import org.sonar.api.batch.sensor.rule.AdHocRule;
import org.sonar.api.batch.sensor.symbol.NewSymbolTable;
import org.sonar.api.batch.sensor.symbol.internal.DefaultSymbolTable;
import org.sonar.api.config.Configuration;
import org.sonar.api.measures.CoreMetrics;
import org.sonar.api.utils.KeyValueFormat;
import org.sonar.core.metric.ScannerMetrics;
import org.sonar.core.util.CloseableIterator;
import org.sonar.duplications.block.Block;
import org.sonar.duplications.internal.pmd.PmdBlockChunker;
import org.sonar.scanner.cpd.index.SonarCpdBlockIndex;
import org.sonar.scanner.issue.IssuePublisher;
import org.sonar.scanner.protocol.Constants;
import org.sonar.scanner.protocol.output.FileStructure;
import org.sonar.scanner.protocol.output.ScannerReport;
import org.sonar.scanner.protocol.output.ScannerReportWriter;
import org.sonar.scanner.report.ReportPublisher;
import org.sonar.scanner.report.ScannerReportUtils;
import org.sonar.scanner.repository.ContextPropertiesCache;
import org.sonar.scanner.scan.branch.BranchConfiguration;
import static java.lang.Math.max;
import static java.util.stream.Collectors.toList;
import static org.sonar.api.measures.CoreMetrics.COMMENT_LINES_DATA_KEY;
import static org.sonar.api.measures.CoreMetrics.LINES_KEY;
import static org.sonar.api.measures.CoreMetrics.PUBLIC_DOCUMENTED_API_DENSITY_KEY;
import static org.sonar.api.measures.CoreMetrics.TEST_SUCCESS_DENSITY_KEY;
public class DefaultSensorStorage implements SensorStorage {
private static final Logger LOG = LoggerFactory.getLogger(DefaultSensorStorage.class);
private static final int DEFAULT_CPD_MIN_LINES = 10;
/**
* The metrics that can be computed by analyzers but that are
* filtered from analysis reports. That allows analyzers to continue
* providing measures that are supported only by older versions.
* <p>
* The metrics in this list should not be declared in {@link ScannerMetrics#ALLOWED_CORE_METRICS}.
*/
private static final Set<String> DEPRECATED_METRICS_KEYS = Set.of(
COMMENT_LINES_DATA_KEY);
/**
* Metrics that were computed by analyzers and that are now computed
* by core
*/
private static final Set<String> NEWLY_CORE_METRICS_KEYS = Set.of(
// Computed on Scanner side
LINES_KEY,
// Computed on CE side
TEST_SUCCESS_DENSITY_KEY,
PUBLIC_DOCUMENTED_API_DENSITY_KEY);
private final MetricFinder metricFinder;
private final IssuePublisher moduleIssues;
private final ReportPublisher reportPublisher;
private final SonarCpdBlockIndex index;
private final ContextPropertiesCache contextPropertiesCache;
private final Configuration settings;
private final ScannerMetrics scannerMetrics;
private final BranchConfiguration branchConfiguration;
private final Set<String> alreadyLogged = new HashSet<>();
public DefaultSensorStorage(MetricFinder metricFinder, IssuePublisher moduleIssues, Configuration settings,
ReportPublisher reportPublisher, SonarCpdBlockIndex index,
ContextPropertiesCache contextPropertiesCache, ScannerMetrics scannerMetrics, BranchConfiguration branchConfiguration) {
this.metricFinder = metricFinder;
this.moduleIssues = moduleIssues;
this.settings = settings;
this.reportPublisher = reportPublisher;
this.index = index;
this.contextPropertiesCache = contextPropertiesCache;
this.scannerMetrics = scannerMetrics;
this.branchConfiguration = branchConfiguration;
}
@Override
public void store(Measure newMeasure) {
saveMeasure(newMeasure.inputComponent(), (DefaultMeasure<?>) newMeasure);
}
private void logOnce(String metricKey, String msg, Object... params) {
if (alreadyLogged.add(metricKey)) {
LOG.warn(msg, params);
}
}
private void saveMeasure(InputComponent component, DefaultMeasure<?> measure) {
if (component.isFile()) {
DefaultInputFile defaultInputFile = (DefaultInputFile) component;
defaultInputFile.setPublished(true);
}
if (component instanceof InputDir || (component instanceof DefaultInputModule && ((DefaultInputModule) component).definition().getParent() != null)) {
logOnce(measure.metric().key(), "Storing measures on folders or modules is deprecated. Provided value of metric '{}' is ignored.", measure.metric().key());
return;
}
if (DEPRECATED_METRICS_KEYS.contains(measure.metric().key())) {
logOnce(measure.metric().key(), "Metric '{}' is deprecated. Provided value is ignored.", measure.metric().key());
return;
}
Metric metric = metricFinder.findByKey(measure.metric().key());
if (metric == null) {
throw new UnsupportedOperationException("Unknown metric: " + measure.metric().key());
}
if (!measure.isFromCore() && NEWLY_CORE_METRICS_KEYS.contains(measure.metric().key())) {
logOnce(measure.metric().key(), "Metric '{}' is an internal metric computed by SonarQube. Provided value is ignored.", measure.metric().key());
return;
}
if (!scannerMetrics.getMetrics().contains(metric)) {
throw new UnsupportedOperationException("Metric '" + metric.key() + "' should not be computed by a Sensor");
}
if (((DefaultInputComponent) component).hasMeasureFor(metric)) {
throw new UnsupportedOperationException("Can not add the same measure twice on " + component + ": " + measure);
}
((DefaultInputComponent) component).setHasMeasureFor(metric);
if (metric.key().equals(CoreMetrics.EXECUTABLE_LINES_DATA_KEY)) {
if (component.isFile()) {
((DefaultInputFile) component).setExecutableLines(
KeyValueFormat.parseIntInt((String) measure.value()).entrySet().stream().filter(e -> e.getValue() > 0).map(Map.Entry::getKey).collect(Collectors.toSet()));
} else {
throw new IllegalArgumentException("Executable lines can only be saved on files");
}
}
reportPublisher.getWriter().appendComponentMeasure(((DefaultInputComponent) component).scannerId(), toReportMeasure(measure));
}
public boolean hasIssues(DefaultInputComponent inputComponent) {
return reportPublisher.getReader().hasIssues(inputComponent.scannerId());
}
public static ScannerReport.Measure toReportMeasure(DefaultMeasure measureToSave) {
ScannerReport.Measure.Builder builder = ScannerReport.Measure.newBuilder();
builder.setMetricKey(measureToSave.metric().key());
setValueAccordingToType(builder, measureToSave);
return builder.build();
}
private static void setValueAccordingToType(ScannerReport.Measure.Builder builder, DefaultMeasure<?> measure) {
Serializable value = measure.value();
Metric<?> metric = measure.metric();
if (Boolean.class.equals(metric.valueType())) {
builder.setBooleanValue(ScannerReport.Measure.BoolValue.newBuilder().setValue((Boolean) value));
} else if (Integer.class.equals(metric.valueType())) {
builder.setIntValue(ScannerReport.Measure.IntValue.newBuilder().setValue(((Number) value).intValue()));
} else if (Double.class.equals(metric.valueType())) {
builder.setDoubleValue(ScannerReport.Measure.DoubleValue.newBuilder().setValue(((Number) value).doubleValue()));
} else if (String.class.equals(metric.valueType())) {
builder.setStringValue(ScannerReport.Measure.StringValue.newBuilder().setValue((String) value));
} else if (Long.class.equals(metric.valueType())) {
builder.setLongValue(ScannerReport.Measure.LongValue.newBuilder().setValue(((Number) value).longValue()));
} else {
throw new UnsupportedOperationException("Unsupported type :" + metric.valueType());
}
}
private boolean shouldSkipStorage(DefaultInputFile defaultInputFile) {
return branchConfiguration.isPullRequest() && defaultInputFile.status() == InputFile.Status.SAME;
}
/**
* Thread safe assuming that each issues for each file are only written once.
*/
@Override
public void store(Issue issue) {
if (issue.primaryLocation().inputComponent() instanceof DefaultInputFile) {
DefaultInputFile defaultInputFile = (DefaultInputFile) issue.primaryLocation().inputComponent();
if (shouldSkipStorage(defaultInputFile)) {
return;
}
defaultInputFile.setPublished(true);
}
moduleIssues.initAndAddIssue(issue);
}
/**
* Thread safe assuming that each issues for each file are only written once.
*/
@Override
public void store(ExternalIssue externalIssue) {
if (externalIssue.primaryLocation().inputComponent() instanceof DefaultInputFile) {
DefaultInputFile defaultInputFile = (DefaultInputFile) externalIssue.primaryLocation().inputComponent();
defaultInputFile.setPublished(true);
}
moduleIssues.initAndAddExternalIssue(externalIssue);
}
@Override
public void store(AdHocRule adHocRule) {
ScannerReportWriter writer = reportPublisher.getWriter();
final ScannerReport.AdHocRule.Builder builder = ScannerReport.AdHocRule.newBuilder();
builder.setEngineId(adHocRule.engineId());
builder.setRuleId(adHocRule.ruleId());
builder.setName(adHocRule.name());
String description = adHocRule.description();
if (description != null) {
builder.setDescription(description);
}
builder.setSeverity(Constants.Severity.valueOf(adHocRule.severity().name()));
builder.setType(ScannerReport.IssueType.valueOf(adHocRule.type().name()));
writer.appendAdHocRule(builder.build());
}
@Override
public void store(NewHighlighting newHighlighting) {
DefaultHighlighting highlighting = (DefaultHighlighting) newHighlighting;
ScannerReportWriter writer = reportPublisher.getWriter();
DefaultInputFile inputFile = (DefaultInputFile) highlighting.inputFile();
if (shouldSkipStorage(inputFile)) {
return;
}
inputFile.setPublished(true);
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);
}
final ScannerReport.SyntaxHighlightingRule.Builder builder = ScannerReport.SyntaxHighlightingRule.newBuilder();
final ScannerReport.TextRange.Builder rangeBuilder = ScannerReport.TextRange.newBuilder();
writer.writeComponentSyntaxHighlighting(componentRef,
highlighting.getSyntaxHighlightingRuleSet().stream()
.map(input -> {
builder.setRange(rangeBuilder.setStartLine(input.range().start().line())
.setStartOffset(input.range().start().lineOffset())
.setEndLine(input.range().end().line())
.setEndOffset(input.range().end().lineOffset())
.build());
builder.setType(ScannerReportUtils.toProtocolType(input.getTextType()));
return builder.build();
}).collect(toList()));
}
@Override
public void store(NewSymbolTable newSymbolTable) {
DefaultSymbolTable symbolTable = (DefaultSymbolTable) newSymbolTable;
ScannerReportWriter writer = reportPublisher.getWriter();
DefaultInputFile inputFile = (DefaultInputFile) symbolTable.inputFile();
if (shouldSkipStorage(inputFile)) {
return;
}
inputFile.setPublished(true);
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());
}
final ScannerReport.Symbol.Builder builder = ScannerReport.Symbol.newBuilder();
final ScannerReport.TextRange.Builder rangeBuilder = ScannerReport.TextRange.newBuilder();
writer.writeComponentSymbols(componentRef,
symbolTable.getReferencesBySymbol().entrySet().stream()
.map(input -> {
builder.clear();
rangeBuilder.clear();
TextRange declaration = input.getKey();
builder.setDeclaration(rangeBuilder.setStartLine(declaration.start().line())
.setStartOffset(declaration.start().lineOffset())
.setEndLine(declaration.end().line())
.setEndOffset(declaration.end().lineOffset())
.build());
for (TextRange reference : input.getValue()) {
builder.addReference(rangeBuilder.setStartLine(reference.start().line())
.setStartOffset(reference.start().lineOffset())
.setEndLine(reference.end().line())
.setEndOffset(reference.end().lineOffset())
.build());
}
return builder.build();
}).collect(Collectors.toList()));
}
@Override
public void store(NewCoverage coverage) {
DefaultCoverage defaultCoverage = (DefaultCoverage) coverage;
DefaultInputFile inputFile = (DefaultInputFile) defaultCoverage.inputFile();
inputFile.setPublished(true);
SortedMap<Integer, ScannerReport.LineCoverage.Builder> coveragePerLine = reloadExistingCoverage(inputFile);
int lineCount = inputFile.lines();
mergeLineCoverageValues(lineCount, defaultCoverage.hitsByLine(), coveragePerLine, (value, builder) -> builder.setHits(builder.getHits() || value > 0));
mergeLineCoverageValues(lineCount, defaultCoverage.conditionsByLine(), coveragePerLine, (value, builder) -> builder.setConditions(max(value, builder.getConditions())));
mergeLineCoverageValues(lineCount, defaultCoverage.coveredConditionsByLine(), coveragePerLine,
(value, builder) -> builder.setCoveredConditions(max(value, builder.getCoveredConditions())));
reportPublisher.getWriter().writeComponentCoverage(inputFile.scannerId(),
coveragePerLine.values().stream().map(ScannerReport.LineCoverage.Builder::build).collect(Collectors.toList()));
}
private SortedMap<Integer, ScannerReport.LineCoverage.Builder> reloadExistingCoverage(DefaultInputFile inputFile) {
SortedMap<Integer, ScannerReport.LineCoverage.Builder> coveragePerLine = new TreeMap<>();
try (CloseableIterator<ScannerReport.LineCoverage> lineCoverageCloseableIterator = reportPublisher.getReader().readComponentCoverage(inputFile.scannerId())) {
while (lineCoverageCloseableIterator.hasNext()) {
final ScannerReport.LineCoverage lineCoverage = lineCoverageCloseableIterator.next();
coveragePerLine.put(lineCoverage.getLine(), ScannerReport.LineCoverage.newBuilder(lineCoverage));
}
}
return coveragePerLine;
}
interface LineCoverageOperation {
void apply(Integer value, ScannerReport.LineCoverage.Builder builder);
}
private static void mergeLineCoverageValues(int lineCount, SortedMap<Integer, Integer> valueByLine, SortedMap<Integer, ScannerReport.LineCoverage.Builder> coveragePerLine,
LineCoverageOperation op) {
for (Map.Entry<Integer, Integer> lineMeasure : valueByLine.entrySet()) {
int lineIdx = lineMeasure.getKey();
if (lineIdx <= lineCount) {
Integer value = lineMeasure.getValue();
op.apply(value, coveragePerLine.computeIfAbsent(lineIdx, line -> ScannerReport.LineCoverage.newBuilder().setLine(line)));
}
}
}
@Override
public void store(NewCpdTokens cpdTokens) {
DefaultCpdTokens defaultCpdTokens = (DefaultCpdTokens) cpdTokens;
DefaultInputFile inputFile = (DefaultInputFile) defaultCpdTokens.inputFile();
inputFile.setPublished(true);
PmdBlockChunker blockChunker = new PmdBlockChunker(getCpdBlockSize(inputFile.language()));
List<Block> blocks = blockChunker.chunk(inputFile.key(), defaultCpdTokens.getTokenLines());
index.insert(inputFile, blocks);
}
private int getCpdBlockSize(@Nullable String languageKey) {
if (languageKey == null) {
return DEFAULT_CPD_MIN_LINES;
}
return settings.getInt("sonar.cpd." + languageKey + ".minimumLines")
.orElseGet(() -> {
if ("cobol".equals(languageKey)) {
return 30;
}
if ("abap".equals(languageKey)) {
return 20;
}
return DEFAULT_CPD_MIN_LINES;
});
}
@Override
public void store(AnalysisError analysisError) {
DefaultInputFile defaultInputFile = (DefaultInputFile) analysisError.inputFile();
if (shouldSkipStorage(defaultInputFile)) {
return;
}
defaultInputFile.setPublished(true);
}
@Override
public void storeProperty(String key, String value) {
contextPropertiesCache.put(key, value);
}
@Override
public void store(NewSignificantCode newSignificantCode) {
DefaultSignificantCode significantCode = (DefaultSignificantCode) newSignificantCode;
ScannerReportWriter writer = reportPublisher.getWriter();
DefaultInputFile inputFile = (DefaultInputFile) significantCode.inputFile();
if (shouldSkipStorage(inputFile)) {
return;
}
inputFile.setPublished(true);
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());
}
List<ScannerReport.LineSgnificantCode> protobuf = significantCode.significantCodePerLine().values().stream()
.map(range -> ScannerReport.LineSgnificantCode.newBuilder()
.setLine(range.start().line())
.setStartOffset(range.start().lineOffset())
.setEndOffset(range.end().lineOffset())
.build())
.collect(Collectors.toList());
writer.writeComponentSignificantCode(componentRef, protobuf);
}
}
| 20,010 | 44.273756 | 173 | java |
sonarqube | sonarqube-master/sonar-scanner-engine/src/main/java/org/sonar/scanner/sensor/ExecutingSensorContext.java | /*
* SonarQube
* Copyright (C) 2009-2023 SonarSource SA
* mailto:info AT sonarsource DOT com
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 3 of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this program; if not, write to the Free Software Foundation,
* Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*/
package org.sonar.scanner.sensor;
import javax.annotation.CheckForNull;
public class ExecutingSensorContext {
private SensorId sensor;
public void setSensorExecuting(SensorId sensor) {
this.sensor = sensor;
}
public void clearExecutingSensor() {
this.sensor = null;
}
@CheckForNull
public SensorId getSensorExecuting() {
return sensor;
}
}
| 1,216 | 29.425 | 75 | java |
sonarqube | sonarqube-master/sonar-scanner-engine/src/main/java/org/sonar/scanner/sensor/ModuleSensorContext.java | /*
* SonarQube
* Copyright (C) 2009-2023 SonarSource SA
* mailto:info AT sonarsource DOT com
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 3 of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this program; if not, write to the Free Software Foundation,
* Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*/
package org.sonar.scanner.sensor;
import javax.annotation.concurrent.ThreadSafe;
import org.sonar.api.SonarRuntime;
import org.sonar.api.batch.fs.FileSystem;
import org.sonar.api.batch.fs.InputModule;
import org.sonar.api.batch.fs.internal.DefaultInputProject;
import org.sonar.api.batch.rule.ActiveRules;
import org.sonar.api.batch.sensor.cache.ReadCache;
import org.sonar.api.batch.sensor.cache.WriteCache;
import org.sonar.api.config.Configuration;
import org.sonar.api.config.Settings;
import org.sonar.scanner.cache.AnalysisCacheEnabled;
import org.sonar.scanner.scan.branch.BranchConfiguration;
@ThreadSafe
public class ModuleSensorContext extends ProjectSensorContext {
private final InputModule module;
public ModuleSensorContext(DefaultInputProject project, InputModule module, Configuration config, Settings mutableModuleSettings, FileSystem fs, ActiveRules activeRules,
DefaultSensorStorage sensorStorage, SonarRuntime sonarRuntime, BranchConfiguration branchConfiguration,
WriteCache writeCache, ReadCache readCache, AnalysisCacheEnabled analysisCacheEnabled, UnchangedFilesHandler unchangedFilesHandler) {
super(project, config, mutableModuleSettings, fs, activeRules, sensorStorage, sonarRuntime, branchConfiguration, writeCache, readCache, analysisCacheEnabled,
unchangedFilesHandler);
this.module = module;
}
@Override
public InputModule module() {
return module;
}
}
| 2,271 | 41.074074 | 171 | java |
sonarqube | sonarqube-master/sonar-scanner-engine/src/main/java/org/sonar/scanner/sensor/ModuleSensorExtensionDictionary.java | /*
* SonarQube
* Copyright (C) 2009-2023 SonarSource SA
* mailto:info AT sonarsource DOT com
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 3 of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this program; if not, write to the Free Software Foundation,
* Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*/
package org.sonar.scanner.sensor;
import java.util.Collection;
import java.util.stream.Collectors;
import org.sonar.api.batch.sensor.Sensor;
import org.sonar.core.platform.ExtensionContainer;
import org.sonar.scanner.bootstrap.AbstractExtensionDictionary;
import org.sonar.scanner.scan.branch.BranchConfiguration;
import org.sonar.scanner.scan.filesystem.MutableFileSystem;
public class ModuleSensorExtensionDictionary extends AbstractExtensionDictionary {
private final ModuleSensorContext sensorContext;
private final ModuleSensorOptimizer sensorOptimizer;
private final MutableFileSystem fileSystem;
private final BranchConfiguration branchConfiguration;
public ModuleSensorExtensionDictionary(ExtensionContainer componentContainer, ModuleSensorContext sensorContext, ModuleSensorOptimizer sensorOptimizer,
MutableFileSystem fileSystem, BranchConfiguration branchConfiguration) {
super(componentContainer);
this.sensorContext = sensorContext;
this.sensorOptimizer = sensorOptimizer;
this.fileSystem = fileSystem;
this.branchConfiguration = branchConfiguration;
}
public Collection<ModuleSensorWrapper> selectSensors(boolean global) {
Collection<Sensor> result = sort(getFilteredExtensions(Sensor.class, null));
return result.stream()
.map(s -> new ModuleSensorWrapper(s, sensorContext, sensorOptimizer, fileSystem, branchConfiguration))
.filter(s -> global == s.isGlobal() && s.shouldExecute())
.collect(Collectors.toList());
}
}
| 2,347 | 42.481481 | 153 | java |
sonarqube | sonarqube-master/sonar-scanner-engine/src/main/java/org/sonar/scanner/sensor/ModuleSensorOptimizer.java | /*
* SonarQube
* Copyright (C) 2009-2023 SonarSource SA
* mailto:info AT sonarsource DOT com
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 3 of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this program; if not, write to the Free Software Foundation,
* Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*/
package org.sonar.scanner.sensor;
import org.sonar.api.batch.fs.FileSystem;
import org.sonar.api.batch.rule.ActiveRules;
import org.sonar.api.config.Configuration;
public class ModuleSensorOptimizer extends AbstractSensorOptimizer {
public ModuleSensorOptimizer(FileSystem fs, ActiveRules activeRules, Configuration config) {
super(fs, activeRules, config);
}
}
| 1,217 | 35.909091 | 94 | java |
sonarqube | sonarqube-master/sonar-scanner-engine/src/main/java/org/sonar/scanner/sensor/ModuleSensorWrapper.java | /*
* SonarQube
* Copyright (C) 2009-2023 SonarSource SA
* mailto:info AT sonarsource DOT com
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 3 of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this program; if not, write to the Free Software Foundation,
* Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*/
package org.sonar.scanner.sensor;
import org.sonar.api.batch.sensor.Sensor;
import org.sonar.scanner.scan.branch.BranchConfiguration;
import org.sonar.scanner.scan.filesystem.MutableFileSystem;
public class ModuleSensorWrapper extends AbstractSensorWrapper<Sensor> {
public ModuleSensorWrapper(Sensor sensor, ModuleSensorContext context, ModuleSensorOptimizer optimizer, MutableFileSystem fileSystem, BranchConfiguration branchConfiguration) {
super(sensor, context, optimizer, fileSystem, branchConfiguration);
}
}
| 1,370 | 41.84375 | 178 | java |
sonarqube | sonarqube-master/sonar-scanner-engine/src/main/java/org/sonar/scanner/sensor/ModuleSensorsExecutor.java | /*
* SonarQube
* Copyright (C) 2009-2023 SonarSource SA
* mailto:info AT sonarsource DOT com
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 3 of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this program; if not, write to the Free Software Foundation,
* Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*/
package org.sonar.scanner.sensor;
import java.util.ArrayList;
import java.util.Collection;
import java.util.stream.Collectors;
import java.util.stream.Stream;
import org.sonar.api.batch.fs.internal.SensorStrategy;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.sonar.core.util.logs.Profiler;
import org.sonar.scanner.bootstrap.ScannerPluginRepository;
import org.sonar.api.batch.fs.internal.DefaultInputModule;
import org.sonar.scanner.fs.InputModuleHierarchy;
public class ModuleSensorsExecutor {
private static final Logger LOG = LoggerFactory.getLogger(ModuleSensorsExecutor.class);
private static final Profiler profiler = Profiler.create(LOG);
private final ModuleSensorExtensionDictionary selector;
private final SensorStrategy strategy;
private final ScannerPluginRepository pluginRepo;
private final ExecutingSensorContext executingSensorCtx;
private final boolean isRoot;
public ModuleSensorsExecutor(ModuleSensorExtensionDictionary selector, DefaultInputModule module, InputModuleHierarchy hierarchy,
SensorStrategy strategy, ScannerPluginRepository pluginRepo, ExecutingSensorContext executingSensorCtx) {
this.selector = selector;
this.strategy = strategy;
this.pluginRepo = pluginRepo;
this.executingSensorCtx = executingSensorCtx;
this.isRoot = hierarchy.isRoot(module);
}
public void execute() {
Collection<ModuleSensorWrapper> moduleSensors = new ArrayList<>();
withModuleStrategy(() -> moduleSensors.addAll(selector.selectSensors(false)));
Collection<ModuleSensorWrapper> deprecatedGlobalSensors = new ArrayList<>();
if (isRoot) {
deprecatedGlobalSensors.addAll(selector.selectSensors(true));
}
printSensors(moduleSensors, deprecatedGlobalSensors);
withModuleStrategy(() -> execute(moduleSensors));
if (isRoot) {
execute(deprecatedGlobalSensors);
}
}
private void printSensors(Collection<ModuleSensorWrapper> moduleSensors, Collection<ModuleSensorWrapper> globalSensors) {
String sensors = Stream
.concat(moduleSensors.stream(), globalSensors.stream())
.map(Object::toString)
.collect(Collectors.joining(" -> "));
LOG.debug("Sensors : {}", sensors);
}
private void withModuleStrategy(Runnable r) {
boolean orig = strategy.isGlobal();
strategy.setGlobal(false);
r.run();
strategy.setGlobal(orig);
}
private void execute(Collection<ModuleSensorWrapper> sensors) {
for (ModuleSensorWrapper sensor : sensors) {
SensorId sensorId = getSensorId(sensor);
profiler.startInfo("Sensor " + sensorId);
executingSensorCtx.setSensorExecuting(sensorId);
sensor.analyse();
executingSensorCtx.clearExecutingSensor();
profiler.stopInfo();
}
}
private SensorId getSensorId(ModuleSensorWrapper sensor) {
ClassLoader cl = getSensorClassLoader(sensor);
String pluginKey = pluginRepo.getPluginKey(cl);
return new SensorId(pluginKey, sensor.toString());
}
private static ClassLoader getSensorClassLoader(ModuleSensorWrapper sensor) {
return sensor.wrappedSensor().getClass().getClassLoader();
}
}
| 3,981 | 37.288462 | 131 | java |
sonarqube | sonarqube-master/sonar-scanner-engine/src/main/java/org/sonar/scanner/sensor/ProjectSensorContext.java | /*
* SonarQube
* Copyright (C) 2009-2023 SonarSource SA
* mailto:info AT sonarsource DOT com
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 3 of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this program; if not, write to the Free Software Foundation,
* Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*/
package org.sonar.scanner.sensor;
import java.io.Serializable;
import javax.annotation.concurrent.ThreadSafe;
import org.sonar.api.SonarRuntime;
import org.sonar.api.batch.fs.FileSystem;
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.DefaultInputProject;
import org.sonar.api.batch.rule.ActiveRules;
import org.sonar.api.batch.sensor.SensorContext;
import org.sonar.api.batch.sensor.cache.ReadCache;
import org.sonar.api.batch.sensor.cache.WriteCache;
import org.sonar.api.batch.sensor.code.NewSignificantCode;
import org.sonar.api.batch.sensor.code.internal.DefaultSignificantCode;
import org.sonar.api.batch.sensor.coverage.NewCoverage;
import org.sonar.api.batch.sensor.coverage.internal.DefaultCoverage;
import org.sonar.api.batch.sensor.cpd.NewCpdTokens;
import org.sonar.api.batch.sensor.cpd.internal.DefaultCpdTokens;
import org.sonar.api.batch.sensor.error.NewAnalysisError;
import org.sonar.api.batch.sensor.highlighting.NewHighlighting;
import org.sonar.api.batch.sensor.highlighting.internal.DefaultHighlighting;
import org.sonar.api.batch.sensor.issue.NewExternalIssue;
import org.sonar.api.batch.sensor.issue.NewIssue;
import org.sonar.api.batch.sensor.issue.internal.DefaultExternalIssue;
import org.sonar.api.batch.sensor.issue.internal.DefaultIssue;
import org.sonar.api.batch.sensor.measure.NewMeasure;
import org.sonar.api.batch.sensor.measure.internal.DefaultMeasure;
import org.sonar.api.batch.sensor.rule.NewAdHocRule;
import org.sonar.api.batch.sensor.rule.internal.DefaultAdHocRule;
import org.sonar.api.batch.sensor.symbol.NewSymbolTable;
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.cache.AnalysisCacheEnabled;
import org.sonar.scanner.scan.branch.BranchConfiguration;
import org.sonar.scanner.sensor.noop.NoOpNewAnalysisError;
@ThreadSafe
public class ProjectSensorContext implements SensorContext {
static final NoOpNewAnalysisError NO_OP_NEW_ANALYSIS_ERROR = new NoOpNewAnalysisError();
private final Settings mutableSettings;
private final FileSystem fs;
private final ActiveRules activeRules;
private final DefaultSensorStorage sensorStorage;
private final DefaultInputProject project;
private final SonarRuntime sonarRuntime;
private final Configuration config;
private final boolean skipUnchangedFiles;
private final UnchangedFilesHandler unchangedFilesHandler;
private final WriteCache writeCache;
private final ReadCache readCache;
private final AnalysisCacheEnabled analysisCacheEnabled;
public ProjectSensorContext(DefaultInputProject project, Configuration config, Settings mutableSettings, FileSystem fs, ActiveRules activeRules,
DefaultSensorStorage sensorStorage, SonarRuntime sonarRuntime, BranchConfiguration branchConfiguration, WriteCache writeCache, ReadCache readCache,
AnalysisCacheEnabled analysisCacheEnabled, UnchangedFilesHandler unchangedFilesHandler) {
this.project = project;
this.config = config;
this.mutableSettings = mutableSettings;
this.fs = fs;
this.activeRules = activeRules;
this.sensorStorage = sensorStorage;
this.sonarRuntime = sonarRuntime;
this.writeCache = writeCache;
this.readCache = readCache;
this.analysisCacheEnabled = analysisCacheEnabled;
this.skipUnchangedFiles = branchConfiguration.isPullRequest();
this.unchangedFilesHandler = unchangedFilesHandler;
}
@Override
public Settings settings() {
return mutableSettings;
}
@Override
public Configuration config() {
return config;
}
@Override
public FileSystem fileSystem() {
return fs;
}
@Override
public ActiveRules activeRules() {
return activeRules;
}
@Override
public InputModule module() {
throw new UnsupportedOperationException("No modules for global Sensors");
}
@Override
public InputProject project() {
return project;
}
@Override
public Version getSonarQubeVersion() {
return sonarRuntime.getApiVersion();
}
@Override
public SonarRuntime runtime() {
return sonarRuntime;
}
@Override
public <G extends Serializable> NewMeasure<G> newMeasure() {
return new DefaultMeasure<>(sensorStorage);
}
@Override
public NewIssue newIssue() {
return new DefaultIssue(project, sensorStorage);
}
@Override
public NewExternalIssue newExternalIssue() {
return new DefaultExternalIssue(project, sensorStorage);
}
@Override
public NewAdHocRule newAdHocRule() {
return new DefaultAdHocRule(sensorStorage);
}
@Override
public NewHighlighting newHighlighting() {
return new DefaultHighlighting(sensorStorage);
}
@Override
public NewSymbolTable newSymbolTable() {
return new DefaultSymbolTable(sensorStorage);
}
@Override
public NewCoverage newCoverage() {
return new DefaultCoverage(sensorStorage);
}
@Override
public NewCpdTokens newCpdTokens() {
return new DefaultCpdTokens(sensorStorage);
}
@Override
public NewAnalysisError newAnalysisError() {
return NO_OP_NEW_ANALYSIS_ERROR;
}
@Override
public boolean isCancelled() {
return false;
}
@Override
public void addContextProperty(String key, String value) {
sensorStorage.storeProperty(key, value);
}
@Override
public void markForPublishing(InputFile inputFile) {
DefaultInputFile file = (DefaultInputFile) inputFile;
file.setPublished(true);
}
@Override
public void markAsUnchanged(InputFile inputFile) {
unchangedFilesHandler.markAsUnchanged((DefaultInputFile) inputFile);
}
@Override
public WriteCache nextCache() {
return writeCache;
}
@Override
public ReadCache previousCache() {
return readCache;
}
@Override
public boolean isCacheEnabled() {
return analysisCacheEnabled.isEnabled();
}
@Override
public NewSignificantCode newSignificantCode() {
return new DefaultSignificantCode(sensorStorage);
}
@Override
public boolean canSkipUnchangedFiles() {
return this.skipUnchangedFiles;
}
}
| 7,125 | 30.39207 | 151 | java |
sonarqube | sonarqube-master/sonar-scanner-engine/src/main/java/org/sonar/scanner/sensor/ProjectSensorExtensionDictionary.java | /*
* SonarQube
* Copyright (C) 2009-2023 SonarSource SA
* mailto:info AT sonarsource DOT com
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 3 of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this program; if not, write to the Free Software Foundation,
* Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*/
package org.sonar.scanner.sensor;
import java.util.Collection;
import java.util.List;
import java.util.stream.Collectors;
import org.sonar.api.scanner.sensor.ProjectSensor;
import org.sonar.core.platform.SpringComponentContainer;
import org.sonar.scanner.bootstrap.AbstractExtensionDictionary;
import org.sonar.scanner.scan.branch.BranchConfiguration;
import org.sonar.scanner.scan.filesystem.MutableFileSystem;
public class ProjectSensorExtensionDictionary extends AbstractExtensionDictionary {
private final ProjectSensorContext sensorContext;
private final ProjectSensorOptimizer sensorOptimizer;
private final MutableFileSystem fileSystem;
private final BranchConfiguration branchConfiguration;
public ProjectSensorExtensionDictionary(SpringComponentContainer componentContainer, ProjectSensorContext sensorContext, ProjectSensorOptimizer sensorOptimizer,
MutableFileSystem fileSystem, BranchConfiguration branchConfiguration) {
super(componentContainer);
this.sensorContext = sensorContext;
this.sensorOptimizer = sensorOptimizer;
this.fileSystem = fileSystem;
this.branchConfiguration = branchConfiguration;
}
public List<ProjectSensorWrapper> selectSensors() {
Collection<ProjectSensor> result = sort(getFilteredExtensions(ProjectSensor.class, null));
return result.stream()
.map(s -> new ProjectSensorWrapper(s, sensorContext, sensorOptimizer, fileSystem, branchConfiguration))
.filter(ProjectSensorWrapper::shouldExecute)
.collect(Collectors.toList());
}
}
| 2,380 | 42.290909 | 162 | java |
sonarqube | sonarqube-master/sonar-scanner-engine/src/main/java/org/sonar/scanner/sensor/ProjectSensorOptimizer.java | /*
* SonarQube
* Copyright (C) 2009-2023 SonarSource SA
* mailto:info AT sonarsource DOT com
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 3 of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this program; if not, write to the Free Software Foundation,
* Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*/
package org.sonar.scanner.sensor;
import org.sonar.api.batch.rule.ActiveRules;
import org.sonar.scanner.scan.ProjectConfiguration;
import org.sonar.scanner.scan.filesystem.DefaultProjectFileSystem;
public class ProjectSensorOptimizer extends AbstractSensorOptimizer {
public ProjectSensorOptimizer(DefaultProjectFileSystem fs, ActiveRules activeRules, ProjectConfiguration config) {
super(fs, activeRules, config);
}
}
| 1,274 | 37.636364 | 116 | java |
sonarqube | sonarqube-master/sonar-scanner-engine/src/main/java/org/sonar/scanner/sensor/ProjectSensorWrapper.java | /*
* SonarQube
* Copyright (C) 2009-2023 SonarSource SA
* mailto:info AT sonarsource DOT com
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 3 of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this program; if not, write to the Free Software Foundation,
* Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*/
package org.sonar.scanner.sensor;
import org.sonar.api.scanner.sensor.ProjectSensor;
import org.sonar.scanner.scan.branch.BranchConfiguration;
import org.sonar.scanner.scan.filesystem.MutableFileSystem;
public class ProjectSensorWrapper extends AbstractSensorWrapper<ProjectSensor> {
public ProjectSensorWrapper(ProjectSensor sensor, ProjectSensorContext context, ProjectSensorOptimizer optimizer,
MutableFileSystem fileSystem, BranchConfiguration branchConfiguration) {
super(sensor, context, optimizer, fileSystem, branchConfiguration);
}
}
| 1,402 | 40.264706 | 115 | java |
sonarqube | sonarqube-master/sonar-scanner-engine/src/main/java/org/sonar/scanner/sensor/ProjectSensorsExecutor.java | /*
* SonarQube
* Copyright (C) 2009-2023 SonarSource SA
* mailto:info AT sonarsource DOT com
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 3 of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this program; if not, write to the Free Software Foundation,
* Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*/
package org.sonar.scanner.sensor;
import java.util.List;
import java.util.stream.Collectors;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.sonar.core.util.logs.Profiler;
import org.sonar.scanner.bootstrap.ScannerPluginRepository;
public class ProjectSensorsExecutor {
private static final Logger LOG = LoggerFactory.getLogger(ProjectSensorsExecutor.class);
private static final Profiler profiler = Profiler.create(LOG);
private final ProjectSensorExtensionDictionary selector;
private final ScannerPluginRepository pluginRepo;
private final ExecutingSensorContext executingSensorCtx;
public ProjectSensorsExecutor(ProjectSensorExtensionDictionary selector, ScannerPluginRepository pluginRepo, ExecutingSensorContext executingSensorCtx) {
this.selector = selector;
this.pluginRepo = pluginRepo;
this.executingSensorCtx = executingSensorCtx;
}
public void execute() {
List<ProjectSensorWrapper> sensors = selector.selectSensors();
LOG.debug("Sensors : {}", sensors.stream()
.map(Object::toString)
.collect(Collectors.joining(" -> ")));
for (ProjectSensorWrapper sensor : sensors) {
SensorId sensorId = getSensorId(sensor);
executingSensorCtx.setSensorExecuting(sensorId);
profiler.startInfo("Sensor " + sensorId);
sensor.analyse();
profiler.stopInfo();
executingSensorCtx.clearExecutingSensor();
}
}
private SensorId getSensorId(ProjectSensorWrapper sensor) {
ClassLoader cl = getSensorClassLoader(sensor);
String pluginKey = pluginRepo.getPluginKey(cl);
return new SensorId(pluginKey, sensor.toString());
}
private static ClassLoader getSensorClassLoader(ProjectSensorWrapper sensor) {
return sensor.wrappedSensor().getClass().getClassLoader();
}
}
| 2,638 | 37.808824 | 155 | java |
sonarqube | sonarqube-master/sonar-scanner-engine/src/main/java/org/sonar/scanner/sensor/SensorId.java | /*
* SonarQube
* Copyright (C) 2009-2023 SonarSource SA
* mailto:info AT sonarsource DOT com
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 3 of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this program; if not, write to the Free Software Foundation,
* Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*/
package org.sonar.scanner.sensor;
import java.util.Objects;
import javax.annotation.Nullable;
import static org.sonar.api.utils.Preconditions.checkNotNull;
public class SensorId {
private final String sensorName;
@Nullable
private final String pluginKey;
public SensorId(@Nullable String pluginKey, String sensorName) {
checkNotNull(sensorName);
this.pluginKey = pluginKey;
this.sensorName = sensorName;
}
@Nullable
public String getPluginKey() {
return pluginKey;
}
public String getSensorName() {
return sensorName;
}
@Override
public String toString() {
if (pluginKey == null) {
return sensorName;
} else {
return sensorName + " [" + pluginKey + "]";
}
}
@Override
public boolean equals(Object o) {
if (this == o) {
return true;
}
if (o == null || getClass() != o.getClass()) {
return false;
}
SensorId sensorId = (SensorId) o;
return Objects.equals(sensorName, sensorId.sensorName) && Objects.equals(pluginKey, sensorId.pluginKey);
}
@Override
public int hashCode() {
return Objects.hash(sensorName, pluginKey);
}
}
| 1,994 | 26.328767 | 108 | java |
sonarqube | sonarqube-master/sonar-scanner-engine/src/main/java/org/sonar/scanner/sensor/UnchangedFilesHandler.java | /*
* SonarQube
* Copyright (C) 2009-2023 SonarSource SA
* mailto:info AT sonarsource DOT com
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 3 of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this program; if not, write to the Free Software Foundation,
* Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*/
package org.sonar.scanner.sensor;
import java.util.Objects;
import java.util.Set;
import org.sonar.api.batch.fs.InputFile;
import org.sonar.api.batch.fs.internal.DefaultInputFile;
import org.sonar.api.config.Configuration;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.sonar.scanner.scan.branch.BranchConfiguration;
public class UnchangedFilesHandler {
private static final Logger LOG = LoggerFactory.getLogger(UnchangedFilesHandler.class);
private static final Set<SensorId> ENABLED_SENSORS = Set.of(
new SensorId("cpp", "CFamily"),
new SensorId("cobol", "CobolSquidSensor"),
// for ITs
new SensorId("xoo", "Mark As Unchanged Sensor"));
private static final String ENABLE_PROPERTY_KEY = "sonar.unchangedFiles.optimize";
private final boolean featureActive;
private final ExecutingSensorContext executingSensorContext;
public UnchangedFilesHandler(Configuration configuration, BranchConfiguration branchConfiguration, ExecutingSensorContext executingSensorContext) {
this.executingSensorContext = executingSensorContext;
this.featureActive = getFeatureActivationStatus(configuration, branchConfiguration);
}
private static boolean getFeatureActivationStatus(Configuration configuration, BranchConfiguration branchConfiguration) {
boolean isPropertyEnabled = configuration.getBoolean(ENABLE_PROPERTY_KEY).orElse(false);
if (!isPropertyEnabled) {
return false;
}
if (branchConfiguration.isPullRequest() || !Objects.equals(branchConfiguration.branchName(), branchConfiguration.referenceBranchName())) {
LOG.debug("Optimization for unchanged files not enabled because it's not an analysis of a branch with a previous analysis");
return false;
}
LOG.info("Optimization for unchanged files enabled");
return true;
}
public void markAsUnchanged(DefaultInputFile file) {
if (isFeatureActive()) {
if (file.status() != InputFile.Status.SAME) {
LOG.error("File '{}' was marked as unchanged but its status is {}", file.getProjectRelativePath(), file.status());
} else {
LOG.debug("File '{}' marked as unchanged", file.getProjectRelativePath());
file.setMarkedAsUnchanged(true);
}
}
}
private boolean isFeatureActive() {
return featureActive && executingSensorContext.getSensorExecuting() != null && ENABLED_SENSORS.contains(executingSensorContext.getSensorExecuting());
}
}
| 3,283 | 42.786667 | 153 | java |
sonarqube | sonarqube-master/sonar-scanner-engine/src/main/java/org/sonar/scanner/sensor/package-info.java | /*
* SonarQube
* Copyright (C) 2009-2023 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.scanner.sensor;
| 925 | 41.090909 | 75 | java |
sonarqube | sonarqube-master/sonar-scanner-engine/src/main/java/org/sonar/scanner/sensor/noop/NoOpNewAnalysisError.java | /*
* SonarQube
* Copyright (C) 2009-2023 SonarSource SA
* mailto:info AT sonarsource DOT com
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 3 of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this program; if not, write to the Free Software Foundation,
* Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*/
package org.sonar.scanner.sensor.noop;
import org.sonar.api.batch.fs.InputFile;
import org.sonar.api.batch.fs.TextPointer;
import org.sonar.api.batch.sensor.error.NewAnalysisError;
public class NoOpNewAnalysisError implements NewAnalysisError {
@Override
public NewAnalysisError onFile(InputFile inputFile) {
// no op
return this;
}
@Override
public NewAnalysisError message(String message) {
// no op
return this;
}
@Override
public NewAnalysisError at(TextPointer location) {
// no op
return this;
}
@Override
public void save() {
// no op
}
}
| 1,448 | 26.865385 | 75 | java |
sonarqube | sonarqube-master/sonar-scanner-engine/src/main/java/org/sonar/scanner/sensor/noop/package-info.java | /*
* SonarQube
* Copyright (C) 2009-2023 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.scanner.sensor.noop;
| 930 | 41.318182 | 75 | java |
sonarqube | sonarqube-master/sonar-scanner-engine/src/main/java/org/sonar/scanner/source/ZeroCoverageSensor.java | /*
* SonarQube
* Copyright (C) 2009-2023 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.source;
import java.util.Set;
import org.sonar.api.batch.Phase;
import org.sonar.api.batch.fs.FileSystem;
import org.sonar.api.batch.fs.InputFile;
import org.sonar.api.batch.fs.InputFile.Type;
import org.sonar.api.batch.fs.internal.DefaultInputFile;
import org.sonar.api.batch.sensor.SensorContext;
import org.sonar.api.batch.sensor.SensorDescriptor;
import org.sonar.api.batch.sensor.coverage.NewCoverage;
import org.sonar.api.scanner.sensor.ProjectSensor;
import org.sonar.scanner.report.ReportPublisher;
@Phase(name = Phase.Name.POST)
public final class ZeroCoverageSensor implements ProjectSensor {
private final ReportPublisher reportPublisher;
public ZeroCoverageSensor(ReportPublisher reportPublisher) {
this.reportPublisher = reportPublisher;
}
@Override
public void describe(SensorDescriptor descriptor) {
descriptor.name("Zero Coverage Sensor");
}
@Override
public void execute(final SensorContext context) {
FileSystem fs = context.fileSystem();
for (InputFile f : fs.inputFiles(fs.predicates().hasType(Type.MAIN))) {
if (((DefaultInputFile) f).isExcludedForCoverage()) {
continue;
}
if (!isCoverageAlreadyDefined(f)) {
((DefaultInputFile) f).getExecutableLines().ifPresent(execLines -> storeZeroCoverageForEachExecutableLine(context, f, execLines));
}
}
}
private static void storeZeroCoverageForEachExecutableLine(final SensorContext context, InputFile f, Set<Integer> executableLines) {
NewCoverage newCoverage = context.newCoverage().onFile(f);
for (Integer lineIdx : executableLines) {
if (lineIdx <= f.lines()) {
newCoverage.lineHits(lineIdx, 0);
}
}
newCoverage.save();
}
private boolean isCoverageAlreadyDefined(InputFile f) {
return reportPublisher.getReader().hasCoverage(((DefaultInputFile) f).scannerId());
}
}
| 2,738 | 35.039474 | 138 | java |
sonarqube | sonarqube-master/sonar-scanner-engine/src/main/java/org/sonar/scanner/source/package-info.java | /*
* SonarQube
* Copyright (C) 2009-2023 SonarSource SA
* mailto:info AT sonarsource DOT com
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 3 of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this program; if not, write to the Free Software Foundation,
* Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*/
@ParametersAreNonnullByDefault
package org.sonar.scanner.source;
import javax.annotation.ParametersAreNonnullByDefault;
| 964 | 39.208333 | 75 | java |
sonarqube | sonarqube-master/sonar-scanner-engine/src/main/java/org/sonar/scanner/util/ProgressReport.java | /*
* SonarQube
* Copyright (C) 2009-2023 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.util;
import javax.annotation.Nullable;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
public class ProgressReport implements Runnable {
private static final Logger LOG = LoggerFactory.getLogger(ProgressReport.class);
private final long period;
private long startTime;
private String message = "";
private final Thread thread;
private String stopMessage = null;
public ProgressReport(String threadName, long period) {
this.period = period;
thread = new Thread(this);
thread.setName(threadName);
thread.setDaemon(true);
}
@Override
public void run() {
while (!Thread.interrupted()) {
try {
Thread.sleep(period);
log(message);
} catch (InterruptedException e) {
break;
}
}
if (stopMessage != null) {
log(stopMessage);
}
}
public void start(String startMessage) {
log(startMessage);
thread.start();
startTime = currentTimeMillis();
}
public void message(String message) {
this.message = message;
}
public void stop(@Nullable String stopMessage) {
this.stopMessage = stopMessage;
thread.interrupt();
try {
thread.join();
} catch (InterruptedException e) {
// Ignore
}
}
public void stopAndLogTotalTime(@Nullable String stopMessage) {
long stopTime = currentTimeMillis();
stopMessage += String.format(" (done) | time=%dms", timeDiff(stopTime, startTime));
stop(stopMessage);
}
private static void log(String message) {
synchronized (LOG) {
LOG.info(message);
LOG.notifyAll();
}
}
private static long currentTimeMillis() {
return System.currentTimeMillis();
}
private static long timeDiff(long endTime, long startTime) {
return endTime - startTime;
}
}
| 2,656 | 26.112245 | 87 | java |
sonarqube | sonarqube-master/sonar-scanner-engine/src/main/java/org/sonar/scanner/util/package-info.java | /*
* SonarQube
* Copyright (C) 2009-2023 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.scanner.util;
| 924 | 39.217391 | 75 | java |
sonarqube | sonarqube-master/sonar-scanner-engine/src/main/java/org/sonar/scm/git/ChangedFile.java | /*
* SonarQube
* Copyright (C) 2009-2023 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.scm.git;
import java.nio.file.Path;
import java.util.Objects;
import javax.annotation.CheckForNull;
import javax.annotation.Nullable;
import javax.annotation.concurrent.Immutable;
import org.sonar.api.batch.fs.internal.DefaultInputFile;
@Immutable
public class ChangedFile {
private final Path absoluteFilePath;
private final String oldRelativeFilePathReference;
private ChangedFile(Path absoluteFilePath, @Nullable String oldRelativeFilePathReference) {
this.absoluteFilePath = absoluteFilePath;
this.oldRelativeFilePathReference = oldRelativeFilePathReference;
}
public Path getAbsolutFilePath() {
return absoluteFilePath;
}
@CheckForNull
public String getOldRelativeFilePathReference() {
return oldRelativeFilePathReference;
}
public boolean isMovedFile() {
return this.getOldRelativeFilePathReference() != null;
}
public static ChangedFile of(Path path) {
return new ChangedFile(path, null);
}
public static ChangedFile of(Path path, @Nullable String oldRelativeFilePathReference) {
return new ChangedFile(path, oldRelativeFilePathReference);
}
public static ChangedFile of(DefaultInputFile file) {
return new ChangedFile(file.path(), file.oldRelativePath());
}
@Override
public boolean equals(Object o) {
if (this == o) {
return true;
}
if (o == null || getClass() != o.getClass()) {
return false;
}
ChangedFile that = (ChangedFile) o;
return Objects.equals(oldRelativeFilePathReference, that.oldRelativeFilePathReference)
&& Objects.equals(absoluteFilePath, that.absoluteFilePath);
}
@Override
public int hashCode() {
return Objects.hash(oldRelativeFilePathReference, absoluteFilePath);
}
}
| 2,596 | 29.552941 | 93 | java |
sonarqube | sonarqube-master/sonar-scanner-engine/src/main/java/org/sonar/scm/git/ChangedLinesComputer.java | /*
* SonarQube
* Copyright (C) 2009-2023 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.scm.git;
import java.io.OutputStream;
import java.util.HashSet;
import java.util.Set;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
class ChangedLinesComputer {
private final Tracker tracker = new Tracker();
private final OutputStream receiver = new OutputStream() {
StringBuilder sb = new StringBuilder();
@Override
public void write(int b) {
sb.append((char) b);
if (b == '\n') {
tracker.parseLine(sb.toString());
sb.setLength(0);
}
}
};
/**
* The OutputStream to pass to JGit's diff command.
*/
OutputStream receiver() {
return receiver;
}
/**
* From a stream of unified diff lines emitted by Git <strong>for a single file</strong>,
* compute the line numbers that should be considered changed.
* Example input:
* <pre>
* diff --git a/lao.txt b/lao.txt
* index 635ef2c..7f050f2 100644
* --- a/lao.txt
* +++ b/lao.txt
* @@ -1,7 +1,6 @@
* -The Way that can be told of is not the eternal Way;
* -The name that can be named is not the eternal name.
* The Nameless is the origin of Heaven and Earth;
* -The Named is the mother of all things.
* +The named is the mother of all things.
* +
* Therefore let there always be non-being,
* so we may see their subtlety,
* And let there always be being,
* @@ -9,3 +8,6 @@ And let there always be being,
* The two are the same,
* But after they are produced,
* they have different names.
* +They both may be called deep and profound.
* +Deeper and more profound,
* +The door of all subtleties!names.
* </pre>
* See also: http://www.gnu.org/software/diffutils/manual/html_node/Example-Unified.html#Example-Unified
*/
Set<Integer> changedLines() {
return tracker.changedLines();
}
private static class Tracker {
private static final Pattern START_LINE_IN_TARGET = Pattern.compile(" \\+(\\d+)");
private final Set<Integer> changedLines = new HashSet<>();
private boolean foundStart = false;
private int lineNumInTarget;
private void parseLine(String line) {
if (line.startsWith("@@ ")) {
Matcher matcher = START_LINE_IN_TARGET.matcher(line);
if (!matcher.find()) {
throw new IllegalStateException("Invalid block header on line " + line);
}
foundStart = true;
lineNumInTarget = Integer.parseInt(matcher.group(1));
} else if (foundStart) {
char firstChar = line.charAt(0);
if (firstChar == ' ') {
lineNumInTarget++;
} else if (firstChar == '+') {
changedLines.add(lineNumInTarget);
lineNumInTarget++;
}
}
}
Set<Integer> changedLines() {
return changedLines;
}
}
}
| 3,638 | 30.102564 | 106 | java |
sonarqube | sonarqube-master/sonar-scanner-engine/src/main/java/org/sonar/scm/git/CompositeBlameCommand.java | /*
* SonarQube
* Copyright (C) 2009-2023 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.scm.git;
import java.io.File;
import java.io.IOException;
import java.nio.file.Files;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import java.util.Set;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;
import org.eclipse.jgit.api.Git;
import org.eclipse.jgit.api.errors.GitAPIException;
import org.eclipse.jgit.diff.RawTextComparator;
import org.eclipse.jgit.lib.Constants;
import org.eclipse.jgit.lib.ObjectId;
import org.eclipse.jgit.lib.Repository;
import org.eclipse.jgit.revwalk.RevCommit;
import org.eclipse.jgit.revwalk.RevWalk;
import org.eclipse.jgit.treewalk.TreeWalk;
import org.sonar.api.batch.fs.InputFile;
import org.sonar.api.batch.scm.BlameCommand;
import org.sonar.api.batch.scm.BlameLine;
import org.sonar.api.notifications.AnalysisWarnings;
import org.sonar.api.scan.filesystem.PathResolver;
import org.sonar.api.utils.log.Logger;
import org.sonar.api.utils.log.Loggers;
import org.sonar.api.utils.log.Profiler;
import org.sonar.scm.git.blame.BlameResult;
import org.sonar.scm.git.blame.RepositoryBlameCommand;
import org.sonar.scm.git.strategy.BlameStrategy;
import org.sonar.scm.git.strategy.DefaultBlameStrategy.BlameAlgorithmEnum;
import static java.util.Optional.ofNullable;
import static org.sonar.scm.git.strategy.DefaultBlameStrategy.BlameAlgorithmEnum.GIT_FILES_BLAME;
public class CompositeBlameCommand extends BlameCommand {
private static final Logger LOG = Loggers.get(CompositeBlameCommand.class);
private final AnalysisWarnings analysisWarnings;
private final PathResolver pathResolver;
private final JGitBlameCommand jgitCmd;
private final NativeGitBlameCommand nativeCmd;
private boolean nativeGitEnabled = false;
private final BlameStrategy blameStrategy;
public CompositeBlameCommand(AnalysisWarnings analysisWarnings, PathResolver pathResolver, JGitBlameCommand jgitCmd,
NativeGitBlameCommand nativeCmd, BlameStrategy blameStrategy) {
this.analysisWarnings = analysisWarnings;
this.pathResolver = pathResolver;
this.blameStrategy = blameStrategy;
this.jgitCmd = jgitCmd;
this.nativeCmd = nativeCmd;
}
@Override
public void blame(BlameInput input, BlameOutput output) {
File basedir = input.fileSystem().baseDir();
try (Repository repo = JGitUtils.buildRepository(basedir.toPath())) {
File gitBaseDir = repo.getWorkTree();
if (cloneIsInvalid(gitBaseDir)) {
return;
}
Profiler profiler = Profiler.create(LOG);
profiler.startDebug("Collecting committed files");
Map<String, InputFile> inputFileByGitRelativePath = getCommittedFilesToBlame(repo, gitBaseDir, input);
profiler.stopDebug();
BlameAlgorithmEnum blameAlgorithmEnum = this.blameStrategy.getBlameAlgorithm(Runtime.getRuntime().availableProcessors(), inputFileByGitRelativePath.size());
LOG.debug("Using {} strategy to blame files", blameAlgorithmEnum);
if (blameAlgorithmEnum == GIT_FILES_BLAME) {
blameWithFilesGitCommand(output, repo, inputFileByGitRelativePath);
} else {
blameWithNativeGitCommand(output, repo, inputFileByGitRelativePath, gitBaseDir);
}
}
}
private Map<String, InputFile> getCommittedFilesToBlame(Repository repo, File gitBaseDir, BlameInput input) {
Set<String> committedFiles = collectAllCommittedFiles(repo);
Map<String, InputFile> inputFileByGitRelativePath = new HashMap<>();
for (InputFile inputFile : input.filesToBlame()) {
String relative = pathResolver.relativePath(gitBaseDir, inputFile.file());
if (relative == null || !committedFiles.contains(relative)) {
continue;
}
inputFileByGitRelativePath.put(relative, inputFile);
}
return inputFileByGitRelativePath;
}
private void blameWithNativeGitCommand(BlameOutput output, Repository repo, Map<String, InputFile> inputFileByGitRelativePath, File gitBaseDir) {
try (Git git = Git.wrap(repo)) {
nativeGitEnabled = nativeCmd.checkIfEnabled();
ExecutorService executorService = Executors.newFixedThreadPool(Runtime.getRuntime().availableProcessors(), new GitThreadFactory());
for (Map.Entry<String, InputFile> e : inputFileByGitRelativePath.entrySet()) {
InputFile inputFile = e.getValue();
String filename = e.getKey();
// exceptions thrown by the blame method will be ignored
executorService.submit(() -> blame(output, git, gitBaseDir, inputFile, filename));
}
executorService.shutdown();
try {
executorService.awaitTermination(Long.MAX_VALUE, TimeUnit.SECONDS);
} catch (InterruptedException e) {
LOG.info("Git blame interrupted", e);
Thread.currentThread().interrupt();
}
}
}
private static Set<String> collectAllCommittedFiles(Repository repo) {
try {
Set<String> files = new HashSet<>();
Optional<ObjectId> headCommit = ofNullable(repo.resolve(Constants.HEAD));
if (headCommit.isEmpty()) {
LOG.warn("Could not find HEAD commit");
return files;
}
try (RevWalk revWalk = new RevWalk(repo)) {
RevCommit head = revWalk.parseCommit(headCommit.get());
try (TreeWalk treeWalk = new TreeWalk(repo)) {
treeWalk.addTree(head.getTree());
treeWalk.setRecursive(true);
while (treeWalk.next()) {
String path = treeWalk.getPathString();
files.add(path);
}
}
}
return files;
} catch (IOException e) {
throw new IllegalStateException("Failed to find all committed files", e);
}
}
private void blame(BlameOutput output, Git git, File gitBaseDir, InputFile inputFile, String filename) {
List<BlameLine> blame = null;
if (nativeGitEnabled) {
try {
LOG.debug("Blame file (native) {}", filename);
blame = nativeCmd.blame(gitBaseDir.toPath(), filename);
} catch (Exception e) {
LOG.debug("Native git blame failed. Falling back to jgit: " + filename, e);
nativeGitEnabled = false;
}
}
if (blame == null) {
LOG.debug("Blame file (JGit) {}", filename);
blame = jgitCmd.blame(git, filename);
}
if (!blame.isEmpty()) {
if (blame.size() == inputFile.lines() - 1) {
// SONARPLUGINS-3097 Git does not report blame on last empty line
blame.add(blame.get(blame.size() - 1));
}
output.blameResult(inputFile, blame);
}
}
private static void blameWithFilesGitCommand(BlameOutput output, Repository repo, Map<String, InputFile> inputFileByGitRelativePath) {
RepositoryBlameCommand blameCommand = new RepositoryBlameCommand(repo)
.setTextComparator(RawTextComparator.WS_IGNORE_ALL)
.setMultithreading(true)
.setFilePaths(inputFileByGitRelativePath.keySet());
try {
BlameResult blameResult = blameCommand.call();
for (Map.Entry<String, InputFile> e : inputFileByGitRelativePath.entrySet()) {
BlameResult.FileBlame fileBlameResult = blameResult.getFileBlameByPath().get(e.getKey());
if (fileBlameResult == null) {
LOG.debug("Unable to blame file {}.", e.getValue().filename());
continue;
}
saveBlameInformationForFileInTheOutput(fileBlameResult, e.getValue(), output);
}
} catch (GitAPIException e) {
LOG.warn("There was an issue when interacting with git repository: " + e.getMessage(), e);
}
}
private boolean cloneIsInvalid(File gitBaseDir) {
if (Files.isRegularFile(gitBaseDir.toPath().resolve(".git/objects/info/alternates"))) {
LOG.info("This git repository references another local repository which is not well supported. SCM information might be missing for some files. "
+ "You can avoid borrow objects from another local repository by not using --reference or --shared when cloning it.");
}
if (Files.isRegularFile(gitBaseDir.toPath().resolve(".git/shallow"))) {
LOG.warn("Shallow clone detected, no blame information will be provided. " + "You can convert to non-shallow with 'git fetch --unshallow'.");
analysisWarnings.addUnique("Shallow clone detected during the analysis. " + "Some files will miss SCM information. This will affect features like auto-assignment of issues. "
+ "Please configure your build to disable shallow clone.");
return true;
}
return false;
}
private static void saveBlameInformationForFileInTheOutput(BlameResult.FileBlame fileBlame, InputFile file, BlameOutput output) {
List<BlameLine> linesList = new ArrayList<>();
for (int i = 0; i < fileBlame.lines(); i++) {
if (fileBlame.getAuthorEmails()[i] == null || fileBlame.getCommitHashes()[i] == null || fileBlame.getCommitDates()[i] == null) {
LOG.debug("Unable to blame file {}. No blame info at line {}. Is file committed? [Author: {} Source commit: {}]", file.filename());
linesList.clear();
break;
}
linesList.add(new BlameLine()
.date(fileBlame.getCommitDates()[i])
.revision(fileBlame.getCommitHashes()[i])
.author(fileBlame.getAuthorEmails()[i]));
}
if (!linesList.isEmpty()) {
if (linesList.size() == file.lines() - 1) {
// SONARPLUGINS-3097 Git does not report blame on last empty line
linesList.add(linesList.get(linesList.size() - 1));
}
output.blameResult(file, linesList);
}
}
}
| 10,413 | 39.839216 | 180 | java |
sonarqube | sonarqube-master/sonar-scanner-engine/src/main/java/org/sonar/scm/git/GitIgnoreCommand.java | /*
* SonarQube
* Copyright (C) 2009-2023 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.scm.git;
import java.io.IOException;
import java.nio.file.Path;
import org.sonar.api.batch.scm.IgnoreCommand;
import org.sonar.api.scanner.ScannerSide;
import static java.util.Objects.requireNonNull;
@ScannerSide
public class GitIgnoreCommand implements IgnoreCommand {
private IncludedFilesRepository includedFilesRepository;
@Override
public void init(Path baseDir) {
try {
this.includedFilesRepository = new IncludedFilesRepository(baseDir);
} catch (IOException e) {
throw new IllegalStateException("I/O error while indexing ignored files.", e);
}
}
@Override
public boolean isIgnored(Path absolutePath) {
return !requireNonNull(includedFilesRepository, "Call init first").contains(absolutePath);
}
@Override
public void clean() {
this.includedFilesRepository = null;
}
}
| 1,696 | 31.018868 | 94 | java |
sonarqube | sonarqube-master/sonar-scanner-engine/src/main/java/org/sonar/scm/git/GitScmProvider.java | /*
* SonarQube
* Copyright (C) 2009-2023 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.scm.git;
import com.google.common.annotations.VisibleForTesting;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.IOException;
import java.nio.file.Path;
import java.time.Instant;
import java.util.Arrays;
import java.util.Collection;
import java.util.HashMap;
import java.util.HashSet;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import java.util.Set;
import java.util.function.Function;
import java.util.function.Predicate;
import java.util.regex.Pattern;
import javax.annotation.CheckForNull;
import org.eclipse.jgit.api.Git;
import org.eclipse.jgit.api.errors.GitAPIException;
import org.eclipse.jgit.diff.DiffAlgorithm;
import org.eclipse.jgit.diff.DiffEntry;
import org.eclipse.jgit.diff.DiffEntry.ChangeType;
import org.eclipse.jgit.diff.DiffFormatter;
import org.eclipse.jgit.diff.RawTextComparator;
import org.eclipse.jgit.diff.RenameDetector;
import org.eclipse.jgit.lib.Config;
import org.eclipse.jgit.lib.ConfigConstants;
import org.eclipse.jgit.lib.NullProgressMonitor;
import org.eclipse.jgit.lib.ObjectId;
import org.eclipse.jgit.lib.ObjectReader;
import org.eclipse.jgit.lib.Ref;
import org.eclipse.jgit.lib.Repository;
import org.eclipse.jgit.lib.RepositoryBuilder;
import org.eclipse.jgit.revwalk.RevCommit;
import org.eclipse.jgit.revwalk.RevWalk;
import org.eclipse.jgit.revwalk.filter.RevFilter;
import org.eclipse.jgit.treewalk.AbstractTreeIterator;
import org.eclipse.jgit.treewalk.CanonicalTreeParser;
import org.eclipse.jgit.treewalk.FileTreeIterator;
import org.eclipse.jgit.treewalk.filter.PathFilter;
import org.eclipse.jgit.treewalk.filter.PathFilterGroup;
import org.eclipse.jgit.treewalk.filter.TreeFilter;
import org.sonar.api.batch.scm.BlameCommand;
import org.sonar.api.batch.scm.ScmProvider;
import org.sonar.api.notifications.AnalysisWarnings;
import org.sonar.api.utils.MessageException;
import org.sonar.api.utils.System2;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.sonar.core.documentation.DocumentationLinkGenerator;
import static java.lang.String.format;
import static java.util.function.Function.identity;
import static java.util.stream.Collectors.toMap;
import static java.util.stream.Collectors.toSet;
import static java.util.stream.Collectors.toUnmodifiableMap;
import static org.eclipse.jgit.diff.DiffEntry.ChangeType.ADD;
import static org.eclipse.jgit.diff.DiffEntry.ChangeType.MODIFY;
import static org.eclipse.jgit.diff.DiffEntry.ChangeType.RENAME;
public class GitScmProvider extends ScmProvider {
private static final Logger LOG = LoggerFactory.getLogger(GitScmProvider.class);
private static final String COULD_NOT_FIND_REF = "Could not find ref '%s' in refs/heads, refs/remotes, refs/remotes/upstream or refs/remotes/origin";
private static final String NO_MERGE_BASE_FOUND_MESSAGE = "No merge base found between HEAD and %s";
@VisibleForTesting
static final String SCM_INTEGRATION_DOCUMENTATION_SUFFIX = "/analyzing-source-code/scm-integration/";
private final BlameCommand blameCommand;
private final AnalysisWarnings analysisWarnings;
private final GitIgnoreCommand gitIgnoreCommand;
private final System2 system2;
private final DocumentationLinkGenerator documentationLinkGenerator;
public GitScmProvider(CompositeBlameCommand blameCommand, AnalysisWarnings analysisWarnings, GitIgnoreCommand gitIgnoreCommand, System2 system2,
DocumentationLinkGenerator documentationLinkGenerator) {
this.blameCommand = blameCommand;
this.analysisWarnings = analysisWarnings;
this.gitIgnoreCommand = gitIgnoreCommand;
this.system2 = system2;
this.documentationLinkGenerator = documentationLinkGenerator;
}
@Override
public GitIgnoreCommand ignoreCommand() {
return gitIgnoreCommand;
}
@Override
public String key() {
return "git";
}
@Override
public boolean supports(File baseDir) {
RepositoryBuilder builder = new RepositoryBuilder().findGitDir(baseDir);
return builder.getGitDir() != null;
}
@Override
public BlameCommand blameCommand() {
return this.blameCommand;
}
@CheckForNull
@Override
public Set<Path> branchChangedFiles(String targetBranchName, Path rootBaseDir) {
return Optional.ofNullable((branchChangedFilesWithFileMovementDetection(targetBranchName, rootBaseDir)))
.map(GitScmProvider::extractAbsoluteFilePaths)
.orElse(null);
}
@CheckForNull
public Set<ChangedFile> branchChangedFilesWithFileMovementDetection(String targetBranchName, Path rootBaseDir) {
try (Repository repo = buildRepo(rootBaseDir)) {
Ref targetRef = resolveTargetRef(targetBranchName, repo);
if (targetRef == null) {
addWarningTargetNotFound(targetBranchName);
return null;
}
if (isDiffAlgoInvalid(repo.getConfig())) {
LOG.warn("The diff algorithm configured in git is not supported. "
+ "No information regarding changes in the branch will be collected, which can lead to unexpected results.");
return null;
}
Optional<RevCommit> mergeBaseCommit = findMergeBase(repo, targetRef);
if (mergeBaseCommit.isEmpty()) {
LOG.warn(composeNoMergeBaseFoundWarning(targetRef.getName()));
return null;
}
AbstractTreeIterator mergeBaseTree = prepareTreeParser(repo, mergeBaseCommit.get());
// we compare a commit with HEAD, so no point ignoring line endings (it will be whatever is committed)
try (Git git = newGit(repo)) {
List<DiffEntry> diffEntries = git.diff()
.setShowNameAndStatusOnly(true)
.setOldTree(mergeBaseTree)
.setNewTree(prepareNewTree(repo))
.call();
return computeChangedFiles(repo, diffEntries);
}
} catch (IOException | GitAPIException e) {
LOG.warn(e.getMessage(), e);
}
return null;
}
private static Set<ChangedFile> computeChangedFiles(Repository repository, List<DiffEntry> diffEntries) throws IOException {
Path workingDirectory = repository.getWorkTree().toPath();
Map<String, String> renamedFilePaths = computeRenamedFilePaths(repository, diffEntries);
Set<String> changedFilePaths = computeChangedFilePaths(diffEntries);
return collectChangedFiles(workingDirectory, renamedFilePaths, changedFilePaths);
}
private static Set<ChangedFile> collectChangedFiles(Path workingDirectory, Map<String, String> renamedFilePaths, Set<String> changedFilePaths) {
Set<ChangedFile> changedFiles = new HashSet<>();
changedFilePaths.forEach(filePath -> changedFiles.add(ChangedFile.of(workingDirectory.resolve(filePath), renamedFilePaths.get(filePath))));
return changedFiles;
}
private static Map<String, String> computeRenamedFilePaths(Repository repository, List<DiffEntry> diffEntries) throws IOException {
RenameDetector renameDetector = new RenameDetector(repository);
renameDetector.addAll(diffEntries);
return renameDetector
.compute()
.stream()
.filter(entry -> RENAME.equals(entry.getChangeType()))
.collect(toUnmodifiableMap(DiffEntry::getNewPath, DiffEntry::getOldPath));
}
private static Set<String> computeChangedFilePaths(List<DiffEntry> diffEntries) {
return diffEntries
.stream()
.filter(isAllowedChangeType(ADD, MODIFY))
.map(DiffEntry::getNewPath)
.collect(toSet());
}
private static Predicate<DiffEntry> isAllowedChangeType(ChangeType... changeTypes) {
Function<ChangeType, Predicate<DiffEntry>> isChangeType = type -> entry -> type.equals(entry.getChangeType());
return Arrays
.stream(changeTypes)
.map(isChangeType)
.reduce(x -> false, Predicate::or);
}
@CheckForNull
@Override
public Map<Path, Set<Integer>> branchChangedLines(String targetBranchName, Path projectBaseDir, Set<Path> changedFiles) {
return branchChangedLinesWithFileMovementDetection(targetBranchName, projectBaseDir, toChangedFileByPathsMap(changedFiles));
}
@CheckForNull
public Map<Path, Set<Integer>> branchChangedLinesWithFileMovementDetection(String targetBranchName, Path projectBaseDir, Map<Path, ChangedFile> changedFiles) {
try (Repository repo = buildRepo(projectBaseDir)) {
Ref targetRef = resolveTargetRef(targetBranchName, repo);
if (targetRef == null) {
addWarningTargetNotFound(targetBranchName);
return null;
}
if (isDiffAlgoInvalid(repo.getConfig())) {
// we already print a warning when branchChangedFiles is called
return null;
}
// force ignore different line endings when comparing a commit with the workspace
repo.getConfig().setBoolean("core", null, "autocrlf", true);
Optional<RevCommit> mergeBaseCommit = findMergeBase(repo, targetRef);
if (mergeBaseCommit.isEmpty()) {
LOG.warn(composeNoMergeBaseFoundWarning(targetRef.getName()));
return null;
}
Map<Path, Set<Integer>> changedLines = new HashMap<>();
for (Map.Entry<Path, ChangedFile> entry : changedFiles.entrySet()) {
collectChangedLines(repo, mergeBaseCommit.get(), changedLines, entry.getKey(), entry.getValue());
}
return changedLines;
} catch (Exception e) {
LOG.warn("Failed to get changed lines from git", e);
}
return null;
}
private static String composeNoMergeBaseFoundWarning(String targetRef) {
return format(NO_MERGE_BASE_FOUND_MESSAGE, targetRef);
}
private void addWarningTargetNotFound(String targetBranchName) {
String url = documentationLinkGenerator.getDocumentationLink(SCM_INTEGRATION_DOCUMENTATION_SUFFIX);
analysisWarnings.addUnique(format(COULD_NOT_FIND_REF
+ ". You may see unexpected issues and changes. "
+ "Please make sure to fetch this ref before pull request analysis and refer to"
+ " <a href=\"%s\" rel=\"noopener noreferrer\" target=\"_blank\">the documentation</a>.", targetBranchName, url));
}
private void collectChangedLines(Repository repo, RevCommit mergeBaseCommit, Map<Path, Set<Integer>> changedLines, Path changedFilePath, ChangedFile changedFile) {
ChangedLinesComputer computer = new ChangedLinesComputer();
try (DiffFormatter diffFmt = new DiffFormatter(new BufferedOutputStream(computer.receiver()))) {
diffFmt.setRepository(repo);
diffFmt.setProgressMonitor(NullProgressMonitor.INSTANCE);
diffFmt.setDiffComparator(RawTextComparator.WS_IGNORE_ALL);
diffFmt.setDetectRenames(changedFile.isMovedFile());
Path workTree = repo.getWorkTree().toPath();
TreeFilter treeFilter = getTreeFilter(changedFile, workTree);
diffFmt.setPathFilter(treeFilter);
AbstractTreeIterator mergeBaseTree = prepareTreeParser(repo, mergeBaseCommit);
List<DiffEntry> diffEntries = diffFmt.scan(mergeBaseTree, new FileTreeIterator(repo));
diffFmt.format(diffEntries);
diffFmt.flush();
diffEntries.stream()
.filter(isAllowedChangeType(ADD, MODIFY, RENAME))
.findAny()
.ifPresent(diffEntry -> changedLines.put(changedFilePath, computer.changedLines()));
} catch (Exception e) {
LOG.warn("Failed to get changed lines from git for file " + changedFilePath, e);
}
}
@Override
@CheckForNull
public Instant forkDate(String referenceBranchName, Path projectBaseDir) {
return null;
}
private static String toGitPath(String path) {
return path.replaceAll(Pattern.quote(File.separator), "/");
}
private static TreeFilter getTreeFilter(ChangedFile changedFile, Path baseDir) {
String path = toGitPath(relativizeFilePath(baseDir, changedFile.getAbsolutFilePath()));
String oldRelativePath = changedFile.getOldRelativeFilePathReference();
if (oldRelativePath != null) {
return PathFilterGroup.createFromStrings(path, toGitPath(oldRelativePath));
}
return PathFilter.create(path);
}
private static Set<Path> extractAbsoluteFilePaths(Collection<ChangedFile> changedFiles) {
return changedFiles
.stream()
.map(ChangedFile::getAbsolutFilePath)
.collect(toSet());
}
@CheckForNull
private Ref resolveTargetRef(String targetBranchName, Repository repo) throws IOException {
String localRef = "refs/heads/" + targetBranchName;
String remotesRef = "refs/remotes/" + targetBranchName;
String originRef = "refs/remotes/origin/" + targetBranchName;
String upstreamRef = "refs/remotes/upstream/" + targetBranchName;
Ref targetRef;
// Because circle ci destroys the local reference to master, try to load remote ref first.
// https://discuss.circleci.com/t/git-checkout-of-a-branch-destroys-local-reference-to-master/23781
if (runningOnCircleCI()) {
targetRef = getFirstExistingRef(repo, originRef, localRef, upstreamRef, remotesRef);
} else {
targetRef = getFirstExistingRef(repo, localRef, originRef, upstreamRef, remotesRef);
}
if (targetRef == null) {
LOG.warn(String.format(COULD_NOT_FIND_REF, targetBranchName));
}
return targetRef;
}
@CheckForNull
private static Ref getFirstExistingRef(Repository repo, String... refs) throws IOException {
Ref targetRef = null;
for (String ref : refs) {
targetRef = repo.exactRef(ref);
if (targetRef != null) {
break;
}
}
return targetRef;
}
private boolean runningOnCircleCI() {
return "true".equals(system2.envVariable("CIRCLECI"));
}
@Override
public Path relativePathFromScmRoot(Path path) {
RepositoryBuilder builder = getVerifiedRepositoryBuilder(path);
return builder.getGitDir().toPath().getParent().relativize(path);
}
@Override
@CheckForNull
public String revisionId(Path path) {
RepositoryBuilder builder = getVerifiedRepositoryBuilder(path);
try {
return Optional.ofNullable(getHead(builder.build()))
.map(Ref::getObjectId)
.map(ObjectId::getName)
.orElse(null);
} catch (IOException e) {
throw new IllegalStateException("I/O error while getting revision ID for path: " + path, e);
}
}
private static boolean isDiffAlgoInvalid(Config cfg) {
try {
DiffAlgorithm.getAlgorithm(cfg.getEnum(
ConfigConstants.CONFIG_DIFF_SECTION, null,
ConfigConstants.CONFIG_KEY_ALGORITHM,
DiffAlgorithm.SupportedAlgorithm.HISTOGRAM));
return false;
} catch (IllegalArgumentException e) {
return true;
}
}
private static AbstractTreeIterator prepareNewTree(Repository repo) throws IOException {
CanonicalTreeParser treeParser = new CanonicalTreeParser();
try (ObjectReader objectReader = repo.newObjectReader()) {
Ref head = getHead(repo);
if (head == null) {
throw new IOException("HEAD reference not found");
}
treeParser.reset(objectReader, repo.parseCommit(head.getObjectId()).getTree());
}
return treeParser;
}
@CheckForNull
private static Ref getHead(Repository repo) throws IOException {
return repo.exactRef("HEAD");
}
private static Optional<RevCommit> findMergeBase(Repository repo, Ref targetRef) throws IOException {
try (RevWalk walk = new RevWalk(repo)) {
Ref head = getHead(repo);
if (head == null) {
throw new IOException("HEAD reference not found");
}
walk.markStart(walk.parseCommit(targetRef.getObjectId()));
walk.markStart(walk.parseCommit(head.getObjectId()));
walk.setRevFilter(RevFilter.MERGE_BASE);
RevCommit next = walk.next();
if (next == null) {
return Optional.empty();
}
RevCommit base = walk.parseCommit(next);
walk.dispose();
LOG.info("Merge base sha1: {}", base.getName());
return Optional.of(base);
}
}
private static Map<Path, ChangedFile> toChangedFileByPathsMap(Set<Path> changedFiles) {
return changedFiles
.stream()
.collect(toMap(identity(), ChangedFile::of, (x, y) -> y, LinkedHashMap::new));
}
private static String relativizeFilePath(Path baseDirectory, Path filePath) {
return baseDirectory.relativize(filePath).toString();
}
AbstractTreeIterator prepareTreeParser(Repository repo, RevCommit commit) throws IOException {
CanonicalTreeParser treeParser = new CanonicalTreeParser();
try (ObjectReader objectReader = repo.newObjectReader()) {
treeParser.reset(objectReader, commit.getTree());
}
return treeParser;
}
Git newGit(Repository repo) {
return new Git(repo);
}
Repository buildRepo(Path basedir) throws IOException {
return getVerifiedRepositoryBuilder(basedir).build();
}
static RepositoryBuilder getVerifiedRepositoryBuilder(Path basedir) {
RepositoryBuilder builder = new RepositoryBuilder()
.findGitDir(basedir.toFile())
.setMustExist(true);
if (builder.getGitDir() == null) {
throw MessageException.of("Not inside a Git work tree: " + basedir);
}
return builder;
}
}
| 17,802 | 36.401261 | 165 | java |
sonarqube | sonarqube-master/sonar-scanner-engine/src/main/java/org/sonar/scm/git/GitScmSupport.java | /*
* SonarQube
* Copyright (C) 2009-2023 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.scm.git;
import java.util.Arrays;
import java.util.List;
import org.eclipse.jgit.util.FS;
import org.sonar.scm.git.strategy.DefaultBlameStrategy;
public final class GitScmSupport {
private GitScmSupport() {
// static only
}
public static List<Object> getObjects() {
FS.FileStoreAttributes.setBackground(true);
return Arrays.asList(
JGitBlameCommand.class,
CompositeBlameCommand.class,
NativeGitBlameCommand.class,
DefaultBlameStrategy.class,
ProcessWrapperFactory.class,
GitScmProvider.class,
GitIgnoreCommand.class);
}
}
| 1,448 | 31.931818 | 75 | java |
sonarqube | sonarqube-master/sonar-scanner-engine/src/main/java/org/sonar/scm/git/GitThreadFactory.java | /*
* SonarQube
* Copyright (C) 2009-2023 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.scm.git;
import java.util.concurrent.ThreadFactory;
import java.util.concurrent.atomic.AtomicInteger;
public class GitThreadFactory implements ThreadFactory {
private static final String NAME_PREFIX = "git-scm-";
private final AtomicInteger count = new AtomicInteger(0);
@Override
public Thread newThread(Runnable r) {
Thread t = new Thread(r);
t.setName(NAME_PREFIX + count.getAndIncrement());
t.setDaemon(true);
return t;
}
}
| 1,318 | 34.648649 | 75 | java |
sonarqube | sonarqube-master/sonar-scanner-engine/src/main/java/org/sonar/scm/git/IncludedFilesRepository.java | /*
* SonarQube
* Copyright (C) 2009-2023 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.scm.git;
import java.io.IOException;
import java.nio.file.Path;
import java.util.HashSet;
import java.util.Set;
import org.eclipse.jgit.lib.Repository;
import org.eclipse.jgit.submodule.SubmoduleWalk;
import org.eclipse.jgit.treewalk.FileTreeIterator;
import org.eclipse.jgit.treewalk.TreeWalk;
import org.eclipse.jgit.treewalk.WorkingTreeIterator;
import org.eclipse.jgit.treewalk.filter.PathFilterGroup;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
public class IncludedFilesRepository {
private static final Logger LOG = LoggerFactory.getLogger(IncludedFilesRepository.class);
private final Set<Path> includedFiles = new HashSet<>();
public IncludedFilesRepository(Path baseDir) throws IOException {
indexFiles(baseDir);
LOG.debug("{} non excluded files in this Git repository", includedFiles.size());
}
public boolean contains(Path absolutePath) {
return includedFiles.contains(absolutePath);
}
private void indexFiles(Path baseDir) throws IOException {
try (Repository repo = JGitUtils.buildRepository(baseDir)) {
collectFilesIterative(repo, baseDir);
}
}
private void collectFiles(Repository repo, Path baseDir) throws IOException {
Path workTreeRoot = repo.getWorkTree().toPath();
FileTreeIterator workingTreeIt = new FileTreeIterator(repo);
try (TreeWalk treeWalk = new TreeWalk(repo)) {
treeWalk.setRecursive(true);
// with submodules, the baseDir may be the parent of the workTreeRoot. In that case, we don't want to set a filter.
if (!workTreeRoot.equals(baseDir) && baseDir.startsWith(workTreeRoot)) {
Path relativeBaseDir = workTreeRoot.relativize(baseDir);
treeWalk.setFilter(PathFilterGroup.createFromStrings(relativeBaseDir.toString().replace('\\', '/')));
}
treeWalk.addTree(workingTreeIt);
while (treeWalk.next()) {
WorkingTreeIterator workingTreeIterator = treeWalk
.getTree(0, WorkingTreeIterator.class);
if (!workingTreeIterator.isEntryIgnored()) {
includedFiles.add(workTreeRoot.resolve(treeWalk.getPathString()));
}
}
}
}
private void collectFilesIterative(Repository repo, Path baseDir) throws IOException {
collectFiles(repo, baseDir);
try (SubmoduleWalk submoduleWalk = SubmoduleWalk.forIndex(repo)) {
while (submoduleWalk.next()) {
try (Repository submoduleRepo = submoduleWalk.getRepository()) {
if (submoduleRepo == null) {
LOG.debug("Git submodule [{}] found, but has not been cloned, skipping.", submoduleWalk.getPath());
continue;
}
collectFilesIterative(submoduleRepo, baseDir);
}
}
}
}
}
| 3,569 | 36.578947 | 121 | java |
sonarqube | sonarqube-master/sonar-scanner-engine/src/main/java/org/sonar/scm/git/JGitBlameCommand.java | /*
* SonarQube
* Copyright (C) 2009-2023 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.scm.git;
import java.util.ArrayList;
import java.util.List;
import org.eclipse.jgit.api.Git;
import org.eclipse.jgit.blame.BlameResult;
import org.eclipse.jgit.diff.RawTextComparator;
import org.sonar.api.batch.scm.BlameLine;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import static java.util.Collections.emptyList;
public class JGitBlameCommand {
private static final Logger LOG = LoggerFactory.getLogger(JGitBlameCommand.class);
public List<BlameLine> blame(Git git, String filename) {
BlameResult blameResult;
try {
blameResult = git.blame()
// Equivalent to -w command line option
.setTextComparator(RawTextComparator.WS_IGNORE_ALL)
.setFilePath(filename).call();
} catch (Exception e) {
throw new IllegalStateException("Unable to blame file " + filename, e);
}
List<BlameLine> lines = new ArrayList<>();
if (blameResult == null) {
LOG.debug("Unable to blame file {}. It is probably a symlink.", filename);
return emptyList();
}
for (int i = 0; i < blameResult.getResultContents().size(); i++) {
if (blameResult.getSourceAuthor(i) == null || blameResult.getSourceCommit(i) == null) {
LOG.debug("Unable to blame file {}. No blame info at line {}. Is file committed? [Author: {} Source commit: {}]", filename, i + 1,
blameResult.getSourceAuthor(i), blameResult.getSourceCommit(i));
return emptyList();
}
lines.add(new BlameLine()
.date(blameResult.getSourceCommitter(i).getWhen())
.revision(blameResult.getSourceCommit(i).getName())
.author(blameResult.getSourceAuthor(i).getEmailAddress()));
}
return lines;
}
}
| 2,558 | 37.19403 | 138 | java |
sonarqube | sonarqube-master/sonar-scanner-engine/src/main/java/org/sonar/scm/git/JGitUtils.java | /*
* SonarQube
* Copyright (C) 2009-2023 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.scm.git;
import java.io.IOException;
import java.nio.file.Path;
import org.eclipse.jgit.lib.ObjectReader;
import org.eclipse.jgit.lib.Repository;
public class JGitUtils {
private JGitUtils() {
}
public static Repository buildRepository(Path basedir) {
try {
Repository repo = GitScmProvider.getVerifiedRepositoryBuilder(basedir).build();
try (ObjectReader objReader = repo.getObjectDatabase().newReader()) {
// SONARSCGIT-2 Force initialization of shallow commits to avoid later concurrent modification issue
objReader.getShallowCommits();
return repo;
}
} catch (IOException e) {
throw new IllegalStateException("Unable to open Git repository", e);
}
}
}
| 1,589 | 34.333333 | 108 | java |
sonarqube | sonarqube-master/sonar-scanner-engine/src/main/java/org/sonar/scm/git/NativeGitBlameCommand.java | /*
* SonarQube
* Copyright (C) 2009-2023 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.scm.git;
import java.io.IOException;
import java.nio.file.Path;
import java.time.Instant;
import java.util.Date;
import java.util.LinkedList;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import java.util.stream.Collectors;
import org.apache.commons.lang.math.NumberUtils;
import org.sonar.api.batch.scm.BlameLine;
import org.sonar.api.utils.System2;
import org.sonar.api.utils.Version;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import static java.util.Collections.emptyList;
import static org.sonar.api.utils.Preconditions.checkState;
public class NativeGitBlameCommand {
protected static final String BLAME_COMMAND = "blame";
protected static final String GIT_DIR_FLAG = "--git-dir";
protected static final String GIT_DIR_ARGUMENT = "%s/.git";
protected static final String GIT_DIR_FORCE_FLAG = "-C";
private static final Logger LOG = LoggerFactory.getLogger(NativeGitBlameCommand.class);
private static final Pattern EMAIL_PATTERN = Pattern.compile("<(.*?)>");
private static final String COMMITTER_TIME = "committer-time ";
private static final String AUTHOR_MAIL = "author-mail ";
private static final String MINIMUM_REQUIRED_GIT_VERSION = "2.24.0";
private static final String DEFAULT_GIT_COMMAND = "git";
private static final String BLAME_LINE_PORCELAIN_FLAG = "--line-porcelain";
private static final String END_OF_OPTIONS_FLAG = "--end-of-options";
private static final String IGNORE_WHITESPACES = "-w";
private static final Pattern whitespaceRegex = Pattern.compile("\\s+");
private static final Pattern semanticVersionDelimiter = Pattern.compile("\\.");
private final System2 system;
private final ProcessWrapperFactory processWrapperFactory;
private String gitCommand;
@Autowired
public NativeGitBlameCommand(System2 system, ProcessWrapperFactory processWrapperFactory) {
this.system = system;
this.processWrapperFactory = processWrapperFactory;
}
NativeGitBlameCommand(String gitCommand, System2 system, ProcessWrapperFactory processWrapperFactory) {
this.gitCommand = gitCommand;
this.system = system;
this.processWrapperFactory = processWrapperFactory;
}
/**
* This method must be executed before org.sonar.scm.git.GitBlameCommand#blame
*
* @return true, if native git is installed
*/
public boolean checkIfEnabled() {
try {
this.gitCommand = locateDefaultGit();
MutableString stdOut = new MutableString();
this.processWrapperFactory.create(null, l -> stdOut.string = l, gitCommand, "--version").execute();
return stdOut.string != null && stdOut.string.startsWith("git version") && isCompatibleGitVersion(stdOut.string);
} catch (Exception e) {
LOG.debug("Failed to find git native client", e);
return false;
}
}
private String locateDefaultGit() throws IOException {
if (this.gitCommand != null) {
return this.gitCommand;
}
// if not set fall back to defaults
if (system.isOsWindows()) {
return locateGitOnWindows();
}
return DEFAULT_GIT_COMMAND;
}
private String locateGitOnWindows() throws IOException {
// Windows will search current directory in addition to the PATH variable, which is unsecure.
// To avoid it we use where.exe to find git binary only in PATH.
LOG.debug("Looking for git command in the PATH using where.exe (Windows)");
List<String> whereCommandResult = new LinkedList<>();
this.processWrapperFactory.create(null, whereCommandResult::add, "C:\\Windows\\System32\\where.exe", "$PATH:git.exe")
.execute();
if (!whereCommandResult.isEmpty()) {
String out = whereCommandResult.get(0).trim();
LOG.debug("Found git.exe at {}", out);
return out;
}
throw new IllegalStateException("git.exe not found in PATH. PATH value was: " + system.property("PATH"));
}
public List<BlameLine> blame(Path baseDir, String fileName) throws Exception {
BlameOutputProcessor outputProcessor = new BlameOutputProcessor();
try {
this.processWrapperFactory.create(
baseDir,
outputProcessor::process,
gitCommand,
GIT_DIR_FLAG, String.format(GIT_DIR_ARGUMENT, baseDir), GIT_DIR_FORCE_FLAG, baseDir.toString(),
BLAME_COMMAND,
BLAME_LINE_PORCELAIN_FLAG, IGNORE_WHITESPACES, END_OF_OPTIONS_FLAG, fileName)
.execute();
} catch (UncommittedLineException e) {
LOG.debug("Unable to blame file '{}' - it has uncommitted changes", fileName);
return emptyList();
}
return outputProcessor.getBlameLines();
}
private static class BlameOutputProcessor {
private final List<BlameLine> blameLines = new LinkedList<>();
private String sha1 = null;
private String committerTime = null;
private String authorMail = null;
public List<BlameLine> getBlameLines() {
return blameLines;
}
public void process(String line) {
if (sha1 == null) {
sha1 = line.split(" ")[0];
} else if (line.startsWith("\t")) {
saveEntry();
} else if (line.startsWith(COMMITTER_TIME)) {
committerTime = line.substring(COMMITTER_TIME.length());
} else if (line.startsWith(AUTHOR_MAIL)) {
Matcher matcher = EMAIL_PATTERN.matcher(line);
if (matcher.find(AUTHOR_MAIL.length())) {
authorMail = matcher.group(1);
}
if (authorMail.equals("not.committed.yet")) {
throw new UncommittedLineException();
}
}
}
private void saveEntry() {
checkState(authorMail != null, "Did not find an author email for an entry");
checkState(committerTime != null, "Did not find a committer time for an entry");
checkState(sha1 != null, "Did not find a commit sha1 for an entry");
try {
blameLines.add(new BlameLine()
.revision(sha1)
.author(authorMail)
.date(Date.from(Instant.ofEpochSecond(Long.parseLong(committerTime)))));
} catch (NumberFormatException e) {
throw new IllegalStateException("Invalid committer time found: " + committerTime);
}
authorMail = null;
sha1 = null;
committerTime = null;
}
}
private static boolean isCompatibleGitVersion(String gitVersionCommandOutput) {
// Due to the danger of argument injection on git blame the use of `--end-of-options` flag is necessary
// The flag is available only on git versions >= 2.24.0
String gitVersion = whitespaceRegex
.splitAsStream(gitVersionCommandOutput)
.skip(2)
.findFirst()
.orElse("");
String formattedGitVersion = formatGitSemanticVersion(gitVersion);
return Version.parse(formattedGitVersion).isGreaterThanOrEqual(Version.parse(MINIMUM_REQUIRED_GIT_VERSION));
}
private static String formatGitSemanticVersion(String version) {
return semanticVersionDelimiter
.splitAsStream(version)
.takeWhile(NumberUtils::isNumber)
.collect(Collectors.joining("."));
}
private static class MutableString {
String string;
}
private static class UncommittedLineException extends RuntimeException {
}
}
| 8,087 | 36.794393 | 121 | java |
sonarqube | sonarqube-master/sonar-scanner-engine/src/main/java/org/sonar/scm/git/ProcessWrapperFactory.java | /*
* SonarQube
* Copyright (C) 2009-2023 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.scm.git;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.nio.file.Path;
import java.util.Scanner;
import java.util.function.Consumer;
import javax.annotation.Nullable;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import static java.lang.String.format;
import static java.lang.String.join;
import static java.nio.charset.StandardCharsets.UTF_8;
public class ProcessWrapperFactory {
private static final Logger LOG = LoggerFactory.getLogger(ProcessWrapperFactory.class);
public ProcessWrapperFactory() {
// nothing to do
}
public ProcessWrapper create(@Nullable Path baseDir, Consumer<String> stdOutLineConsumer, String... command) {
return new ProcessWrapper(baseDir, stdOutLineConsumer, command);
}
static class ProcessWrapper {
private final Path baseDir;
private final Consumer<String> stdOutLineConsumer;
private final String[] command;
ProcessWrapper(@Nullable Path baseDir, Consumer<String> stdOutLineConsumer, String... command) {
this.baseDir = baseDir;
this.stdOutLineConsumer = stdOutLineConsumer;
this.command = command;
}
public void execute() throws IOException {
ProcessBuilder pb = new ProcessBuilder()
.command(command)
.directory(baseDir != null ? baseDir.toFile() : null);
Process p = pb.start();
try {
processInputStream(p.getInputStream(), stdOutLineConsumer);
processInputStream(p.getErrorStream(), line -> {
if (!line.isBlank()) {
LOG.debug(line);
}
});
int exit = p.waitFor();
if (exit != 0) {
throw new IllegalStateException(format("Command execution exited with code: %d", exit));
}
} catch (InterruptedException e) {
LOG.warn(format("Command [%s] interrupted", join(" ", command)), e);
Thread.currentThread().interrupt();
} finally {
p.destroy();
}
}
private static void processInputStream(InputStream inputStream, Consumer<String> stringConsumer) {
try (Scanner scanner = new Scanner(new InputStreamReader(inputStream, UTF_8))) {
scanner.useDelimiter("\n");
while (scanner.hasNext()) {
stringConsumer.accept(scanner.next());
}
}
}
}
}
| 3,190 | 31.896907 | 112 | java |
sonarqube | sonarqube-master/sonar-scanner-engine/src/main/java/org/sonar/scm/git/package-info.java | /*
* SonarQube
* Copyright (C) 2009-2023 SonarSource SA
* mailto:info AT sonarsource DOT com
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 3 of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this program; if not, write to the Free Software Foundation,
* Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*/
@ParametersAreNonnullByDefault
package org.sonar.scm.git;
import javax.annotation.ParametersAreNonnullByDefault;
| 957 | 38.916667 | 75 | java |
sonarqube | sonarqube-master/sonar-scanner-engine/src/main/java/org/sonar/scm/git/strategy/BlameStrategy.java | /*
* SonarQube
* Copyright (C) 2009-2023 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.scm.git.strategy;
public interface BlameStrategy {
DefaultBlameStrategy.BlameAlgorithmEnum getBlameAlgorithm(int availableProcessors, int numberOfFiles);
}
| 1,021 | 38.307692 | 104 | java |
sonarqube | sonarqube-master/sonar-scanner-engine/src/main/java/org/sonar/scm/git/strategy/DefaultBlameStrategy.java | /*
* SonarQube
* Copyright (C) 2009-2023 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.scm.git.strategy;
import org.sonar.api.config.Configuration;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import static org.sonar.scm.git.strategy.DefaultBlameStrategy.BlameAlgorithmEnum.*;
/**
* The blame strategy defines when the files-blame algorithm is used over jgit or native git algorithm.
* It has been found that the JGit/Git native algorithm performs better in certain circumstances, such as:
* - When we have many cores available for multi-threading
* - The number of files to be blame by the algorithm
* This two metrics are correlated:
* - The more threads available, the more it is favorable to use the JGit/Git native algorithm
* - The more files available, the more it is favorable to use the git-files-blame algorithm
*/
public class DefaultBlameStrategy implements BlameStrategy {
private static final Logger LOG = LoggerFactory.getLogger(DefaultBlameStrategy.class);
private static final int FILES_GIT_BLAME_TRIGGER = 10;
public static final String PROP_SONAR_SCM_USE_BLAME_ALGORITHM = "sonar.scm.use.blame.algorithm";
private final Configuration configuration;
public DefaultBlameStrategy(Configuration configuration) {
this.configuration = configuration;
}
@Override
public BlameAlgorithmEnum getBlameAlgorithm(int availableProcessors, int numberOfFiles) {
BlameAlgorithmEnum forcedStrategy = configuration.get(PROP_SONAR_SCM_USE_BLAME_ALGORITHM)
.map(BlameAlgorithmEnum::valueOf)
.orElse(null);
if (forcedStrategy != null) {
return forcedStrategy;
}
if (availableProcessors == 0) {
LOG.warn("Available processors are 0. Falling back to native git blame");
return GIT_NATIVE_BLAME;
}
if (numberOfFiles / availableProcessors > FILES_GIT_BLAME_TRIGGER) {
return GIT_FILES_BLAME;
}
return GIT_NATIVE_BLAME;
}
public enum BlameAlgorithmEnum {
/**
* Strategy using native git for the blame, or JGit on single file as a fallback
*/
GIT_NATIVE_BLAME,
/**
* Strategy using git-files-blame algorithm
*/
GIT_FILES_BLAME;
}
}
| 2,958 | 35.530864 | 106 | java |
sonarqube | sonarqube-master/sonar-scanner-engine/src/main/java/org/sonar/scm/git/strategy/package-info.java | /*
* SonarQube
* Copyright (C) 2009-2023 SonarSource SA
* mailto:info AT sonarsource DOT com
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 3 of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this program; if not, write to the Free Software Foundation,
* Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*/
@ParametersAreNonnullByDefault
package org.sonar.scm.git.strategy;
import javax.annotation.ParametersAreNonnullByDefault;
| 966 | 39.291667 | 75 | java |
sonarqube | sonarqube-master/sonar-scanner-engine/src/main/java/org/sonar/scm/svn/AnnotationHandler.java | /*
* SonarQube
* Copyright (C) 2009-2023 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.scm.svn;
import java.io.File;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import org.sonar.api.batch.scm.BlameLine;
import org.tmatesoft.svn.core.SVNException;
import org.tmatesoft.svn.core.wc.ISVNAnnotateHandler;
public class AnnotationHandler implements ISVNAnnotateHandler {
private List<BlameLine> lines = new ArrayList<>();
@Override
public void handleEOF() {
// Not used
}
@Override
public void handleLine(Date date, long revision, String author, String line) throws SVNException {
// deprecated
}
@Override
public void handleLine(Date date, long revision, String author, String line, Date mergedDate,
long mergedRevision, String mergedAuthor, String mergedPath, int lineNumber) throws SVNException {
lines.add(new BlameLine().date(mergedDate).revision(Long.toString(mergedRevision)).author(mergedAuthor));
}
@Override
public boolean handleRevision(Date date, long revision, String author, File contents) throws SVNException {
/*
* We do not want our file to be annotated for each revision of the range, but only for the last
* revision of it, so we return false
*/
return false;
}
public List<BlameLine> getLines() {
return lines;
}
}
| 2,115 | 32.0625 | 109 | java |
sonarqube | sonarqube-master/sonar-scanner-engine/src/main/java/org/sonar/scm/svn/ChangedLinesComputer.java | /*
* SonarQube
* Copyright (C) 2009-2023 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.scm.svn;
import java.io.OutputStream;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Map;
import java.util.Set;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
class ChangedLinesComputer {
private final Tracker tracker;
private final OutputStream receiver = new OutputStream() {
StringBuilder sb = new StringBuilder();
@Override
public void write(int b) {
sb.append((char) b);
if (b == '\n') {
tracker.parseLine(sb.toString());
sb.setLength(0);
}
}
};
ChangedLinesComputer(Path rootBaseDir, Set<Path> included) {
this.tracker = new Tracker(rootBaseDir, included);
}
/**
* The OutputStream to pass to svnkit's diff command.
*/
OutputStream receiver() {
return receiver;
}
/**
* From a stream of svn-style unified diff lines,
* compute the line numbers that should be considered changed.
*
* Example input:
* <pre>
* Index: path/to/file
* ===================================================================
* --- lao 2002-02-21 23:30:39.942229878 -0800
* +++ tzu 2002-02-21 23:30:50.442260588 -0800
* @@ -1,7 +1,6 @@
* -The Way that can be told of is not the eternal Way;
* -The name that can be named is not the eternal name.
* The Nameless is the origin of Heaven and Earth;
* -The Named is the mother of all things.
* +The named is the mother of all things.
* +
* Therefore let there always be non-being,
* so we may see their subtlety,
* And let there always be being,
* @@ -9,3 +8,6 @@
* The two are the same,
* But after they are produced,
* they have different names.
* +They both may be called deep and profound.
* +Deeper and more profound,
* +The door of all subtleties!
* </pre>
*
* See also: http://www.gnu.org/software/diffutils/manual/html_node/Example-Unified.html#Example-Unified
*/
Map<Path, Set<Integer>> changedLines() {
return tracker.changedLines();
}
private static class Tracker {
private static final Pattern START_LINE_IN_TARGET = Pattern.compile(" \\+(\\d+)");
private static final String ENTRY_START_PREFIX = "Index: ";
private final Map<Path, Set<Integer>> changedLines = new HashMap<>();
private final Set<Path> included;
private final Path rootBaseDir;
private int lineNumInTarget;
private Path currentPath = null;
private int skipCount = 0;
Tracker(Path rootBaseDir, Set<Path> included) {
this.rootBaseDir = rootBaseDir;
this.included = included;
}
private void parseLine(String line) {
if (line.startsWith(ENTRY_START_PREFIX)) {
currentPath = Paths.get(line.substring(ENTRY_START_PREFIX.length()).trim());
if (!currentPath.isAbsolute()) {
currentPath = rootBaseDir.resolve(currentPath);
}
if (!included.contains(currentPath)) {
return;
}
skipCount = 3;
return;
}
if (!included.contains(currentPath)) {
return;
}
if (skipCount > 0) {
skipCount--;
return;
}
if (line.startsWith("@@ ")) {
Matcher matcher = START_LINE_IN_TARGET.matcher(line);
if (!matcher.find()) {
throw new IllegalStateException("Invalid block header: " + line);
}
lineNumInTarget = Integer.parseInt(matcher.group(1));
return;
}
parseContent(line);
}
private void parseContent(String line) {
char firstChar = line.charAt(0);
if (firstChar == ' ') {
lineNumInTarget++;
} else if (firstChar == '+') {
changedLines
.computeIfAbsent(currentPath, path -> new HashSet<>())
.add(lineNumInTarget);
lineNumInTarget++;
}
}
Map<Path, Set<Integer>> changedLines() {
return changedLines;
}
}
}
| 4,800 | 28.27439 | 106 | java |
sonarqube | sonarqube-master/sonar-scanner-engine/src/main/java/org/sonar/scm/svn/ForkPoint.java | /*
* SonarQube
* Copyright (C) 2009-2023 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.scm.svn;
import java.time.Instant;
public class ForkPoint {
private String commit;
private Instant date;
public ForkPoint(String commit, Instant date) {
this.commit = commit;
this.date = date;
}
public String commit() {
return commit;
}
public Instant date() {
return date;
}
@Override
public String toString() {
return "ForkPoint{" +
"commit='" + commit + '\'' +
", date=" + date +
'}';
}
}
| 1,319 | 25.938776 | 75 | java |
sonarqube | sonarqube-master/sonar-scanner-engine/src/main/java/org/sonar/scm/svn/SvnBlameCommand.java | /*
* SonarQube
* Copyright (C) 2009-2023 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.scm.svn;
import com.google.common.annotations.VisibleForTesting;
import java.util.List;
import org.sonar.api.batch.fs.FileSystem;
import org.sonar.api.batch.fs.InputFile;
import org.sonar.api.batch.scm.BlameCommand;
import org.sonar.api.batch.scm.BlameLine;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.tmatesoft.svn.core.SVNAuthenticationException;
import org.tmatesoft.svn.core.SVNErrorCode;
import org.tmatesoft.svn.core.SVNException;
import org.tmatesoft.svn.core.wc.SVNClientManager;
import org.tmatesoft.svn.core.wc.SVNDiffOptions;
import org.tmatesoft.svn.core.wc.SVNLogClient;
import org.tmatesoft.svn.core.wc.SVNRevision;
import org.tmatesoft.svn.core.wc.SVNStatus;
import org.tmatesoft.svn.core.wc.SVNStatusClient;
import org.tmatesoft.svn.core.wc.SVNStatusType;
import static org.sonar.scm.svn.SvnScmSupport.newSvnClientManager;
public class SvnBlameCommand extends BlameCommand {
private static final Logger LOG = LoggerFactory.getLogger(SvnBlameCommand.class);
private final SvnConfiguration configuration;
public SvnBlameCommand(SvnConfiguration configuration) {
this.configuration = configuration;
}
@Override
public void blame(final BlameInput input, final BlameOutput output) {
FileSystem fs = input.fileSystem();
LOG.debug("Working directory: " + fs.baseDir().getAbsolutePath());
SVNClientManager clientManager = null;
try {
clientManager = newSvnClientManager(configuration);
for (InputFile inputFile : input.filesToBlame()) {
blame(clientManager, inputFile, output);
}
} finally {
if (clientManager != null) {
try {
clientManager.dispose();
} catch (Exception e) {
LOG.warn("Unable to dispose SVN ClientManager", e);
}
}
}
}
@VisibleForTesting
void blame(SVNClientManager clientManager, InputFile inputFile, BlameOutput output) {
String filename = inputFile.relativePath();
LOG.debug("Process file {}", filename);
AnnotationHandler handler = new AnnotationHandler();
try {
if (!checkStatus(clientManager, inputFile)) {
return;
}
SVNLogClient logClient = clientManager.getLogClient();
logClient.setDiffOptions(new SVNDiffOptions(true, true, true));
logClient.doAnnotate(inputFile.file(), SVNRevision.UNDEFINED, SVNRevision.create(1), SVNRevision.BASE, true, true, handler, null);
} catch (SVNAuthenticationException e) {
if(configuration.isEmpty()) {
LOG.warn("Authentication to SVN server is required but no authentication data was passed to the scanner");
}
throw new IllegalStateException("Authentication error when executing blame for file " + filename, e);
} catch (SVNException e) {
throw new IllegalStateException("Error when executing blame for file " + filename, e);
}
List<BlameLine> lines = handler.getLines();
if (lines.size() == inputFile.lines() - 1) {
// SONARPLUGINS-3097 SVN do not report blame on last empty line
lines.add(lines.get(lines.size() - 1));
}
output.blameResult(inputFile, lines);
}
private static boolean checkStatus(SVNClientManager clientManager, InputFile inputFile) throws SVNException {
SVNStatusClient statusClient = clientManager.getStatusClient();
try {
SVNStatus status = statusClient.doStatus(inputFile.file(), false);
if (status == null) {
LOG.debug("File {} returns no svn state. Skipping it.", inputFile);
return false;
}
if (status.getContentsStatus() != SVNStatusType.STATUS_NORMAL) {
LOG.debug("File {} is not versionned or contains local modifications. Skipping it.", inputFile);
return false;
}
} catch (SVNException e) {
if (SVNErrorCode.WC_PATH_NOT_FOUND.equals(e.getErrorMessage().getErrorCode())
|| SVNErrorCode.WC_NOT_WORKING_COPY.equals(e.getErrorMessage().getErrorCode())) {
LOG.debug("File {} is not versionned. Skipping it.", inputFile);
return false;
}
throw e;
}
return true;
}
}
| 4,938 | 37.889764 | 136 | java |
sonarqube | sonarqube-master/sonar-scanner-engine/src/main/java/org/sonar/scm/svn/SvnConfiguration.java | /*
* SonarQube
* Copyright (C) 2009-2023 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.scm.svn;
import java.io.File;
import java.util.Optional;
import javax.annotation.CheckForNull;
import org.sonar.api.config.Configuration;
import org.sonar.api.utils.MessageException;
import static org.sonar.core.config.SvnProperties.PASSPHRASE_PROP_KEY;
import static org.sonar.core.config.SvnProperties.PASSWORD_PROP_KEY;
import static org.sonar.core.config.SvnProperties.PRIVATE_KEY_PATH_PROP_KEY;
import static org.sonar.core.config.SvnProperties.USER_PROP_KEY;
public class SvnConfiguration {
private final Configuration config;
public SvnConfiguration(Configuration config) {
this.config = config;
}
@CheckForNull
public String username() {
return config.get(USER_PROP_KEY).orElse(null);
}
@CheckForNull
public String password() {
return config.get(PASSWORD_PROP_KEY).orElse(null);
}
@CheckForNull
public File privateKey() {
Optional<String> privateKeyOpt = config.get(PRIVATE_KEY_PATH_PROP_KEY);
if (privateKeyOpt.isPresent()) {
File privateKeyFile = new File(privateKeyOpt.get());
if (!privateKeyFile.exists() || !privateKeyFile.isFile() || !privateKeyFile.canRead()) {
throw MessageException.of("Unable to read private key from '" + privateKeyFile + "'");
}
return privateKeyFile;
}
return null;
}
@CheckForNull
public String passPhrase() {
return config.get(PASSPHRASE_PROP_KEY).orElse(null);
}
public boolean isEmpty() {
return username() == null && password() == null && privateKey() == null && passPhrase() == null;
}
}
| 2,404 | 32.402778 | 100 | java |
sonarqube | sonarqube-master/sonar-scanner-engine/src/main/java/org/sonar/scm/svn/SvnScmProvider.java | /*
* SonarQube
* Copyright (C) 2009-2023 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.scm.svn;
import java.io.File;
import java.net.MalformedURLException;
import java.net.URISyntaxException;
import java.net.URL;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.time.Instant;
import java.util.HashSet;
import java.util.Map;
import java.util.Set;
import javax.annotation.CheckForNull;
import org.sonar.api.batch.scm.BlameCommand;
import org.sonar.api.batch.scm.ScmProvider;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.tmatesoft.svn.core.SVNDepth;
import org.tmatesoft.svn.core.SVNException;
import org.tmatesoft.svn.core.SVNLogEntryPath;
import org.tmatesoft.svn.core.SVNNodeKind;
import org.tmatesoft.svn.core.SVNURL;
import org.tmatesoft.svn.core.wc.SVNClientManager;
import org.tmatesoft.svn.core.wc.SVNDiffClient;
import org.tmatesoft.svn.core.wc.SVNInfo;
import org.tmatesoft.svn.core.wc.SVNLogClient;
import org.tmatesoft.svn.core.wc.SVNRevision;
import org.tmatesoft.svn.core.wc.SVNWCClient;
import static org.sonar.scm.svn.SvnScmSupport.newSvnClientManager;
public class SvnScmProvider extends ScmProvider {
private static final Logger LOG = LoggerFactory.getLogger(SvnScmProvider.class);
private final SvnConfiguration configuration;
private final SvnBlameCommand blameCommand;
public SvnScmProvider(SvnConfiguration configuration, SvnBlameCommand blameCommand) {
this.configuration = configuration;
this.blameCommand = blameCommand;
}
@Override
public String key() {
return "svn";
}
@Override
public boolean supports(File baseDir) {
File folder = baseDir;
while (folder != null) {
if (new File(folder, ".svn").exists()) {
return true;
}
folder = folder.getParentFile();
}
return false;
}
@Override
public BlameCommand blameCommand() {
return blameCommand;
}
@CheckForNull
@Override
public Set<Path> branchChangedFiles(String targetBranchName, Path rootBaseDir) {
SVNClientManager clientManager = null;
try {
clientManager = newSvnClientManager(configuration);
return computeChangedPaths(rootBaseDir, clientManager);
} catch (SVNException e) {
LOG.warn(e.getMessage());
} finally {
if (clientManager != null) {
try {
clientManager.dispose();
} catch (Exception e) {
LOG.warn("Unable to dispose SVN ClientManager", e);
}
}
}
return null;
}
static Set<Path> computeChangedPaths(Path projectBasedir, SVNClientManager clientManager) throws SVNException {
SVNWCClient wcClient = clientManager.getWCClient();
SVNInfo svnInfo = wcClient.doInfo(projectBasedir.toFile(), null);
// SVN path of the repo root, for example: /C:/Users/JANOSG~1/AppData/Local/Temp/x/y
Path svnRootPath = toPath(svnInfo.getRepositoryRootURL());
// the svn root path may be "" for urls like http://svnserver/
// -> set it to "/" to avoid crashing when using Path.relativize later
if (svnRootPath.equals(Paths.get(""))) {
svnRootPath = Paths.get("/");
}
// SVN path of projectBasedir, for example: /C:/Users/JANOSG~1/AppData/Local/Temp/x/y/branches/b1
Path svnProjectPath = toPath(svnInfo.getURL());
// path of projectBasedir, as "absolute path within the SVN repo", for example: /branches/b1
Path inRepoProjectPath = Paths.get("/").resolve(svnRootPath.relativize(svnProjectPath));
// We inspect "svn log" from latest revision until copy-point.
// The same path may appear in multiple commits, the ordering of changes and removals is important.
Set<Path> paths = new HashSet<>();
Set<Path> removed = new HashSet<>();
SVNLogClient svnLogClient = clientManager.getLogClient();
svnLogClient.doLog(new File[] {projectBasedir.toFile()}, null, null, null, true, true, 0, svnLogEntry ->
svnLogEntry.getChangedPaths().values().forEach(entry -> {
if (entry.getKind().equals(SVNNodeKind.FILE)) {
Path path = projectBasedir.resolve(inRepoProjectPath.relativize(Paths.get(entry.getPath())));
if (isModified(entry)) {
// Skip if the path is removed in a more recent commit
if (!removed.contains(path)) {
paths.add(path);
}
} else if (entry.getType() == SVNLogEntryPath.TYPE_DELETED) {
removed.add(path);
}
}
}));
return paths;
}
private static Path toPath(SVNURL svnUrl) {
if ("file".equals(svnUrl.getProtocol())) {
try {
return Paths.get(new URL("file", svnUrl.getHost(), svnUrl.getPath()).toURI());
} catch (URISyntaxException | MalformedURLException e) {
throw new IllegalStateException(e);
}
}
return Paths.get(svnUrl.getURIEncodedPath());
}
private static boolean isModified(SVNLogEntryPath entry) {
return entry.getType() == SVNLogEntryPath.TYPE_ADDED
|| entry.getType() == SVNLogEntryPath.TYPE_MODIFIED;
}
@CheckForNull
@Override
public Map<Path, Set<Integer>> branchChangedLines(String targetBranchName, Path rootBaseDir, Set<Path> changedFiles) {
SVNClientManager clientManager = null;
try {
clientManager = newSvnClientManager(configuration);
// find reference revision number: the copy point
SVNLogClient svnLogClient = clientManager.getLogClient();
long[] revisionCounter = {0};
svnLogClient.doLog(new File[] {rootBaseDir.toFile()}, null, null, null, true, true, 0,
svnLogEntry -> revisionCounter[0] = svnLogEntry.getRevision());
long startRev = revisionCounter[0];
SVNDiffClient svnDiffClient = clientManager.getDiffClient();
File path = rootBaseDir.toFile();
ChangedLinesComputer computer = newChangedLinesComputer(rootBaseDir, changedFiles);
svnDiffClient.doDiff(path, SVNRevision.create(startRev), path, SVNRevision.WORKING, SVNDepth.INFINITY, false, computer.receiver(), null);
return computer.changedLines();
} catch (Exception e) {
LOG.warn("Failed to get changed lines from Subversion", e);
} finally {
if (clientManager != null) {
try {
clientManager.dispose();
} catch (Exception e) {
LOG.warn("Unable to dispose SVN ClientManager", e);
}
}
}
return null;
}
@CheckForNull
@Override
public Instant forkDate(String referenceBranch, Path rootBaseDir) {
return null;
}
ChangedLinesComputer newChangedLinesComputer(Path rootBaseDir, Set<Path> changedFiles) {
return new ChangedLinesComputer(rootBaseDir, changedFiles);
}
}
| 7,404 | 34.261905 | 143 | java |
sonarqube | sonarqube-master/sonar-scanner-engine/src/main/java/org/sonar/scm/svn/SvnScmSupport.java | /*
* SonarQube
* Copyright (C) 2009-2023 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.scm.svn;
import java.util.Arrays;
import java.util.List;
import javax.annotation.CheckForNull;
import javax.annotation.Nullable;
import org.tmatesoft.svn.core.auth.ISVNAuthenticationManager;
import org.tmatesoft.svn.core.wc.ISVNOptions;
import org.tmatesoft.svn.core.wc.SVNClientManager;
import org.tmatesoft.svn.core.wc.SVNWCUtil;
public class SvnScmSupport {
private SvnScmSupport() {
// static only
}
static SVNClientManager newSvnClientManager(SvnConfiguration configuration) {
ISVNOptions options = SVNWCUtil.createDefaultOptions(true);
final char[] passwordValue = getCharsOrNull(configuration.password());
final char[] passPhraseValue = getCharsOrNull(configuration.passPhrase());
ISVNAuthenticationManager authManager = SVNWCUtil.createDefaultAuthenticationManager(
null,
configuration.username(),
passwordValue,
configuration.privateKey(),
passPhraseValue,
false);
return SVNClientManager.newInstance(options, authManager);
}
@CheckForNull
private static char[] getCharsOrNull(@Nullable String s) {
return s != null ? s.toCharArray() : null;
}
public static List<Object> getObjects() {
return Arrays.asList(SvnScmProvider.class,
SvnBlameCommand.class,
SvnConfiguration.class
);
}
}
| 2,159 | 33.83871 | 89 | java |
sonarqube | sonarqube-master/sonar-scanner-engine/src/main/java/org/sonar/scm/svn/package-info.java | /*
* SonarQube
* Copyright (C) 2009-2023 SonarSource SA
* mailto:info AT sonarsource DOT com
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 3 of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this program; if not, write to the Free Software Foundation,
* Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*/
@ParametersAreNonnullByDefault
package org.sonar.scm.svn;
import javax.annotation.ParametersAreNonnullByDefault;
| 958 | 37.36 | 75 | java |
sonarqube | sonarqube-master/sonar-scanner-engine/src/test/java/org/sonar/batch/bootstrapper/BatchTest.java | /*
* SonarQube
* Copyright (C) 2009-2023 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.batch.bootstrapper;
import java.time.LocalDate;
import java.time.ZoneId;
import java.time.format.DateTimeFormatter;
import org.junit.Test;
import static org.assertj.core.api.Assertions.assertThat;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertNull;
import static org.mockito.Mockito.mock;
public class BatchTest {
private static final DateTimeFormatter FORMATTER = DateTimeFormatter.ofPattern("yyyy-MM-dd'T'HH:mm:ssZ");
@Test
public void testBuilder() {
System.out.println(FORMATTER.format(LocalDate.parse("2019-05-02").atStartOfDay(ZoneId.systemDefault())));
Batch batch = newBatch();
assertNotNull(batch);
}
private Batch newBatch() {
return Batch.builder()
.setEnvironment(new EnvironmentInformation("Gradle", "1.0"))
.addComponent("fake")
.build();
}
@Test(expected = IllegalStateException.class)
public void shouldFailIfNullComponents() {
Batch.builder()
.setEnvironment(new EnvironmentInformation("Gradle", "1.0"))
.setComponents(null)
.build();
}
@Test
public void shouldDisableLoggingConfiguration() {
Batch batch = Batch.builder()
.setEnvironment(new EnvironmentInformation("Gradle", "1.0"))
.addComponent("fake")
.setEnableLoggingConfiguration(false)
.build();
assertNull(batch.getLoggingConfiguration());
}
@Test
public void loggingConfigurationShouldBeEnabledByDefault() {
assertNotNull(newBatch().getLoggingConfiguration());
}
@Test
public void shoudSetLogListener() {
LogOutput logOutput = mock(LogOutput.class);
Batch batch = Batch.builder().setLogOutput(logOutput).build();
assertThat(batch.getLoggingConfiguration().getLogOutput()).isEqualTo(logOutput);
}
}
| 2,623 | 31.8 | 109 | java |
sonarqube | sonarqube-master/sonar-scanner-engine/src/test/java/org/sonar/batch/bootstrapper/EnvironmentInformationTest.java | /*
* SonarQube
* Copyright (C) 2009-2023 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.batch.bootstrapper;
import org.junit.Test;
import static org.assertj.core.api.Assertions.assertThat;
public class EnvironmentInformationTest {
@Test
public void test_bean() {
EnvironmentInformation env = new EnvironmentInformation("Maven Plugin", "2.0");
assertThat(env.getKey()).isEqualTo("Maven Plugin");
assertThat(env.getVersion()).isEqualTo("2.0");
}
@Test
public void test_toString() {
EnvironmentInformation env = new EnvironmentInformation("Maven Plugin", "2.0");
assertThat(env).hasToString("Maven Plugin/2.0");
}
}
| 1,424 | 32.928571 | 83 | java |
sonarqube | sonarqube-master/sonar-scanner-engine/src/test/java/org/sonar/batch/bootstrapper/LogCallbackAppenderTest.java | /*
* SonarQube
* Copyright (C) 2009-2023 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.batch.bootstrapper;
import ch.qos.logback.classic.Level;
import ch.qos.logback.classic.spi.ILoggingEvent;
import org.junit.Before;
import org.junit.Test;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.reset;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.verifyNoMoreInteractions;
import static org.mockito.Mockito.when;
public class LogCallbackAppenderTest {
private LogOutput listener;
private LogCallbackAppender appender;
private ILoggingEvent event;
@Before
public void setUp() {
listener = mock(LogOutput.class);
appender = new LogCallbackAppender(listener);
}
@Test
public void testLevelTranslation() {
testMessage("test", Level.INFO, LogOutput.Level.INFO);
testMessage("test", Level.DEBUG, LogOutput.Level.DEBUG);
testMessage("test", Level.ERROR, LogOutput.Level.ERROR);
testMessage("test", Level.TRACE, LogOutput.Level.TRACE);
testMessage("test", Level.WARN, LogOutput.Level.WARN);
// this should never happen
testMessage("test", Level.OFF, LogOutput.Level.DEBUG);
}
private void testMessage(String msg, Level level, LogOutput.Level translatedLevel) {
reset(listener);
event = mock(ILoggingEvent.class);
when(event.getFormattedMessage()).thenReturn(msg);
when(event.getLevel()).thenReturn(level);
appender.append(event);
verify(event).getFormattedMessage();
verify(event).getLevel();
verify(event).getThrowableProxy();
verify(listener).log(msg, translatedLevel);
verifyNoMoreInteractions(event, listener);
}
@Test
public void testChangeTarget() {
listener = mock(LogOutput.class);
appender.setTarget(listener);
testLevelTranslation();
}
}
| 2,591 | 32.230769 | 86 | java |
sonarqube | sonarqube-master/sonar-scanner-engine/src/test/java/org/sonar/batch/bootstrapper/LoggingConfigurationTest.java | /*
* SonarQube
* Copyright (C) 2009-2023 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.batch.bootstrapper;
import java.util.HashMap;
import java.util.Map;
import org.junit.Test;
import static org.assertj.core.api.Assertions.assertThat;
import static org.mockito.Mockito.mock;
public class LoggingConfigurationTest {
@Test
public void testSetVerbose() {
assertThat(new LoggingConfiguration(null).setVerbose(true)
.getSubstitutionVariable(LoggingConfiguration.PROPERTY_ROOT_LOGGER_LEVEL)).isEqualTo(LoggingConfiguration.LEVEL_ROOT_VERBOSE);
assertThat(new LoggingConfiguration(null).setVerbose(false)
.getSubstitutionVariable(LoggingConfiguration.PROPERTY_ROOT_LOGGER_LEVEL)).isEqualTo(LoggingConfiguration.LEVEL_ROOT_DEFAULT);
assertThat(new LoggingConfiguration(null).setRootLevel("ERROR")
.getSubstitutionVariable(LoggingConfiguration.PROPERTY_ROOT_LOGGER_LEVEL)).isEqualTo("ERROR");
}
@Test
public void testSetVerboseAnalysis() {
Map<String, String> props = new HashMap<>();
LoggingConfiguration conf = new LoggingConfiguration(null).setProperties(props);
assertThat(conf.getSubstitutionVariable(LoggingConfiguration.PROPERTY_ROOT_LOGGER_LEVEL)).isEqualTo(LoggingConfiguration.LEVEL_ROOT_DEFAULT);
props.put("sonar.verbose", "true");
conf.setProperties(props);
assertThat(conf.getSubstitutionVariable(LoggingConfiguration.PROPERTY_ROOT_LOGGER_LEVEL)).isEqualTo(LoggingConfiguration.LEVEL_ROOT_VERBOSE);
}
@Test
public void shouldNotBeVerboseByDefault() {
assertThat(new LoggingConfiguration(null)
.getSubstitutionVariable(LoggingConfiguration.PROPERTY_ROOT_LOGGER_LEVEL)).isEqualTo(LoggingConfiguration.LEVEL_ROOT_DEFAULT);
}
@Test
public void test_log_listener_setter() {
LogOutput listener = mock(LogOutput.class);
assertThat(new LoggingConfiguration(null).setLogOutput(listener).getLogOutput()).isEqualTo(listener);
}
@Test
public void test_deprecated_log_properties() {
Map<String, String> properties = new HashMap<>();
assertThat(new LoggingConfiguration(null).setProperties(properties)
.getSubstitutionVariable(LoggingConfiguration.PROPERTY_ROOT_LOGGER_LEVEL)).isEqualTo(LoggingConfiguration.LEVEL_ROOT_DEFAULT);
properties.put("sonar.verbose", "true");
LoggingConfiguration conf = new LoggingConfiguration(null).setProperties(properties);
assertThat(conf.getSubstitutionVariable(LoggingConfiguration.PROPERTY_ROOT_LOGGER_LEVEL)).isEqualTo(LoggingConfiguration.LEVEL_ROOT_VERBOSE);
properties.put("sonar.verbose", "false");
conf = new LoggingConfiguration(null).setProperties(properties);
assertThat(conf.getSubstitutionVariable(LoggingConfiguration.PROPERTY_ROOT_LOGGER_LEVEL)).isEqualTo(LoggingConfiguration.LEVEL_ROOT_DEFAULT);
properties.put("sonar.verbose", "false");
properties.put("sonar.log.profilingLevel", "FULL");
conf = new LoggingConfiguration(null).setProperties(properties);
assertThat(conf.getSubstitutionVariable(LoggingConfiguration.PROPERTY_ROOT_LOGGER_LEVEL)).isEqualTo("DEBUG");
properties.put("sonar.verbose", "false");
properties.put("sonar.log.profilingLevel", "BASIC");
conf = new LoggingConfiguration(null).setProperties(properties);
assertThat(conf.getSubstitutionVariable(LoggingConfiguration.PROPERTY_ROOT_LOGGER_LEVEL)).isEqualTo("DEBUG");
}
@Test
public void test_log_level_property() {
Map<String, String> properties = new HashMap<>();
LoggingConfiguration conf = new LoggingConfiguration(null).setProperties(properties);
assertThat(conf.getSubstitutionVariable(LoggingConfiguration.PROPERTY_ROOT_LOGGER_LEVEL)).isEqualTo("INFO");
properties.put("sonar.log.level", "INFO");
conf = new LoggingConfiguration(null).setProperties(properties);
assertThat(conf.getSubstitutionVariable(LoggingConfiguration.PROPERTY_ROOT_LOGGER_LEVEL)).isEqualTo("INFO");
properties.put("sonar.log.level", "DEBUG");
conf = new LoggingConfiguration(null).setProperties(properties);
assertThat(conf.getSubstitutionVariable(LoggingConfiguration.PROPERTY_ROOT_LOGGER_LEVEL)).isEqualTo("DEBUG");
properties.put("sonar.log.level", "TRACE");
conf = new LoggingConfiguration(null).setProperties(properties);
assertThat(conf.getSubstitutionVariable(LoggingConfiguration.PROPERTY_ROOT_LOGGER_LEVEL)).isEqualTo("DEBUG");
}
@Test
public void testDefaultFormat() {
assertThat(new LoggingConfiguration(null)
.getSubstitutionVariable(LoggingConfiguration.PROPERTY_FORMAT)).isEqualTo(LoggingConfiguration.FORMAT_DEFAULT);
}
@Test
public void testMavenFormat() {
assertThat(new LoggingConfiguration(new EnvironmentInformation("maven", "1.0"))
.getSubstitutionVariable(LoggingConfiguration.PROPERTY_FORMAT)).isEqualTo(LoggingConfiguration.FORMAT_MAVEN);
}
@Test
public void testSetFormat() {
assertThat(new LoggingConfiguration(null).setFormat("%d %level")
.getSubstitutionVariable(LoggingConfiguration.PROPERTY_FORMAT)).isEqualTo("%d %level");
}
@Test
public void shouldNotSetBlankFormat() {
assertThat(new LoggingConfiguration(null).setFormat(null)
.getSubstitutionVariable(LoggingConfiguration.PROPERTY_FORMAT)).isEqualTo(LoggingConfiguration.FORMAT_DEFAULT);
assertThat(new LoggingConfiguration(null).setFormat("")
.getSubstitutionVariable(LoggingConfiguration.PROPERTY_FORMAT)).isEqualTo(LoggingConfiguration.FORMAT_DEFAULT);
assertThat(new LoggingConfiguration(null).setFormat(" ")
.getSubstitutionVariable(LoggingConfiguration.PROPERTY_FORMAT)).isEqualTo(LoggingConfiguration.FORMAT_DEFAULT);
}
}
| 6,413 | 44.814286 | 145 | java |
sonarqube | sonarqube-master/sonar-scanner-engine/src/test/java/org/sonar/batch/bootstrapper/LoggingConfiguratorTest.java | /*
* SonarQube
* Copyright (C) 2009-2023 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.batch.bootstrapper;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.PrintStream;
import java.io.UnsupportedEncodingException;
import java.nio.charset.StandardCharsets;
import org.apache.commons.io.IOUtils;
import org.junit.Before;
import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.TemporaryFolder;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import static org.assertj.core.api.Assertions.assertThat;
public class LoggingConfiguratorTest {
private static final String DEFAULT_CLASSPATH_CONF = "/org/sonar/batch/bootstrapper/logback.xml";
private static final String TEST_STR = "foo";
private LoggingConfiguration conf = new LoggingConfiguration();
private ByteArrayOutputStream out;
private SimpleLogListener listener;
@Rule
public TemporaryFolder folder = new TemporaryFolder();
@Before
public void setUp() {
out = new ByteArrayOutputStream();
conf = new LoggingConfiguration();
listener = new SimpleLogListener();
}
private static class SimpleLogListener implements LogOutput {
String msg;
LogOutput.Level level;
@Override
public void log(String msg, LogOutput.Level level) {
this.msg = msg;
this.level = level;
}
}
@Test
public void testWithFile() throws IOException {
InputStream is = this.getClass().getResourceAsStream(DEFAULT_CLASSPATH_CONF);
File tmpFolder = folder.getRoot();
File testFile = new File(tmpFolder, "test");
OutputStream os = new FileOutputStream(testFile);
IOUtils.copy(is, os);
os.close();
conf.setLogOutput(listener);
LoggingConfigurator.apply(conf, testFile);
Logger logger = LoggerFactory.getLogger(this.getClass());
logger.info(TEST_STR);
assertThat(listener.msg).endsWith(TEST_STR);
assertThat(listener.level).isEqualTo(LogOutput.Level.INFO);
}
@Test
public void testCustomAppender() {
conf.setLogOutput(listener);
LoggingConfigurator.apply(conf);
Logger logger = LoggerFactory.getLogger(this.getClass());
logger.info(TEST_STR);
assertThat(listener.msg).endsWith(TEST_STR);
assertThat(listener.level).isEqualTo(LogOutput.Level.INFO);
}
@Test
public void testNoStdout() throws UnsupportedEncodingException {
System.setOut(new PrintStream(out, false, StandardCharsets.UTF_8.name()));
conf.setLogOutput(listener);
LoggingConfigurator.apply(conf);
Logger logger = LoggerFactory.getLogger(this.getClass());
logger.error(TEST_STR);
logger.info(TEST_STR);
logger.debug(TEST_STR);
assertThat(out.size()).isZero();
}
@Test
public void testConfigureMultipleTimes() throws UnsupportedEncodingException {
System.setOut(new PrintStream(out, false, StandardCharsets.UTF_8.name()));
conf.setLogOutput(listener);
LoggingConfigurator.apply(conf);
Logger logger = LoggerFactory.getLogger(this.getClass());
logger.debug("debug");
assertThat(listener.msg).isNull();
conf.setVerbose(true);
LoggingConfigurator.apply(conf);
logger.debug("debug");
assertThat(listener.msg).isEqualTo("debug");
}
@Test
public void testFormatNoEffect() {
conf.setLogOutput(listener);
conf.setFormat("%t");
LoggingConfigurator.apply(conf);
Logger logger = LoggerFactory.getLogger(this.getClass());
logger.info("info");
assertThat(listener.msg).isEqualTo("info");
}
@Test
public void testNoListener() throws UnsupportedEncodingException {
System.setOut(new PrintStream(out, false, StandardCharsets.UTF_8.name()));
LoggingConfigurator.apply(conf);
Logger logger = LoggerFactory.getLogger(this.getClass());
logger.info("info");
assertThat(out.toString(StandardCharsets.UTF_8)).contains("info");
}
}
| 4,738 | 29.574194 | 99 | java |
sonarqube | sonarqube-master/sonar-scanner-engine/src/test/java/org/sonar/scanner/DefaultFileLinesContextTest.java | /*
* SonarQube
* Copyright (C) 2009-2023 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;
import java.util.List;
import org.junit.Before;
import org.junit.Test;
import org.mockito.ArgumentCaptor;
import org.sonar.api.batch.fs.internal.DefaultInputFile;
import org.sonar.api.batch.fs.internal.TestInputFileBuilder;
import org.sonar.api.batch.measure.MetricFinder;
import org.sonar.api.batch.sensor.internal.SensorStorage;
import org.sonar.api.batch.sensor.measure.internal.DefaultMeasure;
import org.sonar.api.measures.CoreMetrics;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatThrownBy;
import static org.assertj.core.api.Assertions.tuple;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.times;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
import static org.sonar.api.measures.CoreMetrics.EXECUTABLE_LINES_DATA_KEY;
import static org.sonar.api.measures.CoreMetrics.NCLOC_DATA_KEY;
public class DefaultFileLinesContextTest {
private static final String HITS_METRIC_KEY = "hits";
private static final String AUTHOR_METRIC_KEY = "author";
private static final String BRANCHES_METRIC_KEY = "branches";
private DefaultFileLinesContext fileLineMeasures;
private SensorStorage sensorStorage;
private DefaultInputFile file;
@Before
public void setUp() {
MetricFinder metricFinder = mock(MetricFinder.class);
org.sonar.api.batch.measure.Metric<String> hitsMetric = mock(org.sonar.api.batch.measure.Metric.class);
when(hitsMetric.valueType()).thenReturn(String.class);
when(hitsMetric.key()).thenReturn(HITS_METRIC_KEY);
when(metricFinder.<String>findByKey(HITS_METRIC_KEY)).thenReturn(hitsMetric);
org.sonar.api.batch.measure.Metric<String> authorMetric = mock(org.sonar.api.batch.measure.Metric.class);
when(authorMetric.valueType()).thenReturn(String.class);
when(authorMetric.key()).thenReturn(AUTHOR_METRIC_KEY);
when(metricFinder.<String>findByKey(AUTHOR_METRIC_KEY)).thenReturn(authorMetric);
org.sonar.api.batch.measure.Metric<String> branchesMetric = mock(org.sonar.api.batch.measure.Metric.class);
when(branchesMetric.valueType()).thenReturn(String.class);
when(branchesMetric.key()).thenReturn(BRANCHES_METRIC_KEY);
when(metricFinder.<String>findByKey(BRANCHES_METRIC_KEY)).thenReturn(branchesMetric);
when(metricFinder.<String>findByKey(CoreMetrics.NCLOC_DATA_KEY)).thenReturn(CoreMetrics.NCLOC_DATA);
when(metricFinder.<String>findByKey(CoreMetrics.EXECUTABLE_LINES_DATA_KEY)).thenReturn(CoreMetrics.EXECUTABLE_LINES_DATA);
sensorStorage = mock(SensorStorage.class);
file = new TestInputFileBuilder("foo", "src/foo.php").initMetadata("Foo\nbar\nbiz").build();
fileLineMeasures = new DefaultFileLinesContext(sensorStorage, file, metricFinder);
}
@Test
public void shouldSave() {
fileLineMeasures.setIntValue(HITS_METRIC_KEY, 1, 2);
fileLineMeasures.setIntValue(HITS_METRIC_KEY, 3, 0);
fileLineMeasures.save();
assertThat(fileLineMeasures).hasToString("DefaultFileLinesContext{{hits={1=2, 3=0}}}");
ArgumentCaptor<DefaultMeasure> captor = ArgumentCaptor.forClass(DefaultMeasure.class);
verify(sensorStorage).store(captor.capture());
DefaultMeasure measure = captor.getValue();
assertThat(measure.inputComponent()).isEqualTo(file);
assertThat(measure.metric().key()).isEqualTo(HITS_METRIC_KEY);
assertThat(measure.value()).isEqualTo("1=2;3=0");
}
@Test
public void validateLineGreaterThanZero() {
assertThatThrownBy(() -> fileLineMeasures.setIntValue(HITS_METRIC_KEY, 0, 2))
.hasMessage("Line number should be positive for file src/foo.php.");
}
@Test
public void validateLineLowerThanLineCount() {
assertThatThrownBy(() -> fileLineMeasures.setIntValue(HITS_METRIC_KEY, 4, 2))
.hasMessageContaining("Line 4 is out of range for file src/foo.php. File has 3 lines");
}
@Test
public void optimizeValues() {
fileLineMeasures.setIntValue(NCLOC_DATA_KEY, 1, 0);
fileLineMeasures.setIntValue(NCLOC_DATA_KEY, 2, 1);
fileLineMeasures.setIntValue(EXECUTABLE_LINES_DATA_KEY, 1, 0);
fileLineMeasures.setIntValue(EXECUTABLE_LINES_DATA_KEY, 2, 1);
fileLineMeasures.save();
ArgumentCaptor<DefaultMeasure> captor = ArgumentCaptor.forClass(DefaultMeasure.class);
verify(sensorStorage, times(2)).store(captor.capture());
List<DefaultMeasure> measures = captor.getAllValues();
assertThat(measures).extracting(DefaultMeasure::inputComponent, m -> m.metric().key(), DefaultMeasure::value)
.containsExactlyInAnyOrder(tuple(file, NCLOC_DATA_KEY, "2=1"),
tuple(file, EXECUTABLE_LINES_DATA_KEY, "2=1"));
}
@Test
public void shouldSaveSeveral() {
fileLineMeasures.setIntValue(HITS_METRIC_KEY, 1, 2);
fileLineMeasures.setIntValue(HITS_METRIC_KEY, 3, 4);
fileLineMeasures.setStringValue(AUTHOR_METRIC_KEY, 1, "simon");
fileLineMeasures.setStringValue(AUTHOR_METRIC_KEY, 3, "evgeny");
fileLineMeasures.save();
fileLineMeasures.setIntValue(BRANCHES_METRIC_KEY, 1, 2);
fileLineMeasures.setIntValue(BRANCHES_METRIC_KEY, 3, 4);
fileLineMeasures.save();
ArgumentCaptor<DefaultMeasure> captor = ArgumentCaptor.forClass(DefaultMeasure.class);
verify(sensorStorage, times(3)).store(captor.capture());
List<DefaultMeasure> measures = captor.getAllValues();
assertThat(measures).extracting(DefaultMeasure::inputComponent, m -> m.metric().key(), DefaultMeasure::value)
.containsExactlyInAnyOrder(tuple(file, HITS_METRIC_KEY, "1=2;3=4"),
tuple(file, AUTHOR_METRIC_KEY, "1=simon;3=evgeny"),
tuple(file, BRANCHES_METRIC_KEY, "1=2;3=4"));
}
@Test(expected = UnsupportedOperationException.class)
public void shouldNotModifyAfterSave() {
fileLineMeasures.setIntValue(HITS_METRIC_KEY, 1, 2);
fileLineMeasures.save();
fileLineMeasures.setIntValue(HITS_METRIC_KEY, 1, 2);
}
}
| 6,777 | 43.887417 | 126 | java |
sonarqube | sonarqube-master/sonar-scanner-engine/src/test/java/org/sonar/scanner/FakeJava.java | /*
* SonarQube
* Copyright (C) 2009-2023 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;
import org.sonar.api.resources.AbstractLanguage;
public class FakeJava extends AbstractLanguage {
public static final String KEY = "java";
public static final FakeJava INSTANCE = new FakeJava();
public FakeJava() {
super(KEY, "Java");
}
@Override
public String[] getFileSuffixes() {
return new String[] {".java", ".jav"};
}
}
| 1,224 | 30.410256 | 75 | java |
sonarqube | sonarqube-master/sonar-scanner-engine/src/test/java/org/sonar/scanner/ProjectInfoTest.java | /*
* SonarQube
* Copyright (C) 2009-2023 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;
import com.tngtech.java.junit.dataprovider.DataProvider;
import com.tngtech.java.junit.dataprovider.DataProviderRunner;
import com.tngtech.java.junit.dataprovider.UseDataProvider;
import java.time.Clock;
import java.time.LocalDate;
import java.time.OffsetDateTime;
import java.time.ZoneId;
import java.time.ZoneOffset;
import java.util.Date;
import javax.annotation.Nullable;
import org.apache.commons.lang.RandomStringUtils;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.sonar.api.CoreProperties;
import org.sonar.api.config.internal.MapSettings;
import org.sonar.api.utils.MessageException;
import static org.apache.commons.lang.RandomStringUtils.randomAlphabetic;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatThrownBy;
import static org.mockito.Mockito.mock;
@RunWith(DataProviderRunner.class)
public class ProjectInfoTest {
private MapSettings settings = new MapSettings();
private Clock clock = mock(Clock.class);
private ProjectInfo underTest = new ProjectInfo(settings.asConfig(), clock);
@Test
public void testSimpleDateTime() {
OffsetDateTime date = OffsetDateTime.of(2017, 1, 1, 12, 13, 14, 0, ZoneOffset.ofHours(2));
settings.appendProperty(CoreProperties.PROJECT_DATE_PROPERTY, "2017-01-01T12:13:14+0200");
settings.appendProperty(CoreProperties.PROJECT_VERSION_PROPERTY, "version");
underTest.start();
assertThat(underTest.getAnalysisDate()).isEqualTo(Date.from(date.toInstant()));
assertThat(underTest.getProjectVersion()).contains("version");
}
@Test
public void testSimpleDate() {
LocalDate date = LocalDate.of(2017, 1, 1);
settings.appendProperty(CoreProperties.PROJECT_DATE_PROPERTY, "2017-01-01");
underTest.start();
assertThat(underTest.getAnalysisDate())
.isEqualTo(Date.from(date.atStartOfDay().atZone(ZoneId.systemDefault()).toInstant()));
}
@Test
public void emptyDate() {
settings.setProperty(CoreProperties.PROJECT_DATE_PROPERTY, "");
settings.setProperty(CoreProperties.PROJECT_VERSION_PROPERTY, "version");
assertThatThrownBy(() -> underTest.start())
.isInstanceOf(RuntimeException.class);
}
@Test
public void fail_with_too_long_version() {
String version = randomAlphabetic(101);
settings.setProperty(CoreProperties.PROJECT_DATE_PROPERTY, "2017-01-01");
settings.setProperty(CoreProperties.PROJECT_VERSION_PROPERTY, version);
assertThatThrownBy(() -> underTest.start())
.isInstanceOf(MessageException.class)
.hasMessage("\"" + version + "\" is not a valid project version. " +
"The maximum length is 100 characters.");
}
@Test
public void fail_with_too_long_buildString() {
String buildString = randomAlphabetic(101);
settings.setProperty(CoreProperties.PROJECT_DATE_PROPERTY, "2017-01-01");
settings.setProperty(CoreProperties.BUILD_STRING_PROPERTY, buildString);
assertThatThrownBy(() -> underTest.start())
.isInstanceOf(MessageException.class)
.hasMessage("\"" + buildString + "\" is not a valid buildString. " +
"The maximum length is 100 characters.");
}
@Test
@UseDataProvider("emptyOrNullString")
public void getProjectVersion_is_empty_if_property_is_empty_or_null(@Nullable String projectVersion) {
settings.setProperty(CoreProperties.PROJECT_DATE_PROPERTY, "2017-01-01");
settings.setProperty(CoreProperties.PROJECT_VERSION_PROPERTY, projectVersion);
underTest.start();
assertThat(underTest.getProjectVersion()).isEmpty();
}
@Test
public void getProjectVersion_contains_value_of_property() {
String value = RandomStringUtils.randomAlphabetic(10);
settings.setProperty(CoreProperties.PROJECT_DATE_PROPERTY, "2017-01-01");
settings.setProperty(CoreProperties.PROJECT_VERSION_PROPERTY, value);
underTest.start();
assertThat(underTest.getProjectVersion()).contains(value);
}
@Test
@UseDataProvider("emptyOrNullString")
public void getBuildString_is_empty_if_property_is_empty_or_null(@Nullable String buildString) {
settings.setProperty(CoreProperties.PROJECT_DATE_PROPERTY, "2017-01-01");
settings.setProperty(CoreProperties.BUILD_STRING_PROPERTY, buildString);
underTest.start();
assertThat(underTest.getBuildString()).isEmpty();
}
@Test
public void getBuildString_contains_value_of_property() {
String value = RandomStringUtils.randomAlphabetic(10);
settings.setProperty(CoreProperties.PROJECT_DATE_PROPERTY, "2017-01-01");
settings.setProperty(CoreProperties.BUILD_STRING_PROPERTY, value);
underTest.start();
assertThat(underTest.getBuildString()).contains(value);
}
@DataProvider
public static Object[][] emptyOrNullString() {
return new Object[][] {
{""},
{null},
};
}
}
| 5,698 | 34.842767 | 104 | java |
sonarqube | sonarqube-master/sonar-scanner-engine/src/test/java/org/sonar/scanner/WsTestUtil.java | /*
* SonarQube
* Copyright (C) 2009-2023 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;
import java.io.InputStream;
import java.io.Reader;
import javax.annotation.Nullable;
import org.apache.commons.lang.StringUtils;
import org.mockito.ArgumentMatcher;
import org.sonar.scanner.bootstrap.DefaultScannerWsClient;
import org.sonarqube.ws.client.WsRequest;
import org.sonarqube.ws.client.WsResponse;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.ArgumentMatchers.argThat;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
public class WsTestUtil {
public static void mockStream(DefaultScannerWsClient mock, String path, InputStream is) {
WsResponse response = mock(WsResponse.class);
when(response.contentStream()).thenReturn(is);
when(mock.call(argThat(new RequestMatcher(path)))).thenReturn(response);
}
public static void mockStream(DefaultScannerWsClient mock, InputStream is) {
WsResponse response = mock(WsResponse.class);
when(response.contentStream()).thenReturn(is);
when(mock.call(any(WsRequest.class))).thenReturn(response);
}
public static void mockReader(DefaultScannerWsClient mock, Reader reader) {
WsResponse response = mock(WsResponse.class);
when(response.contentReader()).thenReturn(reader);
when(mock.call(any(WsRequest.class))).thenReturn(response);
}
public static void mockReader(DefaultScannerWsClient mock, String path, Reader reader, Reader... others) {
WsResponse response = mock(WsResponse.class);
when(response.contentReader()).thenReturn(reader);
WsResponse[] otherResponses = new WsResponse[others.length];
for (int i = 0; i < others.length; i++) {
WsResponse otherResponse = mock(WsResponse.class);
when(otherResponse.contentReader()).thenReturn(others[i]);
otherResponses[i] = otherResponse;
}
when(mock.call(argThat(new RequestMatcher(path)))).thenReturn(response, otherResponses);
}
public static void mockException(DefaultScannerWsClient mock, Exception e) {
when(mock.call(any(WsRequest.class))).thenThrow(e);
}
public static void mockException(DefaultScannerWsClient mock, String path, Exception e) {
when(mock.call(argThat(new RequestMatcher(path)))).thenThrow(e);
}
public static void verifyCall(DefaultScannerWsClient mock, String path) {
verify(mock).call(argThat(new RequestMatcher(path)));
}
private static class RequestMatcher implements ArgumentMatcher<WsRequest> {
private String path;
public RequestMatcher(String path) {
this.path = path;
}
@Override
public boolean matches(@Nullable WsRequest item) {
if (item == null) {
return false;
}
return StringUtils.equals(item.getPath(), path);
}
@Override
public String toString() {
return "Request with path: " + path;
}
}
}
| 3,707 | 35.352941 | 108 | java |
sonarqube | sonarqube-master/sonar-scanner-engine/src/test/java/org/sonar/scanner/analysis/AnalysisTempFolderProviderTest.java | /*
* SonarQube
* Copyright (C) 2009-2023 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.io.File;
import org.junit.Before;
import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.TemporaryFolder;
import org.sonar.api.utils.TempFolder;
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 AnalysisTempFolderProviderTest {
@Rule
public TemporaryFolder temp = new TemporaryFolder();
private AnalysisTempFolderProvider tempFolderProvider;
DefaultInputProject project = mock(DefaultInputProject.class);
@Before
public void setUp() {
tempFolderProvider = new AnalysisTempFolderProvider();
when(project.getWorkDir()).thenReturn(temp.getRoot().toPath());
}
@Test
public void createTempFolder() {
File defaultDir = new File(temp.getRoot(), AnalysisTempFolderProvider.TMP_NAME);
TempFolder tempFolder = tempFolderProvider.provide(project);
tempFolder.newDir();
tempFolder.newFile();
assertThat(defaultDir).exists();
assertThat(defaultDir.list()).hasSize(2);
}
}
| 1,985 | 32.661017 | 84 | java |
sonarqube | sonarqube-master/sonar-scanner-engine/src/test/java/org/sonar/scanner/bootstrap/DefaultScannerWsClientTest.java | /*
* SonarQube
* Copyright (C) 2009-2023 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.time.LocalDateTime;
import java.time.ZoneOffset;
import java.time.format.DateTimeFormatter;
import java.util.Collections;
import java.util.List;
import org.apache.commons.lang.StringUtils;
import org.junit.Rule;
import org.junit.Test;
import org.mockito.Mockito;
import org.slf4j.event.Level;
import org.sonar.api.notifications.AnalysisWarnings;
import org.sonar.api.testfixtures.log.LogTester;
import org.sonar.api.utils.MessageException;
import org.sonar.api.utils.log.LoggerLevel;
import org.sonarqube.ws.client.GetRequest;
import org.sonarqube.ws.client.HttpException;
import org.sonarqube.ws.client.MockWsResponse;
import org.sonarqube.ws.client.WsClient;
import org.sonarqube.ws.client.WsRequest;
import org.sonarqube.ws.client.WsResponse;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatThrownBy;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;
import static org.sonar.api.utils.DateUtils.DATETIME_FORMAT;
public class DefaultScannerWsClientTest {
@Rule
public LogTester logTester = new LogTester();
private final WsClient wsClient = mock(WsClient.class, Mockito.RETURNS_DEEP_STUBS);
private final AnalysisWarnings analysisWarnings = mock(AnalysisWarnings.class);
@Test
public void call_whenDebugLevel_shouldLogAndProfileRequest() {
WsRequest request = newRequest();
WsResponse response = newResponse().setRequestUrl("https://local/api/issues/search");
when(wsClient.wsConnector().call(request)).thenReturn(response);
logTester.setLevel(LoggerLevel.DEBUG);
DefaultScannerWsClient underTest = new DefaultScannerWsClient(wsClient, false, new GlobalAnalysisMode(new ScannerProperties(Collections.emptyMap())), analysisWarnings);
WsResponse result = underTest.call(request);
// do not fail the execution -> interceptor returns the response
assertThat(result).isSameAs(response);
// check logs
List<String> debugLogs = logTester.logs(Level.DEBUG);
assertThat(debugLogs).hasSize(1);
assertThat(debugLogs.get(0)).contains("GET 200 https://local/api/issues/search | time=");
}
@Test
public void createErrorMessage_whenJsonError_shouldCreateErrorMsg() {
String content = "{\"errors\":[{\"msg\":\"missing scan permission\"}, {\"msg\":\"missing another permission\"}]}";
assertThat(DefaultScannerWsClient.createErrorMessage(new HttpException("url", 400, content))).isEqualTo("missing scan permission, missing another permission");
}
@Test
public void createErrorMessage_whenHtml_shouldCreateErrorMsg() {
String content = "<!DOCTYPE html><html>something</html>";
assertThat(DefaultScannerWsClient.createErrorMessage(new HttpException("url", 400, content))).isEqualTo("HTTP code 400");
}
@Test
public void createErrorMessage_whenLongContent_shouldCreateErrorMsg() {
String content = StringUtils.repeat("mystring", 1000);
assertThat(DefaultScannerWsClient.createErrorMessage(new HttpException("url", 400, content))).hasSize(15 + 128);
}
@Test
public void call_whenUnauthorizedAndDebugEnabled_shouldLogResponseDetails() {
WsRequest request = newRequest();
WsResponse response = newResponse()
.setContent("Missing credentials")
.setHeader("Authorization: ", "Bearer ImNotAValidToken")
.setCode(403);
logTester.setLevel(LoggerLevel.DEBUG);
when(wsClient.wsConnector().call(request)).thenReturn(response);
DefaultScannerWsClient client = new DefaultScannerWsClient(wsClient, false,
new GlobalAnalysisMode(new ScannerProperties(Collections.emptyMap())), analysisWarnings);
assertThatThrownBy(() -> client.call(request))
.isInstanceOf(MessageException.class)
.hasMessage(
"You're not authorized to analyze this project or the project doesn't exist on SonarQube and you're not authorized to create it. Please contact an administrator.");
List<String> debugLogs = logTester.logs(Level.DEBUG);
assertThat(debugLogs).hasSize(2);
assertThat(debugLogs.get(1)).contains("Error response content: Missing credentials, headers: {Authorization: =[Bearer ImNotAValidToken]}");
}
@Test
public void call_whenUnauthenticatedAndDebugEnabled_shouldLogResponseDetails() {
WsRequest request = newRequest();
WsResponse response = newResponse()
.setContent("Missing authentication")
.setHeader("X-Test-Header: ", "ImATestHeader")
.setCode(401);
logTester.setLevel(LoggerLevel.DEBUG);
when(wsClient.wsConnector().call(request)).thenReturn(response);
DefaultScannerWsClient client = new DefaultScannerWsClient(wsClient, false,
new GlobalAnalysisMode(new ScannerProperties(Collections.emptyMap())), analysisWarnings);
assertThatThrownBy(() -> client.call(request))
.isInstanceOf(MessageException.class)
.hasMessage("Not authorized. Analyzing this project requires authentication. Please check the user token in the property 'sonar.token' " +
"or the credentials in the properties 'sonar.login' and 'sonar.password'.");
List<String> debugLogs = logTester.logs(Level.DEBUG);
assertThat(debugLogs).hasSize(2);
assertThat(debugLogs.get(1)).contains("Error response content: Missing authentication, headers: {X-Test-Header: =[ImATestHeader]}");
}
@Test
public void call_whenMissingCredentials_shouldFailWithMsg() {
WsRequest request = newRequest();
WsResponse response = newResponse()
.setContent("Missing authentication")
.setCode(401);
when(wsClient.wsConnector().call(request)).thenReturn(response);
DefaultScannerWsClient client = new DefaultScannerWsClient(wsClient, false,
new GlobalAnalysisMode(new ScannerProperties(Collections.emptyMap())), analysisWarnings);
assertThatThrownBy(() -> client.call(request))
.isInstanceOf(MessageException.class)
.hasMessage("Not authorized. Analyzing this project requires authentication. Please check the user token in the property 'sonar.token' " +
"or the credentials in the properties 'sonar.login' and 'sonar.password'.");
}
@Test
public void call_whenInvalidCredentials_shouldFailWithMsg() {
WsRequest request = newRequest();
WsResponse response = newResponse()
.setContent("Invalid credentials")
.setCode(401);
when(wsClient.wsConnector().call(request)).thenReturn(response);
DefaultScannerWsClient client = new DefaultScannerWsClient(wsClient, /* credentials are configured */true,
new GlobalAnalysisMode(new ScannerProperties(Collections.emptyMap())), analysisWarnings);
assertThatThrownBy(() -> client.call(request))
.isInstanceOf(MessageException.class)
.hasMessage("Not authorized. Please check the user token in the property 'sonar.token' or the credentials in the properties 'sonar.login' and 'sonar.password'.");
}
@Test
public void call_whenMissingPermissions_shouldFailWithMsg() {
WsRequest request = newRequest();
WsResponse response = newResponse()
.setContent("Unauthorized")
.setCode(403);
when(wsClient.wsConnector().call(request)).thenReturn(response);
DefaultScannerWsClient client = new DefaultScannerWsClient(wsClient, true,
new GlobalAnalysisMode(new ScannerProperties(Collections.emptyMap())), analysisWarnings);
assertThatThrownBy(() -> client.call(request))
.isInstanceOf(MessageException.class)
.hasMessage(
"You're not authorized to analyze this project or the project doesn't exist on SonarQube and you're not authorized to create it. Please contact an administrator.");
}
@Test
public void call_whenTokenExpirationApproaches_shouldLogWarnings() {
WsRequest request = newRequest();
var fiveDaysLatter = LocalDateTime.now().atZone(ZoneOffset.UTC).plusDays(5);
String expirationDate = DateTimeFormatter
.ofPattern(DATETIME_FORMAT)
.format(fiveDaysLatter);
WsResponse response = newResponse()
.setCode(200)
.setExpirationDate(expirationDate);
when(wsClient.wsConnector().call(request)).thenReturn(response);
logTester.setLevel(LoggerLevel.DEBUG);
DefaultScannerWsClient underTest = new DefaultScannerWsClient(wsClient, false, new GlobalAnalysisMode(new ScannerProperties(Collections.emptyMap())), analysisWarnings);
underTest.call(request);
// the second call should not add the same warning twice
underTest.call(request);
// check logs
List<String> warningLogs = logTester.logs(Level.WARN);
assertThat(warningLogs).hasSize(2);
assertThat(warningLogs.get(0)).contains("The token used for this analysis will expire on: " + fiveDaysLatter.format(DateTimeFormatter.ofPattern("MMMM dd, yyyy")));
assertThat(warningLogs.get(1)).contains("Analysis executed with this token will fail after the expiration date.");
}
@Test
public void call_whenBadRequest_shouldFailWithMessage() {
WsRequest request = newRequest();
WsResponse response = newResponse()
.setCode(400)
.setContent("{\"errors\":[{\"msg\":\"Boo! bad request! bad!\"}]}");
when(wsClient.wsConnector().call(request)).thenReturn(response);
DefaultScannerWsClient client = new DefaultScannerWsClient(wsClient, true,
new GlobalAnalysisMode(new ScannerProperties(Collections.emptyMap())), analysisWarnings);
assertThatThrownBy(() -> client.call(request))
.isInstanceOf(MessageException.class)
.hasMessage("Boo! bad request! bad!");
}
private MockWsResponse newResponse() {
return new MockWsResponse().setRequestUrl("https://local/api/issues/search");
}
private WsRequest newRequest() {
return new GetRequest("api/issues/search");
}
}
| 10,560 | 43.188285 | 172 | java |
sonarqube | sonarqube-master/sonar-scanner-engine/src/test/java/org/sonar/scanner/bootstrap/ExtensionInstallerTest.java | /*
* SonarQube
* Copyright (C) 2009-2023 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.Arrays;
import org.apache.commons.lang.ClassUtils;
import org.junit.Test;
import org.sonar.api.Plugin;
import org.sonar.api.SonarRuntime;
import org.sonar.api.batch.ScannerSide;
import org.sonar.api.config.internal.MapSettings;
import org.sonar.core.platform.ListContainer;
import org.sonar.core.platform.PluginInfo;
import static org.assertj.core.api.Assertions.assertThat;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;
public class ExtensionInstallerTest {
private final MapSettings settings = new MapSettings();
private final ScannerPluginRepository pluginRepository = mock(ScannerPluginRepository.class);
private static Plugin newPluginInstance(final Object... extensions) {
return desc -> desc.addExtensions(Arrays.asList(extensions));
}
@Test
public void should_filter_extensions_to_install() {
when(pluginRepository.getPluginInfos()).thenReturn(Arrays.asList(new PluginInfo("foo")));
when(pluginRepository.getPluginInstance("foo")).thenReturn(newPluginInstance(Foo.class, Bar.class));
ListContainer container = new ListContainer();
ExtensionInstaller installer = new ExtensionInstaller(mock(SonarRuntime.class), pluginRepository, settings.asConfig());
installer.install(container, new FooMatcher());
assertThat(container.getAddedObjects())
.contains(Foo.class)
.doesNotContain(Bar.class);
}
private static class FooMatcher implements ExtensionMatcher {
public boolean accept(Object extension) {
return extension.equals(Foo.class) || ClassUtils.isAssignable(Foo.class, extension.getClass());
}
}
@ScannerSide
public static class Foo {
}
@ScannerSide
public static class Bar {
}
}
| 2,615 | 33.421053 | 123 | java |
sonarqube | sonarqube-master/sonar-scanner-engine/src/test/java/org/sonar/scanner/bootstrap/ExtensionUtilsTest.java | /*
* SonarQube
* Copyright (C) 2009-2023 SonarSource SA
* mailto:info AT sonarsource DOT com
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 3 of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this program; if not, write to the Free Software Foundation,
* Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*/
package org.sonar.scanner.bootstrap;
import org.junit.Test;
import org.sonar.api.batch.InstantiationStrategy;
import org.sonar.api.batch.ScannerSide;
import org.sonar.api.ce.ComputeEngineSide;
import org.sonar.api.server.ServerSide;
import static org.assertj.core.api.Assertions.assertThat;
public class ExtensionUtilsTest {
@Test
public void shouldBeBatchInstantiationStrategy() {
assertThat(ExtensionUtils.isInstantiationStrategy(ProjectService.class, InstantiationStrategy.PER_BATCH)).isFalse();
assertThat(ExtensionUtils.isInstantiationStrategy(new ProjectService(), InstantiationStrategy.PER_BATCH)).isFalse();
assertThat(ExtensionUtils.isInstantiationStrategy(DefaultService.class, InstantiationStrategy.PER_BATCH)).isFalse();
assertThat(ExtensionUtils.isInstantiationStrategy(new DefaultService(), InstantiationStrategy.PER_BATCH)).isFalse();
assertThat(ExtensionUtils.isInstantiationStrategy(DefaultScannerService.class, InstantiationStrategy.PER_BATCH)).isFalse();
assertThat(ExtensionUtils.isInstantiationStrategy(new DefaultScannerService(), InstantiationStrategy.PER_BATCH)).isFalse();
}
@Test
public void shouldBeProjectInstantiationStrategy() {
assertThat(ExtensionUtils.isInstantiationStrategy(ProjectService.class, InstantiationStrategy.PER_PROJECT)).isTrue();
assertThat(ExtensionUtils.isInstantiationStrategy(new ProjectService(), InstantiationStrategy.PER_PROJECT)).isTrue();
assertThat(ExtensionUtils.isInstantiationStrategy(DefaultService.class, InstantiationStrategy.PER_PROJECT)).isTrue();
assertThat(ExtensionUtils.isInstantiationStrategy(new DefaultService(), InstantiationStrategy.PER_PROJECT)).isTrue();
assertThat(ExtensionUtils.isInstantiationStrategy(DefaultScannerService.class, InstantiationStrategy.PER_PROJECT)).isTrue();
assertThat(ExtensionUtils.isInstantiationStrategy(new DefaultScannerService(), InstantiationStrategy.PER_PROJECT)).isTrue();
}
@Test
public void testIsScannerSide() {
assertThat(ExtensionUtils.isDeprecatedScannerSide(ScannerService.class)).isTrue();
assertThat(ExtensionUtils.isDeprecatedScannerSide(ServerService.class)).isFalse();
assertThat(ExtensionUtils.isDeprecatedScannerSide(new ServerService())).isFalse();
assertThat(ExtensionUtils.isDeprecatedScannerSide(new WebServerService())).isFalse();
assertThat(ExtensionUtils.isDeprecatedScannerSide(new ComputeEngineService())).isFalse();
}
@ScannerSide
@InstantiationStrategy(InstantiationStrategy.PER_BATCH)
public static class ScannerService {
}
@ScannerSide
@InstantiationStrategy(InstantiationStrategy.PER_PROJECT)
public static class ProjectService {
}
@ScannerSide
public static class DefaultService {
}
@ScannerSide
public static class DefaultScannerService {
}
@ServerSide
public static class ServerService {
}
@ServerSide
public static class WebServerService {
}
@ComputeEngineSide
public static class ComputeEngineService {
}
}
| 3,849 | 36.745098 | 128 | java |
sonarqube | sonarqube-master/sonar-scanner-engine/src/test/java/org/sonar/scanner/bootstrap/GlobalConfigurationProviderTest.java | /*
* SonarQube
* Copyright (C) 2009-2023 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.Collections;
import org.junit.Before;
import org.junit.Rule;
import org.junit.Test;
import org.sonar.api.config.PropertyDefinitions;
import org.sonar.api.utils.System2;
import org.sonar.api.testfixtures.log.LogTester;
import static org.assertj.core.api.Assertions.assertThat;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;
public class GlobalConfigurationProviderTest {
@Rule
public LogTester logTester = new LogTester();
GlobalServerSettings globalServerSettings;
ScannerProperties scannerProps;
@Before
public void prepare() {
globalServerSettings = mock(GlobalServerSettings.class);
scannerProps = new ScannerProperties(Collections.emptyMap());
}
@Test
public void should_load_global_settings() {
when(globalServerSettings.properties()).thenReturn(ImmutableMap.of("sonar.cpd.cross", "true"));
GlobalConfiguration globalConfig = new GlobalConfigurationProvider().provide(globalServerSettings, scannerProps, new PropertyDefinitions(System2.INSTANCE));
assertThat(globalConfig.get("sonar.cpd.cross")).hasValue("true");
}
}
| 2,049 | 34.344828 | 160 | java |
sonarqube | sonarqube-master/sonar-scanner-engine/src/test/java/org/sonar/scanner/bootstrap/GlobalTempFolderProviderTest.java | /*
* SonarQube
* Copyright (C) 2009-2023 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.io.File;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.attribute.BasicFileAttributeView;
import java.nio.file.attribute.FileTime;
import java.util.Collections;
import java.util.concurrent.TimeUnit;
import org.apache.commons.io.FileUtils;
import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.TemporaryFolder;
import org.sonar.api.CoreProperties;
import org.sonar.api.utils.System2;
import org.sonar.api.utils.TempFolder;
import static org.assertj.core.api.Assertions.assertThat;
import static org.junit.Assume.assumeTrue;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;
public class GlobalTempFolderProviderTest {
@Rule
public TemporaryFolder temp = new TemporaryFolder();
private GlobalTempFolderProvider tempFolderProvider = new GlobalTempFolderProvider();
@Test
public void createTempFolderProps() throws Exception {
File workingDir = temp.newFolder();
workingDir.delete();
TempFolder tempFolder = tempFolderProvider.provide(
new ScannerProperties(ImmutableMap.of(CoreProperties.GLOBAL_WORKING_DIRECTORY, workingDir.getAbsolutePath())));
tempFolder.newDir();
tempFolder.newFile();
assertThat(getCreatedTempDir(workingDir)).exists();
assertThat(getCreatedTempDir(workingDir).list()).hasSize(2);
FileUtils.deleteQuietly(workingDir);
}
@Test
public void cleanUpOld() throws IOException {
long creationTime = System.currentTimeMillis() - TimeUnit.DAYS.toMillis(100);
File workingDir = temp.newFolder();
for (int i = 0; i < 3; i++) {
File tmp = new File(workingDir, ".sonartmp_" + i);
tmp.mkdirs();
setFileCreationDate(tmp, creationTime);
}
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();
FileUtils.deleteQuietly(workingDir);
}
@Test
public void createTempFolderSonarHome() throws Exception {
// with sonar home, it will be in {sonar.home}/.sonartmp
File sonarHome = temp.newFolder();
File workingDir = new File(sonarHome, CoreProperties.GLOBAL_WORKING_DIRECTORY_DEFAULT_VALUE).getAbsoluteFile();
TempFolder tempFolder = tempFolderProvider.provide(
new ScannerProperties(ImmutableMap.of("sonar.userHome", sonarHome.getAbsolutePath())));
tempFolder.newDir();
tempFolder.newFile();
assertThat(getCreatedTempDir(workingDir)).exists();
assertThat(getCreatedTempDir(workingDir).list()).hasSize(2);
FileUtils.deleteQuietly(sonarHome);
}
@Test
public void createTempFolderDefault() throws Exception {
System2 system = mock(System2.class);
tempFolderProvider = new GlobalTempFolderProvider(system);
File userHome = temp.newFolder();
when(system.envVariable("SONAR_USER_HOME")).thenReturn(null);
when(system.property("user.home")).thenReturn(userHome.getAbsolutePath());
// if nothing is defined, it will be in {user.home}/.sonar/.sonartmp
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 ScannerProperties(Collections.emptyMap()));
tempFolder.newDir();
tempFolder.newFile();
assertThat(getCreatedTempDir(workingDir)).exists();
assertThat(getCreatedTempDir(workingDir).list()).hasSize(2);
} finally {
FileUtils.deleteQuietly(workingDir);
}
}
@Test
public void dotWorkingDir() {
File sonarHome = temp.getRoot();
String globalWorkDir = ".";
ScannerProperties globalProperties = new ScannerProperties(
ImmutableMap.of("sonar.userHome", sonarHome.getAbsolutePath(), CoreProperties.GLOBAL_WORKING_DIRECTORY, globalWorkDir));
TempFolder tempFolder = tempFolderProvider.provide(globalProperties);
File newFile = tempFolder.newFile();
assertThat(newFile.getParentFile().getParentFile().getAbsolutePath()).isEqualTo(sonarHome.getAbsolutePath());
assertThat(newFile.getParentFile().getName()).startsWith(".sonartmp_");
}
@Test
public void homeIsSymbolicLink() throws IOException {
assumeTrue(!System2.INSTANCE.isOsWindows());
File realSonarHome = temp.newFolder();
File symlink = temp.newFolder();
symlink.delete();
Files.createSymbolicLink(symlink.toPath(), realSonarHome.toPath());
ScannerProperties globalProperties = new ScannerProperties(ImmutableMap.of("sonar.userHome", symlink.getAbsolutePath()));
TempFolder tempFolder = tempFolderProvider.provide(globalProperties);
File newFile = tempFolder.newFile();
assertThat(newFile.getParentFile().getParentFile().getAbsolutePath()).isEqualTo(symlink.getAbsolutePath());
assertThat(newFile.getParentFile().getName()).startsWith(".sonartmp_");
}
private File getCreatedTempDir(File workingDir) {
assertThat(workingDir).isDirectory();
assertThat(workingDir.listFiles()).hasSize(1);
return workingDir.listFiles()[0];
}
private void setFileCreationDate(File f, long time) throws IOException {
BasicFileAttributeView attributes = Files.getFileAttributeView(f.toPath(), BasicFileAttributeView.class);
FileTime creationTime = FileTime.fromMillis(time);
attributes.setTimes(creationTime, creationTime, creationTime);
}
}
| 6,456 | 38.613497 | 126 | java |
sonarqube | sonarqube-master/sonar-scanner-engine/src/test/java/org/sonar/scanner/bootstrap/ModuleSensorExtensionDictionaryTest.java | /*
* SonarQube
* Copyright (C) 2009-2023 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.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.List;
import org.junit.Before;
import org.junit.Test;
import org.sonar.api.batch.DependedUpon;
import org.sonar.api.batch.DependsUpon;
import org.sonar.api.batch.Phase;
import org.sonar.api.batch.ScannerSide;
import org.sonar.api.batch.sensor.Sensor;
import org.sonar.api.batch.sensor.SensorContext;
import org.sonar.api.batch.sensor.SensorDescriptor;
import org.sonar.api.batch.sensor.internal.DefaultSensorDescriptor;
import org.sonar.core.platform.ExtensionContainer;
import org.sonar.scanner.scan.branch.BranchConfiguration;
import org.sonar.scanner.scan.filesystem.MutableFileSystem;
import org.sonar.scanner.sensor.ModuleSensorContext;
import org.sonar.scanner.sensor.ModuleSensorExtensionDictionary;
import org.sonar.scanner.sensor.ModuleSensorOptimizer;
import org.sonar.scanner.sensor.ModuleSensorWrapper;
import static org.assertj.core.api.Assertions.assertThat;
import static org.junit.Assert.assertEquals;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;
public class ModuleSensorExtensionDictionaryTest {
private final ModuleSensorOptimizer sensorOptimizer = mock(ModuleSensorOptimizer.class);
private final MutableFileSystem fileSystem = mock(MutableFileSystem.class);
private final BranchConfiguration branchConfiguration = mock(BranchConfiguration.class);
@Before
public void setUp() {
when(sensorOptimizer.shouldExecute(any(DefaultSensorDescriptor.class))).thenReturn(true);
}
private ModuleSensorExtensionDictionary newSelector(Class type, Object... instances) {
ExtensionContainer iocContainer = mock(ExtensionContainer.class);
when(iocContainer.getComponentsByType(type)).thenReturn(Arrays.asList(instances));
return new ModuleSensorExtensionDictionary(iocContainer, mock(ModuleSensorContext.class), sensorOptimizer, fileSystem, branchConfiguration);
}
@Test
public void testGetFilteredExtensionWithExtensionMatcher() {
final Sensor sensor1 = new FakeSensor();
final Sensor sensor2 = new FakeSensor();
ModuleSensorExtensionDictionary selector = newSelector(Sensor.class, sensor1, sensor2);
Collection<Sensor> sensors = selector.select(Sensor.class, true, extension -> extension.equals(sensor1));
assertThat(sensors).contains(sensor1);
assertEquals(1, sensors.size());
}
@Test
public void testGetFilteredExtensions() {
Sensor sensor1 = new FakeSensor();
Sensor sensor2 = new FakeSensor();
ModuleSensorExtensionDictionary selector = newSelector(Sensor.class, sensor1, sensor2);
Collection<Sensor> sensors = selector.select(Sensor.class, false, null);
assertThat(sensors).containsOnly(sensor1, sensor2);
}
@Test
public void shouldSearchInParentContainers() {
Sensor a = new FakeSensor();
Sensor b = new FakeSensor();
Sensor c = new FakeSensor();
ExtensionContainer grandParent = mock(ExtensionContainer.class);
when(grandParent.getComponentsByType(Sensor.class)).thenReturn(List.of(a));
ExtensionContainer parent = mock(ExtensionContainer.class);
when(parent.getComponentsByType(Sensor.class)).thenReturn(List.of(b));
when(parent.getParent()).thenReturn(grandParent);
ExtensionContainer child = mock(ExtensionContainer.class);
when(child.getComponentsByType(Sensor.class)).thenReturn(List.of(c));
when(child.getParent()).thenReturn(parent);
ModuleSensorExtensionDictionary dictionnary = new ModuleSensorExtensionDictionary(child, mock(ModuleSensorContext.class), mock(ModuleSensorOptimizer.class),
fileSystem, branchConfiguration);
assertThat(dictionnary.select(Sensor.class, true, null)).containsOnly(a, b, c);
}
@Test
public void sortExtensionsByDependency() {
Object a = new MethodDependentOf(null);
Object b = new MethodDependentOf(a);
Object c = new MethodDependentOf(b);
ModuleSensorExtensionDictionary selector = newSelector(Marker.class, b, c, a);
List<Object> extensions = new ArrayList<>(selector.select(Marker.class, true, null));
assertThat(extensions).hasSize(3);
assertThat(extensions.get(0)).isEqualTo(a);
assertThat(extensions.get(1)).isEqualTo(b);
assertThat(extensions.get(2)).isEqualTo(c);
}
@Test
public void useMethodAnnotationsToSortExtensions() {
Object a = new GeneratesSomething("foo");
Object b = new MethodDependentOf("foo");
ModuleSensorExtensionDictionary selector = newSelector(Marker.class, a, b);
List<Object> extensions = new ArrayList<>(selector.select(Marker.class, true, null));
assertThat(extensions).hasSize(2);
assertThat(extensions.get(0)).isEqualTo(a);
assertThat(extensions.get(1)).isEqualTo(b);
// different initial order
selector = newSelector(Marker.class, b, a);
extensions = new ArrayList<>(selector.select(Marker.class, true, null));
assertThat(extensions).hasSize(2);
assertThat(extensions.get(0)).isEqualTo(a);
assertThat(extensions.get(1)).isEqualTo(b);
}
@Test
public void methodDependsUponCollection() {
Object a = new GeneratesSomething("foo");
Object b = new MethodDependentOf(Arrays.asList("foo"));
ModuleSensorExtensionDictionary selector = newSelector(Marker.class, a, b);
List<Object> extensions = new ArrayList<>(selector.select(Marker.class, true, null));
assertThat(extensions).hasSize(2);
assertThat(extensions.get(0)).isEqualTo(a);
assertThat(extensions.get(1)).isEqualTo(b);
// different initial order
selector = newSelector(Marker.class, b, a);
extensions = new ArrayList<>(selector.select(Marker.class, true, null));
assertThat(extensions).hasSize(2);
assertThat(extensions.get(0)).isEqualTo(a);
assertThat(extensions.get(1)).isEqualTo(b);
}
@Test
public void methodDependsUponArray() {
Object a = new GeneratesSomething("foo");
Object b = new MethodDependentOf(new String[] {"foo"});
ModuleSensorExtensionDictionary selector = newSelector(Marker.class, a, b);
List<Object> extensions = new ArrayList<>(selector.select(Marker.class, true, null));
assertThat(extensions).hasSize(2);
assertThat(extensions.get(0)).isEqualTo(a);
assertThat(extensions.get(1)).isEqualTo(b);
// different initial order
selector = newSelector(Marker.class, b, a);
extensions = new ArrayList<>(selector.select(Marker.class, true, null));
assertThat(extensions).hasSize(2);
assertThat(extensions.get(0)).isEqualTo(a);
assertThat(extensions.get(1)).isEqualTo(b);
}
@Test
public void useClassAnnotationsToSortExtensions() {
Object a = new ClassDependedUpon();
Object b = new ClassDependsUpon();
ModuleSensorExtensionDictionary selector = newSelector(Marker.class, a, b);
List<Object> extensions = new ArrayList<>(selector.select(Marker.class, true, null));
assertThat(extensions).hasSize(2);
assertThat(extensions.get(0)).isEqualTo(a);
assertThat(extensions.get(1)).isEqualTo(b);
// different initial order
selector = newSelector(Marker.class, b, a);
extensions = new ArrayList<>(selector.select(Marker.class, true, null));
assertThat(extensions).hasSize(2);
assertThat(extensions.get(0)).isEqualTo(a);
assertThat(extensions.get(1)).isEqualTo(b);
}
@Test
public void useClassAnnotationsOnInterfaces() {
Object a = new InterfaceDependedUpon() {
};
Object b = new InterfaceDependsUpon() {
};
ModuleSensorExtensionDictionary selector = newSelector(Marker.class, a, b);
List<Object> extensions = new ArrayList<>(selector.select(Marker.class, true, null));
assertThat(extensions).hasSize(2);
assertThat(extensions.get(0)).isEqualTo(a);
assertThat(extensions.get(1)).isEqualTo(b);
// different initial order
selector = newSelector(Marker.class, b, a);
extensions = new ArrayList<>(selector.select(Marker.class, true, null));
assertThat(extensions).hasSize(2);
assertThat(extensions.get(0)).isEqualTo(a);
assertThat(extensions.get(1)).isEqualTo(b);
}
@Test
public void inheritAnnotations() {
Object a = new SubClass("foo");
Object b = new MethodDependentOf("foo");
ModuleSensorExtensionDictionary selector = newSelector(Marker.class, b, a);
List<Object> extensions = new ArrayList<>(selector.select(Marker.class, true, null));
assertThat(extensions).hasSize(2);
assertThat(extensions.get(0)).isEqualTo(a);
assertThat(extensions.get(1)).isEqualTo(b);
// change initial order
selector = newSelector(Marker.class, a, b);
extensions = new ArrayList<>(selector.select(Marker.class, true, null));
assertThat(extensions).hasSize(2);
assertThat(extensions.get(0)).isEqualTo(a);
assertThat(extensions.get(1)).isEqualTo(b);
}
@Test(expected = IllegalStateException.class)
public void annotatedMethodsCanNotBePrivate() {
ModuleSensorExtensionDictionary selector = new ModuleSensorExtensionDictionary(mock(ExtensionContainer.class), mock(ModuleSensorContext.class),
sensorOptimizer, fileSystem, branchConfiguration);
Object wrong = new Object() {
@DependsUpon
private Object foo() {
return "foo";
}
};
selector.evaluateAnnotatedClasses(wrong, DependsUpon.class);
}
@Test
public void dependsUponPhaseForSensors() {
PreSensor pre = new PreSensor();
NormalSensor normal = new NormalSensor();
PostSensor post = new PostSensor();
ModuleSensorExtensionDictionary selector = newSelector(Sensor.class, normal, post, pre);
assertThat(selector.selectSensors(false)).extracting("wrappedSensor").containsExactly(pre, normal, post);
}
@Test
public void dependsUponInheritedPhase() {
PreSensorSubclass pre = new PreSensorSubclass();
NormalSensor normal = new NormalSensor();
PostSensorSubclass post = new PostSensorSubclass();
ModuleSensorExtensionDictionary selector = newSelector(Sensor.class, normal, post, pre);
List extensions = new ArrayList<>(selector.select(Sensor.class, true, null));
assertThat(extensions).containsExactly(pre, normal, post);
}
@Test
public void selectSensors() {
FakeSensor nonGlobalSensor = new FakeSensor();
FakeGlobalSensor globalSensor = new FakeGlobalSensor();
ModuleSensorExtensionDictionary selector = newSelector(Sensor.class, nonGlobalSensor, globalSensor);
// verify non-global sensor
Collection<ModuleSensorWrapper> extensions = selector.selectSensors(false);
assertThat(extensions).hasSize(1);
assertThat(extensions).extracting("wrappedSensor").containsExactly(nonGlobalSensor);
// verify global sensor
extensions = selector.selectSensors(true);
assertThat(extensions).extracting("wrappedSensor").containsExactly(globalSensor);
}
interface Marker {
}
static class FakeSensor implements Sensor {
@Override
public void describe(SensorDescriptor descriptor) {
}
@Override
public void execute(SensorContext context) {
}
}
static class FakeGlobalSensor implements Sensor {
@Override
public void describe(SensorDescriptor descriptor) {
descriptor.global();
}
@Override
public void execute(SensorContext context) {
}
}
@ScannerSide static
class MethodDependentOf implements Marker {
private Object dep;
MethodDependentOf(Object o) {
this.dep = o;
}
@DependsUpon
public Object dependsUponObject() {
return dep;
}
}
@ScannerSide
@DependsUpon("flag") static
class ClassDependsUpon implements Marker {
}
@ScannerSide
@DependedUpon("flag") static
class ClassDependedUpon implements Marker {
}
@ScannerSide
@DependsUpon("flag")
interface InterfaceDependsUpon extends Marker {
}
@ScannerSide
@DependedUpon("flag")
interface InterfaceDependedUpon extends Marker {
}
@ScannerSide static
class GeneratesSomething implements Marker {
private Object gen;
GeneratesSomething(Object o) {
this.gen = o;
}
@DependedUpon
public Object generates() {
return gen;
}
}
class SubClass extends GeneratesSomething implements Marker {
SubClass(Object o) {
super(o);
}
}
static class NormalSensor implements Sensor {
@Override
public void describe(SensorDescriptor descriptor) {
}
@Override
public void execute(SensorContext context) {
}
}
@Phase(name = Phase.Name.PRE) static
class PreSensor implements Sensor {
@Override
public void describe(SensorDescriptor descriptor) {
}
@Override
public void execute(SensorContext context) {
}
}
class PreSensorSubclass extends PreSensor {
}
@Phase(name = Phase.Name.POST) static
class PostSensor implements Sensor {
@Override
public void describe(SensorDescriptor descriptor) {
}
@Override
public void execute(SensorContext context) {
}
}
class PostSensorSubclass extends PostSensor {
}
}
| 13,917 | 30.995402 | 160 | java |
sonarqube | sonarqube-master/sonar-scanner-engine/src/test/java/org/sonar/scanner/bootstrap/PluginFilesTest.java | /*
* SonarQube
* Copyright (C) 2009-2023 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.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.util.Collections;
import java.util.Optional;
import javax.annotation.Nullable;
import okhttp3.HttpUrl;
import okhttp3.mockwebserver.MockResponse;
import okhttp3.mockwebserver.MockWebServer;
import okio.Buffer;
import org.apache.commons.codec.digest.DigestUtils;
import org.apache.commons.io.FileUtils;
import org.apache.commons.lang.RandomStringUtils;
import org.junit.Before;
import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.TemporaryFolder;
import org.sonar.api.config.internal.MapSettings;
import org.sonar.api.notifications.AnalysisWarnings;
import org.sonar.scanner.bootstrap.ScannerPluginInstaller.InstalledPlugin;
import org.sonarqube.ws.client.HttpConnector;
import org.sonarqube.ws.client.WsClientFactories;
import static org.apache.commons.io.FileUtils.moveFile;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatThrownBy;
import static org.assertj.core.api.ThrowableAssert.ThrowingCallable;
import static org.mockito.Mockito.mock;
public class PluginFilesTest {
@Rule
public TemporaryFolder temp = new TemporaryFolder();
@Rule
public MockWebServer server = new MockWebServer();
private final AnalysisWarnings analysisWarnings = mock(AnalysisWarnings.class);
private File userHome;
private PluginFiles underTest;
@Before
public void setUp() throws Exception {
HttpConnector connector = HttpConnector.newBuilder().url(server.url("/").toString()).build();
GlobalAnalysisMode analysisMode = new GlobalAnalysisMode(new ScannerProperties(Collections.emptyMap()));
DefaultScannerWsClient wsClient = new DefaultScannerWsClient(WsClientFactories.getDefault().newClient(connector), false,
analysisMode, analysisWarnings);
userHome = temp.newFolder();
MapSettings settings = new MapSettings();
settings.setProperty("sonar.userHome", userHome.getAbsolutePath());
underTest = new PluginFiles(wsClient, settings.asConfig());
}
@Test
public void get_jar_from_cache_if_present() throws Exception {
FileAndMd5 jar = createFileInCache("foo");
File result = underTest.get(newInstalledPlugin("foo", jar.md5)).get();
verifySameContent(result, jar);
// no requests to server
assertThat(server.getRequestCount()).isZero();
}
@Test
public void download_and_add_jar_to_cache_if_missing() throws Exception {
FileAndMd5 tempJar = new FileAndMd5();
enqueueDownload(tempJar);
InstalledPlugin plugin = newInstalledPlugin("foo", tempJar.md5);
File result = underTest.get(plugin).get();
verifySameContent(result, tempJar);
HttpUrl requestedUrl = server.takeRequest().getRequestUrl();
assertThat(requestedUrl.encodedPath()).isEqualTo("/api/plugins/download");
assertThat(requestedUrl.encodedQuery()).isEqualTo("plugin=foo");
// get from cache on second call
result = underTest.get(plugin).get();
verifySameContent(result, tempJar);
assertThat(server.getRequestCount()).isOne();
}
@Test
public void return_empty_if_plugin_not_found_on_server() {
server.enqueue(new MockResponse().setResponseCode(404));
InstalledPlugin plugin = newInstalledPlugin("foo", "abc");
Optional<File> result = underTest.get(plugin);
assertThat(result).isEmpty();
}
@Test
public void fail_if_integrity_of_download_is_not_valid() throws IOException {
FileAndMd5 tempJar = new FileAndMd5();
enqueueDownload(tempJar.file, "invalid_hash");
InstalledPlugin plugin = newInstalledPlugin("foo", "abc");
expectISE("foo", "was expected to have checksum invalid_hash but had " + tempJar.md5,
() -> underTest.get(plugin));
}
@Test
public void fail_if_md5_header_is_missing_from_response() throws IOException {
File tempJar = temp.newFile();
enqueueDownload(tempJar, null);
InstalledPlugin plugin = newInstalledPlugin("foo", "abc");
expectISE("foo", "did not return header Sonar-MD5", () -> underTest.get(plugin));
}
@Test
public void fail_if_server_returns_error() {
server.enqueue(new MockResponse().setResponseCode(500));
InstalledPlugin plugin = newInstalledPlugin("foo", "abc");
expectISE("foo", "returned code 500", () -> underTest.get(plugin));
}
@Test
public void download_a_new_version_of_plugin_during_blue_green_switch() throws IOException {
FileAndMd5 tempJar = new FileAndMd5();
enqueueDownload(tempJar);
// expecting to download plugin foo with checksum "abc"
InstalledPlugin pluginV1 = newInstalledPlugin("foo", "abc");
File result = underTest.get(pluginV1).get();
verifySameContent(result, tempJar);
// new version of downloaded jar is put in cache with the new md5
InstalledPlugin pluginV2 = newInstalledPlugin("foo", tempJar.md5);
result = underTest.get(pluginV2).get();
verifySameContent(result, tempJar);
assertThat(server.getRequestCount()).isOne();
// v1 still requests server and downloads v2
enqueueDownload(tempJar);
result = underTest.get(pluginV1).get();
verifySameContent(result, tempJar);
assertThat(server.getRequestCount()).isEqualTo(2);
}
@Test
public void fail_if_cached_file_is_outside_cache_dir() throws IOException {
FileAndMd5 tempJar = new FileAndMd5();
enqueueDownload(tempJar);
InstalledPlugin plugin = newInstalledPlugin("foo/bar", "abc");
assertThatThrownBy(() -> underTest.get(plugin))
.isInstanceOf(IllegalStateException.class)
.hasMessage("Fail to download plugin [foo/bar]. Key is not valid.");
}
private FileAndMd5 createFileInCache(String pluginKey) throws IOException {
FileAndMd5 tempFile = new FileAndMd5();
return moveToCache(pluginKey, tempFile);
}
private FileAndMd5 moveToCache(String pluginKey, FileAndMd5 jar) throws IOException {
File jarInCache = new File(userHome, "cache/" + jar.md5 + "/sonar-" + pluginKey + "-plugin.jar");
moveFile(jar.file, jarInCache);
return new FileAndMd5(jarInCache, jar.md5);
}
/**
* Enqueue download of file with valid MD5
*/
private void enqueueDownload(FileAndMd5 file) throws IOException {
enqueueDownload(file.file, file.md5);
}
/**
* Enqueue download of file with a MD5 that may not be returned (null) or not valid
*/
private void enqueueDownload(File file, @Nullable String md5) throws IOException {
Buffer body = new Buffer();
body.write(FileUtils.readFileToByteArray(file));
MockResponse response = new MockResponse().setBody(body);
if (md5 != null) {
response.setHeader("Sonar-MD5", md5);
}
server.enqueue(response);
}
private static InstalledPlugin newInstalledPlugin(String pluginKey, String fileChecksum) {
InstalledPlugin plugin = new InstalledPlugin();
plugin.key = pluginKey;
plugin.hash = fileChecksum;
return plugin;
}
private static void verifySameContent(File file1, FileAndMd5 file2) {
assertThat(file1).isFile().exists();
assertThat(file2.file).isFile().exists();
assertThat(file1).hasSameContentAs(file2.file);
}
private void expectISE(String pluginKey, String message, ThrowingCallable shouldRaiseThrowable) {
assertThatThrownBy(shouldRaiseThrowable)
.isInstanceOf(IllegalStateException.class)
.hasMessageStartingWith("Fail to download plugin [" + pluginKey + "]")
.hasMessageContaining(message);
}
private class FileAndMd5 {
private final File file;
private final String md5;
FileAndMd5(File file, String md5) {
this.file = file;
this.md5 = md5;
}
FileAndMd5() throws IOException {
this.file = temp.newFile();
FileUtils.write(this.file, RandomStringUtils.random(3));
try (InputStream fis = FileUtils.openInputStream(this.file)) {
this.md5 = DigestUtils.md5Hex(fis);
} catch (IOException e) {
throw new IllegalStateException("Fail to compute md5 of " + this.file, e);
}
}
}
}
| 8,884 | 34.257937 | 124 | java |
sonarqube | sonarqube-master/sonar-scanner-engine/src/test/java/org/sonar/scanner/bootstrap/PostJobExtensionDictionaryTest.java | /*
* SonarQube
* Copyright (C) 2009-2023 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.List;
import org.junit.Before;
import org.junit.Test;
import org.sonar.api.batch.Phase;
import org.sonar.api.batch.postjob.PostJob;
import org.sonar.api.batch.postjob.PostJobContext;
import org.sonar.api.batch.postjob.PostJobDescriptor;
import org.sonar.api.batch.postjob.internal.DefaultPostJobDescriptor;
import org.sonar.core.platform.ExtensionContainer;
import org.sonar.scanner.postjob.PostJobOptimizer;
import static org.assertj.core.api.Assertions.assertThat;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;
public class PostJobExtensionDictionaryTest {
private final PostJobOptimizer postJobOptimizer = mock(PostJobOptimizer.class);
@Before
public void setUp() {
when(postJobOptimizer.shouldExecute(any(DefaultPostJobDescriptor.class))).thenReturn(true);
}
@Test
public void dependsUponPhaseForPostJob() {
PrePostJob pre = new PrePostJob();
NormalPostJob normal = new NormalPostJob();
ExtensionContainer iocContainer = mock(ExtensionContainer.class);
when(iocContainer.getComponentsByType(PostJob.class)).thenReturn(List.of(pre, normal));
PostJobExtensionDictionary selector = new PostJobExtensionDictionary(iocContainer, postJobOptimizer, mock(PostJobContext.class));
assertThat(selector.selectPostJobs()).extracting("wrappedPostJob").containsExactly(pre, normal);
}
static class NormalPostJob implements PostJob {
@Override
public void describe(PostJobDescriptor descriptor) {
}
@Override
public void execute(PostJobContext context) {
}
}
@Phase(name = Phase.Name.PRE) static
class PrePostJob implements PostJob {
@Override
public void describe(PostJobDescriptor descriptor) {
}
@Override
public void execute(PostJobContext context) {
}
}
}
| 2,743 | 32.060241 | 133 | java |
sonarqube | sonarqube-master/sonar-scanner-engine/src/test/java/org/sonar/scanner/bootstrap/ScannerPluginInstallerTest.java | /*
* SonarQube
* Copyright (C) 2009-2023 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.io.File;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.StringReader;
import java.util.Map;
import java.util.Optional;
import java.util.jar.Attributes;
import java.util.jar.JarOutputStream;
import java.util.jar.Manifest;
import org.apache.commons.io.FileUtils;
import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.TemporaryFolder;
import org.sonar.scanner.WsTestUtil;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatThrownBy;
import static org.mockito.ArgumentMatchers.argThat;
import static org.mockito.Mockito.doReturn;
import static org.mockito.Mockito.mock;
public class ScannerPluginInstallerTest {
@Rule
public TemporaryFolder temp = new TemporaryFolder();
private PluginFiles pluginFiles = mock(PluginFiles.class);
private DefaultScannerWsClient wsClient = mock(DefaultScannerWsClient.class);
private ScannerPluginInstaller underTest = new ScannerPluginInstaller(pluginFiles, wsClient);
@Test
public void download_installed_plugins() throws IOException {
WsTestUtil.mockReader(wsClient, "api/plugins/installed", new InputStreamReader(getClass().getResourceAsStream("ScannerPluginInstallerTest/installed-plugins-ws.json")));
enqueueDownload("scmgit", "abc");
enqueueDownload("java", "def");
Map<String, ScannerPlugin> result = underTest.installRemotes();
assertThat(result.keySet()).containsExactlyInAnyOrder("scmgit", "java");
ScannerPlugin gitPlugin = result.get("scmgit");
assertThat(gitPlugin.getKey()).isEqualTo("scmgit");
assertThat(gitPlugin.getInfo().getNonNullJarFile()).exists().isFile();
assertThat(gitPlugin.getUpdatedAt()).isEqualTo(100L);
ScannerPlugin javaPlugin = result.get("java");
assertThat(javaPlugin.getKey()).isEqualTo("java");
assertThat(javaPlugin.getInfo().getNonNullJarFile()).exists().isFile();
assertThat(javaPlugin.getUpdatedAt()).isEqualTo(200L);
}
@Test
public void fail_if_json_of_installed_plugins_is_not_valid() {
WsTestUtil.mockReader(wsClient, "api/plugins/installed", new StringReader("not json"));
assertThatThrownBy(() -> underTest.installRemotes())
.isInstanceOf(IllegalStateException.class)
.hasMessage("Fail to parse response of api/plugins/installed");
}
@Test
public void reload_list_if_plugin_uninstalled_during_blue_green_switch() throws IOException {
WsTestUtil.mockReader(wsClient, "api/plugins/installed",
new InputStreamReader(getClass().getResourceAsStream("ScannerPluginInstallerTest/blue-installed.json")),
new InputStreamReader(getClass().getResourceAsStream("ScannerPluginInstallerTest/green-installed.json")));
enqueueNotFoundDownload("scmgit", "abc");
enqueueDownload("java", "def");
enqueueDownload("cobol", "ghi");
Map<String, ScannerPlugin> result = underTest.installRemotes();
assertThat(result.keySet()).containsExactlyInAnyOrder("java", "cobol");
}
@Test
public void fail_if_plugin_not_found_two_times() throws IOException {
WsTestUtil.mockReader(wsClient, "api/plugins/installed",
new InputStreamReader(getClass().getResourceAsStream("ScannerPluginInstallerTest/blue-installed.json")),
new InputStreamReader(getClass().getResourceAsStream("ScannerPluginInstallerTest/green-installed.json")));
enqueueDownload("scmgit", "abc");
enqueueDownload("cobol", "ghi");
enqueueNotFoundDownload("java", "def");
assertThatThrownBy(() -> underTest.installRemotes())
.isInstanceOf(IllegalStateException.class)
.hasMessage("Fail to download plugin [java]. Not found.");
}
@Test
public void installLocals_always_returns_empty() {
// this method is used only by medium tests
assertThat(underTest.installLocals()).isEmpty();
}
private void enqueueDownload(String pluginKey, String pluginHash) throws IOException {
File jar = temp.newFile();
Manifest manifest = new Manifest();
manifest.getMainAttributes().put(Attributes.Name.MANIFEST_VERSION, "1.0");
manifest.getMainAttributes().putValue("Plugin-Key", pluginKey);
try (JarOutputStream output = new JarOutputStream(FileUtils.openOutputStream(jar), manifest)) {
}
doReturn(Optional.of(jar)).when(pluginFiles).get(argThat(p -> pluginKey.equals(p.key) && pluginHash.equals(p.hash)));
}
private void enqueueNotFoundDownload(String pluginKey, String pluginHash) {
doReturn(Optional.empty()).when(pluginFiles).get(argThat(p -> pluginKey.equals(p.key) && pluginHash.equals(p.hash)));
}
}
| 5,449 | 40.923077 | 172 | java |
sonarqube | sonarqube-master/sonar-scanner-engine/src/test/java/org/sonar/scanner/bootstrap/ScannerPluginJarExploderTest.java | /*
* SonarQube
* Copyright (C) 2009-2023 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.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.nio.channels.FileLock;
import org.apache.commons.io.FileUtils;
import org.junit.Before;
import org.junit.ClassRule;
import org.junit.Test;
import org.junit.rules.TemporaryFolder;
import org.sonar.core.platform.ExplodedPlugin;
import org.sonar.core.platform.PluginInfo;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatExceptionOfType;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;
public class ScannerPluginJarExploderTest {
@ClassRule
public static TemporaryFolder temp = new TemporaryFolder();
private File tempDir;
private ScannerPluginJarExploder underTest;
@Before
public void setUp() throws IOException {
tempDir = temp.newFolder();
PluginFiles pluginFiles = mock(PluginFiles.class);
when(pluginFiles.createTempDir()).thenReturn(tempDir);
underTest = new ScannerPluginJarExploder(pluginFiles);
}
@Test
public void copy_and_extract_libs() throws IOException {
File jar = loadFile("sonar-checkstyle-plugin-2.8.jar");
ExplodedPlugin exploded = underTest.explode(PluginInfo.create(jar));
assertThat(exploded.getKey()).isEqualTo("checkstyle");
assertThat(exploded.getMain()).isFile().exists();
assertThat(exploded.getLibs()).extracting(File::getName).containsExactlyInAnyOrder("antlr-2.7.6.jar", "checkstyle-5.1.jar", "commons-cli-1.0.jar");
assertThat(new File(jar.getParent(), "sonar-checkstyle-plugin-2.8.jar")).exists();
assertThat(new File(jar.getParent(), "sonar-checkstyle-plugin-2.8.jar_unzip/META-INF/lib/checkstyle-5.1.jar")).exists();
}
@Test
public void extract_only_libs() throws IOException {
File jar = loadFile("sonar-checkstyle-plugin-2.8.jar");
underTest.explode(PluginInfo.create(jar));
assertThat(new File(jar.getParent(), "sonar-checkstyle-plugin-2.8.jar")).exists();
assertThat(new File(jar.getParent(), "sonar-checkstyle-plugin-2.8.jar_unzip/META-INF/MANIFEST.MF")).doesNotExist();
assertThat(new File(jar.getParent(), "sonar-checkstyle-plugin-2.8.jar_unzip/org/sonar/plugins/checkstyle/CheckstyleVersion.class")).doesNotExist();
}
@Test
public void retry_on_locked_file() throws IOException {
File jar = loadFile("sonar-checkstyle-plugin-2.8.jar");
File lockFile = new File(jar.getParentFile(), jar.getName() + "_unzip.lock");
try (FileOutputStream out = new FileOutputStream(lockFile)) {
FileLock lock = out.getChannel().lock();
try {
PluginInfo pluginInfo = PluginInfo.create(jar);
assertThatExceptionOfType(IllegalStateException.class)
.isThrownBy(() -> underTest.explode(pluginInfo))
.withMessage("Fail to open plugin [checkstyle]: " + jar)
.withCauseExactlyInstanceOf(IOException.class);
} finally {
lock.release();
}
}
}
private File loadFile(String filename) throws IOException {
File src = FileUtils.toFile(getClass().getResource(getClass().getSimpleName() + "/" + filename));
File dest = new File(temp.newFolder(), filename);
FileUtils.copyFile(src, dest);
return dest;
}
}
| 4,105 | 38.480769 | 151 | java |
sonarqube | sonarqube-master/sonar-scanner-engine/src/test/java/org/sonar/scanner/bootstrap/ScannerPluginRepositoryTest.java | /*
* SonarQube
* Copyright (C) 2009-2023 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.io.File;
import java.util.Collections;
import org.junit.Test;
import org.sonar.api.Plugin;
import org.sonar.core.platform.ExplodedPlugin;
import org.sonar.core.platform.PluginClassLoader;
import org.sonar.core.platform.PluginInfo;
import org.sonar.core.platform.PluginJarExploder;
import org.sonar.core.plugin.PluginType;
import static org.assertj.core.api.Assertions.assertThat;
import static org.junit.Assert.fail;
import static org.mockito.ArgumentMatchers.anyCollection;
import static org.mockito.ArgumentMatchers.anyMap;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
public class ScannerPluginRepositoryTest {
PluginInstaller installer = mock(PluginInstaller.class);
PluginClassLoader loader = mock(PluginClassLoader.class);
PluginJarExploder exploder = new FakePluginJarExploder();
ScannerPluginRepository underTest = new ScannerPluginRepository(installer, exploder, loader);
@Test
public void install_and_load_plugins() {
PluginInfo info = new PluginInfo("java");
ImmutableMap<String, ScannerPlugin> plugins = ImmutableMap.of("java", new ScannerPlugin("java", 1L, PluginType.EXTERNAL, info));
Plugin instance = mock(Plugin.class);
when(loader.load(anyMap())).thenReturn(ImmutableMap.of("java", instance));
when(installer.installRemotes()).thenReturn(plugins);
underTest.start();
assertThat(underTest.getPluginInfos()).containsOnly(info);
assertThat(underTest.getPluginsByKey()).isEqualTo(plugins);
assertThat(underTest.getPluginInfo("java")).isSameAs(info);
assertThat(underTest.getPluginInstance("java")).isSameAs(instance);
assertThat(underTest.getPluginInstances()).containsOnly(instance);
assertThat(underTest.getBundledPluginsInfos()).isEmpty();
assertThat(underTest.getExternalPluginsInfos()).isEqualTo(underTest.getPluginInfos());
underTest.stop();
verify(loader).unload(anyCollection());
}
@Test
public void fail_if_requesting_missing_plugin() {
underTest.start();
try {
underTest.getPluginInfo("unknown");
fail();
} catch (IllegalStateException e) {
assertThat(e).hasMessage("Plugin [unknown] does not exist");
}
try {
underTest.getPluginInstance("unknown");
fail();
} catch (IllegalStateException e) {
assertThat(e).hasMessage("Plugin [unknown] does not exist");
}
}
private static class FakePluginJarExploder extends PluginJarExploder {
@Override
public ExplodedPlugin explode(PluginInfo plugin) {
return new ExplodedPlugin(plugin, plugin.getKey(), new File(plugin.getKey() + ".jar"), Collections
.singleton(new File(plugin.getKey() + "-lib.jar")));
}
}
}
| 3,675 | 36.896907 | 132 | java |
sonarqube | sonarqube-master/sonar-scanner-engine/src/test/java/org/sonar/scanner/bootstrap/ScannerPropertiesTest.java | /*
* SonarQube
* Copyright (C) 2009-2023 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.Test;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatThrownBy;
public class ScannerPropertiesTest {
@Test
public void initialization() {
ImmutableMap<String, String> map = ImmutableMap.<String, String>builder()
.put("prop-1", "{b64}Zm9v")
.put("sonar.projectKey", "my-project")
.build();
ScannerProperties underTest = new ScannerProperties(map);
assertThat(underTest.getEncryption()).isNotNull();
assertThat(underTest.properties())
.containsEntry("prop-1", "foo")
.containsEntry("sonar.projectKey", "my-project");
assertThat(underTest.getProjectKey()).isEqualTo("my-project");
}
@Test
public void encryption_fail() {
ImmutableMap<String, String> map = ImmutableMap.<String, String>builder()
.put("prop-1", "{aes}Zm9vzxc")
.build();
assertThatThrownBy(() -> new ScannerProperties(map))
.isInstanceOf(IllegalStateException.class)
.hasMessageContaining("Fail to decrypt the property");
}
@Test
public void encryption_ok() {
ImmutableMap<String, String> map = ImmutableMap.<String, String>builder()
.put("prop-1", "{b64}Zm9v")
.build();
ScannerProperties underTest = new ScannerProperties(map);
assertThat(underTest.property("prop-1")).isEqualTo("foo");
}
}
| 2,298 | 33.833333 | 77 | java |
sonarqube | sonarqube-master/sonar-scanner-engine/src/test/java/org/sonar/scanner/bootstrap/ScannerWsClientProviderTest.java | /*
* SonarQube
* Copyright (C) 2009-2023 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.Collections;
import java.util.HashMap;
import java.util.Map;
import org.junit.Test;
import org.sonar.api.utils.System2;
import org.sonar.batch.bootstrapper.EnvironmentInformation;
import org.sonarqube.ws.client.HttpConnector;
import static org.assertj.core.api.Assertions.assertThat;
import static org.mockito.Mockito.mock;
public class ScannerWsClientProviderTest {
private ScannerWsClientProvider underTest = new ScannerWsClientProvider();
private EnvironmentInformation env = new EnvironmentInformation("Maven Plugin", "2.3");
@Test
public void provide_client_with_default_settings() {
ScannerProperties settings = new ScannerProperties(new HashMap<>());
DefaultScannerWsClient client = underTest.provide(settings, env, new GlobalAnalysisMode(new ScannerProperties(Collections.emptyMap())),
mock(System2.class),warning -> {
});
assertThat(client).isNotNull();
assertThat(client.baseUrl()).isEqualTo("http://localhost:9000/");
HttpConnector httpConnector = (HttpConnector) client.wsConnector();
assertThat(httpConnector.baseUrl()).isEqualTo("http://localhost:9000/");
assertThat(httpConnector.okHttpClient().proxy()).isNull();
assertThat(httpConnector.okHttpClient().connectTimeoutMillis()).isEqualTo(5_000);
assertThat(httpConnector.okHttpClient().readTimeoutMillis()).isEqualTo(60_000);
}
@Test
public void provide_client_with_custom_settings() {
Map<String, String> props = new HashMap<>();
props.put("sonar.host.url", "https://here/sonarqube");
props.put("sonar.token", "testToken");
props.put("sonar.ws.timeout", "42");
ScannerProperties settings = new ScannerProperties(props);
DefaultScannerWsClient client = underTest.provide(settings, env, new GlobalAnalysisMode(new ScannerProperties(Collections.emptyMap())),
mock(System2.class),warning -> {
});
assertThat(client).isNotNull();
HttpConnector httpConnector = (HttpConnector) client.wsConnector();
assertThat(httpConnector.baseUrl()).isEqualTo("https://here/sonarqube/");
assertThat(httpConnector.okHttpClient().proxy()).isNull();
}
}
| 3,019 | 40.369863 | 139 | java |
sonarqube | sonarqube-master/sonar-scanner-engine/src/test/java/org/sonar/scanner/bootstrap/SpringGlobalContainerTest.java | /*
* SonarQube
* Copyright (C) 2009-2023 SonarSource SA
* mailto:info AT sonarsource DOT com
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 3 of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this program; if not, write to the Free Software Foundation,
* Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*/
package org.sonar.scanner.bootstrap;
import org.junit.Test;
import static org.assertj.core.api.Assertions.assertThat;
public class SpringGlobalContainerTest {
@Test
public void shouldFormatTime() {
assertThat(SpringGlobalContainer.formatTime(1 * 60 * 60 * 1000 + 2 * 60 * 1000 + 3 * 1000 + 400)).isEqualTo("1:02:03.400 s");
assertThat(SpringGlobalContainer.formatTime(2 * 60 * 1000 + 3 * 1000 + 400)).isEqualTo("2:03.400 s");
assertThat(SpringGlobalContainer.formatTime(3 * 1000 + 400)).isEqualTo("3.400 s");
assertThat(SpringGlobalContainer.formatTime(400)).isEqualTo("0.400 s");
}
}
| 1,453 | 40.542857 | 129 | java |
sonarqube | sonarqube-master/sonar-scanner-engine/src/test/java/org/sonar/scanner/cache/AnalysisCacheEnabledTest.java | /*
* SonarQube
* Copyright (C) 2009-2023 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.cache;
import java.util.Optional;
import org.junit.Test;
import org.sonar.api.config.Configuration;
import static org.assertj.core.api.Assertions.assertThat;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;
import static org.sonar.scanner.cache.AnalysisCacheEnabled.PROP_KEY;
public class AnalysisCacheEnabledTest {
private final Configuration configuration = mock(Configuration.class);
private final AnalysisCacheEnabled analysisCacheEnabled = new AnalysisCacheEnabled(configuration);
@Test
public void enabled_by_default_if_not_pr() {
assertThat(analysisCacheEnabled.isEnabled()).isTrue();
}
@Test
public void disabled_if_property_set() {
when(configuration.getBoolean(PROP_KEY)).thenReturn(Optional.of(false));
assertThat(analysisCacheEnabled.isEnabled()).isFalse();
}
}
| 1,707 | 36.130435 | 100 | java |
sonarqube | sonarqube-master/sonar-scanner-engine/src/test/java/org/sonar/scanner/cache/AnalysisCacheMemoryStorageTest.java | /*
* SonarQube
* Copyright (C) 2009-2023 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.cache;
import com.google.protobuf.ByteString;
import java.io.IOException;
import java.util.List;
import java.util.Optional;
import org.apache.commons.io.IOUtils;
import org.junit.Test;
import org.sonar.scanner.protocol.internal.ScannerInternal.SensorCacheEntry;
import org.sonar.scanner.protocol.internal.SensorCacheData;
import static java.nio.charset.StandardCharsets.UTF_8;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatThrownBy;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
public class AnalysisCacheMemoryStorageTest {
private final AnalysisCacheLoader loader = mock(AnalysisCacheLoader.class);
private final AnalysisCacheMemoryStorage storage = new AnalysisCacheMemoryStorage(loader);
@Test
public void storage_loads_with_loader() throws IOException {
SensorCacheData data = new SensorCacheData(List.of(SensorCacheEntry.newBuilder()
.setKey("key1")
.setData(ByteString.copyFrom("value1", UTF_8))
.build()));
when(loader.load()).thenReturn(Optional.of(data));
storage.load();
verify(loader).load();
assertThat(IOUtils.toString(storage.get("key1"), UTF_8)).isEqualTo("value1");
assertThat(storage.contains("key1")).isTrue();
}
@Test
public void get_throws_IAE_if_doesnt_contain_key() {
when(loader.load()).thenReturn(Optional.empty());
storage.load();
assertThat(storage.contains("key1")).isFalse();
assertThatThrownBy(() -> storage.get("key1")).isInstanceOf(IllegalArgumentException.class);
}
@Test
public void get_throws_IAE_if_no_cache() {
when(loader.load()).thenReturn(Optional.empty());
storage.load();
assertThat(storage.contains("key1")).isFalse();
assertThatThrownBy(() -> storage.get("key1")).isInstanceOf(IllegalArgumentException.class);
}
}
| 2,774 | 37.541667 | 95 | java |
sonarqube | sonarqube-master/sonar-scanner-engine/src/test/java/org/sonar/scanner/cache/AnalysisCacheProviderTest.java | /*
* SonarQube
* Copyright (C) 2009-2023 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.cache;
import java.io.IOException;
import org.junit.Before;
import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.TemporaryFolder;
import org.sonar.api.batch.sensor.cache.ReadCache;
import org.sonar.scanner.cache.AnalysisCacheProvider.NoOpReadCache;
import org.sonar.scanner.cache.AnalysisCacheProvider.NoOpWriteCache;
import org.sonar.scanner.protocol.output.FileStructure;
import org.sonar.scanner.scan.branch.BranchConfiguration;
import static org.assertj.core.api.Assertions.assertThat;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
public class AnalysisCacheProviderTest {
private final AnalysisCacheEnabled analysisCacheEnabled = mock(AnalysisCacheEnabled.class);
private final AnalysisCacheMemoryStorage storage = mock(AnalysisCacheMemoryStorage.class);
private final ReadCache readCache = mock(ReadCache.class);
private final BranchConfiguration branchConfiguration = mock(BranchConfiguration.class);
private final AnalysisCacheProvider cacheProvider = new AnalysisCacheProvider();
@Rule
public TemporaryFolder temp = new TemporaryFolder();
private FileStructure fileStructure;
@Before
public void setup() throws IOException {
fileStructure = new FileStructure(temp.newFolder());
when(branchConfiguration.isPullRequest()).thenReturn(false);
}
@Test
public void provide_noop_writer_cache_if_pr() {
when(branchConfiguration.isPullRequest()).thenReturn(true);
when(analysisCacheEnabled.isEnabled()).thenReturn(true);
var cache = cacheProvider.provideWriter(analysisCacheEnabled, readCache, branchConfiguration, fileStructure);
assertThat(cache).isInstanceOf(AnalysisCacheProvider.NoOpWriteCache.class);
}
@Test
public void provide_noop_reader_cache_when_disable() {
when(analysisCacheEnabled.isEnabled()).thenReturn(false);
var cache = cacheProvider.provideReader(analysisCacheEnabled, storage);
assertThat(cache).isInstanceOf(NoOpReadCache.class);
}
@Test
public void provide_noop_writer_cache_when_disable() {
when(analysisCacheEnabled.isEnabled()).thenReturn(false);
var cache = cacheProvider.provideWriter(analysisCacheEnabled, readCache, branchConfiguration, fileStructure);
assertThat(cache).isInstanceOf(NoOpWriteCache.class);
}
@Test
public void provide_real_reader_cache_when_enable() {
when(analysisCacheEnabled.isEnabled()).thenReturn(true);
var cache = cacheProvider.provideReader(analysisCacheEnabled, storage);
verify(storage).load();
assertThat(cache).isInstanceOf(ReadCacheImpl.class);
}
@Test
public void provide_real_writer_cache_when_enable() {
when(analysisCacheEnabled.isEnabled()).thenReturn(true);
var cache = cacheProvider.provideWriter(analysisCacheEnabled, readCache, branchConfiguration, fileStructure);
assertThat(cache).isInstanceOf(WriteCacheImpl.class);
}
}
| 3,793 | 39.795699 | 113 | java |
sonarqube | sonarqube-master/sonar-scanner-engine/src/test/java/org/sonar/scanner/cache/DefaultAnalysisCacheLoaderTest.java | /*
* SonarQube
* Copyright (C) 2009-2023 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.cache;
import com.google.protobuf.ByteString;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.nio.charset.StandardCharsets;
import java.util.Optional;
import java.util.zip.GZIPOutputStream;
import org.junit.Before;
import org.junit.Rule;
import org.junit.Test;
import org.mockito.ArgumentCaptor;
import org.sonar.api.scanner.fs.InputProject;
import org.sonar.api.utils.MessageException;
import org.sonar.api.testfixtures.log.LogTester;
import org.sonar.scanner.bootstrap.DefaultScannerWsClient;
import org.sonar.scanner.protocol.internal.ScannerInternal.SensorCacheEntry;
import org.sonar.scanner.protocol.internal.SensorCacheData;
import org.sonar.scanner.scan.branch.BranchConfiguration;
import org.sonarqube.ws.client.HttpException;
import org.sonarqube.ws.client.WsRequest;
import org.sonarqube.ws.client.WsResponse;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatThrownBy;
import static org.assertj.core.api.Assertions.entry;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
import static org.sonar.scanner.cache.DefaultAnalysisCacheLoader.CONTENT_ENCODING;
public class DefaultAnalysisCacheLoaderTest {
private final static SensorCacheEntry MSG = SensorCacheEntry.newBuilder()
.setKey("key")
.setData(ByteString.copyFrom("value", StandardCharsets.UTF_8))
.build();
private final WsResponse response = mock(WsResponse.class);
private final DefaultScannerWsClient wsClient = mock(DefaultScannerWsClient.class);
private final InputProject project = mock(InputProject.class);
private final BranchConfiguration branchConfiguration = mock(BranchConfiguration.class);
private final DefaultAnalysisCacheLoader loader = new DefaultAnalysisCacheLoader(wsClient, project, branchConfiguration);
@Rule
public LogTester logs = new LogTester();
@Before
public void before() {
when(project.key()).thenReturn("myproject");
when(wsClient.call(any())).thenReturn(response);
}
@Test
public void loads_content_and_logs_size() throws IOException {
setResponse(MSG);
when(response.header("Content-Length")).thenReturn(Optional.of("123"));
SensorCacheData msg = loader.load().get();
assertThat(msg.getEntries()).containsOnly(entry(MSG.getKey(), MSG.getData()));
assertRequestPath("api/analysis_cache/get?project=myproject");
assertThat(logs.logs()).anyMatch(s -> s.startsWith("Load analysis cache (123 bytes)"));
}
@Test
public void loads_content_for_branch() throws IOException {
when(branchConfiguration.referenceBranchName()).thenReturn("name");
setResponse(MSG);
SensorCacheData msg = loader.load().get();
assertThat(msg.getEntries()).containsOnly(entry(MSG.getKey(), MSG.getData()));
assertRequestPath("api/analysis_cache/get?project=myproject&branch=name");
assertThat(logs.logs()).anyMatch(s -> s.startsWith("Load analysis cache | time="));
}
@Test
public void loads_compressed_content() throws IOException {
setCompressedResponse(MSG);
SensorCacheData msg = loader.load().get();
assertThat(msg.getEntries()).containsOnly(entry(MSG.getKey(), MSG.getData()));
}
@Test
public void returns_empty_if_404() {
when(wsClient.call(any())).thenThrow(new HttpException("url", 404, "content"));
assertThat(loader.load()).isEmpty();
assertThat(logs.logs()).anyMatch(s -> s.startsWith("Load analysis cache (404) | time="));
}
@Test
public void throw_error_if_http_exception_not_404() {
when(wsClient.call(any())).thenThrow(new HttpException("url", 401, "content"));
assertThatThrownBy(loader::load)
.isInstanceOf(MessageException.class)
.hasMessage("Failed to download analysis cache: HTTP code 401: content");
}
@Test
public void throw_error_if_cant_decompress_content() {
setInvalidCompressedResponse();
assertThatThrownBy(loader::load)
.isInstanceOf(IllegalStateException.class)
.hasMessage("Failed to download analysis cache");
}
private void assertRequestPath(String expectedPath) {
ArgumentCaptor<WsRequest> requestCaptor = ArgumentCaptor.forClass(WsRequest.class);
verify(wsClient).call(requestCaptor.capture());
assertThat(requestCaptor.getValue().getPath()).isEqualTo(expectedPath);
}
private void setResponse(SensorCacheEntry msg) throws IOException {
when(response.contentStream()).thenReturn(createInputStream(msg));
}
private void setCompressedResponse(SensorCacheEntry msg) throws IOException {
when(response.contentStream()).thenReturn(createCompressedInputStream(msg));
when(response.header(CONTENT_ENCODING)).thenReturn(Optional.of("gzip"));
}
private void setInvalidCompressedResponse() {
when(response.contentStream()).thenReturn(new ByteArrayInputStream(new byte[] {1, 2, 3}));
when(response.header(CONTENT_ENCODING)).thenReturn(Optional.of("gzip"));
}
private InputStream createInputStream(SensorCacheEntry analysisCacheMsg) throws IOException {
ByteArrayOutputStream serialized = new ByteArrayOutputStream(analysisCacheMsg.getSerializedSize());
analysisCacheMsg.writeDelimitedTo(serialized);
return new ByteArrayInputStream(serialized.toByteArray());
}
private InputStream createCompressedInputStream(SensorCacheEntry analysisCacheMsg) throws IOException {
ByteArrayOutputStream serialized = new ByteArrayOutputStream(analysisCacheMsg.getSerializedSize());
GZIPOutputStream compressed = new GZIPOutputStream(serialized);
analysisCacheMsg.writeDelimitedTo(compressed);
compressed.close();
return new ByteArrayInputStream(serialized.toByteArray());
}
}
| 6,697 | 41.125786 | 123 | java |
sonarqube | sonarqube-master/sonar-scanner-engine/src/test/java/org/sonar/scanner/cache/ReadCacheImplTest.java | /*
* SonarQube
* Copyright (C) 2009-2023 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.cache;
import java.io.InputStream;
import org.junit.Test;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatThrownBy;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;
public class ReadCacheImplTest {
private final AnalysisCacheStorage storage = mock(AnalysisCacheStorage.class);
private final ReadCacheImpl readCache = new ReadCacheImpl(storage);
@Test
public void read_delegates_to_storage() {
InputStream is = mock(InputStream.class);
when(storage.get("key")).thenReturn(is);
when(storage.contains("key")).thenReturn(true);
assertThat(readCache.read("key")).isEqualTo(is);
}
@Test
public void read_fails_if_key_not_found() {
assertThatThrownBy(() -> readCache.read("unknown")).isInstanceOf(IllegalArgumentException.class);
}
@Test
public void contains_delegates_to_storage() {
when(storage.contains("key")).thenReturn(true);
assertThat(readCache.contains("key")).isTrue();
}
}
| 1,899 | 34.849057 | 101 | java |
sonarqube | sonarqube-master/sonar-scanner-engine/src/test/java/org/sonar/scanner/cache/WriteCacheImplTest.java | /*
* SonarQube
* Copyright (C) 2009-2023 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.cache;
import java.io.ByteArrayInputStream;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.util.Map;
import java.util.stream.Collectors;
import java.util.stream.StreamSupport;
import org.junit.Before;
import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.TemporaryFolder;
import org.sonar.core.util.Protobuf;
import org.sonar.scanner.protocol.internal.ScannerInternal.SensorCacheEntry;
import org.sonar.scanner.protocol.output.FileStructure;
import org.sonar.scanner.scan.branch.BranchConfiguration;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatThrownBy;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;
public class WriteCacheImplTest {
private final ReadCacheImpl readCache = mock(ReadCacheImpl.class);
private final BranchConfiguration branchConfiguration = mock(BranchConfiguration.class);
private FileStructure fileStructure;
private WriteCacheImpl writeCache;
@Rule
public TemporaryFolder temp = new TemporaryFolder();
@Before
public void setUp() throws IOException {
fileStructure = new FileStructure(temp.newFolder());
writeCache = new WriteCacheImpl(readCache, fileStructure);
}
@Test
public void write_bytes_adds_entries() {
byte[] b1 = new byte[] {1, 2, 3};
byte[] b2 = new byte[] {3, 4};
writeCache.write("key", b1);
writeCache.write("key2", b2);
assertThatCacheContains(Map.of("key", b1, "key2", b2));
}
@Test
public void dont_write_if_its_pull_request() {
byte[] b1 = new byte[] {1, 2, 3};
when(branchConfiguration.isPullRequest()).thenReturn(true);
writeCache.write("key1", b1);
writeCache.write("key2", new ByteArrayInputStream(b1));
assertThatCacheContains(Map.of());
}
@Test
public void write_inputStream_adds_entries() {
byte[] b1 = new byte[] {1, 2, 3};
byte[] b2 = new byte[] {3, 4};
writeCache.write("key", new ByteArrayInputStream(b1));
writeCache.write("key2", new ByteArrayInputStream(b2));
assertThatCacheContains(Map.of("key", b1, "key2", b2));
}
@Test
public void write_throws_IAE_if_writing_same_key_twice() {
byte[] b1 = new byte[] {1};
byte[] b2 = new byte[] {2};
writeCache.write("key", b1);
assertThatThrownBy(() -> writeCache.write("key", b2))
.isInstanceOf(IllegalArgumentException.class)
.hasMessage("Cache already contains key 'key'");
}
@Test
public void copyFromPrevious_throws_IAE_if_read_cache_doesnt_contain_key() {
assertThatThrownBy(() -> writeCache.copyFromPrevious("key"))
.isInstanceOf(IllegalArgumentException.class)
.hasMessage("Previous cache doesn't contain key 'key'");
}
@Test
public void copyFromPrevious_reads_from_readCache() throws IOException {
byte[] b = new byte[] {1};
InputStream value = new ByteArrayInputStream(b);
when(readCache.contains("key")).thenReturn(true);
when(readCache.read("key")).thenReturn(value);
writeCache.copyFromPrevious("key");
assertThatCacheContains(Map.of("key", b));
}
private void assertThatCacheContains(Map<String, byte[]> expectedData) {
writeCache.close();
File cacheFile = fileStructure.analysisCache();
Iterable<SensorCacheEntry> it = () -> Protobuf.readGzipStream(cacheFile, SensorCacheEntry.parser());
Map<String, byte[]> data = StreamSupport.stream(it.spliterator(), false)
.collect(Collectors.toMap(SensorCacheEntry::getKey, e -> e.getData().toByteArray()));
assertThat(data).containsAllEntriesOf(expectedData);
}
}
| 4,481 | 34.571429 | 104 | java |
sonarqube | sonarqube-master/sonar-scanner-engine/src/test/java/org/sonar/scanner/ci/CiConfigurationImplTest.java | /*
* SonarQube
* Copyright (C) 2009-2023 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.ci;
import org.junit.Test;
import static org.assertj.core.api.Assertions.assertThat;
public class CiConfigurationImplTest {
@Test
public void getScmRevision() {
assertThat(new CiConfigurationImpl(null, "test").getScmRevision()).isEmpty();
assertThat(new CiConfigurationImpl("", "test").getScmRevision()).isEmpty();
assertThat(new CiConfigurationImpl(" ", "test").getScmRevision()).isEmpty();
assertThat(new CiConfigurationImpl("a7bdf2d", "test").getScmRevision()).hasValue("a7bdf2d");
}
@Test
public void getNam_for_undetected_ci() {
assertThat(new CiConfigurationProvider.EmptyCiConfiguration().getCiName()).isEqualTo("undetected");
}
@Test
public void getName_for_detected_ci() {
assertThat(new CiConfigurationImpl(null, "test").getCiName()).isEqualTo("test");
}
}
| 1,686 | 35.673913 | 103 | java |
sonarqube | sonarqube-master/sonar-scanner-engine/src/test/java/org/sonar/scanner/ci/CiConfigurationProviderTest.java | /*
* SonarQube
* Copyright (C) 2009-2023 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.ci;
import org.junit.Test;
import org.sonar.api.config.internal.MapSettings;
import org.sonar.api.utils.MessageException;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.catchThrowable;
public class CiConfigurationProviderTest {
private final MapSettings cli = new MapSettings();
private final CiConfigurationProvider underTest = new CiConfigurationProvider();
@Test
public void empty_configuration_if_no_ci_vendors() {
CiConfiguration CiConfiguration = underTest.provide(cli.asConfig(), new CiVendor[0]);
assertThat(CiConfiguration.getScmRevision()).isEmpty();
}
@Test
public void empty_configuration_if_no_ci_detected() {
CiConfiguration ciConfiguration = underTest.provide(cli.asConfig(), new CiVendor[]{new DisabledCiVendor("vendor1"), new DisabledCiVendor("vendor2")});
assertThat(ciConfiguration.getScmRevision()).isEmpty();
}
@Test
public void configuration_defined_by_ci_vendor() {
CiConfiguration ciConfiguration = underTest.provide(cli.asConfig(), new CiVendor[]{new DisabledCiVendor("vendor1"), new EnabledCiVendor("vendor2")});
assertThat(ciConfiguration.getScmRevision()).hasValue(EnabledCiVendor.SHA);
}
@Test
public void fail_if_multiple_ci_vendor_are_detected() {
Throwable thrown = catchThrowable(() -> underTest.provide(cli.asConfig(), new CiVendor[]{new EnabledCiVendor("vendor1"), new EnabledCiVendor("vendor2")}));
assertThat(thrown)
.isInstanceOf(MessageException.class)
.hasMessage("Multiple CI environments are detected: [vendor1, vendor2]. Please check environment variables or set property sonar.ci.autoconfig.disabled to true.");
}
@Test
public void empty_configuration_if_auto_configuration_is_disabled() {
cli.setProperty("sonar.ci.autoconfig.disabled", true);
CiConfiguration ciConfiguration = underTest.provide(cli.asConfig(), new CiVendor[]{new EnabledCiVendor("vendor1")});
assertThat(ciConfiguration.getScmRevision()).isEmpty();
}
private static class DisabledCiVendor implements CiVendor {
private final String name;
private DisabledCiVendor(String name) {
this.name = name;
}
@Override
public String getName() {
return name;
}
@Override
public boolean isDetected() {
return false;
}
@Override
public CiConfiguration loadConfiguration() {
throw new IllegalStateException("should not be called");
}
}
private static class EnabledCiVendor implements CiVendor {
private static final String SHA = "abc12df";
private final String name;
private EnabledCiVendor(String name) {
this.name = name;
}
@Override
public String getName() {
return name;
}
@Override
public boolean isDetected() {
return true;
}
@Override
public CiConfiguration loadConfiguration() {
return new CiConfigurationImpl(SHA, name);
}
}
}
| 3,830 | 31.193277 | 169 | java |
sonarqube | sonarqube-master/sonar-scanner-engine/src/test/java/org/sonar/scanner/ci/vendors/AppVeyorTest.java | /*
* SonarQube
* Copyright (C) 2009-2023 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.ci.vendors;
import javax.annotation.Nullable;
import org.junit.Test;
import org.sonar.api.utils.System2;
import org.sonar.scanner.ci.CiVendor;
import static org.assertj.core.api.Assertions.assertThat;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;
public class AppVeyorTest {
private System2 system = mock(System2.class);
private CiVendor underTest = new AppVeyor(system);
@Test
public void getName() {
assertThat(underTest.getName()).isEqualTo("AppVeyor");
}
@Test
public void isDetected() {
setEnvVariable("CI", "true");
setEnvVariable("APPVEYOR", "true");
assertThat(underTest.isDetected()).isTrue();
// on Windows
setEnvVariable("CI", "True");
setEnvVariable("APPVEYOR", "True");
assertThat(underTest.isDetected()).isTrue();
setEnvVariable("CI", "true");
setEnvVariable("SEMAPHORE", "true");
setEnvVariable("APPVEYOR", null);
assertThat(underTest.isDetected()).isFalse();
setEnvVariable("CI", "false");
setEnvVariable("APPVEYOR", "true");
assertThat(underTest.isDetected()).isFalse();
}
@Test
public void loadConfiguration() {
setEnvVariable("CI", "true");
setEnvVariable("APPVEYOR", "true");
setEnvVariable("APPVEYOR_REPO_COMMIT", "abd12fc");
assertThat(underTest.loadConfiguration().getScmRevision()).hasValue("abd12fc");
}
private void setEnvVariable(String key, @Nullable String value) {
when(system.envVariable(key)).thenReturn(value);
}
}
| 2,369 | 30.6 | 83 | java |
sonarqube | sonarqube-master/sonar-scanner-engine/src/test/java/org/sonar/scanner/ci/vendors/AwsCodeBuildTest.java | /*
* SonarQube
* Copyright (C) 2009-2023 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.ci.vendors;
import javax.annotation.Nullable;
import org.junit.Test;
import org.sonar.api.utils.System2;
import org.sonar.scanner.ci.CiVendor;
import static org.assertj.core.api.Assertions.assertThat;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;
public class AwsCodeBuildTest {
private final System2 system = mock(System2.class);
private final CiVendor underTest = new AwsCodeBuild(system);
@Test
public void getName() {
assertThat(underTest.getName()).isEqualTo("AwsCodeBuild");
}
@Test
public void isDetected() {
assertThat(underTest.isDetected()).isFalse();
setEnvVariable("CODEBUILD_BUILD_ID", "51");
assertThat(underTest.isDetected()).isFalse();
setEnvVariable("CODEBUILD_BUILD_ID", "52");
setEnvVariable("CODEBUILD_START_TIME", "some-time");
assertThat(underTest.isDetected()).isTrue();
}
@Test
public void loadConfiguration() {
setEnvVariable("CODEBUILD_BUILD_ID", "51");
setEnvVariable("CODEBUILD_START_TIME", "some-time");
assertThat(underTest.loadConfiguration().getScmRevision()).isEmpty();
}
private void setEnvVariable(String key, @Nullable String value) {
when(system.envVariable(key)).thenReturn(value);
}
}
| 2,108 | 31.446154 | 75 | java |
sonarqube | sonarqube-master/sonar-scanner-engine/src/test/java/org/sonar/scanner/ci/vendors/AzureDevopsTest.java | /*
* SonarQube
* Copyright (C) 2009-2023 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.ci.vendors;
import javax.annotation.Nullable;
import org.junit.Test;
import org.sonar.api.utils.System2;
import org.sonar.scanner.ci.CiVendor;
import static org.assertj.core.api.Assertions.assertThat;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;
public class AzureDevopsTest {
private System2 system = mock(System2.class);
private CiVendor underTest = new AzureDevops(system);
@Test
public void getName() {
assertThat(underTest.getName()).isEqualTo("Azure DevOps");
}
@Test
public void isDetected() {
setEnvVariable("TF_BUILD", "True");
assertThat(underTest.isDetected()).isTrue();
setEnvVariable("TF_BUILD", "true");
assertThat(underTest.isDetected()).isTrue();
setEnvVariable("CI", "true");
setEnvVariable("APPVEYOR", null);
setEnvVariable("TF_BUILD", null);
assertThat(underTest.isDetected()).isFalse();
}
@Test
public void loadConfiguration_on_branch() {
setEnvVariable("BUILD_SOURCEVERSION", "abd12fc");
assertThat(underTest.loadConfiguration().getScmRevision()).hasValue("abd12fc");
}
@Test
public void loadConfiguration_on_pull_request() {
setEnvVariable("BUILD_SOURCEVERSION", "0e648ea");
setEnvVariable("SYSTEM_PULLREQUEST_PULLREQUESTID", "12");
setEnvVariable("SYSTEM_PULLREQUEST_PULLREQUESTITERATION", "5");
setEnvVariable("SYSTEM_PULLREQUEST_SOURCEBRANCH", "refs/heads/azure-pipelines");
setEnvVariable("SYSTEM_PULLREQUEST_SOURCECOMMITID", "a0e1e4c");
assertThat(underTest.loadConfiguration().getScmRevision()).hasValue("a0e1e4c");
}
private void setEnvVariable(String key, @Nullable String value) {
when(system.envVariable(key)).thenReturn(value);
}
}
| 2,587 | 32.179487 | 84 | java |
sonarqube | sonarqube-master/sonar-scanner-engine/src/test/java/org/sonar/scanner/ci/vendors/BambooTest.java | /*
* SonarQube
* Copyright (C) 2009-2023 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.ci.vendors;
import javax.annotation.Nullable;
import org.junit.Test;
import org.sonar.api.utils.System2;
import org.sonar.scanner.ci.CiVendor;
import static org.assertj.core.api.Assertions.assertThat;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;
public class BambooTest {
private final System2 system = mock(System2.class);
private final CiVendor underTest = new Bamboo(system);
@Test
public void getName() {
assertThat(underTest.getName()).isEqualTo("Bamboo");
}
@Test
public void isDetected() {
assertThat(underTest.isDetected()).isFalse();
setEnvVariable("bamboo_buildNumber", "41");
assertThat(underTest.isDetected()).isTrue();
}
@Test
public void loadConfiguration() {
setEnvVariable("bamboo_buildNumber", "41");
setEnvVariable("bamboo_planRepository_revision", "42109719-93c9-4d47-9d7c-b3b0b87b6985");
assertThat(underTest.loadConfiguration().getScmRevision()).hasValue("42109719-93c9-4d47-9d7c-b3b0b87b6985");
}
private void setEnvVariable(String key, @Nullable String value) {
when(system.envVariable(key)).thenReturn(value);
}
}
| 2,010 | 31.967213 | 112 | java |
sonarqube | sonarqube-master/sonar-scanner-engine/src/test/java/org/sonar/scanner/ci/vendors/BitbucketPipelinesTest.java | /*
* SonarQube
* Copyright (C) 2009-2023 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.ci.vendors;
import javax.annotation.Nullable;
import org.junit.Test;
import org.sonar.api.utils.System2;
import org.sonar.scanner.ci.CiVendor;
import static org.assertj.core.api.Assertions.assertThat;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;
public class BitbucketPipelinesTest {
private System2 system = mock(System2.class);
private CiVendor underTest = new BitbucketPipelines(system);
@Test
public void getName() {
assertThat(underTest.getName()).isEqualTo("Bitbucket Pipelines");
}
@Test
public void isDetected() {
setEnvVariable("CI", "true");
setEnvVariable("BITBUCKET_COMMIT", "bdf12fe");
assertThat(underTest.isDetected()).isTrue();
setEnvVariable("CI", "true");
setEnvVariable("BITBUCKET_COMMIT", null);
assertThat(underTest.isDetected()).isFalse();
}
@Test
public void configuration_of_pull_request() {
setEnvVariable("CI", "true");
setEnvVariable("BITBUCKET_COMMIT", "abd12fc");
setEnvVariable("BITBUCKET_PR_ID", "1234");
assertThat(underTest.loadConfiguration().getScmRevision()).hasValue("abd12fc");
}
@Test
public void configuration_of_branch() {
setEnvVariable("CI", "true");
setEnvVariable("BITBUCKET_COMMIT", "abd12fc");
setEnvVariable("BITBUCKET_PR_ID", null);
assertThat(underTest.loadConfiguration().getScmRevision()).hasValue("abd12fc");
}
private void setEnvVariable(String key, @Nullable String value) {
when(system.envVariable(key)).thenReturn(value);
}
}
| 2,395 | 31.378378 | 83 | java |
sonarqube | sonarqube-master/sonar-scanner-engine/src/test/java/org/sonar/scanner/ci/vendors/BitriseTest.java | /*
* SonarQube
* Copyright (C) 2009-2023 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.ci.vendors;
import javax.annotation.Nullable;
import org.junit.Test;
import org.sonar.api.utils.System2;
import org.sonar.scanner.ci.CiVendor;
import static org.assertj.core.api.Assertions.assertThat;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;
public class BitriseTest {
private final System2 system = mock(System2.class);
private final CiVendor underTest = new Bitrise(system);
@Test
public void getName() {
assertThat(underTest.getName()).isEqualTo("Bitrise");
}
@Test
public void isDetected() {
assertThat(underTest.isDetected()).isFalse();
setEnvVariable("CI", "true");
assertThat(underTest.isDetected()).isFalse();
setEnvVariable("CI", "true");
setEnvVariable("BITRISE_IO", "false");
assertThat(underTest.isDetected()).isFalse();
setEnvVariable("CI", "true");
setEnvVariable("BITRISE_IO", "true");
assertThat(underTest.isDetected()).isTrue();
}
@Test
public void loadConfiguration() {
setEnvVariable("CI", "true");
setEnvVariable("BITRISE_IO", "true");
setEnvVariable("BITRISE_GIT_COMMIT", "abd12fc");
assertThat(underTest.loadConfiguration().getScmRevision()).hasValue("abd12fc");
}
private void setEnvVariable(String key, @Nullable String value) {
when(system.envVariable(key)).thenReturn(value);
}
}
| 2,213 | 30.183099 | 83 | java |
sonarqube | sonarqube-master/sonar-scanner-engine/src/test/java/org/sonar/scanner/ci/vendors/BuildkiteTest.java | /*
* SonarQube
* Copyright (C) 2009-2023 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.ci.vendors;
import javax.annotation.Nullable;
import org.junit.Test;
import org.sonar.api.utils.System2;
import org.sonar.scanner.ci.CiVendor;
import static org.assertj.core.api.Assertions.assertThat;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;
public class BuildkiteTest {
private System2 system = mock(System2.class);
private CiVendor underTest = new Buildkite(system);
@Test
public void getName() {
assertThat(underTest.getName()).isEqualTo("Buildkite");
}
@Test
public void isDetected() {
setEnvVariable("CI", "true");
setEnvVariable("BUILDKITE", "true");
assertThat(underTest.isDetected()).isTrue();
setEnvVariable("CI", "true");
setEnvVariable("SEMAPHORE", "true");
setEnvVariable("BUILDKITE", null);
assertThat(underTest.isDetected()).isFalse();
setEnvVariable("CI", "false");
setEnvVariable("BUILDKITE", "true");
assertThat(underTest.isDetected()).isFalse();
}
@Test
public void loadConfiguration() {
setEnvVariable("CI", "true");
setEnvVariable("BUILDKITE", "true");
setEnvVariable("BUILDKITE_COMMIT", "abd12fc");
assertThat(underTest.loadConfiguration().getScmRevision()).hasValue("abd12fc");
}
private void setEnvVariable(String key, @Nullable String value) {
when(system.envVariable(key)).thenReturn(value);
}
}
| 2,230 | 30.871429 | 83 | java |
sonarqube | sonarqube-master/sonar-scanner-engine/src/test/java/org/sonar/scanner/ci/vendors/CircleCiTest.java | /*
* SonarQube
* Copyright (C) 2009-2023 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.ci.vendors;
import javax.annotation.Nullable;
import org.junit.Test;
import org.sonar.api.utils.System2;
import org.sonar.scanner.ci.CiVendor;
import static org.assertj.core.api.Assertions.assertThat;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;
public class CircleCiTest {
private System2 system = mock(System2.class);
private CiVendor underTest = new CircleCi(system);
@Test
public void getName() {
assertThat(underTest.getName()).isEqualTo("CircleCI");
}
@Test
public void isDetected() {
setEnvVariable("CI", "true");
setEnvVariable("CIRCLECI", "true");
assertThat(underTest.isDetected()).isTrue();
setEnvVariable("CI", "true");
setEnvVariable("SEMAPHORE", "true");
setEnvVariable("CIRCLECI", null);
assertThat(underTest.isDetected()).isFalse();
setEnvVariable("CI", "false");
setEnvVariable("CIRCLECI", "true");
assertThat(underTest.isDetected()).isFalse();
}
@Test
public void loadConfiguration() {
setEnvVariable("CI", "true");
setEnvVariable("CIRCLECI", "true");
setEnvVariable("CIRCLE_SHA1", "abd12fc");
assertThat(underTest.loadConfiguration().getScmRevision()).hasValue("abd12fc");
}
private void setEnvVariable(String key, @Nullable String value) {
when(system.envVariable(key)).thenReturn(value);
}
}
| 2,218 | 30.7 | 83 | java |
sonarqube | sonarqube-master/sonar-scanner-engine/src/test/java/org/sonar/scanner/ci/vendors/CirrusCiTest.java | /*
* SonarQube
* Copyright (C) 2009-2023 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.ci.vendors;
import javax.annotation.Nullable;
import org.junit.Rule;
import org.junit.Test;
import org.slf4j.event.Level;
import org.sonar.api.testfixtures.log.LogTester;
import org.sonar.api.utils.System2;
import org.sonar.scanner.ci.CiConfiguration;
import org.sonar.scanner.ci.CiVendor;
import static org.assertj.core.api.Assertions.assertThat;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;
public class CirrusCiTest {
private System2 system = mock(System2.class);
private CiVendor underTest = new CirrusCi(system);
@Rule
public LogTester logs = new LogTester();
@Test
public void getName() {
assertThat(underTest.getName()).isEqualTo("CirrusCI");
}
@Test
public void isDetected() {
setEnvVariable("CIRRUS_CI", "true");
assertThat(underTest.isDetected()).isTrue();
setEnvVariable("CIRRUS_CI", null);
assertThat(underTest.isDetected()).isFalse();
}
@Test
public void configuration_of_pull_request() {
setEnvVariable("CIRRUS_PR", "1234");
setEnvVariable("CIRRUS_BASE_SHA", "abd12fc");
setEnvVariable("CIRRUS_CHANGE_IN_REPO", "fd355db");
assertThat(underTest.loadConfiguration().getScmRevision()).hasValue("fd355db");
}
@Test
public void configuration_of_branch() {
setEnvVariable("CIRRUS_CHANGE_IN_REPO", "abd12fc");
assertThat(underTest.loadConfiguration().getScmRevision()).hasValue("abd12fc");
}
@Test
public void log_warning_if_missing_commit_variable() {
setEnvVariable("CIRRUS_PR", "1234");
CiConfiguration configuration = underTest.loadConfiguration();
assertThat(configuration.getScmRevision()).isEmpty();
assertThat(logs.logs(Level.WARN)).contains("Missing environment variable CIRRUS_CHANGE_IN_REPO");
}
private void setEnvVariable(String key, @Nullable String value) {
when(system.envVariable(key)).thenReturn(value);
}
}
| 2,759 | 30.724138 | 101 | java |
sonarqube | sonarqube-master/sonar-scanner-engine/src/test/java/org/sonar/scanner/ci/vendors/CodeMagicTest.java | /*
* SonarQube
* Copyright (C) 2009-2023 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.ci.vendors;
import java.util.List;
import javax.annotation.Nullable;
import org.junit.Rule;
import org.junit.Test;
import org.slf4j.event.Level;
import org.sonar.api.testfixtures.log.LogTester;
import org.sonar.api.utils.System2;
import org.sonar.scanner.ci.CiConfiguration;
import org.sonar.scanner.ci.CiVendor;
import static org.assertj.core.api.Assertions.assertThat;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;
public class CodeMagicTest {
private final System2 system = mock(System2.class);
private final CiVendor underTest = new CodeMagic(system);
@Rule
public LogTester logTester = new LogTester();
@Test
public void getName() {
assertThat(underTest.getName()).isEqualTo("CodeMagic");
}
@Test
public void isDetected_givenBuildID_detectCodeMagic() {
setEnvVariable("FCI_BUILD_ID", "1");
assertThat(underTest.isDetected()).isTrue();
}
@Test
public void isDetected_givenNoEnvVariable_dontDetectCodeMagic() {
assertThat(underTest.isDetected()).isFalse();
}
@Test
public void loadConfiguration_commitEnvVariableAvailable_addScmRevisionToConfig() {
setEnvVariable("FCI_BUILD_ID", "1");
setEnvVariable("FCI_COMMIT", "d9d25f70ec9023f7acc0c520c8b67204229a5c7e");
assertThat(underTest.loadConfiguration().getScmRevision()).hasValue("d9d25f70ec9023f7acc0c520c8b67204229a5c7e");
}
@Test
public void loadConfiguration_commitEnvVariableNotAvailable_addScmRevisionToConfig() {
setEnvVariable("FCI_BUILD_ID", "1");
CiConfiguration ciConfiguration = underTest.loadConfiguration();
List<String> logs = logTester.logs(Level.WARN);
assertThat(ciConfiguration.getScmRevision()).isEmpty();
assertThat(logs).hasSize(1);
assertThat(logs.get(0)).isEqualTo("Missing environment variable FCI_COMMIT");
}
private void setEnvVariable(String key, @Nullable String value) {
when(system.envVariable(key)).thenReturn(value);
}
}
| 2,822 | 31.825581 | 116 | java |
sonarqube | sonarqube-master/sonar-scanner-engine/src/test/java/org/sonar/scanner/ci/vendors/DroneCiTest.java | /*
* SonarQube
* Copyright (C) 2009-2023 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.ci.vendors;
import javax.annotation.Nullable;
import org.junit.Test;
import org.sonar.api.utils.System2;
import org.sonar.scanner.ci.CiVendor;
import static org.assertj.core.api.Assertions.assertThat;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;
public class DroneCiTest {
private System2 system = mock(System2.class);
private CiVendor underTest = new DroneCi(system);
@Test
public void getName() {
assertThat(underTest.getName()).isEqualTo("DroneCI");
}
@Test
public void isDetected() {
setEnvVariable("CI", "true");
setEnvVariable("DRONE", "true");
assertThat(underTest.isDetected()).isTrue();
setEnvVariable("CI", "true");
setEnvVariable("DRONE", null);
assertThat(underTest.isDetected()).isFalse();
}
@Test
public void loadConfiguration() {
setEnvVariable("CI", "true");
setEnvVariable("DRONE", "true");
setEnvVariable("DRONE_COMMIT_SHA", "abd12fc");
assertThat(underTest.loadConfiguration().getScmRevision()).hasValue("abd12fc");
}
private void setEnvVariable(String key, @Nullable String value) {
when(system.envVariable(key)).thenReturn(value);
}
}
| 2,044 | 30.461538 | 83 | java |
sonarqube | sonarqube-master/sonar-scanner-engine/src/test/java/org/sonar/scanner/ci/vendors/GithubActionsTest.java | /*
* SonarQube
* Copyright (C) 2009-2023 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.ci.vendors;
import javax.annotation.Nullable;
import org.junit.Rule;
import org.junit.Test;
import org.slf4j.event.Level;
import org.sonar.api.testfixtures.log.LogTester;
import org.sonar.api.utils.System2;
import org.sonar.scanner.ci.CiVendor;
import static org.assertj.core.api.Assertions.assertThat;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;
public class GithubActionsTest {
@Rule
public LogTester logs = new LogTester();
private System2 system = mock(System2.class);
private CiVendor underTest = new GithubActions(system);
@Test
public void getName() {
assertThat(underTest.getName()).isEqualTo("Github Actions");
}
@Test
public void isDetected() {
setEnvVariable("GITHUB_ACTION", "build");
assertThat(underTest.isDetected()).isTrue();
setEnvVariable("GITHUB_ACTION", null);
assertThat(underTest.isDetected()).isFalse();
}
@Test
public void loadConfiguration() {
setEnvVariable("GITHUB_ACTION", "build");
setEnvVariable("GITHUB_SHA", "abd12fc");
assertThat(underTest.loadConfiguration().getScmRevision()).hasValue("abd12fc");
}
@Test
public void log_warning_if_missing_GITHUB_SHA() {
setEnvVariable("GITHUB_ACTION", "build");
assertThat(underTest.loadConfiguration().getScmRevision()).isEmpty();
assertThat(logs.logs(Level.WARN)).contains("Missing environment variable GITHUB_SHA");
}
private void setEnvVariable(String key, @Nullable String value) {
when(system.envVariable(key)).thenReturn(value);
}
}
| 2,412 | 30.75 | 90 | java |
sonarqube | sonarqube-master/sonar-scanner-engine/src/test/java/org/sonar/scanner/ci/vendors/GitlabCiTest.java | /*
* SonarQube
* Copyright (C) 2009-2023 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.ci.vendors;
import javax.annotation.Nullable;
import org.junit.Test;
import org.sonar.api.utils.System2;
import org.sonar.scanner.ci.CiVendor;
import static org.assertj.core.api.Assertions.assertThat;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;
public class GitlabCiTest {
private System2 system = mock(System2.class);
private CiVendor underTest = new GitlabCi(system);
@Test
public void getName() {
assertThat(underTest.getName()).isEqualTo("Gitlab CI");
}
@Test
public void isDetected() {
setEnvVariable("GITLAB_CI", "true");
assertThat(underTest.isDetected()).isTrue();
setEnvVariable("GITLAB_CI", null);
assertThat(underTest.isDetected()).isFalse();
}
@Test
public void loadConfiguration() {
setEnvVariable("GITLAB_CI", "true");
setEnvVariable("CI_COMMIT_SHA", "abd12fc");
assertThat(underTest.loadConfiguration().getScmRevision()).hasValue("abd12fc");
}
private void setEnvVariable(String key, @Nullable String value) {
when(system.envVariable(key)).thenReturn(value);
}
}
| 1,955 | 30.548387 | 83 | java |
sonarqube | sonarqube-master/sonar-scanner-engine/src/test/java/org/sonar/scanner/ci/vendors/JenkinsTest.java | /*
* SonarQube
* Copyright (C) 2009-2023 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.ci.vendors;
import java.io.File;
import java.io.IOException;
import java.nio.file.Path;
import javax.annotation.Nullable;
import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.TemporaryFolder;
import org.sonar.api.batch.fs.internal.DefaultInputProject;
import org.sonar.api.utils.System2;
import org.sonar.api.utils.ZipUtils;
import org.sonar.scanner.ci.CiVendor;
import static org.assertj.core.api.Assertions.assertThat;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;
public class JenkinsTest {
private System2 system = mock(System2.class);
private DefaultInputProject project = mock(DefaultInputProject.class);
private CiVendor underTest = new Jenkins(system, project);
@Rule
public TemporaryFolder temp = new TemporaryFolder();
@Test
public void getName() {
assertThat(underTest.getName()).isEqualTo("Jenkins");
}
@Test
public void isDetected() {
setEnvVariable("JENKINS_URL", "http://foo");
setEnvVariable("EXECUTOR_NUMBER", "12");
assertThat(underTest.isDetected()).isTrue();
setEnvVariable("JENKINS_URL", null);
setEnvVariable("EXECUTOR_NUMBER", "12");
assertThat(underTest.isDetected()).isFalse();
setEnvVariable("JENKINS_URL", "http://foo");
setEnvVariable("EXECUTOR_NUMBER", null);
assertThat(underTest.isDetected()).isFalse();
}
@Test
public void loadConfiguration_with_deprecated_pull_request_plugin() {
setEnvVariable("ghprbActualCommit", "abd12fc");
assertThat(underTest.loadConfiguration().getScmRevision()).hasValue("abd12fc");
}
@Test
public void loadConfiguration_of_git_repo() {
setEnvVariable("GIT_COMMIT", "abd12fc");
assertThat(underTest.loadConfiguration().getScmRevision()).hasValue("abd12fc");
}
@Test
public void loadConfiguration_of_git_repo_with_branch_plugin() throws IOException {
// prepare fake git clone
Path baseDir = temp.newFolder().toPath();
File unzip = ZipUtils.unzip(this.getClass().getResourceAsStream("gitrepo.zip"), baseDir.toFile());
when(project.getBaseDir()).thenReturn(unzip.toPath().resolve("gitrepo"));
setEnvVariable("CHANGE_ID", "3");
setEnvVariable("GIT_BRANCH", "PR-3");
// this will be ignored
setEnvVariable("GIT_COMMIT", "abd12fc");
assertThat(underTest.loadConfiguration().getScmRevision()).hasValue("e6013986eff4f0ce0a85f5d070070e7fdabead48");
}
@Test
public void loadConfiguration_of_git_repo_with_branch_plugin_without_git_repo() throws IOException {
// prepare fake git clone
Path baseDir = temp.newFolder().toPath();
when(project.getBaseDir()).thenReturn(baseDir);
setEnvVariable("CHANGE_ID", "3");
setEnvVariable("GIT_BRANCH", "PR-3");
setEnvVariable("GIT_COMMIT", "abc");
assertThat(underTest.loadConfiguration().getScmRevision()).hasValue("abc");
}
@Test
public void loadConfiguration_of_svn_repo() {
setEnvVariable("SVN_COMMIT", "abd12fc");
assertThat(underTest.loadConfiguration().getScmRevision()).hasValue("abd12fc");
}
private void setEnvVariable(String key, @Nullable String value) {
when(system.envVariable(key)).thenReturn(value);
}
}
| 4,034 | 32.625 | 116 | java |
sonarqube | sonarqube-master/sonar-scanner-engine/src/test/java/org/sonar/scanner/ci/vendors/SemaphoreCiTest.java | /*
* SonarQube
* Copyright (C) 2009-2023 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.ci.vendors;
import javax.annotation.Nullable;
import org.junit.Test;
import org.sonar.api.utils.System2;
import org.sonar.scanner.ci.CiVendor;
import static org.assertj.core.api.Assertions.assertThat;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;
public class SemaphoreCiTest {
private System2 system = mock(System2.class);
private CiVendor underTest = new SemaphoreCi(system);
@Test
public void getName() {
assertThat(underTest.getName()).isEqualTo("SemaphoreCI");
}
@Test
public void isDetected() {
setEnvVariable("SEMAPHORE", "true");
setEnvVariable("SEMAPHORE_PROJECT_ID", "d782a107-aaf9-494d-8153-206b1a6bc8e9");
assertThat(underTest.isDetected()).isTrue();
setEnvVariable("SEMAPHORE", "true");
setEnvVariable("SEMAPHORE_PROJECT_ID", null);
assertThat(underTest.isDetected()).isFalse();
setEnvVariable("SEMAPHORE", null);
setEnvVariable("SEMAPHORE_PROJECT_ID", "d782a107-aaf9-494d-8153-206b1a6bc8e9");
assertThat(underTest.isDetected()).isFalse();
setEnvVariable("SEMAPHORE", "foo");
setEnvVariable("SEMAPHORE_PROJECT_ID", "d782a107-aaf9-494d-8153-206b1a6bc8e9");
assertThat(underTest.isDetected()).isFalse();
}
@Test
public void loadConfiguration() {
setEnvVariable("SEMAPHORE", "true");
setEnvVariable("SEMAPHORE_PROJECT_ID", "d782a107-aaf9-494d-8153-206b1a6bc8e9");
setEnvVariable("SEMAPHORE_GIT_SHA", "abd12fc");
assertThat(underTest.loadConfiguration().getScmRevision()).hasValue("abd12fc");
}
private void setEnvVariable(String key, @Nullable String value) {
when(system.envVariable(key)).thenReturn(value);
}
}
| 2,536 | 33.753425 | 83 | java |
sonarqube | sonarqube-master/sonar-scanner-engine/src/test/java/org/sonar/scanner/ci/vendors/TravisCiTest.java | /*
* SonarQube
* Copyright (C) 2009-2023 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.ci.vendors;
import javax.annotation.Nullable;
import org.junit.Test;
import org.sonar.api.utils.System2;
import org.sonar.scanner.ci.CiVendor;
import static org.assertj.core.api.Assertions.assertThat;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;
public class TravisCiTest {
private System2 system = mock(System2.class);
private CiVendor underTest = new TravisCi(system);
@Test
public void getName() {
assertThat(underTest.getName()).isEqualTo("TravisCI");
}
@Test
public void isDetected() {
setEnvVariable("CI", "true");
setEnvVariable("TRAVIS", "true");
assertThat(underTest.isDetected()).isTrue();
setEnvVariable("CI", "true");
setEnvVariable("DRONE", "true");
setEnvVariable("TRAVIS", null);
assertThat(underTest.isDetected()).isFalse();
}
@Test
public void loadConfiguration_of_branch() {
setEnvVariable("CI", "true");
setEnvVariable("TRAVIS", "true");
setEnvVariable("TRAVIS_COMMIT", "abd12fc");
setEnvVariable("TRAVIS_PULL_REQUEST", "false");
setEnvVariable("TRAVIS_PULL_REQUEST_SHA", "");
assertThat(underTest.loadConfiguration().getScmRevision()).hasValue("abd12fc");
}
@Test
public void loadConfiguration_of_pull_request() {
setEnvVariable("CI", "true");
setEnvVariable("TRAVIS", "true");
setEnvVariable("TRAVIS_COMMIT", "abd12fc");
setEnvVariable("TRAVIS_PULL_REQUEST", "1234");
setEnvVariable("TRAVIS_PULL_REQUEST_SHA", "987fbd3");
assertThat(underTest.loadConfiguration().getScmRevision()).hasValue("987fbd3");
}
private void setEnvVariable(String key, @Nullable String value) {
when(system.envVariable(key)).thenReturn(value);
}
}
| 2,576 | 31.620253 | 83 | java |
sonarqube | sonarqube-master/sonar-scanner-engine/src/test/java/org/sonar/scanner/config/DefaultConfigurationTest.java | /*
* SonarQube
* Copyright (C) 2009-2023 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.config;
import com.google.common.collect.ImmutableMap;
import java.util.Arrays;
import org.junit.Rule;
import org.junit.Test;
import org.slf4j.event.Level;
import org.sonar.api.config.Configuration;
import org.sonar.api.config.PropertyDefinition;
import org.sonar.api.config.PropertyDefinitions;
import org.sonar.api.config.PropertyFieldDefinition;
import org.sonar.api.config.internal.Encryption;
import org.sonar.api.testfixtures.log.LogTester;
import org.sonar.api.utils.System2;
import static java.util.Collections.singletonList;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.fail;
public class DefaultConfigurationTest {
@Rule
public LogTester logTester = new LogTester();
@Test
public void accessingMultiValuedPropertiesShouldBeConsistentWithDeclaration() {
Configuration config = new DefaultConfiguration(new PropertyDefinitions(System2.INSTANCE, Arrays.asList(
PropertyDefinition.builder("single").multiValues(false).build(),
PropertyDefinition.builder("multiA").multiValues(true).build())), new Encryption(null),
ImmutableMap.of("single", "foo", "multiA", "a,b", "notDeclared", "c,d")) {
};
assertThat(config.get("multiA")).hasValue("a,b");
assertThat(logTester.logs(Level.WARN))
.contains(
"Access to the multi-values/property set property 'multiA' should be made using 'getStringArray' method. The SonarQube plugin using this property should be updated.");
logTester.clear();
assertThat(config.getStringArray("single")).containsExactly("foo");
assertThat(logTester.logs(Level.WARN))
.contains(
"Property 'single' is not declared as multi-values/property set but was read using 'getStringArray' method. The SonarQube plugin declaring this property should be updated.");
logTester.clear();
assertThat(config.get("notDeclared")).hasValue("c,d");
assertThat(config.getStringArray("notDeclared")).containsExactly("c", "d");
assertThat(logTester.logs(Level.WARN)).isEmpty();
}
@Test
public void accessingPropertySetPropertiesShouldBeConsistentWithDeclaration() {
Configuration config = new DefaultConfiguration(new PropertyDefinitions(System2.INSTANCE, Arrays.asList(
PropertyDefinition.builder("props").fields(PropertyFieldDefinition.build("foo1").name("Foo1").build(), PropertyFieldDefinition.build("foo2").name("Foo2").build()).build())),
new Encryption(null),
ImmutableMap.of("props", "1,2", "props.1.foo1", "a", "props.1.foo2", "b")) {
};
assertThat(config.get("props")).hasValue("1,2");
assertThat(logTester.logs(Level.WARN))
.contains(
"Access to the multi-values/property set property 'props' should be made using 'getStringArray' method. The SonarQube plugin using this property should be updated.");
logTester.clear();
assertThat(config.getStringArray("props")).containsExactly("1", "2");
assertThat(logTester.logs(Level.WARN)).isEmpty();
}
@Test
public void getDefaultValues() {
Configuration config = new DefaultConfiguration(new PropertyDefinitions(System2.INSTANCE, Arrays.asList(
PropertyDefinition.builder("single").multiValues(false).defaultValue("default").build(),
PropertyDefinition.builder("multiA").multiValues(true).defaultValue("foo,bar").build())), new Encryption(null),
ImmutableMap.of()) {
};
assertThat(config.get("multiA")).hasValue("foo,bar");
assertThat(config.getStringArray("multiA")).containsExactly("foo", "bar");
assertThat(config.get("single")).hasValue("default");
assertThat(config.getStringArray("single")).containsExactly("default");
}
@Test
public void testParsingMultiValues() {
assertThat(getStringArray("")).isEmpty();
assertThat(getStringArray(",")).isEmpty();
assertThat(getStringArray(",,")).isEmpty();
assertThat(getStringArray("a")).containsExactly("a");
assertThat(getStringArray("a b")).containsExactly("a b");
assertThat(getStringArray("a , b")).containsExactly("a", "b");
assertThat(getStringArray("\"a \",\" b\"")).containsExactly("a ", " b");
assertThat(getStringArray("\"a,b\",c")).containsExactly("a,b", "c");
assertThat(getStringArray("\"a\nb\",c")).containsExactly("a\nb", "c");
assertThat(getStringArray("\"a\",\n b\n")).containsExactly("a", "b");
assertThat(getStringArray("a\n,b\n")).containsExactly("a", "b");
assertThat(getStringArray("a\n,b\n,\"\"")).containsExactly("a", "b", "");
assertThat(getStringArray("a\n, \" \" ,b\n")).containsExactly("a", " ", "b");
assertThat(getStringArray(" \" , ,, \", a\n,b\n")).containsExactly(" , ,, ", "a", "b");
assertThat(getStringArray("a\n,,b\n")).containsExactly("a", "b");
assertThat(getStringArray("a,\n\nb,c")).containsExactly("a", "b", "c");
assertThat(getStringArray("a,b\n\nc,d")).containsExactly("a", "b\nc", "d");
try {
getStringArray("\"a ,b");
fail("Expected exception");
} catch (Exception e) {
assertThat(e).hasMessage("Property: 'multi' doesn't contain a valid CSV value: '\"a ,b'");
}
}
private String[] getStringArray(String value) {
return new DefaultConfiguration(new PropertyDefinitions(System2.INSTANCE, singletonList(
PropertyDefinition.builder("multi").multiValues(true).build())), new Encryption(null),
ImmutableMap.of("multi", value)) {
}.getStringArray("multi");
}
}
| 6,295 | 44.623188 | 182 | java |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.