MergeRequest first

This commit is contained in:
uPagge 2021-01-14 23:56:54 +03:00
parent 6235d03420
commit ab46101067
No known key found for this signature in database
GPG Key ID: 964B40928E4C9088
36 changed files with 571 additions and 1022 deletions

View File

@ -45,11 +45,6 @@
<dependencies>
<dependency>
<groupId>org.sadtech.bot.gitlab</groupId>
<artifactId>gitlab-core</artifactId>
</dependency>
<dependency>
<groupId>org.sadtech.bot.gitlab</groupId>
<artifactId>bot-core</artifactId>

View File

@ -23,4 +23,9 @@ public class SchedulerService {
projectParser.parseNewProject();
}
@Scheduled(cron = "0 */1 * * * *")
public void newMergeRequest() {
}
}

View File

@ -5,12 +5,12 @@ import org.sadtech.bot.gitlab.app.config.property.CommentSchedulerProperty;
import org.sadtech.bot.gitlab.app.service.ExecutorScanner;
import org.sadtech.bot.gitlab.app.service.executor.DataScan;
import org.sadtech.bot.gitlab.context.domain.entity.Comment;
import org.sadtech.bot.gitlab.context.domain.entity.PullRequest;
import org.sadtech.bot.gitlab.context.domain.entity.MergeRequest;
import org.sadtech.bot.gitlab.context.domain.entity.PullRequestMini;
import org.sadtech.bot.gitlab.context.domain.entity.Task;
import org.sadtech.bot.gitlab.context.exception.NotFoundException;
import org.sadtech.bot.gitlab.context.service.CommentService;
import org.sadtech.bot.gitlab.context.service.PullRequestsService;
import org.sadtech.bot.gitlab.context.service.MergeRequestsService;
import org.sadtech.bot.gitlab.context.service.TaskService;
import org.sadtech.bot.gitlab.core.config.properties.GitlabProperty;
import org.sadtech.bot.gitlab.core.config.properties.InitProperty;
@ -33,7 +33,7 @@ import java.util.stream.Collectors;
public class CommentAndTaskParser {
private final CommentService commentService;
private final PullRequestsService pullRequestsService;
private final MergeRequestsService mergeRequestsService;
private final ExecutorScanner executorScanner;
private final TaskService taskService;
private final ConversionService conversionService;
@ -46,7 +46,7 @@ public class CommentAndTaskParser {
public CommentAndTaskParser(
CommentService commentService,
PullRequestsService pullRequestsService,
MergeRequestsService mergeRequestsService,
ExecutorScanner executorScanner,
TaskService taskService,
ConversionService conversionService,
@ -55,7 +55,7 @@ public class CommentAndTaskParser {
InitProperty initProperty
) {
this.commentService = commentService;
this.pullRequestsService = pullRequestsService;
this.mergeRequestsService = mergeRequestsService;
this.executorScanner = executorScanner;
this.taskService = taskService;
this.conversionService = conversionService;
@ -97,7 +97,7 @@ public class CommentAndTaskParser {
List<DataScan> commentUrls = new ArrayList<>();
for (int i = 0; i < 5; i++) {
int page = 0;
Sheet<PullRequest> pullRequestPage = pullRequestsService.getAll(
Sheet<MergeRequest> pullRequestPage = mergeRequestsService.getAll(
PaginationImpl.of(page, commentSchedulerProperty.getCommentCount())
);
while (pullRequestPage.hasContent()) {
@ -110,7 +110,7 @@ public class CommentAndTaskParser {
)
)
.collect(Collectors.toList()));
pullRequestPage = pullRequestsService.getAll(
pullRequestPage = mergeRequestsService.getAll(
PaginationImpl.of(++page, commentSchedulerProperty.getCommentCount())
);
}
@ -125,7 +125,7 @@ public class CommentAndTaskParser {
.map(resultScan -> conversionService.convert(resultScan, Comment.class))
.peek(
comment -> {
final PullRequestMini pullRequestMini = pullRequestsService.getMiniInfo(comment.getPullRequestId())
final PullRequestMini pullRequestMini = mergeRequestsService.getMiniInfo(comment.getPullRequestId())
.orElseThrow(() -> new NotFoundException("Автор ПР не найден"));
comment.setUrl(generateUrl(comment.getId(), pullRequestMini.getUrl()));
comment.setResponsible(pullRequestMini.getAuthorLogin());
@ -140,7 +140,7 @@ public class CommentAndTaskParser {
.map(resultScan -> conversionService.convert(resultScan, Task.class))
.peek(
task -> {
final PullRequestMini pullRequestMini = pullRequestsService.getMiniInfo(task.getPullRequestId())
final PullRequestMini pullRequestMini = mergeRequestsService.getMiniInfo(task.getPullRequestId())
.orElseThrow(() -> new NotFoundException("Автор ПР не найден"));
task.setResponsible(pullRequestMini.getAuthorLogin());
task.setUrl(generateUrl(task.getId(), pullRequestMini.getUrl()));
@ -153,12 +153,13 @@ public class CommentAndTaskParser {
return MessageFormat.format("{0}/overview?commentId={1}", pullRequestUrl, Long.toString(id));
}
private String getCommentUrl(long commentId, PullRequest pullRequest) {
return gitlabProperty.getUrlPullRequestComment()
.replace("{projectKey}", pullRequest.getProjectKey())
.replace("{repositorySlug}", pullRequest.getRepositorySlug())
.replace("{pullRequestId}", pullRequest.getBitbucketId().toString())
.replace("{commentId}", String.valueOf(commentId));
private String getCommentUrl(long commentId, MergeRequest mergeRequest) {
// return gitlabProperty.getUrlPullRequestComment()
// .replace("{projectKey}", mergeRequest.getProjectKey())
// .replace("{repositorySlug}", mergeRequest.getRepositorySlug())
// .replace("{pullRequestId}", mergeRequest.getBitbucketId().toString())
// .replace("{commentId}", String.valueOf(commentId));
return null;
}
public void scanOldComment() {

View File

@ -2,11 +2,10 @@ package org.sadtech.bot.gitlab.app.service.parser;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.sadtech.bot.gitlab.context.service.PullRequestsService;
import org.sadtech.bot.gitlab.context.domain.MergeRequestState;
import org.sadtech.bot.gitlab.context.service.MergeRequestsService;
import org.sadtech.bot.gitlab.core.config.properties.GitlabProperty;
import org.sadtech.bot.gitlab.sdk.domain.MergeRequestJson;
import org.sadtech.bot.vsc.context.domain.PullRequestStatus;
import org.sadtech.bot.vsc.context.service.PullRequestParser;
import org.sadtech.haiti.utils.network.HttpHeader;
import org.sadtech.haiti.utils.network.HttpParse;
import org.springframework.core.convert.ConversionService;
@ -23,20 +22,18 @@ import static org.sadtech.haiti.utils.network.HttpParse.BEARER;
@Slf4j
//@Service
@RequiredArgsConstructor
public class PullRequestBitbucketParser implements PullRequestParser {
public class MergeRequestParserImpl {
private static final Set<PullRequestStatus> OLD_STATUSES = Stream.of(PullRequestStatus.MERGED, PullRequestStatus.OPEN, PullRequestStatus.DECLINED).collect(Collectors.toSet());
private static final Set<MergeRequestState> OLD_STATUSES = Stream.of(MergeRequestState.MERGED, MergeRequestState.OPENED, MergeRequestState.CLOSED).collect(Collectors.toSet());
private final GitlabProperty gitlabProperty;
private final PullRequestsService pullRequestsService;
private final MergeRequestsService mergeRequestsService;
private final ConversionService conversionService;
@Override
public void parsingOldPullRequest() {
// processingOldPullRequests(gitlabProperty.getUrlPullRequestOpen(), gitlabProperty.getUrlPullRequestClose());
}
@Override
public void parsingNewPullRequest() {
final List<MergeRequestJson> mergeRequestJsons = HttpParse.request(gitlabProperty.getUrlPullRequestOpen())
.header(HttpHeader.of(AUTHORIZATION, BEARER + gitlabProperty.getToken()))

View File

@ -33,7 +33,7 @@ gitlab-bot:
username: ${GITLAB_USERNAME}
full-name: ${GITLAB_FULLNAME}
url-project: ${GITLAB_URL}/api/v4/projects
url-pull-request-open: ${GITLAB_URL}/api/v4/projects/18/merge_requests?state=opened
url-pull-request-open: ${GITLAB_URL}/api/v4/projects/{0}/merge_requests?state=opened
url-pull-request-close: ${GITLAB_URL}
url-pull-request-comment: ${GITLAB_URL}
url-pull-request: ${GITLAB_URL}

View File

@ -17,4 +17,56 @@
</createTable>
</changeSet>
<changeSet id="2020-01-14-create-table-person" author="uPagge">
<createTable tableName="person">
<column name="id">
<constraints nullable="false" primaryKey="true"/>
</column>
<column name="username" type="varchar(100)">
<constraints nullable="false" unique="true"/>
</column>
<column name="name" type="varchar(100)"/>
<column name="web_url" type="varchar(300)">
<constraints nullable="false"/>
</column>
</createTable>
</changeSet>
<changeSet id="2020-01-14-create-merge-request" author="uPagge">
<createTable tableName="merge_request">
<column name="id">
<constraints nullable="false" primaryKey="true"/>
</column>
<column name="two_id">
<constraints nullable="false" primaryKey="true"/>
</column>
<column name="project_id" type="int">
<constraints nullable="false" foreignKeyName="merge_request_project_id" references="project(id)"/>
</column>
<column name="title" type="varchar(200)">
<constraints nullable="false"/>
</column>
<column name="description" type="varchar(2000)"/>
<column name="state" type="varchar(10)">
<constraints nullable="false"/>
</column>
<column name="created_date" type="datetime">
<constraints nullable="false"/>
</column>
<column name="updated_date" type="datetime">
<constraints nullable="false"/>
</column>
<column name="web_url" type="varchar(300)">
<constraints nullable="false"/>
</column>
<column name="conflict" type="boolean">
<constraints nullable="false"/>
</column>
<column name="author_id" type="int">
<constraints nullable="false" foreignKeyName="merge_request_author_id_person_id"
references="person(id)"/>
</column>
</createTable>
</changeSet>
</databaseChangeLog>

View File

@ -33,11 +33,6 @@
<artifactId>javax.persistence-api</artifactId>
</dependency>
<dependency>
<groupId>org.sadtech.bot.vcs</groupId>
<artifactId>vcs-bot-context</artifactId>
</dependency>
<dependency>
<groupId>org.hibernate.orm</groupId>
<artifactId>hibernate-jpamodelgen</artifactId>

View File

@ -3,7 +3,6 @@ package org.sadtech.bot.gitlab.context.domain;
import lombok.AllArgsConstructor;
import lombok.Getter;
import lombok.Setter;
import org.sadtech.bot.vsc.context.domain.PullRequestStatus;
@Setter
@Getter
@ -11,6 +10,6 @@ import org.sadtech.bot.vsc.context.domain.PullRequestStatus;
public class IdAndStatusPr {
private Long id;
private PullRequestStatus status;
private MergeRequestState status;
}

View File

@ -0,0 +1,12 @@
package org.sadtech.bot.gitlab.context.domain;
/**
* // TODO: 14.01.2021 Добавить описание.
*
* @author upagge 14.01.2021
*/
public enum MergeRequestState {
OPENED, CLOSED, LOCKED, MERGED
}

View File

@ -0,0 +1,70 @@
package org.sadtech.bot.gitlab.context.domain.entity;
import lombok.EqualsAndHashCode;
import lombok.Getter;
import lombok.Setter;
import org.sadtech.bot.gitlab.context.domain.MergeRequestState;
import org.sadtech.haiti.context.domain.BasicEntity;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.EnumType;
import javax.persistence.Enumerated;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.ManyToOne;
import javax.persistence.Table;
import java.time.LocalDateTime;
/**
* Сущность ПуллРеквест.
*
* @author upagge [31.01.2020]
*/
@Getter
@Setter
@Entity
@Table(name = "merge_request")
@EqualsAndHashCode(onlyExplicitlyIncluded = true)
public class MergeRequest implements BasicEntity<Long> {
@Id
@Column(name = "id")
@EqualsAndHashCode.Include
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
@Column(name = "two_id")
private Long twoId;
@Column(name = "project_id")
private Long projectId;
@Column(name = "title")
private String title;
@Column(name = "description")
private String description;
@Enumerated(EnumType.STRING)
@Column(name = "state")
private MergeRequestState state;
@Column(name = "created_date")
private LocalDateTime createdDate;
@Column(name = "updated_date")
private LocalDateTime updatedDate;
@ManyToOne(optional = false)
@Column(name = "author_id")
private Person author;
@Column(name = "web_url")
private String webUrl;
@Column(name = "conflict")
private String conflicts;
}

View File

@ -0,0 +1,22 @@
package org.sadtech.bot.gitlab.context.domain.entity;
import lombok.Getter;
import lombok.Setter;
import javax.persistence.Entity;
/**
* // TODO: 14.01.2021 Добавить описание.
*
* @author upagge 14.01.2021
*/
@Entity
@Getter
@Setter
public class Person {
private Long id;
private String name;
}

View File

@ -1,139 +0,0 @@
package org.sadtech.bot.gitlab.context.domain.entity;
import lombok.EqualsAndHashCode;
import lombok.Getter;
import lombok.Setter;
import org.sadtech.bot.vsc.context.domain.PullRequestStatus;
import org.sadtech.haiti.context.domain.BasicEntity;
import javax.persistence.CascadeType;
import javax.persistence.Column;
import javax.persistence.EnumType;
import javax.persistence.Enumerated;
import javax.persistence.FetchType;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.OneToMany;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;
/**
* Сущность ПуллРеквест.
*
* @author upagge [31.01.2020]
*/
@Getter
@Setter
//@Entity
//@Table(name = "pull_request")
@EqualsAndHashCode(onlyExplicitlyIncluded = true)
public class PullRequest implements BasicEntity<Long> {
@Id
@Column(name = "id")
@EqualsAndHashCode.Include
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
/**
* Идентификатор на стороне битбакета
*/
@Column(name = "bitbucket_id")
private Long bitbucketId;
/**
* Идентификатор репозитория на стороне битбакета
*/
@Column(name = "repository_id")
private Long repositoryId;
/**
* Идентификатор проекта на стороне битбакета
*/
@Column(name = "project_key")
private String projectKey;
/**
* Символьный идентификатор на стороне битбакета
*/
@Column(name = "repository_slug")
private String repositorySlug;
/**
* Описание пулреквеста
*/
@Column(name = "description")
private String description;
/**
* Адрес ПР
*/
@Column(name = "url")
private String url;
/**
* Название ПР
*/
@Column(name = "title")
private String title;
/**
* Статус ПР
*/
@Enumerated(EnumType.STRING)
@Column(name = "status")
private PullRequestStatus status;
/**
* Дата создания
*/
@Column(name = "create_date")
private LocalDateTime createDate;
/**
* Дата обновления
*/
@Column(name = "update_date")
private LocalDateTime updateDate;
/**
* Флаг показывающий наличие конфликта в ПР
*/
@Column(name = "conflict")
private boolean conflict;
/**
* Версия объекта в битбакет
*/
@Column(name = "bitbucket_version")
private Integer bitbucketVersion;
/**
* Автор ПР
*/
@Column(name = "author_login")
private String authorLogin;
@Column(name = "resolved_task_count")
private Integer resolvedTaskCount;
@Column(name = "comment_count")
private Integer commentCount;
@Column(name = "open_task_count")
private Integer openTaskCount;
/**
* Ревьюверы
*/
@OneToMany(cascade = CascadeType.ALL, fetch = FetchType.EAGER, orphanRemoval = true, mappedBy = "pullRequest")
private List<Reviewer> reviewers = new ArrayList<>();
public void setReviewers(List<Reviewer> reviewers) {
reviewers.forEach(reviewer -> reviewer.setPullRequest(this));
this.reviewers = reviewers;
}
}

View File

@ -3,12 +3,9 @@ package org.sadtech.bot.gitlab.context.domain.entity;
import lombok.EqualsAndHashCode;
import lombok.Getter;
import lombok.Setter;
import org.sadtech.bot.vsc.context.domain.ReviewerStatus;
import javax.persistence.CascadeType;
import javax.persistence.Column;
import javax.persistence.EnumType;
import javax.persistence.Enumerated;
import javax.persistence.FetchType;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
@ -47,9 +44,9 @@ public class Reviewer {
/**
* Статус
*/
@Enumerated(EnumType.STRING)
@Column(name = "status")
private ReviewerStatus status;
// @Enumerated(EnumType.STRING)
// @Column(name = "status")
// private ReviewerStatus status;
@Column(name = "date_change")
private LocalDateTime dateChange;
@ -59,6 +56,6 @@ public class Reviewer {
@ManyToOne(fetch = FetchType.LAZY, cascade = CascadeType.REFRESH, optional = false)
@JoinColumn(name = "pull_request_id")
private PullRequest pullRequest;
private MergeRequest mergeRequest;
}

View File

@ -3,7 +3,7 @@ package org.sadtech.bot.gitlab.context.domain.notify;
import lombok.Builder;
import lombok.Getter;
import org.sadtech.bot.gitlab.context.domain.EntityType;
import org.sadtech.bot.gitlab.context.domain.entity.PullRequest;
import org.sadtech.bot.gitlab.context.domain.entity.MergeRequest;
import org.sadtech.bot.gitlab.context.utils.MessageUtils;
import org.sadtech.bot.gitlab.context.utils.Smile;
import org.sadtech.bot.gitlab.context.utils.UpdateDataComparator;
@ -23,20 +23,20 @@ public class GoodMorningNotify extends Notify {
private static final UpdateDataComparator COMPARATOR = new UpdateDataComparator();
private static final Integer PR_COUNT = 4;
private final List<PullRequest> pullRequestsReviews;
private final List<PullRequest> pullRequestsNeedWork;
private final List<MergeRequest> mergeRequestsReviews;
private final List<MergeRequest> mergeRequestsNeedWork;
private final String personName;
private final String version;
@Builder
protected GoodMorningNotify(
Set<String> recipients,
List<PullRequest> pullRequestsReviews,
List<PullRequest> pullRequestsNeedWork,
List<MergeRequest> mergeRequestsReviews,
List<MergeRequest> mergeRequestsNeedWork,
String personName, String version) {
super(EntityType.PERSON, recipients);
this.pullRequestsReviews = pullRequestsReviews;
this.pullRequestsNeedWork = pullRequestsNeedWork;
this.mergeRequestsReviews = mergeRequestsReviews;
this.mergeRequestsNeedWork = mergeRequestsNeedWork;
this.personName = personName;
this.version = version;
}
@ -44,10 +44,10 @@ public class GoodMorningNotify extends Notify {
@Override
public String generateMessage() {
StringBuilder message = new StringBuilder().append(Smile.SUN).append(" *Доброе утро, ").append(personName).append("* ").append(Smile.SUN).append(Smile.TWO_BR);
if (!pullRequestsReviews.isEmpty()) {
message.append("Необходимо проверить ").append(pullRequestsReviews.size()).append(" ПР:").append(Smile.BR);
if (!mergeRequestsReviews.isEmpty()) {
message.append("Необходимо проверить ").append(mergeRequestsReviews.size()).append(" ПР:").append(Smile.BR);
MessageUtils.pullRequestForReview(
pullRequestsReviews.stream()
mergeRequestsReviews.stream()
.limit(3)
.collect(Collectors.toList())
).ifPresent(message::append);
@ -55,12 +55,12 @@ public class GoodMorningNotify extends Notify {
message.append("Поздравляю, у тебя ни одного ПР на проверку!");
}
MessageUtils.pullRequestForNeedWork(
pullRequestsNeedWork.stream()
mergeRequestsNeedWork.stream()
.limit(3)
.collect(Collectors.toList())
).ifPresent(
messageNeedWork -> message.append(Smile.TWO_BR)
.append(Smile.DANGEROUS).append(" Требуется доработать ").append(pullRequestsNeedWork.size()).append(" ПР:").append(Smile.BR)
.append(Smile.DANGEROUS).append(" Требуется доработать ").append(mergeRequestsNeedWork.size()).append(" ПР:").append(Smile.BR)
.append(messageNeedWork)
);
message

View File

@ -1,72 +0,0 @@
package org.sadtech.bot.gitlab.context.domain.notify.pullrequest;
import lombok.Builder;
import lombok.Getter;
import org.sadtech.bot.gitlab.context.domain.util.ReviewerChange;
import org.sadtech.bot.gitlab.context.utils.Smile;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.stream.Collectors;
import static org.sadtech.bot.gitlab.context.domain.util.ReviewerChange.Type.DELETED;
import static org.sadtech.bot.gitlab.context.domain.util.ReviewerChange.Type.NEW;
import static org.sadtech.bot.gitlab.context.domain.util.ReviewerChange.Type.OLD;
@Getter
public class ReviewersPrNotify extends PrNotify {
private final List<ReviewerChange> reviewerChanges;
@Builder
private ReviewersPrNotify(
Set<String> recipients,
String title,
String url,
String projectKey,
String repositorySlug,
List<ReviewerChange> reviewerChanges
) {
super(recipients, projectKey, repositorySlug, title, url);
this.reviewerChanges = reviewerChanges;
}
@Override
public String generateMessage() {
StringBuilder stringBuilder = new StringBuilder();
final Map<ReviewerChange.Type, List<ReviewerChange>> changes = reviewerChanges.stream()
.collect(Collectors.groupingBy(ReviewerChange::getType));
if (changes.containsKey(OLD)) {
changes.get(OLD).forEach(
change -> stringBuilder
.append(Smile.AUTHOR).append(change.getName()).append(": ")
.append(change.getOldStatus().getValue()).append(" ").append(Smile.ARROW).append(" ")
.append(change.getStatus().getValue())
.append(Smile.BR)
);
stringBuilder.append(Smile.BR);
}
if (changes.containsKey(NEW)) {
stringBuilder.append("Новые ревьюверы:").append(Smile.BR);
changes.get(NEW).forEach(
change -> stringBuilder
.append(change.getName()).append(": ").append(change.getStatus().getValue()).append(Smile.BR)
);
stringBuilder.append(Smile.BR);
}
if (changes.containsKey(DELETED)) {
stringBuilder.append("Не выдержали ревью:").append(Smile.BR)
.append(
changes.get(DELETED).stream()
.map(ReviewerChange::getName).collect(Collectors.joining(","))
);
}
final String createMessage = stringBuilder.toString();
return Smile.PEN + " *Изменения ревьюверов PullRequest | " + projectKey + " | " + repositorySlug + "*" +
Smile.HR +
"[" + title + "](" + url + ")" + Smile.HR +
createMessage;
}
}

View File

@ -38,7 +38,7 @@ public class SmartPrNotify extends PrNotify {
"{3}[{1}]({2})" +
"{3}" +
"{4} изменил свое решение на {5}\n\n",
Smile.SMART, title, url, Smile.HR, reviewerTriggered.getPersonLogin(), reviewerTriggered.getStatus().getValue(),
Smile.SMART, title, url, Smile.HR, reviewerTriggered.getPersonLogin(),
projectKey, repositorySlug
);
}

View File

@ -2,8 +2,8 @@ package org.sadtech.bot.gitlab.context.domain.notify.pullrequest;
import lombok.Builder;
import lombok.Getter;
import org.sadtech.bot.gitlab.context.domain.MergeRequestState;
import org.sadtech.bot.gitlab.context.utils.Smile;
import org.sadtech.bot.vsc.context.domain.PullRequestStatus;
import java.text.MessageFormat;
import java.util.Set;
@ -11,8 +11,8 @@ import java.util.Set;
@Getter
public class StatusPrNotify extends PrNotify {
private final PullRequestStatus oldStatus;
private final PullRequestStatus newStatus;
private final MergeRequestState oldStatus;
private final MergeRequestState newStatus;
@Builder
private StatusPrNotify(
@ -21,8 +21,8 @@ public class StatusPrNotify extends PrNotify {
String url,
String projectKey,
String repositorySlug,
PullRequestStatus oldStatus,
PullRequestStatus newStatus
MergeRequestState oldStatus,
MergeRequestState newStatus
) {
super(recipients, projectKey, repositorySlug, name, url);
this.oldStatus = oldStatus;

View File

@ -1,57 +0,0 @@
package org.sadtech.bot.gitlab.context.domain.util;
import lombok.Getter;
import lombok.NonNull;
import org.sadtech.bot.vsc.context.domain.ReviewerStatus;
/**
* TODO: Добавить описание класса.
*
* @author upagge [07.02.2020]
*/
@Getter
public class ReviewerChange {
private final String name;
private final Type type;
private ReviewerStatus status;
private ReviewerStatus oldStatus;
private ReviewerChange(String name, Type type, ReviewerStatus status) {
this.name = name;
this.type = type;
this.status = status;
}
private ReviewerChange(String name, Type type, ReviewerStatus status, ReviewerStatus oldStatus) {
this.name = name;
this.type = type;
this.status = status;
this.oldStatus = oldStatus;
}
private ReviewerChange(String name, Type type) {
this.name = name;
this.type = type;
}
@NonNull
public static ReviewerChange ofNew(String name, ReviewerStatus reviewerStatus) {
return new ReviewerChange(name, Type.NEW, reviewerStatus);
}
@NonNull
public static ReviewerChange ofOld(String name, ReviewerStatus oldStatus, ReviewerStatus newStatus) {
return new ReviewerChange(name, Type.OLD, newStatus, oldStatus);
}
@NonNull
public static ReviewerChange ofDeleted(String name) {
return new ReviewerChange(name, Type.DELETED);
}
public enum Type {
NEW, DELETED, OLD
}
}

View File

@ -2,24 +2,18 @@ package org.sadtech.bot.gitlab.context.repository;
import lombok.NonNull;
import org.sadtech.bot.gitlab.context.domain.IdAndStatusPr;
import org.sadtech.bot.gitlab.context.domain.entity.PullRequest;
import org.sadtech.bot.gitlab.context.domain.MergeRequestState;
import org.sadtech.bot.gitlab.context.domain.entity.MergeRequest;
import org.sadtech.bot.gitlab.context.domain.entity.PullRequestMini;
import org.sadtech.bot.vsc.context.domain.PullRequestStatus;
import org.sadtech.bot.vsc.context.domain.ReviewerStatus;
import org.sadtech.haiti.context.repository.SimpleManagerRepository;
import org.sadtech.haiti.filter.FilterOperation;
import java.util.List;
import java.util.Optional;
import java.util.Set;
public interface PullRequestsRepository extends SimpleManagerRepository<PullRequest, Long>, FilterOperation<PullRequest> {
public interface PullRequestsRepository extends SimpleManagerRepository<MergeRequest, Long>, FilterOperation<MergeRequest> {
List<PullRequest> findAllByReviewerAndStatuses(String login, ReviewerStatus reviewerStatus, Set<PullRequestStatus> statuses);
List<PullRequest> findAllByAuthorAndReviewerStatus(String login, ReviewerStatus status);
Set<IdAndStatusPr> findAllIdByStatusIn(Set<PullRequestStatus> statuses);
Set<IdAndStatusPr> findAllIdByStatusIn(Set<MergeRequestState> statuses);
Optional<PullRequestMini> findMiniInfoById(@NonNull Long id);

View File

@ -0,0 +1,27 @@
package org.sadtech.bot.gitlab.context.service;
import lombok.NonNull;
import org.sadtech.bot.gitlab.context.domain.IdAndStatusPr;
import org.sadtech.bot.gitlab.context.domain.MergeRequestState;
import org.sadtech.bot.gitlab.context.domain.entity.MergeRequest;
import org.sadtech.bot.gitlab.context.domain.entity.PullRequestMini;
import org.sadtech.bot.gitlab.context.domain.filter.PullRequestFilter;
import org.sadtech.haiti.context.service.SimpleManagerService;
import org.sadtech.haiti.filter.FilterService;
import java.util.Optional;
import java.util.Set;
public interface MergeRequestsService extends SimpleManagerService<MergeRequest, Long>, FilterService<MergeRequest, PullRequestFilter> {
/**
* Получить все идентификаторы вместе со статусами.
*
* @param statuses Статусы ПРов
* @return Объект, содержащий идентификатор и статус ПР
*/
Set<IdAndStatusPr> getAllId(Set<MergeRequestState> statuses);
Optional<PullRequestMini> getMiniInfo(@NonNull Long pullRequestId);
}

View File

@ -1,46 +0,0 @@
package org.sadtech.bot.gitlab.context.service;
import lombok.NonNull;
import org.sadtech.bot.gitlab.context.domain.IdAndStatusPr;
import org.sadtech.bot.gitlab.context.domain.entity.PullRequest;
import org.sadtech.bot.gitlab.context.domain.entity.PullRequestMini;
import org.sadtech.bot.gitlab.context.domain.filter.PullRequestFilter;
import org.sadtech.bot.vsc.context.domain.PullRequestStatus;
import org.sadtech.bot.vsc.context.domain.ReviewerStatus;
import org.sadtech.haiti.context.service.SimpleManagerService;
import org.sadtech.haiti.filter.FilterService;
import java.util.List;
import java.util.Optional;
import java.util.Set;
public interface PullRequestsService extends SimpleManagerService<PullRequest, Long>, FilterService<PullRequest, PullRequestFilter> {
/**
* Получить все пулреквесты ревьювера с определенным статусом.
*
* @param login Логин ревьювера
* @param reviewerStatus Статус ревьювера в ПР
* @param pullRequestStatuses Статус ПР
*/
List<PullRequest> getAllByReviewerAndStatuses(@NonNull String login, @NonNull ReviewerStatus reviewerStatus, @NonNull Set<PullRequestStatus> pullRequestStatuses);
/**
* Получить все ПР с определенным статусом, который есть хотя бы у одного ревьювера.
*
* @param login Автор ПР.
* @param status Статус ревьювера.
*/
List<PullRequest> getAllByAuthorAndReviewerStatus(@NonNull String login, @NonNull ReviewerStatus status);
/**
* Получить все идентификаторы вместе со статусами.
*
* @param statuses Статусы ПРов
* @return Объект, содержащий идентификатор и статус ПР
*/
Set<IdAndStatusPr> getAllId(Set<PullRequestStatus> statuses);
Optional<PullRequestMini> getMiniInfo(@NonNull Long pullRequestId);
}

View File

@ -3,7 +3,7 @@ package org.sadtech.bot.gitlab.context.utils;
import lombok.AccessLevel;
import lombok.NoArgsConstructor;
import lombok.NonNull;
import org.sadtech.bot.gitlab.context.domain.entity.PullRequest;
import org.sadtech.bot.gitlab.context.domain.entity.MergeRequest;
import java.util.List;
import java.util.Optional;
@ -19,10 +19,10 @@ public final class MessageUtils {
private static final UpdateDataComparator COMPARATOR = new UpdateDataComparator();
public static Optional<String> pullRequestForReview(@NonNull List<PullRequest> pullRequestsReviews) {
if (!pullRequestsReviews.isEmpty()) {
public static Optional<String> pullRequestForReview(@NonNull List<MergeRequest> mergeRequestsReviews) {
if (!mergeRequestsReviews.isEmpty()) {
return Optional.of(
pullRequestsReviews.stream()
mergeRequestsReviews.stream()
.sorted(COMPARATOR)
.map(MessageUtils::generateStringItemPullRequestReview)
.collect(Collectors.joining("\n"))
@ -31,10 +31,10 @@ public final class MessageUtils {
return Optional.empty();
}
public static Optional<String> pullRequestForNeedWork(@NonNull List<PullRequest> pullRequestNeedWork) {
if (!pullRequestNeedWork.isEmpty()) {
public static Optional<String> pullRequestForNeedWork(@NonNull List<MergeRequest> mergeRequestNeedWork) {
if (!mergeRequestNeedWork.isEmpty()) {
return Optional.of(
pullRequestNeedWork.stream()
mergeRequestNeedWork.stream()
.map(MessageUtils::generateStringItemPullRequestNeedWork)
.collect(Collectors.joining("\n"))
);
@ -42,13 +42,13 @@ public final class MessageUtils {
return Optional.empty();
}
private static String generateStringItemPullRequestNeedWork(PullRequest pullRequest) {
return "-- " + link(pullRequest.getTitle(), pullRequest.getUrl());
private static String generateStringItemPullRequestNeedWork(MergeRequest mergeRequest) {
return "-- " + link(mergeRequest.getTitle(), mergeRequest.getWebUrl());
}
private static String generateStringItemPullRequestReview(PullRequest pullRequest) {
return Smile.statusPr(pullRequest.getUpdateDate()) + " " +
link(pullRequest.getTitle(), pullRequest.getUrl());
private static String generateStringItemPullRequestReview(MergeRequest mergeRequest) {
return Smile.statusPr(mergeRequest.getUpdatedDate()) + " " +
link(mergeRequest.getTitle(), mergeRequest.getWebUrl());
}
@NonNull

View File

@ -1,14 +1,15 @@
package org.sadtech.bot.gitlab.context.utils;
import org.sadtech.bot.gitlab.context.domain.entity.PullRequest;
import org.sadtech.bot.gitlab.context.domain.entity.MergeRequest;
import java.util.Comparator;
public class UpdateDataComparator implements Comparator<PullRequest> {
public class UpdateDataComparator implements Comparator<MergeRequest> {
@Override
public int compare(PullRequest pullRequest, PullRequest t1) {
return pullRequest.getUpdateDate().compareTo(t1.getUpdateDate());
public int compare(MergeRequest mergeRequest, MergeRequest t1) {
// return mergeRequest.getUpdateDate().compareTo(t1.getUpdateDate());
return 0;
}
}

View File

@ -0,0 +1,290 @@
package org.sadtech.bot.gitlab.core.service.impl;
import lombok.NonNull;
import org.sadtech.bot.gitlab.context.domain.IdAndStatusPr;
import org.sadtech.bot.gitlab.context.domain.MergeRequestState;
import org.sadtech.bot.gitlab.context.domain.entity.MergeRequest;
import org.sadtech.bot.gitlab.context.domain.entity.PullRequestMini;
import org.sadtech.bot.gitlab.context.domain.entity.Reviewer;
import org.sadtech.bot.gitlab.context.domain.filter.PullRequestFilter;
import org.sadtech.bot.gitlab.context.domain.notify.pullrequest.NewPrNotify;
import org.sadtech.bot.gitlab.context.repository.PullRequestsRepository;
import org.sadtech.bot.gitlab.context.service.MergeRequestsService;
import org.sadtech.bot.gitlab.context.service.NotifyService;
import org.sadtech.haiti.context.domain.ExistsContainer;
import org.sadtech.haiti.context.page.Pagination;
import org.sadtech.haiti.context.page.Sheet;
import org.sadtech.haiti.core.service.AbstractSimpleManagerService;
import org.sadtech.haiti.core.util.Assert;
import org.sadtech.haiti.filter.FilterService;
import org.springframework.beans.factory.annotation.Qualifier;
import java.time.LocalDateTime;
import java.util.Collection;
import java.util.Optional;
import java.util.Set;
//@Service
public class MergeRequestsServiceImpl extends AbstractSimpleManagerService<MergeRequest, Long> implements MergeRequestsService {
protected final NotifyService notifyService;
protected final PullRequestsRepository pullRequestsRepository;
protected final FilterService<MergeRequest, PullRequestFilter> filterService;
protected MergeRequestsServiceImpl(
PullRequestsRepository pullRequestsRepository,
NotifyService notifyService,
@Qualifier("pullRequestFilterService") FilterService<MergeRequest, PullRequestFilter> pullRequestsFilterService
) {
super(pullRequestsRepository);
this.notifyService = notifyService;
this.pullRequestsRepository = pullRequestsRepository;
this.filterService = pullRequestsFilterService;
}
@Override
public MergeRequest create(@NonNull MergeRequest mergeRequest) {
Assert.isNull(mergeRequest.getId(), "При создании идентификатор должен быть пустым");
final MergeRequest newMergeRequest = pullRequestsRepository.save(mergeRequest);
notifyService.send(
NewPrNotify.builder()
.author(newMergeRequest.getAuthor().getName())
.description(newMergeRequest.getDescription())
.title(newMergeRequest.getTitle())
.url(newMergeRequest.getWebUrl())
.build()
);
return newMergeRequest;
}
@Override
public MergeRequest update(@NonNull MergeRequest mergeRequest) {
final MergeRequest oldMergeRequest = findAndFillId(mergeRequest);
forgottenNotification(oldMergeRequest);
oldMergeRequest.setTitle(mergeRequest.getTitle());
oldMergeRequest.setDescription(mergeRequest.getDescription());
updateReviewers(oldMergeRequest, mergeRequest);
updateBitbucketVersion(oldMergeRequest, mergeRequest);
updateStatus(oldMergeRequest, mergeRequest);
updateConflict(oldMergeRequest, mergeRequest);
return pullRequestsRepository.save(oldMergeRequest);
}
protected void forgottenNotification(MergeRequest mergeRequest) {
// if (LocalDateTime.now().isAfter(mergeRequest.getUpdateDate().plusHours(2L))) {
// final Set<String> smartReviewers = mergeRequest.getReviewers().stream()
// .filter(
// reviewer -> ReviewerStatus.NEEDS_WORK.equals(reviewer.getStatus())
// && LocalDateTime.now().isAfter(reviewer.getDateChange().plusHours(2L))
// && reviewer.getDateSmartNotify() == null
// )
// .peek(reviewer -> reviewer.setDateSmartNotify(LocalDateTime.now()))
// .map(Reviewer::getPersonLogin)
// .collect(Collectors.toSet());
// if (!smartReviewers.isEmpty()) {
// notifyService.send(
// ForgottenSmartPrNotify.builder()
// .projectKey(mergeRequest.getProjectKey())
// .repositorySlug(mergeRequest.getRepositorySlug())
// .recipients(smartReviewers)
// .title(mergeRequest.getTitle())
// .url(mergeRequest.getUrl())
// .build()
// );
// }
// }
}
protected void updateBitbucketVersion(MergeRequest oldMergeRequest, MergeRequest mergeRequest) {
// if (
// !oldMergeRequest.getBitbucketVersion().equals(mergeRequest.getBitbucketVersion())
// ) {
// oldMergeRequest.setBitbucketVersion(mergeRequest.getBitbucketVersion());
// if (PullRequestStatus.OPEN.equals(mergeRequest.getStatus())) {
// notifyService.send(
// UpdatePrNotify.builder()
// .author(oldMergeRequest.getAuthorLogin())
// .name(mergeRequest.getTitle())
// .recipients(
// mergeRequest.getReviewers().stream()
// .map(Reviewer::getPersonLogin)
// .collect(Collectors.toSet())
// )
// .url(oldMergeRequest.getUrl())
// .projectKey(oldMergeRequest.getProjectKey())
// .repositorySlug(oldMergeRequest.getRepositorySlug())
// .build()
// );
// }
// }
}
protected void updateConflict(MergeRequest oldMergeRequest, MergeRequest mergeRequest) {
// if (!oldMergeRequest.isConflict() && mergeRequest.isConflict()) {
// notifyService.send(
// ConflictPrNotify.builder()
// .name(mergeRequest.getTitle())
// .url(mergeRequest.getUrl())
// .projectKey(mergeRequest.getProjectKey())
// .repositorySlug(mergeRequest.getRepositorySlug())
// .recipients(Collections.singleton(mergeRequest.getAuthorLogin()))
// .build()
// );
// }
// oldMergeRequest.setConflict(mergeRequest.isConflict());
}
protected void updateStatus(MergeRequest oldMergeRequest, MergeRequest newMergeRequest) {
// final PullRequestStatus oldStatus = oldMergeRequest.getStatus();
// final PullRequestStatus newStatus = newMergeRequest.getStatus();
// if (!oldStatus.equals(newStatus)) {
// notifyService.send(
// StatusPrNotify.builder()
// .name(newMergeRequest.getTitle())
// .url(oldMergeRequest.getUrl())
// .projectKey(oldMergeRequest.getProjectKey())
// .repositorySlug(oldMergeRequest.getRepositorySlug())
// .newStatus(newStatus)
// .oldStatus(oldStatus)
// .recipients(Collections.singleton(oldMergeRequest.getAuthorLogin()))
// .build()
// );
// oldMergeRequest.setStatus(newStatus);
// }
}
protected void updateReviewers(MergeRequest oldMergeRequest, MergeRequest newMergeRequest) {
// final Map<String, Reviewer> oldReviewers = oldMergeRequest.getReviewers().stream()
// .collect(Collectors.toMap(Reviewer::getPersonLogin, reviewer -> reviewer));
// final Map<String, Reviewer> newReviewers = newMergeRequest.getReviewers().stream()
// .collect(Collectors.toMap(Reviewer::getPersonLogin, reviewer -> reviewer));
// final List<ReviewerChange> reviewerChanges = new ArrayList<>();
// for (Reviewer newReviewer : newReviewers.values()) {
// if (oldReviewers.containsKey(newReviewer.getPersonLogin())) {
// final Reviewer oldReviewer = oldReviewers.get(newReviewer.getPersonLogin());
// final ReviewerStatus oldStatus = oldReviewer.getStatus();
// final ReviewerStatus newStatus = newReviewer.getStatus();
// if (!oldStatus.equals(newStatus)) {
// reviewerChanges.add(ReviewerChange.ofOld(oldReviewer.getPersonLogin(), oldStatus, newStatus));
// oldReviewer.setStatus(newStatus);
// oldReviewer.setDateChange(LocalDateTime.now());
// smartNotifyAfterReviewerDecision(newReviewer, oldMergeRequest);
// }
// } else {
// reviewerChanges.add(ReviewerChange.ofNew(newReviewer.getPersonLogin(), newReviewer.getStatus()));
// newReviewer.setMergeRequest(oldMergeRequest);
// newReviewer.setDateChange(LocalDateTime.now());
// oldMergeRequest.getReviewers().add(newReviewer);
// }
// }
// final Set<String> oldIds = oldReviewers.keySet();
// oldIds.removeAll(newReviewers.keySet());
// reviewerChanges.addAll(
// oldReviewers.entrySet().stream()
// .filter(e -> oldIds.contains(e.getKey()))
// .map(e -> ReviewerChange.ofDeleted(e.getValue().getPersonLogin()))
// .collect(Collectors.toList())
// );
// oldMergeRequest.getReviewers()
// .removeIf(reviewer -> oldIds.contains(reviewer.getPersonLogin()));
// if (!reviewerChanges.isEmpty()) {
// notifyService.send(
// ReviewersPrNotify.builder()
// .title(newMergeRequest.getTitle())
// .url(newMergeRequest.getUrl())
// .projectKey(newMergeRequest.getProjectKey())
// .repositorySlug(newMergeRequest.getRepositorySlug())
// .recipients(Collections.singleton(newMergeRequest.getAuthorLogin()))
// .reviewerChanges(reviewerChanges)
// .build()
// );
// }
}
/**
* Умное уведомление ревьюверов, после того, как кто-то изменил свое решение.
*/
protected void smartNotifyAfterReviewerDecision(Reviewer newReviewer, MergeRequest oldMergeRequest) {
// final ReviewerStatus newStatus = newReviewer.getStatus();
// if (!ReviewerStatus.NEEDS_WORK.equals(newStatus) && enoughTimHasPassedSinceUpdatePr(oldMergeRequest.getUpdateDate())) {
// final List<Reviewer> smartReviewers = oldMergeRequest.getReviewers().stream()
// .filter(reviewer -> LocalDateTime.now().isAfter(reviewer.getDateChange().plusHours(2L)))
// .collect(Collectors.toList());
// if (!smartReviewers.isEmpty()) {
// notifyService.send(
// SmartPrNotify.builder()
// .reviewerTriggered(newReviewer)
// .title(oldMergeRequest.getTitle())
// .url(oldMergeRequest.getUrl())
// .projectKey(oldMergeRequest.getProjectKey())
// .repositorySlug(oldMergeRequest.getRepositorySlug())
// .recipients(
// smartReviewers.stream()
// .map(Reviewer::getPersonLogin)
// .collect(Collectors.toSet())
// )
// .build()
// );
// }
// }
}
protected boolean enoughTimHasPassedSinceUpdatePr(LocalDateTime updateDate) {
return LocalDateTime.now().isAfter(updateDate.plusHours(4L));
}
@Override
public Set<IdAndStatusPr> getAllId(Set<MergeRequestState> statuses) {
return null;
}
@Override
public Optional<PullRequestMini> getMiniInfo(@NonNull Long pullRequestId) {
return pullRequestsRepository.findMiniInfoById(pullRequestId);
}
@Override
public Sheet<MergeRequest> getAll(@NonNull PullRequestFilter filter, Pagination pagination) {
return filterService.getAll(filter, pagination);
}
@Override
public Optional<MergeRequest> getFirst(@NonNull PullRequestFilter pullRequestFilter) {
return filterService.getFirst(pullRequestFilter);
}
@Override
public boolean exists(@NonNull PullRequestFilter filter) {
return filterService.exists(filter);
}
@Override
public long count(@NonNull PullRequestFilter pullRequestFilter) {
return filterService.count(pullRequestFilter);
}
protected MergeRequest findAndFillId(@NonNull MergeRequest mergeRequest) {
// return pullRequestsRepository.findFirst(
// CriteriaFilter.create().and(
// CriteriaQuery.create()
// .matchPhrase("hyita", mergeRequest.getBitbucketId())
// .matchPhrase("hyita", mergeRequest.getRepositoryId())
// )
// ).orElseThrow(() -> new UpdateException("ПР с таким id не существует"));
return null;
}
@Override
public ExistsContainer<MergeRequest, Long> existsById(@NonNull Collection<Long> collection) {
return null;
}
}

View File

@ -1,330 +0,0 @@
package org.sadtech.bot.gitlab.core.service.impl;
import lombok.NonNull;
import org.sadtech.bot.gitlab.context.domain.IdAndStatusPr;
import org.sadtech.bot.gitlab.context.domain.entity.PullRequest;
import org.sadtech.bot.gitlab.context.domain.entity.PullRequestMini;
import org.sadtech.bot.gitlab.context.domain.entity.Reviewer;
import org.sadtech.bot.gitlab.context.domain.filter.PullRequestFilter;
import org.sadtech.bot.gitlab.context.domain.notify.pullrequest.ConflictPrNotify;
import org.sadtech.bot.gitlab.context.domain.notify.pullrequest.ForgottenSmartPrNotify;
import org.sadtech.bot.gitlab.context.domain.notify.pullrequest.NewPrNotify;
import org.sadtech.bot.gitlab.context.domain.notify.pullrequest.ReviewersPrNotify;
import org.sadtech.bot.gitlab.context.domain.notify.pullrequest.SmartPrNotify;
import org.sadtech.bot.gitlab.context.domain.notify.pullrequest.StatusPrNotify;
import org.sadtech.bot.gitlab.context.domain.notify.pullrequest.UpdatePrNotify;
import org.sadtech.bot.gitlab.context.domain.util.ReviewerChange;
import org.sadtech.bot.gitlab.context.exception.UpdateException;
import org.sadtech.bot.gitlab.context.repository.PullRequestsRepository;
import org.sadtech.bot.gitlab.context.service.NotifyService;
import org.sadtech.bot.gitlab.context.service.PullRequestsService;
import org.sadtech.bot.vsc.context.domain.PullRequestStatus;
import org.sadtech.bot.vsc.context.domain.ReviewerStatus;
import org.sadtech.haiti.context.domain.ExistsContainer;
import org.sadtech.haiti.context.page.Pagination;
import org.sadtech.haiti.context.page.Sheet;
import org.sadtech.haiti.core.service.AbstractSimpleManagerService;
import org.sadtech.haiti.core.util.Assert;
import org.sadtech.haiti.filter.FilterService;
import org.sadtech.haiti.filter.criteria.CriteriaFilter;
import org.sadtech.haiti.filter.criteria.CriteriaQuery;
import org.springframework.beans.factory.annotation.Qualifier;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import java.util.Set;
import java.util.stream.Collectors;
//@Service
public class PullRequestsServiceImpl extends AbstractSimpleManagerService<PullRequest, Long> implements PullRequestsService {
protected final NotifyService notifyService;
protected final PullRequestsRepository pullRequestsRepository;
protected final FilterService<PullRequest, PullRequestFilter> filterService;
protected PullRequestsServiceImpl(
PullRequestsRepository pullRequestsRepository,
NotifyService notifyService,
@Qualifier("pullRequestFilterService") FilterService<PullRequest, PullRequestFilter> pullRequestsFilterService
) {
super(pullRequestsRepository);
this.notifyService = notifyService;
this.pullRequestsRepository = pullRequestsRepository;
this.filterService = pullRequestsFilterService;
}
@Override
public PullRequest create(@NonNull PullRequest pullRequest) {
Assert.isNull(pullRequest.getId(), "При создании идентификатор должен быть пустым");
pullRequest.getReviewers().forEach(
reviewer -> reviewer.setDateChange(LocalDateTime.now())
);
final PullRequest newPullRequest = pullRequestsRepository.save(pullRequest);
notifyService.send(
NewPrNotify.builder()
.author(newPullRequest.getAuthorLogin())
.description(newPullRequest.getDescription())
.title(newPullRequest.getTitle())
.url(newPullRequest.getUrl())
.projectKey(newPullRequest.getProjectKey())
.repositorySlug(newPullRequest.getRepositorySlug())
.recipients(
newPullRequest.getReviewers().stream()
.map(Reviewer::getPersonLogin)
.collect(Collectors.toSet())
)
.build()
);
return newPullRequest;
}
@Override
public PullRequest update(@NonNull PullRequest pullRequest) {
final PullRequest oldPullRequest = findAndFillId(pullRequest);
forgottenNotification(oldPullRequest);
oldPullRequest.setTitle(pullRequest.getTitle());
oldPullRequest.setDescription(pullRequest.getDescription());
oldPullRequest.setOpenTaskCount(pullRequest.getResolvedTaskCount());
oldPullRequest.setCommentCount(pullRequest.getOpenTaskCount());
oldPullRequest.setResolvedTaskCount(pullRequest.getResolvedTaskCount());
updateReviewers(oldPullRequest, pullRequest);
oldPullRequest.setUpdateDate(pullRequest.getUpdateDate());
updateBitbucketVersion(oldPullRequest, pullRequest);
updateStatus(oldPullRequest, pullRequest);
updateConflict(oldPullRequest, pullRequest);
return pullRequestsRepository.save(oldPullRequest);
}
protected void forgottenNotification(PullRequest pullRequest) {
if (LocalDateTime.now().isAfter(pullRequest.getUpdateDate().plusHours(2L))) {
final Set<String> smartReviewers = pullRequest.getReviewers().stream()
.filter(
reviewer -> ReviewerStatus.NEEDS_WORK.equals(reviewer.getStatus())
&& LocalDateTime.now().isAfter(reviewer.getDateChange().plusHours(2L))
&& reviewer.getDateSmartNotify() == null
)
.peek(reviewer -> reviewer.setDateSmartNotify(LocalDateTime.now()))
.map(Reviewer::getPersonLogin)
.collect(Collectors.toSet());
if (!smartReviewers.isEmpty()) {
notifyService.send(
ForgottenSmartPrNotify.builder()
.projectKey(pullRequest.getProjectKey())
.repositorySlug(pullRequest.getRepositorySlug())
.recipients(smartReviewers)
.title(pullRequest.getTitle())
.url(pullRequest.getUrl())
.build()
);
}
}
}
protected void updateBitbucketVersion(PullRequest oldPullRequest, PullRequest pullRequest) {
if (
!oldPullRequest.getBitbucketVersion().equals(pullRequest.getBitbucketVersion())
) {
oldPullRequest.setBitbucketVersion(pullRequest.getBitbucketVersion());
if (PullRequestStatus.OPEN.equals(pullRequest.getStatus())) {
notifyService.send(
UpdatePrNotify.builder()
.author(oldPullRequest.getAuthorLogin())
.name(pullRequest.getTitle())
.recipients(
pullRequest.getReviewers().stream()
.map(Reviewer::getPersonLogin)
.collect(Collectors.toSet())
)
.url(oldPullRequest.getUrl())
.projectKey(oldPullRequest.getProjectKey())
.repositorySlug(oldPullRequest.getRepositorySlug())
.build()
);
}
}
}
protected void updateConflict(PullRequest oldPullRequest, PullRequest pullRequest) {
if (!oldPullRequest.isConflict() && pullRequest.isConflict()) {
notifyService.send(
ConflictPrNotify.builder()
.name(pullRequest.getTitle())
.url(pullRequest.getUrl())
.projectKey(pullRequest.getProjectKey())
.repositorySlug(pullRequest.getRepositorySlug())
.recipients(Collections.singleton(pullRequest.getAuthorLogin()))
.build()
);
}
oldPullRequest.setConflict(pullRequest.isConflict());
}
protected void updateStatus(PullRequest oldPullRequest, PullRequest newPullRequest) {
final PullRequestStatus oldStatus = oldPullRequest.getStatus();
final PullRequestStatus newStatus = newPullRequest.getStatus();
if (!oldStatus.equals(newStatus)) {
notifyService.send(
StatusPrNotify.builder()
.name(newPullRequest.getTitle())
.url(oldPullRequest.getUrl())
.projectKey(oldPullRequest.getProjectKey())
.repositorySlug(oldPullRequest.getRepositorySlug())
.newStatus(newStatus)
.oldStatus(oldStatus)
.recipients(Collections.singleton(oldPullRequest.getAuthorLogin()))
.build()
);
oldPullRequest.setStatus(newStatus);
}
}
protected void updateReviewers(PullRequest oldPullRequest, PullRequest newPullRequest) {
final Map<String, Reviewer> oldReviewers = oldPullRequest.getReviewers().stream()
.collect(Collectors.toMap(Reviewer::getPersonLogin, reviewer -> reviewer));
final Map<String, Reviewer> newReviewers = newPullRequest.getReviewers().stream()
.collect(Collectors.toMap(Reviewer::getPersonLogin, reviewer -> reviewer));
final List<ReviewerChange> reviewerChanges = new ArrayList<>();
for (Reviewer newReviewer : newReviewers.values()) {
if (oldReviewers.containsKey(newReviewer.getPersonLogin())) {
final Reviewer oldReviewer = oldReviewers.get(newReviewer.getPersonLogin());
final ReviewerStatus oldStatus = oldReviewer.getStatus();
final ReviewerStatus newStatus = newReviewer.getStatus();
if (!oldStatus.equals(newStatus)) {
reviewerChanges.add(ReviewerChange.ofOld(oldReviewer.getPersonLogin(), oldStatus, newStatus));
oldReviewer.setStatus(newStatus);
oldReviewer.setDateChange(LocalDateTime.now());
smartNotifyAfterReviewerDecision(newReviewer, oldPullRequest);
}
} else {
reviewerChanges.add(ReviewerChange.ofNew(newReviewer.getPersonLogin(), newReviewer.getStatus()));
newReviewer.setPullRequest(oldPullRequest);
newReviewer.setDateChange(LocalDateTime.now());
oldPullRequest.getReviewers().add(newReviewer);
}
}
final Set<String> oldIds = oldReviewers.keySet();
oldIds.removeAll(newReviewers.keySet());
reviewerChanges.addAll(
oldReviewers.entrySet().stream()
.filter(e -> oldIds.contains(e.getKey()))
.map(e -> ReviewerChange.ofDeleted(e.getValue().getPersonLogin()))
.collect(Collectors.toList())
);
oldPullRequest.getReviewers()
.removeIf(reviewer -> oldIds.contains(reviewer.getPersonLogin()));
if (!reviewerChanges.isEmpty()) {
notifyService.send(
ReviewersPrNotify.builder()
.title(newPullRequest.getTitle())
.url(newPullRequest.getUrl())
.projectKey(newPullRequest.getProjectKey())
.repositorySlug(newPullRequest.getRepositorySlug())
.recipients(Collections.singleton(newPullRequest.getAuthorLogin()))
.reviewerChanges(reviewerChanges)
.build()
);
}
}
/**
* Умное уведомление ревьюверов, после того, как кто-то изменил свое решение.
*/
protected void smartNotifyAfterReviewerDecision(Reviewer newReviewer, PullRequest oldPullRequest) {
final ReviewerStatus newStatus = newReviewer.getStatus();
if (!ReviewerStatus.NEEDS_WORK.equals(newStatus) && enoughTimHasPassedSinceUpdatePr(oldPullRequest.getUpdateDate())) {
final List<Reviewer> smartReviewers = oldPullRequest.getReviewers().stream()
.filter(reviewer -> LocalDateTime.now().isAfter(reviewer.getDateChange().plusHours(2L)))
.collect(Collectors.toList());
if (!smartReviewers.isEmpty()) {
notifyService.send(
SmartPrNotify.builder()
.reviewerTriggered(newReviewer)
.title(oldPullRequest.getTitle())
.url(oldPullRequest.getUrl())
.projectKey(oldPullRequest.getProjectKey())
.repositorySlug(oldPullRequest.getRepositorySlug())
.recipients(
smartReviewers.stream()
.map(Reviewer::getPersonLogin)
.collect(Collectors.toSet())
)
.build()
);
}
}
}
protected boolean enoughTimHasPassedSinceUpdatePr(LocalDateTime updateDate) {
return LocalDateTime.now().isAfter(updateDate.plusHours(4L));
}
@NonNull
@Override
public List<PullRequest> getAllByReviewerAndStatuses(String login, ReviewerStatus reviewerStatus, Set<PullRequestStatus> statuses) {
return pullRequestsRepository.findAllByReviewerAndStatuses(login, reviewerStatus, statuses);
}
@Override
public List<PullRequest> getAllByAuthorAndReviewerStatus(@NonNull String login, @NonNull ReviewerStatus status) {
return pullRequestsRepository.findAllByAuthorAndReviewerStatus(login, status);
}
@Override
public Set<IdAndStatusPr> getAllId(Set<PullRequestStatus> statuses) {
return pullRequestsRepository.findAllIdByStatusIn(statuses);
}
@Override
public Optional<PullRequestMini> getMiniInfo(@NonNull Long pullRequestId) {
return pullRequestsRepository.findMiniInfoById(pullRequestId);
}
@Override
public Sheet<PullRequest> getAll(@NonNull PullRequestFilter filter, Pagination pagination) {
return filterService.getAll(filter, pagination);
}
@Override
public Optional<PullRequest> getFirst(@NonNull PullRequestFilter pullRequestFilter) {
return filterService.getFirst(pullRequestFilter);
}
@Override
public boolean exists(@NonNull PullRequestFilter filter) {
return filterService.exists(filter);
}
@Override
public long count(@NonNull PullRequestFilter pullRequestFilter) {
return filterService.count(pullRequestFilter);
}
protected PullRequest findAndFillId(@NonNull PullRequest pullRequest) {
return pullRequestsRepository.findFirst(
CriteriaFilter.create().and(
CriteriaQuery.create()
.matchPhrase("hyita", pullRequest.getBitbucketId())
.matchPhrase("hyita", pullRequest.getRepositoryId())
)
).orElseThrow(() -> new UpdateException("ПР с таким id не существует"));
}
@Override
public ExistsContainer<PullRequest, Long> existsById(@NonNull Collection<Long> collection) {
return null;
}
}

View File

@ -4,7 +4,7 @@ import lombok.NonNull;
import org.sadtech.bot.gitlab.context.domain.Answer;
import org.sadtech.bot.gitlab.context.domain.TaskStatus;
import org.sadtech.bot.gitlab.context.domain.entity.Comment;
import org.sadtech.bot.gitlab.context.domain.entity.PullRequest;
import org.sadtech.bot.gitlab.context.domain.entity.MergeRequest;
import org.sadtech.bot.gitlab.context.domain.entity.Task;
import org.sadtech.bot.gitlab.context.domain.notify.comment.AnswerCommentNotify;
import org.sadtech.bot.gitlab.context.domain.notify.comment.CommentNotify;
@ -13,8 +13,8 @@ import org.sadtech.bot.gitlab.context.domain.notify.task.TaskNewNotify;
import org.sadtech.bot.gitlab.context.exception.NotFoundException;
import org.sadtech.bot.gitlab.context.repository.TaskRepository;
import org.sadtech.bot.gitlab.context.service.CommentService;
import org.sadtech.bot.gitlab.context.service.MergeRequestsService;
import org.sadtech.bot.gitlab.context.service.NotifyService;
import org.sadtech.bot.gitlab.context.service.PullRequestsService;
import org.sadtech.bot.gitlab.context.service.TaskService;
import org.sadtech.haiti.context.domain.ExistsContainer;
import org.sadtech.haiti.core.service.AbstractSimpleManagerService;
@ -38,7 +38,7 @@ public class TaskServiceImpl extends AbstractSimpleManagerService<Task, Long> im
private final TaskRepository taskRepository;
private final PullRequestsService pullRequestsService;
private final MergeRequestsService mergeRequestsService;
private final NotifyService notifyService;
private final CommentService commentService;
@ -46,14 +46,14 @@ public class TaskServiceImpl extends AbstractSimpleManagerService<Task, Long> im
public TaskServiceImpl(
TaskRepository taskRepository,
PullRequestsService pullRequestsService,
MergeRequestsService mergeRequestsService,
NotifyService notifyService,
CommentService commentService,
ConversionService conversionService
) {
super(taskRepository);
this.taskRepository = taskRepository;
this.pullRequestsService = pullRequestsService;
this.mergeRequestsService = mergeRequestsService;
this.notifyService = notifyService;
this.commentService = commentService;
this.conversionService = conversionService;
@ -168,7 +168,7 @@ public class TaskServiceImpl extends AbstractSimpleManagerService<Task, Long> im
}
private void notifyNewTask(Task task) {
final PullRequest pullRequest = pullRequestsService.getById(task.getPullRequestId())
final MergeRequest mergeRequest = mergeRequestsService.getById(task.getPullRequestId())
.orElseThrow(() -> new NotFoundException("ПР не найден"));
notifyService.send(
@ -176,7 +176,7 @@ public class TaskServiceImpl extends AbstractSimpleManagerService<Task, Long> im
.authorName(task.getAuthor())
.messageTask(task.getDescription())
.url(task.getUrl())
.recipients(Collections.singleton(pullRequest.getAuthorLogin()))
// .recipients(Collections.singleton(mergeRequest.getAuthor().getId()))
.build()
);
}

View File

@ -1,7 +1,7 @@
package org.sadtech.bot.gitlab.core.service.impl.filter;
import lombok.NonNull;
import org.sadtech.bot.gitlab.context.domain.entity.PullRequest;
import org.sadtech.bot.gitlab.context.domain.entity.MergeRequest;
import org.sadtech.bot.gitlab.context.domain.filter.PullRequestFilter;
import org.sadtech.bot.gitlab.context.repository.PullRequestsRepository;
import org.sadtech.haiti.core.service.AbstractFilterService;
@ -11,7 +11,7 @@ import org.sadtech.haiti.filter.criteria.CriteriaFilter;
import org.sadtech.haiti.filter.criteria.CriteriaQuery;
//@Service
public class PullRequestFilterService extends AbstractFilterService<PullRequest, PullRequestFilter> {
public class PullRequestFilterService extends AbstractFilterService<MergeRequest, PullRequestFilter> {
public PullRequestFilterService(PullRequestsRepository filterOperation) {
super(filterOperation);
@ -19,14 +19,14 @@ public class PullRequestFilterService extends AbstractFilterService<PullRequest,
@Override
protected Filter createFilter(@NonNull PullRequestFilter filter) {
return CriteriaFilter.<PullRequest>create()
return CriteriaFilter.<MergeRequest>create()
.and(
convertFilter(filter)
);
}
private FilterQuery convertFilter(@NonNull PullRequestFilter filter) {
return CriteriaQuery.<PullRequest>create()
return CriteriaQuery.<MergeRequest>create()
.matchPhrase("hyita", filter.getBitbucketId())
.matchPhrase("hyita", filter.getBitbucketRepositoryId());
}

View File

@ -2,21 +2,19 @@ package org.sadtech.bot.gitlab.data.impl;
import lombok.NonNull;
import org.sadtech.bot.gitlab.context.domain.IdAndStatusPr;
import org.sadtech.bot.gitlab.context.domain.entity.PullRequest;
import org.sadtech.bot.gitlab.context.domain.MergeRequestState;
import org.sadtech.bot.gitlab.context.domain.entity.MergeRequest;
import org.sadtech.bot.gitlab.context.domain.entity.PullRequestMini;
import org.sadtech.bot.gitlab.context.repository.PullRequestsRepository;
import org.sadtech.bot.gitlab.data.jpa.PullRequestMiniRepositoryJpa;
import org.sadtech.bot.gitlab.data.jpa.PullRequestsRepositoryJpa;
import org.sadtech.bot.vsc.context.domain.PullRequestStatus;
import org.sadtech.bot.vsc.context.domain.ReviewerStatus;
import org.sadtech.haiti.database.repository.manager.FilterManagerRepository;
import java.util.List;
import java.util.Optional;
import java.util.Set;
//@Repository
public class PullRequestsRepositoryImpl extends FilterManagerRepository<PullRequest, Long> implements PullRequestsRepository {
public class PullRequestsRepositoryImpl extends FilterManagerRepository<MergeRequest, Long> implements PullRequestsRepository {
private final PullRequestsRepositoryJpa repositoryJpa;
private final PullRequestMiniRepositoryJpa pullRequestMiniRepositoryJpa;
@ -27,18 +25,9 @@ public class PullRequestsRepositoryImpl extends FilterManagerRepository<PullRequ
this.pullRequestMiniRepositoryJpa = pullRequestMiniRepositoryJpa;
}
@Override
public List<PullRequest> findAllByReviewerAndStatuses(String login, ReviewerStatus reviewerStatus, Set<PullRequestStatus> statuses) {
return repositoryJpa.findAllByReviewerAndStatuses(login, reviewerStatus, statuses);
}
@Override
public List<PullRequest> findAllByAuthorAndReviewerStatus(String login, ReviewerStatus status) {
return repositoryJpa.findAllByAuthorAndReviewerStatus(login, status);
}
@Override
public Set<IdAndStatusPr> findAllIdByStatusIn(Set<PullRequestStatus> statuses) {
public Set<IdAndStatusPr> findAllIdByStatusIn(Set<MergeRequestState> statuses) {
return repositoryJpa.findAllIdByStatusIn(statuses);
}

View File

@ -1,15 +1,13 @@
package org.sadtech.bot.gitlab.data.jpa;
import org.sadtech.bot.gitlab.context.domain.IdAndStatusPr;
import org.sadtech.bot.gitlab.context.domain.entity.PullRequest;
import org.sadtech.bot.vsc.context.domain.PullRequestStatus;
import org.sadtech.bot.vsc.context.domain.ReviewerStatus;
import org.sadtech.bot.gitlab.context.domain.MergeRequestState;
import org.sadtech.bot.gitlab.context.domain.entity.MergeRequest;
import org.springframework.data.jpa.repository.support.JpaRepositoryImplementation;
import org.springframework.data.repository.NoRepositoryBean;
import org.springframework.data.repository.query.Param;
import java.util.Collection;
import java.util.List;
import java.util.Optional;
import java.util.Set;
@ -18,30 +16,24 @@ import java.util.Set;
*/
@NoRepositoryBean
public interface PullRequestsRepositoryJpa extends JpaRepositoryImplementation<PullRequest, Long> {
public interface PullRequestsRepositoryJpa extends JpaRepositoryImplementation<MergeRequest, Long> {
Set<PullRequest> findAllByIdIn(Set<Long> ids);
Set<MergeRequest> findAllByIdIn(Set<Long> ids);
Boolean existsByBitbucketIdAndRepositoryId(Long bitbucketId, Long repositoryId);
// @Query("SELECT p.id FROM PullRequest p WHERE p.bitbucketId=:bitbucketId AND p.repositoryId=:repositoryId")
// @Query("SELECT p.id FROM PullRequest p WHERE p.bitbucketId=:bitbucketId AND p.repositoryId=:repositoryId")
Optional<Long> findIdByBitbucketIdAndRepositoryId(@Param("bitbucketId") Long bitbucketId, @Param("repositoryId") Long repositoryId);
void deleteAllByIdIn(Collection<Long> id);
// @Query("SELECT p FROM PullRequest p LEFT JOIN p.reviewers r WHERE r.personLogin=:reviewer AND r.status =:reviewerStatus AND p.status IN :pullRequestStatus")
List<PullRequest> findAllByReviewerAndStatuses(@Param("reviewer") String reviewer, @Param("reviewerStatus") ReviewerStatus reviewerStatus, @Param("pullRequestStatus") Set<PullRequestStatus> pullRequestStatus);
// @Query("SELECT p FROM PullRequest p LEFT JOIN p.reviewers r WHERE p.authorLogin=:author AND r.status=:reviewerStatus")
List<PullRequest> findAllByAuthorAndReviewerStatus(@Param("author") String author, @Param("reviewerStatus") ReviewerStatus reviewerStatus);
// @Query("SELECT new org.sadtech.bot.bitbucketbot.domain.IdAndStatusPr(p.id, p.status) FROM PullRequest p WHERE p.status IN :statuses")
Set<IdAndStatusPr> findAllIdByStatusIn(@Param("statuses") Set<PullRequestStatus> statuses);
Set<IdAndStatusPr> findAllIdByStatusIn(@Param("statuses") Set<MergeRequestState> statuses);
// @Query("SELECT p.id from PullRequest p")
// @Query("SELECT p.id from PullRequest p")
Set<Long> findAllIds();
// @Query("SELECT p.authorLogin from PullRequest p WHERE p.id = :id")
// @Query("SELECT p.authorLogin from PullRequest p WHERE p.id = :id")
Optional<String> findAuthorById(@Param("id") Long id);
}

View File

@ -1,90 +0,0 @@
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns="http://maven.apache.org/POM/4.0.0"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<parent>
<artifactId>gitlab-bot</artifactId>
<groupId>org.sadtech.bot.gitlab</groupId>
<version>3.0.1-RELEASE</version>
</parent>
<modelVersion>4.0.0</modelVersion>
<artifactId>gitlab-core</artifactId>
<version>${gitlab.context.version}</version>
<name>GitLab Server Core</name>
<description>Implementation of the Bitbucket server version service layer</description>
<url>https://github.com/uPagge/bitbucketbot</url>
<dependencies>
<dependency>
<groupId>org.sadtech.bot.gitlab</groupId>
<artifactId>bot-context</artifactId>
</dependency>
<dependency>
<groupId>org.sadtech.bot.gitlab</groupId>
<artifactId>bot-core</artifactId>
</dependency>
<dependency>
<groupId>org.sadtech.bot.gitlab</groupId>
<artifactId>gitlab-sdk</artifactId>
</dependency>
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
</dependency>
<dependency>
<groupId>org.sadtech.bot.vcs</groupId>
<artifactId>vcs-bot-context</artifactId>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-core</artifactId>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.sonatype.plugins</groupId>
<artifactId>nexus-staging-maven-plugin</artifactId>
<configuration>
<skipNexusStagingDeployMojo>false</skipNexusStagingDeployMojo>
</configuration>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-source-plugin</artifactId>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-javadoc-plugin</artifactId>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-gpg-plugin</artifactId>
</plugin>
</plugins>
</build>
<developers>
<developer>
<id>uPagge</id>
<name>Struchkov Mark</name>
<email>upagge@ya.ru</email>
<organization>SADTECH</organization>
<organizationUrl>https://sadtech.org</organizationUrl>
<url>https://uPagge.sadtech.org</url>
<roles>
<role>Project lead</role>
</roles>
<timezone>+3</timezone>
</developer>
</developers>
</project>

View File

@ -1,35 +0,0 @@
package org.sadtech.bot.gitalb.core.service.converter;
import org.sadtech.bot.gitlab.context.domain.entity.Comment;
import org.sadtech.bot.gitlab.core.utils.StringUtils;
import org.sadtech.bot.gitlab.sdk.domain.CommentJson;
import org.sadtech.bot.gitlab.sdk.domain.Severity;
import org.springframework.core.convert.converter.Converter;
import org.springframework.stereotype.Component;
import java.util.stream.Collectors;
@Component
public class CommentJsonToComment implements Converter<CommentJson, Comment> {
@Override
public Comment convert(CommentJson source) {
final Comment comment = new Comment();
comment.setId(source.getId());
comment.setCreateDate(source.getCreatedDate());
comment.setAuthor(source.getAuthor().getName());
comment.setPullRequestId(source.getCustomPullRequestId());
comment.setMessage(StringUtils.cutOff(source.getText(), 490));
comment.setUrlApi(source.getCustomCommentApiUrl());
comment.setBitbucketVersion(source.getVersion());
comment.setAnswers(
source.getComments().stream()
.filter(json -> Severity.NORMAL.equals(json.getSeverity()))
.map(CommentJson::getId)
.collect(Collectors.toSet())
);
return comment;
}
}

View File

@ -1,49 +0,0 @@
package org.sadtech.bot.gitalb.core.service.converter;
import org.sadtech.bot.gitlab.context.domain.TaskStatus;
import org.sadtech.bot.gitlab.context.domain.entity.Task;
import org.sadtech.bot.gitlab.core.utils.StringUtils;
import org.sadtech.bot.gitlab.sdk.domain.CommentJson;
import org.sadtech.bot.gitlab.sdk.domain.CommentState;
import org.sadtech.bot.gitlab.sdk.domain.Severity;
import org.sadtech.haiti.context.exception.ConvertException;
import org.springframework.core.convert.converter.Converter;
import org.springframework.stereotype.Component;
import java.util.stream.Collectors;
@Component
public class CommentJsonToTaskConvert implements Converter<CommentJson, Task> {
@Override
public Task convert(CommentJson source) {
final Task task = new Task();
task.setId(source.getId());
task.setAuthor(source.getAuthor().getName());
task.setDescription(StringUtils.cutOff(source.getText(), 490));
task.setCreateDate(source.getCreatedDate());
task.setBitbucketVersion(source.getVersion());
task.setPullRequestId(source.getCustomPullRequestId());
task.setStatus(convertState(source.getState()));
task.setUrlApi(source.getCustomCommentApiUrl());
task.setAnswers(
source.getComments().stream()
.filter(json -> Severity.NORMAL.equals(json.getSeverity()))
.map(CommentJson::getId)
.collect(Collectors.toSet())
);
return task;
}
private TaskStatus convertState(CommentState state) {
switch (state) {
case RESOLVED:
return TaskStatus.RESOLVED;
case OPEN:
return TaskStatus.OPEN;
default:
throw new ConvertException("Неподдерживаемый тип задачи");
}
}
}

View File

@ -1,61 +0,0 @@
package org.sadtech.bot.gitalb.core.service.converter;
import lombok.RequiredArgsConstructor;
import org.sadtech.bot.gitlab.context.domain.entity.PullRequest;
import org.sadtech.bot.gitlab.sdk.domain.MergeRequestJson;
import org.sadtech.bot.gitlab.sdk.domain.Outcome;
import org.sadtech.bot.gitlab.sdk.domain.Properties;
import org.sadtech.bot.gitlab.sdk.domain.PullRequestState;
import org.sadtech.bot.gitlab.sdk.domain.UserPullRequestStatus;
import org.sadtech.bot.vsc.context.domain.PullRequestStatus;
import org.sadtech.bot.vsc.context.domain.ReviewerStatus;
import org.sadtech.haiti.context.exception.ConvertException;
import org.springframework.core.convert.converter.Converter;
import org.springframework.stereotype.Component;
@Component
@RequiredArgsConstructor
public class PullRequestJsonConverter implements Converter<MergeRequestJson, PullRequest> {
public static PullRequestStatus convertPullRequestStatus(PullRequestState state) {
switch (state) {
case OPENED:
return PullRequestStatus.OPEN;
case MERGED:
return PullRequestStatus.MERGED;
case DECLINED:
return PullRequestStatus.DECLINED;
default:
throw new ConvertException("Неподдерживаемый тип ПР");
}
}
private static ReviewerStatus convertStatusReviewer(UserPullRequestStatus status) {
switch (status) {
case APPROVED:
return ReviewerStatus.APPROVED;
case NEEDS_WORK:
return ReviewerStatus.UNAPPROVED;
case UNAPPROVED:
return ReviewerStatus.NEEDS_WORK;
default:
throw new ConvertException("Неподдерживаемый статус ревьювера");
}
}
@Override
public PullRequest convert(MergeRequestJson json) {
final PullRequest pullRequest = new PullRequest();
return pullRequest;
}
private boolean convertConflict(Properties properties) {
return properties != null
&& properties.getMergeResult() != null
&& properties.getMergeResult().getOutcome() != null
&& Outcome.CONFLICTED.equals(properties.getMergeResult().getOutcome());
}
}

10
pom.xml
View File

@ -15,7 +15,6 @@
<module>bot-core</module>
<module>bot-app</module>
<module>teamcity</module>
<module>gitlab-core</module>
<module>bot-data</module>
</modules>
@ -104,16 +103,7 @@
<dependencyManagement>
<dependencies>
<!-- абстракции -->
<dependency>
<groupId>org.sadtech.bot.vcs</groupId>
<artifactId>vcs-bot-context</artifactId>
<version>${sadtech.bot.vsc.context.version}</version>
</dependency>
<!-- /абстракции -->
<!-- модули проекта -->
<dependency>
<groupId>org.sadtech.bot.gitlab</groupId>
<artifactId>bot-core</artifactId>

View File

@ -1,7 +1,7 @@
package org.sadtech.bot.gitlab.telegram.service.unit.pullrequest;
import lombok.RequiredArgsConstructor;
import org.sadtech.bot.gitlab.context.service.PullRequestsService;
import org.sadtech.bot.gitlab.context.service.MergeRequestsService;
import org.sadtech.social.bot.service.usercode.ProcessingData;
import org.sadtech.social.core.domain.BoxAnswer;
import org.sadtech.social.core.domain.content.Message;
@ -15,7 +15,7 @@ import org.sadtech.social.core.domain.content.Message;
@RequiredArgsConstructor
public class PullRequestNeedWorkProcessing implements ProcessingData<Message> {
private final PullRequestsService pullRequestsService;
private final MergeRequestsService mergeRequestsService;
@Override
public BoxAnswer processing(Message message) {

View File

@ -1,7 +1,7 @@
package org.sadtech.bot.gitlab.telegram.service.unit.pullrequest;
import lombok.RequiredArgsConstructor;
import org.sadtech.bot.gitlab.context.service.PullRequestsService;
import org.sadtech.bot.gitlab.context.service.MergeRequestsService;
import org.sadtech.social.bot.service.usercode.ProcessingData;
import org.sadtech.social.core.domain.BoxAnswer;
import org.sadtech.social.core.domain.content.Message;
@ -15,7 +15,7 @@ import org.sadtech.social.core.domain.content.Message;
@RequiredArgsConstructor
public class PullRequestReviewProcessing implements ProcessingData<Message> {
private final PullRequestsService pullRequestsService;
private final MergeRequestsService mergeRequestsService;
@Override
public BoxAnswer processing(Message message) {