return this;
}
+ @CheckForNull
+ public String getBranchKey() {
+ return branchType == BranchType.BRANCH ? kee : null;
+ }
+
+ @CheckForNull
+ public String getPullRequestKey() {
+ return branchType == BranchType.PULL_REQUEST ? kee : null;
+ }
+
@Override
public boolean equals(Object o) {
if (this == o) {
return split.size() == 2 ? split.get(1) : null;
}
- /**
- * @return the pull request id. It will be null when the component is not on a pull request
- */
- @CheckForNull
- public String getPullRequest() {
- List<String> split = PULL_REQUEST_SPLITTER.splitToList(kee);
- return split.size() == 2 ? split.get(1) : null;
- }
-
public String scope() {
return scope;
}
import java.util.List;
import java.util.Map;
import java.util.function.Predicate;
+import org.apache.commons.lang.RandomStringUtils;
import org.assertj.core.groups.Tuple;
import org.junit.Rule;
import org.junit.Test;
@Test
public void updateKey_updates_pull_requests_too() {
ComponentDto project = db.components().insertPublicProject();
- ComponentDto pullRequest = db.components().insertProjectBranch(project, b -> b.setBranchType(PULL_REQUEST));
+ String pullRequestKey1 = RandomStringUtils.randomAlphanumeric(100);
+ ComponentDto pullRequest = db.components().insertProjectBranch(project, b -> b.setBranchType(PULL_REQUEST).setKey(pullRequestKey1));
db.components().insertComponent(newFileDto(pullRequest));
db.components().insertComponent(newFileDto(pullRequest));
int branchComponentCount = 3;
assertThat(dbClient.componentDao().selectAllComponentsFromProjectKey(dbSession, oldBranchKey)).hasSize(branchComponentCount);
String newProjectKey = "newKey";
- String newBranchKey = ComponentDto.generatePullRequestKey(newProjectKey, pullRequest.getPullRequest());
+ String newBranchKey = ComponentDto.generatePullRequestKey(newProjectKey, pullRequestKey1);
underTest.updateKey(dbSession, project.uuid(), newProjectKey);
assertThat(dbClient.componentDao().selectAllComponentsFromProjectKey(dbSession, oldProjectKey)).isEmpty();
import org.sonar.core.util.stream.MoreCollectors;
import org.sonar.db.DbClient;
import org.sonar.db.DbSession;
+import org.sonar.db.component.BranchDto;
import org.sonar.db.component.ComponentDto;
import org.sonar.db.component.SnapshotDto;
import org.sonar.db.rule.RuleDto;
.count() <= 1;
}
- private void addComponentParameters(IssueQuery.Builder builder, DbSession session, boolean onComponentOnly, List<ComponentDto> components, SearchRequest request) {
+ private void addComponentParameters(IssueQuery.Builder builder, DbSession session, boolean onComponentOnly, List<ComponentDto> components,
+ SearchRequest request) {
builder.onComponentOnly(onComponentOnly);
if (onComponentOnly) {
builder.componentUuids(components.stream().map(ComponentDto::uuid).collect(toList()));
- setBranch(builder, components.get(0), request.getBranch(), request.getPullRequest());
+ setBranch(builder, components.get(0), request.getBranch(), request.getPullRequest(), session);
return;
}
if (projectKeys != null) {
List<ComponentDto> projects = getComponentsFromKeys(session, projectKeys, request.getBranch(), request.getPullRequest());
builder.projectUuids(projects.stream().map(IssueQueryFactory::toProjectUuid).collect(toList()));
- setBranch(builder, projects.get(0), request.getBranch(), request.getPullRequest());
+ setBranch(builder, projects.get(0), request.getBranch(), request.getPullRequest(), session);
}
builder.directories(request.getDirectories());
builder.files(request.getFiles());
Set<String> qualifiers = components.stream().map(ComponentDto::qualifier).collect(toHashSet());
checkArgument(qualifiers.size() == 1, "All components must have the same qualifier, found %s", String.join(",", qualifiers));
- setBranch(builder, components.get(0), request.getBranch(), request.getPullRequest());
+ setBranch(builder, components.get(0), request.getBranch(), request.getPullRequest(), dbSession);
String qualifier = qualifiers.iterator().next();
switch (qualifier) {
case Qualifiers.VIEW:
}
}
+ private BranchDto findComponentBranch(DbSession dbSession, ComponentDto componentDto) {
+ Optional<BranchDto> optionalBranch = dbClient.branchDao().selectByUuid(dbSession, componentDto.branchUuid());
+ checkArgument(optionalBranch.isPresent(), "All components must belong to a branch. This error may indicate corrupted data.");
+ return optionalBranch.get();
+ }
+
private void addProjectUuidsForApplication(IssueQuery.Builder builder, DbSession session, SearchRequest request) {
List<String> projectKeys = request.getProjects();
if (projectKeys != null) {
return mainBranchProjectUuid == null ? componentDto.branchUuid() : mainBranchProjectUuid;
}
- private static void setBranch(IssueQuery.Builder builder, ComponentDto component, @Nullable String branch, @Nullable String pullRequest) {
+ private void setBranch(IssueQuery.Builder builder, ComponentDto component, @Nullable String branch, @Nullable String pullRequest,
+ DbSession session) {
+ BranchDto branchDto = findComponentBranch(session, component);
+ String componentBranch = branchDto.isMain() ? null : branchDto.getBranchKey();
builder.branchUuid(branch == null && pullRequest == null ? null : component.branchUuid());
builder.mainBranch(UNKNOWN_COMPONENT.equals(component)
|| (branch == null && pullRequest == null)
- || (branch != null && !branch.equals(component.getBranch()))
- || (pullRequest != null && !pullRequest.equals(component.getPullRequest())));
+ || (branch != null && !branch.equals(componentBranch))
+ || (pullRequest != null && !pullRequest.equals(branchDto.getPullRequestKey())));
}
}
try (DbSession session = dbClient.openSession(false)) {
ComponentDto component = loadComponent(session, request);
userSession.checkComponentPermission(UserRole.USER, component);
- writeJsonResponse(response, session, component);
+ writeJsonResponse(response, session, component, request);
}
}
return componentFinder.getByKeyAndOptionalBranchOrPullRequest(dbSession, componentKey, branch, pullRequest);
}
- private void writeJsonResponse(Response response, DbSession session, ComponentDto component) {
+ private void writeJsonResponse(Response response, DbSession session, ComponentDto component, Request request) {
try (JsonWriter json = response.newJsonWriter()) {
json.beginObject();
- componentViewerJsonWriter.writeComponent(json, component, userSession, session);
+ componentViewerJsonWriter.writeComponent(json, component, userSession, session, request.param(PARAM_BRANCH),
+ request.param(PARAM_PULL_REQUEST));
appendPermissions(json, userSession);
componentViewerJsonWriter.writeMeasures(json, component, session);
json.endObject();
}
public static Components.Component.Builder componentDtoToWsComponent(ComponentDto dto, @Nullable ProjectDto parentProjectDto,
- @Nullable SnapshotDto lastAnalysis) {
+ @Nullable SnapshotDto lastAnalysis, @Nullable String branch, @Nullable String pullRequest) {
Components.Component.Builder wsComponent = Components.Component.newBuilder()
.setKey(dto.getKey())
.setName(dto.name())
.setQualifier(dto.qualifier());
- ofNullable(emptyToNull(dto.getBranch())).ifPresent(wsComponent::setBranch);
- ofNullable(emptyToNull(dto.getPullRequest())).ifPresent(wsComponent::setPullRequest);
+ ofNullable(emptyToNull(branch)).ifPresent(wsComponent::setBranch);
+ ofNullable(emptyToNull(pullRequest)).ifPresent(wsComponent::setPullRequest);
ofNullable(emptyToNull(dto.path())).ifPresent(wsComponent::setPath);
ofNullable(emptyToNull(dto.description())).ifPresent(wsComponent::setDescription);
ofNullable(emptyToNull(dto.language())).ifPresent(wsComponent::setLanguage);
this.dbClient = dbClient;
}
- public void writeComponentWithoutFav(JsonWriter json, ComponentDto component, DbSession session) {
+ public void writeComponentWithoutFav(JsonWriter json, ComponentDto component, DbSession session, @Nullable String branch, @Nullable String pullRequest) {
json.prop("key", component.getKey());
json.prop("uuid", component.uuid());
json.prop("path", component.path());
json.prop("project", project.getKey());
json.prop("projectName", project.longName());
- String branch = project.getBranch();
if (branch != null) {
json.prop("branch", branch);
}
- String pullRequest = project.getPullRequest();
if (pullRequest != null) {
json.prop("pullRequest", pullRequest);
}
}
- public void writeComponent(JsonWriter json, ComponentDto component, UserSession userSession, DbSession session) {
- writeComponentWithoutFav(json, component, session);
+ public void writeComponent(JsonWriter json, ComponentDto component, UserSession userSession, DbSession session, @Nullable String branch,
+ @Nullable String pullRequest) {
+ writeComponentWithoutFav(json, component, session, branch, pullRequest);
List<PropertyDto> propertyDtos = dbClient.propertiesDao().selectByQuery(PropertyQuery.builder()
.setKey("favourite")
userSession.checkComponentPermission(UserRole.USER, component);
Optional<SnapshotDto> lastAnalysis = dbClient.snapshotDao().selectLastAnalysisByComponentUuid(dbSession, component.branchUuid());
List<ComponentDto> ancestors = dbClient.componentDao().selectAncestors(dbSession, component);
- return buildResponse(dbSession, component, ancestors, lastAnalysis.orElse(null));
+ return buildResponse(dbSession, component, ancestors, lastAnalysis.orElse(null), request);
}
}
}
private ShowWsResponse buildResponse(DbSession dbSession, ComponentDto component, List<ComponentDto> orderedAncestors,
- @Nullable SnapshotDto lastAnalysis) {
+ @Nullable SnapshotDto lastAnalysis, Request request) {
ShowWsResponse.Builder response = ShowWsResponse.newBuilder();
- response.setComponent(toWsComponent(dbSession, component, lastAnalysis));
- addAncestorsToResponse(dbSession, response, orderedAncestors, lastAnalysis);
+ response.setComponent(toWsComponent(dbSession, component, lastAnalysis, request));
+ addAncestorsToResponse(dbSession, response, orderedAncestors, lastAnalysis, request);
return response.build();
}
private void addAncestorsToResponse(DbSession dbSession, ShowWsResponse.Builder response, List<ComponentDto> orderedAncestors,
- @Nullable SnapshotDto lastAnalysis) {
+ @Nullable SnapshotDto lastAnalysis, Request request) {
// ancestors are ordered from root to leaf, whereas it's the opposite in WS response
int size = orderedAncestors.size() - 1;
IntStream.rangeClosed(0, size).forEach(
- index -> response.addAncestors(toWsComponent(dbSession, orderedAncestors.get(size - index), lastAnalysis)));
+ index -> response.addAncestors(toWsComponent(dbSession, orderedAncestors.get(size - index), lastAnalysis, request)));
}
- private Components.Component.Builder toWsComponent(DbSession dbSession, ComponentDto component, @Nullable SnapshotDto lastAnalysis) {
+ private Components.Component.Builder toWsComponent(DbSession dbSession, ComponentDto component, @Nullable SnapshotDto lastAnalysis,
+ Request request) {
if (isProjectOrApp(component)) {
ProjectDto project = dbClient.projectDao().selectProjectOrAppByKey(dbSession, component.getKey())
.orElseThrow(() -> new IllegalStateException("Project is in invalid state."));
Optional<ProjectDto> parentProject = dbClient.projectDao().selectByUuid(dbSession,
ofNullable(component.getMainBranchProjectUuid()).orElse(component.branchUuid()));
boolean needIssueSync = needIssueSync(dbSession, component, parentProject.orElse(null));
- return componentDtoToWsComponent(component, parentProject.orElse(null), lastAnalysis)
+ return componentDtoToWsComponent(component, parentProject.orElse(null), lastAnalysis, request.branch, request.pullRequest)
.setNeedIssueSync(needIssueSync);
}
}
components = paginateComponents(components, treeRequest);
Map<String, ComponentDto> referenceComponentsByUuid = searchReferenceComponentsByUuid(dbSession, components);
-
- return buildResponse(dbSession, baseComponent, components, referenceComponentsByUuid,
- Paging.forPageIndex(treeRequest.getPage()).withPageSize(treeRequest.getPageSize()).andTotal(total));
+ Paging paging = Paging.forPageIndex(treeRequest.getPage()).withPageSize(treeRequest.getPageSize()).andTotal(total);
+ return buildResponse(dbSession, baseComponent, components, referenceComponentsByUuid, paging, treeRequest);
}
}
}
private TreeWsResponse buildResponse(DbSession dbSession, ComponentDto baseComponent, List<ComponentDto> components,
- Map<String, ComponentDto> referenceComponentsByUuid, Paging paging) {
+ Map<String, ComponentDto> referenceComponentsByUuid, Paging paging, Request request) {
TreeWsResponse.Builder response = TreeWsResponse.newBuilder();
response.getPagingBuilder()
.setPageIndex(paging.pageIndex())
.setTotal(paging.total())
.build();
- response.setBaseComponent(toWsComponent(dbSession, baseComponent, referenceComponentsByUuid));
+ response.setBaseComponent(toWsComponent(dbSession, baseComponent, referenceComponentsByUuid, request));
for (ComponentDto dto : components) {
- response.addComponents(toWsComponent(dbSession, dto, referenceComponentsByUuid));
+ response.addComponents(toWsComponent(dbSession, dto, referenceComponentsByUuid, request));
}
return response.build();
}
private Components.Component.Builder toWsComponent(DbSession dbSession, ComponentDto component,
- Map<String, ComponentDto> referenceComponentsByUuid) {
+ Map<String, ComponentDto> referenceComponentsByUuid, Request request) {
Components.Component.Builder wsComponent;
if (component.getMainBranchProjectUuid() == null && component.isRootProject() &&
} else {
Optional<ProjectDto> parentProject = dbClient.projectDao().selectByUuid(dbSession,
ofNullable(component.getMainBranchProjectUuid()).orElse(component.branchUuid()));
- wsComponent = componentDtoToWsComponent(component, parentProject.orElse(null), null);
+ wsComponent = componentDtoToWsComponent(component, parentProject.orElse(null), null, request.branch, request.pullRequest);
}
ComponentDto referenceComponent = referenceComponentsByUuid.get(component.getCopyComponentUuid());
package org.sonar.server.duplication.ws;
import java.util.List;
+import java.util.Optional;
import javax.annotation.CheckForNull;
import org.sonar.api.measures.CoreMetrics;
import org.sonar.api.server.ws.Change;
import org.sonar.api.web.UserRole;
import org.sonar.db.DbClient;
import org.sonar.db.DbSession;
+import org.sonar.db.component.BranchDto;
import org.sonar.db.component.ComponentDto;
import org.sonar.db.measure.LiveMeasureDto;
import org.sonar.server.component.ComponentFinder;
public void handle(Request request, Response response) {
try (DbSession dbSession = dbClient.openSession(false)) {
ComponentDto component = loadComponent(dbSession, request);
+ BranchDto branchDto = loadBranch(dbSession, component);
+ String branch = branchDto.isMain() ? null : branchDto.getBranchKey();
+ String pullRequest = branchDto.getPullRequestKey();
userSession.checkComponentPermission(UserRole.CODEVIEWER, component);
String duplications = findDataFromComponent(dbSession, component);
- String branch = component.getBranch();
- String pullRequest = component.getPullRequest();
List<DuplicationsParser.Block> blocks = parser.parse(dbSession, component, branch, pullRequest, duplications);
writeProtobuf(responseBuilder.build(dbSession, blocks, branch, pullRequest), request, response);
}
}
+ private BranchDto loadBranch(DbSession dbSession, ComponentDto component) {
+ Optional<BranchDto> branchDto = dbClient.branchDao().selectByUuid(dbSession, component.branchUuid());
+ if (branchDto.isEmpty()) {
+ throw new IllegalStateException("Could not find a branch for component with " + component.uuid());
+ }
+ return branchDto.get();
+ }
+
private ComponentDto loadComponent(DbSession dbSession, Request request) {
String key = request.mandatoryParam(PARAM_KEY);
String branch = request.param(PARAM_BRANCH);
package org.sonar.server.hotspot.ws;
import javax.annotation.Nullable;
+import org.sonar.db.component.BranchDto;
import org.sonar.db.component.ComponentDto;
import org.sonarqube.ws.Hotspots;
// nothing to do here
}
- Hotspots.Component formatComponent(Hotspots.Component.Builder builder, ComponentDto component, @Nullable String branch, @Nullable String pr) {
+ Hotspots.Component formatComponent(Hotspots.Component.Builder builder, ComponentDto component, @Nullable String branch, @Nullable String pullRequest) {
builder
.clear()
.setKey(component.getKey())
.setName(component.name())
.setLongName(component.longName());
ofNullable(branch).ifPresent(builder::setBranch);
- ofNullable(pr).ifPresent(builder::setPullRequest);
+ ofNullable(pullRequest).ifPresent(builder::setPullRequest);
ofNullable(component.path()).ifPresent(builder::setPath);
return builder.build();
}
+ Hotspots.Component formatComponent(Hotspots.Component.Builder builder, ComponentDto component, BranchDto branchDto) {
+ if (branchDto.isMain()) {
+ return formatComponent(builder, component, null, null);
+ }
+ return formatComponent(builder, component, branchDto.getBranchKey(), branchDto.getPullRequestKey());
+ }
+
}
import java.util.Set;
import java.util.stream.Collectors;
import java.util.stream.Stream;
-import javax.annotation.CheckForNull;
import javax.annotation.Nullable;
import org.apache.lucene.search.TotalHits;
import org.elasticsearch.action.search.SearchResponse;
import org.sonar.db.project.ProjectDto;
import org.sonar.db.protobuf.DbIssues;
import org.sonar.db.rule.RuleDto;
-import org.sonar.server.component.ComponentFinder;
import org.sonar.server.es.SearchOptions;
import org.sonar.server.exceptions.NotFoundException;
import org.sonar.server.issue.TextRangeResponseFormatter;
List<IssueDto> hotspots = toIssueDtos(dbSession, issueKeys);
Paging paging = forPageIndex(wsRequest.getPage()).withPageSize(wsRequest.getIndex()).andTotal((int) getTotalHits(result).value);
- return new SearchResponseData(paging, hotspots, wsRequest.getBranch().orElse(null), wsRequest.getPullRequest().orElse(null));
+ return new SearchResponseData(paging, hotspots);
}
private static TotalHits getTotalHits(SearchResponse response) {
Map<String, IssueQuery.PeriodStart> leakByProjects = snapshots
.stream()
.filter(s -> isNullOrEmpty(s.getPeriodMode()) || !s.getPeriodMode().equals(REFERENCE_BRANCH.name()))
- .collect(uniqueIndex(SnapshotDto::getComponentUuid, s ->
- new IssueQuery.PeriodStart(longToDate(s.getPeriodDate() == null ? now : s.getPeriodDate()), false)));
+ .collect(uniqueIndex(SnapshotDto::getComponentUuid, s -> new IssueQuery.PeriodStart(longToDate(s.getPeriodDate() == null ? now : s.getPeriodDate()), false)));
builder.createdAfterByProjectUuids(leakByProjects);
builder.newCodeOnReferenceByProjectUuids(newCodeReferenceByProjects);
.collect(Collectors.toSet());
if (!aggregatedComponentUuids.isEmpty()) {
- searchResponseData.addComponents(dbClient.componentDao().selectByUuids(dbSession, aggregatedComponentUuids));
+ List<ComponentDto> componentDtos = dbClient.componentDao().selectByUuids(dbSession, aggregatedComponentUuids);
+ searchResponseData.addComponents(componentDtos);
+
+ Set<String> branchUuids = componentDtos.stream().map(ComponentDto::branchUuid).collect(Collectors.toSet());
+ List<BranchDto> branchDtos = dbClient.branchDao().selectByUuids(dbSession, branchUuids);
+ searchResponseData.addBranches(branchDtos);
}
}
Hotspots.Component.Builder builder = Hotspots.Component.newBuilder();
for (ComponentDto component : components) {
- responseBuilder.addComponents(responseFormatter.formatComponent(builder, component, searchResponseData.getBranch(), searchResponseData.getPullRequest()));
+ BranchDto branchDto = searchResponseData.getBranch(component.branchUuid());
+ if (branchDto == null) {
+ throw new IllegalStateException("Could not find a branch for a component " + component.getKey() + " with uuid " + component.uuid());
+ }
+ responseBuilder.addComponents(responseFormatter.formatComponent(builder, component, branchDto));
}
}
private static final class SearchResponseData {
private final Paging paging;
private final List<IssueDto> orderedHotspots;
- private final String branch;
- private final String pullRequest;
private final Map<String, ComponentDto> componentsByUuid = new HashMap<>();
private final Map<RuleKey, RuleDto> rulesByRuleKey = new HashMap<>();
+ private final Map<String, BranchDto> branchesByBranchUuid = new HashMap<>();
- private SearchResponseData(Paging paging, List<IssueDto> orderedHotspots, @Nullable String branch, @Nullable String pullRequest) {
+ private SearchResponseData(Paging paging, List<IssueDto> orderedHotspots) {
this.paging = paging;
this.orderedHotspots = orderedHotspots;
- this.branch = branch;
- this.pullRequest = pullRequest;
- }
-
- @CheckForNull
- public String getBranch() {
- return branch;
- }
-
- @CheckForNull
- public String getPullRequest() {
- return pullRequest;
}
boolean isEmpty() {
}
}
+ public void addBranches(List<BranchDto> branchDtos) {
+ for (BranchDto branch : branchDtos) {
+ branchesByBranchUuid.put(branch.getUuid(), branch);
+ }
+ }
+
+ public BranchDto getBranch(String branchUuid) {
+ return branchesByBranchUuid.get(branchUuid);
+ }
+
Collection<ComponentDto> getComponents() {
return componentsByUuid.values();
}
import java.util.Set;
import javax.annotation.CheckForNull;
import javax.annotation.Nullable;
+import org.sonar.db.component.BranchDto;
import org.sonar.db.component.ComponentDto;
import org.sonar.db.issue.IssueChangeDto;
import org.sonar.db.issue.IssueDto;
private final ListMultimap<String, String> actionsByIssueKey = ArrayListMultimap.create();
private final ListMultimap<String, Transition> transitionsByIssueKey = ArrayListMultimap.create();
private final Set<String> updatableComments = new HashSet<>();
+ private final Map<String, BranchDto> branchesByBranchUuid = new HashMap<>();
public SearchResponseData(IssueDto issue) {
checkNotNull(issue);
}
}
+ public void addBranches(List<BranchDto> branchDtos) {
+ for (BranchDto branch : branchDtos) {
+ branchesByBranchUuid.put(branch.getUuid(), branch);
+ }
+ }
+
+ public BranchDto getBranch(String branchUuid) {
+ return branchesByBranchUuid.get(branchUuid);
+ }
+
void addActions(String issueKey, Iterable<String> actions) {
actionsByIssueKey.putAll(issueKey, actions);
}
import org.sonar.api.utils.Duration;
import org.sonar.api.utils.Durations;
import org.sonar.api.utils.Paging;
+import org.sonar.db.component.BranchDto;
+import org.sonar.db.component.BranchType;
import org.sonar.db.component.ComponentDto;
import org.sonar.db.issue.IssueChangeDto;
import org.sonar.db.issue.IssueDto;
ComponentDto component = data.getComponentByUuid(dto.getComponentUuid());
issueBuilder.setComponent(component.getKey());
- ofNullable(component.getBranch()).ifPresent(issueBuilder::setBranch);
- ofNullable(component.getPullRequest()).ifPresent(issueBuilder::setPullRequest);
+ setBranchOrPr(component, issueBuilder, data);
ComponentDto project = data.getComponentByUuid(dto.getProjectUuid());
if (project != null) {
issueBuilder.setProject(project.getKey());
.setName(nullToEmpty(dto.name()))
.setLongName(nullToEmpty(dto.longName()))
.setEnabled(dto.isEnabled());
- ofNullable(dto.getBranch()).ifPresent(builder::setBranch);
- ofNullable(dto.getPullRequest()).ifPresent(builder::setPullRequest);
+ setBranchOrPr(dto, builder, data);
ofNullable(emptyToNull(dto.path())).ifPresent(builder::setPath);
result.add(builder.build());
return result;
}
+ private static void setBranchOrPr(ComponentDto componentDto, Component.Builder builder, SearchResponseData data) {
+ BranchDto branchDto = data.getBranch(componentDto.branchUuid());
+ if (branchDto.isMain()) {
+ return;
+ }
+ builder.setBranch(branchDto.getBranchKey());
+ builder.setPullRequest(branchDto.getPullRequestKey());
+ }
+
+ private static void setBranchOrPr(ComponentDto componentDto, Issue.Builder builder, SearchResponseData data) {
+ BranchDto branchDto = data.getBranch(componentDto.branchUuid());
+ if (branchDto.isMain()) {
+ return;
+ }
+ if (branchDto.getBranchType() == BranchType.BRANCH) {
+ builder.setBranch(branchDto.getKey());
+ } else if (branchDto.getBranchType() == BranchType.PULL_REQUEST) {
+ builder.setPullRequest(branchDto.getKey());
+ }
+ }
+
private Users.Builder formatUsers(SearchResponseData data) {
Users.Builder wsUsers = Users.newBuilder();
List<UserDto> users = data.getUsers();
import org.sonar.core.util.stream.MoreCollectors;
import org.sonar.db.DbClient;
import org.sonar.db.DbSession;
+import org.sonar.db.component.BranchDto;
import org.sonar.db.component.ComponentDto;
import org.sonar.db.issue.IssueChangeDto;
import org.sonar.db.issue.IssueDto;
loadComments(collector, dbSession, fields, result);
loadUsers(preloadedResponseData, collector, dbSession, result);
loadComponents(preloadedResponseData, collector, dbSession, result);
+ // for all loaded components in result we "join" branches to know to which branch components belong
+ loadBranches(dbSession, result);
+
loadActionsAndTransitions(result, fields);
completeTotalEffortFromFacet(facets, result);
return result;
loadProjects(collector, dbSession, result);
}
+ private void loadBranches(DbSession dbSession, SearchResponseData result) {
+ Set<String> branchUuids = result.getComponents().stream().map(ComponentDto::branchUuid).collect(Collectors.toSet());
+ List<BranchDto> branchDtos = dbClient.branchDao().selectByUuids(dbSession, branchUuids);
+ result.addBranches(branchDtos);
+ }
+
private void loadProjects(Collector collector, DbSession dbSession, SearchResponseData result) {
Collection<ComponentDto> loadedComponents = result.getComponents();
for (ComponentDto component : loadedComponents) {
ComponentWsResponse.Builder response = ComponentWsResponse.newBuilder();
if (refComponent.isPresent()) {
- response.setComponent(componentDtoToWsComponent(component, measuresByMetric, singletonMap(refComponent.get().uuid(), refComponent.get())));
+ response.setComponent(componentDtoToWsComponent(component, measuresByMetric, singletonMap(refComponent.get().uuid(),
+ refComponent.get()), request.getBranch(), request.getPullRequest()));
} else {
- response.setComponent(componentDtoToWsComponent(component, measuresByMetric, emptyMap()));
+ response.setComponent(componentDtoToWsComponent(component, measuresByMetric, emptyMap(), request.getBranch(), request.getPullRequest()));
}
List<String> additionalFields = request.getAdditionalFields();
package org.sonar.server.measure.ws;
import java.util.Map;
+import javax.annotation.Nullable;
import org.sonar.db.component.ComponentDto;
import org.sonar.db.measure.LiveMeasureDto;
import org.sonar.db.metric.MetricDto;
}
static Component.Builder componentDtoToWsComponent(ComponentDto component, Map<MetricDto, LiveMeasureDto> measuresByMetric,
- Map<String, ComponentDto> referenceComponentsByUuid) {
- Component.Builder wsComponent = componentDtoToWsComponent(component);
+ Map<String, ComponentDto> referenceComponentsByUuid, @Nullable String branch,
+ @Nullable String pullRequest) {
+ Component.Builder wsComponent = componentDtoToWsComponent(component, branch, pullRequest);
ComponentDto referenceComponent = referenceComponentsByUuid.get(component.getCopyComponentUuid());
if (referenceComponent != null) {
return wsComponent;
}
- static Component.Builder componentDtoToWsComponent(ComponentDto component) {
+ static Component.Builder componentDtoToWsComponent(ComponentDto component, @Nullable String branch, @Nullable String pullRequest) {
Component.Builder wsComponent = Component.newBuilder()
.setKey(component.getKey())
.setName(component.name())
.setQualifier(component.qualifier());
- ofNullable(component.getBranch()).ifPresent(wsComponent::setBranch);
- ofNullable(component.getPullRequest()).ifPresent(wsComponent::setPullRequest);
+ ofNullable(branch).ifPresent(wsComponent::setBranch);
+ ofNullable(pullRequest).ifPresent(wsComponent::setPullRequest);
ofNullable(component.path()).ifPresent(wsComponent::setPath);
ofNullable(component.description()).ifPresent(wsComponent::setDescription);
ofNullable(component.language()).ifPresent(wsComponent::setLanguage);
toWsComponent(
data.getBaseComponent(),
data.getMeasuresByComponentUuidAndMetric().row(data.getBaseComponent().uuid()),
- data.getReferenceComponentsByUuid()));
+ data.getReferenceComponentsByUuid(), request.getBranch(), request.getPullRequest()));
for (ComponentDto componentDto : data.getComponents()) {
response.addComponents(toWsComponent(
componentDto,
data.getMeasuresByComponentUuidAndMetric().row(componentDto.uuid()),
- data.getReferenceComponentsByUuid()));
+ data.getReferenceComponentsByUuid(), request.getBranch(), request.getPullRequest()));
}
if (areMetricsInResponse(request)) {
.setPageSize(request.getPageSize())
.setTotal(0);
if (baseComponent != null) {
- response.setBaseComponent(componentDtoToWsComponent(baseComponent));
+ response.setBaseComponent(componentDtoToWsComponent(baseComponent, request.getBranch(), request.getPullRequest()));
}
return response.build();
}
}
private static Measures.Component.Builder toWsComponent(ComponentDto component, Map<MetricDto, ComponentTreeData.Measure> measures,
- Map<String, ComponentDto> referenceComponentsByUuid) {
- Measures.Component.Builder wsComponent = componentDtoToWsComponent(component);
+ Map<String, ComponentDto> referenceComponentsByUuid, @Nullable String branch, @Nullable String pullRequest) {
+ Measures.Component.Builder wsComponent = componentDtoToWsComponent(component, branch, pullRequest);
ComponentDto referenceComponent = referenceComponentsByUuid.get(component.getCopyComponentUuid());
if (referenceComponent != null) {
wsComponent.setRefKey(referenceComponent.getKey());
import org.sonar.api.web.UserRole;
import org.sonar.db.DbClient;
import org.sonar.db.DbSession;
+import org.sonar.db.component.BranchDto;
import org.sonar.db.component.ComponentDto;
import org.sonar.db.component.SnapshotDto;
import org.sonar.db.issue.IssueDto;
Map<String, TreeSet<Integer>> linesPerComponent = getLinesPerComponent(componentUuid, locations);
Map<String, ComponentDto> componentsByUuid = dbClient.componentDao().selectByUuids(dbSession, linesPerComponent.keySet())
.stream().collect(Collectors.toMap(ComponentDto::uuid, c -> c));
+
+ Map<String, BranchDto> branches = dbClient.branchDao()
+ .selectByUuids(dbSession, componentsByUuid.keySet())
+ .stream()
+ .collect(Collectors.toMap(BranchDto::getUuid, b -> b));
+
try (JsonWriter jsonWriter = response.newJsonWriter()) {
jsonWriter.beginObject();
for (Map.Entry<String, TreeSet<Integer>> e : linesPerComponent.entrySet()) {
ComponentDto componentDto = componentsByUuid.get(e.getKey());
if (componentDto != null) {
- writeSnippet(dbSession, jsonWriter, componentDto, e.getValue());
+ writeSnippet(dbSession, jsonWriter, componentDto, e.getValue(), branches.get(componentDto.branchUuid()));
}
}
}
}
- private void writeSnippet(DbSession dbSession, JsonWriter writer, ComponentDto fileDto, Set<Integer> lines) {
+ private void writeSnippet(DbSession dbSession, JsonWriter writer, ComponentDto fileDto, Set<Integer> lines, BranchDto branchDto) {
Optional<Iterable<DbFileSources.Line>> lineSourcesOpt = sourceService.getLines(dbSession, fileDto.uuid(), lines);
if (lineSourcesOpt.isEmpty()) {
return;
writer.name(fileDto.getKey()).beginObject();
writer.name("component").beginObject();
- componentViewerJsonWriter.writeComponentWithoutFav(writer, fileDto, dbSession);
+ String branch = branchDto.isMain() ? null : branchDto.getBranchKey();
+ String pullRequest = branchDto.getPullRequestKey();
+ componentViewerJsonWriter.writeComponentWithoutFav(writer, fileDto, dbSession, branch, pullRequest);
componentViewerJsonWriter.writeMeasures(writer, fileDto, dbSession);
writer.endObject();
linesJsonWriter.writeSource(lineSources, writer, periodDateSupplier);
import java.util.List;
import java.util.stream.IntStream;
import javax.annotation.Nullable;
+import org.apache.commons.lang.RandomStringUtils;
import org.junit.Rule;
import org.junit.Test;
import org.sonar.api.server.ws.WebService.Param;
logInAsSystemAdministrator();
ComponentDto project = db.components().insertPrivateProject();
userSession.addProjectPermission(UserRole.USER, project);
- ComponentDto pullRequest = db.components().insertProjectBranch(project, b -> b.setBranchType(BranchType.PULL_REQUEST));
+ String pullRequestKey = RandomStringUtils.randomAlphanumeric(100);
+ ComponentDto pullRequest = db.components().insertProjectBranch(project, b -> b.setBranchType(BranchType.PULL_REQUEST).setKey(pullRequestKey));
SnapshotDto analysis = db.components().insertSnapshot(pullRequest);
CeActivityDto activity = insertActivity("T1", project, SUCCESS, analysis);
- insertCharacteristic(activity, PULL_REQUEST, pullRequest.getPullRequest());
+ insertCharacteristic(activity, PULL_REQUEST, pullRequestKey);
ActivityResponse response = ws.newRequest().executeProtobuf(ActivityResponse.class);
.extracting(Task::getId, Ce.Task::getPullRequest, Ce.Task::hasPullRequestTitle, Ce.Task::getStatus, Ce.Task::getComponentKey)
.containsExactlyInAnyOrder(
// TODO the pull request title must be loaded from db
- tuple("T1", pullRequest.getPullRequest(), false, Ce.TaskStatus.SUCCESS, pullRequest.getKey()));
+ tuple("T1", pullRequestKey, false, Ce.TaskStatus.SUCCESS, pullRequest.getKey()));
}
@Test
*/
package org.sonar.server.component.ws;
+import org.apache.commons.lang.RandomStringUtils;
import org.junit.Rule;
import org.junit.Test;
import org.sonar.api.server.ws.WebService;
public void component_and_pull_request_parameters_provided() {
ComponentDto project = db.components().insertPrivateProject();
userSession.logIn("john").addProjectPermission(USER, project);
- ComponentDto branch = db.components().insertProjectBranch(project, b -> b.setBranchType(PULL_REQUEST));
+ String pullRequestKey = RandomStringUtils.randomAlphanumeric(100);
+ ComponentDto branch = db.components().insertProjectBranch(project, b -> b.setBranchType(PULL_REQUEST).setKey(pullRequestKey));
ComponentDto file = db.components().insertComponent(newFileDto(branch));
String result = ws.newRequest()
.setParam("component", file.getKey())
- .setParam("pullRequest", file.getPullRequest())
+ .setParam("pullRequest", pullRequestKey)
.execute()
.getInput();
" \"q\": \"" + file.qualifier() + "\",\n" +
" \"project\": \"" + project.getKey() + "\",\n" +
" \"projectName\": \"" + project.longName() + "\",\n" +
- " \"pullRequest\": \"" + file.getPullRequest() + "\",\n" +
+ " \"pullRequest\": \"" + pullRequestKey + "\",\n" +
" \"fav\": false,\n" +
" \"canMarkAsFavorite\": true,\n" +
" \"measures\": {}\n" +
import java.util.Date;
import java.util.Optional;
import javax.annotation.Nullable;
+import org.apache.commons.lang.RandomStringUtils;
import org.junit.Rule;
import org.junit.Test;
import org.sonar.api.resources.Qualifiers;
ComponentDto portfolio2 = db.components().insertPublicPortfolio();
ComponentDto subview = db.components().insertSubView(portfolio1);
+ String pullRequestKey1 = RandomStringUtils.randomAlphanumeric(100);
ComponentDto project1 = db.components().insertPrivateProject();
- ComponentDto branch1 = db.components().insertProjectBranch(project1, b -> b.setBranchType(PULL_REQUEST).setNeedIssueSync(true));
+ ComponentDto branch1 = db.components().insertProjectBranch(project1, b -> b.setBranchType(PULL_REQUEST).setKey(pullRequestKey1)
+ .setNeedIssueSync(true));
ComponentDto module = db.components().insertComponent(newModuleDto(branch1));
ComponentDto directory = db.components().insertComponent(newDirectory(module, "dir"));
ComponentDto file = db.components().insertComponent(newFileDto(directory));
ComponentDto branch3 = db.components().insertProjectBranch(project2, b -> b.setBranchType(BRANCH).setNeedIssueSync(false));
ComponentDto project3 = db.components().insertPrivateProject();
- ComponentDto branch4 = db.components().insertProjectBranch(project3, b -> b.setBranchType(PULL_REQUEST).setNeedIssueSync(false));
+ String pullRequestKey4 = RandomStringUtils.randomAlphanumeric(100);
+ ComponentDto branch4 = db.components().insertProjectBranch(project3, b -> b.setBranchType(PULL_REQUEST).setKey(pullRequestKey4).setNeedIssueSync(false));
ComponentDto moduleOfBranch4 = db.components().insertComponent(newModuleDto(branch4));
ComponentDto directoryOfBranch4 = db.components().insertComponent(newDirectory(moduleOfBranch4, "dir"));
ComponentDto fileOfBranch4 = db.components().insertComponent(newFileDto(directoryOfBranch4));
// if branch need sync it is propagated to other components
assertNeedIssueSyncEqual(null, null, project1, true);
- assertNeedIssueSyncEqual(branch1.getPullRequest(), null, branch1, true);
- assertNeedIssueSyncEqual(branch1.getPullRequest(), null, module, true);
- assertNeedIssueSyncEqual(branch1.getPullRequest(), null, directory, true);
- assertNeedIssueSyncEqual(branch1.getPullRequest(), null, file, true);
+ assertNeedIssueSyncEqual(pullRequestKey1, null, branch1, true);
+ assertNeedIssueSyncEqual(pullRequestKey1, null, module, true);
+ assertNeedIssueSyncEqual(pullRequestKey1, null, directory, true);
+ assertNeedIssueSyncEqual(pullRequestKey1, null, file, true);
assertNeedIssueSyncEqual(null, null, project2, true);
assertNeedIssueSyncEqual(null, branch2.getBranch(), branch2, true);
// if all branches are synced, need issue sync on project is is set to false
assertNeedIssueSyncEqual(null, null, project3, false);
- assertNeedIssueSyncEqual(branch4.getPullRequest(), null, branch4, false);
- assertNeedIssueSyncEqual(branch4.getPullRequest(), null, moduleOfBranch4, false);
- assertNeedIssueSyncEqual(branch4.getPullRequest(), null, directoryOfBranch4, false);
- assertNeedIssueSyncEqual(branch4.getPullRequest(), null, fileOfBranch4, false);
+ assertNeedIssueSyncEqual(pullRequestKey4, null, branch4, false);
+ assertNeedIssueSyncEqual(pullRequestKey4, null, moduleOfBranch4, false);
+ assertNeedIssueSyncEqual(pullRequestKey4, null, directoryOfBranch4, false);
+ assertNeedIssueSyncEqual(pullRequestKey4, null, fileOfBranch4, false);
assertNeedIssueSyncEqual(null, branch5.getBranch(), branch5, false);
}
SnapshotDto nonMainBranchAnalysis = insertAnalysis(nonMainBranch, 1_500_000_000_000L);
insertIssue(nonMainBranch, nonMainBranchAnalysis);
insertIssue(nonMainBranch, nonMainBranchAnalysis);
- ComponentDto pullRequest = db.components().insertProjectBranch(project, b -> b.setBranchType(BranchType.PULL_REQUEST).setKey("42"));
+ String pullRequestKey = "42";
+ ComponentDto pullRequest = db.components().insertProjectBranch(project, b -> b.setBranchType(BranchType.PULL_REQUEST).setKey(pullRequestKey));
SnapshotDto pullRequestAnalysis = insertAnalysis(pullRequest, 1_300_000_000_000L);
insertIssue(pullRequest, pullRequestAnalysis);
issueIndexer.indexAllIssues();
format("https://sonarcloud.io/project/issues?id=%s&createdAfter=%s&assignees=%s&resolved=false&branch=%s", nonMainBranch.getKey(), encode(formatDateTime(from + 1_000L)),
userSession.getLogin(), nonMainBranch.getBranch()),
formatDateTime(nonMainBranchAnalysis.getCreatedAt())),
- tuple("NEW_ISSUES", project.getKey(), format("You have 1 new issue on project '%s' on pull request '%s'", project.name(), pullRequest.getPullRequest()),
+ tuple("NEW_ISSUES", project.getKey(), format("You have 1 new issue on project '%s' on pull request '%s'", project.name(), pullRequestKey),
format("https://sonarcloud.io/project/issues?id=%s&createdAfter=%s&assignees=%s&resolved=false&pullRequest=%s", pullRequest.getKey(),
encode(formatDateTime(from + 1_000L)),
- userSession.getLogin(), pullRequest.getPullRequest()),
+ userSession.getLogin(), pullRequestKey),
formatDateTime(pullRequestAnalysis.getCreatedAt())));
}
import com.google.common.collect.Iterables;
import java.util.List;
import javax.annotation.Nullable;
+import org.apache.commons.lang.RandomStringUtils;
import org.junit.Rule;
import org.junit.Test;
import org.sonar.db.DbTester;
@Test
public void duplication_on_pull_request() {
ComponentDto project = db.components().insertPublicProject();
- ComponentDto pullRequest = db.components().insertProjectBranch(project, b -> b.setBranchType(BranchType.PULL_REQUEST));
+ String pullRequestKey = RandomStringUtils.randomAlphanumeric(100);
+ ComponentDto pullRequest = db.components().insertProjectBranch(project, b -> b.setBranchType(BranchType.PULL_REQUEST).setKey(pullRequestKey));
ComponentDto file1 = db.components().insertComponent(newFileDto(pullRequest));
ComponentDto file2 = db.components().insertComponent(newFileDto(pullRequest));
- List<DuplicationsParser.Block> blocks = parser.parse(db.getSession(), file1, null, pullRequest.getPullRequest(),
+ List<DuplicationsParser.Block> blocks = parser.parse(db.getSession(), file1, null, pullRequestKey,
format("<duplications>\n" +
" <g>\n" +
" <b s=\"20\" l=\"5\" r=\"%s\"/>\n" +
package org.sonar.server.duplication.ws;
import java.util.function.Function;
+import org.apache.commons.lang.RandomStringUtils;
import org.junit.Before;
import org.junit.Rule;
import org.junit.Test;
import org.sonar.api.web.UserRole;
import org.sonar.core.util.Uuids;
import org.sonar.db.DbTester;
-import org.sonar.db.component.BranchType;
import org.sonar.db.component.ComponentDto;
import org.sonar.db.metric.MetricDto;
import org.sonar.server.component.TestComponentFinder;
import static java.lang.String.format;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatThrownBy;
+import static org.sonar.db.component.BranchType.PULL_REQUEST;
import static org.sonar.db.component.ComponentTesting.newFileDto;
import static org.sonar.db.component.SnapshotTesting.newAnalysis;
import static org.sonar.test.JsonAssert.assertJson;
public void duplications_by_file_key_and_pull_request() {
ComponentDto project = db.components().insertPrivateProject();
userSessionRule.addProjectPermission(UserRole.CODEVIEWER, project);
- ComponentDto pullRequest = db.components().insertProjectBranch(project, b -> b.setBranchType(BranchType.PULL_REQUEST));
+ String pullRequestKey = RandomStringUtils.randomAlphanumeric(100);
+ ComponentDto pullRequest = db.components().insertProjectBranch(project, b -> b.setBranchType(PULL_REQUEST).setKey(pullRequestKey));
ComponentDto file = db.components().insertComponent(newFileDto(pullRequest));
db.measures().insertLiveMeasure(file, dataMetric, m -> m.setData(format("<duplications>\n" +
" <g>\n" +
String result = ws.newRequest()
.setParam("key", file.getKey())
- .setParam("pullRequest", pullRequest.getPullRequest())
+ .setParam("pullRequest", pullRequestKey)
.execute()
.getInput();
" }\n" +
" }\n" +
"}",
- file.getKey(), file.longName(), file.uuid(), pullRequest.getKey(), pullRequest.uuid(), project.longName(), file.getPullRequest()));
+ file.getKey(), file.longName(), file.uuid(), pullRequest.getKey(), pullRequest.uuid(), project.longName(), pullRequestKey));
}
@Test
import java.util.Collections;
import java.util.List;
import javax.annotation.Nullable;
+import org.apache.commons.lang.RandomStringUtils;
import org.junit.Rule;
import org.junit.Test;
import org.sonar.api.utils.text.JsonWriter;
@Test
public void write_duplications_on_pull_request() {
ComponentDto project = db.components().insertPublicProject();
- ComponentDto pullRequest = db.components().insertProjectBranch(project, b -> b.setBranchType(PULL_REQUEST));
+ String pullRequestKey = RandomStringUtils.randomAlphanumeric(100);
+ ComponentDto pullRequest = db.components().insertProjectBranch(project, b -> b.setBranchType(PULL_REQUEST).setKey(pullRequestKey));
ComponentDto file1 = db.components().insertComponent(newFileDto(pullRequest));
ComponentDto file2 = db.components().insertComponent(newFileDto(pullRequest));
List<DuplicationsParser.Block> blocks = newArrayList();
Duplication.newComponent(file1, 57, 12),
Duplication.newComponent(file2, 73, 12))));
- test(blocks, null, pullRequest.getPullRequest(),
+ test(blocks, null, pullRequestKey,
"{\n" +
" \"duplications\": [\n" +
" {\n" +
" \"name\": \"" + file1.longName() + "\",\n" +
" \"project\": \"" + pullRequest.getKey() + "\",\n" +
" \"projectName\": \"" + pullRequest.longName() + "\",\n" +
- " \"pullRequest\": \"" + pullRequest.getPullRequest() + "\",\n" +
+ " \"pullRequest\": \"" + pullRequestKey + "\",\n" +
" },\n" +
" \"2\": {\n" +
" \"key\": \"" + file2.getKey() + "\",\n" +
" \"name\": \"" + file2.longName() + "\",\n" +
" \"project\": \"" + pullRequest.getKey() + "\",\n" +
" \"projectName\": \"" + pullRequest.longName() + "\",\n" +
- " \"pullRequest\": \"" + pullRequest.getPullRequest() + "\",\n" +
+ " \"pullRequest\": \"" + pullRequestKey + "\",\n" +
" }\n" +
" }" +
"}");
import java.util.stream.IntStream;
import java.util.stream.Stream;
import javax.annotation.Nullable;
+import org.apache.commons.lang.RandomStringUtils;
import org.junit.Rule;
import org.junit.Test;
import org.junit.runner.RunWith;
userSessionRule.registerComponents(project);
indexPermissions();
ComponentDto branch = dbTester.components().insertProjectBranch(project);
- ComponentDto pullRequest = dbTester.components().insertProjectBranch(project, t -> t.setBranchType(BranchType.PULL_REQUEST));
+ ComponentDto pullRequest = dbTester.components().insertProjectBranch(project, t -> t.setBranchType(BranchType.PULL_REQUEST).setKey("prKey"));
ComponentDto fileProject = dbTester.components().insertComponent(newFileDto(project));
ComponentDto fileBranch = dbTester.components().insertComponent(newFileDto(branch));
ComponentDto filePR = dbTester.components().insertComponent(newFileDto(pullRequest));
.executeProtobuf(SearchWsResponse.class);
SearchWsResponse responseBranch = newRequest(branch)
.executeProtobuf(SearchWsResponse.class);
- SearchWsResponse responsePR = newRequest(pullRequest)
+ SearchWsResponse responsePR = newRequest(pullRequest, res -> res.setParam(PARAM_PULL_REQUEST, "prKey"))
.executeProtobuf(SearchWsResponse.class);
assertThat(responseProject.getHotspotsList())
@Test
public void returns_pullRequest_field_of_components_of_pullRequest() {
ComponentDto project = dbTester.components().insertPublicProject();
- ComponentDto pullRequest = dbTester.components().insertProjectBranch(project, t -> t.setBranchType(BranchType.PULL_REQUEST));
+ String pullRequestKey = RandomStringUtils.randomAlphanumeric(100);
+ ComponentDto pullRequest = dbTester.components().insertProjectBranch(project, t -> t.setBranchType(BranchType.PULL_REQUEST)
+ .setKey(pullRequestKey));
userSessionRule.registerComponents(project, pullRequest);
indexPermissions();
ComponentDto directory = dbTester.components().insertComponent(newDirectory(pullRequest, "donut/acme"));
IssueDto projectHotspot = insertHotspot(pullRequest, pullRequest, rule);
indexIssues();
- SearchWsResponse response = newRequest(pullRequest)
+ SearchWsResponse response = newRequest(pullRequest, r -> r.setParam(PARAM_PULL_REQUEST, "pullRequestKey"))
.executeProtobuf(SearchWsResponse.class);
assertThat(response.getHotspotsList())
Map<String, Component> componentByKey = response.getComponentsList().stream().collect(uniqueIndex(Component::getKey));
Component actualProject = componentByKey.get(project.getKey());
assertThat(actualProject.hasBranch()).isFalse();
- assertThat(actualProject.getPullRequest()).isEqualTo(pullRequest.getPullRequest());
+ assertThat(actualProject.getPullRequest()).isEqualTo(pullRequestKey);
Component actualDirectory = componentByKey.get(directory.getKey());
assertThat(actualDirectory.hasBranch()).isFalse();
- assertThat(actualDirectory.getPullRequest()).isEqualTo(pullRequest.getPullRequest());
+ assertThat(actualDirectory.getPullRequest()).isEqualTo(pullRequestKey);
Component actualFile = componentByKey.get(file.getKey());
assertThat(actualFile.hasBranch()).isFalse();
- assertThat(actualFile.getPullRequest()).isEqualTo(pullRequest.getPullRequest());
+ assertThat(actualFile.getPullRequest()).isEqualTo(pullRequestKey);
}
@Test
if (branch != null) {
res.setParam(PARAM_BRANCH, branch);
}
- String pullRequest = project.getPullRequest();
- if (pullRequest != null) {
- res.setParam(PARAM_PULL_REQUEST, pullRequest);
- }
if (status != null) {
res.setParam(PARAM_STATUS, status);
}
import java.util.stream.IntStream;
import java.util.stream.Stream;
import javax.annotation.Nullable;
+import org.apache.commons.lang.RandomStringUtils;
import org.assertj.core.groups.Tuple;
import org.junit.Rule;
import org.junit.Test;
@Test
public void returns_pullRequest_but_no_branch_on_component_and_project_on_pullRequest() {
ComponentDto project = dbTester.components().insertPublicProject();
+ String pullRequestKey = RandomStringUtils.randomAlphanumeric(100);
ComponentDto pullRequest = dbTester.components().insertProjectBranch(project,
- t -> t.setBranchType(BranchType.PULL_REQUEST));
+ t -> t.setBranchType(BranchType.PULL_REQUEST).setKey(pullRequestKey));
ComponentDto file = dbTester.components().insertComponent(newFileDto(pullRequest));
userSessionRule.registerComponents(project);
RuleDto rule = newRule(SECURITY_HOTSPOT);
Hotspots.ShowWsResponse response = newRequest(hotspot)
.executeProtobuf(Hotspots.ShowWsResponse.class);
- verifyComponent(response.getProject(), pullRequest, null, pullRequest.getPullRequest());
- verifyComponent(response.getComponent(), file, null, pullRequest.getPullRequest());
+ verifyComponent(response.getProject(), pullRequest, null, pullRequestKey);
+ verifyComponent(response.getComponent(), file, null, pullRequestKey);
}
@Test
import java.time.Clock;
import java.util.Arrays;
import java.util.Date;
+import org.apache.commons.lang.RandomStringUtils;
import org.junit.Rule;
import org.junit.Test;
import org.sonar.api.resources.Languages;
ComponentDto project = db.components().insertPrivateProject();
ComponentDto projectFile = db.components().insertComponent(newFileDto(project));
IssueDto projectIssue = db.issues().insertIssue(rule, project, projectFile);
- ComponentDto pullRequest = db.components().insertProjectBranch(project, b -> b.setBranchType(PULL_REQUEST));
+
+ String pullRequestKey = RandomStringUtils.randomAlphanumeric(100);
+ ComponentDto pullRequest = db.components().insertProjectBranch(project, b -> b.setBranchType(PULL_REQUEST).setKey(pullRequestKey));
ComponentDto pullRequestFile = db.components().insertComponent(newFileDto(pullRequest));
IssueDto pullRequestIssue = db.issues().insertIssue(rule, pullRequest, pullRequestFile);
allowAnyoneOnProjects(project);
SearchWsResponse result = ws.newRequest()
.setParam(PARAM_COMPONENT_KEYS, pullRequest.getKey())
- .setParam(PARAM_PULL_REQUEST, pullRequest.getPullRequest())
+ .setParam(PARAM_PULL_REQUEST, pullRequestKey)
.executeProtobuf(SearchWsResponse.class);
assertThat(result.getIssuesList())
.extracting(Issue::getKey, Issue::getComponent, Issue::getPullRequest)
- .containsExactlyInAnyOrder(tuple(pullRequestIssue.getKey(), pullRequestFile.getKey(), pullRequestFile.getPullRequest()));
+ .containsExactlyInAnyOrder(tuple(pullRequestIssue.getKey(), pullRequestFile.getKey(), pullRequestKey));
assertThat(result.getComponentsList())
.extracting(Issues.Component::getKey, Issues.Component::getPullRequest)
.containsExactlyInAnyOrder(
- tuple(pullRequestFile.getKey(), pullRequestFile.getPullRequest()),
- tuple(pullRequest.getKey(), pullRequest.getPullRequest()));
+ tuple(pullRequestFile.getKey(), pullRequestKey),
+ tuple(pullRequest.getKey(), pullRequestKey));
}
@Test
@Test
public void formatOperation_should_add_pullrequest_on_issue() {
- componentDto.setKey(randomAlphanumeric(5) + PULL_REQUEST_SEPARATOR + randomAlphanumeric(5));
+ String pullRequestKey = randomAlphanumeric(5);
+ componentDto.setKey(randomAlphanumeric(5) + PULL_REQUEST_SEPARATOR + pullRequestKey);
Operation result = searchResponseFormat.formatOperation(searchResponseData);
- assertThat(result.getIssue().getPullRequest()).isEqualTo(componentDto.getPullRequest());
+ assertThat(result.getIssue().getPullRequest()).isEqualTo(pullRequestKey);
}
@Test
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import org.apache.commons.io.IOUtils;
+import org.apache.commons.lang.RandomStringUtils;
import org.junit.Rule;
import org.junit.Test;
import org.sonar.api.measures.CoreMetrics;
@Test
public void return_live_status_when_pull_request_is_referenced_by_its_key() throws IOException {
ComponentDto project = db.components().insertPrivateProject();
- ComponentDto pr = db.components().insertProjectBranch(project, branch -> branch.setBranchType(BranchType.PULL_REQUEST));
+ String pullRequestKey = RandomStringUtils.randomAlphanumeric(100);
+ ComponentDto pr = db.components().insertProjectBranch(project, branch -> branch.setBranchType(BranchType.PULL_REQUEST)
+ .setKey(pullRequestKey));
dbClient.snapshotDao().insert(dbSession, newAnalysis(pr)
.setPeriodMode("last_version")
String response = ws.newRequest()
.setParam(PARAM_PROJECT_KEY, project.getKey())
- .setParam(PARAM_PULL_REQUEST, pr.getPullRequest())
+ .setParam(PARAM_PULL_REQUEST, pullRequestKey)
.execute().getInput();
assertJson(response).isSimilarTo(getClass().getResource("project_status-example.json"));
import org.sonar.server.ws.WsActionTester;
import static java.lang.String.format;
+import static org.apache.commons.lang.RandomStringUtils.randomAlphanumeric;
import static org.assertj.core.api.Assertions.assertThatThrownBy;
import static org.mockito.ArgumentMatchers.anyString;
import static org.mockito.Mockito.mock;
public void pull_request() {
ComponentDto project = db.components().insertPrivateProject();
userSession.addProjectPermission(UserRole.USER, project);
- ComponentDto branch = db.components().insertProjectBranch(project, b -> b.setBranchType(PULL_REQUEST));
+ String pullRequestKey = randomAlphanumeric(100);
+ ComponentDto branch = db.components().insertProjectBranch(project, b -> b.setBranchType(PULL_REQUEST).setKey(pullRequestKey));
ComponentDto file = db.components().insertComponent(newFileDto(branch));
db.getDbClient().fileSourceDao().insert(db.getSession(), new FileSourceDto()
.setUuid(Uuids.createFast())
tester.newRequest()
.setParam("key", file.getKey())
- .setParam("pullRequest", file.getPullRequest())
+ .setParam("pullRequest", pullRequestKey)
.execute()
.assertJson(getClass(), "show_source.json");
}