@Test public void insert_branch_with_all_fields_and_max_length_values() { BranchDto dto = new BranchDto(); dto.setProjectUuid(repeat("a", 50)); dto.setUuid(repeat("b", 50)); dto.setBranchType(BranchType.SHORT); dto.setKey(repeat("c", 255)); dto.setMergeBranchUuid(repeat("d", 50)); underTest.insert(dbSession, dto); Map<String, Object> map = db.selectFirst(dbSession, SELECT_FROM + " where uuid='" + dto.getUuid() + "'"); assertThat((String) map.get("projectUuid")).contains("a").isEqualTo(dto.getProjectUuid()); assertThat((String) map.get("uuid")).contains("b").isEqualTo(dto.getUuid()); assertThat((String) map.get("kee")).contains("c").isEqualTo(dto.getKey()); assertThat((String) map.get("mergeBranchUuid")).contains("d").isEqualTo(dto.getMergeBranchUuid()); }
private static String toString(BranchDto branch) { return branch.getBranchType() + ":" + branch.getUuid() + ":" + branch.getProjectUuid() + ":" + branch.getMergeBranchUuid(); }
private static void setKeyType(BranchDto dto) { if (dto.getBranchType() == BranchType.PULL_REQUEST) { dto.setKeyType(KeyType.PULL_REQUEST); } else { dto.setKeyType(KeyType.BRANCH); } }
private BranchDto createMainBranch(DbSession session, String componentUuid) { BranchDto branch = new BranchDto() .setBranchType(BranchType.LONG) .setUuid(componentUuid) .setKey(BranchDto.DEFAULT_MAIN_BRANCH_NAME) .setMergeBranchUuid(null) .setProjectUuid(componentUuid); dbClient.branchDao().upsert(session, branch); return branch; }
@Test public void fail_when_not_having_right_permission() { ComponentDto project = db.components().insertMainBranch(); db.components().insertProjectBranch(project, b -> b.setKey("123") .setBranchType(PULL_REQUEST) .setMergeBranchUuid(project.uuid()) .setPullRequestData(DbProjectBranches.PullRequestData.newBuilder().setBranch("feature/bar").build())); userSession.logIn().addProjectPermission(CODEVIEWER, project); expectedException.expect(ForbiddenException.class); ws.newRequest() .setParam("project", project.getDbKey()) .execute(); }
@Test public void mergeBranch_is_using_default_main_name_when_main_branch_has_no_name() { ComponentDto project = db.components().insertMainBranch(); userSession.logIn().addProjectPermission(USER, project); ComponentDto shortLivingBranch = db.components().insertProjectBranch(project, b -> b.setKey("short").setBranchType(SHORT).setMergeBranchUuid(project.uuid())); ProjectBranches.ShowWsResponse response = ws.newRequest() .setParam("project", shortLivingBranch.getKey()) .executeProtobuf(ProjectBranches.ShowWsResponse.class); assertThat(response.getBranch()) .extracting(Branch::getName, Branch::getType, Branch::getMergeBranch) .containsExactlyInAnyOrder(shortLivingBranch.getBranch(), BranchType.SHORT, "master"); }
private static ProjectBranches.Branch.Builder toBranchBuilder(BranchDto branch, Optional<BranchDto> mergeBranch) { ProjectBranches.Branch.Builder builder = ProjectBranches.Branch.newBuilder(); String branchKey = branch.getKey(); ofNullable(branchKey).ifPresent(builder::setName); builder.setIsMain(branch.isMain()); builder.setType(Common.BranchType.valueOf(branch.getBranchType().name())); if (branch.getBranchType() == SHORT) { if (mergeBranch.isPresent()) { String mergeBranchKey = mergeBranch.get().getKey(); builder.setMergeBranch(mergeBranchKey); } else { builder.setIsOrphan(true); } } return builder; }
@SafeVarargs public final ComponentDto insertMainBranch(OrganizationDto organization, String mainBranchName, Consumer<ComponentDto>... dtoPopulators) { ComponentDto project = newPrivateProjectDto(organization); BranchDto branchDto = newBranchDto(project, LONG).setKey(mainBranchName); Arrays.stream(dtoPopulators).forEach(dtoPopulator -> dtoPopulator.accept(project)); insertComponent(project); dbClient.branchDao().insert(dbSession, branchDto); db.commit(); return project; }
@Test public void status_on_short_living_branch_with_no_issue() { ComponentDto project = db.components().insertMainBranch(); userSession.logIn().addProjectPermission(USER, project); ComponentDto longLivingBranch = db.components().insertProjectBranch(project, b -> b.setBranchType(org.sonar.db.component.BranchType.LONG)); db.components().insertProjectBranch(project, b -> b.setBranchType(SHORT).setMergeBranchUuid(longLivingBranch.uuid())); issueIndexer.indexOnStartup(emptySet()); permissionIndexerTester.allowOnlyAnyone(project); ListWsResponse response = ws.newRequest() .setParam("project", project.getKey()) .executeProtobuf(ListWsResponse.class); assertThat(response.getBranchesList().stream().filter(b -> b.getType().equals(BranchType.SHORT)).map(ProjectBranches.Branch::getStatus)) .extracting(Status::getBugs, Status::getVulnerabilities, Status::getCodeSmells) .containsExactlyInAnyOrder(tuple(0L, 0L, 0L)); }
@Test public void fail_when_pull_request_branch_provided() { ComponentDto project = db.components().insertMainBranch(); ComponentDto pullRequest = db.components().insertProjectBranch(project, b -> b.setKey("pr-123").setBranchType(PULL_REQUEST)); expectedException.expect(IllegalArgumentException.class); expectedException.expectMessage("Either branch or pull request can be provided, not both"); assertThat(underTest.getByKeyAndOptionalBranchOrPullRequest(dbSession, project.getKey(), "pr-123", "pr-123").uuid()).isEqualTo(pullRequest.uuid()); }
@Override public void handle(Request request, Response response) throws Exception { String projectKey = request.mandatoryParam(PARAM_PROJECT); try (DbSession dbSession = dbClient.openSession(false)) { ComponentDto project = componentFinder.getByKey(dbSession, projectKey); checkPermission(project); checkArgument(ALLOWED_QUALIFIERS.contains(project.qualifier()), "Invalid project"); Collection<BranchDto> branches = dbClient.branchDao().selectByComponent(dbSession, project).stream() .filter(b -> b.getBranchType() == SHORT || b.getBranchType() == LONG) .collect(toList()); List<String> branchUuids = branches.stream().map(BranchDto::getUuid).collect(toList()); Map<String, BranchDto> mergeBranchesByUuid = dbClient.branchDao() .selectByUuids(dbSession, branches.stream().map(BranchDto::getMergeBranchUuid).filter(Objects::nonNull).collect(toList())) .stream().collect(uniqueIndex(BranchDto::getUuid)); Map<String, LiveMeasureDto> qualityGateMeasuresByComponentUuids = dbClient.liveMeasureDao() .selectByComponentUuidsAndMetricKeys(dbSession, branchUuids, singletonList(ALERT_STATUS_KEY)).stream() .collect(uniqueIndex(LiveMeasureDto::getComponentUuid)); Map<String, BranchStatistics> branchStatisticsByBranchUuid = issueIndex.searchBranchStatistics(project.uuid(), branches.stream() .filter(b -> b.getBranchType().equals(SHORT)) .map(BranchDto::getUuid).collect(toList())).stream() .collect(uniqueIndex(BranchStatistics::getBranchUuid, Function.identity())); Map<String, String> analysisDateByBranchUuid = dbClient.snapshotDao() .selectLastAnalysesByRootComponentUuids(dbSession, branchUuids).stream() .collect(uniqueIndex(SnapshotDto::getComponentUuid, s -> formatDateTime(s.getCreatedAt()))); ProjectBranches.ListWsResponse.Builder protobufResponse = ProjectBranches.ListWsResponse.newBuilder(); branches.forEach(b -> addBranch(protobufResponse, b, mergeBranchesByUuid, qualityGateMeasuresByComponentUuids.get(b.getUuid()), branchStatisticsByBranchUuid.get(b.getUuid()), analysisDateByBranchUuid.get(b.getUuid()))); WsUtils.writeProtobuf(protobufResponse.build(), request, response); } }
private static void addPullRequest(ProjectPullRequests.ListWsResponse.Builder response, BranchDto branch, Map<String, BranchDto> mergeBranchesByUuid, @Nullable LiveMeasureDto qualityGateMeasure, BranchStatistics branchStatistics, @Nullable String analysisDate) { Optional<BranchDto> mergeBranch = Optional.ofNullable(mergeBranchesByUuid.get(branch.getMergeBranchUuid())); ProjectPullRequests.PullRequest.Builder builder = ProjectPullRequests.PullRequest.newBuilder(); builder.setKey(branch.getKey()); DbProjectBranches.PullRequestData pullRequestData = requireNonNull(branch.getPullRequestData(), "Pull request data should be available for branch type PULL_REQUEST"); builder.setBranch(pullRequestData.getBranch()); ofNullable(emptyToNull(pullRequestData.getUrl())).ifPresent(builder::setUrl); ofNullable(emptyToNull(pullRequestData.getTitle())).ifPresent(builder::setTitle); if (mergeBranch.isPresent()) { String mergeBranchKey = mergeBranch.get().getKey(); builder.setBase(mergeBranchKey); } else { builder.setIsOrphan(true); } ofNullable(analysisDate).ifPresent(builder::setAnalysisDate); setQualityGate(builder, qualityGateMeasure, branchStatistics); response.addPullRequests(builder); }
@Test public void isMain_is_true_if_branch_uuid_equals_project_uuid() { underTest.setProjectUuid("U1"); underTest.setUuid("U1"); assertThat(underTest.isMain()).isTrue(); }
@Test public void rename() { userSession.logIn(); ComponentDto project = db.components().insertMainBranch(); ComponentDto branch = db.components().insertProjectBranch(project, b -> b.setKey("branch")); userSession.addProjectPermission(UserRole.ADMIN, project); tester.newRequest() .setParam("project", project.getKey()) .setParam("name", "master") .execute(); assertThat(db.countRowsOfTable("project_branches")).isEqualTo(2); Optional<BranchDto> mainBranch = db.getDbClient().branchDao().selectByUuid(db.getSession(), project.uuid()); assertThat(mainBranch.get().getKey()).isEqualTo("master"); Optional<BranchDto> unchangedBranch = db.getDbClient().branchDao().selectByUuid(db.getSession(), branch.uuid()); assertThat(unchangedBranch.get().getKey()).isEqualTo("branch"); }
public static ComponentDto newProjectBranch(ComponentDto project, BranchDto branchDto) { checkArgument(project.qualifier().equals(Qualifiers.PROJECT) || project.qualifier().equals(Qualifiers.APP)); checkArgument(project.getMainBranchProjectUuid() == null); String branchName = branchDto.getKey(); String branchSeparator = branchDto.getBranchType() == PULL_REQUEST ? PULL_REQUEST_SEPARATOR : BRANCH_KEY_SEPARATOR; String uuid = branchDto.getUuid(); return new ComponentDto() .setUuid(uuid) .setOrganizationUuid(project.getOrganizationUuid()) .setUuidPath(UUID_PATH_OF_ROOT) .setProjectUuid(uuid) .setModuleUuidPath(UUID_PATH_SEPARATOR + uuid + UUID_PATH_SEPARATOR) .setRootUuid(uuid) // name of the branch is not mandatory on the main branch .setDbKey(branchName != null ? project.getDbKey() + branchSeparator + branchName : project.getKey()) .setMainBranchProjectUuid(project.uuid()) .setName(project.name()) .setLongName(project.longName()) .setDescription(project.description()) .setScope(project.scope()) .setQualifier(project.qualifier()) .setPath(null) .setLanguage(null) .setEnabled(true) .setPrivate(project.isPrivate()); } }
@Override public void handle(Request request, Response response) throws Exception { userSession.checkLoggedIn(); String projectKey = request.mandatoryParam(PARAM_PROJECT); String pullRequestId = request.mandatoryParam(PARAM_PULL_REQUEST); try (DbSession dbSession = dbClient.openSession(false)) { ComponentDto project = componentFinder.getRootComponentByUuidOrKey(dbSession, null, projectKey); checkPermission(project); BranchDto pullRequest = dbClient.branchDao().selectByPullRequestKey(dbSession, project.uuid(), pullRequestId) .filter(branch -> branch.getBranchType() == PULL_REQUEST) .orElseThrow(() -> new NotFoundException(String.format("Pull request '%s' is not found for project '%s'", pullRequestId, projectKey))); ComponentDto branchComponent = componentFinder.getByKeyAndPullRequest(dbSession, projectKey, pullRequest.getKey()); componentCleanerService.deleteBranch(dbSession, branchComponent); response.noContent(); } }
@Test public void loadQualityGate_returns_hardcoded_gate_for_pull_requests() { OrganizationDto organization = db.organizations().insert(); ComponentDto project = db.components().insertPublicProject(organization); BranchDto pullRequest = newBranchDto(project).setBranchType(BranchType.PULL_REQUEST); db.components().insertProjectBranch(project, pullRequest); QualityGate result = underTest.loadQualityGate(db.getSession(), organization, project, pullRequest); assertThat(result).isSameAs(ShortLivingBranchQualityGate.GATE); }
private void setPrivateForRootComponentUuid(DbSession dbSession, String uuid, boolean isPrivate) { dbClient.componentDao().setPrivateForRootComponentUuid(dbSession, uuid, isPrivate); ComponentMapper mapper = dbSession.getMapper(ComponentMapper.class); dbSession.getMapper(BranchMapper.class).selectByProjectUuid(uuid) .stream() .filter(branch -> !uuid.equals(branch.getUuid())) .forEach(branch -> mapper.setPrivateForRootComponentUuid(branch.getUuid(), isPrivate)); }
@Test public void return_alm_info_on_branch() { ComponentDto project = insertOrganizationAndProject(); ComponentDto branch = componentDbTester.insertProjectBranch(project, b -> b.setKey("feature1").setUuid("xyz")); dbClient.projectAlmBindingsDao().insertOrUpdate(db.getSession(), ALM.BITBUCKETCLOUD, "{123456789}", project.uuid(), null, "http://bitbucket.org/foo/bar"); db.getSession().commit(); userSession.addProjectPermission(UserRole.USER, project); init(); String json = ws.newRequest() .setParam("componentKey", project.getKey()) .setParam("branch", branch.getBranch()) .execute() .getInput(); assertJson(json).isSimilarTo("{\n" + " \"organization\": \"my-org\",\n" + " \"key\": \"polop\",\n" + " \"id\": \"xyz\",\n" + " \"branch\": \"feature1\"," + " \"name\": \"Polop\",\n" + " \"description\": \"test project\",\n" + " \"alm\": {\n" + " \"key\": \"bitbucketcloud\",\n" + " \"url\": \"http://bitbucket.org/foo/bar\"\n" + " }\n" + "}\n"); }
private static QGChangeEvent newQGChangeEvent(Configuration configuration, @Nullable Metric.Level previousQQStatus, @Nullable EvaluatedQualityGate evaluatedQualityGate) { return new QGChangeEvent(new ComponentDto(), new BranchDto(), new SnapshotDto(), configuration, previousQQStatus, () -> Optional.ofNullable(evaluatedQualityGate)); }