private static void setKeyType(BranchDto dto) { if (dto.getBranchType() == BranchType.PULL_REQUEST) { dto.setKeyType(KeyType.PULL_REQUEST); } else { dto.setKeyType(KeyType.BRANCH); } }
private static String toString(BranchDto branch) { return branch.getBranchType() + ":" + branch.getUuid() + ":" + branch.getProjectUuid() + ":" + branch.getMergeBranchUuid(); }
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; }
private static void setBranchStatus(ProjectBranches.Branch.Builder builder, BranchDto branch, @Nullable LiveMeasureDto qualityGateMeasure, @Nullable BranchStatistics branchStatistics) { ProjectBranches.Status.Builder statusBuilder = ProjectBranches.Status.newBuilder(); if (qualityGateMeasure != null) { ofNullable(qualityGateMeasure.getDataAsString()).ifPresent(statusBuilder::setQualityGateStatus); } if (branch.getBranchType() == BranchType.SHORT) { statusBuilder.setBugs(branchStatistics == null ? 0L : branchStatistics.getBugs()); statusBuilder.setVulnerabilities(branchStatistics == null ? 0L : branchStatistics.getVulnerabilities()); statusBuilder.setCodeSmells(branchStatistics == null ? 0L : branchStatistics.getCodeSmells()); } builder.setStatus(statusBuilder); }
private void checkComponentType(DbSession dbSession, ComponentDto project) { Optional<BranchDto> branch = dbClient.branchDao().selectByUuid(dbSession, project.uuid()); if (project.isPrivate()) { throw generateInvalidProjectExcpetion(); } if (branch.isPresent() && !branch.get().getBranchType().equals(LONG)) { throw generateInvalidProjectExcpetion(); } if (!project.qualifier().equals(PROJECT) && !project.qualifier().equals(APP)) { throw generateInvalidProjectExcpetion(); } }
@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); } }
@Override public QualityGate loadQualityGate(DbSession dbSession, OrganizationDto organization, ComponentDto project, BranchDto branch) { if (branch.getBranchType() == BranchType.SHORT || branch.getBranchType() == BranchType.PULL_REQUEST) { return ShortLivingBranchQualityGate.GATE; } ComponentDto mainProject = project.getMainBranchProjectUuid() == null ? project : dbClient.componentDao().selectOrFailByKey(dbSession, project.getKey()); QualityGateDto gateDto = qGateFinder.getQualityGate(dbSession, organization, mainProject) .orElseThrow(() -> new IllegalStateException(format("Quality Gate not found for project %s", mainProject.getKey()))) .getQualityGate(); Collection<QualityGateConditionDto> conditionDtos = dbClient.gateConditionDao().selectForQualityGate(dbSession, gateDto.getId()); Set<Integer> metricIds = conditionDtos.stream().map(c -> (int) c.getMetricId()) .collect(toHashSet(conditionDtos.size())); Map<Integer, MetricDto> metricsById = dbClient.metricDao().selectByIds(dbSession, metricIds).stream() .collect(uniqueIndex(MetricDto::getId)); Set<Condition> conditions = conditionDtos.stream().map(conditionDto -> { String metricKey = metricsById.get((int) conditionDto.getMetricId()).getKey(); Condition.Operator operator = Condition.Operator.fromDbValue(conditionDto.getOperator()); return new Condition(metricKey, operator, conditionDto.getErrorThreshold()); }).collect(toHashSet(conditionDtos.size())); return new QualityGate(String.valueOf(gateDto.getId()), gateDto.getName(), conditions); }
@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(project.isEnabled() && PROJECT.equals(project.qualifier()), "Invalid project key"); List<BranchDto> pullRequests = dbClient.branchDao().selectByComponent(dbSession, project).stream() .filter(b -> b.getBranchType() == PULL_REQUEST) .collect(toList()); List<String> pullRequestUuids = pullRequests.stream().map(BranchDto::getUuid).collect(toList()); Map<String, BranchDto> mergeBranchesByUuid = dbClient.branchDao() .selectByUuids(dbSession, pullRequests.stream().map(BranchDto::getMergeBranchUuid).filter(Objects::nonNull).collect(toList())) .stream().collect(uniqueIndex(BranchDto::getUuid)); Map<String, BranchStatistics> branchStatisticsByBranchUuid = issueIndex.searchBranchStatistics(project.uuid(), pullRequestUuids).stream() .collect(uniqueIndex(BranchStatistics::getBranchUuid, Function.identity())); Map<String, LiveMeasureDto> qualityGateMeasuresByComponentUuids = dbClient.liveMeasureDao() .selectByComponentUuidsAndMetricKeys(dbSession, pullRequestUuids, singletonList(ALERT_STATUS_KEY)).stream() .collect(uniqueIndex(LiveMeasureDto::getComponentUuid)); Map<String, String> analysisDateByBranchUuid = dbClient.snapshotDao().selectLastAnalysesByRootComponentUuids(dbSession, pullRequestUuids).stream() .collect(uniqueIndex(SnapshotDto::getComponentUuid, s -> formatDateTime(s.getCreatedAt()))); ProjectPullRequests.ListWsResponse.Builder protobufResponse = ProjectPullRequests.ListWsResponse.newBuilder(); pullRequests .forEach(b -> addPullRequest(protobufResponse, b, mergeBranchesByUuid, qualityGateMeasuresByComponentUuids.get(b.getUuid()), branchStatisticsByBranchUuid.get(b.getUuid()), analysisDateByBranchUuid.get(b.getUuid()))); writeProtobuf(protobufResponse.build(), request, response); } }
@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(); } }
private WebhookPayload buildWebHookPayload(DbSession dbSession, QGChangeEvent event, @Nullable EvaluatedQualityGate evaluatedQualityGate) { ComponentDto project = event.getProject(); BranchDto branch = event.getBranch(); SnapshotDto analysis = event.getAnalysis(); Map<String, String> analysisProperties = dbClient.analysisPropertiesDao().selectBySnapshotUuid(dbSession, analysis.getUuid()) .stream() .collect(Collectors.toMap(AnalysisPropertyDto::getKey, AnalysisPropertyDto::getValue)); String projectUuid = StringUtils.defaultString(project.getMainBranchProjectUuid(), project.projectUuid()); ProjectAnalysis projectAnalysis = new ProjectAnalysis( new Project(projectUuid, project.getKey(), project.name()), null, new Analysis(analysis.getUuid(), analysis.getCreatedAt()), new Branch(branch.isMain(), branch.getKey(), Type.valueOf(branch.getBranchType().name())), evaluatedQualityGate, null, analysisProperties); return webhookPayloadFactory.create(projectAnalysis); }
@Test public void insert_pull_request_branch_with_only_non_null_fields() { String projectUuid = "U1"; String uuid = "U2"; BranchType branchType = BranchType.PULL_REQUEST; String kee = "123"; BranchDto dto = new BranchDto(); dto.setProjectUuid(projectUuid); dto.setUuid(uuid); dto.setBranchType(branchType); dto.setKey(kee); underTest.insert(dbSession, dto); BranchDto loaded = underTest.selectByUuid(dbSession, dto.getUuid()).get(); assertThat(loaded.getProjectUuid()).isEqualTo(projectUuid); assertThat(loaded.getUuid()).isEqualTo(uuid); assertThat(loaded.getBranchType()).isEqualTo(branchType); assertThat(loaded.getKey()).isEqualTo(kee); assertThat(loaded.getMergeBranchUuid()).isNull(); assertThat(loaded.getPullRequestData()).isNull(); }
@Test public void create_application() { NewComponent application = NewComponent.newComponentBuilder() .setKey("app-key") .setName("app-name") .setQualifier(APP) .setOrganizationUuid(db.getDefaultOrganization().getUuid()) .build(); ComponentDto returned = underTest.create(db.getSession(), application, null); ComponentDto loaded = db.getDbClient().componentDao().selectOrFailByUuid(db.getSession(), returned.uuid()); assertThat(loaded.getDbKey()).isEqualTo("app-key"); assertThat(loaded.name()).isEqualTo("app-name"); assertThat(loaded.qualifier()).isEqualTo("APP"); assertThat(projectIndexers.hasBeenCalled(loaded.uuid(), ProjectIndexer.Cause.PROJECT_CREATION)).isTrue(); Optional<BranchDto> branch = db.getDbClient().branchDao().selectByUuid(db.getSession(), returned.uuid()); assertThat(branch).isPresent(); assertThat(branch.get().getKey()).isEqualTo(BranchDto.DEFAULT_MAIN_BRANCH_NAME); assertThat(branch.get().getMergeBranchUuid()).isNull(); assertThat(branch.get().getBranchType()).isEqualTo(BranchType.LONG); assertThat(branch.get().getUuid()).isEqualTo(returned.uuid()); assertThat(branch.get().getProjectUuid()).isEqualTo(returned.uuid()); }
@Test public void upsert_branch() { BranchDto dto = new BranchDto(); dto.setProjectUuid("U1"); dto.setUuid("U2"); dto.setBranchType(BranchType.LONG); dto.setKey("foo"); underTest.insert(dbSession, dto); // the fields that can be updated dto.setMergeBranchUuid("U3"); // the fields that can't be updated. New values are ignored. dto.setProjectUuid("ignored"); dto.setBranchType(BranchType.SHORT); underTest.upsert(dbSession, dto); BranchDto loaded = underTest.selectByBranchKey(dbSession, "U1", "foo").get(); assertThat(loaded.getMergeBranchUuid()).isEqualTo("U3"); assertThat(loaded.getProjectUuid()).isEqualTo("U1"); assertThat(loaded.getBranchType()).isEqualTo(BranchType.LONG); }
assertThat(loaded.getBranchType()).isEqualTo(branchType); assertThat(loaded.getKey()).isEqualTo(kee); assertThat(loaded.getMergeBranchUuid()).isNull();
@Test public void selectByBranchKey() { BranchDto mainBranch = new BranchDto(); mainBranch.setProjectUuid("U1"); mainBranch.setUuid("U1"); mainBranch.setBranchType(BranchType.LONG); mainBranch.setKey("master"); underTest.insert(dbSession, mainBranch); BranchDto featureBranch = new BranchDto(); featureBranch.setProjectUuid("U1"); featureBranch.setUuid("U2"); featureBranch.setBranchType(BranchType.SHORT); featureBranch.setKey("feature/foo"); featureBranch.setMergeBranchUuid("U3"); underTest.insert(dbSession, featureBranch); // select the feature branch BranchDto loaded = underTest.selectByBranchKey(dbSession, "U1", "feature/foo").get(); assertThat(loaded.getUuid()).isEqualTo(featureBranch.getUuid()); assertThat(loaded.getKey()).isEqualTo(featureBranch.getKey()); assertThat(loaded.getProjectUuid()).isEqualTo(featureBranch.getProjectUuid()); assertThat(loaded.getBranchType()).isEqualTo(featureBranch.getBranchType()); assertThat(loaded.getMergeBranchUuid()).isEqualTo(featureBranch.getMergeBranchUuid()); // select a branch on another project with same branch name assertThat(underTest.selectByBranchKey(dbSession, "U3", "feature/foo")).isEmpty(); }
@Test public void selectByPullRequestKey() { BranchDto mainBranch = new BranchDto(); mainBranch.setProjectUuid("U1"); mainBranch.setUuid("U1"); mainBranch.setBranchType(BranchType.LONG); mainBranch.setKey("master"); underTest.insert(dbSession, mainBranch); String pullRequestId = "123"; BranchDto pullRequest = new BranchDto(); pullRequest.setProjectUuid("U1"); pullRequest.setUuid("U2"); pullRequest.setBranchType(BranchType.PULL_REQUEST); pullRequest.setKey(pullRequestId); pullRequest.setMergeBranchUuid("U3"); underTest.insert(dbSession, pullRequest); // select the feature branch BranchDto loaded = underTest.selectByPullRequestKey(dbSession, "U1", pullRequestId).get(); assertThat(loaded.getUuid()).isEqualTo(pullRequest.getUuid()); assertThat(loaded.getKey()).isEqualTo(pullRequest.getKey()); assertThat(loaded.getProjectUuid()).isEqualTo(pullRequest.getProjectUuid()); assertThat(loaded.getBranchType()).isEqualTo(pullRequest.getBranchType()); assertThat(loaded.getMergeBranchUuid()).isEqualTo(pullRequest.getMergeBranchUuid()); // select a branch on another project with same branch name assertThat(underTest.selectByPullRequestKey(dbSession, "U3", pullRequestId)).isEmpty(); }
@Test public void update_main_branch_name() { BranchDto dto = new BranchDto(); dto.setProjectUuid("U1"); dto.setUuid("U1"); dto.setBranchType(BranchType.LONG); dto.setKey("feature"); underTest.insert(dbSession, dto); BranchDto dto2 = new BranchDto(); dto2.setProjectUuid("U2"); dto2.setUuid("U2"); dto2.setBranchType(BranchType.LONG); dto2.setKey("branch"); underTest.insert(dbSession, dto2); underTest.updateMainBranchName(dbSession, "U1", "master"); BranchDto loaded = underTest.selectByBranchKey(dbSession, "U1", "master").get(); assertThat(loaded.getMergeBranchUuid()).isNull(); assertThat(loaded.getProjectUuid()).isEqualTo("U1"); assertThat(loaded.getBranchType()).isEqualTo(BranchType.LONG); }
@Test @UseDataProvider("nullOrNotNullString") public void persist_creates_row_in_PROJECTS_BRANCHES_for_long_branch(@Nullable String mergeBranchUuid) { String branchName = "branch"; // add project and branch in table PROJECTS ComponentDto mainComponent = ComponentTesting.newPrivateProjectDto(dbTester.organizations().insert(), MAIN.getUuid()).setDbKey(MAIN.getKey()); ComponentDto component = ComponentTesting.newProjectBranch(mainComponent, new BranchDto().setUuid(BRANCH.getUuid()).setKey(BRANCH.getKey()).setBranchType(LONG)); dbTester.getDbClient().componentDao().insert(dbTester.getSession(), mainComponent, component); dbTester.commit(); // set project in metadata treeRootHolder.setRoot(BRANCH); analysisMetadataHolder.setBranch(createBranch(LONG, false, branchName, mergeBranchUuid)); analysisMetadataHolder.setProject(Project.from(mainComponent)); underTest.persist(dbTester.getSession()); dbTester.getSession().commit(); assertThat(dbTester.countRowsOfTable("projects")).isEqualTo(2); Optional<BranchDto> branchDto = dbTester.getDbClient().branchDao().selectByUuid(dbTester.getSession(), BRANCH.getUuid()); assertThat(branchDto).isPresent(); assertThat(branchDto.get().getBranchType()).isEqualTo(LONG); assertThat(branchDto.get().getKey()).isEqualTo(branchName); assertThat(branchDto.get().getMergeBranchUuid()).isEqualTo(mergeBranchUuid); assertThat(branchDto.get().getProjectUuid()).isEqualTo(MAIN.getUuid()); assertThat(branchDto.get().getPullRequestData()).isNull(); }
@Test @UseDataProvider("nullOrNotNullString") public void persist_creates_row_in_PROJECTS_BRANCHES_for_pull_request(@Nullable String mergeBranchUuid) { String pullRequestId = "pr-123"; // add project and branch in table PROJECTS ComponentDto mainComponent = ComponentTesting.newPrivateProjectDto(dbTester.organizations().insert(), MAIN.getUuid()).setDbKey(MAIN.getKey()); ComponentDto component = ComponentTesting.newProjectBranch(mainComponent, new BranchDto().setUuid(BRANCH.getUuid()).setKey(BRANCH.getKey()).setBranchType(PULL_REQUEST)); dbTester.getDbClient().componentDao().insert(dbTester.getSession(), mainComponent, component); dbTester.commit(); // set project in metadata treeRootHolder.setRoot(BRANCH); analysisMetadataHolder.setBranch(createBranch(PULL_REQUEST, false, pullRequestId, mergeBranchUuid)); analysisMetadataHolder.setProject(Project.from(mainComponent)); analysisMetadataHolder.setPullRequestKey(pullRequestId); underTest.persist(dbTester.getSession()); dbTester.getSession().commit(); assertThat(dbTester.countRowsOfTable("projects")).isEqualTo(2); Optional<BranchDto> branchDto = dbTester.getDbClient().branchDao().selectByUuid(dbTester.getSession(), BRANCH.getUuid()); 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().getProjectUuid()).isEqualTo(MAIN.getUuid()); assertThat(branchDto.get().getPullRequestData()).isEqualTo(DbProjectBranches.PullRequestData.newBuilder() .setBranch(pullRequestId) .setTitle(pullRequestId) .build()); }
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()); } }