*/
package org.sonar.ce.task.projectanalysis.analysis;
-import java.util.Optional;
import javax.annotation.concurrent.Immutable;
import org.sonar.ce.task.projectanalysis.component.ComponentKeyGenerator;
import org.sonar.db.component.BranchType;
String getName();
/**
- * Indicates the branch from which it was forked.
- * It will be empty for main branches or legacy branches.
+ * Indicates the first LLB branch from which it was forked.
+ *
+ * @throws IllegalStateException for main branches or legacy branches.
*/
- Optional<String> getMergeBranchUuid();
+ String getMergeBranchUuid();
/**
* Whether the cross-project duplication tracker must be enabled
* @throws IllegalStateException if this branch configuration is not a pull request.
*/
String getPullRequestKey();
+
+ /**
+ * The target/base branch name of a SLB or PR.
+ * Correspond to <pre>sonar.pullrequest.base</pre> or <pre>sonar.branch.target</pre>
+ * It's not guaranteed to exist.
+ *
+ * @throws IllegalStateException if this branch configuration is not a pull request or SLB.
+ */
+ String getTargetBranchName();
}
package org.sonar.ce.task.projectanalysis.component;
import javax.annotation.Nullable;
+import org.sonar.api.resources.Qualifiers;
import org.sonar.ce.task.projectanalysis.analysis.AnalysisMetadataHolder;
import org.sonar.ce.task.projectanalysis.analysis.Branch;
import org.sonar.db.DbClient;
dto.setProjectUuid(firstNonNull(componentDto.getMainBranchProjectUuid(), componentDto.projectUuid()));
dto.setBranchType(branch.getType());
- // merge branch is only present if it's a short living branch
- dto.setMergeBranchUuid(branch.getMergeBranchUuid().orElse(null));
+ // merge branch is only present if it's not a main branch and not an application
+ if (!branch.isMain() && !Qualifiers.APP.equals(componentDto.qualifier())) {
+ dto.setMergeBranchUuid(branch.getMergeBranchUuid());
+ }
if (branch.getType() == BranchType.PULL_REQUEST) {
dto.setKey(analysisMetadataHolder.getPullRequestKey());
DbProjectBranches.PullRequestData pullRequestData = DbProjectBranches.PullRequestData.newBuilder()
.setBranch(branch.getName())
.setTitle(branch.getName())
+ .setTarget(branch.getTargetBranchName())
.build();
dto.setPullRequestData(pullRequestData);
} else {
*/
package org.sonar.ce.task.projectanalysis.component;
-import java.util.Optional;
import javax.annotation.Nullable;
import org.sonar.api.utils.MessageException;
import org.sonar.ce.task.projectanalysis.analysis.Branch;
}
@Override
- public Optional<String> getMergeBranchUuid() {
- return Optional.empty();
+ public String getMergeBranchUuid() {
+ throw new IllegalStateException("Not valid for the main branch");
}
@Override
throw new IllegalStateException("Only a branch of type PULL_REQUEST can have a pull request id.");
}
+ @Override
+ public String getTargetBranchName() {
+ throw new IllegalStateException("Only on a short lived branch or pull request");
+ }
+
@Override
public String generateKey(String projectKey, @Nullable String fileOrDirPath) {
if (isLegacyBranch) {
private void lazyInit() {
if (uuidsByKey == null) {
- String mergeBranchUuid = analysisMetadataHolder.getBranch().getMergeBranchUuid().get();
+ String mergeBranchUuid = analysisMetadataHolder.getBranch().getMergeBranchUuid();
uuidsByKey = new HashMap<>();
try (DbSession dbSession = dbClient.openSession(false)) {
/**
* Cache a map of component key -> set<uuid> in sibling branches/PR that have open issues
- *
*/
public class SiblingComponentsWithOpenIssues {
private final DbClient dbClient;
}
private void loadUuidsByKey() {
- uuidsByKey = new HashMap<>();
String currentBranchUuid = treeRootHolder.getRoot().getUuid();
+ String longLivingReferenceBranchUuid;
+
+ if (metadataHolder.isSLBorPR()) {
+ longLivingReferenceBranchUuid = metadataHolder.getBranch().getMergeBranchUuid();
+ } else {
+ longLivingReferenceBranchUuid = currentBranchUuid;
+ }
+
+ uuidsByKey = new HashMap<>();
try (DbSession dbSession = dbClient.openSession(false)) {
List<KeyWithUuidDto> components = dbClient.componentDao().selectAllSiblingComponentKeysHavingOpenIssues(dbSession,
- metadataHolder.getBranch().getMergeBranchUuid().orElse(currentBranchUuid), currentBranchUuid);
+ longLivingReferenceBranchUuid, currentBranchUuid);
for (KeyWithUuidDto dto : components) {
uuidsByKey.computeIfAbsent(removeBranchAndPullRequestFromKey(dto.key()), s -> new HashSet<>()).add(dto.uuid());
}
// at this point, it's the first analysis but had copyFromPrevious flag true
Branch branch = analysisMetadataHolder.getBranch();
- if (branch.getMergeBranchUuid().isPresent()) {
+ if (!branch.isMain()) {
return Optional.ofNullable(mergeBranchComponentUuid.getUuid(file.getDbKey()));
}
if (!analysisMetadataHolder.isSLBorPR()) {
return;
}
- String mergeBranchUuid = analysisMetadataHolder.getBranch().getMergeBranchUuid().get();
+ String mergeBranchUuid = analysisMetadataHolder.getBranch().getMergeBranchUuid();
int moduleCount = dbClient.componentDao().countEnabledModulesByProjectUuid(session, mergeBranchUuid);
if (moduleCount > 0) {
Optional<BranchDto> opt = dbClient.branchDao().selectByUuid(session, mergeBranchUuid);
import com.tngtech.java.junit.dataprovider.UseDataProvider;
import java.util.Date;
import java.util.List;
-import java.util.Optional;
import java.util.Random;
import javax.annotation.Nullable;
import org.apache.commons.lang.RandomStringUtils;
new PostProjectAnalysisTasksExecutor(
ceTask, analysisMetadataHolder, qualityGateHolder, qualityGateStatusHolder, reportReader,
system2, new PostProjectAnalysisTask[] {postProjectAnalysisTask1, postProjectAnalysisTask2})
- .finished(allStepsExecuted);
+ .finished(allStepsExecuted);
inOrder.verify(postProjectAnalysisTask1).finished(projectAnalysisArgumentCaptor.capture());
inOrder.verify(postProjectAnalysisTask2).finished(projectAnalysisArgumentCaptor.capture());
}
@Override
- public Optional<String> getMergeBranchUuid() {
- return Optional.empty();
+ public String getMergeBranchUuid() {
+ throw new UnsupportedOperationException();
}
@Override
throw new UnsupportedOperationException();
}
+ @Override public String getTargetBranchName() {
+ throw new UnsupportedOperationException();
+ }
+
@Override
public String generateKey(String projectKey, @Nullable String fileOrDirPath) {
throw new UnsupportedOperationException();
new PostProjectAnalysisTasksExecutor(
ceTask, analysisMetadataHolder, qualityGateHolder, qualityGateStatusHolder, reportReader,
system2, new PostProjectAnalysisTask[] {postProjectAnalysisTask1, postProjectAnalysisTask2, postProjectAnalysisTask3})
- .finished(allStepsExecuted);
+ .finished(allStepsExecuted);
inOrder.verify(postProjectAnalysisTask1).finished(projectAnalysisArgumentCaptor.capture());
inOrder.verify(postProjectAnalysisTask2).finished(projectAnalysisArgumentCaptor.capture());
}
@Test
- @UseDataProvider("nullOrNotNullString")
- public void persist_creates_row_in_PROJECTS_BRANCHES_for_pull_request(@Nullable String mergeBranchUuid) {
+ public void persist_creates_row_in_PROJECTS_BRANCHES_for_pull_request() {
String pullRequestId = "pr-123";
// add project and branch in table PROJECTS
dbTester.commit();
// set project in metadata
treeRootHolder.setRoot(BRANCH);
- analysisMetadataHolder.setBranch(createBranch(PULL_REQUEST, false, pullRequestId, mergeBranchUuid));
+ analysisMetadataHolder.setBranch(createBranch(PULL_REQUEST, false, pullRequestId, "mergeBanchUuid"));
analysisMetadataHolder.setProject(Project.from(mainComponent));
analysisMetadataHolder.setPullRequestKey(pullRequestId);
assertThat(branchDto).isPresent();
assertThat(branchDto.get().getBranchType()).isEqualTo(PULL_REQUEST);
assertThat(branchDto.get().getKey()).isEqualTo(pullRequestId);
- assertThat(branchDto.get().getMergeBranchUuid()).isEqualTo(mergeBranchUuid);
+ assertThat(branchDto.get().getMergeBranchUuid()).isEqualTo("mergeBanchUuid");
assertThat(branchDto.get().getProjectUuid()).isEqualTo(MAIN.getUuid());
assertThat(branchDto.get().getPullRequestData()).isEqualTo(DbProjectBranches.PullRequestData.newBuilder()
.setBranch(pullRequestId)
+ .setTarget("mergeBanchUuid")
.setTitle(pullRequestId)
.build());
}
when(branch.getType()).thenReturn(type);
when(branch.getName()).thenReturn(name);
when(branch.isMain()).thenReturn(isMain);
- when(branch.getMergeBranchUuid()).thenReturn(Optional.ofNullable(mergeBranchUuid));
+ when(branch.getMergeBranchUuid()).thenReturn(mergeBranchUuid);
+ when(branch.getTargetBranchName()).thenReturn(mergeBranchUuid);
return branch;
}
*/
package org.sonar.ce.task.projectanalysis.component;
-import java.util.Optional;
import org.junit.Before;
import org.junit.Rule;
import org.junit.Test;
@Test
public void should_support_db_key() {
- when(branch.getMergeBranchUuid()).thenReturn(Optional.of(mergeBranch.uuid()));
+ when(branch.getMergeBranchUuid()).thenReturn(mergeBranch.uuid());
assertThat(underTest.getUuid(branchFile.getDbKey())).isEqualTo(mergeBranchFile.uuid());
}
@Test
public void should_support_key() {
- when(branch.getMergeBranchUuid()).thenReturn(Optional.of(mergeBranch.uuid()));
+ when(branch.getMergeBranchUuid()).thenReturn(mergeBranch.uuid());
assertThat(underTest.getUuid(branchFile.getKey())).isEqualTo(mergeBranchFile.uuid());
}
@Test
public void return_null_if_file_doesnt_exist() {
- when(branch.getMergeBranchUuid()).thenReturn(Optional.of(mergeBranch.uuid()));
+ when(branch.getMergeBranchUuid()).thenReturn(mergeBranch.uuid());
assertThat(underTest.getUuid("doesnt exist")).isNull();
}
}
*/
package org.sonar.ce.task.projectanalysis.component;
-import java.util.Optional;
import javax.annotation.Nullable;
import org.junit.Before;
import org.junit.Rule;
fileWithOneResolvedIssueOnLong2Short1 = db.components().insertComponent(ComponentTesting.newFileDto(long2short1, null));
db.issues().insertIssue(IssueTesting.newIssue(rule, long2short1, fileWithOneResolvedIssueOnLong2Short1).setStatus("RESOLVED"));
- setCurrentBranchUuid(long1.uuid());
+ setRoot(long1);
underTest = new SiblingComponentsWithOpenIssues(treeRootHolder, metadataHolder, db.getDbClient());
}
@Test
public void should_find_sibling_components_with_open_issues_for_long1() {
- setCurrentBranchUuid(long1.uuid());
- setReferenceBranchUuid(null);
+ setRoot(long1);
+ setBranch(BranchType.LONG);
assertThat(underTest.getUuids(fileWithNoIssuesOnLong1.getKey())).isEmpty();
assertThat(underTest.getUuids(fileWithOneOpenIssueOnLong1Short1.getKey())).containsOnly(fileWithOneOpenIssueOnLong1Short1.uuid());
@Test
public void should_find_sibling_components_with_open_issues_for_short1() {
- setCurrentBranchUuid(long1short1.uuid());
- setReferenceBranchUuid(long1.uuid());
+ setRoot(long1short1);
+ setBranch(BranchType.SHORT, long1.uuid());
assertThat(underTest.getUuids(fileWithNoIssuesOnLong1.getKey())).isEmpty();
assertThat(underTest.getUuids(fileWithOneOpenIssueOnLong1Short1.getKey())).isEmpty();
@Test
public void should_find_sibling_components_with_open_issues_for_long2() {
- setCurrentBranchUuid(long2.uuid());
- setReferenceBranchUuid(null);
+ setRoot(long2);
+ setBranch(BranchType.LONG);
+
underTest = new SiblingComponentsWithOpenIssues(treeRootHolder, metadataHolder, db.getDbClient());
assertThat(underTest.getUuids(fileWithOneResolvedIssueOnLong1Short1.getKey())).isEmpty();
@Test
public void should_find_sibling_components_with_open_issues_from_short() {
ComponentDto project = db.components().insertMainBranch();
- setCurrentBranchUuid(project.uuid());
- setReferenceBranchUuid(null);
+ setRoot(project);
+ setBranch(BranchType.LONG);
ComponentDto branch = db.components().insertProjectBranch(project,
b -> b.setBranchType(BranchType.SHORT),
@Test
public void should_find_sibling_components_with_open_issues_from_pullrequest() {
ComponentDto project = db.components().insertMainBranch();
- setCurrentBranchUuid(project.uuid());
- setReferenceBranchUuid(null);
+ setRoot(project);
+ setBranch(BranchType.LONG);
ComponentDto pullRequest = db.components().insertProjectBranch(project,
b -> b.setBranchType(BranchType.PULL_REQUEST),
@Test
public void should_not_find_sibling_components_on_derived_long() {
ComponentDto project = db.components().insertMainBranch();
- setCurrentBranchUuid(project.uuid());
- setReferenceBranchUuid(null);
+ setRoot(project);
+ setBranch(BranchType.LONG);
ComponentDto derivedLongBranch = db.components().insertProjectBranch(project,
b -> b.setBranchType(BranchType.LONG),
assertThat(underTest.getUuids(fileWithResolvedIssueOnDerivedLongBranch.getKey())).isEmpty();
}
- private void setCurrentBranchUuid(String uuid) {
+ private void setRoot(ComponentDto componentDto) {
Component root = mock(Component.class);
- when(root.getUuid()).thenReturn(uuid);
+ when(root.getUuid()).thenReturn(componentDto.uuid());
treeRootHolder.setRoot(root);
}
- private void setReferenceBranchUuid(@Nullable String uuid) {
+ private void setBranch(BranchType currentBranchType) {
+ setBranch(currentBranchType, null);
+ }
+
+ private void setBranch(BranchType currentBranchType, @Nullable String mergeBranchUuid) {
Branch branch = mock(Branch.class);
- when(branch.getMergeBranchUuid()).thenReturn(Optional.ofNullable(uuid));
+ when(branch.getType()).thenReturn(currentBranchType);
+ when(branch.getMergeBranchUuid()).thenReturn(mergeBranchUuid);
metadataHolder.setBranch(branch);
}
}
import java.time.temporal.ChronoUnit;
import java.util.Collections;
import java.util.Date;
-import java.util.Optional;
import javax.annotation.Nullable;
import org.junit.Before;
import org.junit.Rule;
private static final org.sonar.ce.task.projectanalysis.component.Component FILE_1 = builder(
org.sonar.ce.task.projectanalysis.component.Component.Type.FILE, FILE_1_REF)
- .setKey(FILE_1_KEY)
- .setUuid(FILE_1_UUID)
- .build();
+ .setKey(FILE_1_KEY)
+ .setUuid(FILE_1_UUID)
+ .build();
private SimpleTracker<DefaultIssue, SiblingIssue> tracker = new SimpleTracker<>();
private SiblingsIssueMerger copier;
@Before
public void setUp() {
MockitoAnnotations.initMocks(this);
- when(branch.getMergeBranchUuid()).thenReturn(Optional.empty());
- metadataHolder.setBranch(branch);
DbClient dbClient = db.getDbClient();
ComponentIssuesLoader componentIssuesLoader = new ComponentIssuesLoader(dbClient, null, null, new MapSettings().asConfig(), System2.INSTANCE);
- copier = new SiblingsIssueMerger(new SiblingsIssuesLoader(new SiblingComponentsWithOpenIssues(treeRootHolder, metadataHolder, dbClient), dbClient, componentIssuesLoader), tracker,
+ copier = new SiblingsIssueMerger(new SiblingsIssuesLoader(new SiblingComponentsWithOpenIssues(treeRootHolder, metadataHolder, dbClient), dbClient, componentIssuesLoader),
+ tracker,
issueLifecycle);
projectDto = db.components().insertMainBranch(p -> p.setDbKey(PROJECT_KEY).setUuid(PROJECT_UUID));
branch1Dto = db.components().insertProjectBranch(projectDto, b -> b.setKey("myBranch1")
fileOnBranch2Dto = db.components().insertComponent(newFileDto(branch2Dto).setDbKey(FILE_1_KEY + ":BRANCH:myBranch2"));
fileOnBranch3Dto = db.components().insertComponent(newFileDto(branch3Dto).setDbKey(FILE_1_KEY + ":BRANCH:myBranch3"));
rule = db.rules().insert();
+ when(branch.getMergeBranchUuid()).thenReturn(projectDto.uuid());
+ metadataHolder.setBranch(branch);
}
@Test
String mergeFileUuid = "mergeFileUuid";
String hash = computeSourceHash(1);
- when(branch.getMergeBranchUuid()).thenReturn(Optional.of("mergeBranchUuid"));
+ when(branch.getMergeBranchUuid()).thenReturn("mergeBranchUuid");
when(mergeBranchComponentUuids.getUuid(FILE.getDbKey())).thenReturn(mergeFileUuid);
addFileSourceInDb("henry", DATE_1, "rev-1", hash, mergeFileUuid);
@Test
public void do_not_read_from_db_on_first_analysis_and_no_merge_branch() {
Branch branch = mock(Branch.class);
- when(branch.getMergeBranchUuid()).thenReturn(Optional.empty());
analysisMetadataHolder.setBaseAnalysis(null);
analysisMetadataHolder.setBranch(branch);
import java.text.SimpleDateFormat;
import java.util.Arrays;
import java.util.Date;
-import java.util.Optional;
import java.util.Random;
import java.util.stream.Stream;
import javax.annotation.Nullable;
}
@Override
- public Optional<String> getMergeBranchUuid() {
+ public String getMergeBranchUuid() {
throw new UnsupportedOperationException("getMergeBranchUuid not implemented");
}
throw new UnsupportedOperationException("getPullRequestKey not implemented");
}
+ @Override
+ public String getTargetBranchName() {
+ throw new UnsupportedOperationException();
+ }
+
@Override
public String generateKey(String projectKey, @Nullable String fileOrDirPath) {
throw new UnsupportedOperationException("generateKey not implemented");
}
@Override
- public java.util.Optional<String> getMergeBranchUuid() {
- return java.util.Optional.empty();
+ public String getMergeBranchUuid() {
+ throw new UnsupportedOperationException();
}
@Override
throw new UnsupportedOperationException();
}
+ @Override
+ public String getTargetBranchName() {
+ throw new UnsupportedOperationException();
+ }
+
@Override
public String generateKey(String projectKey, @Nullable String fileOrDirPath) {
if (isEmpty(fileOrDirPath)) {
package org.sonar.ce.task.projectanalysis.step;
import java.util.Date;
-import java.util.Optional;
import javax.annotation.Nullable;
import org.junit.Rule;
import org.junit.Test;
underTest.execute(new TestComputationStepContext());
}
-
private void setBranch(BranchType type, @Nullable String mergeBranchUuid) {
Branch branch = mock(Branch.class);
when(branch.getType()).thenReturn(type);
- when(branch.getMergeBranchUuid()).thenReturn(Optional.ofNullable(mergeBranchUuid));
+ when(branch.getMergeBranchUuid()).thenReturn(mergeBranchUuid);
analysisMetadataHolder.setBranch(branch);
}
return mapper(dbSession).selectProjectsByNameQuery(nameQueryForSql, includeModules);
}
+ /**
+ * Returns components with open issues from branches that use a certain long living branch as reference (merge branch).
+ * Excludes components from the current branch.
+ */
public List<KeyWithUuidDto> selectAllSiblingComponentKeysHavingOpenIssues(DbSession dbSession, String referenceBranchUuid, String currentBranchUuid) {
return mapper(dbSession).selectAllSiblingComponentKeysHavingOpenIssues(referenceBranchUuid, currentBranchUuid);
}
string url = 3;
map<string, string> attributes = 4;
+
+ string target = 5;
}
import java.util.Optional;
import java.util.function.Function;
import javax.annotation.Nullable;
+import org.apache.commons.lang.StringUtils;
import org.sonar.api.server.ws.Request;
import org.sonar.api.server.ws.Response;
import org.sonar.api.server.ws.WebService;
} else {
builder.setIsOrphan(true);
}
+
+ if (StringUtils.isNotEmpty(pullRequestData.getTarget())) {
+ builder.setTarget(pullRequestData.getTarget());
+ } else if (mergeBranch.isPresent()) {
+ builder.setTarget(mergeBranch.get().getKey());
+ }
+
ofNullable(analysisDate).ifPresent(builder::setAnalysisDate);
setQualityGate(builder, qualityGateMeasure, branchStatistics);
response.addPullRequests(builder);
"codeSmells": 0
},
"analysisDate": "2017-04-01T02:15:42+0200",
- "url": "https://github.com/SonarSource/sonar-core-plugins/pull/32"
+ "url": "https://github.com/SonarSource/sonar-core-plugins/pull/32",
+ "target": "feature/foo"
}
]
}
import javax.annotation.Nullable;
import org.sonar.api.batch.fs.InputFile;
+@Deprecated
+/**
+ * @deprecated since 7.8
+ */
public class StatusPredicate extends AbstractFilePredicate {
private final InputFile.Status status;
@Override
public void publish(ScannerReportWriter writer) {
- String targetScmBranch = branchConfiguration.targetScmBranch();
- if (scmConfiguration.isDisabled() || !branchConfiguration.isShortOrPullRequest() || targetScmBranch == null) {
+ String targetBranchName = branchConfiguration.targetBranchName();
+ if (scmConfiguration.isDisabled() || !branchConfiguration.isShortOrPullRequest() || targetBranchName == null) {
return;
}
}
Profiler profiler = Profiler.create(LOG).startInfo(LOG_MSG);
- int count = writeChangedLines(provider, writer, targetScmBranch);
+ int count = writeChangedLines(provider, writer, targetBranchName);
LOG.debug("SCM reported changed lines for {} {} in the branch", count, ScannerUtils.pluralize("file", count));
profiler.stopInfo();
}
if (referenceBranch != null) {
builder.setMergeBranchName(referenceBranch);
}
+ String targetBranchName = branchConfiguration.targetBranchName();
+ if (targetBranchName != null) {
+ builder.setTargetBranchName(targetBranchName);
+ }
if (branchType == BranchType.PULL_REQUEST) {
builder.setPullRequestKey(branchConfiguration.pullRequestKey());
}
this.wsClient = wsClient;
}
- @Override
- public List<QualityProfile> loadDefault() {
+ private List<QualityProfile> loadDefault() {
StringBuilder url = new StringBuilder(WS_URL + "?defaults=true");
- return handleErrors(url, () -> "Failed to load the default quality profiles");
+ return handleErrors(url, () -> "Failed to load the default quality profiles", false);
}
@Override
public List<QualityProfile> load(String projectKey) {
StringBuilder url = new StringBuilder(WS_URL + "?projectKey=").append(encodeForUrl(projectKey));
- return handleErrors(url, () -> String.format("Failed to load the quality profiles of project '%s'", 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) {
+ private List<QualityProfile> handleErrors(StringBuilder url, Supplier<String> errorMsg, boolean tryLoadDefault) {
try {
return doLoad(url);
} catch (HttpException e) {
if (e.code() == 404) {
- throw MessageException.of(errorMsg.get() + ": " + ScannerWsClient.createErrorMessage(e));
+ if (tryLoadDefault) {
+ return loadDefault();
+ } else {
+ throw MessageException.of(errorMsg.get() + ": " + ScannerWsClient.createErrorMessage(e));
+ }
}
throw new IllegalStateException(errorMsg.get() + ": " + ScannerWsClient.createErrorMessage(e));
} catch (MessageException e) {
+++ /dev/null
-/*
- * SonarQube
- * Copyright (C) 2009-2019 SonarSource SA
- * mailto:info AT sonarsource DOT com
- *
- * This program is free software; you can redistribute it and/or
- * modify it under the terms of the GNU Lesser General Public
- * License as published by the Free Software Foundation; either
- * version 3 of the License, or (at your option) any later version.
- *
- * This program is distributed in the hope that it will be useful,
- * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
- * Lesser General Public License for more details.
- *
- * You should have received a copy of the GNU Lesser General Public License
- * along with this program; if not, write to the Free Software Foundation,
- * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
- */
-package org.sonar.scanner.repository;
-
-import org.picocontainer.injectors.ProviderAdapter;
-import org.sonar.api.utils.log.Logger;
-import org.sonar.api.utils.log.Loggers;
-import org.sonar.api.utils.log.Profiler;
-import org.sonar.scanner.bootstrap.ProcessedScannerProperties;
-import org.sonar.scanner.scan.branch.BranchConfiguration;
-
-public class ProjectRepositoriesProvider extends ProviderAdapter {
- private static final Logger LOG = Loggers.get(ProjectRepositoriesProvider.class);
- private static final String LOG_MSG = "Load project repositories";
- private ProjectRepositories project = null;
-
- public ProjectRepositories provide(ProjectRepositoriesLoader loader, ProcessedScannerProperties scannerProperties, BranchConfiguration branchConfig) {
- if (project == null) {
- Profiler profiler = Profiler.create(LOG).startInfo(LOG_MSG);
- project = loader.load(scannerProperties.getKeyWithBranch(), branchConfig.longLivingSonarReferenceBranch());
- profiler.stopInfo();
- }
-
- return project;
- }
-}
--- /dev/null
+/*
+ * SonarQube
+ * Copyright (C) 2009-2019 SonarSource SA
+ * mailto:info AT sonarsource DOT com
+ *
+ * This program is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU Lesser General Public
+ * License as published by the Free Software Foundation; either
+ * version 3 of the License, or (at your option) any later version.
+ *
+ * This program is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+ * Lesser General Public License for more details.
+ *
+ * You should have received a copy of the GNU Lesser General Public License
+ * along with this program; if not, write to the Free Software Foundation,
+ * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
+ */
+package org.sonar.scanner.repository;
+
+import java.util.function.Supplier;
+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.ProcessedScannerProperties;
+import org.sonar.scanner.scan.branch.BranchConfiguration;
+
+public class ProjectRepositoriesSupplier implements Supplier<ProjectRepositories> {
+ private static final Logger LOG = Loggers.get(ProjectRepositoriesSupplier.class);
+ private static final String LOG_MSG = "Load project repositories";
+ private final ProjectRepositoriesLoader loader;
+ private final ProcessedScannerProperties scannerProperties;
+ private final BranchConfiguration branchConfig;
+
+ private ProjectRepositories project = null;
+
+ public ProjectRepositoriesSupplier(ProjectRepositoriesLoader loader, ProcessedScannerProperties scannerProperties, BranchConfiguration branchConfig) {
+ this.loader = loader;
+ this.scannerProperties = scannerProperties;
+ this.branchConfig = branchConfig;
+ }
+
+ public ProjectRepositories get() {
+ if (project == null) {
+ Profiler profiler = Profiler.create(LOG).startInfo(LOG_MSG);
+ project = loader.load(scannerProperties.getKeyWithBranch(), branchConfig.longLivingSonarReferenceBranch());
+ profiler.stopInfo();
+ }
+
+ return project;
+ }
+}
public interface QualityProfileLoader {
List<QualityProfile> load(String projectKey);
-
- List<QualityProfile> loadDefault();
}
*/
package org.sonar.scanner.repository;
-import java.util.List;
import org.picocontainer.injectors.ProviderAdapter;
import org.sonar.api.utils.log.Logger;
import org.sonar.api.utils.log.Loggers;
import org.sonar.api.utils.log.Profiler;
import org.sonar.scanner.bootstrap.ProcessedScannerProperties;
import org.sonar.scanner.rule.QualityProfiles;
-import org.sonarqube.ws.Qualityprofiles.SearchWsResponse.QualityProfile;
public class QualityProfilesProvider extends ProviderAdapter {
private static final Logger LOG = Loggers.get(QualityProfilesProvider.class);
private static final String LOG_MSG = "Load quality profiles";
private QualityProfiles profiles = null;
- public QualityProfiles provide(QualityProfileLoader loader, ProjectRepositories projectRepositories, ProcessedScannerProperties props) {
+ public QualityProfiles provide(QualityProfileLoader loader, ProcessedScannerProperties props) {
if (this.profiles == null) {
- List<QualityProfile> profileList;
Profiler profiler = Profiler.create(LOG).startInfo(LOG_MSG);
- if (!projectRepositories.exists()) {
- profileList = loader.loadDefault();
- } else {
- profileList = loader.load(props.getKeyWithBranch());
- }
+ profiles = new QualityProfiles(loader.load(props.getKeyWithBranch()));
profiler.stopInfo();
- profiles = new QualityProfiles(profileList);
}
return profiles;
import org.sonar.scanner.repository.DefaultProjectRepositoriesLoader;
import org.sonar.scanner.repository.DefaultQualityProfileLoader;
import org.sonar.scanner.repository.ProjectRepositoriesLoader;
-import org.sonar.scanner.repository.ProjectRepositoriesProvider;
+import org.sonar.scanner.repository.ProjectRepositoriesSupplier;
import org.sonar.scanner.repository.QualityProfileLoader;
import org.sonar.scanner.repository.QualityProfilesProvider;
import org.sonar.scanner.repository.language.DefaultLanguagesRepository;
new ProjectBranchesProvider(),
new ProjectPullRequestsProvider(),
DefaultAnalysisMode.class,
- new ProjectRepositoriesProvider(),
+ ProjectRepositoriesSupplier.class,
new ProjectServerSettingsProvider(),
// temp
BranchConfiguration branchConfig = getComponentByType(BranchConfiguration.class);
if (branchConfig.branchType() == BranchType.PULL_REQUEST) {
- LOG.info("Pull request {} for merge into {} from {}", branchConfig.pullRequestKey(), pullRequestBaseToDisplayName(branchConfig.targetScmBranch()), branchConfig.branchName());
+ LOG.info("Pull request {} for merge into {} from {}", branchConfig.pullRequestKey(), pullRequestBaseToDisplayName(branchConfig.targetBranchName()), branchConfig.branchName());
} else if (branchConfig.branchName() != null) {
LOG.info("Branch name: {}, type: {}", branchConfig.branchName(), branchTypeToDisplayName(branchConfig.branchType()));
}
/**
* The type of the branch we're on, determined by:
- *
* - If the specified branch exists on the server, then its type
* - If the branch name matches the pattern of long-lived branches, then it's long-lived
* - Otherwise it's short-lived
/**
* For long/short living 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)
- * Only @null if the branch feature is not available.
+ *
+ * @return null if the branch feature is not available or no branch was specified.
*/
@CheckForNull
String branchName();
* transitively use its own target.
* For PR, we look at sonar.pullrequest.base (default to default branch). If it exists but is a short living branch or PR, we will
* transitively use its own target. If base is not analyzed, we will use default branch.
- * Only @null if the branch feature is not available.
+ *
+ * @return null if the branch feature is not available or no branch was specified.
*/
@CheckForNull
String longLivingSonarReferenceBranch();
/**
- * Raw value of sonar.branch.target or sonar.pullrequest.base (fallback to the default branch), will be used by the SCM to compute changed files and changed lines.
- * @null for long living branches and if the branch feature is not available
+ * Raw value of sonar.branch.target or sonar.pullrequest.base (fallback to the default branch).
+ * 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, the branch being analyzed is the main branch or no branch was specified.
*/
@CheckForNull
- String targetScmBranch();
+ String targetBranchName();
/**
* The key of the pull request.
@CheckForNull
@Override
- public String targetScmBranch() {
+ public String targetBranchName() {
return null;
}
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.repository.ProjectRepositoriesSupplier;
import org.sonar.scanner.scm.ScmChangedFiles;
import static org.sonar.api.batch.fs.InputFile.Status.ADDED;
@Immutable
public class StatusDetection {
- private final ProjectRepositories projectRepositories;
+ private final ProjectRepositoriesSupplier projectSettingsSupplier;
private final ScmChangedFiles scmChangedFiles;
- public StatusDetection(ProjectRepositories projectSettings, ScmChangedFiles scmChangedFiles) {
- this.projectRepositories = projectSettings;
+ public StatusDetection(ProjectRepositoriesSupplier projectSettingsSupplier, ScmChangedFiles scmChangedFiles) {
+ this.projectSettingsSupplier = projectSettingsSupplier;
this.scmChangedFiles = scmChangedFiles;
}
InputFile.Status status(String moduleKeyWithBranch, DefaultInputFile inputFile, String hash) {
- FileData fileDataPerPath = projectRepositories.fileData(moduleKeyWithBranch, inputFile);
+ if (scmChangedFiles.isValid()) {
+ return checkChangedWithScm(inputFile);
+ }
+ return checkChangedWithProjectRepositories(moduleKeyWithBranch, inputFile, hash);
+ }
+
+ private InputFile.Status checkChangedWithProjectRepositories(String moduleKeyWithBranch, DefaultInputFile inputFile, String hash) {
+ FileData fileDataPerPath = projectSettingsSupplier.get().fileData(moduleKeyWithBranch, inputFile);
if (fileDataPerPath == null) {
- return checkChanged(ADDED, inputFile);
+ return ADDED;
}
String previousHash = fileDataPerPath.hash();
if (StringUtils.equals(hash, previousHash)) {
return SAME;
}
if (StringUtils.isEmpty(previousHash)) {
- return checkChanged(ADDED, inputFile);
+ return ADDED;
}
- return checkChanged(CHANGED, inputFile);
+ return CHANGED;
}
- private InputFile.Status checkChanged(InputFile.Status status, DefaultInputFile inputFile) {
- if (!scmChangedFiles.verifyChanged(inputFile.path())) {
+ private InputFile.Status checkChangedWithScm(DefaultInputFile inputFile) {
+ if (!scmChangedFiles.isChanged(inputFile.path())) {
return SAME;
}
- return status;
+ return CHANGED;
}
}
import java.nio.file.Path;
import java.util.Collection;
+import javax.annotation.CheckForNull;
import javax.annotation.Nullable;
import javax.annotation.concurrent.Immutable;
this.fileCollection = changedFiles;
}
- public boolean verifyChanged(Path file) {
- return fileCollection == null || fileCollection.contains(file);
+ public boolean isChanged(Path file) {
+ if (!isValid()) {
+ throw new IllegalStateException("Scm didn't provide valid data");
+ }
+
+ return fileCollection.contains(file);
+ }
+
+ public boolean isValid() {
+ return fileCollection != null;
}
+ @CheckForNull
Collection<Path> get() {
return fileCollection;
}
import java.nio.file.Path;
import java.util.Collection;
import javax.annotation.CheckForNull;
-import org.picocontainer.annotations.Nullable;
import org.picocontainer.injectors.ProviderAdapter;
import org.sonar.api.batch.fs.internal.DefaultInputProject;
import org.sonar.api.batch.scm.ScmProvider;
private ScmChangedFiles scmBranchChangedFiles;
- /*
- * ScmConfiguration is not available in issues mode
- */
- public ScmChangedFiles provide(@Nullable ScmConfiguration scmConfiguration, BranchConfiguration branchConfiguration, DefaultInputProject project) {
+ public ScmChangedFiles provide(ScmConfiguration scmConfiguration, BranchConfiguration branchConfiguration, DefaultInputProject project) {
if (scmBranchChangedFiles == null) {
- if (scmConfiguration == null) {
- scmBranchChangedFiles = new ScmChangedFiles(null);
- } else {
- Path rootBaseDir = project.getBaseDir();
- Collection<Path> changedFiles = loadChangedFilesIfNeeded(scmConfiguration, branchConfiguration, rootBaseDir);
- validatePaths(changedFiles);
- scmBranchChangedFiles = new ScmChangedFiles(changedFiles);
- }
+ Path rootBaseDir = project.getBaseDir();
+ Collection<Path> changedFiles = loadChangedFilesIfNeeded(scmConfiguration, branchConfiguration, rootBaseDir);
+ validatePaths(changedFiles);
+ scmBranchChangedFiles = new ScmChangedFiles(changedFiles);
}
return scmBranchChangedFiles;
}
@CheckForNull
private static Collection<Path> loadChangedFilesIfNeeded(ScmConfiguration scmConfiguration, BranchConfiguration branchConfiguration, Path rootBaseDir) {
- String targetScmBranch = branchConfiguration.targetScmBranch();
- if (branchConfiguration.isShortOrPullRequest() && targetScmBranch != null) {
+ final String targetBranchName = branchConfiguration.targetBranchName();
+ if (branchConfiguration.isShortOrPullRequest() && targetBranchName != null) {
ScmProvider scmProvider = scmConfiguration.provider();
if (scmProvider != null) {
Profiler profiler = Profiler.create(LOG).startInfo(LOG_MSG);
- Collection<Path> changedFiles = scmProvider.branchChangedFiles(targetScmBranch, rootBaseDir);
+ Collection<Path> changedFiles = scmProvider.branchChangedFiles(targetBranchName, rootBaseDir);
profiler.stopInfo();
if (changedFiles != null) {
LOG.debug("SCM reported {} {} changed in the branch", changedFiles.size(), ScannerUtils.pluralize("file", changedFiles.size()));
import org.sonar.scanner.protocol.output.ScannerReportWriter;
import org.sonar.scanner.report.ReportPublisher;
import org.sonar.scanner.repository.FileData;
-import org.sonar.scanner.repository.ProjectRepositories;
+import org.sonar.scanner.repository.ProjectRepositoriesSupplier;
import org.sonar.scanner.scan.branch.BranchConfiguration;
import org.sonar.scanner.scan.filesystem.InputComponentStore;
private static final Logger LOG = Loggers.get(ScmPublisher.class);
private final ScmConfiguration configuration;
- private final ProjectRepositories projectRepositories;
+ private final ProjectRepositoriesSupplier projectRepositoriesSupplier;
private final InputComponentStore componentStore;
private final FileSystem fs;
private final ScannerReportWriter writer;
private final BranchConfiguration branchConfiguration;
- public ScmPublisher(ScmConfiguration configuration, ProjectRepositories projectRepositories,
- InputComponentStore componentStore, FileSystem fs, ReportPublisher reportPublisher, BranchConfiguration branchConfiguration) {
+ public ScmPublisher(ScmConfiguration configuration, ProjectRepositoriesSupplier projectRepositoriesSupplier,
+ InputComponentStore componentStore, FileSystem fs, ReportPublisher reportPublisher, BranchConfiguration branchConfiguration) {
this.configuration = configuration;
- this.projectRepositories = projectRepositories;
+ this.projectRepositoriesSupplier = projectRepositoriesSupplier;
this.componentStore = componentStore;
this.fs = fs;
this.branchConfiguration = branchConfiguration;
if (configuration.forceReloadAll() || f.status() != Status.SAME) {
addIfNotEmpty(filesToBlame, f);
} else if (!branchConfiguration.isShortOrPullRequest()) {
- // File status is SAME so that mean fileData exists
- FileData fileData = projectRepositories.fileData(componentStore.findModule(f).getKeyWithBranch(), f);
- if (StringUtils.isEmpty(fileData.revision())) {
+ FileData fileData = projectRepositoriesSupplier.get().fileData(componentStore.findModule(f).getKeyWithBranch(), f);
+ if (fileData == null || StringUtils.isEmpty(fileData.revision())) {
addIfNotEmpty(filesToBlame, f);
} else {
- askToCopyDataFromPreviousAnalysis((DefaultInputFile) f, writer);
+ askToCopyDataFromPreviousAnalysis(f, writer);
}
}
}
/**
* Main utility class for writing scanner medium tests.
- *
*/
public class ScannerMediumTester extends ExternalResource {
@CheckForNull
@Override
- public String targetScmBranch() {
+ public String targetBranchName() {
return branchTarget;
}
public List<QualityProfile> load(String projectKey) {
return qualityProfiles;
}
-
- @Override
- public List<QualityProfile> loadDefault() {
- return qualityProfiles;
- }
}
private static class FakeGlobalSettingsLoader implements GlobalSettingsLoader {
when(branchConfiguration.isShortOrPullRequest()).thenReturn(true);
when(scmConfiguration.isDisabled()).thenReturn(false);
when(scmConfiguration.provider()).thenReturn(provider);
- when(branchConfiguration.targetScmBranch()).thenReturn(TARGET_BRANCH);
+ when(branchConfiguration.targetBranchName()).thenReturn(TARGET_BRANCH);
when(project.getBaseDir()).thenReturn(BASE_DIR);
}
@Test
public void skip_if_target_branch_is_null() {
- when(branchConfiguration.targetScmBranch()).thenReturn(null);
+ when(branchConfiguration.targetBranchName()).thenReturn(null);
publisher.publish(writer);
verifyZeroInteractions(inputComponentStore, inputModuleHierarchy, provider);
assertNotPublished();
@Test
public void write_short_lived_branch_info() throws Exception {
String branchName = "feature";
- String branchTarget = "short-lived";
+ String targetBranchName = "short-lived";
+ String longLivingSonarReferenceBranch = "long-lived";
when(branches.branchName()).thenReturn(branchName);
- when(branches.longLivingSonarReferenceBranch()).thenReturn(branchTarget);
+ when(branches.targetBranchName()).thenReturn(targetBranchName);
+ when(branches.longLivingSonarReferenceBranch()).thenReturn(longLivingSonarReferenceBranch);
File outputDir = temp.newFolder();
underTest.publish(new ScannerReportWriter(outputDir));
ScannerReport.Metadata metadata = reader.readMetadata();
assertThat(metadata.getBranchName()).isEqualTo(branchName);
assertThat(metadata.getBranchType()).isEqualTo(ScannerReport.Metadata.BranchType.SHORT);
- assertThat(metadata.getMergeBranchName()).isEqualTo(branchTarget);
+ assertThat(metadata.getMergeBranchName()).isEqualTo(longLivingSonarReferenceBranch);
+ assertThat(metadata.getTargetBranchName()).isEqualTo(targetBranchName);
}
@Test
}
@Test
- public void loadDefault_gets_all_default_profiles() throws IOException {
- prepareCallWithResults();
- underTest.loadDefault();
+ public void load_tries_default_if_no_profiles_found_for_project() throws IOException {
+ HttpException e = new HttpException("", 404, "{\"errors\":[{\"msg\":\"No project found with key 'foo'\"}]}");
+ WsTestUtil.mockException(wsClient, "/api/qualityprofiles/search.protobuf?projectKey=foo", e);
+ WsTestUtil.mockStream(wsClient, "/api/qualityprofiles/search.protobuf?defaults=true", createStreamOfProfiles("qp"));
+
+ underTest.load("foo");
+
+ verifyCalledPath("/api/qualityprofiles/search.protobuf?projectKey=foo");
verifyCalledPath("/api/qualityprofiles/search.protobuf?defaults=true");
}
@Test
public void loadDefault_sets_organization_parameter_if_defined_in_settings() throws IOException {
when(properties.organizationKey()).thenReturn(Optional.of("my-org"));
+
+ HttpException e = new HttpException("", 404, "{\"errors\":[{\"msg\":\"No organization with key 'myorg'\"}]}");
+ WsTestUtil.mockException(wsClient, "/api/qualityprofiles/search.protobuf?projectKey=foo&organization=my-org", e);
WsTestUtil.mockStream(wsClient, "/api/qualityprofiles/search.protobuf?defaults=true&organization=my-org", createStreamOfProfiles("qp"));
- underTest.loadDefault();
+
+ underTest.load("foo");
+
verifyCalledPath("/api/qualityprofiles/search.protobuf?defaults=true&organization=my-org");
}
}
@Test
- public void load_throws_MessageException_if_organization_is_not_found() throws IOException {
+ public void load_throws_MessageException_if_organization_is_not_found_after_trying_default() throws IOException {
HttpException e = new HttpException("", 404, "{\"errors\":[{\"msg\":\"No organization with key 'myorg'\"}]}");
WsTestUtil.mockException(wsClient, e);
exception.expect(MessageException.class);
- exception.expectMessage("Failed to load the quality profiles of project 'project': No organization with key 'myorg'");
+ exception.expectMessage("Failed to load the default quality profiles: No organization with key 'myorg'");
underTest.load("project");
verifyNoMoreInteractions(wsClient);
+++ /dev/null
-/*
- * SonarQube
- * Copyright (C) 2009-2019 SonarSource SA
- * mailto:info AT sonarsource DOT com
- *
- * This program is free software; you can redistribute it and/or
- * modify it under the terms of the GNU Lesser General Public
- * License as published by the Free Software Foundation; either
- * version 3 of the License, or (at your option) any later version.
- *
- * This program is distributed in the hope that it will be useful,
- * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
- * Lesser General Public License for more details.
- *
- * You should have received a copy of the GNU Lesser General Public License
- * along with this program; if not, write to the Free Software Foundation,
- * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
- */
-package org.sonar.scanner.repository;
-
-import com.google.common.collect.Maps;
-import java.util.Map;
-import org.junit.Before;
-import org.junit.Test;
-import org.mockito.Mock;
-import org.mockito.MockitoAnnotations;
-import org.sonar.scanner.bootstrap.ProcessedScannerProperties;
-import org.sonar.scanner.scan.branch.BranchConfiguration;
-
-import static org.assertj.core.api.Assertions.assertThat;
-import static org.mockito.ArgumentMatchers.any;
-import static org.mockito.ArgumentMatchers.eq;
-import static org.mockito.Mockito.verify;
-import static org.mockito.Mockito.verifyNoMoreInteractions;
-import static org.mockito.Mockito.when;
-
-public class ProjectRepositoriesProviderTest {
- private ProjectRepositoriesProvider provider;
- private ProjectRepositories project;
-
- @Mock
- private ProjectRepositoriesLoader loader;
- @Mock
- private ProcessedScannerProperties props;
- @Mock
- private BranchConfiguration branchConfiguration;
-
- @Before
- public void setUp() {
- MockitoAnnotations.initMocks(this);
-
- Map<String, FileData> fileMap = Maps.newHashMap();
-
- project = new SingleProjectRepository(fileMap);
- provider = new ProjectRepositoriesProvider();
-
- when(props.getKeyWithBranch()).thenReturn("key");
- }
-
- @Test
- public void testValidation() {
- when(loader.load(eq("key"), any())).thenReturn(project);
-
- provider.provide(loader, props, branchConfiguration);
- }
-
- @Test
- public void testAssociated() {
- when(loader.load(eq("key"), any())).thenReturn(project);
-
- ProjectRepositories repo = provider.provide(loader, props, branchConfiguration);
-
- assertThat(repo.exists()).isEqualTo(true);
-
- verify(props).getKeyWithBranch();
- verify(loader).load(eq("key"), eq(null));
- verifyNoMoreInteractions(loader, props);
- }
-}
--- /dev/null
+/*
+ * SonarQube
+ * Copyright (C) 2009-2019 SonarSource SA
+ * mailto:info AT sonarsource DOT com
+ *
+ * This program is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU Lesser General Public
+ * License as published by the Free Software Foundation; either
+ * version 3 of the License, or (at your option) any later version.
+ *
+ * This program is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+ * Lesser General Public License for more details.
+ *
+ * You should have received a copy of the GNU Lesser General Public License
+ * along with this program; if not, write to the Free Software Foundation,
+ * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
+ */
+package org.sonar.scanner.repository;
+
+import com.google.common.collect.Maps;
+import java.util.Map;
+import org.junit.Before;
+import org.junit.Test;
+import org.sonar.scanner.bootstrap.ProcessedScannerProperties;
+import org.sonar.scanner.scan.branch.BranchConfiguration;
+
+import static org.assertj.core.api.Assertions.assertThat;
+import static org.mockito.ArgumentMatchers.any;
+import static org.mockito.ArgumentMatchers.eq;
+import static org.mockito.Mockito.mock;
+import static org.mockito.Mockito.verify;
+import static org.mockito.Mockito.verifyNoMoreInteractions;
+import static org.mockito.Mockito.when;
+
+public class ProjectRepositoriesSupplierTest {
+ private ProjectRepositoriesSupplier underTest;
+ private ProjectRepositories project;
+
+ private ProjectRepositoriesLoader loader = mock(ProjectRepositoriesLoader.class);
+ private ProcessedScannerProperties props = mock(ProcessedScannerProperties.class);
+ private BranchConfiguration branchConfiguration = mock(BranchConfiguration.class);
+
+ @Before
+ public void setUp() {
+ underTest = new ProjectRepositoriesSupplier(loader, props, branchConfiguration);
+ Map<String, FileData> fileMap = Maps.newHashMap();
+ project = new SingleProjectRepository(fileMap);
+ when(props.getKeyWithBranch()).thenReturn("key");
+ }
+
+ @Test
+ public void testValidation() {
+ when(loader.load(eq("key"), any())).thenReturn(project);
+ underTest.get();
+ }
+
+ @Test
+ public void testAssociated() {
+ when(loader.load(eq("key"), any())).thenReturn(project);
+ ProjectRepositories repo = underTest.get();
+
+ assertThat(repo.exists()).isEqualTo(true);
+
+ verify(props).getKeyWithBranch();
+ verify(loader).load(eq("key"), eq(null));
+ verifyNoMoreInteractions(loader, props);
+ }
+}
*/
package org.sonar.scanner.repository;
-import com.google.common.collect.ImmutableMap;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import org.junit.Before;
import org.junit.Rule;
import org.junit.Test;
-import org.mockito.Mock;
-import org.mockito.MockitoAnnotations;
import org.sonar.api.utils.DateUtils;
import org.sonar.api.utils.log.LogTester;
-import org.sonar.api.utils.log.LoggerLevel;
import org.sonar.scanner.bootstrap.ProcessedScannerProperties;
import org.sonar.scanner.rule.QualityProfiles;
import org.sonarqube.ws.Qualityprofiles.SearchWsResponse.QualityProfile;
import static org.assertj.core.api.Assertions.assertThat;
-import static org.mockito.ArgumentMatchers.anyString;
import static org.mockito.ArgumentMatchers.eq;
+import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.verifyNoMoreInteractions;
import static org.mockito.Mockito.when;
private QualityProfilesProvider qualityProfileProvider;
- @Mock
- private QualityProfileLoader loader;
- @Mock
- private ProcessedScannerProperties props;
- @Mock
- private ProjectRepositories projectRepo;
+ private QualityProfileLoader loader = mock(QualityProfileLoader.class);
+ private ProcessedScannerProperties props = mock(ProcessedScannerProperties.class);
private List<QualityProfile> response;
@Before
public void setUp() {
- MockitoAnnotations.initMocks(this);
qualityProfileProvider = new QualityProfilesProvider();
when(props.getKeyWithBranch()).thenReturn("project");
- when(projectRepo.exists()).thenReturn(true);
response = new ArrayList<>(1);
response.add(QualityProfile.newBuilder().setKey("profile").setName("profile").setLanguage("lang").setRulesUpdatedAt(DateUtils.formatDateTime(new Date())).build());
@Test
public void testProvide() {
when(loader.load("project")).thenReturn(response);
- QualityProfiles qps = qualityProfileProvider.provide(loader, projectRepo, props);
+ QualityProfiles qps = qualityProfileProvider.provide(loader, props);
assertResponse(qps);
verify(loader).load("project");
verifyNoMoreInteractions(loader);
}
- @Test
- public void testProjectDoesntExist() {
- when(projectRepo.exists()).thenReturn(false);
- when(loader.loadDefault()).thenReturn(response);
- QualityProfiles qps = qualityProfileProvider.provide(loader, projectRepo, props);
- assertResponse(qps);
-
- verify(loader).loadDefault();
- verifyNoMoreInteractions(loader);
- }
-
@Test
public void testProfileProp() {
when(loader.load(eq("project"))).thenReturn(response);
- QualityProfiles qps = qualityProfileProvider.provide(loader, projectRepo, props);
+ QualityProfiles qps = qualityProfileProvider.provide(loader, props);
assertResponse(qps);
verify(loader).load(eq("project"));
verifyNoMoreInteractions(loader);
}
- @Test
- public void testProfilePropDefault() {
- when(projectRepo.exists()).thenReturn(false);
- when(loader.loadDefault()).thenReturn(response);
-
- QualityProfiles qps = qualityProfileProvider.provide(loader, projectRepo, props);
- assertResponse(qps);
-
- verify(loader).loadDefault();
- verifyNoMoreInteractions(loader);
- }
-
private void assertResponse(QualityProfiles qps) {
assertThat(qps.findAll()).extracting("key").containsExactly("profile");
public void should_return_default_if_no_loader() {
BranchConfiguration result = provider.provide(null, globalConfiguration, reactor, globalServerSettings, projectServerSettings, branches, pullRequests);
- assertThat(result.targetScmBranch()).isNull();
+ assertThat(result.targetBranchName()).isNull();
assertThat(result.branchType()).isEqualTo(BranchType.LONG);
}
}
import java.util.Collections;
import java.util.HashMap;
import java.util.Map;
+import org.junit.Before;
import org.junit.Test;
import org.sonar.api.batch.fs.InputFile;
import org.sonar.api.batch.fs.internal.DefaultInputFile;
import org.sonar.api.batch.fs.internal.TestInputFileBuilder;
import org.sonar.scanner.repository.FileData;
+import org.sonar.scanner.repository.ProjectRepositoriesSupplier;
import org.sonar.scanner.repository.SingleProjectRepository;
import org.sonar.scanner.scm.ScmChangedFiles;
import static org.assertj.core.api.Assertions.assertThat;
+import static org.mockito.Mockito.mock;
+import static org.mockito.Mockito.when;
public class StatusDetectionTest {
+ private ProjectRepositoriesSupplier projectRepositoriesSupplier = mock(ProjectRepositoriesSupplier.class);
+
+ @Before
+ public void setUp() {
+ when(projectRepositoriesSupplier.get()).thenReturn(new SingleProjectRepository(createFileDataPerPathMap()));
+ }
+
@Test
public void detect_status() {
- SingleProjectRepository ref = new SingleProjectRepository(createFileDataPerPathMap());
ScmChangedFiles changedFiles = new ScmChangedFiles(null);
- StatusDetection statusDetection = new StatusDetection(ref, changedFiles);
+ StatusDetection statusDetection = new StatusDetection(projectRepositoriesSupplier, changedFiles);
assertThat(statusDetection.status("foo", createFile("src/Foo.java"), "ABCDE")).isEqualTo(InputFile.Status.SAME);
assertThat(statusDetection.status("foo", createFile("src/Foo.java"), "XXXXX")).isEqualTo(InputFile.Status.CHANGED);
@Test
public void detect_status_branches_exclude() {
- SingleProjectRepository ref = new SingleProjectRepository(createFileDataPerPathMap());
ScmChangedFiles changedFiles = new ScmChangedFiles(Collections.emptyList());
- StatusDetection statusDetection = new StatusDetection(ref, changedFiles);
+ StatusDetection statusDetection = new StatusDetection(projectRepositoriesSupplier, changedFiles);
// normally changed
assertThat(statusDetection.status("foo", createFile("src/Foo.java"), "XXXXX")).isEqualTo(InputFile.Status.SAME);
@Test
public void detect_status_branches_confirm() {
- SingleProjectRepository ref = new SingleProjectRepository(createFileDataPerPathMap());
ScmChangedFiles changedFiles = new ScmChangedFiles(Collections.singletonList(Paths.get("module", "src", "Foo.java")));
- StatusDetection statusDetection = new StatusDetection(ref, changedFiles);
+ StatusDetection statusDetection = new StatusDetection(projectRepositoriesSupplier, changedFiles);
assertThat(statusDetection.status("foo", createFile("src/Foo.java"), "XXXXX")).isEqualTo(InputFile.Status.CHANGED);
}
@Test
public void testNoScmProvider() {
when(branchConfiguration.isShortOrPullRequest()).thenReturn(true);
- when(branchConfiguration.targetScmBranch()).thenReturn("target");
+ when(branchConfiguration.targetBranchName()).thenReturn("target");
ScmChangedFiles scmChangedFiles = provider.provide(scmConfiguration, branchConfiguration, project);
@Test
public void testFailIfRelativePath() {
- when(branchConfiguration.targetScmBranch()).thenReturn("target");
+ when(branchConfiguration.targetBranchName()).thenReturn("target");
when(branchConfiguration.isShortOrPullRequest()).thenReturn(true);
when(scmConfiguration.provider()).thenReturn(scmProvider);
when(scmProvider.branchChangedFiles("target", rootBaseDir)).thenReturn(Collections.singleton(Paths.get("changedFile")));
@Test
public void testProviderDoesntSupport() {
- when(branchConfiguration.targetScmBranch()).thenReturn("target");
+ when(branchConfiguration.targetBranchName()).thenReturn("target");
when(branchConfiguration.isShortOrPullRequest()).thenReturn(true);
when(scmConfiguration.provider()).thenReturn(scmProvider);
when(scmProvider.branchChangedFiles("target", rootBaseDir)).thenReturn(null);
when(scmConfiguration.provider()).thenReturn(legacy);
when(branchConfiguration.isShortOrPullRequest()).thenReturn(true);
- when(branchConfiguration.targetScmBranch()).thenReturn("target");
+ when(branchConfiguration.targetBranchName()).thenReturn("target");
ScmChangedFiles scmChangedFiles = provider.provide(scmConfiguration, branchConfiguration, project);
@Test
public void testReturnChangedFiles() {
- when(branchConfiguration.targetScmBranch()).thenReturn("target");
+ when(branchConfiguration.targetBranchName()).thenReturn("target");
when(branchConfiguration.isShortOrPullRequest()).thenReturn(true);
when(scmConfiguration.provider()).thenReturn(scmProvider);
when(scmProvider.branchChangedFiles("target", rootBaseDir)).thenReturn(Collections.singleton(Paths.get("changedFile").toAbsolutePath()));
import java.nio.file.Paths;
import java.util.Collection;
import java.util.Collections;
+import org.junit.Rule;
import org.junit.Test;
+import org.junit.rules.ExpectedException;
import static org.assertj.core.api.Assertions.assertThat;
public class ScmChangedFilesTest {
private ScmChangedFiles scmChangedFiles;
+ @Rule
+ public ExpectedException exception = ExpectedException.none();
+
@Test
public void testGetter() {
Collection<Path> files = Collections.singletonList(Paths.get("files"));
@Test
public void testNullable() {
scmChangedFiles = new ScmChangedFiles(null);
+ assertThat(scmChangedFiles.isValid()).isFalse();
assertThat(scmChangedFiles.get()).isNull();
- assertThat(scmChangedFiles.verifyChanged(Paths.get("files2"))).isTrue();
+
+ exception.expect(IllegalStateException.class);
+ assertThat(scmChangedFiles.isChanged(Paths.get("files2"))).isTrue();
}
@Test
public void testConfirm() {
Collection<Path> files = Collections.singletonList(Paths.get("files"));
scmChangedFiles = new ScmChangedFiles(files);
- assertThat(scmChangedFiles.verifyChanged(Paths.get("files"))).isTrue();
- assertThat(scmChangedFiles.verifyChanged(Paths.get("files2"))).isFalse();
+ assertThat(scmChangedFiles.isValid()).isTrue();
+ assertThat(scmChangedFiles.isChanged(Paths.get("files"))).isTrue();
+ assertThat(scmChangedFiles.isChanged(Paths.get("files2"))).isFalse();
}
}
bool cross_project_duplication_activated = 6;
map<string, QProfile> qprofiles_per_language = 7;
map<string, Plugin> plugins_by_key = 8;
+
string branch_name = 9;
BranchType branch_type = 10;
string merge_branch_name = 11;
string projectVersion = 16;
string buildString = 17;
+ string target_branch_name = 18;
+
message QProfile {
string key = 1;
string name = 2;
optional bool isOrphan = 6;
optional string analysisDate = 7;
optional string url = 8;
+ optional string target = 9;
}
message Status {