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/repository/DefaultQualityProfileLoader.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.repository;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.function.BinaryOperator;
import java.util.function.Supplier;
import org.sonar.api.utils.MessageException;
import org.sonar.scanner.bootstrap.DefaultScannerWsClient;
import org.sonarqube.ws.Qualityprofiles.SearchWsResponse;
import org.sonarqube.ws.Qualityprofiles.SearchWsResponse.QualityProfile;
import org.sonarqube.ws.client.GetRequest;
import org.sonarqube.ws.client.HttpException;
import static java.util.function.Function.identity;
import static java.util.stream.Collectors.toMap;
import static org.sonar.api.impl.utils.ScannerUtils.encodeForUrl;
public class DefaultQualityProfileLoader implements QualityProfileLoader {
private static final String WS_URL = "/api/qualityprofiles/search.protobuf";
private final DefaultScannerWsClient wsClient;
public DefaultQualityProfileLoader(DefaultScannerWsClient wsClient) {
this.wsClient = wsClient;
}
private List<QualityProfile> loadDefault() {
StringBuilder url = new StringBuilder(WS_URL + "?defaults=true");
return handleErrors(url, () -> "Failed to load the default quality profiles", false);
}
@Override
public List<QualityProfile> load(String projectKey) {
StringBuilder url = new StringBuilder(WS_URL + "?project=").append(encodeForUrl(projectKey));
return handleErrors(url, () -> String.format("Failed to load the quality profiles of project '%s'", projectKey), true);
}
private List<QualityProfile> handleErrors(StringBuilder url, Supplier<String> errorMsg, boolean tryLoadDefault) {
try {
return doLoad(url);
} catch (HttpException e) {
if (e.code() == 404) {
if (tryLoadDefault) {
return loadDefault();
} else {
throw MessageException.of(errorMsg.get() + ": " + DefaultScannerWsClient.createErrorMessage(e));
}
}
throw new IllegalStateException(errorMsg.get() + ": " + DefaultScannerWsClient.createErrorMessage(e));
} catch (MessageException e) {
throw e;
} catch (Exception e) {
throw new IllegalStateException(errorMsg.get(), e);
}
}
private List<QualityProfile> doLoad(StringBuilder url) throws IOException {
Map<String, QualityProfile> result = call(url.toString());
if (result.isEmpty()) {
throw MessageException.of("No quality profiles have been found, you probably don't have any language plugin installed.");
}
return new ArrayList<>(result.values());
}
private Map<String, QualityProfile> call(String url) throws IOException {
GetRequest getRequest = new GetRequest(url);
try (InputStream is = wsClient.call(getRequest).contentStream()) {
SearchWsResponse profiles = SearchWsResponse.parseFrom(is);
List<QualityProfile> profilesList = profiles.getProfilesList();
return profilesList.stream().collect(toMap(QualityProfile::getLanguage, identity(), throwingMerger(), LinkedHashMap::new));
}
}
private static <T> BinaryOperator<T> throwingMerger() {
return (u, v) -> {
throw new IllegalStateException(String.format("Duplicate key %s", u));
};
}
}
| 4,106 | 37.745283 | 129 | java |
sonarqube | sonarqube-master/sonar-scanner-engine/src/main/java/org/sonar/scanner/repository/FileData.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.repository;
import javax.annotation.concurrent.Immutable;
@Immutable
public class FileData {
private final String hash;
private final String revision;
public FileData(String hash, String revision) {
this.hash = hash;
this.revision = revision;
}
public String hash() {
return hash;
}
public String revision() {
return revision;
}
}
| 1,237 | 28.47619 | 75 | java |
sonarqube | sonarqube-master/sonar-scanner-engine/src/main/java/org/sonar/scanner/repository/MetricsRepository.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.repository;
import java.util.Collection;
import java.util.List;
import org.sonar.api.measures.Metric;
public class MetricsRepository {
private Collection<Metric> metrics;
public MetricsRepository(List<Metric> metrics) {
this.metrics = metrics;
}
public Collection<Metric> metrics() {
return metrics;
}
}
| 1,196 | 30.5 | 75 | java |
sonarqube | sonarqube-master/sonar-scanner-engine/src/main/java/org/sonar/scanner/repository/MetricsRepositoryLoader.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.repository;
public interface MetricsRepositoryLoader {
MetricsRepository load();
}
| 955 | 37.24 | 75 | java |
sonarqube | sonarqube-master/sonar-scanner-engine/src/main/java/org/sonar/scanner/repository/MetricsRepositoryProvider.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.repository;
import org.sonar.api.utils.log.Logger;
import org.sonar.api.utils.log.Loggers;
import org.sonar.api.utils.log.Profiler;
import org.springframework.context.annotation.Bean;
public class MetricsRepositoryProvider {
private static final Logger LOG = Loggers.get(MetricsRepositoryProvider.class);
private static final String LOG_MSG = "Load metrics repository";
@Bean("MetricsRepository")
public MetricsRepository provide(MetricsRepositoryLoader loader) {
Profiler profiler = Profiler.create(LOG).startInfo(LOG_MSG);
MetricsRepository metricsRepository = loader.load();
profiler.stopInfo();
return metricsRepository;
}
}
| 1,528 | 37.225 | 81 | java |
sonarqube | sonarqube-master/sonar-scanner-engine/src/main/java/org/sonar/scanner/repository/MultiModuleProjectRepository.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.repository;
import java.util.Map;
import javax.annotation.CheckForNull;
import javax.annotation.concurrent.Immutable;
@Immutable
public class MultiModuleProjectRepository extends ProjectRepositories {
private Map<String, SingleProjectRepository> repositoriesPerModule;
public MultiModuleProjectRepository(Map<String, SingleProjectRepository> repositoriesPerModule) {
super(true);
this.repositoriesPerModule = Map.copyOf(repositoriesPerModule);
}
@CheckForNull
public FileData fileData(String moduleKeyWithBranch, String path) {
SingleProjectRepository repository = repositoriesPerModule.get(moduleKeyWithBranch);
return repository == null ? null : repository.fileData(path);
}
}
| 1,582 | 35.813953 | 99 | java |
sonarqube | sonarqube-master/sonar-scanner-engine/src/main/java/org/sonar/scanner/repository/NewCodePeriodLoader.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.repository;
import org.sonarqube.ws.NewCodePeriods;
public interface NewCodePeriodLoader {
NewCodePeriods.ShowWSResponse load(String projectKey, String branchName);
}
| 1,040 | 37.555556 | 75 | java |
sonarqube | sonarqube-master/sonar-scanner-engine/src/main/java/org/sonar/scanner/repository/ProjectRepositories.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.repository;
import javax.annotation.CheckForNull;
import javax.annotation.concurrent.Immutable;
import org.sonar.api.batch.fs.internal.DefaultInputFile;
@Immutable
public abstract class ProjectRepositories {
private final boolean exists;
public ProjectRepositories(boolean exists) {
this.exists = exists;
}
public boolean exists() {
return exists;
}
@CheckForNull
public FileData fileData(String moduleKeyWithBranch, DefaultInputFile inputFile) {
if (this instanceof SingleProjectRepository) {
return ((SingleProjectRepository) this).fileData(inputFile.getProjectRelativePath());
} else {
return ((MultiModuleProjectRepository) this).fileData(moduleKeyWithBranch, inputFile.getModuleRelativePath());
}
}
}
| 1,629 | 32.958333 | 116 | java |
sonarqube | sonarqube-master/sonar-scanner-engine/src/main/java/org/sonar/scanner/repository/ProjectRepositoriesLoader.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.repository;
import javax.annotation.Nullable;
public interface ProjectRepositoriesLoader {
ProjectRepositories load(String projectKeyWithBranch, @Nullable String branchBase);
}
| 1,050 | 37.925926 | 85 | java |
sonarqube | sonarqube-master/sonar-scanner-engine/src/main/java/org/sonar/scanner/repository/ProjectRepositoriesProvider.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.repository;
import org.sonar.api.utils.log.Logger;
import org.sonar.api.utils.log.Loggers;
import org.sonar.api.utils.log.Profiler;
import org.sonar.scanner.bootstrap.ScannerProperties;
import org.sonar.scanner.scan.branch.BranchConfiguration;
import org.springframework.context.annotation.Bean;
public class ProjectRepositoriesProvider {
private static final Logger LOG = Loggers.get(ProjectRepositoriesProvider.class);
private static final String LOG_MSG = "Load project repositories";
private final ProjectRepositoriesLoader loader;
private final ScannerProperties scannerProperties;
private final BranchConfiguration branchConfig;
public ProjectRepositoriesProvider(ProjectRepositoriesLoader loader, ScannerProperties scannerProperties, BranchConfiguration branchConfig) {
this.loader = loader;
this.scannerProperties = scannerProperties;
this.branchConfig = branchConfig;
}
@Bean
public ProjectRepositories projectRepositories() {
Profiler profiler = Profiler.create(LOG).startInfo(LOG_MSG);
ProjectRepositories project = loader.load(scannerProperties.getProjectKey(), branchConfig.referenceBranchName());
profiler.stopInfo();
return project;
}
}
| 2,073 | 40.48 | 143 | java |
sonarqube | sonarqube-master/sonar-scanner-engine/src/main/java/org/sonar/scanner/repository/QualityProfileLoader.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.repository;
import java.util.List;
import org.sonarqube.ws.Qualityprofiles.SearchWsResponse.QualityProfile;
public interface QualityProfileLoader {
List<QualityProfile> load(String projectKey);
}
| 1,069 | 37.214286 | 75 | java |
sonarqube | sonarqube-master/sonar-scanner-engine/src/main/java/org/sonar/scanner/repository/QualityProfilesProvider.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.repository;
import org.sonar.api.utils.log.Logger;
import org.sonar.api.utils.log.Loggers;
import org.sonar.api.utils.log.Profiler;
import org.sonar.scanner.bootstrap.ScannerProperties;
import org.sonar.scanner.rule.QualityProfiles;
import org.springframework.context.annotation.Bean;
public class QualityProfilesProvider {
private static final Logger LOG = Loggers.get(QualityProfilesProvider.class);
private static final String LOG_MSG = "Load quality profiles";
@Bean("QualityProfiles")
public QualityProfiles provide(QualityProfileLoader loader, ScannerProperties props) {
Profiler profiler = Profiler.create(LOG).startInfo(LOG_MSG);
QualityProfiles profiles = new QualityProfiles(loader.load(props.getProjectKey()));
profiler.stopInfo();
return profiles;
}
}
| 1,663 | 38.619048 | 88 | java |
sonarqube | sonarqube-master/sonar-scanner-engine/src/main/java/org/sonar/scanner/repository/ReferenceBranchSupplier.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.repository;
import java.util.Optional;
import javax.annotation.CheckForNull;
import org.sonar.api.batch.fs.internal.DefaultInputProject;
import org.sonar.api.config.Configuration;
import org.sonar.api.utils.log.Logger;
import org.sonar.api.utils.log.Loggers;
import org.sonar.api.utils.log.Profiler;
import org.sonar.scanner.scan.branch.BranchConfiguration;
import org.sonar.scanner.scan.branch.ProjectBranches;
import org.sonarqube.ws.NewCodePeriods;
import static java.lang.String.format;
public class ReferenceBranchSupplier {
private static final Logger LOG = Loggers.get(ReferenceBranchSupplier.class);
private static final String LOG_MSG_WS = "Load New Code definition";
private static final String NEW_CODE_PARAM_KEY = "sonar.newCode.referenceBranch";
private final Configuration configuration;
private final NewCodePeriodLoader newCodePeriodLoader;
private final BranchConfiguration branchConfiguration;
private final DefaultInputProject project;
private final ProjectBranches branches;
public ReferenceBranchSupplier(Configuration configuration, NewCodePeriodLoader newCodePeriodLoader, BranchConfiguration branchConfiguration, DefaultInputProject project,
ProjectBranches branches) {
this.configuration = configuration;
this.newCodePeriodLoader = newCodePeriodLoader;
this.branchConfiguration = branchConfiguration;
this.project = project;
this.branches = branches;
}
@CheckForNull
public String get() {
// branches will be empty in CE
if (branchConfiguration.isPullRequest() || branches.isEmpty()) {
return null;
}
return Optional.ofNullable(getFromProperties()).orElseGet(this::loadWs);
}
private String loadWs() {
String branchName = getBranchName();
Profiler profiler = Profiler.create(LOG).startInfo(LOG_MSG_WS);
NewCodePeriods.ShowWSResponse newCode = newCodePeriodLoader.load(project.key(), branchName);
profiler.stopInfo();
if (newCode.getType() != NewCodePeriods.NewCodePeriodType.REFERENCE_BRANCH) {
return null;
}
String referenceBranchName = newCode.getValue();
if (branchName.equals(referenceBranchName)) {
LOG.warn("New Code reference branch is set to the branch being analyzed. Skipping the computation of New Code");
return null;
}
return referenceBranchName;
}
@CheckForNull
public String getFromProperties() {
// branches will be empty in CE
if (branchConfiguration.isPullRequest() || branches.isEmpty()) {
return null;
}
Optional<String> value = configuration.get(NEW_CODE_PARAM_KEY);
if (value.isPresent()) {
String referenceBranchName = value.get();
if (referenceBranchName.equals(getBranchName())) {
throw new IllegalStateException(format("Reference branch set with '%s' points to the current branch '%s'", NEW_CODE_PARAM_KEY, referenceBranchName));
}
return referenceBranchName;
}
return null;
}
private String getBranchName() {
return branchConfiguration.branchName() != null ? branchConfiguration.branchName() : branches.defaultBranchName();
}
}
| 3,977 | 36.885714 | 172 | java |
sonarqube | sonarqube-master/sonar-scanner-engine/src/main/java/org/sonar/scanner/repository/SingleProjectRepository.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.repository;
import java.util.Collections;
import java.util.Map;
import javax.annotation.CheckForNull;
import javax.annotation.concurrent.Immutable;
@Immutable
public class SingleProjectRepository extends ProjectRepositories {
private final Map<String, FileData> fileDataByPath;
public SingleProjectRepository() {
super(false);
this.fileDataByPath = Collections.emptyMap();
}
public SingleProjectRepository(Map<String, FileData> fileDataByPath) {
super(true);
this.fileDataByPath = Map.copyOf(fileDataByPath);
}
@CheckForNull
public FileData fileData(String path) {
return fileDataByPath.get(path);
}
}
| 1,513 | 31.212766 | 75 | java |
sonarqube | sonarqube-master/sonar-scanner-engine/src/main/java/org/sonar/scanner/repository/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.repository;
import javax.annotation.ParametersAreNonnullByDefault;
| 968 | 39.375 | 75 | java |
sonarqube | sonarqube-master/sonar-scanner-engine/src/main/java/org/sonar/scanner/repository/language/DefaultLanguagesRepository.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.repository.language;
import java.util.Arrays;
import java.util.Collection;
import java.util.stream.Collectors;
import javax.annotation.CheckForNull;
import javax.annotation.concurrent.Immutable;
import org.sonar.api.Startable;
import org.sonar.api.resources.Languages;
/**
* Languages repository using {@link Languages}
* @since 4.4
*/
@Immutable
public class DefaultLanguagesRepository implements LanguagesRepository, Startable {
private final Languages languages;
public DefaultLanguagesRepository(Languages languages) {
this.languages = languages;
}
@Override
public void start() {
if (languages.all().length == 0) {
throw new IllegalStateException("No language plugins are installed.");
}
}
/**
* Get language.
*/
@Override
@CheckForNull
public Language get(String languageKey) {
org.sonar.api.resources.Language language = languages.get(languageKey);
return language != null ? new Language(language) : null;
}
/**
* Get list of all supported languages.
*/
@Override
public Collection<Language> all() {
return Arrays.stream(languages.all())
.map(Language::new)
.collect(Collectors.toList());
}
@Override
public void stop() {
// nothing to do
}
}
| 2,125 | 26.973684 | 83 | java |
sonarqube | sonarqube-master/sonar-scanner-engine/src/main/java/org/sonar/scanner/repository/language/Language.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.repository.language;
import java.util.Arrays;
import java.util.Collection;
import java.util.Objects;
import javax.annotation.concurrent.Immutable;
@Immutable
public final class Language {
private final String key;
private final String name;
private final boolean publishAllFiles;
private final String[] fileSuffixes;
private final String[] filenamePatterns;
public Language(org.sonar.api.resources.Language language) {
this.key = language.getKey();
this.name = language.getName();
this.publishAllFiles = language.publishAllFiles();
this.fileSuffixes = language.getFileSuffixes();
this.filenamePatterns = language.filenamePatterns();
}
/**
* For example "java".
*/
public String key() {
return key;
}
/**
* For example "Java"
*/
public String name() {
return name;
}
/**
* For example ["jav", "java"].
*/
public Collection<String> fileSuffixes() {
return Arrays.asList(fileSuffixes);
}
public Collection<String> filenamePatterns() {
return Arrays.asList(filenamePatterns);
}
public boolean isPublishAllFiles() {
return publishAllFiles;
}
@Override
public String toString() {
return name;
}
@Override
public boolean equals(Object o) {
if (this == o) {
return true;
}
if (o == null || getClass() != o.getClass()) {
return false;
}
Language language = (Language) o;
return Objects.equals(key, language.key);
}
@Override
public int hashCode() {
return Objects.hash(key);
}
}
| 2,412 | 24.135417 | 75 | java |
sonarqube | sonarqube-master/sonar-scanner-engine/src/main/java/org/sonar/scanner/repository/language/LanguagesRepository.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.repository.language;
import java.util.Collection;
import javax.annotation.CheckForNull;
import javax.annotation.concurrent.Immutable;
/**
* Languages repository
* @since 4.4
*/
@Immutable
public interface LanguagesRepository {
/**
* Get language.
*/
@CheckForNull
Language get(String languageKey);
/**
* Get list of all supported languages.
*/
Collection<Language> all();
}
| 1,273 | 27.311111 | 75 | java |
sonarqube | sonarqube-master/sonar-scanner-engine/src/main/java/org/sonar/scanner/repository/language/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.repository.language;
| 938 | 41.681818 | 75 | java |
sonarqube | sonarqube-master/sonar-scanner-engine/src/main/java/org/sonar/scanner/repository/settings/AbstractSettingsLoader.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.repository.settings;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.util.ArrayList;
import java.util.Collections;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;
import javax.annotation.Nullable;
import org.apache.commons.lang.StringEscapeUtils;
import org.sonar.api.impl.utils.ScannerUtils;
import org.sonar.api.utils.log.Logger;
import org.sonar.api.utils.log.Loggers;
import org.sonar.api.utils.log.Profiler;
import org.sonar.scanner.bootstrap.DefaultScannerWsClient;
import org.sonarqube.ws.Settings;
import org.sonarqube.ws.client.GetRequest;
import org.sonarqube.ws.client.HttpException;
public abstract class AbstractSettingsLoader {
private static final Logger LOG = Loggers.get(AbstractSettingsLoader.class);
private final DefaultScannerWsClient wsClient;
public AbstractSettingsLoader(final DefaultScannerWsClient wsClient) {
this.wsClient = wsClient;
}
Map<String, String> load(@Nullable String componentKey) {
String url = "api/settings/values.protobuf";
Profiler profiler = Profiler.create(LOG);
if (componentKey != null) {
url += "?component=" + ScannerUtils.encodeForUrl(componentKey);
profiler.startInfo(String.format("Load project settings for component key: '%s'", componentKey));
} else {
profiler.startInfo("Load global settings");
}
try (InputStream is = wsClient.call(new GetRequest(url)).contentStream()) {
Settings.ValuesWsResponse values = Settings.ValuesWsResponse.parseFrom(is);
profiler.stopInfo();
return toMap(values.getSettingsList());
} catch (HttpException e) {
if (e.code() == HttpURLConnection.HTTP_NOT_FOUND) {
return Collections.emptyMap();
}
throw e;
} catch (IOException e) {
throw new IllegalStateException("Unable to load settings", e);
}
}
static Map<String, String> toMap(List<Settings.Setting> settingsList) {
Map<String, String> result = new LinkedHashMap<>();
for (Settings.Setting s : settingsList) {
if (!s.getInherited()) {
switch (s.getValueOneOfCase()) {
case VALUE:
result.put(s.getKey(), s.getValue());
break;
case VALUES:
result.put(s.getKey(), s.getValues().getValuesList().stream().map(StringEscapeUtils::escapeCsv).collect(Collectors.joining(",")));
break;
case FIELDVALUES:
convertPropertySetToProps(result, s);
break;
default:
if (!s.getKey().endsWith(".secured")) {
throw new IllegalStateException("Unknown property value for " + s.getKey());
}
}
}
}
return result;
}
private static void convertPropertySetToProps(Map<String, String> result, Settings.Setting s) {
List<String> ids = new ArrayList<>();
int id = 1;
for (Settings.FieldValues.Value v : s.getFieldValues().getFieldValuesList()) {
for (Map.Entry<String, String> entry : v.getValueMap().entrySet()) {
result.put(s.getKey() + "." + id + "." + entry.getKey(), entry.getValue());
}
ids.add(String.valueOf(id));
id++;
}
result.put(s.getKey(), String.join(",", ids));
}
}
| 4,160 | 36.151786 | 142 | java |
sonarqube | sonarqube-master/sonar-scanner-engine/src/main/java/org/sonar/scanner/repository/settings/DefaultGlobalSettingsLoader.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.repository.settings;
import java.util.Map;
import javax.inject.Inject;
import org.sonar.scanner.bootstrap.DefaultScannerWsClient;
public class DefaultGlobalSettingsLoader extends AbstractSettingsLoader implements GlobalSettingsLoader {
@Inject
public DefaultGlobalSettingsLoader(DefaultScannerWsClient wsClient) {
super(wsClient);
}
@Override
public Map<String, String> loadGlobalSettings() {
return load(null);
}
}
| 1,309 | 33.473684 | 105 | java |
sonarqube | sonarqube-master/sonar-scanner-engine/src/main/java/org/sonar/scanner/repository/settings/DefaultProjectSettingsLoader.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.repository.settings;
import java.util.Map;
import org.sonar.scanner.bootstrap.DefaultScannerWsClient;
import org.sonar.scanner.bootstrap.ScannerProperties;
public class DefaultProjectSettingsLoader extends AbstractSettingsLoader implements ProjectSettingsLoader {
private final ScannerProperties scannerProperties;
public DefaultProjectSettingsLoader(final DefaultScannerWsClient wsClient, final ScannerProperties scannerProperties) {
super(wsClient);
this.scannerProperties = scannerProperties;
}
@Override
public Map<String, String> loadProjectSettings() {
return load(scannerProperties.getProjectKey());
}
}
| 1,508 | 37.692308 | 121 | java |
sonarqube | sonarqube-master/sonar-scanner-engine/src/main/java/org/sonar/scanner/repository/settings/GlobalSettingsLoader.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.repository.settings;
import java.util.Map;
public interface GlobalSettingsLoader {
Map<String, String> loadGlobalSettings();
}
| 1,000 | 36.074074 | 75 | java |
sonarqube | sonarqube-master/sonar-scanner-engine/src/main/java/org/sonar/scanner/repository/settings/ProjectSettingsLoader.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.repository.settings;
import java.util.Map;
public interface ProjectSettingsLoader {
Map<String, String> loadProjectSettings();
}
| 1,002 | 36.148148 | 75 | java |
sonarqube | sonarqube-master/sonar-scanner-engine/src/main/java/org/sonar/scanner/repository/settings/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.repository.settings;
import javax.annotation.ParametersAreNonnullByDefault;
| 977 | 39.75 | 75 | java |
sonarqube | sonarqube-master/sonar-scanner-engine/src/main/java/org/sonar/scanner/rule/ActiveRulesLoader.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.rule;
import java.util.List;
import org.sonar.api.batch.rule.LoadedActiveRule;
public interface ActiveRulesLoader {
List<LoadedActiveRule> load(String qualityProfileKey);
}
| 1,046 | 36.392857 | 75 | java |
sonarqube | sonarqube-master/sonar-scanner-engine/src/main/java/org/sonar/scanner/rule/ActiveRulesProvider.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.rule;
import java.util.ArrayList;
import java.util.Collection;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import org.sonar.api.batch.rule.LoadedActiveRule;
import org.sonar.api.batch.rule.internal.ActiveRulesBuilder;
import org.sonar.api.batch.rule.internal.DefaultActiveRules;
import org.sonar.api.batch.rule.internal.NewActiveRule;
import org.sonar.api.rule.RuleKey;
import org.sonar.api.utils.log.Logger;
import org.sonar.api.utils.log.Loggers;
import org.sonar.api.utils.log.Profiler;
import org.springframework.context.annotation.Bean;
/**
* Loads the rules that are activated on the Quality profiles
* used by the current project and builds {@link org.sonar.api.batch.rule.ActiveRules}.
*/
public class ActiveRulesProvider {
private static final Logger LOG = Loggers.get(ActiveRulesProvider.class);
private static final String LOG_MSG = "Load active rules";
@Bean("ActiveRules")
public DefaultActiveRules provide(ActiveRulesLoader loader, QualityProfiles qProfiles) {
Profiler profiler = Profiler.create(LOG).startInfo(LOG_MSG);
DefaultActiveRules activeRules = load(loader, qProfiles);
profiler.stopInfo();
return activeRules;
}
private static DefaultActiveRules load(ActiveRulesLoader loader, QualityProfiles qProfiles) {
Collection<String> qProfileKeys = getKeys(qProfiles);
Set<RuleKey> loadedRulesKey = new HashSet<>();
ActiveRulesBuilder builder = new ActiveRulesBuilder();
for (String qProfileKey : qProfileKeys) {
Collection<LoadedActiveRule> qProfileRules = load(loader, qProfileKey);
for (LoadedActiveRule r : qProfileRules) {
if (!loadedRulesKey.contains(r.getRuleKey())) {
loadedRulesKey.add(r.getRuleKey());
builder.addRule(transform(r, qProfileKey, r.getDeprecatedKeys()));
}
}
}
return builder.build();
}
private static NewActiveRule transform(LoadedActiveRule activeRule, String qProfileKey, Set<RuleKey> deprecatedKeys) {
NewActiveRule.Builder builder = new NewActiveRule.Builder();
builder
.setRuleKey(activeRule.getRuleKey())
.setName(activeRule.getName())
.setSeverity(activeRule.getSeverity())
.setCreatedAt(activeRule.getCreatedAt())
.setUpdatedAt(activeRule.getUpdatedAt())
.setLanguage(activeRule.getLanguage())
.setInternalKey(activeRule.getInternalKey())
.setTemplateRuleKey(activeRule.getTemplateRuleKey())
.setQProfileKey(qProfileKey)
.setDeprecatedKeys(deprecatedKeys);
// load parameters
if (activeRule.getParams() != null) {
for (Map.Entry<String, String> params : activeRule.getParams().entrySet()) {
builder.setParam(params.getKey(), params.getValue());
}
}
return builder.build();
}
private static List<LoadedActiveRule> load(ActiveRulesLoader loader, String qProfileKey) {
return loader.load(qProfileKey);
}
private static Collection<String> getKeys(QualityProfiles qProfiles) {
List<String> keys = new ArrayList<>(qProfiles.findAll().size());
for (QProfile qp : qProfiles.findAll()) {
keys.add(qp.getKey());
}
return keys;
}
}
| 4,055 | 35.540541 | 120 | java |
sonarqube | sonarqube-master/sonar-scanner-engine/src/main/java/org/sonar/scanner/rule/DefaultActiveRulesLoader.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.rule;
import java.io.IOException;
import java.io.InputStream;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;
import org.apache.commons.io.IOUtils;
import org.sonar.api.batch.rule.LoadedActiveRule;
import org.sonar.api.impl.utils.ScannerUtils;
import org.sonar.api.rule.RuleKey;
import org.sonar.api.utils.DateUtils;
import org.sonar.api.utils.MessageException;
import org.sonar.scanner.bootstrap.ScannerWsClient;
import org.sonarqube.ws.Rules;
import org.sonarqube.ws.Rules.Active;
import org.sonarqube.ws.Rules.Active.Param;
import org.sonarqube.ws.Rules.ActiveList;
import org.sonarqube.ws.Rules.Rule;
import org.sonarqube.ws.Rules.SearchResponse;
import org.sonarqube.ws.client.GetRequest;
public class DefaultActiveRulesLoader implements ActiveRulesLoader {
private static final String RULES_SEARCH_URL = "/api/rules/search.protobuf?" +
"f=repo,name,severity,lang,internalKey,templateKey,params,actives,createdAt,updatedAt,deprecatedKeys&activation=true";
private final ScannerWsClient wsClient;
public DefaultActiveRulesLoader(ScannerWsClient wsClient) {
this.wsClient = wsClient;
}
@Override
public List<LoadedActiveRule> load(String qualityProfileKey) {
List<LoadedActiveRule> ruleList = new LinkedList<>();
int page = 1;
int pageSize = 500;
long loaded = 0;
while (true) {
GetRequest getRequest = new GetRequest(getUrl(qualityProfileKey, page, pageSize));
SearchResponse response = loadFromStream(wsClient.call(getRequest).contentStream());
List<LoadedActiveRule> pageRules = readPage(response);
ruleList.addAll(pageRules);
loaded += response.getPs();
if (response.getTotal() <= loaded) {
break;
}
page++;
}
return ruleList;
}
private static String getUrl(String qualityProfileKey, int page, int pageSize) {
StringBuilder builder = new StringBuilder(1024);
builder.append(RULES_SEARCH_URL);
builder.append("&qprofile=").append(ScannerUtils.encodeForUrl(qualityProfileKey));
builder.append("&ps=").append(pageSize);
builder.append("&p=").append(page);
return builder.toString();
}
private static SearchResponse loadFromStream(InputStream is) {
try {
return SearchResponse.parseFrom(is);
} catch (IOException e) {
throw new IllegalStateException("Failed to load quality profiles", e);
} finally {
IOUtils.closeQuietly(is);
}
}
private static List<LoadedActiveRule> readPage(SearchResponse response) {
List<LoadedActiveRule> loadedRules = new LinkedList<>();
List<Rule> rulesList = response.getRulesList();
Map<String, ActiveList> actives = response.getActives().getActivesMap();
for (Rule r : rulesList) {
ActiveList activeList = actives.get(r.getKey());
if (activeList == null) {
throw MessageException.of("Elasticsearch indices have become inconsistent. Consider re-indexing. " +
"Check documentation for more information https://docs.sonarqube.org/latest/setup/troubleshooting");
}
Active active = activeList.getActiveList(0);
LoadedActiveRule loadedRule = new LoadedActiveRule();
loadedRule.setRuleKey(RuleKey.parse(r.getKey()));
loadedRule.setName(r.getName());
loadedRule.setSeverity(active.getSeverity());
loadedRule.setCreatedAt(DateUtils.dateToLong(DateUtils.parseDateTime(active.getCreatedAt())));
loadedRule.setUpdatedAt(DateUtils.dateToLong(DateUtils.parseDateTime(active.getUpdatedAt())));
loadedRule.setLanguage(r.getLang());
loadedRule.setInternalKey(r.getInternalKey());
if (r.hasTemplateKey()) {
RuleKey templateRuleKey = RuleKey.parse(r.getTemplateKey());
loadedRule.setTemplateRuleKey(templateRuleKey.rule());
}
Map<String, String> params = new HashMap<>();
for (Rules.Rule.Param param : r.getParams().getParamsList()) {
params.put(param.getKey(), param.getDefaultValue());
}
// overrides defaultValue if the key is the same
for (Param param : active.getParamsList()) {
params.put(param.getKey(), param.getValue());
}
loadedRule.setParams(params);
loadedRule.setDeprecatedKeys(r.getDeprecatedKeys().getDeprecatedKeyList()
.stream()
.map(RuleKey::parse)
.collect(Collectors.toSet()));
loadedRules.add(loadedRule);
}
return loadedRules;
}
}
| 5,353 | 35.924138 | 122 | java |
sonarqube | sonarqube-master/sonar-scanner-engine/src/main/java/org/sonar/scanner/rule/DefaultRulesLoader.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.rule;
import java.io.IOException;
import java.io.InputStream;
import java.util.List;
import org.apache.commons.io.IOUtils;
import org.sonar.scanner.bootstrap.DefaultScannerWsClient;
import org.sonarqube.ws.Rules.ListResponse;
import org.sonarqube.ws.Rules.ListResponse.Rule;
import org.sonarqube.ws.client.GetRequest;
public class DefaultRulesLoader implements RulesLoader {
private static final String RULES_SEARCH_URL = "/api/rules/list.protobuf";
private final DefaultScannerWsClient wsClient;
public DefaultRulesLoader(DefaultScannerWsClient wsClient) {
this.wsClient = wsClient;
}
@Override
public List<Rule> load() {
GetRequest getRequest = new GetRequest(RULES_SEARCH_URL);
ListResponse list = loadFromStream(wsClient.call(getRequest).contentStream());
return list.getRulesList();
}
private static ListResponse loadFromStream(InputStream is) {
try {
return ListResponse.parseFrom(is);
} catch (IOException e) {
throw new IllegalStateException("Unable to get rules", e);
} finally {
IOUtils.closeQuietly(is);
}
}
}
| 1,965 | 32.896552 | 82 | java |
sonarqube | sonarqube-master/sonar-scanner-engine/src/main/java/org/sonar/scanner/rule/QProfile.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.rule;
import java.util.Date;
import javax.annotation.concurrent.Immutable;
@Immutable
public class QProfile {
private final String key;
private final String name;
private final String language;
private final Date rulesUpdatedAt;
public QProfile(String key, String name, String language, Date rulesUpdatedAt) {
this.key = key;
this.name = name;
this.language = language;
this.rulesUpdatedAt = rulesUpdatedAt;
}
public String getKey() {
return key;
}
public String getName() {
return name;
}
public String getLanguage() {
return language;
}
public Date getRulesUpdatedAt() {
return rulesUpdatedAt;
}
@Override
public boolean equals(Object o) {
if (this == o) {
return true;
}
if (o == null || getClass() != o.getClass()) {
return false;
}
QProfile qProfile = (QProfile) o;
return key.equals(qProfile.key);
}
@Override
public int hashCode() {
return key.hashCode();
}
@Override
public String toString() {
return new StringBuilder()
.append(this.getClass().getSimpleName())
.append("{")
.append("key=").append(key)
.append("name=").append(name)
.append("language=").append(language)
.append("rulesUpdatedAt=").append(rulesUpdatedAt)
.append("}")
.toString();
}
public static class Builder {
private String key;
private String name;
private String language;
private Date rulesUpdatedAt;
public String getKey() {
return key;
}
public Builder setKey(String key) {
this.key = key;
return this;
}
public String getName() {
return name;
}
public Builder setName(String name) {
this.name = name;
return this;
}
public String getLanguage() {
return language;
}
public Builder setLanguage(String language) {
this.language = language;
return this;
}
public Date getRulesUpdatedAt() {
return rulesUpdatedAt;
}
public Builder setRulesUpdatedAt(Date d) {
this.rulesUpdatedAt = d;
return this;
}
public QProfile build() {
return new QProfile(key, name, language, rulesUpdatedAt);
}
}
}
| 3,098 | 22.300752 | 82 | java |
sonarqube | sonarqube-master/sonar-scanner-engine/src/main/java/org/sonar/scanner/rule/QProfileVerifier.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.rule;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.sonar.scanner.scan.filesystem.InputComponentStore;
public class QProfileVerifier {
private static final Logger LOG = LoggerFactory.getLogger(QProfileVerifier.class);
private final InputComponentStore store;
private final QualityProfiles profiles;
public QProfileVerifier(InputComponentStore store, QualityProfiles profiles) {
this.store = store;
this.profiles = profiles;
}
public void execute() {
execute(LOG);
}
void execute(Logger logger) {
for (String lang : store.languages()) {
QProfile profile = profiles.findByLanguage(lang);
if (profile == null) {
logger.warn("No Quality profile found for language {}", lang);
} else {
logger.info("Quality profile for {}: {}", lang, profile.getName());
}
}
}
}
| 1,733 | 31.716981 | 84 | java |
sonarqube | sonarqube-master/sonar-scanner-engine/src/main/java/org/sonar/scanner/rule/QualityProfiles.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.rule;
import java.util.Collection;
import java.util.Collections;
import java.util.HashMap;
import java.util.Map;
import javax.annotation.CheckForNull;
import javax.annotation.concurrent.Immutable;
import org.sonar.api.utils.DateUtils;
import org.sonarqube.ws.Qualityprofiles.SearchWsResponse.QualityProfile;
/**
* Lists the Quality profiles enabled on the current project.
*/
@Immutable
public class QualityProfiles {
private final Map<String, QProfile> byLanguage;
public QualityProfiles(Collection<QualityProfile> profiles) {
Map<String, QProfile> map = new HashMap<>(profiles.size());
for (QualityProfile qProfile : profiles) {
map.put(qProfile.getLanguage(),
new QProfile.Builder()
.setKey(qProfile.getKey())
.setName(qProfile.getName())
.setLanguage(qProfile.getLanguage())
.setRulesUpdatedAt(DateUtils.parseDateTime(qProfile.getRulesUpdatedAt())).build());
}
byLanguage = Collections.unmodifiableMap(map);
}
public Collection<QProfile> findAll() {
return byLanguage.values();
}
@CheckForNull
public QProfile findByLanguage(String language) {
return byLanguage.get(language);
}
}
| 2,057 | 32.193548 | 93 | java |
sonarqube | sonarqube-master/sonar-scanner-engine/src/main/java/org/sonar/scanner/rule/RulesLoader.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.rule;
import java.util.List;
import org.sonarqube.ws.Rules.ListResponse.Rule;
public interface RulesLoader {
List<Rule> load();
}
| 1,003 | 34.857143 | 75 | java |
sonarqube | sonarqube-master/sonar-scanner-engine/src/main/java/org/sonar/scanner/rule/RulesProvider.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.rule;
import java.util.List;
import org.sonar.api.batch.rule.Rules;
import org.sonar.api.batch.rule.internal.NewRule;
import org.sonar.api.batch.rule.internal.RulesBuilder;
import org.sonar.api.rule.RuleKey;
import org.sonar.api.utils.log.Logger;
import org.sonar.api.utils.log.Loggers;
import org.sonar.api.utils.log.Profiler;
import org.sonarqube.ws.Rules.ListResponse.Rule;
import org.springframework.context.annotation.Bean;
public class RulesProvider {
private static final Logger LOG = Loggers.get(RulesProvider.class);
private static final String LOG_MSG = "Load server rules";
@Bean("Rules")
public Rules provide(RulesLoader ref) {
Profiler profiler = Profiler.create(LOG).startInfo(LOG_MSG);
List<Rule> loadedRules = ref.load();
RulesBuilder builder = new RulesBuilder();
for (Rule r : loadedRules) {
NewRule newRule = builder.add(RuleKey.of(r.getRepository(), r.getKey()));
newRule.setName(r.getName());
newRule.setInternalKey(r.getInternalKey());
}
profiler.stopInfo();
return builder.build();
}
}
| 1,939 | 35.603774 | 79 | java |
sonarqube | sonarqube-master/sonar-scanner-engine/src/main/java/org/sonar/scanner/rule/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.rule;
import javax.annotation.ParametersAreNonnullByDefault;
| 962 | 39.125 | 75 | java |
sonarqube | sonarqube-master/sonar-scanner-engine/src/main/java/org/sonar/scanner/scan/DefaultInputModuleHierarchy.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.scan;
import java.nio.file.Path;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import javax.annotation.CheckForNull;
import javax.annotation.concurrent.Immutable;
import org.sonar.api.batch.fs.internal.AbstractProjectOrModule;
import org.sonar.api.batch.fs.internal.DefaultInputModule;
import org.sonar.api.scan.filesystem.PathResolver;
import org.sonar.scanner.fs.InputModuleHierarchy;
@Immutable
public class DefaultInputModuleHierarchy implements InputModuleHierarchy {
private final DefaultInputModule root;
private final Map<DefaultInputModule, DefaultInputModule> parents;
private final Map<DefaultInputModule, List<DefaultInputModule>> children;
public DefaultInputModuleHierarchy(DefaultInputModule root) {
this.children = Collections.emptyMap();
this.parents = Collections.emptyMap();
this.root = root;
}
/**
* Map of child->parent. Neither the Keys or values can be null.
*/
public DefaultInputModuleHierarchy(DefaultInputModule root, Map<DefaultInputModule, DefaultInputModule> parents) {
Map<DefaultInputModule, List<DefaultInputModule>> childrenBuilder = new HashMap<>();
for (Map.Entry<DefaultInputModule, DefaultInputModule> e : parents.entrySet()) {
childrenBuilder.computeIfAbsent(e.getValue(), x -> new ArrayList<>()).add(e.getKey());
}
this.children = Collections.unmodifiableMap(childrenBuilder);
this.parents = Map.copyOf(parents);
this.root = root;
}
@Override
public DefaultInputModule root() {
return root;
}
@Override
public Collection<DefaultInputModule> children(DefaultInputModule component) {
return children.getOrDefault(component, Collections.emptyList());
}
@Override
public DefaultInputModule parent(DefaultInputModule component) {
return parents.get(component);
}
@Override
public boolean isRoot(DefaultInputModule module) {
return root.equals(module);
}
@Override
@CheckForNull
public String relativePath(DefaultInputModule module) {
AbstractProjectOrModule parent = parent(module);
if (parent == null) {
return "";
}
Path parentBaseDir = parent.getBaseDir();
Path moduleBaseDir = module.getBaseDir();
return PathResolver.relativize(parentBaseDir, moduleBaseDir).orElse(null);
}
public String relativePathToRoot(DefaultInputModule module) {
Path rootBaseDir = root.getBaseDir();
Path moduleBaseDir = module.getBaseDir();
return PathResolver.relativize(rootBaseDir, moduleBaseDir).orElse(null);
}
}
| 3,486 | 32.854369 | 116 | java |
sonarqube | sonarqube-master/sonar-scanner-engine/src/main/java/org/sonar/scanner/scan/DeprecatedPropertiesWarningGenerator.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.scan;
import com.google.common.annotations.VisibleForTesting;
import java.util.Optional;
import org.apache.commons.lang.StringUtils;
import org.sonar.api.CoreProperties;
import org.sonar.api.config.Configuration;
import org.sonar.api.notifications.AnalysisWarnings;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.sonar.batch.bootstrapper.EnvironmentInformation;
import org.sonar.scanner.bootstrap.ScannerWsClientProvider;
public class DeprecatedPropertiesWarningGenerator {
private static final Logger LOG = LoggerFactory.getLogger(DeprecatedPropertiesWarningGenerator.class);
@VisibleForTesting
static final String PASSWORD_WARN_MESSAGE = String.format("The properties '%s' and '%s' are deprecated and will be removed in the " +
"future. Please pass a token with the '%s' property instead.", CoreProperties.LOGIN, CoreProperties.PASSWORD,
ScannerWsClientProvider.TOKEN_PROPERTY);
@VisibleForTesting
static final String LOGIN_WARN_MESSAGE = String.format("The property '%s' is deprecated and will be removed in the future. " +
"Please use the '%s' property instead when passing a token.", CoreProperties.LOGIN, ScannerWsClientProvider.TOKEN_PROPERTY);
@VisibleForTesting
static final String SCANNER_DOTNET_WARN_MESSAGE = String.format(" The '%s' property is available from SonarScanner " +
"for .NET version 5.13.", ScannerWsClientProvider.TOKEN_PROPERTY);
private static final String ENV_KEY_SCANNER_DOTNET = "ScannerMSBuild";
private final Configuration configuration;
private final AnalysisWarnings analysisWarnings;
private final EnvironmentInformation environmentInformation;
public DeprecatedPropertiesWarningGenerator(Configuration configuration, AnalysisWarnings analysisWarnings,
EnvironmentInformation environmentInformation) {
this.configuration = configuration;
this.analysisWarnings = analysisWarnings;
this.environmentInformation = environmentInformation;
}
public void execute() {
Optional<String> login = configuration.get(CoreProperties.LOGIN);
Optional<String> password = configuration.get(CoreProperties.PASSWORD);
String warningMessage = null;
if (password.isPresent()) {
warningMessage = PASSWORD_WARN_MESSAGE;
} else if (login.isPresent()) {
warningMessage = LOGIN_WARN_MESSAGE;
}
if (warningMessage != null) {
if (isScannerDotNet()) {
warningMessage += SCANNER_DOTNET_WARN_MESSAGE;
}
LOG.warn(warningMessage);
analysisWarnings.addUnique(warningMessage);
}
}
private boolean isScannerDotNet() {
return StringUtils.containsIgnoreCase(environmentInformation.getKey(), ENV_KEY_SCANNER_DOTNET);
}
}
| 3,606 | 42.457831 | 135 | java |
sonarqube | sonarqube-master/sonar-scanner-engine/src/main/java/org/sonar/scanner/scan/DirectoryLock.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.scan;
import java.io.IOException;
import java.io.RandomAccessFile;
import java.nio.channels.FileChannel;
import java.nio.channels.FileLock;
import java.nio.file.Path;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
public class DirectoryLock {
private static final Logger LOGGER = LoggerFactory.getLogger(DirectoryLock.class);
public static final String LOCK_FILE_NAME = ".sonar_lock";
private final Path lockFilePath;
private RandomAccessFile lockRandomAccessFile;
private FileChannel lockChannel;
private FileLock lockFile;
public DirectoryLock(Path directory) {
this.lockFilePath = directory.resolve(LOCK_FILE_NAME).toAbsolutePath();
}
public boolean tryLock() {
try {
lockRandomAccessFile = new RandomAccessFile(lockFilePath.toFile(), "rw");
lockChannel = lockRandomAccessFile.getChannel();
lockFile = lockChannel.tryLock(0, 1024, false);
return lockFile != null;
} catch (IOException e) {
throw new IllegalStateException("Failed to create lock in " + lockFilePath.toString(), e);
}
}
public void unlock() {
if (lockFile != null) {
try {
lockFile.release();
lockFile = null;
} catch (IOException e) {
LOGGER.error("Error releasing lock", e);
}
}
if (lockChannel != null) {
try {
lockChannel.close();
lockChannel = null;
} catch (IOException e) {
LOGGER.error("Error closing file channel", e);
}
}
if (lockRandomAccessFile != null) {
try {
lockRandomAccessFile.close();
lockRandomAccessFile = null;
} catch (IOException e) {
LOGGER.error("Error closing file", e);
}
}
}
}
| 2,581 | 30.108434 | 96 | java |
sonarqube | sonarqube-master/sonar-scanner-engine/src/main/java/org/sonar/scanner/scan/InputModuleHierarchyProvider.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.scan;
import java.util.HashMap;
import java.util.Locale;
import java.util.Map;
import org.sonar.api.batch.bootstrap.ProjectDefinition;
import org.sonar.api.batch.fs.internal.DefaultInputModule;
import org.sonar.api.batch.fs.internal.DefaultInputProject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.sonar.scanner.scan.filesystem.ScannerComponentIdGenerator;
import org.springframework.context.annotation.Bean;
public class InputModuleHierarchyProvider {
private static final Logger LOG = LoggerFactory.getLogger(InputModuleHierarchyProvider.class);
@Bean("DefaultInputModuleHierarchy")
public DefaultInputModuleHierarchy provide(ScannerComponentIdGenerator scannerComponentIdGenerator, WorkDirectoriesInitializer workDirectoriesInit, DefaultInputProject project) {
LOG.debug("Creating module hierarchy");
DefaultInputModule root = createModule(project.definition(), project.scannerId());
Map<DefaultInputModule, DefaultInputModule> parents = createChildren(root, scannerComponentIdGenerator, new HashMap<>());
DefaultInputModuleHierarchy inputModuleHierarchy;
if (parents.isEmpty()) {
inputModuleHierarchy = new DefaultInputModuleHierarchy(root);
} else {
inputModuleHierarchy = new DefaultInputModuleHierarchy(root, parents);
}
workDirectoriesInit.execute(inputModuleHierarchy);
return inputModuleHierarchy;
}
private static Map<DefaultInputModule, DefaultInputModule> createChildren(DefaultInputModule parent, ScannerComponentIdGenerator scannerComponentIdGenerator,
Map<DefaultInputModule, DefaultInputModule> parents) {
for (ProjectDefinition def : parent.definition().getSubProjects()) {
DefaultInputModule child = createModule(def, scannerComponentIdGenerator.getAsInt());
parents.put(child, parent);
createChildren(child, scannerComponentIdGenerator, parents);
}
return parents;
}
private static DefaultInputModule createModule(ProjectDefinition def, int scannerComponentId) {
LOG.debug(" Init module '{}'", def.getName());
DefaultInputModule module = new DefaultInputModule(def, scannerComponentId);
LOG.debug(" Base dir: {}", module.getBaseDir().toAbsolutePath().toString());
LOG.debug(" Working dir: {}", module.getWorkDir().toAbsolutePath().toString());
LOG.debug(" Module global encoding: {}, default locale: {}", module.getEncoding().displayName(), Locale.getDefault());
return module;
}
}
| 3,334 | 45.319444 | 180 | java |
sonarqube | sonarqube-master/sonar-scanner-engine/src/main/java/org/sonar/scanner/scan/InputProjectProvider.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.scan;
import java.util.Locale;
import org.sonar.api.batch.bootstrap.ProjectReactor;
import org.sonar.api.batch.fs.internal.DefaultInputProject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.sonar.scanner.scan.filesystem.ScannerComponentIdGenerator;
import org.springframework.context.annotation.Bean;
public class InputProjectProvider {
private static final Logger LOG = LoggerFactory.getLogger(InputProjectProvider.class);
@Bean("DefaultInputProject")
public DefaultInputProject provide(ProjectBuildersExecutor projectBuildersExecutor, ProjectReactorValidator validator,
ProjectReactor projectReactor, ScannerComponentIdGenerator scannerComponentIdGenerator, WorkDirectoriesInitializer workDirectoriesInit) {
// 1 Apply project builders
projectBuildersExecutor.execute(projectReactor);
// 2 Validate final reactor
validator.validate(projectReactor);
// 3 Create project
DefaultInputProject project = new DefaultInputProject(projectReactor.getRoot(), scannerComponentIdGenerator.getAsInt());
workDirectoriesInit.execute(project);
LOG.info("Project key: {}", project.key());
LOG.info("Base dir: {}", project.getBaseDir().toAbsolutePath().toString());
LOG.info("Working dir: {}", project.getWorkDir().toAbsolutePath().toString());
LOG.debug("Project global encoding: {}, default locale: {}", project.getEncoding().displayName(), Locale.getDefault());
return project;
}
}
| 2,326 | 42.90566 | 141 | java |
sonarqube | sonarqube-master/sonar-scanner-engine/src/main/java/org/sonar/scanner/scan/ModuleConfiguration.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.scan;
import java.util.Map;
import org.sonar.api.config.PropertyDefinitions;
import org.sonar.api.config.internal.Encryption;
import org.sonar.scanner.config.DefaultConfiguration;
public class ModuleConfiguration extends DefaultConfiguration {
public ModuleConfiguration(PropertyDefinitions propertyDefinitions, Encryption encryption, Map<String, String> props) {
super(propertyDefinitions, encryption, props);
}
}
| 1,294 | 39.46875 | 121 | java |
sonarqube | sonarqube-master/sonar-scanner-engine/src/main/java/org/sonar/scanner/scan/ModuleConfigurationProvider.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.scan;
import java.util.ArrayList;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import org.sonar.api.batch.bootstrap.ProjectDefinition;
import org.sonar.api.batch.fs.internal.DefaultInputModule;
import org.sonar.scanner.bootstrap.GlobalConfiguration;
import org.sonar.scanner.bootstrap.GlobalServerSettings;
import org.springframework.context.annotation.Bean;
public class ModuleConfigurationProvider {
private final SonarGlobalPropertiesFilter sonarGlobalPropertiesFilter;
public ModuleConfigurationProvider(SonarGlobalPropertiesFilter sonarGlobalPropertiesFilter) {
this.sonarGlobalPropertiesFilter = sonarGlobalPropertiesFilter;
}
@Bean("ModuleConfiguration")
public ModuleConfiguration provide(GlobalConfiguration globalConfig, DefaultInputModule module, GlobalServerSettings globalServerSettings,
ProjectServerSettings projectServerSettings) {
Map<String, String> settings = new LinkedHashMap<>();
settings.putAll(globalServerSettings.properties());
settings.putAll(projectServerSettings.properties());
addScannerSideProperties(settings, module.definition());
settings = sonarGlobalPropertiesFilter.enforceOnlyServerSideSonarGlobalPropertiesAreUsed(settings, globalServerSettings.properties());
return new ModuleConfiguration(globalConfig.getDefinitions(), globalConfig.getEncryption(), settings);
}
private static void addScannerSideProperties(Map<String, String> settings, ProjectDefinition project) {
List<ProjectDefinition> orderedProjects = getTopDownParentProjects(project);
for (ProjectDefinition p : orderedProjects) {
settings.putAll(p.properties());
}
}
/**
* From root to given project
*/
static List<ProjectDefinition> getTopDownParentProjects(ProjectDefinition project) {
List<ProjectDefinition> result = new ArrayList<>();
ProjectDefinition p = project;
while (p != null) {
result.add(0, p);
p = p.getParent();
}
return result;
}
}
| 2,871 | 37.810811 | 140 | java |
sonarqube | sonarqube-master/sonar-scanner-engine/src/main/java/org/sonar/scanner/scan/ModuleIndexer.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.scan;
import org.sonar.api.Startable;
import org.sonar.api.batch.fs.internal.DefaultInputModule;
import org.sonar.scanner.fs.InputModuleHierarchy;
import org.sonar.scanner.scan.filesystem.InputComponentStore;
/**
* Indexes all modules into {@link DefaultComponentTree}, {@link DefaultInputModuleHierarchy) and {@link InputComponentStore}, using the
* project definitions provided by the {@link ImmutableProjectReactor}.
*/
public class ModuleIndexer implements Startable {
private final InputModuleHierarchy moduleHierarchy;
private final InputComponentStore componentStore;
public ModuleIndexer(InputComponentStore componentStore, InputModuleHierarchy moduleHierarchy) {
this.componentStore = componentStore;
this.moduleHierarchy = moduleHierarchy;
}
@Override
public void start() {
DefaultInputModule root = moduleHierarchy.root();
componentStore.put(root);
indexChildren(root);
}
private void indexChildren(DefaultInputModule parent) {
for (DefaultInputModule module : moduleHierarchy.children(parent)) {
componentStore.put(module);
indexChildren(module);
}
}
@Override
public void stop() {
// nothing to do
}
}
| 2,061 | 33.949153 | 136 | java |
sonarqube | sonarqube-master/sonar-scanner-engine/src/main/java/org/sonar/scanner/scan/MutableModuleSettings.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.scan;
import java.util.HashMap;
import java.util.Map;
import java.util.Optional;
import javax.annotation.Priority;
import org.sonar.api.config.internal.Settings;
import static java.util.Objects.requireNonNull;
/**
* @deprecated since 6.5 {@link ModuleConfiguration} used to be mutable, so keep a mutable copy for backward compatibility.
*/
@Deprecated
@Priority(1)
public class MutableModuleSettings extends Settings {
private final Map<String, String> properties = new HashMap<>();
public MutableModuleSettings(ModuleConfiguration config) {
super(config.getDefinitions(), config.getEncryption());
addProperties(config.getProperties());
}
@Override
protected Optional<String> get(String key) {
return Optional.ofNullable(properties.get(key));
}
@Override
protected void set(String key, String value) {
properties.put(
requireNonNull(key, "key can't be null"),
requireNonNull(value, "value can't be null").trim());
}
@Override
protected void remove(String key) {
properties.remove(key);
}
@Override
public Map<String, String> getProperties() {
return properties;
}
}
| 2,012 | 29.5 | 123 | java |
sonarqube | sonarqube-master/sonar-scanner-engine/src/main/java/org/sonar/scanner/scan/MutableProjectReactorProvider.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.scan;
import org.sonar.api.batch.bootstrap.ProjectReactor;
import org.springframework.context.annotation.Bean;
public class MutableProjectReactorProvider {
@Bean("ProjectReactor")
public ProjectReactor provide(ProjectReactorBuilder builder) {
return builder.execute();
}
}
| 1,154 | 36.258065 | 75 | java |
sonarqube | sonarqube-master/sonar-scanner-engine/src/main/java/org/sonar/scanner/scan/MutableProjectSettings.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.scan;
import java.util.HashMap;
import java.util.Map;
import java.util.Optional;
import org.sonar.api.config.internal.Settings;
import org.sonar.scanner.bootstrap.GlobalConfiguration;
import javax.annotation.Priority;
import static java.util.Objects.requireNonNull;
/**
* @deprecated since 6.5 {@link ProjectConfiguration} used to be mutable, so keep a mutable copy for backward compatibility.
*/
@Deprecated
@Priority(2)
public class MutableProjectSettings extends Settings {
private final Map<String, String> properties = new HashMap<>();
public MutableProjectSettings(GlobalConfiguration globalConfig) {
super(globalConfig.getDefinitions(), globalConfig.getEncryption());
addProperties(globalConfig.getProperties());
}
public void complete(ProjectConfiguration projectConfig) {
addProperties(projectConfig.getProperties());
}
@Override
protected Optional<String> get(String key) {
return Optional.ofNullable(properties.get(key));
}
@Override
protected void set(String key, String value) {
properties.put(
requireNonNull(key, "key can't be null"),
requireNonNull(value, "value can't be null").trim());
}
@Override
protected void remove(String key) {
properties.remove(key);
}
@Override
public Map<String, String> getProperties() {
return properties;
}
}
| 2,212 | 29.736111 | 124 | java |
sonarqube | sonarqube-master/sonar-scanner-engine/src/main/java/org/sonar/scanner/scan/ProjectBuildersExecutor.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.scan;
import java.lang.reflect.Method;
import org.sonar.api.batch.bootstrap.ProjectBuilder;
import org.sonar.api.batch.bootstrap.ProjectReactor;
import org.sonar.api.batch.bootstrap.internal.ProjectBuilderContext;
import org.sonar.api.utils.MessageException;
import org.sonar.api.utils.log.Logger;
import org.sonar.api.utils.log.Loggers;
import org.sonar.api.utils.log.Profiler;
import org.sonar.scanner.bootstrap.GlobalConfiguration;
import org.springframework.beans.factory.annotation.Autowired;
public class ProjectBuildersExecutor {
private static final Logger LOG = Loggers.get(ProjectBuildersExecutor.class);
private final GlobalConfiguration globalConfig;
private final ProjectBuilder[] projectBuilders;
@Autowired(required = false)
public ProjectBuildersExecutor(GlobalConfiguration globalConfig, ProjectBuilder... projectBuilders) {
this.globalConfig = globalConfig;
this.projectBuilders = projectBuilders;
}
@Autowired(required = false)
public ProjectBuildersExecutor(GlobalConfiguration globalConfig) {
this(globalConfig, new ProjectBuilder[0]);
}
public void execute(ProjectReactor reactor) {
if (projectBuilders.length > 0) {
Profiler profiler = Profiler.create(LOG).startInfo("Execute project builders");
ProjectBuilderContext context = new ProjectBuilderContext(reactor, globalConfig);
for (ProjectBuilder projectBuilder : projectBuilders) {
try {
LOG.debug("Execute project builder: {}", projectBuilder.getClass().getName());
projectBuilder.build(context);
} catch (Exception e) {
throw MessageException.of("Failed to execute project builder: " + getDescription(projectBuilder), e);
}
}
profiler.stopInfo();
}
}
private static String getDescription(ProjectBuilder projectBuilder) {
Method toString;
try {
toString = projectBuilder.getClass().getMethod("toString");
} catch (Exception e) {
// should never happen as every class has toString
return projectBuilder.toString();
}
if (toString.getDeclaringClass() != Object.class) {
return projectBuilder.toString();
} else {
return projectBuilder.getClass().getName();
}
}
}
| 3,103 | 36.39759 | 111 | java |
sonarqube | sonarqube-master/sonar-scanner-engine/src/main/java/org/sonar/scanner/scan/ProjectConfiguration.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.scan;
import java.util.Map;
import org.sonar.api.config.PropertyDefinitions;
import org.sonar.api.config.internal.Encryption;
import org.sonar.scanner.config.DefaultConfiguration;
public class ProjectConfiguration extends DefaultConfiguration {
public ProjectConfiguration(PropertyDefinitions propertyDefinitions, Encryption encryption, Map<String, String> props) {
super(propertyDefinitions, encryption, props);
}
}
| 1,296 | 39.53125 | 122 | java |
sonarqube | sonarqube-master/sonar-scanner-engine/src/main/java/org/sonar/scanner/scan/ProjectConfigurationProvider.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.scan;
import java.util.LinkedHashMap;
import java.util.Map;
import org.sonar.api.batch.fs.internal.DefaultInputProject;
import org.sonar.scanner.bootstrap.GlobalConfiguration;
import org.sonar.scanner.bootstrap.GlobalServerSettings;
import org.springframework.context.annotation.Bean;
public class ProjectConfigurationProvider {
private final SonarGlobalPropertiesFilter sonarGlobalPropertiesFilter;
public ProjectConfigurationProvider(SonarGlobalPropertiesFilter sonarGlobalPropertiesFilter) {
this.sonarGlobalPropertiesFilter = sonarGlobalPropertiesFilter;
}
@Bean("ProjectConfiguration")
public ProjectConfiguration provide(DefaultInputProject project, GlobalConfiguration globalConfig, GlobalServerSettings globalServerSettings,
ProjectServerSettings projectServerSettings, MutableProjectSettings projectSettings) {
Map<String, String> settings = new LinkedHashMap<>();
settings.putAll(globalServerSettings.properties());
settings.putAll(projectServerSettings.properties());
settings.putAll(project.properties());
settings = sonarGlobalPropertiesFilter.enforceOnlyServerSideSonarGlobalPropertiesAreUsed(settings, globalServerSettings.properties());
ProjectConfiguration projectConfig = new ProjectConfiguration(globalConfig.getDefinitions(), globalConfig.getEncryption(), settings);
projectSettings.complete(projectConfig);
return projectConfig;
}
}
| 2,285 | 40.563636 | 143 | java |
sonarqube | sonarqube-master/sonar-scanner-engine/src/main/java/org/sonar/scanner/scan/ProjectLock.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.scan;
import java.io.IOException;
import java.nio.channels.OverlappingFileLockException;
import java.nio.file.Files;
import java.nio.file.Path;
import org.sonar.api.Startable;
import org.sonar.api.batch.fs.internal.AbstractProjectOrModule;
public class ProjectLock implements Startable {
private final DirectoryLock lock;
public ProjectLock(AbstractProjectOrModule project) {
Path directory = project.getWorkDir();
try {
if (!directory.toFile().exists()) {
Files.createDirectories(directory);
}
} catch (IOException e) {
throw new IllegalStateException("Failed to create work directory", e);
}
this.lock = new DirectoryLock(directory.toAbsolutePath());
}
public void tryLock() {
try {
if (!lock.tryLock()) {
failAlreadyInProgress(null);
}
} catch (OverlappingFileLockException e) {
failAlreadyInProgress(e);
}
}
private static void failAlreadyInProgress(Exception e) {
throw new IllegalStateException("Another SonarQube analysis is already in progress for this project", e);
}
@Override
public void stop() {
lock.unlock();
}
@Override
public void start() {
// nothing to do
}
}
| 2,076 | 29.544118 | 109 | java |
sonarqube | sonarqube-master/sonar-scanner-engine/src/main/java/org/sonar/scanner/scan/ProjectReactorBuilder.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.scan;
import com.google.common.annotations.VisibleForTesting;
import java.io.File;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.text.MessageFormat;
import java.util.Arrays;
import java.util.Collection;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Objects;
import java.util.stream.Stream;
import javax.annotation.Nullable;
import org.apache.commons.lang.ArrayUtils;
import org.apache.commons.lang.StringUtils;
import org.sonar.api.CoreProperties;
import org.sonar.api.batch.bootstrap.ProjectDefinition;
import org.sonar.api.batch.bootstrap.ProjectReactor;
import org.sonar.api.impl.utils.ScannerUtils;
import org.sonar.api.notifications.AnalysisWarnings;
import org.sonar.api.utils.MessageException;
import org.sonar.api.utils.log.Logger;
import org.sonar.api.utils.log.Loggers;
import org.sonar.api.utils.log.Profiler;
import org.sonar.core.config.IssueExclusionProperties;
import org.sonar.scanner.bootstrap.ScannerProperties;
import org.sonar.scanner.issue.ignore.pattern.IssueExclusionPatternInitializer;
import org.sonar.scanner.issue.ignore.pattern.IssueInclusionPatternInitializer;
import static java.util.Arrays.asList;
import static java.util.stream.Collectors.toList;
import static org.sonar.api.config.internal.MultivalueProperty.parseAsCsv;
/**
* Class that creates a project definition based on a set of properties.
*/
public class ProjectReactorBuilder {
private static final String INVALID_VALUE_OF_X_FOR_Y = "Invalid value of {0} for {1}";
private static final Logger LOG = Loggers.get(ProjectReactorBuilder.class);
@VisibleForTesting
static final String WILDCARDS_NOT_SUPPORTED = "Wildcards ** and * are not supported in \"sonar.sources\" and \"sonar.tests\" properties. " +
"\"sonar.sources\" and \"sonar.tests\" properties support only comma separated list of directories. " +
"Use \"sonar.exclusions/sonar.inclusions\" and \"sonar.test.exclusions/sonar.test.inclusions\" " +
"to further filter files in \"sonar.sources\" and \"sonar.tests\" respectively. Please refer to SonarQube documentation for more details.";
/**
* @since 4.1 but not yet exposed in {@link CoreProperties}
*/
private static final String MODULE_KEY_PROPERTY = "sonar.moduleKey";
protected static final String PROPERTY_PROJECT_BASEDIR = "sonar.projectBaseDir";
private static final String PROPERTY_MODULES = "sonar.modules";
/**
* New properties, to be consistent with Sonar naming conventions
*
* @since 1.5
*/
private static final String PROPERTY_SOURCES = ProjectDefinition.SOURCES_PROPERTY;
private static final String PROPERTY_TESTS = ProjectDefinition.TESTS_PROPERTY;
/**
* Array of all mandatory properties required for a project without child.
*/
private static final String[] MANDATORY_PROPERTIES_FOR_SIMPLE_PROJECT = {
PROPERTY_PROJECT_BASEDIR, CoreProperties.PROJECT_KEY_PROPERTY
};
/**
* Array of all mandatory properties required for a project with children.
*/
private static final String[] MANDATORY_PROPERTIES_FOR_MULTIMODULE_PROJECT = {PROPERTY_PROJECT_BASEDIR, CoreProperties.PROJECT_KEY_PROPERTY};
/**
* Array of all mandatory properties required for a child project before its properties get merged with its parent ones.
*/
private static final String[] MANDATORY_PROPERTIES_FOR_CHILD = {MODULE_KEY_PROPERTY};
private static final Collection<String> UNSUPPORTED_PROPS_FOR_MODULES = asList(IssueExclusionPatternInitializer.CONFIG_KEY, IssueInclusionPatternInitializer.CONFIG_KEY,
IssueExclusionProperties.PATTERNS_BLOCK_KEY, IssueExclusionProperties.PATTERNS_ALLFILE_KEY);
/**
* Properties that must not be passed from the parent project to its children.
*/
private static final List<String> NON_HERITED_PROPERTIES_FOR_CHILD = Stream.concat(Stream.of(PROPERTY_PROJECT_BASEDIR, CoreProperties.WORKING_DIRECTORY, PROPERTY_MODULES,
CoreProperties.PROJECT_DESCRIPTION_PROPERTY), UNSUPPORTED_PROPS_FOR_MODULES.stream()).collect(toList());
private final ScannerProperties scannerProps;
private final AnalysisWarnings analysisWarnings;
private File rootProjectWorkDir;
private boolean warnExclusionsAlreadyLogged;
public ProjectReactorBuilder(ScannerProperties props, AnalysisWarnings analysisWarnings) {
this.scannerProps = props;
this.analysisWarnings = analysisWarnings;
}
public ProjectReactor execute() {
Profiler profiler = Profiler.create(LOG).startInfo("Process project properties");
Map<String, Map<String, String>> propertiesByModuleIdPath = new HashMap<>();
extractPropertiesByModule(propertiesByModuleIdPath, "", "", new HashMap<>(scannerProps.properties()));
ProjectDefinition rootProject = createModuleDefinition(propertiesByModuleIdPath.get(""), null);
rootProjectWorkDir = rootProject.getWorkDir();
defineChildren(rootProject, propertiesByModuleIdPath, "");
cleanAndCheckProjectDefinitions(rootProject);
profiler.stopInfo();
return new ProjectReactor(rootProject);
}
private static void extractPropertiesByModule(Map<String, Map<String, String>> propertiesByModuleIdPath, String currentModuleId, String currentModuleIdPath,
Map<String, String> parentProperties) {
if (propertiesByModuleIdPath.containsKey(currentModuleIdPath)) {
throw MessageException.of(String.format("Two modules have the same id: '%s'. Each module must have a unique id.", currentModuleId));
}
Map<String, String> currentModuleProperties = new HashMap<>();
String prefix = !currentModuleId.isEmpty() ? (currentModuleId + ".") : "";
int prefixLength = prefix.length();
// By default all properties starting with module prefix belong to current module
Iterator<Entry<String, String>> it = parentProperties.entrySet().iterator();
while (it.hasNext()) {
Map.Entry<String, String> e = it.next();
String key = e.getKey();
if (key.startsWith(prefix)) {
currentModuleProperties.put(key.substring(prefixLength), e.getValue());
it.remove();
}
}
String[] moduleIds = getListFromProperty(currentModuleProperties, PROPERTY_MODULES);
// Sort modules by reverse lexicographic order to avoid issue when one module id is a prefix of another one
Arrays.sort(moduleIds);
ArrayUtils.reverse(moduleIds);
propertiesByModuleIdPath.put(currentModuleIdPath, currentModuleProperties);
for (String moduleId : moduleIds) {
if ("sonar".equals(moduleId)) {
throw MessageException.of("'sonar' is not a valid module id. Please check property '" + PROPERTY_MODULES + "'.");
}
String subModuleIdPath = currentModuleIdPath.isEmpty() ? moduleId : (currentModuleIdPath + "." + moduleId);
extractPropertiesByModule(propertiesByModuleIdPath, moduleId, subModuleIdPath, currentModuleProperties);
}
}
protected ProjectDefinition createModuleDefinition(Map<String, String> moduleProperties, @Nullable ProjectDefinition parent) {
if (moduleProperties.containsKey(PROPERTY_MODULES)) {
checkMandatoryProperties(moduleProperties, MANDATORY_PROPERTIES_FOR_MULTIMODULE_PROJECT);
} else {
checkMandatoryProperties(moduleProperties, MANDATORY_PROPERTIES_FOR_SIMPLE_PROJECT);
}
File baseDir = new File(moduleProperties.get(PROPERTY_PROJECT_BASEDIR));
final String projectKey = moduleProperties.get(CoreProperties.PROJECT_KEY_PROPERTY);
File workDir;
if (parent == null) {
validateDirectories(moduleProperties, baseDir, projectKey);
workDir = initRootProjectWorkDir(baseDir, moduleProperties);
} else {
workDir = initModuleWorkDir(baseDir, moduleProperties);
checkUnsupportedIssueExclusions(moduleProperties, parent.properties());
}
return ProjectDefinition.create().setProperties(moduleProperties)
.setBaseDir(baseDir)
.setWorkDir(workDir);
}
private void checkUnsupportedIssueExclusions(Map<String, String> moduleProperties, Map<String, String> parentProps) {
UNSUPPORTED_PROPS_FOR_MODULES.forEach(p -> {
if (moduleProperties.containsKey(p) && !Objects.equals(moduleProperties.get(p), parentProps.get(p))) {
warnOnceUnsupportedIssueExclusions(
"Specifying issue exclusions at module level is not supported anymore. Configure the property '" + p + "' and any other issue exclusions at project level.");
}
});
}
private void warnOnceUnsupportedIssueExclusions(String msg) {
if (!warnExclusionsAlreadyLogged) {
LOG.warn(msg);
analysisWarnings.addUnique(msg);
warnExclusionsAlreadyLogged = true;
}
}
protected File initRootProjectWorkDir(File baseDir, Map<String, String> rootProperties) {
String workDir = rootProperties.get(CoreProperties.WORKING_DIRECTORY);
if (StringUtils.isBlank(workDir)) {
return new File(baseDir, CoreProperties.WORKING_DIRECTORY_DEFAULT_VALUE);
}
File customWorkDir = new File(workDir);
if (customWorkDir.isAbsolute()) {
return customWorkDir;
}
return new File(baseDir, customWorkDir.getPath());
}
protected File initModuleWorkDir(File moduleBaseDir, Map<String, String> moduleProperties) {
String workDir = moduleProperties.get(CoreProperties.WORKING_DIRECTORY);
if (StringUtils.isBlank(workDir)) {
return new File(rootProjectWorkDir, ScannerUtils.cleanKeyForFilename(moduleProperties.get(CoreProperties.PROJECT_KEY_PROPERTY)));
}
File customWorkDir = new File(workDir);
if (customWorkDir.isAbsolute()) {
return customWorkDir;
}
return new File(moduleBaseDir, customWorkDir.getPath());
}
private void defineChildren(ProjectDefinition parentProject, Map<String, Map<String, String>> propertiesByModuleIdPath, String parentModuleIdPath) {
Map<String, String> parentProps = parentProject.properties();
if (parentProps.containsKey(PROPERTY_MODULES)) {
for (String moduleId : getListFromProperty(parentProps, PROPERTY_MODULES)) {
String moduleIdPath = parentModuleIdPath.isEmpty() ? moduleId : (parentModuleIdPath + "." + moduleId);
Map<String, String> moduleProps = propertiesByModuleIdPath.get(moduleIdPath);
ProjectDefinition childProject = loadChildProject(parentProject, moduleProps, moduleId);
// check the uniqueness of the child key
checkUniquenessOfChildKey(childProject, parentProject);
// the child project may have children as well
defineChildren(childProject, propertiesByModuleIdPath, moduleIdPath);
// and finally add this child project to its parent
parentProject.addSubProject(childProject);
}
}
}
protected ProjectDefinition loadChildProject(ProjectDefinition parentProject, Map<String, String> moduleProps, String moduleId) {
final File baseDir;
if (moduleProps.containsKey(PROPERTY_PROJECT_BASEDIR)) {
baseDir = resolvePath(parentProject.getBaseDir(), moduleProps.get(PROPERTY_PROJECT_BASEDIR));
setProjectBaseDir(baseDir, moduleProps, moduleId);
} else {
baseDir = new File(parentProject.getBaseDir(), moduleId);
setProjectBaseDir(baseDir, moduleProps, moduleId);
}
setModuleKeyAndNameIfNotDefined(moduleProps, moduleId, parentProject.getKey());
// and finish
checkMandatoryProperties(moduleProps, MANDATORY_PROPERTIES_FOR_CHILD);
validateDirectories(moduleProps, baseDir, moduleId);
mergeParentProperties(moduleProps, parentProject.properties());
return createModuleDefinition(moduleProps, parentProject);
}
protected static void setModuleKeyAndNameIfNotDefined(Map<String, String> childProps, String moduleId, String parentKey) {
if (!childProps.containsKey(MODULE_KEY_PROPERTY)) {
if (!childProps.containsKey(CoreProperties.PROJECT_KEY_PROPERTY)) {
childProps.put(MODULE_KEY_PROPERTY, parentKey + ":" + moduleId);
} else {
String childKey = childProps.get(CoreProperties.PROJECT_KEY_PROPERTY);
childProps.put(MODULE_KEY_PROPERTY, parentKey + ":" + childKey);
}
}
childProps.putIfAbsent(CoreProperties.PROJECT_NAME_PROPERTY, moduleId);
// For backward compatibility with ProjectDefinition
childProps.put(CoreProperties.PROJECT_KEY_PROPERTY, childProps.get(MODULE_KEY_PROPERTY));
}
protected static void checkUniquenessOfChildKey(ProjectDefinition childProject, ProjectDefinition parentProject) {
for (ProjectDefinition definition : parentProject.getSubProjects()) {
if (definition.getKey().equals(childProject.getKey())) {
throw MessageException.of("Project '" + parentProject.getKey() + "' can't have 2 modules with the following key: " + childProject.getKey());
}
}
}
protected static void setProjectBaseDir(File baseDir, Map<String, String> childProps, String moduleId) {
if (!baseDir.isDirectory()) {
throw MessageException.of("The base directory of the module '" + moduleId + "' does not exist: " + baseDir.getAbsolutePath());
}
childProps.put(PROPERTY_PROJECT_BASEDIR, baseDir.getAbsolutePath());
}
protected static void checkMandatoryProperties(Map<String, String> props, String[] mandatoryProps) {
StringBuilder missing = new StringBuilder();
for (String mandatoryProperty : mandatoryProps) {
if (!props.containsKey(mandatoryProperty)) {
if (missing.length() > 0) {
missing.append(", ");
}
missing.append(mandatoryProperty);
}
}
String moduleKey = StringUtils.defaultIfBlank(props.get(MODULE_KEY_PROPERTY), props.get(CoreProperties.PROJECT_KEY_PROPERTY));
if (missing.length() != 0) {
throw MessageException.of("You must define the following mandatory properties for '" + (moduleKey == null ? "Unknown" : moduleKey) + "': " + missing);
}
}
protected static void validateDirectories(Map<String, String> props, File baseDir, String projectId) {
if (!props.containsKey(PROPERTY_MODULES)) {
// SONARPLUGINS-2285 Not an aggregator project so we can validate that paths are correct if defined
// Check sonar.tests
String[] testPaths = getListFromProperty(props, PROPERTY_TESTS);
checkExistenceAndValidateSourcePaths(projectId, baseDir, testPaths, PROPERTY_TESTS);
}
}
protected static void cleanAndCheckProjectDefinitions(ProjectDefinition project) {
if (project.getSubProjects().isEmpty()) {
cleanAndCheckModuleProperties(project);
} else {
logMissingSourcesAndTests(project);
// clean modules properties as well
for (ProjectDefinition module : project.getSubProjects()) {
cleanAndCheckProjectDefinitions(module);
}
}
}
private static void logMissingSourcesAndTests(ProjectDefinition project) {
Map<String, String> properties = project.properties();
File baseDir = project.getBaseDir();
logMissingPaths("source", baseDir, getListFromProperty(properties, PROPERTY_SOURCES));
logMissingPaths("test", baseDir, getListFromProperty(properties, PROPERTY_TESTS));
}
private static void logMissingPaths(String label, File baseDir, String[] paths) {
for (String path : paths) {
File file = resolvePath(baseDir, path);
if (!file.exists()) {
LOG.debug("Path '{}' does not exist, will not be used as {}", file, label);
}
}
}
protected static void cleanAndCheckModuleProperties(ProjectDefinition project) {
Map<String, String> properties = project.properties();
// We need to check the existence of source directories
String[] sourcePaths = getListFromProperty(properties, PROPERTY_SOURCES);
checkExistenceAndValidateSourcePaths(project.getKey(), project.getBaseDir(), sourcePaths, PROPERTY_SOURCES);
}
protected static void mergeParentProperties(Map<String, String> childProps, Map<String, String> parentProps) {
for (Map.Entry<String, String> entry : parentProps.entrySet()) {
String key = entry.getKey();
if ((!childProps.containsKey(key) || childProps.get(key).equals(entry.getValue()))
&& !NON_HERITED_PROPERTIES_FOR_CHILD.contains(key)) {
childProps.put(entry.getKey(), entry.getValue());
}
}
}
protected static void checkExistenceAndValidateSourcePaths(String moduleRef, File baseDir, String[] paths, String propName) {
for (String path : paths) {
validateNoAsterisksInSourcePath(path, propName, moduleRef);
File sourceFolder = resolvePath(baseDir, path);
if (!sourceFolder.exists()) {
LOG.error(MessageFormat.format(INVALID_VALUE_OF_X_FOR_Y, propName, moduleRef));
throw MessageException.of("The folder '" + path + "' does not exist for '" + moduleRef +
"' (base directory = " + baseDir.getAbsolutePath() + ")");
}
}
}
private static void validateNoAsterisksInSourcePath(String path, String propName, String moduleRef) {
if (path.contains("*")) {
LOG.error(MessageFormat.format(INVALID_VALUE_OF_X_FOR_Y, propName, moduleRef));
throw MessageException.of(WILDCARDS_NOT_SUPPORTED);
}
}
protected static File resolvePath(File baseDir, String path) {
Path filePath = Paths.get(path);
if (!filePath.isAbsolute()) {
filePath = baseDir.toPath().resolve(path);
}
return filePath.normalize().toFile();
}
/**
* Transforms a comma-separated list String property in to a array of trimmed strings.
* <p>
* This works even if they are separated by whitespace characters (space char, EOL, ...)
*/
static String[] getListFromProperty(Map<String, String> properties, String key) {
String propValue = properties.get(key);
if (propValue != null) {
return parseAsCsv(key, propValue);
}
return new String[0];
}
}
| 18,618 | 43.330952 | 172 | java |
sonarqube | sonarqube-master/sonar-scanner-engine/src/main/java/org/sonar/scanner/scan/ProjectReactorValidator.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.scan;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Stream;
import javax.annotation.Nullable;
import org.sonar.api.batch.bootstrap.ProjectDefinition;
import org.sonar.api.batch.bootstrap.ProjectReactor;
import org.sonar.api.utils.MessageException;
import org.sonar.core.component.ComponentKeys;
import org.sonar.core.documentation.DocumentationLinkGenerator;
import org.sonar.scanner.bootstrap.GlobalConfiguration;
import org.sonar.scanner.scan.branch.BranchParamsValidator;
import org.springframework.beans.factory.annotation.Autowired;
import static java.lang.String.format;
import static java.util.Objects.nonNull;
import static org.apache.commons.lang.StringUtils.isNotEmpty;
import static org.sonar.core.component.ComponentKeys.ALLOWED_CHARACTERS_MESSAGE;
import static org.sonar.core.config.ScannerProperties.BRANCHES_DOC_LINK_SUFFIX;
import static org.sonar.core.config.ScannerProperties.BRANCH_NAME;
import static org.sonar.core.config.ScannerProperties.PULL_REQUEST_BASE;
import static org.sonar.core.config.ScannerProperties.PULL_REQUEST_BRANCH;
import static org.sonar.core.config.ScannerProperties.PULL_REQUEST_KEY;
/**
* This class aims at validating project reactor
*
* @since 3.6
*/
public class ProjectReactorValidator {
private final GlobalConfiguration settings;
// null = branch plugin is not available
@Nullable
private final BranchParamsValidator branchParamsValidator;
private final DocumentationLinkGenerator documentationLinkGenerator;
@Autowired(required = false)
public ProjectReactorValidator(GlobalConfiguration settings, @Nullable BranchParamsValidator branchParamsValidator, DocumentationLinkGenerator documentationLinkGenerator) {
this.settings = settings;
this.branchParamsValidator = branchParamsValidator;
this.documentationLinkGenerator = documentationLinkGenerator;
}
@Autowired(required = false)
public ProjectReactorValidator(GlobalConfiguration settings, DocumentationLinkGenerator documentationLinkGenerator) {
this(settings, null, documentationLinkGenerator);
}
public void validate(ProjectReactor reactor) {
List<String> validationMessages = new ArrayList<>();
for (ProjectDefinition moduleDef : reactor.getProjects()) {
validateModule(moduleDef, validationMessages);
}
if (isBranchFeatureAvailable()) {
branchParamsValidator.validate(validationMessages);
} else {
validateBranchParamsWhenPluginAbsent(validationMessages);
validatePullRequestParamsWhenPluginAbsent(validationMessages);
}
if (!validationMessages.isEmpty()) {
throw MessageException.of("Validation of project failed:\n o " +
String.join("\n o ", validationMessages));
}
}
private void validateBranchParamsWhenPluginAbsent(List<String> validationMessages) {
if (isNotEmpty(settings.get(BRANCH_NAME).orElse(null))) {
validationMessages.add(format("To use the property \"%s\" and analyze branches, Developer Edition or above is required. "
+ "See %s for more information.", BRANCH_NAME, documentationLinkGenerator.getDocumentationLink(BRANCHES_DOC_LINK_SUFFIX)));
}
}
private void validatePullRequestParamsWhenPluginAbsent(List<String> validationMessages) {
Stream.of(PULL_REQUEST_KEY, PULL_REQUEST_BRANCH, PULL_REQUEST_BASE)
.filter(param -> nonNull(settings.get(param).orElse(null)))
.forEach(param -> validationMessages.add(format("To use the property \"%s\" and analyze pull requests, Developer Edition or above is required. "
+ "See %s for more information.", param, documentationLinkGenerator.getDocumentationLink(BRANCHES_DOC_LINK_SUFFIX))));
}
private static void validateModule(ProjectDefinition projectDefinition, List<String> validationMessages) {
if (!ComponentKeys.isValidProjectKey(projectDefinition.getKey())) {
validationMessages.add(format("\"%s\" is not a valid project key. %s.", projectDefinition.getKey(), ALLOWED_CHARACTERS_MESSAGE));
}
}
private boolean isBranchFeatureAvailable() {
return branchParamsValidator != null;
}
}
| 4,964 | 41.801724 | 174 | java |
sonarqube | sonarqube-master/sonar-scanner-engine/src/main/java/org/sonar/scanner/scan/ProjectServerSettings.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.scan;
import java.util.Map;
import javax.annotation.concurrent.Immutable;
/**
* Project settings coming from the server. Does not contain global settings.
*/
@Immutable
public class ProjectServerSettings {
private final Map<String, String> properties;
public ProjectServerSettings(Map<String, String> properties) {
this.properties = Map.copyOf(properties);
}
public Map<String, String> properties() {
return properties;
}
public String property(String key) {
return properties.get(key);
}
}
| 1,395 | 29.347826 | 77 | java |
sonarqube | sonarqube-master/sonar-scanner-engine/src/main/java/org/sonar/scanner/scan/ProjectServerSettingsProvider.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.scan;
import java.util.Map;
import org.apache.commons.lang.StringUtils;
import org.sonar.api.CoreProperties;
import org.sonar.api.notifications.AnalysisWarnings;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.sonar.scanner.repository.settings.ProjectSettingsLoader;
import org.springframework.context.annotation.Bean;
public class ProjectServerSettingsProvider {
private static final Logger LOG = LoggerFactory.getLogger(ProjectServerSettingsProvider.class);
private static final String MODULE_LEVEL_ARCHIVED_SETTINGS_WARNING = "Settings that were previously configured at " +
"sub-project level are not used anymore. Transition the settings listed in ‘General Settings -> General -> " +
"Archived Sub-Projects Settings' at project level, and clear the property to prevent the analysis from " +
"displaying this warning.";
@Bean("ProjectServerSettings")
public ProjectServerSettings provide(ProjectSettingsLoader loader, AnalysisWarnings analysisWarnings) {
Map<String, String> serverSideSettings = loader.loadProjectSettings();
if (StringUtils.isNotBlank(serverSideSettings.get(CoreProperties.MODULE_LEVEL_ARCHIVED_SETTINGS))) {
LOG.warn(MODULE_LEVEL_ARCHIVED_SETTINGS_WARNING);
analysisWarnings.addUnique(MODULE_LEVEL_ARCHIVED_SETTINGS_WARNING);
}
return new ProjectServerSettings(serverSideSettings);
}
}
| 2,253 | 44.08 | 119 | java |
sonarqube | sonarqube-master/sonar-scanner-engine/src/main/java/org/sonar/scanner/scan/ScanProperties.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.scan;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.Optional;
import org.sonar.api.batch.fs.internal.DefaultInputProject;
import org.sonar.api.config.Configuration;
import org.sonar.api.utils.MessageException;
import static org.sonar.core.config.ScannerProperties.BRANCH_NAME;
import static org.sonar.core.config.ScannerProperties.FILE_SIZE_LIMIT;
/**
* Properties that can be passed to the scanners and are not exposed in SonarQube.
*/
public class ScanProperties {
public static final String METADATA_FILE_PATH_KEY = "sonar.scanner.metadataFilePath";
public static final String KEEP_REPORT_PROP_KEY = "sonar.scanner.keepReport";
public static final String VERBOSE_KEY = "sonar.verbose";
public static final String METADATA_DUMP_FILENAME = "report-task.txt";
public static final String SONAR_REPORT_EXPORT_PATH = "sonar.report.export.path";
public static final String PRELOAD_FILE_METADATA_KEY = "sonar.preloadFileMetadata";
public static final String FORCE_RELOAD_KEY = "sonar.scm.forceReloadAll";
public static final String SCM_REVISION = "sonar.scm.revision";
public static final String QUALITY_GATE_WAIT = "sonar.qualitygate.wait";
public static final String QUALITY_GATE_TIMEOUT_IN_SEC = "sonar.qualitygate.timeout";
public static final String REPORT_PUBLISH_TIMEOUT_IN_SEC = "sonar.ws.report.timeout";
private final Configuration configuration;
private final DefaultInputProject project;
public ScanProperties(Configuration configuration, DefaultInputProject project) {
this.configuration = configuration;
this.project = project;
}
public boolean shouldKeepReport() {
return configuration.getBoolean(KEEP_REPORT_PROP_KEY).orElse(false) || configuration.getBoolean(VERBOSE_KEY).orElse(false);
}
public boolean preloadFileMetadata() {
return configuration.getBoolean(PRELOAD_FILE_METADATA_KEY).orElse(false);
}
public Optional<String> branch() {
return configuration.get(BRANCH_NAME);
}
public Optional<String> get(String propertyKey) {
return configuration.get(propertyKey);
}
public Path metadataFilePath() {
Optional<String> metadataFilePath = configuration.get(METADATA_FILE_PATH_KEY);
if (metadataFilePath.isPresent()) {
Path metadataPath = Paths.get(metadataFilePath.get());
if (!metadataPath.isAbsolute()) {
throw MessageException.of(String.format("Property '%s' must point to an absolute path: %s", METADATA_FILE_PATH_KEY, metadataFilePath.get()));
}
return project.getBaseDir().resolve(metadataPath);
} else {
return project.getWorkDir().resolve(METADATA_DUMP_FILENAME);
}
}
public boolean shouldWaitForQualityGate() {
return configuration.getBoolean(QUALITY_GATE_WAIT).orElse(false);
}
public int qualityGateWaitTimeout() {
return configuration.getInt(QUALITY_GATE_TIMEOUT_IN_SEC).orElse(300);
}
public int reportPublishTimeout() {
return configuration.getInt(REPORT_PUBLISH_TIMEOUT_IN_SEC).orElse(60);
}
public long fileSizeLimit() {
return configuration.getInt(FILE_SIZE_LIMIT).orElse(20);
}
/**
* This should be called in the beginning of the analysis to fail fast
*/
public void validate() {
metadataFilePath();
}
}
| 4,123 | 37.185185 | 149 | java |
sonarqube | sonarqube-master/sonar-scanner-engine/src/main/java/org/sonar/scanner/scan/SonarGlobalPropertiesFilter.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.scan;
import com.google.common.annotations.VisibleForTesting;
import java.util.Map;
import java.util.stream.Collectors;
public class SonarGlobalPropertiesFilter {
@VisibleForTesting
static final String SONAR_GLOBAL_PROPERTIES_PREFIX = "sonar.global.";
public Map<String, String> enforceOnlyServerSideSonarGlobalPropertiesAreUsed(Map<String, String> settingProperties, Map<String, String> globalServerSettingsProperties) {
Map<String, String> settings = getNonSonarGlobalProperties(settingProperties);
settings.putAll(getSonarGlobalProperties(globalServerSettingsProperties));
return settings;
}
private static Map<String, String> getNonSonarGlobalProperties(Map<String, String> settingProperties) {
return settingProperties.entrySet()
.stream()
.filter(entry -> !isSonarGlobalProperty(entry.getKey()))
.collect(Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue));
}
private static Map<String, String> getSonarGlobalProperties(Map<String, String> properties) {
return properties
.entrySet()
.stream()
.filter(entry -> isSonarGlobalProperty(entry.getKey()))
.collect(Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue));
}
private static boolean isSonarGlobalProperty(String propertiesCode) {
return propertiesCode.startsWith(SONAR_GLOBAL_PROPERTIES_PREFIX);
}
}
| 2,236 | 37.568966 | 171 | java |
sonarqube | sonarqube-master/sonar-scanner-engine/src/main/java/org/sonar/scanner/scan/SpringModuleScanContainer.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.scan;
import javax.annotation.Priority;
import org.sonar.api.batch.fs.internal.DefaultInputModule;
import org.sonar.api.scan.filesystem.FileExclusions;
import org.sonar.scanner.bootstrap.ExtensionInstaller;
import org.sonar.core.platform.SpringComponentContainer;
import org.sonar.scanner.scan.filesystem.DefaultModuleFileSystem;
import org.sonar.scanner.scan.filesystem.ModuleInputComponentStore;
import org.sonar.scanner.sensor.ModuleSensorContext;
import org.sonar.scanner.sensor.ModuleSensorExtensionDictionary;
import org.sonar.scanner.sensor.ModuleSensorOptimizer;
import org.sonar.scanner.sensor.ModuleSensorsExecutor;
import static org.sonar.api.batch.InstantiationStrategy.PER_PROJECT;
import static org.sonar.scanner.bootstrap.ExtensionUtils.isDeprecatedScannerSide;
import static org.sonar.scanner.bootstrap.ExtensionUtils.isInstantiationStrategy;
@Priority(1)
public class SpringModuleScanContainer extends SpringComponentContainer {
private final DefaultInputModule module;
public SpringModuleScanContainer(SpringComponentContainer parent, DefaultInputModule module) {
super(parent);
this.module = module;
}
@Override
protected void doBeforeStart() {
addCoreComponents();
addExtensions();
}
private void addCoreComponents() {
add(
module.definition(),
module,
MutableModuleSettings.class,
SonarGlobalPropertiesFilter.class,
ModuleConfigurationProvider.class,
ModuleSensorsExecutor.class,
// file system
ModuleInputComponentStore.class,
FileExclusions.class,
DefaultModuleFileSystem.class,
ModuleSensorOptimizer.class,
ModuleSensorContext.class,
ModuleSensorExtensionDictionary.class
);
}
private void addExtensions() {
ExtensionInstaller pluginInstaller = parent.getComponentByType(ExtensionInstaller.class);
pluginInstaller.install(this, e -> isDeprecatedScannerSide(e) && isInstantiationStrategy(e, PER_PROJECT));
}
@Override
protected void doAfterStart() {
getComponentByType(ModuleSensorsExecutor.class).execute();
}
}
| 2,957 | 33.8 | 110 | java |
sonarqube | sonarqube-master/sonar-scanner-engine/src/main/java/org/sonar/scanner/scan/SpringProjectScanContainer.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.scan;
import javax.annotation.Nullable;
import javax.annotation.Priority;
import org.sonar.api.batch.fs.internal.DefaultInputModule;
import org.sonar.api.batch.fs.internal.FileMetadata;
import org.sonar.api.batch.fs.internal.SensorStrategy;
import org.sonar.api.batch.rule.CheckFactory;
import org.sonar.api.batch.sensor.issue.internal.DefaultNoSonarFilter;
import org.sonar.api.resources.ResourceTypes;
import org.sonar.api.scan.filesystem.PathResolver;
import org.sonar.api.utils.MessageException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.sonar.core.config.ScannerProperties;
import org.sonar.core.extension.CoreExtensionsInstaller;
import org.sonar.core.language.LanguagesProvider;
import org.sonar.core.metric.ScannerMetrics;
import org.sonar.core.platform.SpringComponentContainer;
import org.sonar.scanner.DefaultFileLinesContextFactory;
import org.sonar.scanner.ProjectInfo;
import org.sonar.scanner.analysis.AnalysisTempFolderProvider;
import org.sonar.scanner.bootstrap.ExtensionInstaller;
import org.sonar.scanner.bootstrap.ExtensionMatcher;
import org.sonar.scanner.bootstrap.GlobalAnalysisMode;
import org.sonar.scanner.bootstrap.PostJobExtensionDictionary;
import org.sonar.scanner.cache.AnalysisCacheEnabled;
import org.sonar.scanner.cache.AnalysisCacheMemoryStorage;
import org.sonar.scanner.cache.AnalysisCacheProvider;
import org.sonar.scanner.cache.DefaultAnalysisCacheLoader;
import org.sonar.scanner.ci.CiConfigurationProvider;
import org.sonar.scanner.ci.vendors.AppVeyor;
import org.sonar.scanner.ci.vendors.AwsCodeBuild;
import org.sonar.scanner.ci.vendors.AzureDevops;
import org.sonar.scanner.ci.vendors.Bamboo;
import org.sonar.scanner.ci.vendors.BitbucketPipelines;
import org.sonar.scanner.ci.vendors.Bitrise;
import org.sonar.scanner.ci.vendors.Buildkite;
import org.sonar.scanner.ci.vendors.CircleCi;
import org.sonar.scanner.ci.vendors.CirrusCi;
import org.sonar.scanner.ci.vendors.CodeMagic;
import org.sonar.scanner.ci.vendors.DroneCi;
import org.sonar.scanner.ci.vendors.GithubActions;
import org.sonar.scanner.ci.vendors.GitlabCi;
import org.sonar.scanner.ci.vendors.Jenkins;
import org.sonar.scanner.ci.vendors.SemaphoreCi;
import org.sonar.scanner.ci.vendors.TravisCi;
import org.sonar.scanner.cpd.CpdExecutor;
import org.sonar.scanner.cpd.CpdSettings;
import org.sonar.scanner.cpd.index.SonarCpdBlockIndex;
import org.sonar.scanner.fs.InputModuleHierarchy;
import org.sonar.scanner.issue.IssueFilters;
import org.sonar.scanner.issue.IssuePublisher;
import org.sonar.scanner.issue.ignore.EnforceIssuesFilter;
import org.sonar.scanner.issue.ignore.IgnoreIssuesFilter;
import org.sonar.scanner.issue.ignore.pattern.IssueExclusionPatternInitializer;
import org.sonar.scanner.issue.ignore.pattern.IssueInclusionPatternInitializer;
import org.sonar.scanner.issue.ignore.scanner.IssueExclusionsLoader;
import org.sonar.scanner.mediumtest.AnalysisObservers;
import org.sonar.scanner.postjob.DefaultPostJobContext;
import org.sonar.scanner.postjob.PostJobOptimizer;
import org.sonar.scanner.postjob.PostJobsExecutor;
import org.sonar.scanner.qualitygate.QualityGateCheck;
import org.sonar.scanner.report.ActiveRulesPublisher;
import org.sonar.scanner.report.AnalysisCachePublisher;
import org.sonar.scanner.report.AnalysisContextReportPublisher;
import org.sonar.scanner.report.AnalysisWarningsPublisher;
import org.sonar.scanner.report.CeTaskReportDataHolder;
import org.sonar.scanner.report.ChangedLinesPublisher;
import org.sonar.scanner.report.ComponentsPublisher;
import org.sonar.scanner.report.ContextPropertiesPublisher;
import org.sonar.scanner.report.JavaArchitectureInformationProvider;
import org.sonar.scanner.report.MetadataPublisher;
import org.sonar.scanner.report.ReportPublisher;
import org.sonar.scanner.report.ScannerFileStructureProvider;
import org.sonar.scanner.report.SourcePublisher;
import org.sonar.scanner.report.TestExecutionPublisher;
import org.sonar.scanner.repository.ContextPropertiesCache;
import org.sonar.scanner.repository.DefaultProjectRepositoriesLoader;
import org.sonar.scanner.repository.DefaultQualityProfileLoader;
import org.sonar.scanner.repository.ProjectRepositoriesProvider;
import org.sonar.scanner.repository.QualityProfilesProvider;
import org.sonar.scanner.repository.ReferenceBranchSupplier;
import org.sonar.scanner.repository.language.DefaultLanguagesRepository;
import org.sonar.scanner.repository.settings.DefaultProjectSettingsLoader;
import org.sonar.scanner.rule.ActiveRulesProvider;
import org.sonar.scanner.rule.DefaultActiveRulesLoader;
import org.sonar.scanner.rule.DefaultRulesLoader;
import org.sonar.scanner.rule.QProfileVerifier;
import org.sonar.scanner.rule.RulesProvider;
import org.sonar.scanner.scan.branch.BranchConfiguration;
import org.sonar.scanner.scan.branch.BranchConfigurationProvider;
import org.sonar.scanner.scan.branch.BranchType;
import org.sonar.scanner.scan.branch.ProjectBranchesProvider;
import org.sonar.scanner.scan.filesystem.DefaultProjectFileSystem;
import org.sonar.scanner.scan.filesystem.FileIndexer;
import org.sonar.scanner.scan.filesystem.InputComponentStore;
import org.sonar.scanner.scan.filesystem.LanguageDetection;
import org.sonar.scanner.scan.filesystem.MetadataGenerator;
import org.sonar.scanner.scan.filesystem.ProjectCoverageAndDuplicationExclusions;
import org.sonar.scanner.scan.filesystem.ProjectExclusionFilters;
import org.sonar.scanner.scan.filesystem.ProjectFileIndexer;
import org.sonar.scanner.scan.filesystem.ScannerComponentIdGenerator;
import org.sonar.scanner.scan.filesystem.StatusDetection;
import org.sonar.scanner.scan.measure.DefaultMetricFinder;
import org.sonar.scanner.scm.ScmChangedFilesProvider;
import org.sonar.scanner.scm.ScmConfiguration;
import org.sonar.scanner.scm.ScmPublisher;
import org.sonar.scanner.scm.ScmRevisionImpl;
import org.sonar.scanner.sensor.DefaultSensorStorage;
import org.sonar.scanner.sensor.ExecutingSensorContext;
import org.sonar.scanner.sensor.ProjectSensorContext;
import org.sonar.scanner.sensor.ProjectSensorExtensionDictionary;
import org.sonar.scanner.sensor.ProjectSensorOptimizer;
import org.sonar.scanner.sensor.ProjectSensorsExecutor;
import org.sonar.scanner.sensor.UnchangedFilesHandler;
import org.sonar.scm.git.GitScmSupport;
import org.sonar.scm.svn.SvnScmSupport;
import static org.sonar.api.batch.InstantiationStrategy.PER_BATCH;
import static org.sonar.api.utils.Preconditions.checkNotNull;
import static org.sonar.core.extension.CoreExtensionsInstaller.noExtensionFilter;
import static org.sonar.scanner.bootstrap.ExtensionUtils.isDeprecatedScannerSide;
import static org.sonar.scanner.bootstrap.ExtensionUtils.isInstantiationStrategy;
import static org.sonar.scanner.bootstrap.ExtensionUtils.isScannerSide;
@Priority(2)
public class SpringProjectScanContainer extends SpringComponentContainer {
private static final Logger LOG = LoggerFactory.getLogger(SpringProjectScanContainer.class);
public SpringProjectScanContainer(SpringComponentContainer globalContainer) {
super(globalContainer);
}
@Override
protected void doBeforeStart() {
addScannerExtensions();
addScannerComponents();
}
private void addScannerComponents() {
add(
ScanProperties.class,
ProjectReactorBuilder.class,
WorkDirectoriesInitializer.class,
new MutableProjectReactorProvider(),
ProjectBuildersExecutor.class,
ProjectLock.class,
ResourceTypes.class,
ProjectReactorValidator.class,
ProjectInfo.class,
new RulesProvider(),
new BranchConfigurationProvider(),
new ProjectBranchesProvider(),
ProjectRepositoriesProvider.class,
new ProjectServerSettingsProvider(),
AnalysisCacheEnabled.class,
DeprecatedPropertiesWarningGenerator.class,
// temp
new AnalysisTempFolderProvider(),
// file system
ModuleIndexer.class,
InputComponentStore.class,
PathResolver.class,
new InputProjectProvider(),
new InputModuleHierarchyProvider(),
ScannerComponentIdGenerator.class,
new ScmChangedFilesProvider(),
StatusDetection.class,
LanguageDetection.class,
MetadataGenerator.class,
FileMetadata.class,
FileIndexer.class,
ProjectFileIndexer.class,
ProjectExclusionFilters.class,
// rules
new ActiveRulesProvider(),
new QualityProfilesProvider(),
CheckFactory.class,
QProfileVerifier.class,
// issues
DefaultNoSonarFilter.class,
IssueFilters.class,
IssuePublisher.class,
// metrics
DefaultMetricFinder.class,
// lang
LanguagesProvider.class,
DefaultLanguagesRepository.class,
// issue exclusions
IssueInclusionPatternInitializer.class,
IssueExclusionPatternInitializer.class,
IssueExclusionsLoader.class,
EnforceIssuesFilter.class,
IgnoreIssuesFilter.class,
// context
ContextPropertiesCache.class,
ContextPropertiesPublisher.class,
SensorStrategy.class,
MutableProjectSettings.class,
ScannerProperties.class,
SonarGlobalPropertiesFilter.class,
ProjectConfigurationProvider.class,
ProjectCoverageAndDuplicationExclusions.class,
// Plugin cache
AnalysisCacheProvider.class,
AnalysisCacheMemoryStorage.class,
DefaultAnalysisCacheLoader.class,
// Report
ReferenceBranchSupplier.class,
ScannerMetrics.class,
JavaArchitectureInformationProvider.class,
ReportPublisher.class,
ScannerFileStructureProvider.class,
AnalysisContextReportPublisher.class,
MetadataPublisher.class,
ActiveRulesPublisher.class,
ComponentsPublisher.class,
AnalysisCachePublisher.class,
TestExecutionPublisher.class,
SourcePublisher.class,
ChangedLinesPublisher.class,
AnalysisWarningsPublisher.class,
CeTaskReportDataHolder.class,
// QualityGate check
QualityGateCheck.class,
// Cpd
CpdExecutor.class,
CpdSettings.class,
SonarCpdBlockIndex.class,
// PostJobs
PostJobsExecutor.class,
PostJobOptimizer.class,
DefaultPostJobContext.class,
PostJobExtensionDictionary.class,
// SCM
ScmConfiguration.class,
ScmPublisher.class,
ScmRevisionImpl.class,
// Sensors
DefaultSensorStorage.class,
DefaultFileLinesContextFactory.class,
ProjectSensorContext.class,
ProjectSensorOptimizer.class,
ProjectSensorsExecutor.class,
ExecutingSensorContext.class,
ProjectSensorExtensionDictionary.class,
UnchangedFilesHandler.class,
// Filesystem
DefaultProjectFileSystem.class,
// CI
new CiConfigurationProvider(),
AppVeyor.class,
AwsCodeBuild.class,
AzureDevops.class,
Bamboo.class,
BitbucketPipelines.class,
Bitrise.class,
Buildkite.class,
CircleCi.class,
CirrusCi.class,
DroneCi.class,
GithubActions.class,
CodeMagic.class,
GitlabCi.class,
Jenkins.class,
SemaphoreCi.class,
TravisCi.class,
AnalysisObservers.class);
add(GitScmSupport.getObjects());
add(SvnScmSupport.getObjects());
add(DefaultProjectSettingsLoader.class,
DefaultRulesLoader.class,
DefaultActiveRulesLoader.class,
DefaultQualityProfileLoader.class,
DefaultProjectRepositoriesLoader.class);
}
private void addScannerExtensions() {
checkNotNull(getParent());
getParent().getComponentByType(CoreExtensionsInstaller.class)
.install(this, noExtensionFilter(), extension -> getScannerProjectExtensionsFilter().accept(extension));
getParent().getComponentByType(ExtensionInstaller.class)
.install(this, getScannerProjectExtensionsFilter());
}
static ExtensionMatcher getScannerProjectExtensionsFilter() {
return extension -> {
if (isDeprecatedScannerSide(extension)) {
return isInstantiationStrategy(extension, PER_BATCH);
}
return isScannerSide(extension);
};
}
@Override
protected void doAfterStart() {
getComponentByType(ProjectLock.class).tryLock();
GlobalAnalysisMode analysisMode = getComponentByType(GlobalAnalysisMode.class);
InputModuleHierarchy tree = getComponentByType(InputModuleHierarchy.class);
ScanProperties properties = getComponentByType(ScanProperties.class);
properties.validate();
properties.get("sonar.branch").ifPresent(deprecatedBranch -> {
throw MessageException.of("The 'sonar.branch' parameter is no longer supported. You should stop using it. " +
"Branch analysis is available in Developer Edition and above. See https://www.sonarsource.com/plans-and-pricing/developer/ for more information.");
});
BranchConfiguration branchConfig = getComponentByType(BranchConfiguration.class);
if (branchConfig.branchType() == BranchType.PULL_REQUEST) {
LOG.info("Pull request {} for merge into {} from {}", branchConfig.pullRequestKey(), pullRequestBaseToDisplayName(branchConfig.targetBranchName()),
branchConfig.branchName());
} else if (branchConfig.branchName() != null) {
LOG.info("Branch name: {}", branchConfig.branchName());
}
getComponentByType(DeprecatedPropertiesWarningGenerator.class).execute();
getComponentByType(ProjectFileIndexer.class).index();
// Log detected languages and their profiles after FS is indexed and languages detected
getComponentByType(QProfileVerifier.class).execute();
scanRecursively(tree, tree.root());
LOG.info("------------- Run sensors on project");
getComponentByType(ProjectSensorsExecutor.class).execute();
getComponentByType(ScmPublisher.class).publish();
getComponentByType(CpdExecutor.class).execute();
getComponentByType(ReportPublisher.class).execute();
if (properties.shouldWaitForQualityGate()) {
LOG.info("------------- Check Quality Gate status");
getComponentByType(QualityGateCheck.class).await();
}
getComponentByType(PostJobsExecutor.class).execute();
if (analysisMode.isMediumTest()) {
getComponentByType(AnalysisObservers.class).notifyEndOfScanTask();
}
}
private static String pullRequestBaseToDisplayName(@Nullable String pullRequestBase) {
return pullRequestBase != null ? pullRequestBase : "default branch";
}
private void scanRecursively(InputModuleHierarchy tree, DefaultInputModule module) {
for (DefaultInputModule child : tree.children(module)) {
scanRecursively(tree, child);
}
LOG.info("------------- Run sensors on module {}", module.definition().getName());
scan(module);
}
void scan(DefaultInputModule module) {
new SpringModuleScanContainer(this, module).execute();
}
}
| 15,674 | 37.513514 | 155 | java |
sonarqube | sonarqube-master/sonar-scanner-engine/src/main/java/org/sonar/scanner/scan/WorkDirectoriesInitializer.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.scan;
import java.io.IOException;
import java.nio.file.DirectoryStream;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.Iterator;
import java.util.Objects;
import org.sonar.api.batch.fs.internal.AbstractProjectOrModule;
import org.sonar.api.batch.fs.internal.DefaultInputModule;
import org.sonar.api.batch.fs.internal.DefaultInputProject;
import org.sonar.core.util.FileUtils;
import org.sonar.scanner.fs.InputModuleHierarchy;
/**
* Clean and create working directories of each module, except the root.
* Be careful that sub module work dir might be nested in parent working directory.
*/
public class WorkDirectoriesInitializer {
public void execute(InputModuleHierarchy moduleHierarchy) {
DefaultInputModule root = moduleHierarchy.root();
// dont apply to root. Root is done by InputProjectProvider
for (DefaultInputModule sub : moduleHierarchy.children(root)) {
if (!Objects.equals(root.getWorkDir(), sub.getWorkDir())) {
cleanAllWorkingDirs(moduleHierarchy, sub);
mkdirsAllWorkingDirs(moduleHierarchy, sub);
}
}
}
public void execute(DefaultInputProject project) {
cleanWorkingDir(project);
mkdirWorkingDir(project);
}
private static void cleanAllWorkingDirs(InputModuleHierarchy moduleHierarchy, DefaultInputModule module) {
for (DefaultInputModule sub : moduleHierarchy.children(module)) {
cleanAllWorkingDirs(moduleHierarchy, sub);
}
cleanWorkingDir(module);
}
private static void cleanWorkingDir(AbstractProjectOrModule projectOrModule) {
if (Files.exists(projectOrModule.getWorkDir())) {
deleteAllRecursivelyExceptLockFile(projectOrModule.getWorkDir());
}
}
private static void mkdirsAllWorkingDirs(InputModuleHierarchy moduleHierarchy, DefaultInputModule module) {
for (DefaultInputModule sub : moduleHierarchy.children(module)) {
mkdirsAllWorkingDirs(moduleHierarchy, sub);
}
mkdirWorkingDir(module);
}
private static void mkdirWorkingDir(AbstractProjectOrModule projectOrModule) {
try {
Files.createDirectories(projectOrModule.getWorkDir());
} catch (Exception e) {
throw new IllegalStateException("Fail to create working dir: " + projectOrModule.getWorkDir(), e);
}
}
private static void deleteAllRecursivelyExceptLockFile(Path dirToDelete) {
try (DirectoryStream<Path> stream = list(dirToDelete)) {
Iterator<Path> it = stream.iterator();
while (it.hasNext()) {
FileUtils.deleteQuietly(it.next().toFile());
}
} catch (IOException e) {
throw new IllegalStateException("Failed to clean working directory: " + dirToDelete.toString(), e);
}
}
private static DirectoryStream<Path> list(Path dir) throws IOException {
return Files.newDirectoryStream(dir, entry -> !DirectoryLock.LOCK_FILE_NAME.equals(entry.getFileName().toString()));
}
}
| 3,758 | 36.969697 | 120 | java |
sonarqube | sonarqube-master/sonar-scanner-engine/src/main/java/org/sonar/scanner/scan/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.scan;
import javax.annotation.ParametersAreNonnullByDefault;
| 962 | 39.125 | 75 | java |
sonarqube | sonarqube-master/sonar-scanner-engine/src/main/java/org/sonar/scanner/scan/branch/BranchConfiguration.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.scan.branch;
import javax.annotation.CheckForNull;
import javax.annotation.concurrent.Immutable;
@Immutable
public interface BranchConfiguration {
/**
* @return type of the current branch
*/
BranchType branchType();
default boolean isPullRequest() {
return branchType() == BranchType.PULL_REQUEST;
}
/**
* For branches, this is the value of sonar.branch.name, and fallback on the default branch name configured in SQ
* For PR: the name of the branch containing PR changes (sonar.pullrequest.branch)
*
* @return null if the branch feature is not available or no branch was specified.
*/
@CheckForNull
String branchName();
/**
* The branch from which we should load project settings/quality profiles/compare changed files/...
* For branches, it's the default branch in case of first analysis, otherwise it's the branch itself.
* For PR, we look at sonar.pullrequest.base (default to default branch). If it exists and is not a PR we use it. If it exists but is a PR, we will
* transitively use its own target. If base is not analyzed, we will use default branch.
*
* @return null if the branch feature is not available or no branch was specified.
*/
@CheckForNull
String referenceBranchName();
/**
* For P/Rs, it's the raw value of 'sonar.pullrequest.base'.
* For branches it's always null.
* In the scanner side, it will be used by the SCM to compute changed files and changed lines.
*
* @return null if the branch feature is not available or if it's not a P/R.
*/
@CheckForNull
String targetBranchName();
/**
* The key of the pull request.
*
* @throws IllegalStateException if this branch configuration is not a pull request.
*/
String pullRequestKey();
}
| 2,639 | 34.2 | 149 | java |
sonarqube | sonarqube-master/sonar-scanner-engine/src/main/java/org/sonar/scanner/scan/branch/BranchConfigurationLoader.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.scan.branch;
import java.util.Map;
import org.sonar.api.scanner.ScannerSide;
@ScannerSide
public interface BranchConfigurationLoader {
BranchConfiguration load(Map<String, String> projectSettings, ProjectBranches branches);
}
| 1,099 | 36.931034 | 90 | java |
sonarqube | sonarqube-master/sonar-scanner-engine/src/main/java/org/sonar/scanner/scan/branch/BranchConfigurationProvider.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.scan.branch;
import javax.annotation.Nullable;
import org.sonar.api.utils.log.Logger;
import org.sonar.api.utils.log.Loggers;
import org.sonar.api.utils.log.Profiler;
import org.sonar.scanner.scan.ProjectConfiguration;
import org.springframework.context.annotation.Bean;
public class BranchConfigurationProvider {
private static final Logger LOG = Loggers.get(BranchConfigurationProvider.class);
private static final String LOG_MSG = "Load branch configuration";
@Bean("BranchConfiguration")
public BranchConfiguration provide(@Nullable BranchConfigurationLoader loader, ProjectConfiguration projectConfiguration, ProjectBranches branches) {
if (loader == null) {
return new DefaultBranchConfiguration();
} else {
Profiler profiler = Profiler.create(LOG).startInfo(LOG_MSG);
BranchConfiguration branchConfiguration = loader.load(projectConfiguration.getProperties(), branches);
profiler.stopInfo();
return branchConfiguration;
}
}
}
| 1,858 | 39.413043 | 151 | java |
sonarqube | sonarqube-master/sonar-scanner-engine/src/main/java/org/sonar/scanner/scan/branch/BranchInfo.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.scan.branch;
import javax.annotation.CheckForNull;
import javax.annotation.Nullable;
import javax.annotation.concurrent.Immutable;
/**
* Container class for information about a branch.
*/
@Immutable
public class BranchInfo {
private final String name;
private final BranchType type;
private final boolean isMain;
@Nullable
private final String branchTargetName;
public BranchInfo(String name, BranchType type, boolean isMain, @Nullable String branchTargetName) {
this.name = name;
this.type = type;
this.isMain = isMain;
this.branchTargetName = branchTargetName;
}
@CheckForNull
public String branchTargetName() {
return branchTargetName;
}
public String name() {
return name;
}
public BranchType type() {
return type;
}
public boolean isMain() {
return isMain;
}
}
| 1,708 | 27.016393 | 102 | java |
sonarqube | sonarqube-master/sonar-scanner-engine/src/main/java/org/sonar/scanner/scan/branch/BranchParamsValidator.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.scan.branch;
import java.util.List;
import org.sonar.api.scanner.ScannerSide;
@ScannerSide
public interface BranchParamsValidator {
void validate(List<String> validationMessages);
}
| 1,055 | 35.413793 | 75 | java |
sonarqube | sonarqube-master/sonar-scanner-engine/src/main/java/org/sonar/scanner/scan/branch/BranchType.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.scan.branch;
public enum BranchType {
BRANCH, PULL_REQUEST
}
| 933 | 36.36 | 75 | java |
sonarqube | sonarqube-master/sonar-scanner-engine/src/main/java/org/sonar/scanner/scan/branch/DefaultBranchConfiguration.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.scan.branch;
import javax.annotation.CheckForNull;
import javax.annotation.concurrent.Immutable;
@Immutable
public class DefaultBranchConfiguration implements BranchConfiguration {
@Override
public BranchType branchType() {
return BranchType.BRANCH;
}
@CheckForNull
@Override
public String branchName() {
return null;
}
@CheckForNull
@Override
public String targetBranchName() {
return null;
}
@CheckForNull
@Override
public String referenceBranchName() {
return null;
}
@Override
public String pullRequestKey() {
throw new IllegalStateException("Only a branch of type PULL_REQUEST can have a pull request id.");
}
}
| 1,548 | 27.163636 | 102 | java |
sonarqube | sonarqube-master/sonar-scanner-engine/src/main/java/org/sonar/scanner/scan/branch/ProjectBranches.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.scan.branch;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import javax.annotation.CheckForNull;
import javax.annotation.concurrent.Immutable;
/**
* Container class for information about the branches of a project.
*/
@Immutable
public class ProjectBranches {
// matches server-side default when creating a project. See BranchDto#DEFAULT_MAIN_BRANCH_NAME
private static final String DEFAULT_MAIN_BRANCH_NAME = "main";
private final Map<String, BranchInfo> branches;
private final String defaultBranchName;
public ProjectBranches(List<BranchInfo> branchInfos) {
this.branches = new HashMap<>();
String mainBranchName = null;
for (BranchInfo branch : branchInfos) {
String branchName = branch.name();
this.branches.put(branchName, branch);
if (branch.isMain()) {
mainBranchName = branchName;
}
}
this.defaultBranchName = Objects.requireNonNullElse(mainBranchName, DEFAULT_MAIN_BRANCH_NAME);
}
@CheckForNull
public BranchInfo get(String name) {
return branches.get(name);
}
public boolean isEmpty() {
return branches.isEmpty();
}
public String defaultBranchName() {
return defaultBranchName;
}
}
| 2,112 | 30.537313 | 98 | java |
sonarqube | sonarqube-master/sonar-scanner-engine/src/main/java/org/sonar/scanner/scan/branch/ProjectBranchesLoader.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.scan.branch;
import org.sonar.api.scanner.ScannerSide;
@ScannerSide
public interface ProjectBranchesLoader {
/**
* Load the branches of a project.
*/
ProjectBranches load(String projectKey);
}
| 1,076 | 31.636364 | 75 | java |
sonarqube | sonarqube-master/sonar-scanner-engine/src/main/java/org/sonar/scanner/scan/branch/ProjectBranchesProvider.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.scan.branch;
import java.util.Collections;
import javax.annotation.Nullable;
import org.sonar.api.utils.log.Logger;
import org.sonar.api.utils.log.Loggers;
import org.sonar.api.utils.log.Profiler;
import org.sonar.scanner.bootstrap.ScannerProperties;
import org.springframework.context.annotation.Bean;
public class ProjectBranchesProvider {
private static final Logger LOG = Loggers.get(ProjectBranchesProvider.class);
private static final String LOG_MSG = "Load project branches";
@Bean("ProjectBranches")
public ProjectBranches provide(@Nullable ProjectBranchesLoader loader, ScannerProperties scannerProperties) {
if (loader == null) {
return new ProjectBranches(Collections.emptyList());
}
Profiler profiler = Profiler.create(LOG).startInfo(LOG_MSG);
ProjectBranches branches = loader.load(scannerProperties.getProjectKey());
profiler.stopInfo();
return branches;
}
}
| 1,787 | 37.042553 | 111 | java |
sonarqube | sonarqube-master/sonar-scanner-engine/src/main/java/org/sonar/scanner/scan/branch/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.scan.branch;
import javax.annotation.ParametersAreNonnullByDefault;
| 969 | 39.416667 | 75 | java |
sonarqube | sonarqube-master/sonar-scanner-engine/src/main/java/org/sonar/scanner/scan/filesystem/AbstractCoverageAndDuplicationExclusions.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.scan.filesystem;
import java.util.Collection;
import java.util.function.Function;
import java.util.stream.Collectors;
import java.util.stream.Stream;
import javax.annotation.concurrent.Immutable;
import org.sonar.api.CoreProperties;
import org.sonar.api.utils.WildcardPattern;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.sonar.api.batch.fs.internal.DefaultInputFile;
import static java.util.stream.Collectors.toList;
@Immutable
public abstract class AbstractCoverageAndDuplicationExclusions {
private static final Logger LOG = LoggerFactory.getLogger(AbstractCoverageAndDuplicationExclusions.class);
private final Function<DefaultInputFile, String> pathExtractor;
private final String[] coverageExclusionConfig;
private final String[] duplicationExclusionConfig;
private final Collection<WildcardPattern> coverageExclusionPatterns;
private final Collection<WildcardPattern> duplicationExclusionPatterns;
public AbstractCoverageAndDuplicationExclusions(Function<String, String[]> configProvider, Function<DefaultInputFile, String> pathExtractor) {
this.pathExtractor = pathExtractor;
coverageExclusionConfig = configProvider.apply(CoreProperties.PROJECT_COVERAGE_EXCLUSIONS_PROPERTY);
coverageExclusionPatterns = Stream.of(coverageExclusionConfig).map(WildcardPattern::create).collect(toList());
duplicationExclusionConfig = configProvider.apply(CoreProperties.CPD_EXCLUSIONS);
duplicationExclusionPatterns = Stream.of(duplicationExclusionConfig).map(WildcardPattern::create).collect(toList());
}
public String[] getCoverageExclusionConfig() {
return coverageExclusionConfig;
}
public String[] getDuplicationExclusionConfig() {
return duplicationExclusionConfig;
}
void log(String indent) {
if (!coverageExclusionPatterns.isEmpty()) {
log("Excluded sources for coverage:", coverageExclusionPatterns, indent);
}
if (!duplicationExclusionPatterns.isEmpty()) {
log("Excluded sources for duplication:", duplicationExclusionPatterns, indent);
}
}
public boolean isExcludedForCoverage(DefaultInputFile file) {
return isExcluded(file, coverageExclusionPatterns);
}
public boolean isExcludedForDuplication(DefaultInputFile file) {
return isExcluded(file, duplicationExclusionPatterns);
}
private boolean isExcluded(DefaultInputFile file, Collection<WildcardPattern> patterns) {
if (patterns.isEmpty()) {
return false;
}
final String path = pathExtractor.apply(file);
return patterns
.stream()
.anyMatch(p -> p.match(path));
}
private static void log(String title, Collection<WildcardPattern> patterns, String ident) {
if (!patterns.isEmpty()) {
LOG.info("{}{} {}", ident, title, patterns.stream().map(WildcardPattern::toString).collect(Collectors.joining(", ")));
}
}
}
| 3,722 | 38.606383 | 144 | java |
sonarqube | sonarqube-master/sonar-scanner-engine/src/main/java/org/sonar/scanner/scan/filesystem/AbstractExclusionFilters.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.scan.filesystem;
import java.nio.file.Path;
import java.util.Arrays;
import java.util.function.Function;
import java.util.stream.Collectors;
import java.util.stream.Stream;
import org.apache.commons.lang.ArrayUtils;
import org.apache.commons.lang.StringUtils;
import org.sonar.api.CoreProperties;
import org.sonar.api.batch.fs.InputFile;
import org.sonar.api.batch.fs.internal.PathPattern;
import org.sonar.api.notifications.AnalysisWarnings;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import static java.lang.String.format;
import static org.sonar.api.CoreProperties.PROJECT_TESTS_EXCLUSIONS_PROPERTY;
import static org.sonar.api.CoreProperties.PROJECT_TESTS_INCLUSIONS_PROPERTY;
import static org.sonar.api.CoreProperties.PROJECT_TEST_EXCLUSIONS_PROPERTY;
import static org.sonar.api.CoreProperties.PROJECT_TEST_INCLUSIONS_PROPERTY;
public abstract class AbstractExclusionFilters {
private static final Logger LOG = LoggerFactory.getLogger(AbstractExclusionFilters.class);
private static final String WARNING_ALIAS_PROPERTY_USAGE = "Use of %s detected. While being taken into account, the only supported property is %s." +
" Consider updating your configuration.";
private static final String WARNING_LEGACY_AND_ALIAS_PROPERTIES_USAGE =
"Use of %s and %s at the same time. %s is taken into account. Consider updating your configuration";
private final AnalysisWarnings analysisWarnings;
private final String[] sourceInclusions;
private final String[] testInclusions;
private final String[] sourceExclusions;
private final String[] testExclusions;
private PathPattern[] mainInclusionsPattern;
private PathPattern[] mainExclusionsPattern;
private PathPattern[] testInclusionsPattern;
private PathPattern[] testExclusionsPattern;
protected AbstractExclusionFilters(AnalysisWarnings analysisWarnings, Function<String, String[]> configProvider) {
this.analysisWarnings = analysisWarnings;
this.sourceInclusions = inclusions(configProvider, CoreProperties.PROJECT_INCLUSIONS_PROPERTY);
this.sourceExclusions = exclusions(configProvider, CoreProperties.GLOBAL_EXCLUSIONS_PROPERTY, CoreProperties.PROJECT_EXCLUSIONS_PROPERTY);
String[] testInclusionsFromLegacy = inclusions(configProvider, PROJECT_TEST_INCLUSIONS_PROPERTY);
String[] testInclusionsFromAlias = inclusions(configProvider, PROJECT_TESTS_INCLUSIONS_PROPERTY);
this.testInclusions = keepInclusionTestBetweenLegacyAndAliasProperties(testInclusionsFromLegacy, testInclusionsFromAlias);
String[] testExclusionsFromLegacy = exclusions(configProvider, CoreProperties.GLOBAL_TEST_EXCLUSIONS_PROPERTY, PROJECT_TEST_EXCLUSIONS_PROPERTY);
String[] testExclusionsFromAlias = exclusions(configProvider, CoreProperties.GLOBAL_TEST_EXCLUSIONS_PROPERTY, PROJECT_TESTS_EXCLUSIONS_PROPERTY);
this.testExclusions = keepExclusionTestBetweenLegacyAndAliasProperties(testExclusionsFromLegacy, testExclusionsFromAlias);
this.mainInclusionsPattern = prepareMainInclusions(sourceInclusions);
this.mainExclusionsPattern = prepareMainExclusions(sourceExclusions, this.testInclusions);
this.testInclusionsPattern = prepareTestInclusions(this.testInclusions);
this.testExclusionsPattern = prepareTestExclusions(this.testExclusions);
}
private String[] keepExclusionTestBetweenLegacyAndAliasProperties(String[] fromLegacyProperty, String[] fromAliasProperty) {
if (fromAliasProperty.length == 0) {
return fromLegacyProperty;
}
if (fromLegacyProperty.length == 0) {
logWarningForAliasUsage(PROJECT_TEST_EXCLUSIONS_PROPERTY, PROJECT_TESTS_EXCLUSIONS_PROPERTY);
return fromAliasProperty;
}
logWarningForLegacyAndAliasUsage(PROJECT_TEST_EXCLUSIONS_PROPERTY, PROJECT_TESTS_EXCLUSIONS_PROPERTY);
return fromLegacyProperty;
}
private String[] keepInclusionTestBetweenLegacyAndAliasProperties(String[] fromLegacyProperty, String[] fromAliasProperty) {
if (fromAliasProperty.length == 0) {
return fromLegacyProperty;
}
if (fromLegacyProperty.length == 0) {
logWarningForAliasUsage(PROJECT_TEST_INCLUSIONS_PROPERTY, PROJECT_TESTS_INCLUSIONS_PROPERTY);
return fromAliasProperty;
}
logWarningForLegacyAndAliasUsage(PROJECT_TEST_INCLUSIONS_PROPERTY, PROJECT_TESTS_INCLUSIONS_PROPERTY);
return fromLegacyProperty;
}
private void logWarningForAliasUsage(String legacyProperty, String aliasProperty) {
logWarning(format(WARNING_ALIAS_PROPERTY_USAGE, aliasProperty, legacyProperty));
}
private void logWarningForLegacyAndAliasUsage(String legacyProperty, String aliasProperty) {
logWarning(format(WARNING_LEGACY_AND_ALIAS_PROPERTIES_USAGE, legacyProperty, aliasProperty, legacyProperty));
}
private void logWarning(String warning) {
LOG.warn(warning);
analysisWarnings.addUnique(warning);
}
public void log(String indent) {
log("Included sources:", mainInclusionsPattern, indent);
log("Excluded sources:", mainExclusionsPattern, indent);
log("Included tests:", testInclusionsPattern, indent);
log("Excluded tests:", testExclusionsPattern, indent);
}
private String[] inclusions(Function<String, String[]> configProvider, String propertyKey) {
return Arrays.stream(configProvider.apply(propertyKey))
.map(StringUtils::trim)
.filter(s -> !"**/*".equals(s))
.filter(s -> !"file:**/*".equals(s))
.toArray(String[]::new);
}
private String[] exclusions(Function<String, String[]> configProvider, String globalExclusionsProperty, String exclusionsProperty) {
String[] globalExclusions = configProvider.apply(globalExclusionsProperty);
String[] exclusions = configProvider.apply(exclusionsProperty);
return Stream.concat(Arrays.stream(globalExclusions), Arrays.stream(exclusions))
.map(StringUtils::trim)
.toArray(String[]::new);
}
public boolean hasPattern() {
return mainInclusionsPattern.length > 0 || mainExclusionsPattern.length > 0 || testInclusionsPattern.length > 0 || testExclusionsPattern.length > 0;
}
private static void log(String title, PathPattern[] patterns, String indent) {
if (patterns.length > 0) {
LOG.info("{}{} {}", indent, title, Arrays.stream(patterns).map(PathPattern::toString).collect(Collectors.joining(", ")));
}
}
private static PathPattern[] prepareMainInclusions(String[] sourceInclusions) {
if (sourceInclusions.length > 0) {
// User defined params
return PathPattern.create(sourceInclusions);
}
return new PathPattern[0];
}
private static PathPattern[] prepareTestInclusions(String[] testInclusions) {
return PathPattern.create(testInclusions);
}
static PathPattern[] prepareMainExclusions(String[] sourceExclusions, String[] testInclusions) {
String[] patterns = (String[]) ArrayUtils.addAll(
sourceExclusions, testInclusions);
return PathPattern.create(patterns);
}
private static PathPattern[] prepareTestExclusions(String[] testExclusions) {
return PathPattern.create(testExclusions);
}
public String[] getInclusionsConfig(InputFile.Type type) {
return type == InputFile.Type.MAIN ? sourceInclusions : testInclusions;
}
public String[] getExclusionsConfig(InputFile.Type type) {
return type == InputFile.Type.MAIN ? sourceExclusions : testExclusions;
}
public boolean isIncluded(Path absolutePath, Path relativePath, InputFile.Type type) {
PathPattern[] inclusionPatterns = InputFile.Type.MAIN == type ? mainInclusionsPattern : testInclusionsPattern;
if (inclusionPatterns.length == 0) {
return true;
}
for (PathPattern pattern : inclusionPatterns) {
if (pattern.match(absolutePath, relativePath)) {
return true;
}
}
return false;
}
public boolean isExcluded(Path absolutePath, Path relativePath, InputFile.Type type) {
PathPattern[] exclusionPatterns = InputFile.Type.MAIN == type ? mainExclusionsPattern : testExclusionsPattern;
for (PathPattern pattern : exclusionPatterns) {
if (pattern.match(absolutePath, relativePath)) {
return true;
}
}
return false;
}
/**
* <p>Checks if the file should be excluded as a parent directory of excluded files and subdirectories.</p>
*
* @param absolutePath The full path of the file.
* @param relativePath The relative path of the file.
* @param baseDir The base directory of the project.
* @param type The file type.
* @return True if the file should be excluded, false otherwise.
*/
public boolean isExcludedAsParentDirectoryOfExcludedChildren(Path absolutePath, Path relativePath, Path baseDir, InputFile.Type type) {
PathPattern[] exclusionPatterns = InputFile.Type.MAIN == type ? mainExclusionsPattern : testExclusionsPattern;
return Stream.of(exclusionPatterns)
.map(PathPattern::toString)
.filter(ps -> ps.endsWith("/**/*"))
.map(ps -> ps.substring(0, ps.length() - 5))
.map(baseDir::resolve)
.anyMatch(exclusionRootPath -> absolutePath.startsWith(exclusionRootPath)
|| PathPattern.create(exclusionRootPath.toString()).match(absolutePath, relativePath));
}
}
| 10,041 | 42.851528 | 152 | java |
sonarqube | sonarqube-master/sonar-scanner-engine/src/main/java/org/sonar/scanner/scan/filesystem/AdditionalFilePredicates.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.scan.filesystem;
import org.sonar.api.batch.fs.InputFile;
import org.sonar.api.batch.fs.internal.predicates.AbstractFilePredicate;
/**
* Additional {@link org.sonar.api.batch.fs.FilePredicate}s that are
* not published in public API
*/
class AdditionalFilePredicates {
private AdditionalFilePredicates() {
// only static inner classes
}
static class KeyPredicate extends AbstractFilePredicate {
private final String key;
KeyPredicate(String key) {
this.key = key;
}
@Override
public boolean apply(InputFile f) {
return key.equals(f.key());
}
}
}
| 1,473 | 29.081633 | 75 | java |
sonarqube | sonarqube-master/sonar-scanner-engine/src/main/java/org/sonar/scanner/scan/filesystem/ByteCharsetDetector.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.scan.filesystem;
import java.nio.charset.Charset;
import java.util.Arrays;
import javax.annotation.CheckForNull;
import org.apache.commons.io.ByteOrderMark;
import org.sonar.scanner.scan.filesystem.CharsetValidation.Result;
import org.sonar.scanner.scan.filesystem.CharsetValidation.Validation;
import static java.nio.charset.StandardCharsets.UTF_16;
import static java.nio.charset.StandardCharsets.UTF_16BE;
import static java.nio.charset.StandardCharsets.UTF_16LE;
import static java.nio.charset.StandardCharsets.UTF_8;
public class ByteCharsetDetector {
// these needs to be sorted by longer first!
private static final ByteOrderMark[] boms = {ByteOrderMark.UTF_8, ByteOrderMark.UTF_32LE, ByteOrderMark.UTF_32BE,
ByteOrderMark.UTF_16LE, ByteOrderMark.UTF_16BE};
private final Charset userConfiguration;
private final CharsetValidation validator;
public ByteCharsetDetector(CharsetValidation validator, Charset userConfiguration) {
this.validator = validator;
this.userConfiguration = userConfiguration;
}
@CheckForNull
public Charset detect(byte[] buf) {
// Try UTF-8 first since we are very confident in it if it's a yes.
// Fail if we see nulls to not have FPs if the text is ASCII encoded in UTF-16.
Result utf8Result = validator.isUTF8(buf, true);
if (utf8Result.valid() == Validation.YES) {
return utf8Result.charset();
} else if (utf8Result.valid() == Validation.MAYBE) {
return detectAscii(buf);
}
// try UTF16 with both endiness. Fail if we see nulls to not have FPs if it's UTF-32.
Result utf16 = validator.isUTF16(buf, true);
if (utf16.valid() == Validation.YES && validator.isValidUTF16(buf, UTF_16LE.equals(utf16.charset()))) {
return utf16.charset();
}
// at this point we know it can't be UTF-8
Charset c = userConfiguration;
if (!UTF_8.equals(c) && (!isUtf16(c) || utf16.valid() == Validation.MAYBE) && validator.tryDecode(buf, c)) {
return c;
}
Result windows1252 = validator.isValidWindows1252(buf);
if (windows1252.valid() == Validation.MAYBE) {
return windows1252.charset();
}
return null;
}
private Charset detectAscii(byte[] buf) {
if (!isUtf16Or32(userConfiguration) && validator.tryDecode(buf, userConfiguration)) {
return userConfiguration;
}
return null;
}
private static boolean isUtf16(Charset charset) {
return UTF_16.equals(charset) || UTF_16BE.equals(charset) || UTF_16LE.equals(charset);
}
private static boolean isUtf16Or32(Charset charset) {
return isUtf16(charset) || MetadataGenerator.UTF_32BE.equals(charset) || MetadataGenerator.UTF_32LE.equals(charset);
}
@CheckForNull
public ByteOrderMark detectBOM(byte[] buffer) {
return Arrays.stream(boms)
.filter(b -> isBom(b, buffer))
.findAny()
.orElse(null);
}
private static boolean isBom(ByteOrderMark bom, byte[] buffer) {
if (buffer.length < bom.length()) {
return false;
}
for (int i = 0; i < bom.length(); i++) {
if ((byte) bom.get(i) != buffer[i]) {
return false;
}
}
return true;
}
}
| 4,010 | 33.878261 | 120 | java |
sonarqube | sonarqube-master/sonar-scanner-engine/src/main/java/org/sonar/scanner/scan/filesystem/CharsetDetector.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.scan.filesystem;
import java.io.BufferedInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.nio.charset.Charset;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.Arrays;
import javax.annotation.CheckForNull;
import org.apache.commons.io.ByteOrderMark;
import org.apache.commons.io.IOUtils;
public class CharsetDetector {
private static final int BYTES_TO_DECODE = 4192;
private final Path filePath;
private BufferedInputStream stream;
private Charset detectedCharset;
private Charset userEncoding;
public CharsetDetector(Path filePath, Charset userEncoding) {
this.filePath = filePath;
this.userEncoding = userEncoding;
}
public boolean run() {
try {
byte[] buf = readBuffer();
return detectCharset(buf);
} catch (IOException e) {
throw new IllegalStateException("Unable to read file " + filePath.toAbsolutePath(), e);
}
}
@CheckForNull
public Charset charset() {
assertRun();
return detectedCharset;
}
public InputStream inputStream() {
assertRun();
return stream;
}
private byte[] readBuffer() throws IOException {
stream = new BufferedInputStream(Files.newInputStream(filePath), BYTES_TO_DECODE * 2);
stream.mark(BYTES_TO_DECODE);
byte[] buf = new byte[BYTES_TO_DECODE];
int read = IOUtils.read(stream, buf, 0, BYTES_TO_DECODE);
stream.reset();
stream.mark(-1);
return Arrays.copyOf(buf, read);
}
private boolean detectCharset(byte[] buf) throws IOException {
ByteCharsetDetector detector = new ByteCharsetDetector(new CharsetValidation(), userEncoding);
ByteOrderMark bom = detector.detectBOM(buf);
if (bom != null) {
detectedCharset = Charset.forName(bom.getCharsetName());
stream.skip(bom.length());
return true;
}
detectedCharset = detector.detect(buf);
return detectedCharset != null;
}
private void assertRun() {
if (stream == null) {
throw new IllegalStateException("Charset detection did not run");
}
}
}
| 2,925 | 30.12766 | 98 | java |
sonarqube | sonarqube-master/sonar-scanner-engine/src/main/java/org/sonar/scanner/scan/filesystem/CharsetValidation.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.scan.filesystem;
import java.nio.ByteBuffer;
import java.nio.charset.CharacterCodingException;
import java.nio.charset.Charset;
import java.nio.charset.CharsetDecoder;
import java.nio.charset.CodingErrorAction;
import java.nio.charset.StandardCharsets;
import java.nio.charset.UnsupportedCharsetException;
import java.util.Arrays;
import javax.annotation.CheckForNull;
import javax.annotation.Nullable;
public class CharsetValidation {
private static final double UTF_16_NULL_PASS_THRESHOLD = 0.7;
private static final double UTF_16_NULL_FAIL_THRESHOLD = 0.1;
private static final boolean[] VALID_WINDOWS_1252 = new boolean[256];
static {
Arrays.fill(VALID_WINDOWS_1252, true);
// See the Undefined cells in the charset table on https://en.wikipedia.org/wiki/Windows-1252
VALID_WINDOWS_1252[129 - 128] = false;
VALID_WINDOWS_1252[141 - 128] = false;
VALID_WINDOWS_1252[143 - 128] = false;
VALID_WINDOWS_1252[144 - 128] = false;
VALID_WINDOWS_1252[157 - 128] = false;
}
/**
* Checks if an array of bytes looks UTF-16 encoded.
* We look for clues by checking the presence of nulls and new line control chars in both little and big endian byte orders.
* Failing on nulls will greatly reduce FPs if the buffer is actually encoded in UTF-32.
*
* Note that for any unicode between 0-255, UTF-16 encodes it directly in 2 bytes, being the first 0 (null). Since ASCII, ANSI and control chars are
* within this range, we look for number of nulls and see if it is above a certain threshold.
* It's possible to have valid chars that map to the opposite (non-null followed by a null) even though it is very unlike.
* That will happen, for example, for any unicode 0x??00, being ?? between 00 and D7. For this reason, we give a small maximum tolerance
* for opposite nulls (10%).
*
* Line feed code point (0x000A) reversed would be (0x0A00). This code point is reserved and should never be found.
*
*/
public Result isUTF16(byte[] buffer, boolean failOnNull) {
if (buffer.length < 2) {
return Result.INVALID;
}
int beAscii = 0;
int beLines = 0;
int leAscii = 0;
int leLines = 0;
for (int i = 0; i < buffer.length / 2; i++) {
// using bytes is fine, since we will compare with positive numbers only
byte c1 = buffer[i * 2];
byte c2 = buffer[i * 2 + 1];
if (c1 == 0) {
if (c2 != 0) {
if (c2 == 0x0a || c2 == 0x0d) {
beLines++;
}
beAscii++;
} else if (failOnNull) {
// it's probably UTF-32 or binary
return Result.INVALID;
}
} else if (c2 == 0) {
leAscii++;
if (c1 == 0x0a || c1 == 0x0d) {
leLines++;
}
}
}
double beAsciiPerc = beAscii * 2.0D / buffer.length;
double leAsciiPerc = leAscii * 2.0D / buffer.length;
if (leLines == 0) {
// could be BE
if (beAsciiPerc >= UTF_16_NULL_PASS_THRESHOLD && leAsciiPerc < UTF_16_NULL_FAIL_THRESHOLD) {
return Result.newValid(StandardCharsets.UTF_16BE);
}
if (beLines > 0) {
// this gives FPs for UTF-32 if !failOnNull
return Result.newValid(StandardCharsets.UTF_16BE);
}
} else if (beLines > 0) {
// lines detected with both endiness -> can't be utf-16
return Result.INVALID;
}
if (beLines == 0) {
// could be BE
if (leAsciiPerc >= UTF_16_NULL_PASS_THRESHOLD && beAsciiPerc < UTF_16_NULL_FAIL_THRESHOLD) {
return Result.newValid(StandardCharsets.UTF_16LE);
}
if (leLines > 0) {
// this gives FPs for UTF-32 if !failOnNull
return Result.newValid(StandardCharsets.UTF_16LE);
}
}
// if we reach here, means that there wasn't a line feed for a single endiness and we didn't see a strong null pattern for any of the
// endiness.
// It could happen if there are no line feeds in the text and it's a language that does not use ANSI (unicode > 255).
return new Result(Validation.MAYBE, null);
}
/**
* Checks whether it's a valid UTF-16-encoded buffer.
* Most sequences of bytes of any encoding will be valid UTF-16, so this is not very effective and gives
* often false positives.
*
* Possible 16bit values in UTF-16:
*
* 0x0000-0xD7FF: single 16bit block
* 0xD800-0xDBFF: first block
* 0xDC00-0xDFFF: second block
* 0XE000-0xFFFF: single 16 bit block
*
* The following UTF code points get mapped into 1 or 2 blocks:
* 0x0000 -0xD7FF (0 -55295) : 2 bytes, direct mapping
* 0xE000 -0xFFFF (57344-65535) : 2 bytes, direct mapping
* 0x10000-0x10FFFF (65536-1114111): 2 blocks of 2 bytes (not direct..)
*
* Note that Unicode 55296-57345 (0xD800 to 0xDFFF) are not used, since it's reserved and used in UTF-16 for the high/low surrogates.
*
* We reject 2-byte blocks with 0 (we consider it's binary) even though it's a valid UTF-16 encoding.
*
*/
public boolean isValidUTF16(byte[] buffer) {
return isValidUTF16(buffer, false);
}
public boolean isValidUTF16(byte[] buffer, boolean le) {
if (buffer.length < 2) {
return false;
}
for (int i = 0; i < buffer.length / 2; i++) {
boolean extraByte = false;
int c = read16bit(buffer, i, le);
if (c >= 0xD800 && c < 0xDC00) {
// it's a higher surrogate (10 bits)
extraByte = true;
i++;
} else if ((c >= 0xDC00 && c < 0xE000) || c == 0) {
return false;
}
// else it is a simple 2 byte encoding (code points in BMP), and it's valid
if (extraByte && i < buffer.length / 2) {
c = read16bit(buffer, i, le);
if (c < 0xDC00 || c >= 0xE000) {
// invalid lower surrogate (10 bits)
return false;
}
}
}
return true;
}
/**
* Checks if a buffer contains only valid UTF8 encoded bytes.
* It's very effective, giving a clear YES/NO, unless it's ASCII (unicode < 127), in which case it returns MAYBE.
*
*
* First byte:
* 0xxxxxxx: only one byte (0-127)
* 110xxxxx: 2 bytes (194-223, as 192/193 are invalid)
* 1110xxxx: 3 bytes (224-239)
* 11110xxx: 4 bytes (240-244)
*
* Bytes 2,3 and 4 are always 10xxxxxx (0x80-0xBF or 128-191).
*
* So depending on the number of significant bits in the unicode code point, the length will be 1,2,3 or 4 bytes:
* 0 -7 bits (0x0000-007F): 1 byte encoding
* 8 -11 bits (0x0080-07FF): 2 bytes encoding
* 12-16 bits (0x0800-FFFF): 3 bytes encoding
* 17-21 bits (0x10000-10FFFF): 4 bytes encoding
*/
public Result isUTF8(byte[] buffer, boolean rejectNulls) {
boolean onlyAscii = true;
for (int i = 0; i < buffer.length; i++) {
byte len;
// make it unsigned for the comparisons
int c = (0xFF) & buffer[i];
if (rejectNulls && c == 0) {
return Result.INVALID;
}
if ((c & 0b10000000) == 0) {
len = 0;
} else if (c >= 194 && c < 224) {
len = 1;
} else if ((c & 0b11110000) == 0b11100000) {
len = 2;
} else if ((c & 0b11111000) == 0b11110000) {
len = 3;
} else {
return Result.INVALID;
}
while (len > 0) {
i++;
if (i >= buffer.length) {
break;
}
c = (0xFF) & buffer[i];
onlyAscii = false;
// first 2 bits should be 10
if ((c & 0b11000000) != 0b10000000) {
return Result.INVALID;
}
len--;
}
}
return onlyAscii ? new Result(Validation.MAYBE, StandardCharsets.UTF_8) : Result.newValid(StandardCharsets.UTF_8);
}
/**
* Tries to use the given charset to decode the byte array.
* @return true if decoding succeeded, false if there was a decoding error.
*/
public boolean tryDecode(byte[] bytes, @Nullable Charset charset) {
if (charset == null) {
return false;
}
CharsetDecoder decoder = charset.newDecoder()
.onMalformedInput(CodingErrorAction.REPORT)
.onUnmappableCharacter(CodingErrorAction.REPORT);
try {
decoder.decode(ByteBuffer.wrap(bytes));
} catch (CharacterCodingException e) {
return false;
}
return true;
}
private static int read16bit(byte[] buffer, int i, boolean le) {
return le ? (buffer[i / 2] & 0xff) | ((buffer[i / 2 + 1] & 0xff) << 8)
: ((buffer[i / 2] & 0xff) << 8) | (buffer[i / 2 + 1] & 0xff);
}
/**
* Verify that the buffer doesn't contain bytes that are not supposed to be used by Windows-1252.
*
* @return Result object with Validation.MAYBE and Windows-1252 if no unknown characters are used,
* otherwise Result.INVALID
* @param buf byte buffer to validate
*/
public Result isValidWindows1252(byte[] buf) {
for (byte b : buf) {
if (!VALID_WINDOWS_1252[b + 128]) {
return Result.INVALID;
}
}
try {
return new Result(Validation.MAYBE, Charset.forName("Windows-1252"));
} catch (UnsupportedCharsetException e) {
return Result.INVALID;
}
}
public enum Validation {
NO,
YES,
MAYBE
}
public static class Result {
static final Result INVALID = new Result(Validation.NO, null);
private Validation valid;
private Charset charset;
public Result(Validation valid, @Nullable Charset charset) {
this.valid = valid;
this.charset = charset;
}
public static Result newValid(Charset charset) {
return new Result(Validation.YES, charset);
}
public Validation valid() {
return valid;
}
/**
* Only non-null if Valid.Yes
*/
@CheckForNull
public Charset charset() {
return charset;
}
}
}
| 10,614 | 31.863777 | 150 | java |
sonarqube | sonarqube-master/sonar-scanner-engine/src/main/java/org/sonar/scanner/scan/filesystem/DefaultModuleFileSystem.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.scan.filesystem;
import org.sonar.api.batch.fs.internal.DefaultInputModule;
import org.sonar.api.batch.fs.internal.predicates.DefaultFilePredicates;
import javax.annotation.Priority;
import javax.inject.Inject;
@Priority(1)
public class DefaultModuleFileSystem extends MutableFileSystem {
@Inject
public DefaultModuleFileSystem(ModuleInputComponentStore moduleInputFileCache, DefaultInputModule module) {
super(module.getBaseDir(), moduleInputFileCache, new DefaultFilePredicates(module.getBaseDir()));
initFields(module);
}
public DefaultModuleFileSystem(DefaultInputModule module) {
super(module.getBaseDir());
initFields(module);
}
private void initFields(DefaultInputModule module) {
setWorkDir(module.getWorkDir());
setEncoding(module.getEncoding());
}
}
| 1,674 | 33.895833 | 109 | java |
sonarqube | sonarqube-master/sonar-scanner-engine/src/main/java/org/sonar/scanner/scan/filesystem/DefaultProjectFileSystem.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.scan.filesystem;
import org.sonar.api.batch.fs.internal.DefaultInputProject;
import org.sonar.api.batch.fs.internal.predicates.DefaultFilePredicates;
import javax.annotation.Priority;
import javax.inject.Inject;
@Priority(2)
public class DefaultProjectFileSystem extends MutableFileSystem {
@Inject
public DefaultProjectFileSystem(InputComponentStore inputComponentStore, DefaultInputProject project) {
super(project.getBaseDir(), inputComponentStore, new DefaultFilePredicates(project.getBaseDir()));
setFields(project);
}
public DefaultProjectFileSystem(DefaultInputProject project) {
super(project.getBaseDir());
setFields(project);
}
private void setFields(DefaultInputProject project) {
setWorkDir(project.getWorkDir());
setEncoding(project.getEncoding());
}
}
| 1,680 | 34.020833 | 105 | java |
sonarqube | sonarqube-master/sonar-scanner-engine/src/main/java/org/sonar/scanner/scan/filesystem/FileIndexer.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.scan.filesystem;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.LinkOption;
import java.nio.file.Path;
import java.util.Arrays;
import java.util.function.BooleanSupplier;
import javax.annotation.Nullable;
import org.apache.commons.io.FilenameUtils;
import org.sonar.api.CoreProperties;
import org.sonar.api.batch.fs.InputFile;
import org.sonar.api.batch.fs.InputFile.Type;
import org.sonar.api.batch.fs.InputFileFilter;
import org.sonar.api.batch.fs.internal.DefaultIndexedFile;
import org.sonar.api.batch.fs.internal.DefaultInputFile;
import org.sonar.api.batch.fs.internal.DefaultInputModule;
import org.sonar.api.batch.fs.internal.DefaultInputProject;
import org.sonar.api.batch.fs.internal.SensorStrategy;
import org.sonar.api.batch.scm.IgnoreCommand;
import org.sonar.api.notifications.AnalysisWarnings;
import org.sonar.api.utils.MessageException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.sonar.scanner.issue.ignore.scanner.IssueExclusionsLoader;
import org.sonar.scanner.repository.language.Language;
import org.sonar.scanner.scan.ScanProperties;
import org.sonar.scanner.scm.ScmChangedFiles;
import org.sonar.scanner.util.ProgressReport;
import static java.lang.String.format;
/**
* Index input files into {@link InputComponentStore}.
*/
public class FileIndexer {
private static final Logger LOG = LoggerFactory.getLogger(FileIndexer.class);
private final AnalysisWarnings analysisWarnings;
private final ScanProperties properties;
private final InputFileFilter[] filters;
private final ProjectExclusionFilters projectExclusionFilters;
private final ProjectCoverageAndDuplicationExclusions projectCoverageAndDuplicationExclusions;
private final IssueExclusionsLoader issueExclusionsLoader;
private final MetadataGenerator metadataGenerator;
private final DefaultInputProject project;
private final ScannerComponentIdGenerator scannerComponentIdGenerator;
private final InputComponentStore componentStore;
private final SensorStrategy sensorStrategy;
private final LanguageDetection langDetection;
private final StatusDetection statusDetection;
private final ScmChangedFiles scmChangedFiles;
private boolean warnInclusionsAlreadyLogged;
private boolean warnExclusionsAlreadyLogged;
private boolean warnCoverageExclusionsAlreadyLogged;
private boolean warnDuplicationExclusionsAlreadyLogged;
public FileIndexer(DefaultInputProject project, ScannerComponentIdGenerator scannerComponentIdGenerator, InputComponentStore componentStore,
ProjectExclusionFilters projectExclusionFilters, ProjectCoverageAndDuplicationExclusions projectCoverageAndDuplicationExclusions, IssueExclusionsLoader issueExclusionsLoader,
MetadataGenerator metadataGenerator, SensorStrategy sensorStrategy, LanguageDetection languageDetection, AnalysisWarnings analysisWarnings, ScanProperties properties,
InputFileFilter[] filters, ScmChangedFiles scmChangedFiles, StatusDetection statusDetection) {
this.project = project;
this.scannerComponentIdGenerator = scannerComponentIdGenerator;
this.componentStore = componentStore;
this.projectCoverageAndDuplicationExclusions = projectCoverageAndDuplicationExclusions;
this.issueExclusionsLoader = issueExclusionsLoader;
this.metadataGenerator = metadataGenerator;
this.sensorStrategy = sensorStrategy;
this.langDetection = languageDetection;
this.analysisWarnings = analysisWarnings;
this.properties = properties;
this.filters = filters;
this.projectExclusionFilters = projectExclusionFilters;
this.scmChangedFiles = scmChangedFiles;
this.statusDetection = statusDetection;
}
void indexFile(DefaultInputModule module, ModuleExclusionFilters moduleExclusionFilters, ModuleCoverageAndDuplicationExclusions moduleCoverageAndDuplicationExclusions,
Path sourceFile, Type type, ProgressReport progressReport, ProjectFileIndexer.ExclusionCounter exclusionCounter, @Nullable IgnoreCommand ignoreCommand)
throws IOException {
// get case of real file without resolving link
Path realAbsoluteFile = sourceFile.toRealPath(LinkOption.NOFOLLOW_LINKS).toAbsolutePath().normalize();
Path projectRelativePath = project.getBaseDir().relativize(realAbsoluteFile);
Path moduleRelativePath = module.getBaseDir().relativize(realAbsoluteFile);
boolean included = evaluateInclusionsFilters(moduleExclusionFilters, realAbsoluteFile, projectRelativePath, moduleRelativePath, type);
if (!included) {
exclusionCounter.increaseByPatternsCount();
return;
}
boolean excluded = evaluateExclusionsFilters(moduleExclusionFilters, realAbsoluteFile, projectRelativePath, moduleRelativePath, type);
if (excluded) {
exclusionCounter.increaseByPatternsCount();
return;
}
if (!realAbsoluteFile.startsWith(project.getBaseDir())) {
LOG.warn("File '{}' is ignored. It is not located in project basedir '{}'.", realAbsoluteFile.toAbsolutePath(), project.getBaseDir());
return;
}
if (!realAbsoluteFile.startsWith(module.getBaseDir())) {
LOG.warn("File '{}' is ignored. It is not located in module basedir '{}'.", realAbsoluteFile.toAbsolutePath(), module.getBaseDir());
return;
}
if (Files.exists(realAbsoluteFile) && isFileSizeBiggerThanLimit(realAbsoluteFile)) {
LOG.warn("File '{}' is bigger than {}MB and as consequence is removed from the analysis scope.", realAbsoluteFile.toAbsolutePath(), properties.fileSizeLimit());
return;
}
Language language = langDetection.language(realAbsoluteFile, projectRelativePath);
if (ignoreCommand != null && ignoreCommand.isIgnored(realAbsoluteFile)) {
LOG.debug("File '{}' is excluded by the scm ignore settings.", realAbsoluteFile);
exclusionCounter.increaseByScmCount();
return;
}
DefaultIndexedFile indexedFile = new DefaultIndexedFile(
realAbsoluteFile,
project.key(),
projectRelativePath.toString(),
moduleRelativePath.toString(),
type,
language != null ? language.key() : null,
scannerComponentIdGenerator.getAsInt(),
sensorStrategy,
scmChangedFiles.getOldRelativeFilePath(realAbsoluteFile)
);
DefaultInputFile inputFile = new DefaultInputFile(indexedFile, f -> metadataGenerator.setMetadata(module.key(), f, module.getEncoding()),
f -> f.setStatus(statusDetection.findStatusFromScm(f)));
if (language != null && language.isPublishAllFiles()) {
inputFile.setPublished(true);
}
if (!accept(inputFile)) {
return;
}
checkIfAlreadyIndexed(inputFile);
componentStore.put(module.key(), inputFile);
issueExclusionsLoader.addMulticriteriaPatterns(inputFile);
String langStr = inputFile.language() != null ? format("with language '%s'", inputFile.language()) : "with no language";
LOG.debug("'{}' indexed {}{}", projectRelativePath, type == Type.TEST ? "as test " : "", langStr);
evaluateCoverageExclusions(moduleCoverageAndDuplicationExclusions, inputFile);
evaluateDuplicationExclusions(moduleCoverageAndDuplicationExclusions, inputFile);
if (properties.preloadFileMetadata()) {
inputFile.checkMetadata();
}
int count = componentStore.inputFiles().size();
progressReport.message(count + " " + pluralizeFiles(count) + " indexed... (last one was " + inputFile.getProjectRelativePath() + ")");
}
private boolean evaluateInclusionsFilters(ModuleExclusionFilters moduleExclusionFilters, Path realAbsoluteFile, Path projectRelativePath, Path moduleRelativePath,
InputFile.Type type) {
if (!Arrays.equals(moduleExclusionFilters.getInclusionsConfig(type), projectExclusionFilters.getInclusionsConfig(type))) {
// Module specific configuration
return moduleExclusionFilters.isIncluded(realAbsoluteFile, moduleRelativePath, type);
}
boolean includedByProjectConfiguration = projectExclusionFilters.isIncluded(realAbsoluteFile, projectRelativePath, type);
if (includedByProjectConfiguration) {
return true;
} else if (moduleExclusionFilters.isIncluded(realAbsoluteFile, moduleRelativePath, type)) {
warnOnce(
type == Type.MAIN ? CoreProperties.PROJECT_INCLUSIONS_PROPERTY : CoreProperties.PROJECT_TEST_INCLUSIONS_PROPERTY,
FilenameUtils.normalize(projectRelativePath.toString(), true), () -> warnInclusionsAlreadyLogged, () -> warnInclusionsAlreadyLogged = true);
return true;
}
return false;
}
private boolean evaluateExclusionsFilters(ModuleExclusionFilters moduleExclusionFilters, Path realAbsoluteFile, Path projectRelativePath, Path moduleRelativePath,
InputFile.Type type) {
if (!Arrays.equals(moduleExclusionFilters.getExclusionsConfig(type), projectExclusionFilters.getExclusionsConfig(type))) {
// Module specific configuration
return moduleExclusionFilters.isExcluded(realAbsoluteFile, moduleRelativePath, type);
}
boolean includedByProjectConfiguration = projectExclusionFilters.isExcluded(realAbsoluteFile, projectRelativePath, type);
if (includedByProjectConfiguration) {
return true;
} else if (moduleExclusionFilters.isExcluded(realAbsoluteFile, moduleRelativePath, type)) {
warnOnce(
type == Type.MAIN ? CoreProperties.PROJECT_EXCLUSIONS_PROPERTY : CoreProperties.PROJECT_TEST_EXCLUSIONS_PROPERTY,
FilenameUtils.normalize(projectRelativePath.toString(), true), () -> warnExclusionsAlreadyLogged, () -> warnExclusionsAlreadyLogged = true);
return true;
}
return false;
}
private void checkIfAlreadyIndexed(DefaultInputFile inputFile) {
if (componentStore.inputFile(inputFile.getProjectRelativePath()) != null) {
throw MessageException.of("File " + inputFile + " can't be indexed twice. Please check that inclusion/exclusion patterns produce "
+ "disjoint sets for main and test files");
}
}
private void evaluateCoverageExclusions(ModuleCoverageAndDuplicationExclusions moduleCoverageAndDuplicationExclusions, DefaultInputFile inputFile) {
boolean excludedForCoverage = isExcludedForCoverage(moduleCoverageAndDuplicationExclusions, inputFile);
inputFile.setExcludedForCoverage(excludedForCoverage);
if (excludedForCoverage) {
LOG.debug("File {} excluded for coverage", inputFile);
}
}
private boolean isExcludedForCoverage(ModuleCoverageAndDuplicationExclusions moduleCoverageAndDuplicationExclusions, DefaultInputFile inputFile) {
if (!Arrays.equals(moduleCoverageAndDuplicationExclusions.getCoverageExclusionConfig(), projectCoverageAndDuplicationExclusions.getCoverageExclusionConfig())) {
// Module specific configuration
return moduleCoverageAndDuplicationExclusions.isExcludedForCoverage(inputFile);
}
boolean excludedByProjectConfiguration = projectCoverageAndDuplicationExclusions.isExcludedForCoverage(inputFile);
if (excludedByProjectConfiguration) {
return true;
} else if (moduleCoverageAndDuplicationExclusions.isExcludedForCoverage(inputFile)) {
warnOnce(CoreProperties.PROJECT_COVERAGE_EXCLUSIONS_PROPERTY, inputFile.getProjectRelativePath(), () -> warnCoverageExclusionsAlreadyLogged,
() -> warnCoverageExclusionsAlreadyLogged = true);
return true;
}
return false;
}
private void evaluateDuplicationExclusions(ModuleCoverageAndDuplicationExclusions moduleCoverageAndDuplicationExclusions, DefaultInputFile inputFile) {
boolean excludedForDuplications = isExcludedForDuplications(moduleCoverageAndDuplicationExclusions, inputFile);
inputFile.setExcludedForDuplication(excludedForDuplications);
if (excludedForDuplications) {
LOG.debug("File {} excluded for duplication", inputFile);
}
}
private boolean isExcludedForDuplications(ModuleCoverageAndDuplicationExclusions moduleCoverageAndDuplicationExclusions, DefaultInputFile inputFile) {
if (!Arrays.equals(moduleCoverageAndDuplicationExclusions.getDuplicationExclusionConfig(), projectCoverageAndDuplicationExclusions.getDuplicationExclusionConfig())) {
// Module specific configuration
return moduleCoverageAndDuplicationExclusions.isExcludedForDuplication(inputFile);
}
boolean excludedByProjectConfiguration = projectCoverageAndDuplicationExclusions.isExcludedForDuplication(inputFile);
if (excludedByProjectConfiguration) {
return true;
} else if (moduleCoverageAndDuplicationExclusions.isExcludedForDuplication(inputFile)) {
warnOnce(CoreProperties.CPD_EXCLUSIONS, inputFile.getProjectRelativePath(), () -> warnDuplicationExclusionsAlreadyLogged,
() -> warnDuplicationExclusionsAlreadyLogged = true);
return true;
}
return false;
}
private void warnOnce(String propKey, String filePath, BooleanSupplier alreadyLoggedGetter, Runnable markAsLogged) {
if (!alreadyLoggedGetter.getAsBoolean()) {
String msg = "Specifying module-relative paths at project level in the property '" + propKey + "' is deprecated. " +
"To continue matching files like '" + filePath + "', update this property so that patterns refer to project-relative paths.";
LOG.warn(msg);
analysisWarnings.addUnique(msg);
markAsLogged.run();
}
}
private boolean accept(InputFile indexedFile) {
// InputFileFilter extensions. Might trigger generation of metadata
for (InputFileFilter filter : filters) {
if (!filter.accept(indexedFile)) {
LOG.debug("'{}' excluded by {}", indexedFile, filter.getClass().getName());
return false;
}
}
return true;
}
private static String pluralizeFiles(int count) {
return count == 1 ? "file" : "files";
}
private boolean isFileSizeBiggerThanLimit(Path filePath) throws IOException {
return Files.size(filePath) > properties.fileSizeLimit() * 1024L * 1024L;
}
}
| 14,717 | 49.40411 | 178 | java |
sonarqube | sonarqube-master/sonar-scanner-engine/src/main/java/org/sonar/scanner/scan/filesystem/InputComponentStore.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.scan.filesystem;
import com.google.common.collect.ImmutableMap;
import java.util.Collection;
import java.util.Collections;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.LinkedHashSet;
import java.util.Map;
import java.util.Optional;
import java.util.Set;
import java.util.SortedSet;
import java.util.TreeSet;
import java.util.regex.Pattern;
import java.util.stream.Stream;
import javax.annotation.CheckForNull;
import org.sonar.api.SonarEdition;
import org.sonar.api.SonarRuntime;
import org.sonar.api.batch.fs.InputComponent;
import org.sonar.api.batch.fs.InputFile;
import org.sonar.api.batch.fs.internal.DefaultFileSystem;
import org.sonar.api.batch.fs.internal.DefaultInputFile;
import org.sonar.api.batch.fs.internal.DefaultInputModule;
import org.sonar.api.batch.fs.internal.predicates.FileExtensionPredicate;
import org.sonar.core.language.UnanalyzedLanguages;
import org.sonar.scanner.scan.branch.BranchConfiguration;
import static org.sonar.api.utils.Preconditions.checkNotNull;
import static org.sonar.api.utils.Preconditions.checkState;
/**
* Store of all files and dirs. Inclusion and
* exclusion patterns are already applied.
*/
public class InputComponentStore extends DefaultFileSystem.Cache {
private static final Map<UnanalyzedLanguages, Pattern> FILE_PATTERN_BY_LANGUAGE = ImmutableMap.of(
UnanalyzedLanguages.C, Pattern.compile(".*\\.c", Pattern.CASE_INSENSITIVE),
UnanalyzedLanguages.CPP, Pattern.compile(".*\\.cpp|.*\\.cc|.*\\.cxx|.*\\.c\\+\\+", Pattern.CASE_INSENSITIVE));
private final SortedSet<String> globalLanguagesCache = new TreeSet<>();
private final Map<String, SortedSet<String>> languagesCache = new HashMap<>();
private final Map<String, InputFile> globalInputFileCache = new HashMap<>();
private final Map<String, Map<String, InputFile>> inputFileByModuleCache = new LinkedHashMap<>();
private final Map<InputFile, String> inputModuleKeyByFileCache = new HashMap<>();
private final Map<String, DefaultInputModule> inputModuleCache = new HashMap<>();
private final Map<String, InputComponent> inputComponents = new HashMap<>();
private final Map<String, Set<InputFile>> filesByNameCache = new HashMap<>();
private final Map<String, Set<InputFile>> filesByExtensionCache = new HashMap<>();
private final BranchConfiguration branchConfiguration;
private final SonarRuntime sonarRuntime;
private final Map<String, Integer> notAnalysedFilesByLanguage = new HashMap<>();
public InputComponentStore(BranchConfiguration branchConfiguration, SonarRuntime sonarRuntime) {
this.branchConfiguration = branchConfiguration;
this.sonarRuntime = sonarRuntime;
}
public Collection<InputComponent> all() {
return inputComponents.values();
}
private Stream<DefaultInputFile> allFilesToPublishStream() {
return globalInputFileCache.values().stream()
.map(f -> (DefaultInputFile) f)
.filter(DefaultInputFile::isPublished);
}
public Iterable<DefaultInputFile> allFilesToPublish() {
return allFilesToPublishStream()::iterator;
}
public Iterable<DefaultInputFile> allChangedFilesToPublish() {
return allFilesToPublishStream()
.filter(f -> !branchConfiguration.isPullRequest() || f.status() != InputFile.Status.SAME)::iterator;
}
@Override
public Collection<InputFile> inputFiles() {
return globalInputFileCache.values();
}
public InputComponent getByKey(String key) {
return inputComponents.get(key);
}
public Iterable<InputFile> filesByModule(String moduleKey) {
return inputFileByModuleCache.getOrDefault(moduleKey, Collections.emptyMap()).values();
}
public InputComponentStore put(String moduleKey, InputFile inputFile) {
DefaultInputFile file = (DefaultInputFile) inputFile;
updateNotAnalysedCAndCppFileCount(file);
addToLanguageCache(moduleKey, file);
inputFileByModuleCache.computeIfAbsent(moduleKey, x -> new HashMap<>()).put(file.getModuleRelativePath(), inputFile);
inputModuleKeyByFileCache.put(inputFile, moduleKey);
globalInputFileCache.put(file.getProjectRelativePath(), inputFile);
inputComponents.put(inputFile.key(), inputFile);
filesByNameCache.computeIfAbsent(inputFile.filename(), x -> new LinkedHashSet<>()).add(inputFile);
filesByExtensionCache.computeIfAbsent(FileExtensionPredicate.getExtension(inputFile), x -> new LinkedHashSet<>()).add(inputFile);
return this;
}
private void addToLanguageCache(String moduleKey, DefaultInputFile inputFile) {
String language = inputFile.language();
if (language != null) {
globalLanguagesCache.add(language);
languagesCache.computeIfAbsent(moduleKey, k -> new TreeSet<>()).add(language);
}
}
@CheckForNull
public InputFile getFile(String moduleKey, String relativePath) {
return inputFileByModuleCache.getOrDefault(moduleKey, Collections.emptyMap())
.get(relativePath);
}
@Override
@CheckForNull
public InputFile inputFile(String relativePath) {
return globalInputFileCache.get(relativePath);
}
public DefaultInputModule findModule(DefaultInputFile file) {
return Optional.ofNullable(inputModuleKeyByFileCache.get(file)).map(inputModuleCache::get)
.orElseThrow(() -> new IllegalStateException("No modules for file '" + file.toString() + "'"));
}
public void put(DefaultInputModule inputModule) {
String key = inputModule.key();
checkNotNull(inputModule);
checkState(!inputComponents.containsKey(key), "Module '%s' already indexed", key);
checkState(!inputModuleCache.containsKey(key), "Module '%s' already indexed", key);
inputComponents.put(key, inputModule);
inputModuleCache.put(key, inputModule);
}
@Override
public Iterable<InputFile> getFilesByName(String filename) {
return filesByNameCache.getOrDefault(filename, Collections.emptySet());
}
@Override
public Iterable<InputFile> getFilesByExtension(String extension) {
return filesByExtensionCache.getOrDefault(extension, Collections.emptySet());
}
@Override
public SortedSet<String> languages() {
return globalLanguagesCache;
}
public SortedSet<String> languages(String moduleKey) {
return languagesCache.getOrDefault(moduleKey, Collections.emptySortedSet());
}
public Collection<DefaultInputModule> allModules() {
return inputModuleCache.values();
}
@Override
protected void doAdd(InputFile inputFile) {
throw new UnsupportedOperationException();
}
private void updateNotAnalysedCAndCppFileCount(DefaultInputFile inputFile) {
if (!SonarEdition.COMMUNITY.equals(sonarRuntime.getEdition())) {
return;
}
FILE_PATTERN_BY_LANGUAGE.forEach((language, filePattern) -> {
if (filePattern.matcher(inputFile.filename()).matches()) {
notAnalysedFilesByLanguage.put(language.toString(), notAnalysedFilesByLanguage.getOrDefault(language.toString(), 0) + 1);
}
});
}
public Map<String, Integer> getNotAnalysedFilesByLanguage() {
return ImmutableMap.copyOf(notAnalysedFilesByLanguage);
}
}
| 7,907 | 38.343284 | 133 | java |
sonarqube | sonarqube-master/sonar-scanner-engine/src/main/java/org/sonar/scanner/scan/filesystem/LanguageDetection.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.scan.filesystem;
import java.nio.file.Path;
import java.text.MessageFormat;
import java.util.Arrays;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;
import java.util.stream.Stream;
import javax.annotation.CheckForNull;
import javax.annotation.concurrent.ThreadSafe;
import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.sonar.api.batch.fs.internal.PathPattern;
import org.sonar.api.config.Configuration;
import org.sonar.api.utils.MessageException;
import org.sonar.scanner.repository.language.Language;
import org.sonar.scanner.repository.language.LanguagesRepository;
import static java.util.Collections.unmodifiableMap;
/**
* Detect language of a source file based on its suffix and configured patterns.
*/
@ThreadSafe
public class LanguageDetection {
private static final Logger LOG = LoggerFactory.getLogger(LanguageDetection.class);
/**
* Lower-case extension -> languages
*/
private final Map<Language, PathPattern[]> patternsByLanguage;
private final List<Language> languagesToConsider;
public LanguageDetection(Configuration settings, LanguagesRepository languages) {
Map<Language, PathPattern[]> patternsByLanguageBuilder = new LinkedHashMap<>();
for (Language language : languages.all()) {
String[] filePatterns = settings.getStringArray(getFileLangPatternPropKey(language.key()));
PathPattern[] pathPatterns = PathPattern.create(filePatterns);
if (pathPatterns.length > 0) {
patternsByLanguageBuilder.put(language, pathPatterns);
} else {
PathPattern[] languagePatterns = getLanguagePatterns(language);
patternsByLanguageBuilder.put(language, languagePatterns);
}
}
languagesToConsider = List.copyOf(patternsByLanguageBuilder.keySet());
patternsByLanguage = unmodifiableMap(patternsByLanguageBuilder);
}
private static PathPattern[] getLanguagePatterns(Language language) {
Stream<PathPattern> fileSuffixes = language.fileSuffixes().stream()
.map(suffix -> "**/*." + sanitizeExtension(suffix))
.map(PathPattern::create);
Stream<PathPattern> filenamePatterns = language.filenamePatterns()
.stream()
.map(filenamePattern -> "**/" + filenamePattern)
.map(PathPattern::create);
PathPattern[] defaultLanguagePatterns = Stream.concat(fileSuffixes, filenamePatterns)
.distinct()
.toArray(PathPattern[]::new);
LOG.debug("Declared patterns of language {} were converted to {}", language, getDetails(language, defaultLanguagePatterns));
return defaultLanguagePatterns;
}
@CheckForNull
Language language(Path absolutePath, Path relativePath) {
Language detectedLanguage = null;
for (Language language : languagesToConsider) {
if (isCandidateForLanguage(absolutePath, relativePath, language)) {
if (detectedLanguage == null) {
detectedLanguage = language;
} else {
// Language was already forced by another pattern
throw MessageException.of(MessageFormat.format("Language of file ''{0}'' can not be decided as the file matches patterns of both {1} and {2}",
relativePath, getDetails(detectedLanguage), getDetails(language)));
}
}
}
return detectedLanguage;
}
private boolean isCandidateForLanguage(Path absolutePath, Path relativePath, Language language) {
PathPattern[] patterns = patternsByLanguage.get(language);
return patterns != null && Arrays.stream(patterns).anyMatch(pattern -> pattern.match(absolutePath, relativePath, false));
}
private static String getFileLangPatternPropKey(String languageKey) {
return "sonar.lang.patterns." + languageKey;
}
private String getDetails(Language detectedLanguage) {
return getDetails(detectedLanguage, patternsByLanguage.get(detectedLanguage));
}
private static String getDetails(Language detectedLanguage, PathPattern[] patterns) {
return getFileLangPatternPropKey(detectedLanguage.key()) + " : " +
Arrays.stream(patterns).map(PathPattern::toString).collect(Collectors.joining(","));
}
static String sanitizeExtension(String suffix) {
return StringUtils.lowerCase(StringUtils.removeStart(suffix, "."));
}
}
| 5,172 | 38.792308 | 152 | java |
sonarqube | sonarqube-master/sonar-scanner-engine/src/main/java/org/sonar/scanner/scan/filesystem/MetadataGenerator.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.scan.filesystem;
import java.io.InputStream;
import java.nio.charset.Charset;
import org.sonar.api.batch.fs.InputFile.Type;
import org.sonar.api.batch.fs.internal.DefaultInputFile;
import org.sonar.api.batch.fs.internal.FileMetadata;
import org.sonar.api.batch.fs.internal.Metadata;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.sonar.scanner.issue.ignore.scanner.IssueExclusionsLoader;
public class MetadataGenerator {
private static final Logger LOG = LoggerFactory.getLogger(MetadataGenerator.class);
static final Charset UTF_32BE = Charset.forName("UTF-32BE");
static final Charset UTF_32LE = Charset.forName("UTF-32LE");
private final StatusDetection statusDetection;
private final FileMetadata fileMetadata;
private final IssueExclusionsLoader exclusionsScanner;
public MetadataGenerator(StatusDetection statusDetection, FileMetadata fileMetadata, IssueExclusionsLoader exclusionsScanner) {
this.statusDetection = statusDetection;
this.fileMetadata = fileMetadata;
this.exclusionsScanner = exclusionsScanner;
}
/**
* Sets all metadata in the file, including charset and status.
* It is an expensive computation, reading the entire file.
*/
public void setMetadata(String moduleKeyWithBranch, final DefaultInputFile inputFile, Charset defaultEncoding) {
CharsetDetector charsetDetector = new CharsetDetector(inputFile.path(), defaultEncoding);
try {
Charset charset;
if (charsetDetector.run()) {
charset = charsetDetector.charset();
} else {
LOG.debug("Failed to detect a valid charset for file '{}'. Using default charset.", inputFile);
charset = defaultEncoding;
}
InputStream is = charsetDetector.inputStream();
inputFile.setCharset(charset);
Metadata metadata = fileMetadata.readMetadata(is, charset, inputFile.absolutePath(), exclusionsScanner.createCharHandlerFor(inputFile));
inputFile.setMetadata(metadata);
if(!inputFile.isStatusSet()) {
inputFile.setStatus(statusDetection.status(moduleKeyWithBranch, inputFile, metadata.hash()));
}
LOG.debug("'{}' generated metadata{} with charset '{}'", inputFile, inputFile.type() == Type.TEST ? " as test " : "", charset);
} catch (Exception e) {
throw new IllegalStateException(e);
}
}
}
| 3,203 | 41.157895 | 142 | java |
sonarqube | sonarqube-master/sonar-scanner-engine/src/main/java/org/sonar/scanner/scan/filesystem/ModuleCoverageAndDuplicationExclusions.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.scan.filesystem;
import javax.annotation.concurrent.Immutable;
import org.sonar.api.batch.fs.internal.DefaultInputFile;
import org.sonar.scanner.scan.ModuleConfiguration;
@Immutable
public class ModuleCoverageAndDuplicationExclusions extends AbstractCoverageAndDuplicationExclusions {
public ModuleCoverageAndDuplicationExclusions(ModuleConfiguration moduleConfiguration) {
super(moduleConfiguration::getStringArray, DefaultInputFile::getModuleRelativePath);
}
}
| 1,343 | 39.727273 | 102 | java |
sonarqube | sonarqube-master/sonar-scanner-engine/src/main/java/org/sonar/scanner/scan/filesystem/ModuleExclusionFilters.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.scan.filesystem;
import org.sonar.api.notifications.AnalysisWarnings;
import org.sonar.scanner.scan.ModuleConfiguration;
public class ModuleExclusionFilters extends AbstractExclusionFilters {
public ModuleExclusionFilters(ModuleConfiguration moduleConfiguration, AnalysisWarnings analysisWarnings) {
super(analysisWarnings, moduleConfiguration::getStringArray);
}
}
| 1,248 | 36.848485 | 109 | java |
sonarqube | sonarqube-master/sonar-scanner-engine/src/main/java/org/sonar/scanner/scan/filesystem/ModuleInputComponentStore.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.scan.filesystem;
import java.util.SortedSet;
import org.sonar.api.batch.ScannerSide;
import org.sonar.api.batch.fs.InputFile;
import org.sonar.api.batch.fs.InputModule;
import org.sonar.api.batch.fs.internal.SensorStrategy;
import org.sonar.api.batch.fs.internal.DefaultFileSystem;
@ScannerSide
public class ModuleInputComponentStore extends DefaultFileSystem.Cache {
private final String moduleKey;
private final InputComponentStore inputComponentStore;
private final SensorStrategy strategy;
public ModuleInputComponentStore(InputModule module, InputComponentStore inputComponentStore, SensorStrategy strategy) {
this.moduleKey = module.key();
this.inputComponentStore = inputComponentStore;
this.strategy = strategy;
}
@Override
public Iterable<InputFile> inputFiles() {
if (strategy.isGlobal()) {
return inputComponentStore.inputFiles();
} else {
return inputComponentStore.filesByModule(moduleKey);
}
}
@Override
public InputFile inputFile(String relativePath) {
if (strategy.isGlobal()) {
return inputComponentStore.inputFile(relativePath);
} else {
return inputComponentStore.getFile(moduleKey, relativePath);
}
}
@Override
public SortedSet<String> languages() {
if (strategy.isGlobal()) {
return inputComponentStore.languages();
} else {
return inputComponentStore.languages(moduleKey);
}
}
@Override
protected void doAdd(InputFile inputFile) {
inputComponentStore.put(moduleKey, inputFile);
}
@Override
public Iterable<InputFile> getFilesByName(String filename) {
return inputComponentStore.getFilesByName(filename);
}
@Override
public Iterable<InputFile> getFilesByExtension(String extension) {
return inputComponentStore.getFilesByExtension(extension);
}
}
| 2,689 | 31.02381 | 122 | java |
sonarqube | sonarqube-master/sonar-scanner-engine/src/main/java/org/sonar/scanner/scan/filesystem/MutableFileSystem.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.scan.filesystem;
import java.nio.file.Path;
import org.sonar.api.batch.fs.FilePredicate;
import org.sonar.api.batch.fs.FilePredicates;
import org.sonar.api.batch.fs.InputFile;
import org.sonar.api.batch.fs.internal.DefaultFileSystem;
import org.sonar.api.batch.fs.internal.predicates.ChangedFilePredicate;
public class MutableFileSystem extends DefaultFileSystem {
private boolean restrictToChangedFiles = false;
public MutableFileSystem(Path baseDir, Cache cache, FilePredicates filePredicates) {
super(baseDir, cache, filePredicates);
}
public MutableFileSystem(Path baseDir) {
super(baseDir);
}
@Override
public Iterable<InputFile> inputFiles(FilePredicate requestPredicate) {
if (restrictToChangedFiles) {
return super.inputFiles(new ChangedFilePredicate(requestPredicate));
}
return super.inputFiles(requestPredicate);
}
@Override
public InputFile inputFile(FilePredicate requestPredicate) {
if (restrictToChangedFiles) {
return super.inputFile(new ChangedFilePredicate(requestPredicate));
}
return super.inputFile(requestPredicate);
}
public void setRestrictToChangedFiles(boolean restrictToChangedFiles) {
this.restrictToChangedFiles = restrictToChangedFiles;
}
}
| 2,121 | 34.366667 | 86 | java |
sonarqube | sonarqube-master/sonar-scanner-engine/src/main/java/org/sonar/scanner/scan/filesystem/ProjectCoverageAndDuplicationExclusions.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.scan.filesystem;
import javax.annotation.concurrent.Immutable;
import org.sonar.api.batch.fs.internal.DefaultInputFile;
import org.sonar.scanner.scan.ProjectConfiguration;
@Immutable
public class ProjectCoverageAndDuplicationExclusions extends AbstractCoverageAndDuplicationExclusions {
public ProjectCoverageAndDuplicationExclusions(ProjectConfiguration projectConfig) {
super(projectConfig::getStringArray, DefaultInputFile::getProjectRelativePath);
}
}
| 1,336 | 39.515152 | 103 | java |
sonarqube | sonarqube-master/sonar-scanner-engine/src/main/java/org/sonar/scanner/scan/filesystem/ProjectExclusionFilters.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.scan.filesystem;
import org.sonar.api.config.Configuration;
import org.sonar.api.notifications.AnalysisWarnings;
public class ProjectExclusionFilters extends AbstractExclusionFilters {
public ProjectExclusionFilters(Configuration projectConfig, AnalysisWarnings analysisWarnings) {
super(analysisWarnings, projectConfig::getStringArray);
}
}
| 1,223 | 37.25 | 98 | java |
sonarqube | sonarqube-master/sonar-scanner-engine/src/main/java/org/sonar/scanner/scan/filesystem/ProjectFileIndexer.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.scan.filesystem;
import java.io.IOException;
import java.nio.file.AccessDeniedException;
import java.nio.file.FileSystemLoopException;
import java.nio.file.FileVisitOption;
import java.nio.file.FileVisitResult;
import java.nio.file.FileVisitor;
import java.nio.file.Files;
import java.nio.file.LinkOption;
import java.nio.file.Path;
import java.nio.file.attribute.BasicFileAttributes;
import java.nio.file.attribute.DosFileAttributes;
import java.util.Collections;
import java.util.Comparator;
import java.util.Iterator;
import java.util.List;
import java.util.Optional;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicInteger;
import org.apache.commons.lang.StringUtils;
import org.apache.commons.lang.SystemUtils;
import org.sonar.api.batch.fs.InputFile;
import org.sonar.api.batch.fs.InputFile.Type;
import org.sonar.api.batch.fs.internal.DefaultInputModule;
import org.sonar.api.batch.scm.IgnoreCommand;
import org.sonar.api.notifications.AnalysisWarnings;
import org.sonar.api.scan.filesystem.PathResolver;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.sonar.scanner.bootstrap.GlobalConfiguration;
import org.sonar.scanner.bootstrap.GlobalServerSettings;
import org.sonar.scanner.fs.InputModuleHierarchy;
import org.sonar.scanner.scan.ModuleConfiguration;
import org.sonar.scanner.scan.ModuleConfigurationProvider;
import org.sonar.scanner.scan.ProjectServerSettings;
import org.sonar.scanner.scan.SonarGlobalPropertiesFilter;
import org.sonar.scanner.scm.ScmConfiguration;
import org.sonar.scanner.util.ProgressReport;
import static java.util.Collections.emptyList;
import static java.util.Collections.singletonList;
/**
* Index project input files into {@link InputComponentStore}.
*/
public class ProjectFileIndexer {
private static final Logger LOG = LoggerFactory.getLogger(ProjectFileIndexer.class);
private final ProjectExclusionFilters projectExclusionFilters;
private final SonarGlobalPropertiesFilter sonarGlobalPropertiesFilter;
private final ProjectCoverageAndDuplicationExclusions projectCoverageAndDuplicationExclusions;
private final ScmConfiguration scmConfiguration;
private final InputComponentStore componentStore;
private final InputModuleHierarchy inputModuleHierarchy;
private final GlobalConfiguration globalConfig;
private final GlobalServerSettings globalServerSettings;
private final ProjectServerSettings projectServerSettings;
private final FileIndexer fileIndexer;
private final IgnoreCommand ignoreCommand;
private final boolean useScmExclusion;
private final AnalysisWarnings analysisWarnings;
private ProgressReport progressReport;
public ProjectFileIndexer(InputComponentStore componentStore, ProjectExclusionFilters exclusionFilters,
SonarGlobalPropertiesFilter sonarGlobalPropertiesFilter, InputModuleHierarchy inputModuleHierarchy,
GlobalConfiguration globalConfig, GlobalServerSettings globalServerSettings, ProjectServerSettings projectServerSettings,
FileIndexer fileIndexer, ProjectCoverageAndDuplicationExclusions projectCoverageAndDuplicationExclusions, ScmConfiguration scmConfiguration,
AnalysisWarnings analysisWarnings) {
this.componentStore = componentStore;
this.sonarGlobalPropertiesFilter = sonarGlobalPropertiesFilter;
this.inputModuleHierarchy = inputModuleHierarchy;
this.globalConfig = globalConfig;
this.globalServerSettings = globalServerSettings;
this.projectServerSettings = projectServerSettings;
this.fileIndexer = fileIndexer;
this.projectExclusionFilters = exclusionFilters;
this.projectCoverageAndDuplicationExclusions = projectCoverageAndDuplicationExclusions;
this.scmConfiguration = scmConfiguration;
this.analysisWarnings = analysisWarnings;
this.ignoreCommand = loadIgnoreCommand();
this.useScmExclusion = ignoreCommand != null;
}
public void index() {
progressReport = new ProgressReport("Report about progress of file indexation", TimeUnit.SECONDS.toMillis(10));
progressReport.start("Indexing files...");
LOG.info("Project configuration:");
projectExclusionFilters.log(" ");
projectCoverageAndDuplicationExclusions.log(" ");
ExclusionCounter exclusionCounter = new ExclusionCounter();
if (useScmExclusion) {
ignoreCommand.init(inputModuleHierarchy.root().getBaseDir().toAbsolutePath());
indexModulesRecursively(inputModuleHierarchy.root(), exclusionCounter);
ignoreCommand.clean();
} else {
indexModulesRecursively(inputModuleHierarchy.root(), exclusionCounter);
}
int totalIndexed = componentStore.inputFiles().size();
progressReport.stop(totalIndexed + " " + pluralizeFiles(totalIndexed) + " indexed");
int excludedFileByPatternCount = exclusionCounter.getByPatternsCount();
if (projectExclusionFilters.hasPattern() || excludedFileByPatternCount > 0) {
LOG.info("{} {} ignored because of inclusion/exclusion patterns", excludedFileByPatternCount, pluralizeFiles(excludedFileByPatternCount));
}
int excludedFileByScmCount = exclusionCounter.getByScmCount();
if (useScmExclusion) {
LOG.info("{} {} ignored because of scm ignore settings", excludedFileByScmCount, pluralizeFiles(excludedFileByScmCount));
}
}
private IgnoreCommand loadIgnoreCommand() {
try {
if (!scmConfiguration.isExclusionDisabled() && scmConfiguration.provider() != null) {
return scmConfiguration.provider().ignoreCommand();
}
} catch (UnsupportedOperationException e) {
LOG.debug("File exclusion based on SCM ignore information is not available with this plugin.");
}
return null;
}
private void indexModulesRecursively(DefaultInputModule module, ExclusionCounter exclusionCounter) {
inputModuleHierarchy.children(module).stream().sorted(Comparator.comparing(DefaultInputModule::key)).forEach(m -> indexModulesRecursively(m, exclusionCounter));
index(module, exclusionCounter);
}
private void index(DefaultInputModule module, ExclusionCounter exclusionCounter) {
// Emulate creation of module level settings
ModuleConfiguration moduleConfig = new ModuleConfigurationProvider(sonarGlobalPropertiesFilter).provide(globalConfig, module, globalServerSettings, projectServerSettings);
ModuleExclusionFilters moduleExclusionFilters = new ModuleExclusionFilters(moduleConfig, analysisWarnings);
ModuleCoverageAndDuplicationExclusions moduleCoverageAndDuplicationExclusions = new ModuleCoverageAndDuplicationExclusions(moduleConfig);
if (componentStore.allModules().size() > 1) {
LOG.info("Indexing files of module '{}'", module.getName());
LOG.info(" Base dir: {}", module.getBaseDir().toAbsolutePath());
module.getSourceDirsOrFiles().ifPresent(srcs -> logPaths(" Source paths: ", module.getBaseDir(), srcs));
module.getTestDirsOrFiles().ifPresent(tests -> logPaths(" Test paths: ", module.getBaseDir(), tests));
moduleExclusionFilters.log(" ");
moduleCoverageAndDuplicationExclusions.log(" ");
}
boolean hasChildModules = !module.definition().getSubProjects().isEmpty();
boolean hasTests = module.getTestDirsOrFiles().isPresent();
// Default to index basedir when no sources provided
List<Path> mainSourceDirsOrFiles = module.getSourceDirsOrFiles()
.orElseGet(() -> hasChildModules || hasTests ? emptyList() : singletonList(module.getBaseDir().toAbsolutePath()));
indexFiles(module, moduleExclusionFilters, moduleCoverageAndDuplicationExclusions, mainSourceDirsOrFiles, Type.MAIN, exclusionCounter);
module.getTestDirsOrFiles().ifPresent(tests -> indexFiles(module, moduleExclusionFilters, moduleCoverageAndDuplicationExclusions, tests, Type.TEST, exclusionCounter));
}
private static void logPaths(String label, Path baseDir, List<Path> paths) {
if (!paths.isEmpty()) {
StringBuilder sb = new StringBuilder(label);
for (Iterator<Path> it = paths.iterator(); it.hasNext(); ) {
Path file = it.next();
Optional<String> relativePathToBaseDir = PathResolver.relativize(baseDir, file);
if (!relativePathToBaseDir.isPresent()) {
sb.append(file);
} else if (StringUtils.isBlank(relativePathToBaseDir.get())) {
sb.append(".");
} else {
sb.append(relativePathToBaseDir.get());
}
if (it.hasNext()) {
sb.append(", ");
}
}
if (LOG.isDebugEnabled()) {
LOG.debug(sb.toString());
} else {
LOG.info(StringUtils.abbreviate(sb.toString(), 80));
}
}
}
private static String pluralizeFiles(int count) {
return count == 1 ? "file" : "files";
}
private void indexFiles(DefaultInputModule module, ModuleExclusionFilters moduleExclusionFilters,
ModuleCoverageAndDuplicationExclusions moduleCoverageAndDuplicationExclusions, List<Path> sources, Type type, ExclusionCounter exclusionCounter) {
try {
for (Path dirOrFile : sources) {
if (dirOrFile.toFile().isDirectory()) {
indexDirectory(module, moduleExclusionFilters, moduleCoverageAndDuplicationExclusions, dirOrFile, type, exclusionCounter);
} else {
fileIndexer.indexFile(module, moduleExclusionFilters, moduleCoverageAndDuplicationExclusions, dirOrFile, type, progressReport, exclusionCounter,
ignoreCommand);
}
}
} catch (IOException e) {
throw new IllegalStateException("Failed to index files", e);
}
}
private void indexDirectory(DefaultInputModule module, ModuleExclusionFilters moduleExclusionFilters,
ModuleCoverageAndDuplicationExclusions moduleCoverageAndDuplicationExclusions, Path dirToIndex, Type type, ExclusionCounter exclusionCounter)
throws IOException {
Files.walkFileTree(dirToIndex.normalize(), Collections.singleton(FileVisitOption.FOLLOW_LINKS), Integer.MAX_VALUE,
new IndexFileVisitor(module, moduleExclusionFilters, moduleCoverageAndDuplicationExclusions, type, exclusionCounter));
}
/**
* <p>Checks if the path is a directory that is excluded.</p>
*
* <p>Exclusions patterns are checked both at project and module level.</p>
*
* @param moduleExclusionFilters The exclusion filters.
* @param realAbsoluteFile The path to be checked.
* @param projectBaseDir The project base directory.
* @param moduleBaseDir The module base directory.
* @param type The input file type.
* @return True if path is an excluded directory, false otherwise.
*/
private static boolean isExcludedDirectory(ModuleExclusionFilters moduleExclusionFilters, Path realAbsoluteFile, Path projectBaseDir, Path moduleBaseDir,
InputFile.Type type) {
Path projectRelativePath = projectBaseDir.relativize(realAbsoluteFile);
Path moduleRelativePath = moduleBaseDir.relativize(realAbsoluteFile);
return moduleExclusionFilters.isExcludedAsParentDirectoryOfExcludedChildren(realAbsoluteFile, projectRelativePath, projectBaseDir, type)
|| moduleExclusionFilters.isExcludedAsParentDirectoryOfExcludedChildren(realAbsoluteFile, moduleRelativePath, moduleBaseDir, type);
}
private class IndexFileVisitor implements FileVisitor<Path> {
private final DefaultInputModule module;
private final ModuleExclusionFilters moduleExclusionFilters;
private final ModuleCoverageAndDuplicationExclusions moduleCoverageAndDuplicationExclusions;
private final Type type;
private final ExclusionCounter exclusionCounter;
IndexFileVisitor(DefaultInputModule module, ModuleExclusionFilters moduleExclusionFilters, ModuleCoverageAndDuplicationExclusions moduleCoverageAndDuplicationExclusions,
Type type,
ExclusionCounter exclusionCounter) {
this.module = module;
this.moduleExclusionFilters = moduleExclusionFilters;
this.moduleCoverageAndDuplicationExclusions = moduleCoverageAndDuplicationExclusions;
this.type = type;
this.exclusionCounter = exclusionCounter;
}
@Override
public FileVisitResult preVisitDirectory(Path dir, BasicFileAttributes attrs) throws IOException {
if (isHidden(dir)) {
return FileVisitResult.SKIP_SUBTREE;
}
return FileVisitResult.CONTINUE;
}
@Override
public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) throws IOException {
if (!Files.isHidden(file)) {
fileIndexer.indexFile(module, moduleExclusionFilters, moduleCoverageAndDuplicationExclusions, file, type, progressReport, exclusionCounter, ignoreCommand);
}
return FileVisitResult.CONTINUE;
}
/**
* <p>Overridden method to handle exceptions while visiting files in the analysis.</p>
*
* <p>
* <ul>
* <li>FileSystemLoopException - We show a warning that a symlink loop exists and we skip the file.</li>
* <li>AccessDeniedException for excluded files/directories - We skip the file, as files excluded from the analysis, shouldn't throw access exceptions.</li>
* </ul>
* </p>
*
* @param file a reference to the file
* @param exc the I/O exception that prevented the file from being visited
* @throws IOException
*/
@Override
public FileVisitResult visitFileFailed(Path file, IOException exc) throws IOException {
if (exc instanceof FileSystemLoopException) {
LOG.warn("Not indexing due to symlink loop: {}", file.toFile());
return FileVisitResult.CONTINUE;
} else if (exc instanceof AccessDeniedException && isExcluded(file)) {
return FileVisitResult.CONTINUE;
}
throw exc;
}
/**
* <p>Checks if the directory is excluded in the analysis or not. Only the exclusions are checked.</p>
*
* <p>The inclusions cannot be checked for directories, since the current implementation of pattern matching is intended only for files.</p>
*
* @param path The file or directory.
* @return True if file/directory is excluded from the analysis, false otherwise.
*/
private boolean isExcluded(Path path) throws IOException {
Path realAbsoluteFile = path.toRealPath(LinkOption.NOFOLLOW_LINKS).toAbsolutePath().normalize();
return isExcludedDirectory(moduleExclusionFilters, realAbsoluteFile, inputModuleHierarchy.root().getBaseDir(), module.getBaseDir(), type);
}
@Override
public FileVisitResult postVisitDirectory(Path dir, IOException exc) {
return FileVisitResult.CONTINUE;
}
private boolean isHidden(Path path) throws IOException {
if (SystemUtils.IS_OS_WINDOWS) {
try {
DosFileAttributes dosFileAttributes = Files.readAttributes(path, DosFileAttributes.class, LinkOption.NOFOLLOW_LINKS);
return dosFileAttributes.isHidden();
} catch (UnsupportedOperationException e) {
return path.toFile().isHidden();
}
} else {
return Files.isHidden(path);
}
}
}
static class ExclusionCounter {
private final AtomicInteger excludedByPatternsCount = new AtomicInteger(0);
private final AtomicInteger excludedByScmCount = new AtomicInteger(0);
public void increaseByPatternsCount() {
excludedByPatternsCount.incrementAndGet();
}
public int getByPatternsCount() {
return excludedByPatternsCount.get();
}
public void increaseByScmCount() {
excludedByScmCount.incrementAndGet();
}
public int getByScmCount() {
return excludedByScmCount.get();
}
}
}
| 16,388 | 44.907563 | 175 | java |
sonarqube | sonarqube-master/sonar-scanner-engine/src/main/java/org/sonar/scanner/scan/filesystem/ScannerComponentIdGenerator.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.scan.filesystem;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.function.IntSupplier;
import javax.annotation.concurrent.ThreadSafe;
import org.sonar.api.batch.fs.InputComponent;
/**
* Generates unique IDs for any {@link InputComponent}.
* The IDs must be unique among all types of components (project, files) in the project.
* The ID should never be 0, as it is sometimes used to indicate invalid components.
*/
@ThreadSafe
public class ScannerComponentIdGenerator implements IntSupplier {
private AtomicInteger nextId = new AtomicInteger(1);
@Override
public int getAsInt() {
return nextId.getAndIncrement();
}
}
| 1,527 | 34.534884 | 88 | java |
sonarqube | sonarqube-master/sonar-scanner-engine/src/main/java/org/sonar/scanner/scan/filesystem/StatusDetection.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.scan.filesystem;
import javax.annotation.concurrent.Immutable;
import org.apache.commons.lang.StringUtils;
import org.sonar.api.batch.fs.InputFile;
import org.sonar.api.batch.fs.internal.DefaultInputFile;
import org.sonar.scanner.repository.FileData;
import org.sonar.scanner.repository.ProjectRepositories;
import org.sonar.scanner.scm.ScmChangedFiles;
import static org.sonar.api.batch.fs.InputFile.Status.ADDED;
import static org.sonar.api.batch.fs.InputFile.Status.CHANGED;
import static org.sonar.api.batch.fs.InputFile.Status.SAME;
@Immutable
public class StatusDetection {
private final ProjectRepositories projectRepositories;
private final ScmChangedFiles scmChangedFiles;
public StatusDetection(ProjectRepositories projectRepositories, ScmChangedFiles scmChangedFiles) {
this.projectRepositories = projectRepositories;
this.scmChangedFiles = scmChangedFiles;
}
public boolean isScmStatusAvailable() {
return scmChangedFiles.isValid();
}
InputFile.Status status(String moduleKeyWithBranch, DefaultInputFile inputFile, String hash) {
InputFile.Status statusFromScm = findStatusFromScm(inputFile);
if (statusFromScm != null) {
return statusFromScm;
}
return checkChangedWithProjectRepositories(moduleKeyWithBranch, inputFile, hash);
}
InputFile.Status findStatusFromScm(DefaultInputFile inputFile) {
if (isScmStatusAvailable()) {
return checkChangedWithScm(inputFile);
}
return null;
}
private InputFile.Status checkChangedWithProjectRepositories(String moduleKeyWithBranch, DefaultInputFile inputFile, String hash) {
FileData fileDataPerPath = projectRepositories.fileData(moduleKeyWithBranch, inputFile);
if (fileDataPerPath == null) {
return ADDED;
}
String previousHash = fileDataPerPath.hash();
if (StringUtils.equals(hash, previousHash)) {
return SAME;
}
if (StringUtils.isEmpty(previousHash)) {
return ADDED;
}
return CHANGED;
}
private InputFile.Status checkChangedWithScm(DefaultInputFile inputFile) {
if (!scmChangedFiles.isChanged(inputFile.path())) {
return SAME;
}
return CHANGED;
}
}
| 3,035 | 34.717647 | 133 | java |
sonarqube | sonarqube-master/sonar-scanner-engine/src/main/java/org/sonar/scanner/scan/filesystem/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.
*/
/**
* This package is a part of bootstrap process, so we should take care about backward compatibility.
*/
@ParametersAreNonnullByDefault
package org.sonar.scanner.scan.filesystem;
import javax.annotation.ParametersAreNonnullByDefault;
| 1,082 | 39.111111 | 100 | java |
sonarqube | sonarqube-master/sonar-scanner-engine/src/main/java/org/sonar/scanner/scan/measure/DefaultMetricFinder.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.scan.measure;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import javax.annotation.concurrent.ThreadSafe;
import org.sonar.api.batch.measure.Metric;
import org.sonar.api.batch.measure.MetricFinder;
import org.sonar.scanner.repository.MetricsRepository;
@ThreadSafe
public class DefaultMetricFinder implements MetricFinder {
private Map<String, Metric<Serializable>> metricsByKey;
public DefaultMetricFinder(MetricsRepository metricsRepository) {
Map<String, Metric<Serializable>> metrics = new LinkedHashMap<>();
for (org.sonar.api.measures.Metric metric : metricsRepository.metrics()) {
metrics.put(metric.key(), new org.sonar.api.measures.Metric.Builder(metric.key(), metric.key(), metric.getType()).create());
}
metricsByKey = Collections.unmodifiableMap(metrics);
}
@Override
public Metric<Serializable> findByKey(String key) {
return metricsByKey.get(key);
}
@Override
public Collection<Metric<Serializable>> findAll(List<String> metricKeys) {
List<Metric<Serializable>> result = new ArrayList<>();
for (String metricKey : metricKeys) {
Metric<Serializable> metric = findByKey(metricKey);
if (metric != null) {
result.add(metric);
}
}
return result;
}
@Override
public Collection<Metric<Serializable>> findAll() {
return metricsByKey.values();
}
}
| 2,374 | 32.928571 | 130 | java |
sonarqube | sonarqube-master/sonar-scanner-engine/src/main/java/org/sonar/scanner/scan/measure/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.
*/
/**
* This package is a part of bootstrap process, so we should take care about backward compatibility.
*/
@ParametersAreNonnullByDefault
package org.sonar.scanner.scan.measure;
import javax.annotation.ParametersAreNonnullByDefault;
| 1,079 | 39 | 100 | java |
sonarqube | sonarqube-master/sonar-scanner-engine/src/main/java/org/sonar/scanner/scm/DefaultBlameInput.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 org.sonar.api.batch.fs.FileSystem;
import org.sonar.api.batch.fs.InputFile;
import org.sonar.api.batch.scm.BlameCommand.BlameInput;
class DefaultBlameInput implements BlameInput {
private FileSystem fs;
private Iterable<InputFile> filesToBlame;
DefaultBlameInput(FileSystem fs, Iterable<InputFile> filesToBlame) {
this.fs = fs;
this.filesToBlame = filesToBlame;
}
@Override
public FileSystem fileSystem() {
return fs;
}
@Override
public Iterable<InputFile> filesToBlame() {
return filesToBlame;
}
}
| 1,423 | 29.297872 | 75 | java |
sonarqube | sonarqube-master/sonar-scanner-engine/src/main/java/org/sonar/scanner/scm/DefaultBlameOutput.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 com.google.common.annotations.VisibleForTesting;
import java.util.HashMap;
import java.util.LinkedHashSet;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.TimeUnit;
import javax.annotation.Nullable;
import org.apache.commons.lang.StringUtils;
import org.sonar.api.batch.fs.InputFile;
import org.sonar.api.batch.fs.internal.DefaultInputFile;
import org.sonar.api.batch.scm.BlameCommand.BlameOutput;
import org.sonar.api.batch.scm.BlameLine;
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.util.ProgressReport;
import static java.lang.String.format;
import static org.sonar.api.utils.Preconditions.checkArgument;
class DefaultBlameOutput implements BlameOutput {
private static final Logger LOG = LoggerFactory.getLogger(DefaultBlameOutput.class);
@VisibleForTesting
static final String SCM_INTEGRATION_DOCUMENTATION_SUFFIX = "/analyzing-source-code/scm-integration/";
private final ScannerReportWriter writer;
private AnalysisWarnings analysisWarnings;
private final DocumentationLinkGenerator documentationLinkGenerator;
private final Set<InputFile> allFilesToBlame = new LinkedHashSet<>();
private ProgressReport progressReport;
private int count;
private int total;
DefaultBlameOutput(ScannerReportWriter writer, AnalysisWarnings analysisWarnings, List<InputFile> filesToBlame,
DocumentationLinkGenerator documentationLinkGenerator) {
this.writer = writer;
this.analysisWarnings = analysisWarnings;
this.documentationLinkGenerator = documentationLinkGenerator;
this.allFilesToBlame.addAll(filesToBlame);
count = 0;
total = filesToBlame.size();
progressReport = new ProgressReport("Report about progress of SCM blame", TimeUnit.SECONDS.toMillis(10));
progressReport.start("SCM Publisher " + total + " " + pluralize(total) + " to be analyzed");
}
@Override
public synchronized void blameResult(InputFile file, List<BlameLine> lines) {
checkNotNull(file);
checkNotNull(lines);
checkArgument(allFilesToBlame.contains(file), "It was not expected to blame file %s", file);
if (lines.size() != file.lines()) {
LOG.debug("Ignoring blame result since provider returned {} blame lines but file {} has {} lines", lines.size(), file, file.lines());
return;
}
Builder scmBuilder = ScannerReport.Changesets.newBuilder();
DefaultInputFile inputFile = (DefaultInputFile) file;
scmBuilder.setComponentRef(inputFile.scannerId());
Map<String, Integer> changesetsIdByRevision = new HashMap<>();
int lineId = 1;
for (BlameLine line : lines) {
validateLine(line, lineId, file);
Integer changesetId = changesetsIdByRevision.get(line.revision());
if (changesetId == null) {
addChangeset(scmBuilder, line);
changesetId = scmBuilder.getChangesetCount() - 1;
changesetsIdByRevision.put(line.revision(), changesetId);
}
scmBuilder.addChangesetIndexByLine(changesetId);
lineId++;
}
writer.writeComponentChangesets(scmBuilder.build());
allFilesToBlame.remove(file);
count++;
progressReport.message(count + "/" + total + " " + pluralize(count) + " have been analyzed");
}
private static void validateLine(BlameLine line, int lineId, InputFile file) {
checkArgument(StringUtils.isNotBlank(line.revision()), "Blame revision is blank for file %s at line %s", file, lineId);
checkArgument(line.date() != null, "Blame date is null for file %s at line %s", file, lineId);
}
private static void addChangeset(Builder scmBuilder, BlameLine line) {
ScannerReport.Changesets.Changeset.Builder changesetBuilder = ScannerReport.Changesets.Changeset.newBuilder();
changesetBuilder.setRevision(line.revision());
changesetBuilder.setDate(line.date().getTime());
if (StringUtils.isNotBlank(line.author())) {
changesetBuilder.setAuthor(normalizeString(line.author()));
}
scmBuilder.addChangeset(changesetBuilder.build());
}
private static String normalizeString(@Nullable String inputString) {
if (inputString == null) {
return "";
}
return inputString.toLowerCase(Locale.US);
}
private static void checkNotNull(@Nullable Object obj) {
if (obj == null) {
throw new NullPointerException();
}
}
public void finish(boolean success) {
progressReport.stopAndLogTotalTime("SCM Publisher " + count + "/" + total + " " + pluralize(count) + " have been analyzed");
if (success && !allFilesToBlame.isEmpty()) {
LOG.warn("Missing blame information for the following files:");
for (InputFile f : allFilesToBlame) {
LOG.warn(" * " + f);
}
LOG.warn("This may lead to missing/broken features in SonarQube");
String docUrl = documentationLinkGenerator.getDocumentationLink(SCM_INTEGRATION_DOCUMENTATION_SUFFIX);
analysisWarnings.addUnique(format("Missing blame information for %d %s. This may lead to some features not working correctly. " +
"Please check the analysis logs and refer to <a href=\"%s\" rel=\"noopener noreferrer\" target=\"_blank\">the documentation</a>.",
allFilesToBlame.size(),
allFilesToBlame.size() > 1 ? "files" : "file",
docUrl));
}
}
private static String pluralize(long filesCount) {
return filesCount == 1 ? "source file" : "source files";
}
}
| 6,611 | 40.584906 | 139 | java |
sonarqube | sonarqube-master/sonar-scanner-engine/src/main/java/org/sonar/scanner/scm/ScmChangedFiles.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.nio.file.Path;
import java.util.Collection;
import java.util.Map;
import java.util.Optional;
import java.util.Set;
import javax.annotation.CheckForNull;
import javax.annotation.Nullable;
import javax.annotation.concurrent.Immutable;
import org.sonar.scm.git.ChangedFile;
import static java.util.Collections.emptyMap;
import static java.util.function.Function.identity;
import static java.util.stream.Collectors.toMap;
@Immutable
public class ScmChangedFiles {
@Nullable
private final Set<ChangedFile> changedFiles;
private final Map<Path, ChangedFile> changedFilesByPath;
public ScmChangedFiles(@Nullable Set<ChangedFile> changedFiles) {
this.changedFiles = changedFiles;
this.changedFilesByPath = toChangedFilesByPathMap(changedFiles);
}
public boolean isChanged(Path file) {
if (!isValid()) {
throw new IllegalStateException("Scm didn't provide valid data");
}
return this.getChangedFile(file).isPresent();
}
public boolean isValid() {
return changedFiles != null;
}
@CheckForNull
public Collection<ChangedFile> get() {
return changedFiles;
}
@CheckForNull
public String getOldRelativeFilePath(Path absoluteFilePath) {
return this.getChangedFile(absoluteFilePath)
.filter(ChangedFile::isMovedFile)
.map(ChangedFile::getOldRelativeFilePathReference)
.orElse(null);
}
private Optional<ChangedFile> getChangedFile(Path absoluteFilePath) {
return Optional.ofNullable(changedFilesByPath.get(absoluteFilePath));
}
private static Map<Path, ChangedFile> toChangedFilesByPathMap(@Nullable Set<ChangedFile> changedFiles) {
return Optional.ofNullable(changedFiles)
.map(files -> files.stream().collect(toMap(ChangedFile::getAbsolutFilePath, identity())))
.orElse(emptyMap());
}
}
| 2,682 | 31.719512 | 106 | java |
sonarqube | sonarqube-master/sonar-scanner-engine/src/main/java/org/sonar/scanner/scm/ScmChangedFilesProvider.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.nio.file.Path;
import java.util.Collection;
import java.util.Set;
import javax.annotation.CheckForNull;
import javax.annotation.Nullable;
import org.sonar.api.batch.fs.internal.DefaultInputProject;
import org.sonar.api.batch.scm.ScmProvider;
import org.sonar.api.impl.utils.ScannerUtils;
import org.sonar.api.utils.log.Logger;
import org.sonar.api.utils.log.Loggers;
import org.sonar.api.utils.log.Profiler;
import org.sonar.scanner.scan.branch.BranchConfiguration;
import org.sonar.scm.git.ChangedFile;
import org.sonar.scm.git.GitScmProvider;
import org.springframework.context.annotation.Bean;
import static java.util.stream.Collectors.toSet;
public class ScmChangedFilesProvider {
private static final Logger LOG = Loggers.get(ScmChangedFilesProvider.class);
private static final String LOG_MSG = "SCM collecting changed files in the branch";
@Bean("ScmChangedFiles")
public ScmChangedFiles provide(ScmConfiguration scmConfiguration, BranchConfiguration branchConfiguration, DefaultInputProject project) {
Path rootBaseDir = project.getBaseDir();
Set<ChangedFile> changedFiles = loadChangedFilesIfNeeded(scmConfiguration, branchConfiguration, rootBaseDir);
if (changedFiles != null) {
validatePaths(getAbsoluteFilePaths(changedFiles));
}
return new ScmChangedFiles(changedFiles);
}
private static void validatePaths(Set<Path> changedFilePaths) {
if (changedFilePaths.stream().anyMatch(p -> !p.isAbsolute())) {
throw new IllegalStateException("SCM provider returned a changed file with a relative path but paths must be absolute. Please fix the provider.");
}
}
private static Set<Path> getAbsoluteFilePaths(Collection<ChangedFile> changedFiles) {
return changedFiles
.stream()
.map(ChangedFile::getAbsolutFilePath)
.collect(toSet());
}
@CheckForNull
private static Set<ChangedFile> loadChangedFilesIfNeeded(ScmConfiguration scmConfiguration, BranchConfiguration branchConfiguration, Path rootBaseDir) {
final String targetBranchName = branchConfiguration.targetBranchName();
if (branchConfiguration.isPullRequest() && targetBranchName != null) {
ScmProvider scmProvider = scmConfiguration.provider();
if (scmProvider != null) {
Profiler profiler = Profiler.create(LOG).startInfo(LOG_MSG);
Set<ChangedFile> changedFiles = getChangedFilesByScm(scmProvider, targetBranchName, rootBaseDir);
profiler.stopInfo();
if (changedFiles != null) {
LOG.debug("SCM reported {} {} changed in the branch", changedFiles.size(), ScannerUtils.pluralize("file", changedFiles.size()));
return changedFiles;
}
}
LOG.debug("SCM information about changed files in the branch is not available");
}
return null;
}
private static Set<ChangedFile> getChangedFilesByScm(ScmProvider scmProvider, String targetBranchName, Path rootBaseDir) {
if (scmProvider instanceof GitScmProvider) {
return ((GitScmProvider) scmProvider).branchChangedFilesWithFileMovementDetection(targetBranchName, rootBaseDir);
}
return toChangedFiles(scmProvider.branchChangedFiles(targetBranchName, rootBaseDir));
}
@CheckForNull
private static Set<ChangedFile> toChangedFiles(@Nullable Set<Path> changedPaths) {
if (changedPaths == null) {
return null;
}
return changedPaths
.stream()
.map(ChangedFile::of)
.collect(toSet());
}
}
| 4,329 | 38.724771 | 154 | java |
sonarqube | sonarqube-master/sonar-scanner-engine/src/main/java/org/sonar/scanner/scm/ScmConfiguration.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.LinkedHashMap;
import java.util.Map;
import java.util.stream.Collectors;
import javax.annotation.CheckForNull;
import org.apache.commons.lang.StringUtils;
import org.sonar.api.CoreProperties;
import org.sonar.api.Properties;
import org.sonar.api.Property;
import org.sonar.api.PropertyType;
import org.sonar.api.Startable;
import org.sonar.api.batch.scm.ScmProvider;
import org.sonar.api.config.Configuration;
import org.sonar.api.notifications.AnalysisWarnings;
import org.sonar.api.utils.MessageException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.sonar.core.config.ScannerProperties;
import org.sonar.scanner.fs.InputModuleHierarchy;
import static org.sonar.api.CoreProperties.SCM_PROVIDER_KEY;
@Properties({
@Property(
key = ScmConfiguration.FORCE_RELOAD_KEY,
defaultValue = "false",
name = "Force reloading of SCM information for all files",
description = "By default only files modified since previous analysis are inspected. Set this parameter to true to force the reloading.",
category = CoreProperties.CATEGORY_SCM,
project = false,
module = false,
global = false,
type = PropertyType.BOOLEAN)
})
public class ScmConfiguration implements Startable {
private static final Logger LOG = LoggerFactory.getLogger(ScmConfiguration.class);
public static final String FORCE_RELOAD_KEY = "sonar.scm.forceReloadAll";
static final String MESSAGE_SCM_STEP_IS_DISABLED_BY_CONFIGURATION = "SCM Step is disabled by configuration";
static final String MESSAGE_SCM_EXCLUSIONS_IS_DISABLED_BY_CONFIGURATION = "Exclusions based on SCM info is disabled by configuration";
private final Configuration settings;
private final AnalysisWarnings analysisWarnings;
private final Map<String, ScmProvider> providerPerKey = new LinkedHashMap<>();
private final InputModuleHierarchy moduleHierarchy;
private ScmProvider provider;
public ScmConfiguration(InputModuleHierarchy moduleHierarchy, Configuration settings, AnalysisWarnings analysisWarnings,
ScmProvider... providers) {
this.moduleHierarchy = moduleHierarchy;
this.settings = settings;
this.analysisWarnings = analysisWarnings;
for (ScmProvider scmProvider : providers) {
providerPerKey.put(scmProvider.key(), scmProvider);
}
}
@Override
public void start() {
if (isDisabled()) {
LOG.debug(MESSAGE_SCM_STEP_IS_DISABLED_BY_CONFIGURATION);
return;
}
if (settings.hasKey(SCM_PROVIDER_KEY)) {
settings.get(SCM_PROVIDER_KEY).ifPresent(this::setProviderIfSupported);
} else {
autodetection();
if (this.provider == null) {
considerOldScmUrl();
}
if (this.provider == null) {
String message = "SCM provider autodetection failed. Please use \"" + SCM_PROVIDER_KEY + "\" to define SCM of " +
"your project, or disable the SCM Sensor in the project settings.";
LOG.warn(message);
analysisWarnings.addUnique(message);
}
}
if (isExclusionDisabled()) {
LOG.info(MESSAGE_SCM_EXCLUSIONS_IS_DISABLED_BY_CONFIGURATION);
}
}
private void setProviderIfSupported(String forcedProviderKey) {
if (providerPerKey.containsKey(forcedProviderKey)) {
this.provider = providerPerKey.get(forcedProviderKey);
} else {
String supportedProviders = providerPerKey.isEmpty() ? "No SCM provider installed"
: ("Supported SCM providers are " + providerPerKey.keySet().stream().collect(Collectors.joining(",")));
throw new IllegalArgumentException("SCM provider was set to \"" + forcedProviderKey + "\" but no SCM provider found for this key. " + supportedProviders);
}
}
private void considerOldScmUrl() {
settings.get(ScannerProperties.LINKS_SOURCES_DEV).ifPresent(url -> {
if (StringUtils.startsWith(url, "scm:")) {
String[] split = url.split(":");
if (split.length > 1) {
setProviderIfSupported(split[1]);
}
}
});
}
private void autodetection() {
for (ScmProvider installedProvider : providerPerKey.values()) {
if (installedProvider.supports(moduleHierarchy.root().getBaseDir().toFile())) {
if (this.provider == null) {
this.provider = installedProvider;
} else {
throw MessageException.of("SCM provider autodetection failed. Both " + this.provider.key() + " and " + installedProvider.key()
+ " claim to support this project. Please use \"" + SCM_PROVIDER_KEY + "\" to define SCM of your project.");
}
}
}
}
@CheckForNull
public ScmProvider provider() {
return provider;
}
public boolean isDisabled() {
return settings.getBoolean(CoreProperties.SCM_DISABLED_KEY).orElse(false);
}
public boolean isExclusionDisabled() {
return isDisabled() || settings.getBoolean(CoreProperties.SCM_EXCLUSIONS_DISABLED_KEY).orElse(false);
}
public boolean forceReloadAll() {
return settings.getBoolean(FORCE_RELOAD_KEY).orElse(false);
}
@Override
public void stop() {
// Nothing to do
}
}
| 5,952 | 35.746914 | 160 | java |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.