The Unified and Autonomous Development Platform
midwork
robin shine2362ec579c15
diff --git a/gitplex.core/src/main/java/com/pmease/gitplex/core/manager/impl/DefaultPullRequestManager.java b/gitplex.core/src/main/java/com/pmease/gitplex/core/manager/impl/DefaultPullRequestManager.javaindex efaaa24e42..18de8a51bd 100644--- a/gitplex.core/src/main/java/com/pmease/gitplex/core/manager/impl/DefaultPullRequestManager.java+++ b/gitplex.core/src/main/java/com/pmease/gitplex/core/manager/impl/DefaultPullRequestManager.java@@ -1,841 +1,841 @@-package com.pmease.gitplex.core.manager.impl;--import static com.pmease.gitplex.core.model.PullRequest.CriterionHelper.ofOpen;-import static com.pmease.gitplex.core.model.PullRequest.CriterionHelper.ofSource;-import static com.pmease.gitplex.core.model.PullRequest.CriterionHelper.ofTarget;-import static com.pmease.gitplex.core.model.PullRequest.IntegrationStrategy.MERGE_ALWAYS;-import static com.pmease.gitplex.core.model.PullRequest.IntegrationStrategy.MERGE_IF_NECESSARY;-import static com.pmease.gitplex.core.model.PullRequest.IntegrationStrategy.MERGE_WITH_SQUASH;-import static com.pmease.gitplex.core.model.PullRequest.IntegrationStrategy.REBASE_SOURCE_ONTO_TARGET;-import static com.pmease.gitplex.core.model.PullRequest.IntegrationStrategy.REBASE_TARGET_ONTO_SOURCE;-import static com.pmease.gitplex.core.model.PullRequest.Status.PENDING_APPROVAL;-import static com.pmease.gitplex.core.model.PullRequest.Status.PENDING_INTEGRATE;-import static com.pmease.gitplex.core.model.PullRequest.Status.PENDING_UPDATE;--import java.io.File;-import java.util.Collection;-import java.util.Date;-import java.util.List;-import java.util.Set;--import javax.annotation.Nullable;-import javax.inject.Inject;-import javax.inject.Singleton;--import org.apache.commons.lang3.builder.EqualsBuilder;-import org.apache.commons.lang3.builder.HashCodeBuilder;-import org.apache.wicket.request.cycle.RequestCycle;-import org.eclipse.jetty.util.ConcurrentHashSet;-import org.eclipse.jgit.lib.ObjectId;-import org.hibernate.Query;-import org.hibernate.criterion.Criterion;-import org.hibernate.criterion.Restrictions;-import org.joda.time.DateTime;-import org.slf4j.Logger;-import org.slf4j.LoggerFactory;--import com.google.common.base.Preconditions;-import com.google.common.collect.Lists;-import com.pmease.commons.git.Git;-import com.pmease.commons.git.GitUtils;-import com.pmease.commons.git.command.MergeCommand.FastForwardMode;-import com.pmease.commons.hibernate.Sessional;-import com.pmease.commons.hibernate.Transactional;-import com.pmease.commons.hibernate.UnitOfWork;-import com.pmease.commons.hibernate.dao.Dao;-import com.pmease.commons.hibernate.dao.EntityCriteria;-import com.pmease.commons.markdown.MarkdownManager;-import com.pmease.commons.util.FileUtils;-import com.pmease.commons.util.concurrent.PrioritizedRunnable;-import com.pmease.gitplex.core.GitPlex;-import com.pmease.gitplex.core.listeners.LifecycleListener;-import com.pmease.gitplex.core.listeners.PullRequestListener;-import com.pmease.gitplex.core.listeners.RefListener;-import com.pmease.gitplex.core.listeners.RepositoryListener;-import com.pmease.gitplex.core.manager.CommentManager;-import com.pmease.gitplex.core.manager.NotificationManager;-import com.pmease.gitplex.core.manager.PullRequestManager;-import com.pmease.gitplex.core.manager.PullRequestUpdateManager;-import com.pmease.gitplex.core.manager.ReviewInvitationManager;-import com.pmease.gitplex.core.manager.StorageManager;-import com.pmease.gitplex.core.manager.UserManager;-import com.pmease.gitplex.core.manager.WorkManager;-import com.pmease.gitplex.core.model.CloseInfo;-import com.pmease.gitplex.core.model.Comment;-import com.pmease.gitplex.core.model.IntegrationPolicy;-import com.pmease.gitplex.core.model.IntegrationPreview;-import com.pmease.gitplex.core.model.PullRequest;-import com.pmease.gitplex.core.model.PullRequest.IntegrationStrategy;-import com.pmease.gitplex.core.model.PullRequestActivity;-import com.pmease.gitplex.core.model.PullRequestUpdate;-import com.pmease.gitplex.core.model.PullRequestVisit;-import com.pmease.gitplex.core.model.RepoAndBranch;-import com.pmease.gitplex.core.model.Repository;-import com.pmease.gitplex.core.model.ReviewInvitation;-import com.pmease.gitplex.core.model.User;--@Singleton-public class DefaultPullRequestManager implements PullRequestManager, RepositoryListener, RefListener, LifecycleListener {-- private static final Logger logger = LoggerFactory.getLogger(DefaultPullRequestManager.class);-- private static final int UI_PREVIEW_PRIORITY = 10;-- private static final int BACKEND_PREVIEW_PRIORITY = 50;-- private final Dao dao;-- private final PullRequestUpdateManager pullRequestUpdateManager;-- private final CommentManager commentManager;-- private final UserManager userManager;-- private final StorageManager storageManager;-- private final UnitOfWork unitOfWork;-- private final Set<PullRequestListener> pullRequestListeners;-- private final ReviewInvitationManager reviewInvitationManager;-- private final Set<Long> integrationPreviewCalculatingRequestIds = new ConcurrentHashSet<>();-- private final WorkManager workManager;-- @Inject- public DefaultPullRequestManager(Dao dao, PullRequestUpdateManager pullRequestUpdateManager,- StorageManager storageManager, ReviewInvitationManager reviewInvitationManager,- UserManager userManager, NotificationManager notificationManager,- CommentManager commentManager, MarkdownManager markdownManager,- WorkManager workManager, UnitOfWork unitOfWork,- Set<PullRequestListener> pullRequestListeners) {- this.dao = dao;- this.pullRequestUpdateManager = pullRequestUpdateManager;- this.storageManager = storageManager;- this.reviewInvitationManager = reviewInvitationManager;- this.commentManager = commentManager;- this.userManager = userManager;- this.workManager = workManager;- this.unitOfWork = unitOfWork;- this.pullRequestListeners = pullRequestListeners;- }-- @Transactional- @Override- public void delete(PullRequest request) {- deleteRefs(request);-- dao.remove(request);- }-- @Sessional- @Override- public void deleteRefs(PullRequest request) {- for (PullRequestUpdate update : request.getUpdates())- update.deleteRefs();-- request.deleteRefs();- }-- @Transactional- @Override- public void restoreSourceBranch(PullRequest request) {- Preconditions.checkState(!request.isOpen() && request.getSourceRepo() != null);-- if (request.getSource().getHead(false) == null) {- String latestCommitHash = request.getLatestUpdate().getHeadCommitHash();- request.getSourceRepo().git().createBranch(- request.getSourceBranch(), latestCommitHash);- request.getSourceRepo().cacheObjectId(request.getSourceBranch(), ObjectId.fromString(latestCommitHash));- PullRequestActivity activity = new PullRequestActivity();- activity.setRequest(request);- activity.setAction(PullRequestActivity.Action.RESTORE_SOURCE_BRANCH);- activity.setDate(new Date());- activity.setUser(GitPlex.getInstance(UserManager.class).getCurrent());- dao.persist(activity);- }- }-- @Transactional- @Override- public void deleteSourceBranch(PullRequest request) {- Preconditions.checkState(!request.isOpen() && request.getSourceRepo() != null);-- if (request.getSource().getHead(false) != null) {- request.getSource().delete();-- PullRequestActivity activity = new PullRequestActivity();- activity.setRequest(request);- activity.setAction(PullRequestActivity.Action.DELETE_SOURCE_BRANCH);- activity.setDate(new Date());- activity.setUser(GitPlex.getInstance(UserManager.class).getCurrent());- dao.persist(activity);- }- }-- @Transactional- @Override- public void reopen(PullRequest request, String comment) {- Preconditions.checkState(!request.isOpen());-- User user = userManager.getCurrent();- request.setCloseInfo(null);- request.setSubmitter(user);- request.setSubmitDate(new Date());-- dao.persist(request);-- PullRequestActivity activity = new PullRequestActivity();- activity.setRequest(request);- activity.setDate(new DateTime(request.getSubmitDate()).minusSeconds(1).toDate());- activity.setAction(PullRequestActivity.Action.REOPEN);- activity.setUser(user);-- dao.persist(activity);-- if (comment != null) {- Comment requestComment = new Comment();- requestComment.setContent(comment);- requestComment.setRequest(request);- requestComment.setUser(user);- commentManager.save(requestComment, false);- }-- onSourceBranchUpdate(request, false);-- if (request.isOpen()) {- for (PullRequestListener listener: pullRequestListeners)- listener.onReopened(request, user, comment);- }- }-- @Transactional- @Override- public void discard(PullRequest request, final String comment) {- User user = userManager.getCurrent();- PullRequestActivity activity = new PullRequestActivity();- activity.setRequest(request);- activity.setDate(new Date());- activity.setAction(PullRequestActivity.Action.DISCARD);- activity.setUser(user);-- dao.persist(activity);-- if (comment != null) {- Comment requestComment = new Comment();- requestComment.setContent(comment);- requestComment.setRequest(request);- requestComment.setUser(user);-- commentManager.save(requestComment, false);- }-- CloseInfo closeInfo = new CloseInfo();- closeInfo.setCloseDate(activity.getDate());- closeInfo.setClosedBy(user);- closeInfo.setCloseStatus(CloseInfo.Status.DISCARDED);- request.setCloseInfo(closeInfo);- request.setLastEventDate(activity.getDate());- dao.persist(request);-- for (PullRequestListener listener: pullRequestListeners)- listener.onDiscarded(request, user, comment);- }-- @Transactional- @Override- public void integrate(PullRequest request, String comment) {- if (request.getStatus() != PENDING_INTEGRATE)- throw new IllegalStateException("Gate keeper disallows integration right now.");-- IntegrationPreview preview = request.getIntegrationPreview();- if (preview == null)- throw new IllegalStateException("Integration preview has not been calculated yet.");-- String integrated = preview.getIntegrated();- if (integrated == null)- throw new IllegalStateException("There are integration conflicts.");-- User user = userManager.getCurrent();-- Repository targetRepo = request.getTargetRepo();- Git git = targetRepo.git();- IntegrationStrategy strategy = request.getIntegrationStrategy();- if ((strategy == MERGE_ALWAYS || strategy == MERGE_IF_NECESSARY || strategy == MERGE_WITH_SQUASH)- && !preview.getIntegrated().equals(preview.getRequestHead()) && comment != null) {- File tempDir = FileUtils.createTempDir();- try {- Git tempGit = new Git(tempDir);- tempGit.clone(git.repoDir().getAbsolutePath(), false, true, true, request.getTargetBranch());- tempGit.updateRef("HEAD", preview.getIntegrated(), null, null);- tempGit.reset(null, null);-- tempGit.commit(comment, false, true);- integrated = tempGit.parseRevision("HEAD", true);- git.fetch(tempGit, "+HEAD:" + request.getIntegrateRef());- comment = null;- } finally {- FileUtils.deleteDir(tempDir);- }- }- if (strategy == REBASE_SOURCE_ONTO_TARGET || strategy == MERGE_WITH_SQUASH) {- Repository sourceRepo = request.getSourceRepo();- Git sourceGit = sourceRepo.git();- String sourceRef = request.getSourceRef();- sourceGit.updateRef(sourceRef, integrated, preview.getRequestHead(),- "Pull request #" + request.getId());- sourceRepo.cacheObjectId(request.getSourceRef(), ObjectId.fromString(integrated));- onRefUpdate(sourceRepo, sourceRef, integrated);- }-- String targetRef = request.getTargetRef();- git.updateRef(targetRef, integrated, preview.getTargetHead(), "Pull request #" + request.getId());- targetRepo.cacheObjectId(request.getTargetRef(), ObjectId.fromString(integrated));- onRefUpdate(targetRepo, targetRef, integrated);-- PullRequestActivity activity = new PullRequestActivity();- activity.setRequest(request);- activity.setDate(new Date());- activity.setAction(PullRequestActivity.Action.INTEGRATE);- activity.setUser(user);-- dao.persist(activity);-- if (comment != null) {- Comment requestComment = new Comment();- requestComment.setContent(comment);- requestComment.setRequest(request);- requestComment.setUser(user);- commentManager.save(requestComment, false);- }-- CloseInfo closeInfo = new CloseInfo();- closeInfo.setCloseDate(activity.getDate());- closeInfo.setClosedBy(user);- closeInfo.setCloseStatus(CloseInfo.Status.INTEGRATED);- request.setCloseInfo(closeInfo);-- request.setLastEventDate(activity.getDate());-- dao.persist(request);-- for (PullRequestListener listener: pullRequestListeners)- listener.onIntegrated(request, user, comment);- }-- @Transactional- @Override- public void open(final PullRequest request, final Object listenerData) {- dao.persist(request);-- PullRequestActivity activity = new PullRequestActivity();- activity.setDate(request.getSubmitDate());- activity.setAction(PullRequestActivity.Action.OPEN);- activity.setRequest(request);- activity.setUser(request.getSubmitter());- dao.persist(activity);-- FileUtils.cleanDir(storageManager.getCacheDir(request));-- request.git().updateRef(request.getBaseRef(), request.getBaseCommitHash(), null, null);-- for (PullRequestUpdate update: request.getUpdates()) {- update.setDate(new DateTime(activity.getDate()).plusSeconds(1).toDate());- pullRequestUpdateManager.save(update, false);- }-- for (ReviewInvitation invitation: request.getReviewInvitations())- reviewInvitationManager.save(invitation);-- for (PullRequestListener listener: pullRequestListeners)- listener.onOpened(request);-- dao.afterCommit(new Runnable() {-- @Override- public void run() {- IntegrationPreviewTask task = new IntegrationPreviewTask(request.getId());- workManager.remove(task);- workManager.execute(task);- }-- });- }-- @Override- public List<IntegrationStrategy> getApplicableIntegrationStrategies(PullRequest request) {- List<IntegrationStrategy> strategies = null;- for (IntegrationPolicy policy: request.getTargetRepo().getIntegrationPolicies()) {- if (policy.getTargetBranches().matches(request.getTargetBranch())- && policy.getSourceBranches().matches(request.getSourceRepo(), request.getSourceBranch())) {- strategies = policy.getIntegrationStrategies();- break;- }- }- if (strategies == null)- strategies = Lists.newArrayList(IntegrationStrategy.MERGE_ALWAYS);- return strategies;- }-- @Transactional- @Override- public void onAssigneeChange(PullRequest request) {- dao.persist(request);- for (PullRequestListener listener: pullRequestListeners)- listener.onAssigned(request);- }-- @Transactional- @Override- public void onTargetBranchUpdate(PullRequest request) {- String targetHead = request.getTarget().getHead();- if (request.getLastIntegrationPreview() == null || !request.getLastIntegrationPreview().getTargetHead().equals(targetHead)) {- closeIfMerged(request);- if (request.isOpen()) {- IntegrationPreviewTask task = new IntegrationPreviewTask(request.getId());- workManager.remove(task);- workManager.execute(task);- }- }- }-- @Transactional- private void closeIfMerged(PullRequest request) {- if (request.getTargetRepo().isAncestor(request.getLatestUpdate().getHeadCommitHash(), request.getTarget().getHead())) {- PullRequestActivity activity = new PullRequestActivity();- activity.setRequest(request);- activity.setUser(GitPlex.getInstance(UserManager.class).getRoot());- activity.setAction(PullRequestActivity.Action.INTEGRATE);- activity.setDate(new Date());- dao.persist(activity);-- request.setLastIntegrationPreview(null);- CloseInfo closeInfo = new CloseInfo();- closeInfo.setCloseDate(activity.getDate());- closeInfo.setClosedBy(activity.getUser());- closeInfo.setCloseStatus(CloseInfo.Status.INTEGRATED);- request.setCloseInfo(closeInfo);- request.setLastEventDate(activity.getDate());-- dao.persist(request);-- for (PullRequestListener listener: pullRequestListeners)- listener.onIntegrated(request, null, null);- }- }-- @Transactional- @Override- public void onSourceBranchUpdate(PullRequest request, boolean notify) {- if (!request.getLatestUpdate().getHeadCommitHash().equals(request.getSource().getHead())) {- PullRequestUpdate update = new PullRequestUpdate();- update.setRequest(request);- update.setDate(new Date());- update.setHeadCommitHash(request.getSource().getHead());-- request.addUpdate(update);- pullRequestUpdateManager.save(update, notify);- closeIfMerged(request);-- if (request.isOpen()) {- final Long requestId = request.getId();- dao.afterCommit(new Runnable() {-- @Override- public void run() {- unitOfWork.asyncCall(new Runnable() {-- @Override- public void run() {- check(dao.load(PullRequest.class, requestId));- }-- });- }-- });- }- }- }-- /**- * This method might take some time and is not key to pull request logic (even if we- * did not call it, we can always call it later), so normally should be called in an- * executor- */- @Transactional- @Override- public void check(PullRequest request) {- Date now = new Date();- if (request.isOpen()) {- closeIfMerged(request);- if (request.isOpen()) {- if (request.getStatus() == PENDING_UPDATE) {- for (PullRequestListener listener: pullRequestListeners)- listener.pendingUpdate(request);- } else if (request.getStatus() == PENDING_INTEGRATE) {- for (PullRequestListener listener: pullRequestListeners)- listener.pendingIntegration(request);-- IntegrationPreview integrationPreview = request.getIntegrationPreview();- if (integrationPreview != null- && integrationPreview.getIntegrated() != null- && request.getAssignee() == null) {- integrate(request, "Integrated automatically by system");- }- } else if (request.getStatus() == PENDING_APPROVAL) {- for (PullRequestListener listener: pullRequestListeners)- listener.pendingApproval(request);-- for (ReviewInvitation invitation: request.getReviewInvitations()) {- if (!invitation.getDate().before(now))- reviewInvitationManager.save(invitation);- }- }- }- }- }-- @Override- public boolean canIntegrate(PullRequest request) {- if (request.getStatus() != PENDING_INTEGRATE) {- return false;- } else {- IntegrationPreview integrationPreview = request.getIntegrationPreview();- return integrationPreview != null && integrationPreview.getIntegrated() != null;- }- }-- @Override- public IntegrationPreview previewIntegration(PullRequest request) {- IntegrationPreview preview = request.getLastIntegrationPreview();- if (request.isOpen() && (preview == null || preview.isObsolete(request))) {- IntegrationPreviewTask task = new IntegrationPreviewTask(request.getId());- workManager.remove(task);- workManager.execute(task);- return null;- } else {- return preview;- }- }-- private class IntegrationPreviewTask extends PrioritizedRunnable {-- private final Long requestId;-- public IntegrationPreviewTask(Long requestId) {- super(RequestCycle.get() != null?UI_PREVIEW_PRIORITY:BACKEND_PREVIEW_PRIORITY);- this.requestId = requestId;- }-- @Override- public void run() {- unitOfWork.begin();- try {- if (!integrationPreviewCalculatingRequestIds.contains(requestId)) {- integrationPreviewCalculatingRequestIds.add(requestId);- logger.info("Calculating integration preview of pull request #{}...", requestId);- try {- PullRequest request = dao.load(PullRequest.class, requestId);- IntegrationPreview preview = request.getLastIntegrationPreview();- if (request.isOpen() && (preview == null || preview.isObsolete(request))) {- String requestHead = request.getLatestUpdate().getHeadCommitHash();- String targetHead = request.getTarget().getHead();- Repository targetRepo = request.getTargetRepo();- Git git = request.getTargetRepo().git();- preview = new IntegrationPreview(targetHead,- request.getLatestUpdate().getHeadCommitHash(), request.getIntegrationStrategy(), null);- request.setLastIntegrationPreview(preview);- String integrateRef = request.getIntegrateRef();- if (preview.getIntegrationStrategy() == MERGE_IF_NECESSARY && targetRepo.isAncestor(targetHead, requestHead)- || preview.getIntegrationStrategy() == MERGE_WITH_SQUASH && targetRepo.isAncestor(targetHead, requestHead)- && git.log(targetHead, requestHead, null, 0, 0, false).size() == 1) {- preview.setIntegrated(requestHead);- git.updateRef(integrateRef, requestHead, null, null);- } else {- File tempDir = FileUtils.createTempDir();- try {- Git tempGit = new Git(tempDir);- tempGit.clone(git.repoDir().getAbsolutePath(), false, true, true,- request.getTargetBranch());-- String integrated;-- if (preview.getIntegrationStrategy() == REBASE_TARGET_ONTO_SOURCE) {- tempGit.updateRef("HEAD", requestHead, null, null);- tempGit.reset(null, null);- List<String> cherries = tempGit.listCherries("HEAD", targetHead);- integrated = tempGit.cherryPick(cherries.toArray(new String[cherries.size()]));- } else {- tempGit.updateRef("HEAD", targetHead, null, null);- tempGit.reset(null, null);- if (preview.getIntegrationStrategy() == REBASE_SOURCE_ONTO_TARGET) {- List<String> cherries = tempGit.listCherries("HEAD", requestHead);- integrated = tempGit.cherryPick(cherries.toArray(new String[cherries.size()]));- } else if (preview.getIntegrationStrategy() == MERGE_WITH_SQUASH) {- String commitMessage = request.getTitle() + "\n\n";- if (request.getDescription() != null)- commitMessage += request.getDescription() + "\n\n";- commitMessage += "(squashed commit of pull request #" + request.getId() + ")\n";- integrated = tempGit.squash(requestHead, null, null, commitMessage);- } else {- FastForwardMode fastForwardMode;- if (preview.getIntegrationStrategy() == MERGE_ALWAYS)- fastForwardMode = FastForwardMode.NO_FF;- else- fastForwardMode = FastForwardMode.FF;- String commitMessage = "Merge pull request #" + request.getId()- + "\n\n" + request.getTitle() + "\n";- integrated = tempGit.merge(requestHead, fastForwardMode, null, null, commitMessage);- }- }-- if (integrated != null) {- preview.setIntegrated(integrated);- git.fetch(tempGit, "+HEAD:" + integrateRef);- } else {- git.deleteRef(integrateRef, null, null);- }- } finally {- FileUtils.deleteDir(tempDir);- }- }- dao.persist(request);-- if (request.getStatus() == PENDING_INTEGRATE- && preview.getIntegrated() != null- && request.getAssignee() == null) {- integrate(request, "Integrated automatically by system");- }-- for (PullRequestListener listener: pullRequestListeners)- listener.onIntegrationPreviewCalculated(request);- }- } finally {- integrationPreviewCalculatingRequestIds.remove(requestId);- logger.info("Integration preview of pull request #{} is calculated.", requestId);- }- }- } catch (Exception e) {- logger.error("Error calculating integration preview of pull request #" + requestId, e);- } finally {- unitOfWork.end();- }- }-- @Override- public boolean equals(Object other) {- if (!(other instanceof IntegrationPreviewTask))- return false;- if (this == other)- return true;- IntegrationPreviewTask otherRunnable = (IntegrationPreviewTask) other;- return new EqualsBuilder().append(requestId, otherRunnable.requestId).isEquals();- }-- @Override- public int hashCode() {- return new HashCodeBuilder(17, 37).append(requestId).toHashCode();- }-- }-- @Override- public Date getLastVisitDate(PullRequest request) {- User user = userManager.getCurrent();- if (user != null) {- PullRequestVisit visit = request.getVisit(user);- if (visit != null)- return visit.getDate();- else- return null;- } else {- return null;- }- }-- @Override- public void systemStarted() {- logger.info("Checking pull requests...");-- checkSanity();- }-- @Override- public void systemStopping() {- }-- @Override- public void systemStopped() {- }-- @Transactional- @Override- public void beforeDelete(Repository repository) {- for (PullRequest request: repository.getOutgoingRequests()) {- if (!request.getTargetRepo().equals(repository) && request.isOpen())- discard(request, "Source repository is deleted.");- }-- Query query = dao.getSession().createQuery("update PullRequest set sourceRepo=null where "- + "sourceRepo = :repo and targetRepo != :repo");- query.setParameter("repo", repository);- query.executeUpdate();- }-- @Override- public void afterDelete(Repository repository) {- }-- @Transactional- @Override- public void onRefUpdate(Repository repository, String refName, @Nullable String newCommitHash) {- final String branch = GitUtils.ref2branch(refName);- if (branch != null) {- RepoAndBranch repoAndBranch = new RepoAndBranch(repository, branch);- if (newCommitHash != null) {- /**- * Source branch update is key to the logic as it has to create- * pull request update, so we should not postpone it to be executed- * in a executor service like target branch update below- */- Criterion criterion = Restrictions.and(ofOpen(), ofSource(repoAndBranch));- for (PullRequest request: dao.query(EntityCriteria.of(PullRequest.class).add(criterion))) {- if (repository.getObjectId(request.getBaseCommitHash(), false) != null)- onSourceBranchUpdate(request, true);- else- logger.error("Unable to update pull request #{} due to unexpected source repository.", request.getId());- }-- final Long repoId = repository.getId();- dao.afterCommit(new Runnable() {-- @Override- public void run() {- unitOfWork.asyncCall(new Runnable() {-- @Override- public void run() {- RepoAndBranch repoAndBranch = new RepoAndBranch(repoId, branch);- Criterion criterion = Restrictions.and(ofOpen(), ofTarget(repoAndBranch));- for (PullRequest request: dao.query(EntityCriteria.of(PullRequest.class).add(criterion))) {- if (request.getSourceRepo().getObjectId(request.getBaseCommitHash(), false) != null)- onTargetBranchUpdate(request);- else- logger.error("Unable to update pull request #{} due to unexpected target repository.", request.getId());-- }- }-- });- }-- });- } else {- Criterion criterion = Restrictions.and(- ofOpen(),- Restrictions.or(ofSource(repoAndBranch), ofTarget(repoAndBranch)));- for (PullRequest request: dao.query(EntityCriteria.of(PullRequest.class).add(criterion))) {- if (request.getTargetRepo().equals(repository) && request.getTargetBranch().equals(branch))- discard(request, "Target branch is deleted.");- else- discard(request, "Source branch is deleted.");- }- }- }- }-- @Sessional- @Override- public PullRequest findOpen(RepoAndBranch target, RepoAndBranch source) {- return dao.find(EntityCriteria.of(PullRequest.class)- .add(ofTarget(target)).add(ofSource(source)).add(ofOpen()));- }-- @Sessional- @Override- public Collection<PullRequest> queryOpenTo(RepoAndBranch target, @Nullable Repository sourceRepo) {- EntityCriteria<PullRequest> criteria = EntityCriteria.of(PullRequest.class);- criteria.add(ofTarget(target));-- if (sourceRepo != null)- criteria.add(Restrictions.eq("sourceRepo", sourceRepo));- criteria.add(ofOpen());- return dao.query(criteria);- }-- @Sessional- @Override- public Collection<PullRequest> queryOpenFrom(RepoAndBranch source, @Nullable Repository targetRepo) {- EntityCriteria<PullRequest> criteria = EntityCriteria.of(PullRequest.class);- criteria.add(ofSource(source));-- if (targetRepo != null)- criteria.add(Restrictions.eq("targetRepo", targetRepo));- criteria.add(ofOpen());- return dao.query(criteria);- }-- @Sessional- @Override- public Collection<PullRequest> queryOpen(RepoAndBranch sourceOrTarget) {- EntityCriteria<PullRequest> criteria = EntityCriteria.of(PullRequest.class);- criteria.add(ofOpen());- criteria.add(Restrictions.or(ofSource(sourceOrTarget), ofTarget(sourceOrTarget)));- return dao.query(criteria);- }-- @Transactional- @Override- public void checkSanity() {- EntityCriteria<PullRequest> criteria = EntityCriteria.of(PullRequest.class);- criteria.add(ofOpen());- for (PullRequest request: dao.query(criteria)) {- Repository sourceRepo = request.getSourceRepo();- if (sourceRepo == null) {- discard(request, "Source repository is deleted.");- } else if (sourceRepo.isValid()) {- String baseCommitHash = request.getBaseCommitHash();-- // only modifies pull request status if source repository is the repository we- // previously worked with. This avoids disaster of closing all pull requests- // if repository storage points to a different location by mistake- if (sourceRepo.getObjectId(baseCommitHash, false) != null) {- String sourceHead = request.getSource().getHead(false);- if (sourceHead == null)- discard(request, "Source branch is deleted.");- else- onSourceBranchUpdate(request, true);- } else {- logger.error("Unable to update pull request #{} due to unexpected source repository", request.getId());- }- }-- if (request.isOpen()) {- Repository targetRepo = request.getTargetRepo();- if (targetRepo.isValid()) {- String baseCommitHash = request.getBaseCommitHash();-- // only modifies pull request status if target repository is the repository we- // previously worked with. This avoids disaster of closing all pull requests- // if repository storage points to a different location by mistake- if (targetRepo.getObjectId(baseCommitHash, false) != null) {- String targetHead = request.getTarget().getHead(false);- if (targetHead == null)- discard(request, "Target branch is deleted.");- else- onTargetBranchUpdate(request);- } else {- logger.error("Unable to update pull request #{} due to unexpected target repository", request.getId());- }- }- }- }- }-- @Override- public void systemStarting() {- }--}+package com.pmease.gitplex.core.manager.impl;++import static com.pmease.gitplex.core.model.PullRequest.CriterionHelper.ofOpen;+import static com.pmease.gitplex.core.model.PullRequest.CriterionHelper.ofSource;+import static com.pmease.gitplex.core.model.PullRequest.CriterionHelper.ofTarget;+import static com.pmease.gitplex.core.model.PullRequest.IntegrationStrategy.MERGE_ALWAYS;+import static com.pmease.gitplex.core.model.PullRequest.IntegrationStrategy.MERGE_IF_NECESSARY;+import static com.pmease.gitplex.core.model.PullRequest.IntegrationStrategy.MERGE_WITH_SQUASH;+import static com.pmease.gitplex.core.model.PullRequest.IntegrationStrategy.REBASE_SOURCE_ONTO_TARGET;+import static com.pmease.gitplex.core.model.PullRequest.IntegrationStrategy.REBASE_TARGET_ONTO_SOURCE;+import static com.pmease.gitplex.core.model.PullRequest.Status.PENDING_APPROVAL;+import static com.pmease.gitplex.core.model.PullRequest.Status.PENDING_INTEGRATE;+import static com.pmease.gitplex.core.model.PullRequest.Status.PENDING_UPDATE;++import java.io.File;+import java.util.Collection;+import java.util.Date;+import java.util.List;+import java.util.Set;++import javax.annotation.Nullable;+import javax.inject.Inject;+import javax.inject.Singleton;++import org.apache.commons.lang3.builder.EqualsBuilder;+import org.apache.commons.lang3.builder.HashCodeBuilder;+import org.apache.wicket.request.cycle.RequestCycle;+import org.eclipse.jetty.util.ConcurrentHashSet;+import org.eclipse.jgit.lib.ObjectId;+import org.hibernate.Query;+import org.hibernate.criterion.Criterion;+import org.hibernate.criterion.Restrictions;+import org.joda.time.DateTime;+import org.slf4j.Logger;+import org.slf4j.LoggerFactory;++import com.google.common.base.Preconditions;+import com.google.common.collect.Lists;+import com.pmease.commons.git.Git;+import com.pmease.commons.git.GitUtils;+import com.pmease.commons.git.command.MergeCommand.FastForwardMode;+import com.pmease.commons.hibernate.Sessional;+import com.pmease.commons.hibernate.Transactional;+import com.pmease.commons.hibernate.UnitOfWork;+import com.pmease.commons.hibernate.dao.Dao;+import com.pmease.commons.hibernate.dao.EntityCriteria;+import com.pmease.commons.markdown.MarkdownManager;+import com.pmease.commons.util.FileUtils;+import com.pmease.commons.util.concurrent.PrioritizedRunnable;+import com.pmease.gitplex.core.GitPlex;+import com.pmease.gitplex.core.listeners.LifecycleListener;+import com.pmease.gitplex.core.listeners.PullRequestListener;+import com.pmease.gitplex.core.listeners.RefListener;+import com.pmease.gitplex.core.listeners.RepositoryListener;+import com.pmease.gitplex.core.manager.CommentManager;+import com.pmease.gitplex.core.manager.NotificationManager;+import com.pmease.gitplex.core.manager.PullRequestManager;+import com.pmease.gitplex.core.manager.PullRequestUpdateManager;+import com.pmease.gitplex.core.manager.ReviewInvitationManager;+import com.pmease.gitplex.core.manager.StorageManager;+import com.pmease.gitplex.core.manager.UserManager;+import com.pmease.gitplex.core.manager.WorkManager;+import com.pmease.gitplex.core.model.CloseInfo;+import com.pmease.gitplex.core.model.Comment;+import com.pmease.gitplex.core.model.IntegrationPolicy;+import com.pmease.gitplex.core.model.IntegrationPreview;+import com.pmease.gitplex.core.model.PullRequest;+import com.pmease.gitplex.core.model.PullRequest.IntegrationStrategy;+import com.pmease.gitplex.core.model.PullRequestActivity;+import com.pmease.gitplex.core.model.PullRequestUpdate;+import com.pmease.gitplex.core.model.PullRequestVisit;+import com.pmease.gitplex.core.model.RepoAndBranch;+import com.pmease.gitplex.core.model.Repository;+import com.pmease.gitplex.core.model.ReviewInvitation;+import com.pmease.gitplex.core.model.User;++@Singleton+public class DefaultPullRequestManager implements PullRequestManager, RepositoryListener, RefListener, LifecycleListener {++ private static final Logger logger = LoggerFactory.getLogger(DefaultPullRequestManager.class);++ private static final int UI_PREVIEW_PRIORITY = 10;++ private static final int BACKEND_PREVIEW_PRIORITY = 50;++ private final Dao dao;++ private final PullRequestUpdateManager pullRequestUpdateManager;++ private final CommentManager commentManager;++ private final UserManager userManager;++ private final StorageManager storageManager;++ private final UnitOfWork unitOfWork;++ private final Set<PullRequestListener> pullRequestListeners;++ private final ReviewInvitationManager reviewInvitationManager;++ private final Set<Long> integrationPreviewCalculatingRequestIds = new ConcurrentHashSet<>();++ private final WorkManager workManager;++ @Inject+ public DefaultPullRequestManager(Dao dao, PullRequestUpdateManager pullRequestUpdateManager,+ StorageManager storageManager, ReviewInvitationManager reviewInvitationManager,+ UserManager userManager, NotificationManager notificationManager,+ CommentManager commentManager, MarkdownManager markdownManager,+ WorkManager workManager, UnitOfWork unitOfWork,+ Set<PullRequestListener> pullRequestListeners) {+ this.dao = dao;+ this.pullRequestUpdateManager = pullRequestUpdateManager;+ this.storageManager = storageManager;+ this.reviewInvitationManager = reviewInvitationManager;+ this.commentManager = commentManager;+ this.userManager = userManager;+ this.workManager = workManager;+ this.unitOfWork = unitOfWork;+ this.pullRequestListeners = pullRequestListeners;+ }++ @Transactional+ @Override+ public void delete(PullRequest request) {+ deleteRefs(request);++ dao.remove(request);+ }++ @Sessional+ @Override+ public void deleteRefs(PullRequest request) {+ for (PullRequestUpdate update : request.getUpdates())+ update.deleteRefs();++ request.deleteRefs();+ }++ @Transactional+ @Override+ public void restoreSourceBranch(PullRequest request) {+ Preconditions.checkState(!request.isOpen() && request.getSourceRepo() != null);++ if (request.getSource().getObjectName(false) == null) {+ String latestCommitHash = request.getLatestUpdate().getHeadCommitHash();+ request.getSourceRepo().git().createBranch(+ request.getSourceBranch(), latestCommitHash);+ request.getSourceRepo().cacheObjectId(request.getSourceBranch(), ObjectId.fromString(latestCommitHash));+ PullRequestActivity activity = new PullRequestActivity();+ activity.setRequest(request);+ activity.setAction(PullRequestActivity.Action.RESTORE_SOURCE_BRANCH);+ activity.setDate(new Date());+ activity.setUser(GitPlex.getInstance(UserManager.class).getCurrent());+ dao.persist(activity);+ }+ }++ @Transactional+ @Override+ public void deleteSourceBranch(PullRequest request) {+ Preconditions.checkState(!request.isOpen() && request.getSourceRepo() != null);++ if (request.getSource().getObjectName(false) != null) {+ request.getSource().delete();++ PullRequestActivity activity = new PullRequestActivity();+ activity.setRequest(request);+ activity.setAction(PullRequestActivity.Action.DELETE_SOURCE_BRANCH);+ activity.setDate(new Date());+ activity.setUser(GitPlex.getInstance(UserManager.class).getCurrent());+ dao.persist(activity);+ }+ }++ @Transactional+ @Override+ public void reopen(PullRequest request, String comment) {+ Preconditions.checkState(!request.isOpen());++ User user = userManager.getCurrent();+ request.setCloseInfo(null);+ request.setSubmitter(user);+ request.setSubmitDate(new Date());++ dao.persist(request);++ PullRequestActivity activity = new PullRequestActivity();+ activity.setRequest(request);+ activity.setDate(new DateTime(request.getSubmitDate()).minusSeconds(1).toDate());+ activity.setAction(PullRequestActivity.Action.REOPEN);+ activity.setUser(user);++ dao.persist(activity);++ if (comment != null) {+ Comment requestComment = new Comment();+ requestComment.setContent(comment);+ requestComment.setRequest(request);+ requestComment.setUser(user);+ commentManager.save(requestComment, false);+ }++ onSourceBranchUpdate(request, false);++ if (request.isOpen()) {+ for (PullRequestListener listener: pullRequestListeners)+ listener.onReopened(request, user, comment);+ }+ }++ @Transactional+ @Override+ public void discard(PullRequest request, final String comment) {+ User user = userManager.getCurrent();+ PullRequestActivity activity = new PullRequestActivity();+ activity.setRequest(request);+ activity.setDate(new Date());+ activity.setAction(PullRequestActivity.Action.DISCARD);+ activity.setUser(user);++ dao.persist(activity);++ if (comment != null) {+ Comment requestComment = new Comment();+ requestComment.setContent(comment);+ requestComment.setRequest(request);+ requestComment.setUser(user);++ commentManager.save(requestComment, false);+ }++ CloseInfo closeInfo = new CloseInfo();+ closeInfo.setCloseDate(activity.getDate());+ closeInfo.setClosedBy(user);+ closeInfo.setCloseStatus(CloseInfo.Status.DISCARDED);+ request.setCloseInfo(closeInfo);+ request.setLastEventDate(activity.getDate());+ dao.persist(request);++ for (PullRequestListener listener: pullRequestListeners)+ listener.onDiscarded(request, user, comment);+ }++ @Transactional+ @Override+ public void integrate(PullRequest request, String comment) {+ if (request.getStatus() != PENDING_INTEGRATE)+ throw new IllegalStateException("Gate keeper disallows integration right now.");++ IntegrationPreview preview = request.getIntegrationPreview();+ if (preview == null)+ throw new IllegalStateException("Integration preview has not been calculated yet.");++ String integrated = preview.getIntegrated();+ if (integrated == null)+ throw new IllegalStateException("There are integration conflicts.");++ User user = userManager.getCurrent();++ Repository targetRepo = request.getTargetRepo();+ Git git = targetRepo.git();+ IntegrationStrategy strategy = request.getIntegrationStrategy();+ if ((strategy == MERGE_ALWAYS || strategy == MERGE_IF_NECESSARY || strategy == MERGE_WITH_SQUASH)+ && !preview.getIntegrated().equals(preview.getRequestHead()) && comment != null) {+ File tempDir = FileUtils.createTempDir();+ try {+ Git tempGit = new Git(tempDir);+ tempGit.clone(git.repoDir().getAbsolutePath(), false, true, true, request.getTargetBranch());+ tempGit.updateRef("HEAD", preview.getIntegrated(), null, null);+ tempGit.reset(null, null);++ tempGit.commit(comment, false, true);+ integrated = tempGit.parseRevision("HEAD", true);+ git.fetch(tempGit, "+HEAD:" + request.getIntegrateRef());+ comment = null;+ } finally {+ FileUtils.deleteDir(tempDir);+ }+ }+ if (strategy == REBASE_SOURCE_ONTO_TARGET || strategy == MERGE_WITH_SQUASH) {+ Repository sourceRepo = request.getSourceRepo();+ Git sourceGit = sourceRepo.git();+ String sourceRef = request.getSourceRef();+ sourceGit.updateRef(sourceRef, integrated, preview.getRequestHead(),+ "Pull request #" + request.getId());+ sourceRepo.cacheObjectId(request.getSourceRef(), ObjectId.fromString(integrated));+ onRefUpdate(sourceRepo, sourceRef, integrated);+ }++ String targetRef = request.getTargetRef();+ git.updateRef(targetRef, integrated, preview.getTargetHead(), "Pull request #" + request.getId());+ targetRepo.cacheObjectId(request.getTargetRef(), ObjectId.fromString(integrated));+ onRefUpdate(targetRepo, targetRef, integrated);++ PullRequestActivity activity = new PullRequestActivity();+ activity.setRequest(request);+ activity.setDate(new Date());+ activity.setAction(PullRequestActivity.Action.INTEGRATE);+ activity.setUser(user);++ dao.persist(activity);++ if (comment != null) {+ Comment requestComment = new Comment();+ requestComment.setContent(comment);+ requestComment.setRequest(request);+ requestComment.setUser(user);+ commentManager.save(requestComment, false);+ }++ CloseInfo closeInfo = new CloseInfo();+ closeInfo.setCloseDate(activity.getDate());+ closeInfo.setClosedBy(user);+ closeInfo.setCloseStatus(CloseInfo.Status.INTEGRATED);+ request.setCloseInfo(closeInfo);++ request.setLastEventDate(activity.getDate());++ dao.persist(request);++ for (PullRequestListener listener: pullRequestListeners)+ listener.onIntegrated(request, user, comment);+ }++ @Transactional+ @Override+ public void open(final PullRequest request, final Object listenerData) {+ dao.persist(request);++ PullRequestActivity activity = new PullRequestActivity();+ activity.setDate(request.getSubmitDate());+ activity.setAction(PullRequestActivity.Action.OPEN);+ activity.setRequest(request);+ activity.setUser(request.getSubmitter());+ dao.persist(activity);++ FileUtils.cleanDir(storageManager.getCacheDir(request));++ request.git().updateRef(request.getBaseRef(), request.getBaseCommitHash(), null, null);++ for (PullRequestUpdate update: request.getUpdates()) {+ update.setDate(new DateTime(activity.getDate()).plusSeconds(1).toDate());+ pullRequestUpdateManager.save(update, false);+ }++ for (ReviewInvitation invitation: request.getReviewInvitations())+ reviewInvitationManager.save(invitation);++ for (PullRequestListener listener: pullRequestListeners)+ listener.onOpened(request);++ dao.afterCommit(new Runnable() {++ @Override+ public void run() {+ IntegrationPreviewTask task = new IntegrationPreviewTask(request.getId());+ workManager.remove(task);+ workManager.execute(task);+ }++ });+ }++ @Override+ public List<IntegrationStrategy> getApplicableIntegrationStrategies(PullRequest request) {+ List<IntegrationStrategy> strategies = null;+ for (IntegrationPolicy policy: request.getTargetRepo().getIntegrationPolicies()) {+ if (policy.getTargetBranches().matches(request.getTargetBranch())+ && policy.getSourceBranches().matches(request.getSourceRepo(), request.getSourceBranch())) {+ strategies = policy.getIntegrationStrategies();+ break;+ }+ }+ if (strategies == null)+ strategies = Lists.newArrayList(IntegrationStrategy.MERGE_ALWAYS);+ return strategies;+ }++ @Transactional+ @Override+ public void onAssigneeChange(PullRequest request) {+ dao.persist(request);+ for (PullRequestListener listener: pullRequestListeners)+ listener.onAssigned(request);+ }++ @Transactional+ @Override+ public void onTargetBranchUpdate(PullRequest request) {+ String targetHead = request.getTarget().getObjectName();+ if (request.getLastIntegrationPreview() == null || !request.getLastIntegrationPreview().getTargetHead().equals(targetHead)) {+ closeIfMerged(request);+ if (request.isOpen()) {+ IntegrationPreviewTask task = new IntegrationPreviewTask(request.getId());+ workManager.remove(task);+ workManager.execute(task);+ }+ }+ }++ @Transactional+ private void closeIfMerged(PullRequest request) {+ if (request.getTargetRepo().isAncestor(request.getLatestUpdate().getHeadCommitHash(), request.getTarget().getObjectName())) {+ PullRequestActivity activity = new PullRequestActivity();+ activity.setRequest(request);+ activity.setUser(GitPlex.getInstance(UserManager.class).getRoot());+ activity.setAction(PullRequestActivity.Action.INTEGRATE);+ activity.setDate(new Date());+ dao.persist(activity);++ request.setLastIntegrationPreview(null);+ CloseInfo closeInfo = new CloseInfo();+ closeInfo.setCloseDate(activity.getDate());+ closeInfo.setClosedBy(activity.getUser());+ closeInfo.setCloseStatus(CloseInfo.Status.INTEGRATED);+ request.setCloseInfo(closeInfo);+ request.setLastEventDate(activity.getDate());++ dao.persist(request);++ for (PullRequestListener listener: pullRequestListeners)+ listener.onIntegrated(request, null, null);+ }+ }++ @Transactional+ @Override+ public void onSourceBranchUpdate(PullRequest request, boolean notify) {+ if (!request.getLatestUpdate().getHeadCommitHash().equals(request.getSource().getObjectName())) {+ PullRequestUpdate update = new PullRequestUpdate();+ update.setRequest(request);+ update.setDate(new Date());+ update.setHeadCommitHash(request.getSource().getObjectName());++ request.addUpdate(update);+ pullRequestUpdateManager.save(update, notify);+ closeIfMerged(request);++ if (request.isOpen()) {+ final Long requestId = request.getId();+ dao.afterCommit(new Runnable() {++ @Override+ public void run() {+ unitOfWork.asyncCall(new Runnable() {++ @Override+ public void run() {+ check(dao.load(PullRequest.class, requestId));+ }++ });+ }++ });+ }+ }+ }++ /**+ * This method might take some time and is not key to pull request logic (even if we+ * did not call it, we can always call it later), so normally should be called in an+ * executor+ */+ @Transactional+ @Override+ public void check(PullRequest request) {+ Date now = new Date();+ if (request.isOpen()) {+ closeIfMerged(request);+ if (request.isOpen()) {+ if (request.getStatus() == PENDING_UPDATE) {+ for (PullRequestListener listener: pullRequestListeners)+ listener.pendingUpdate(request);+ } else if (request.getStatus() == PENDING_INTEGRATE) {+ for (PullRequestListener listener: pullRequestListeners)+ listener.pendingIntegration(request);++ IntegrationPreview integrationPreview = request.getIntegrationPreview();+ if (integrationPreview != null+ && integrationPreview.getIntegrated() != null+ && request.getAssignee() == null) {+ integrate(request, "Integrated automatically by system");+ }+ } else if (request.getStatus() == PENDING_APPROVAL) {+ for (PullRequestListener listener: pullRequestListeners)+ listener.pendingApproval(request);++ for (ReviewInvitation invitation: request.getReviewInvitations()) {+ if (!invitation.getDate().before(now))+ reviewInvitationManager.save(invitation);+ }+ }+ }+ }+ }++ @Override+ public boolean canIntegrate(PullRequest request) {+ if (request.getStatus() != PENDING_INTEGRATE) {+ return false;+ } else {+ IntegrationPreview integrationPreview = request.getIntegrationPreview();+ return integrationPreview != null && integrationPreview.getIntegrated() != null;+ }+ }++ @Override+ public IntegrationPreview previewIntegration(PullRequest request) {+ IntegrationPreview preview = request.getLastIntegrationPreview();+ if (request.isOpen() && (preview == null || preview.isObsolete(request))) {+ IntegrationPreviewTask task = new IntegrationPreviewTask(request.getId());+ workManager.remove(task);+ workManager.execute(task);+ return null;+ } else {+ return preview;+ }+ }++ private class IntegrationPreviewTask extends PrioritizedRunnable {++ private final Long requestId;++ public IntegrationPreviewTask(Long requestId) {+ super(RequestCycle.get() != null?UI_PREVIEW_PRIORITY:BACKEND_PREVIEW_PRIORITY);+ this.requestId = requestId;+ }++ @Override+ public void run() {+ unitOfWork.begin();+ try {+ if (!integrationPreviewCalculatingRequestIds.contains(requestId)) {+ integrationPreviewCalculatingRequestIds.add(requestId);+ logger.info("Calculating integration preview of pull request #{}...", requestId);+ try {+ PullRequest request = dao.load(PullRequest.class, requestId);+ IntegrationPreview preview = request.getLastIntegrationPreview();+ if (request.isOpen() && (preview == null || preview.isObsolete(request))) {+ String requestHead = request.getLatestUpdate().getHeadCommitHash();+ String targetHead = request.getTarget().getObjectName();+ Repository targetRepo = request.getTargetRepo();+ Git git = request.getTargetRepo().git();+ preview = new IntegrationPreview(targetHead,+ request.getLatestUpdate().getHeadCommitHash(), request.getIntegrationStrategy(), null);+ request.setLastIntegrationPreview(preview);+ String integrateRef = request.getIntegrateRef();+ if (preview.getIntegrationStrategy() == MERGE_IF_NECESSARY && targetRepo.isAncestor(targetHead, requestHead)+ || preview.getIntegrationStrategy() == MERGE_WITH_SQUASH && targetRepo.isAncestor(targetHead, requestHead)+ && git.log(targetHead, requestHead, null, 0, 0, false).size() == 1) {+ preview.setIntegrated(requestHead);+ git.updateRef(integrateRef, requestHead, null, null);+ } else {+ File tempDir = FileUtils.createTempDir();+ try {+ Git tempGit = new Git(tempDir);+ tempGit.clone(git.repoDir().getAbsolutePath(), false, true, true,+ request.getTargetBranch());++ String integrated;++ if (preview.getIntegrationStrategy() == REBASE_TARGET_ONTO_SOURCE) {+ tempGit.updateRef("HEAD", requestHead, null, null);+ tempGit.reset(null, null);+ List<String> cherries = tempGit.listCherries("HEAD", targetHead);+ integrated = tempGit.cherryPick(cherries.toArray(new String[cherries.size()]));+ } else {+ tempGit.updateRef("HEAD", targetHead, null, null);+ tempGit.reset(null, null);+ if (preview.getIntegrationStrategy() == REBASE_SOURCE_ONTO_TARGET) {+ List<String> cherries = tempGit.listCherries("HEAD", requestHead);+ integrated = tempGit.cherryPick(cherries.toArray(new String[cherries.size()]));+ } else if (preview.getIntegrationStrategy() == MERGE_WITH_SQUASH) {+ String commitMessage = request.getTitle() + "\n\n";+ if (request.getDescription() != null)+ commitMessage += request.getDescription() + "\n\n";+ commitMessage += "(squashed commit of pull request #" + request.getId() + ")\n";+ integrated = tempGit.squash(requestHead, null, null, commitMessage);+ } else {+ FastForwardMode fastForwardMode;+ if (preview.getIntegrationStrategy() == MERGE_ALWAYS)+ fastForwardMode = FastForwardMode.NO_FF;+ else+ fastForwardMode = FastForwardMode.FF;+ String commitMessage = "Merge pull request #" + request.getId()+ + "\n\n" + request.getTitle() + "\n";+ integrated = tempGit.merge(requestHead, fastForwardMode, null, null, commitMessage);+ }+ }++ if (integrated != null) {+ preview.setIntegrated(integrated);+ git.fetch(tempGit, "+HEAD:" + integrateRef);+ } else {+ git.deleteRef(integrateRef, null, null);+ }+ } finally {+ FileUtils.deleteDir(tempDir);+ }+ }+ dao.persist(request);++ if (request.getStatus() == PENDING_INTEGRATE+ && preview.getIntegrated() != null+ && request.getAssignee() == null) {+ integrate(request, "Integrated automatically by system");+ }++ for (PullRequestListener listener: pullRequestListeners)+ listener.onIntegrationPreviewCalculated(request);+ }+ } finally {+ integrationPreviewCalculatingRequestIds.remove(requestId);+ logger.info("Integration preview of pull request #{} is calculated.", requestId);+ }+ }+ } catch (Exception e) {+ logger.error("Error calculating integration preview of pull request #" + requestId, e);+ } finally {+ unitOfWork.end();+ }+ }++ @Override+ public boolean equals(Object other) {+ if (!(other instanceof IntegrationPreviewTask))+ return false;+ if (this == other)+ return true;+ IntegrationPreviewTask otherRunnable = (IntegrationPreviewTask) other;+ return new EqualsBuilder().append(requestId, otherRunnable.requestId).isEquals();+ }++ @Override+ public int hashCode() {+ return new HashCodeBuilder(17, 37).append(requestId).toHashCode();+ }++ }++ @Override+ public Date getLastVisitDate(PullRequest request) {+ User user = userManager.getCurrent();+ if (user != null) {+ PullRequestVisit visit = request.getVisit(user);+ if (visit != null)+ return visit.getDate();+ else+ return null;+ } else {+ return null;+ }+ }++ @Override+ public void systemStarted() {+ logger.info("Checking pull requests...");++ checkSanity();+ }++ @Override+ public void systemStopping() {+ }++ @Override+ public void systemStopped() {+ }++ @Transactional+ @Override+ public void beforeDelete(Repository repository) {+ for (PullRequest request: repository.getOutgoingRequests()) {+ if (!request.getTargetRepo().equals(repository) && request.isOpen())+ discard(request, "Source repository is deleted.");+ }++ Query query = dao.getSession().createQuery("update PullRequest set sourceRepo=null where "+ + "sourceRepo = :repo and targetRepo != :repo");+ query.setParameter("repo", repository);+ query.executeUpdate();+ }++ @Override+ public void afterDelete(Repository repository) {+ }++ @Transactional+ @Override+ public void onRefUpdate(Repository repository, String refName, @Nullable String newCommitHash) {+ final String branch = GitUtils.ref2branch(refName);+ if (branch != null) {+ RepoAndBranch repoAndBranch = new RepoAndBranch(repository, branch);+ if (newCommitHash != null) {+ /**+ * Source branch update is key to the logic as it has to create+ * pull request update, so we should not postpone it to be executed+ * in a executor service like target branch update below+ */+ Criterion criterion = Restrictions.and(ofOpen(), ofSource(repoAndBranch));+ for (PullRequest request: dao.query(EntityCriteria.of(PullRequest.class).add(criterion))) {+ if (repository.getObjectId(request.getBaseCommitHash(), false) != null)+ onSourceBranchUpdate(request, true);+ else+ logger.error("Unable to update pull request #{} due to unexpected source repository.", request.getId());+ }++ final Long repoId = repository.getId();+ dao.afterCommit(new Runnable() {++ @Override+ public void run() {+ unitOfWork.asyncCall(new Runnable() {++ @Override+ public void run() {+ RepoAndBranch repoAndBranch = new RepoAndBranch(repoId, branch);+ Criterion criterion = Restrictions.and(ofOpen(), ofTarget(repoAndBranch));+ for (PullRequest request: dao.query(EntityCriteria.of(PullRequest.class).add(criterion))) {+ if (request.getSourceRepo().getObjectId(request.getBaseCommitHash(), false) != null)+ onTargetBranchUpdate(request);+ else+ logger.error("Unable to update pull request #{} due to unexpected target repository.", request.getId());++ }+ }++ });+ }++ });+ } else {+ Criterion criterion = Restrictions.and(+ ofOpen(),+ Restrictions.or(ofSource(repoAndBranch), ofTarget(repoAndBranch)));+ for (PullRequest request: dao.query(EntityCriteria.of(PullRequest.class).add(criterion))) {+ if (request.getTargetRepo().equals(repository) && request.getTargetBranch().equals(branch))+ discard(request, "Target branch is deleted.");+ else+ discard(request, "Source branch is deleted.");+ }+ }+ }+ }++ @Sessional+ @Override+ public PullRequest findOpen(RepoAndBranch target, RepoAndBranch source) {+ return dao.find(EntityCriteria.of(PullRequest.class)+ .add(ofTarget(target)).add(ofSource(source)).add(ofOpen()));+ }++ @Sessional+ @Override+ public Collection<PullRequest> queryOpenTo(RepoAndBranch target, @Nullable Repository sourceRepo) {+ EntityCriteria<PullRequest> criteria = EntityCriteria.of(PullRequest.class);+ criteria.add(ofTarget(target));++ if (sourceRepo != null)+ criteria.add(Restrictions.eq("sourceRepo", sourceRepo));+ criteria.add(ofOpen());+ return dao.query(criteria);+ }++ @Sessional+ @Override+ public Collection<PullRequest> queryOpenFrom(RepoAndBranch source, @Nullable Repository targetRepo) {+ EntityCriteria<PullRequest> criteria = EntityCriteria.of(PullRequest.class);+ criteria.add(ofSource(source));++ if (targetRepo != null)+ criteria.add(Restrictions.eq("targetRepo", targetRepo));+ criteria.add(ofOpen());+ return dao.query(criteria);+ }++ @Sessional+ @Override+ public Collection<PullRequest> queryOpen(RepoAndBranch sourceOrTarget) {+ EntityCriteria<PullRequest> criteria = EntityCriteria.of(PullRequest.class);+ criteria.add(ofOpen());+ criteria.add(Restrictions.or(ofSource(sourceOrTarget), ofTarget(sourceOrTarget)));+ return dao.query(criteria);+ }++ @Transactional+ @Override+ public void checkSanity() {+ EntityCriteria<PullRequest> criteria = EntityCriteria.of(PullRequest.class);+ criteria.add(ofOpen());+ for (PullRequest request: dao.query(criteria)) {+ Repository sourceRepo = request.getSourceRepo();+ if (sourceRepo == null) {+ discard(request, "Source repository is deleted.");+ } else if (sourceRepo.isValid()) {+ String baseCommitHash = request.getBaseCommitHash();++ // only modifies pull request status if source repository is the repository we+ // previously worked with. This avoids disaster of closing all pull requests+ // if repository storage points to a different location by mistake+ if (sourceRepo.getObjectId(baseCommitHash, false) != null) {+ String sourceHead = request.getSource().getObjectName(false);+ if (sourceHead == null)+ discard(request, "Source branch is deleted.");+ else+ onSourceBranchUpdate(request, true);+ } else {+ logger.error("Unable to update pull request #{} due to unexpected source repository", request.getId());+ }+ }++ if (request.isOpen()) {+ Repository targetRepo = request.getTargetRepo();+ if (targetRepo.isValid()) {+ String baseCommitHash = request.getBaseCommitHash();++ // only modifies pull request status if target repository is the repository we+ // previously worked with. This avoids disaster of closing all pull requests+ // if repository storage points to a different location by mistake+ if (targetRepo.getObjectId(baseCommitHash, false) != null) {+ String targetHead = request.getTarget().getObjectName(false);+ if (targetHead == null)+ discard(request, "Target branch is deleted.");+ else+ onTargetBranchUpdate(request);+ } else {+ logger.error("Unable to update pull request #{} due to unexpected target repository", request.getId());+ }+ }+ }+ }+ }++ @Override+ public void systemStarting() {+ }++}diff --git a/gitplex.core/src/main/java/com/pmease/gitplex/core/manager/impl/DefaultPullRequestUpdateManager.java b/gitplex.core/src/main/java/com/pmease/gitplex/core/manager/impl/DefaultPullRequestUpdateManager.javaindex 50f3dedb7c..f44435449d 100644--- a/gitplex.core/src/main/java/com/pmease/gitplex/core/manager/impl/DefaultPullRequestUpdateManager.java+++ b/gitplex.core/src/main/java/com/pmease/gitplex/core/manager/impl/DefaultPullRequestUpdateManager.java@@ -49,7 +49,7 @@ public class DefaultPullRequestUpdateManager implements PullRequestUpdateManagerFileUtils.cleanDir(storageManager.getCacheDir(update));PullRequest request = update.getRequest();- String sourceHead = request.getSource().getHead();+ String sourceHead = request.getSource().getObjectName();if (!request.getTargetRepo().equals(request.getSourceRepo())) {request.getTargetRepo().git().fetch(diff --git a/gitplex.core/src/main/java/com/pmease/gitplex/core/model/IntegrationPreview.java b/gitplex.core/src/main/java/com/pmease/gitplex/core/model/IntegrationPreview.javaindex 8058bb6b3d..5499a6f002 100644--- a/gitplex.core/src/main/java/com/pmease/gitplex/core/model/IntegrationPreview.java+++ b/gitplex.core/src/main/java/com/pmease/gitplex/core/model/IntegrationPreview.java@@ -79,7 +79,7 @@ public class IntegrationPreview implements Serializable {public boolean isObsolete(PullRequest request) {if (getRequestHead().equals(request.getLatestUpdate().getHeadCommitHash())- && getTargetHead().equals(request.getTarget().getHead())+ && getTargetHead().equals(request.getTarget().getObjectName())&& getIntegrationStrategy() == request.getIntegrationStrategy()&& (getIntegrated() == null || ObjectId.fromString(getIntegrated()).equals((request.getTargetRepo().getObjectId(request.getIntegrateRef(), false))))) {return false;diff --git a/gitplex.core/src/main/java/com/pmease/gitplex/core/model/PullRequest.java b/gitplex.core/src/main/java/com/pmease/gitplex/core/model/PullRequest.javaindex c75ed69063..51b63f1d4b 100644--- a/gitplex.core/src/main/java/com/pmease/gitplex/core/model/PullRequest.java+++ b/gitplex.core/src/main/java/com/pmease/gitplex/core/model/PullRequest.java@@ -1,978 +1,978 @@-package com.pmease.gitplex.core.model;--import java.util.ArrayList;-import java.util.Collection;-import java.util.Collections;-import java.util.Comparator;-import java.util.Date;-import java.util.HashMap;-import java.util.HashSet;-import java.util.List;-import java.util.Map;-import java.util.Set;-import java.util.concurrent.Callable;--import javax.annotation.Nullable;-import javax.persistence.Column;-import javax.persistence.Embedded;-import javax.persistence.Entity;-import javax.persistence.FetchType;-import javax.persistence.JoinColumn;-import javax.persistence.Lob;-import javax.persistence.ManyToOne;-import javax.persistence.OneToMany;-import javax.persistence.PrePersist;-import javax.persistence.Transient;-import javax.persistence.Version;--import org.apache.commons.lang3.StringUtils;-import org.hibernate.annotations.DynamicUpdate;-import org.hibernate.annotations.Index;-import org.hibernate.annotations.OnDelete;-import org.hibernate.annotations.OnDeleteAction;-import org.hibernate.annotations.OptimisticLock;-import org.hibernate.criterion.Criterion;-import org.hibernate.criterion.Restrictions;--import com.fasterxml.jackson.annotation.JsonView;-import com.google.common.base.Preconditions;-import com.pmease.commons.git.Commit;-import com.pmease.commons.git.Git;-import com.pmease.commons.git.GitUtils;-import com.pmease.commons.hibernate.AbstractEntity;-import com.pmease.commons.hibernate.dao.Dao;-import com.pmease.commons.hibernate.dao.EntityCriteria;-import com.pmease.commons.jackson.ExternalView;-import com.pmease.commons.util.LockUtils;-import com.pmease.gitplex.core.GitPlex;-import com.pmease.gitplex.core.gatekeeper.checkresult.Blocking;-import com.pmease.gitplex.core.gatekeeper.checkresult.CheckResult;-import com.pmease.gitplex.core.gatekeeper.checkresult.Failed;-import com.pmease.gitplex.core.gatekeeper.checkresult.Pending;-import com.pmease.gitplex.core.manager.PullRequestManager;-import com.pmease.gitplex.core.manager.ReviewManager;-import com.pmease.gitplex.core.permission.ObjectPermission;--/*- * @DynamicUpdate annotation here along with various @OptimisticLock annotations- * on certain fields tell Hibernate not to perform version check on those fields- * which can be updated from background thread.- */-@SuppressWarnings("serial")-@Entity-@DynamicUpdate-public class PullRequest extends AbstractEntity {-- public enum Status {- PENDING_APPROVAL("Pending Approval"),- PENDING_UPDATE("Pending Update"), PENDING_INTEGRATE("Pending Integration"),- INTEGRATED("Integrated"), DISCARDED("Discarded");-- private final String displayName;-- Status(String displayName) {- this.displayName = displayName;- }-- @Override- public String toString() {- return displayName;- }-- }-- public enum IntegrationStrategy {- MERGE_ALWAYS("Merge always",- "Always create merge commit when integrate into target branch"),- MERGE_IF_NECESSARY("Merge if necessary",- "Create merge commit only if target branch can not be fast-forwarded to the pull request"),- MERGE_WITH_SQUASH("Merge with squash",- "Squash all commits in the pull request and then merge with target branch"),- REBASE_SOURCE_ONTO_TARGET("Rebase source onto target",- "Rebase source branch onto target branch and then fast-forward target branch to source branch"),- REBASE_TARGET_ONTO_SOURCE("Rebase target onto source",- "Rebase target branch onto source branch");-- private final String displayName;-- private final String description;-- IntegrationStrategy(String displayName, String description) {- this.displayName = displayName;- this.description = description;- }-- public String getDisplayName() {- return displayName;- }-- public String getDescription() {- return description;- }-- @Override- public String toString() {- return displayName;- }-- }-- public enum Event {- OPENED("Newly opened"),- REVIEWED("New reviews in"),- VERIFIED("Build verification is finished for"),- UPDATED("New commits in"),- COMMENTED("New comments in"),- INTEGRATION_STRATEGY_CHANGED("Integration strategy is changed"),- INTEGRATED("Integration is done for"),- DISCARDED("Discarded"),- REOPENED("Reopened"),- INTEGRATION_PREVIEW_CALCULATED("Integration preview is calculated"),- ASSIGNED("Assigned"),- REVIEWER_CHANGED("Reviewer changed"),- REVIEW_REMOVED("Review removed"),- COMMENT_REPLIED("Comment is replied");-- private final String displayName;-- Event(String displayName) {- this.displayName = displayName;- }-- public String toString() {- return displayName;- }-- };-- @Embedded- private CloseInfo closeInfo;-- @Index(name="PR_TITLE")- @Column(nullable=false)- private String title;-- @Lob- @Column(length=65535)- private String description;-- @ManyToOne(fetch=FetchType.LAZY)- private User submitter;-- @ManyToOne(fetch=FetchType.LAZY)- @JoinColumn(nullable=false)- private Repository targetRepo;-- @Column(nullable=false)- private String targetBranch;-- @ManyToOne(fetch=FetchType.LAZY)- private Repository sourceRepo;-- @Column(nullable=false)- private String sourceBranch;-- @Column(nullable=false)- private String baseCommitHash;-- @ManyToOne(fetch=FetchType.LAZY)- private User assignee;-- // used for id search in markdown editor- @Index(name="PR_ID_STR")- @Column(nullable=false)- private String idStr;-- // used for title search in markdown editor- @Index(name="PR_NO_SP_TITLE")- @Column(nullable=false)- private String noSpaceTitle;-- @Version- private long version;-- @Transient- private Git sandbox;-- @OptimisticLock(excluded=true)- @Embedded- private IntegrationPreview lastIntegrationPreview;-- @Column(nullable=false)- private Date submitDate = new Date();-- @OptimisticLock(excluded=true)- @Column(nullable=false)- private Date lastEventDate = new Date();-- @OptimisticLock(excluded=true)- @Column(nullable=false)- private Event lastEvent = Event.OPENED;-- @Column(nullable=false)- private IntegrationStrategy integrationStrategy;-- @OneToMany(mappedBy="request")- @OnDelete(action=OnDeleteAction.CASCADE)- private Collection<PullRequestUpdate> updates = new ArrayList<>();-- @OneToMany(mappedBy="request")- @OnDelete(action=OnDeleteAction.CASCADE)- private Collection<ReviewInvitation> reviewInvitations = new ArrayList<>();-- @OneToMany(mappedBy="referenced")- @OnDelete(action=OnDeleteAction.CASCADE)- private Collection<PullRequestReference> referencedBy = new ArrayList<>();-- @OneToMany(mappedBy="referencedBy")- @OnDelete(action=OnDeleteAction.CASCADE)- private Collection<PullRequestReference> referenced = new ArrayList<>();-- @OneToMany(mappedBy="request")- @OnDelete(action=OnDeleteAction.CASCADE)- private Collection<Verification> verifications = new ArrayList<>();-- @OneToMany(mappedBy="request")- @OnDelete(action=OnDeleteAction.CASCADE)- private Collection<Comment> comments = new ArrayList<>();-- @OneToMany(mappedBy="request")- @OnDelete(action=OnDeleteAction.CASCADE)- private Collection<PullRequestActivity> activities = new ArrayList<>();-- @OneToMany(mappedBy="request")- @OnDelete(action=OnDeleteAction.CASCADE)- private Collection<Notification> notifications = new ArrayList<>();-- @OneToMany(mappedBy="request")- @OnDelete(action=OnDeleteAction.CASCADE)- private Collection<PullRequestVisit> visits = new ArrayList<>();-- @OneToMany(mappedBy="request")- @OnDelete(action=OnDeleteAction.CASCADE)- private Collection<PullRequestWatch> watches = new ArrayList<>();-- private transient CheckResult checkResult;-- private transient List<PullRequestUpdate> sortedUpdates;-- private transient List<PullRequestUpdate> effectiveUpdates;-- private transient PullRequestUpdate referentialUpdate;-- private transient Set<String> pendingCommits;-- private transient Collection<Commit> mergedCommits;-- private transient Collection<CommentReply> commentReplies;-- private transient List<Review> reviews;-- /**- * Get title of this merge request.- *- * @return user specified title of this merge request, <tt>null</tt> for- * auto-created merge request.- */- public @Nullable String getTitle() {- return title;- }-- public void setTitle(String title) {- this.title = title;- noSpaceTitle = StringUtils.deleteWhitespace(title);- }-- public String getDescription() {- return description;- }-- public void setDescription(String description) {- this.description = description;- }-- /**- * Get the user submitting the pull request.- *- * @return- * the user submitting the pull request, or <tt>null</tt> if unknown- */- @Nullable- public User getSubmitter() {- return submitter;- }-- public void setSubmitter(@Nullable User submitter) {- this.submitter = submitter;- }-- /**- * Get the user responsible for integration of the pull request.- *- * @return- * the user responsible for integration of this pull request, or <tt>null</tt> to have the- * system integrate the pull request automatically- */- @Nullable- public User getAssignee() {- return assignee;- }-- public void setAssignee(User assignee) {- this.assignee = assignee;- }-- public Repository getTargetRepo() {- return targetRepo;- }-- public RepoAndBranch getTarget() {- return new RepoAndBranch(getTargetRepo(), getTargetBranch());- }-- public void setTarget(RepoAndBranch target) {- setTargetRepo(target.getRepository());- setTargetBranch(target.getBranch());- }-- public void setSource(RepoAndBranch source) {- setSourceRepo(source.getRepository());- setSourceBranch(source.getBranch());- }-- public void setTargetRepo(Repository targetRepo) {- this.targetRepo = targetRepo;- }-- public String getTargetBranch() {- return targetBranch;- }-- public void setTargetBranch(String targetBranch) {- this.targetBranch = targetBranch;- }-- @Nullable- public Repository getSourceRepo() {- return sourceRepo;- }-- public void setSourceRepo(Repository sourceRepo) {- this.sourceRepo = sourceRepo;- }-- public String getSourceBranch() {- return sourceBranch;- }-- public void setSourceBranch(String sourceBranch) {- this.sourceBranch = sourceBranch;- }-- public RepoAndBranch getSource() {- return new RepoAndBranch(getSourceRepo(), getSourceBranch());- }-- public String getTargetRef() {- return GitUtils.branch2ref(getTargetBranch());- }-- public String getSourceRef() {- return GitUtils.branch2ref(getSourceBranch());- }-- public String getBaseCommitHash() {- return baseCommitHash;- }-- public void setBaseCommitHash(String baseCommitHash) {- this.baseCommitHash = baseCommitHash;- }-- public Commit getBaseCommit() {- return getTargetRepo().getCommit(getBaseCommitHash());- }-- public Git git() {- if (sandbox == null)- return getTargetRepo().git();- else- return sandbox;- }-- public Git getSandbox() {- return sandbox;- }-- public void setSandbox(Git sandbox) {- this.sandbox = sandbox;- }-- /**- * Get unmodifiable collection of updates of this pull request. To add update- * to the pull request, call {@link this#addUpdate(PullRequestUpdate)} instead.- *- * @return- * unmodifiable collection of updates- */- public Collection<PullRequestUpdate> getUpdates() {- return Collections.unmodifiableCollection(updates);- }-- public void setUpdates(Collection<PullRequestUpdate> updates) {- this.updates = updates;- sortedUpdates = null;- effectiveUpdates = null;- }-- public void addUpdate(PullRequestUpdate update) {- updates.add(update);- sortedUpdates = null;- effectiveUpdates = null;- }-- public Collection<ReviewInvitation> getReviewInvitations() {- return reviewInvitations;- }-- public void setReviewInvitations(Collection<ReviewInvitation> reviewInvitations) {- this.reviewInvitations = reviewInvitations;- }-- public Collection<Verification> getVerifications() {- return verifications;- }-- public void setVerifications(Collection<Verification> verifications) {- this.verifications = verifications;- }-- public Collection<PullRequestReference> getReferencedBy() {- return referencedBy;- }-- public void setReferencedBy(Collection<PullRequestReference> referencedBy) {- this.referencedBy = referencedBy;- }-- public Collection<PullRequestReference> getReferenced() {- return referenced;- }-- public void setReferenced(Collection<PullRequestReference> referenced) {- this.referenced = referenced;- }-- public Collection<Comment> getComments() {- return comments;- }-- public void setComments(Collection<Comment> comments) {- this.comments = comments;- }-- public Collection<PullRequestActivity> getActivities() {- return activities;- }-- public void setActivities(Collection<PullRequestActivity> activities) {- this.activities = activities;- }-- public Collection<Notification> getNotifications() {- return notifications;- }-- public void setNotifications(Collection<Notification> notifications) {- this.notifications = notifications;- }-- public Collection<PullRequestVisit> getVisits() {- return visits;- }-- public void setVisits(Collection<PullRequestVisit> visits) {- this.visits = visits;- }-- public Collection<PullRequestWatch> getWatches() {- return watches;- }-- public void setWatches(Collection<PullRequestWatch> watches) {- this.watches = watches;- }-- public Status getStatus() {- if (closeInfo != null) {- if (closeInfo.getCloseStatus() == CloseInfo.Status.INTEGRATED)- return Status.INTEGRATED;- else- return Status.DISCARDED;- } else if (getCheckResult() instanceof Pending || getCheckResult() instanceof Blocking)- return Status.PENDING_APPROVAL;- else if (getCheckResult() instanceof Failed)- return Status.PENDING_UPDATE;- else- return Status.PENDING_INTEGRATE;- }-- @Nullable- public CloseInfo getCloseInfo() {- return closeInfo;- }-- public void setCloseInfo(CloseInfo closeInfo) {- this.closeInfo = closeInfo;- }-- public boolean isOpen() {- return closeInfo == null;- }-- public PullRequestUpdate getReferentialUpdate() {- if (referentialUpdate != null)- return referentialUpdate;- else- return getEffectiveUpdates().get(0);- }-- public void setReferentialUpdate(PullRequestUpdate referentiralUpdate) {- this.referentialUpdate = referentiralUpdate;- }-- /**- * Get gate keeper check result.- *- * @return- * check result of this pull request has not been refreshed yet- */- public CheckResult getCheckResult() {- if (checkResult == null)- checkResult = getTargetRepo().getGateKeeper().checkRequest(this);- return checkResult;- }-- /**- * Get last integration preview of this pull request. Note that this method may return an- * out dated integration preview. Refer to {@link this#getIntegrationPreview()}- * if you'd like to get an update-to-date integration preview- *- * @return- * integration preview of this pull request, or <tt>null</tt> if integration- * preview has not been calculated yet.- */- @Nullable- public IntegrationPreview getLastIntegrationPreview() {- return lastIntegrationPreview;- }-- public void setLastIntegrationPreview(IntegrationPreview lastIntegrationPreview) {- this.lastIntegrationPreview = lastIntegrationPreview;- }-- /**- * Get effective integration preview of this pull request.- *- * @return- * update to date integration preview of this pull request, or <tt>null</tt> if- * the integration preview has not been calculated or out dated. In both cases,- * it will trigger a re-calculation, and client should call this method later- * to get the calculated result- */- @JsonView(ExternalView.class)- @Nullable- public IntegrationPreview getIntegrationPreview() {- return GitPlex.getInstance(PullRequestManager.class).previewIntegration(this);- }-- /**- * Get list of sorted updates.- *- * @return- * list of sorted updates ordered by id- */- public List<PullRequestUpdate> getSortedUpdates() {- if (sortedUpdates == null) {- Preconditions.checkState(updates.size() >= 1);- sortedUpdates = new ArrayList<PullRequestUpdate>(updates);- Collections.sort(sortedUpdates);- }- return sortedUpdates;- }-- /**- * Get list of effective updates reversely sorted by id. Update is considered effective if it is- * not ancestor of target branch head.- *- * @return- * list of effective updates reversely sorted by id- */- public List<PullRequestUpdate> getEffectiveUpdates() {- Preconditions.checkState(isOpen(), "Can only be called while request is open");- if (effectiveUpdates == null) {- effectiveUpdates = new ArrayList<PullRequestUpdate>();-- for (int i=getSortedUpdates().size()-1; i>=0; i--) {- PullRequestUpdate update = getSortedUpdates().get(i);- if (!getTargetRepo().isAncestor(update.getHeadCommitHash(), getTarget().getHead()))- effectiveUpdates.add(update);- else- break;- }-- Preconditions.checkState(!effectiveUpdates.isEmpty());- }- return effectiveUpdates;- }-- public IntegrationStrategy getIntegrationStrategy() {- return integrationStrategy;- }-- public void setIntegrationStrategy(IntegrationStrategy integrationStrategy) {- this.integrationStrategy = integrationStrategy;- }-- @JsonView(ExternalView.class)- public PullRequestUpdate getLatestUpdate() {- return getSortedUpdates().get(getSortedUpdates().size()-1);- }-- public Collection<String> findTouchedFiles() {- Git git = getTargetRepo().git();- return git.listChangedFiles(getTarget().getHead(), getLatestUpdate().getHeadCommitHash(), null);- }-- @JsonView(ExternalView.class)- public String getBaseRef() {- Preconditions.checkNotNull(getId());- return Repository.REFS_GITPLEX + "pulls/" + getId() + "/base";- }-- @JsonView(ExternalView.class)- public String getIntegrateRef() {- Preconditions.checkNotNull(getId());- return Repository.REFS_GITPLEX + "pulls/" + getId() + "/integrate";- }-- /**- * Delete refs of this pull request, without touching refs of its updates.- */- public void deleteRefs() {- Git git = getTargetRepo().git();- git.deleteRef(getBaseRef(), null, null);- git.deleteRef(getIntegrateRef(), null, null);- }-- public <T> T lockAndCall(Callable<T> callable) {- Preconditions.checkNotNull(getId());-- return LockUtils.call("pull request: " + getId(), callable);- }-- /**- * Invite specified number of users in candidates to review this request.- * <p>- *- * @param candidates- * a collection of users to invite users from- * @param count- * number of users to invite- */- public void pickReviewers(Collection<User> candidates, int count) {- List<User> pickList = new ArrayList<User>(candidates);-- /*- * users already reviewed since base update should be excluded from- * invitation list as their reviews are still valid- */- for (Review review: getReferentialUpdate().listReviewsOnwards())- pickList.remove(review.getReviewer());-- final Map<User, Date> firstChoices = new HashMap<>();- final Map<User, Date> secondChoices = new HashMap<>();-- for (ReviewInvitation invitation: getReviewInvitations()) {- if (invitation.isPreferred())- firstChoices.put(invitation.getReviewer(), invitation.getDate());- else- secondChoices.put(invitation.getReviewer(), invitation.getDate());- }-- // submitter is not preferred- if (getSubmitter() != null)- secondChoices.put(getSubmitter(), new Date());-- /* Follow below rules to pick reviewers:- * 1. If user is excluded previously, it will be considered last.- * 2. If user is already a reviewer, it will be considered first.- * 3. Otherwise pick user with least reviews.- */- Collections.sort(pickList, new Comparator<User>() {-- @Override- public int compare(User user1, User user2) {- if (firstChoices.containsKey(user1)) {- if (firstChoices.containsKey(user2))- return user1.getReviewEffort() - user2.getReviewEffort();- else- return -1;- } else if (firstChoices.containsKey(user2)) {- return 1;- } else if (secondChoices.containsKey(user1)) {- if (secondChoices.containsKey(user2))- return secondChoices.get(user1).compareTo(secondChoices.get(user2));- else- return 1;- } else if (secondChoices.containsKey(user2)) {- return -1;- } else {- return user1.getReviewEffort() - user2.getReviewEffort();- }- }-- });-- List<User> picked;- if (count <= pickList.size())- picked = pickList.subList(0, count);- else- picked = pickList;-- for (User user: picked) {- boolean found = false;- for (ReviewInvitation invitation: getReviewInvitations()) {- if (invitation.getReviewer().equals(user)) {- invitation.setDate(new Date());- invitation.setPerferred(true);- found = true;- }- }- if (!found) {- ReviewInvitation invitation = new ReviewInvitation();- invitation.setRequest(this);- invitation.setReviewer(user);- getReviewInvitations().add(invitation);- }- }-- }-- public static class CriterionHelper {- public static Criterion ofOpen() {- return Restrictions.isNull("closeInfo");- }-- public static Criterion ofClosed() {- return Restrictions.isNotNull("closeInfo");- }-- public static Criterion ofTarget(RepoAndBranch target) {- return Restrictions.and(- Restrictions.eq("targetRepo", target.getRepository()),- Restrictions.eq("targetBranch", target.getBranch()));- }-- public static Criterion ofSource(RepoAndBranch source) {- return Restrictions.and(- Restrictions.eq("sourceRepo", source.getRepository()),- Restrictions.eq("sourceBranch", source.getBranch()));- }-- public static Criterion ofSubmitter(User submitter) {- return Restrictions.eq("submitter", submitter);- }-- }-- public Date getSubmitDate() {- return submitDate;- }-- public void setSubmitDate(Date submitDate) {- this.submitDate = submitDate;- }-- public Date getLastEventDate() {- return lastEventDate;- }-- public void setLastEventDate(Date lastEventDate) {- this.lastEventDate = lastEventDate;- }-- public Event getLastEvent() {- return lastEvent;- }-- public void setLastEvent(Event lastEvent) {- this.lastEvent = lastEvent;- }-- /**- * Get commits pending integration.- *- * @return- * commits pending integration- */- public Set<String> getPendingCommits() {- if (pendingCommits == null) {- pendingCommits = new HashSet<>();- Repository repo = getTargetRepo();- for (Commit commit: repo.git().log(getTarget().getHead(), getLatestUpdate().getHeadCommitHash(), null, 0, 0, false))- pendingCommits.add(commit.getHash());- }- return pendingCommits;- }-- public List<String> getCommentables() {- List<String> commentables = new ArrayList<>();- commentables.add(getBaseCommitHash());- for (PullRequestUpdate update: getSortedUpdates()) {- for (Commit commit: update.getCommits())- commentables.add(commit.getHash());- }- return commentables;- }-- /**- * Merged commits represent commits already merged to target branch since base commit.- *- * @return- * commits already merged to target branch since base commit- */- public Collection<Commit> getMergedCommits() {- if (mergedCommits == null) {- mergedCommits = new HashSet<>();-- Repository repo = getTargetRepo();- for (Commit commit: repo.git().log(getBaseCommitHash(), getTarget().getHead(), null, 0, 0, false))- mergedCommits.add(commit);- }- return mergedCommits;- }-- private Collection<CommentReply> getCommentReplies() {- if (commentReplies == null) {- EntityCriteria<CommentReply> criteria = EntityCriteria.of(CommentReply.class);- criteria.createCriteria("comment").add(Restrictions.eq("request", this));- commentReplies = GitPlex.getInstance(Dao.class).query(criteria);- }- return commentReplies;- }-- /**- * This method is here for performance consideration. Often we need to load replies of- * different comments in a pull request. And we optimize it to load all replies at once- * for all comments in a pull request to reduce SQL queries.- *- * @param comment- * @return- */- public Collection<CommentReply> getCommentReplies(Comment comment) {- List<CommentReply> replies = new ArrayList<>();- for (CommentReply reply: getCommentReplies()) {- if (reply.getComment().equals(comment))- replies.add(reply);- }- return replies;- }-- public List<Review> getReviews() {- if (reviews == null) {- if (!isNew())- reviews = GitPlex.getInstance(ReviewManager.class).findBy(this);- else- reviews = new ArrayList<>();- }- return reviews;- }-- /**- * This method is here for performance consideration. Often we need to load reviews of- * different updates in a pull request. And we optimize it to load all reviews at once- * for all updates in a pull request to reduce SQL queries.- *- * @param update- * @return- */- public List<Review> getReviews(PullRequestUpdate update) {- List<Review> reviews = new ArrayList<>();- for (Review review: getReviews()) {- if (review.getUpdate().equals(update))- reviews.add(review);- }- return reviews;- }-- public boolean isReviewEffective(User user) {- for (Review review: getReviews()) {- if (review.getUpdate().equals(getLatestUpdate()) && review.getReviewer().equals(user))- return true;- }- return false;- }-- /**- * Calculate list of users can be added as reviewers of this pull request.- *- * @return- * list of potential reviewers- */- public List<User> getPotentialReviewers() {- List<User> reviewers = new ArrayList<>();- Set<User> alreadyInvited = new HashSet<>();- for (ReviewInvitation invitation: getReviewInvitations()) {- if (invitation.isPreferred())- alreadyInvited.add(invitation.getReviewer());- }- ObjectPermission readPerm = ObjectPermission.ofRepoPull(getTargetRepo());- for (User user: GitPlex.getInstance(Dao.class).allOf(User.class)) {- if (user.asSubject().isPermitted(readPerm) && !alreadyInvited.contains(user))- reviewers.add(user);- }- return reviewers;- }-- @Nullable- public PullRequestWatch getWatch(User user) {- for (PullRequestWatch watch: getWatches()) {- if (watch.getUser().equals(user))- return watch;- }- return null;- }-- @Nullable- public PullRequestVisit getVisit(User user) {- for (PullRequestVisit visit: getVisits()) {- if (visit.getUser().equals(user))- return visit;- }- return null;- }-- public String getUrl() {- return GitPlex.getInstance().guessServerUrl() + "/" + getTargetRepo().getFQN()- + "/pull_requests/" + getId() + "/overview";- }-- @PrePersist- public void prePersist() {- idStr = getId().toString();- }-- public String getIdStr() {- return idStr;- }-- public String getNoSpaceTitle() {- return noSpaceTitle;- }-- public long getVersion() {- return version;- }--}+package com.pmease.gitplex.core.model;++import java.util.ArrayList;+import java.util.Collection;+import java.util.Collections;+import java.util.Comparator;+import java.util.Date;+import java.util.HashMap;+import java.util.HashSet;+import java.util.List;+import java.util.Map;+import java.util.Set;+import java.util.concurrent.Callable;++import javax.annotation.Nullable;+import javax.persistence.Column;+import javax.persistence.Embedded;+import javax.persistence.Entity;+import javax.persistence.FetchType;+import javax.persistence.JoinColumn;+import javax.persistence.Lob;+import javax.persistence.ManyToOne;+import javax.persistence.OneToMany;+import javax.persistence.PrePersist;+import javax.persistence.Transient;+import javax.persistence.Version;++import org.apache.commons.lang3.StringUtils;+import org.hibernate.annotations.DynamicUpdate;+import org.hibernate.annotations.Index;+import org.hibernate.annotations.OnDelete;+import org.hibernate.annotations.OnDeleteAction;+import org.hibernate.annotations.OptimisticLock;+import org.hibernate.criterion.Criterion;+import org.hibernate.criterion.Restrictions;++import com.fasterxml.jackson.annotation.JsonView;+import com.google.common.base.Preconditions;+import com.pmease.commons.git.Commit;+import com.pmease.commons.git.Git;+import com.pmease.commons.git.GitUtils;+import com.pmease.commons.hibernate.AbstractEntity;+import com.pmease.commons.hibernate.dao.Dao;+import com.pmease.commons.hibernate.dao.EntityCriteria;+import com.pmease.commons.jackson.ExternalView;+import com.pmease.commons.util.LockUtils;+import com.pmease.gitplex.core.GitPlex;+import com.pmease.gitplex.core.gatekeeper.checkresult.Blocking;+import com.pmease.gitplex.core.gatekeeper.checkresult.CheckResult;+import com.pmease.gitplex.core.gatekeeper.checkresult.Failed;+import com.pmease.gitplex.core.gatekeeper.checkresult.Pending;+import com.pmease.gitplex.core.manager.PullRequestManager;+import com.pmease.gitplex.core.manager.ReviewManager;+import com.pmease.gitplex.core.permission.ObjectPermission;++/*+ * @DynamicUpdate annotation here along with various @OptimisticLock annotations+ * on certain fields tell Hibernate not to perform version check on those fields+ * which can be updated from background thread.+ */+@SuppressWarnings("serial")+@Entity+@DynamicUpdate+public class PullRequest extends AbstractEntity {++ public enum Status {+ PENDING_APPROVAL("Pending Approval"),+ PENDING_UPDATE("Pending Update"), PENDING_INTEGRATE("Pending Integration"),+ INTEGRATED("Integrated"), DISCARDED("Discarded");++ private final String displayName;++ Status(String displayName) {+ this.displayName = displayName;+ }++ @Override+ public String toString() {+ return displayName;+ }++ }++ public enum IntegrationStrategy {+ MERGE_ALWAYS("Merge always",+ "Always create merge commit when integrate into target branch"),+ MERGE_IF_NECESSARY("Merge if necessary",+ "Create merge commit only if target branch can not be fast-forwarded to the pull request"),+ MERGE_WITH_SQUASH("Merge with squash",+ "Squash all commits in the pull request and then merge with target branch"),+ REBASE_SOURCE_ONTO_TARGET("Rebase source onto target",+ "Rebase source branch onto target branch and then fast-forward target branch to source branch"),+ REBASE_TARGET_ONTO_SOURCE("Rebase target onto source",+ "Rebase target branch onto source branch");++ private final String displayName;++ private final String description;++ IntegrationStrategy(String displayName, String description) {+ this.displayName = displayName;+ this.description = description;+ }++ public String getDisplayName() {+ return displayName;+ }++ public String getDescription() {+ return description;+ }++ @Override+ public String toString() {+ return displayName;+ }++ }++ public enum Event {+ OPENED("Newly opened"),+ REVIEWED("New reviews in"),+ VERIFIED("Build verification is finished for"),+ UPDATED("New commits in"),+ COMMENTED("New comments in"),+ INTEGRATION_STRATEGY_CHANGED("Integration strategy is changed"),+ INTEGRATED("Integration is done for"),+ DISCARDED("Discarded"),+ REOPENED("Reopened"),+ INTEGRATION_PREVIEW_CALCULATED("Integration preview is calculated"),+ ASSIGNED("Assigned"),+ REVIEWER_CHANGED("Reviewer changed"),+ REVIEW_REMOVED("Review removed"),+ COMMENT_REPLIED("Comment is replied");++ private final String displayName;++ Event(String displayName) {+ this.displayName = displayName;+ }++ public String toString() {+ return displayName;+ }++ };++ @Embedded+ private CloseInfo closeInfo;++ @Index(name="PR_TITLE")+ @Column(nullable=false)+ private String title;++ @Lob+ @Column(length=65535)+ private String description;++ @ManyToOne(fetch=FetchType.LAZY)+ private User submitter;++ @ManyToOne(fetch=FetchType.LAZY)+ @JoinColumn(nullable=false)+ private Repository targetRepo;++ @Column(nullable=false)+ private String targetBranch;++ @ManyToOne(fetch=FetchType.LAZY)+ private Repository sourceRepo;++ @Column(nullable=false)+ private String sourceBranch;++ @Column(nullable=false)+ private String baseCommitHash;++ @ManyToOne(fetch=FetchType.LAZY)+ private User assignee;++ // used for id search in markdown editor+ @Index(name="PR_ID_STR")+ @Column(nullable=false)+ private String idStr;++ // used for title search in markdown editor+ @Index(name="PR_NO_SP_TITLE")+ @Column(nullable=false)+ private String noSpaceTitle;++ @Version+ private long version;++ @Transient+ private Git sandbox;++ @OptimisticLock(excluded=true)+ @Embedded+ private IntegrationPreview lastIntegrationPreview;++ @Column(nullable=false)+ private Date submitDate = new Date();++ @OptimisticLock(excluded=true)+ @Column(nullable=false)+ private Date lastEventDate = new Date();++ @OptimisticLock(excluded=true)+ @Column(nullable=false)+ private Event lastEvent = Event.OPENED;++ @Column(nullable=false)+ private IntegrationStrategy integrationStrategy;++ @OneToMany(mappedBy="request")+ @OnDelete(action=OnDeleteAction.CASCADE)+ private Collection<PullRequestUpdate> updates = new ArrayList<>();++ @OneToMany(mappedBy="request")+ @OnDelete(action=OnDeleteAction.CASCADE)+ private Collection<ReviewInvitation> reviewInvitations = new ArrayList<>();++ @OneToMany(mappedBy="referenced")+ @OnDelete(action=OnDeleteAction.CASCADE)+ private Collection<PullRequestReference> referencedBy = new ArrayList<>();++ @OneToMany(mappedBy="referencedBy")+ @OnDelete(action=OnDeleteAction.CASCADE)+ private Collection<PullRequestReference> referenced = new ArrayList<>();++ @OneToMany(mappedBy="request")+ @OnDelete(action=OnDeleteAction.CASCADE)+ private Collection<Verification> verifications = new ArrayList<>();++ @OneToMany(mappedBy="request")+ @OnDelete(action=OnDeleteAction.CASCADE)+ private Collection<Comment> comments = new ArrayList<>();++ @OneToMany(mappedBy="request")+ @OnDelete(action=OnDeleteAction.CASCADE)+ private Collection<PullRequestActivity> activities = new ArrayList<>();++ @OneToMany(mappedBy="request")+ @OnDelete(action=OnDeleteAction.CASCADE)+ private Collection<Notification> notifications = new ArrayList<>();++ @OneToMany(mappedBy="request")+ @OnDelete(action=OnDeleteAction.CASCADE)+ private Collection<PullRequestVisit> visits = new ArrayList<>();++ @OneToMany(mappedBy="request")+ @OnDelete(action=OnDeleteAction.CASCADE)+ private Collection<PullRequestWatch> watches = new ArrayList<>();++ private transient CheckResult checkResult;++ private transient List<PullRequestUpdate> sortedUpdates;++ private transient List<PullRequestUpdate> effectiveUpdates;++ private transient PullRequestUpdate referentialUpdate;++ private transient Set<String> pendingCommits;++ private transient Collection<Commit> mergedCommits;++ private transient Collection<CommentReply> commentReplies;++ private transient List<Review> reviews;++ /**+ * Get title of this merge request.+ *+ * @return user specified title of this merge request, <tt>null</tt> for+ * auto-created merge request.+ */+ public @Nullable String getTitle() {+ return title;+ }++ public void setTitle(String title) {+ this.title = title;+ noSpaceTitle = StringUtils.deleteWhitespace(title);+ }++ public String getDescription() {+ return description;+ }++ public void setDescription(String description) {+ this.description = description;+ }++ /**+ * Get the user submitting the pull request.+ *+ * @return+ * the user submitting the pull request, or <tt>null</tt> if unknown+ */+ @Nullable+ public User getSubmitter() {+ return submitter;+ }++ public void setSubmitter(@Nullable User submitter) {+ this.submitter = submitter;+ }++ /**+ * Get the user responsible for integration of the pull request.+ *+ * @return+ * the user responsible for integration of this pull request, or <tt>null</tt> to have the+ * system integrate the pull request automatically+ */+ @Nullable+ public User getAssignee() {+ return assignee;+ }++ public void setAssignee(User assignee) {+ this.assignee = assignee;+ }++ public Repository getTargetRepo() {+ return targetRepo;+ }++ public RepoAndBranch getTarget() {+ return new RepoAndBranch(getTargetRepo(), getTargetBranch());+ }++ public void setTarget(RepoAndBranch target) {+ setTargetRepo(target.getRepository());+ setTargetBranch(target.getBranch());+ }++ public void setSource(RepoAndBranch source) {+ setSourceRepo(source.getRepository());+ setSourceBranch(source.getBranch());+ }++ public void setTargetRepo(Repository targetRepo) {+ this.targetRepo = targetRepo;+ }++ public String getTargetBranch() {+ return targetBranch;+ }++ public void setTargetBranch(String targetBranch) {+ this.targetBranch = targetBranch;+ }++ @Nullable+ public Repository getSourceRepo() {+ return sourceRepo;+ }++ public void setSourceRepo(Repository sourceRepo) {+ this.sourceRepo = sourceRepo;+ }++ public String getSourceBranch() {+ return sourceBranch;+ }++ public void setSourceBranch(String sourceBranch) {+ this.sourceBranch = sourceBranch;+ }++ public RepoAndBranch getSource() {+ return new RepoAndBranch(getSourceRepo(), getSourceBranch());+ }++ public String getTargetRef() {+ return GitUtils.branch2ref(getTargetBranch());+ }++ public String getSourceRef() {+ return GitUtils.branch2ref(getSourceBranch());+ }++ public String getBaseCommitHash() {+ return baseCommitHash;+ }++ public void setBaseCommitHash(String baseCommitHash) {+ this.baseCommitHash = baseCommitHash;+ }++ public Commit getBaseCommit() {+ return getTargetRepo().getCommit(getBaseCommitHash());+ }++ public Git git() {+ if (sandbox == null)+ return getTargetRepo().git();+ else+ return sandbox;+ }++ public Git getSandbox() {+ return sandbox;+ }++ public void setSandbox(Git sandbox) {+ this.sandbox = sandbox;+ }++ /**+ * Get unmodifiable collection of updates of this pull request. To add update+ * to the pull request, call {@link this#addUpdate(PullRequestUpdate)} instead.+ *+ * @return+ * unmodifiable collection of updates+ */+ public Collection<PullRequestUpdate> getUpdates() {+ return Collections.unmodifiableCollection(updates);+ }++ public void setUpdates(Collection<PullRequestUpdate> updates) {+ this.updates = updates;+ sortedUpdates = null;+ effectiveUpdates = null;+ }++ public void addUpdate(PullRequestUpdate update) {+ updates.add(update);+ sortedUpdates = null;+ effectiveUpdates = null;+ }++ public Collection<ReviewInvitation> getReviewInvitations() {+ return reviewInvitations;+ }++ public void setReviewInvitations(Collection<ReviewInvitation> reviewInvitations) {+ this.reviewInvitations = reviewInvitations;+ }++ public Collection<Verification> getVerifications() {+ return verifications;+ }++ public void setVerifications(Collection<Verification> verifications) {+ this.verifications = verifications;+ }++ public Collection<PullRequestReference> getReferencedBy() {+ return referencedBy;+ }++ public void setReferencedBy(Collection<PullRequestReference> referencedBy) {+ this.referencedBy = referencedBy;+ }++ public Collection<PullRequestReference> getReferenced() {+ return referenced;+ }++ public void setReferenced(Collection<PullRequestReference> referenced) {+ this.referenced = referenced;+ }++ public Collection<Comment> getComments() {+ return comments;+ }++ public void setComments(Collection<Comment> comments) {+ this.comments = comments;+ }++ public Collection<PullRequestActivity> getActivities() {+ return activities;+ }++ public void setActivities(Collection<PullRequestActivity> activities) {+ this.activities = activities;+ }++ public Collection<Notification> getNotifications() {+ return notifications;+ }++ public void setNotifications(Collection<Notification> notifications) {+ this.notifications = notifications;+ }++ public Collection<PullRequestVisit> getVisits() {+ return visits;+ }++ public void setVisits(Collection<PullRequestVisit> visits) {+ this.visits = visits;+ }++ public Collection<PullRequestWatch> getWatches() {+ return watches;+ }++ public void setWatches(Collection<PullRequestWatch> watches) {+ this.watches = watches;+ }++ public Status getStatus() {+ if (closeInfo != null) {+ if (closeInfo.getCloseStatus() == CloseInfo.Status.INTEGRATED)+ return Status.INTEGRATED;+ else+ return Status.DISCARDED;+ } else if (getCheckResult() instanceof Pending || getCheckResult() instanceof Blocking)+ return Status.PENDING_APPROVAL;+ else if (getCheckResult() instanceof Failed)+ return Status.PENDING_UPDATE;+ else+ return Status.PENDING_INTEGRATE;+ }++ @Nullable+ public CloseInfo getCloseInfo() {+ return closeInfo;+ }++ public void setCloseInfo(CloseInfo closeInfo) {+ this.closeInfo = closeInfo;+ }++ public boolean isOpen() {+ return closeInfo == null;+ }++ public PullRequestUpdate getReferentialUpdate() {+ if (referentialUpdate != null)+ return referentialUpdate;+ else+ return getEffectiveUpdates().get(0);+ }++ public void setReferentialUpdate(PullRequestUpdate referentiralUpdate) {+ this.referentialUpdate = referentiralUpdate;+ }++ /**+ * Get gate keeper check result.+ *+ * @return+ * check result of this pull request has not been refreshed yet+ */+ public CheckResult getCheckResult() {+ if (checkResult == null)+ checkResult = getTargetRepo().getGateKeeper().checkRequest(this);+ return checkResult;+ }++ /**+ * Get last integration preview of this pull request. Note that this method may return an+ * out dated integration preview. Refer to {@link this#getIntegrationPreview()}+ * if you'd like to get an update-to-date integration preview+ *+ * @return+ * integration preview of this pull request, or <tt>null</tt> if integration+ * preview has not been calculated yet.+ */+ @Nullable+ public IntegrationPreview getLastIntegrationPreview() {+ return lastIntegrationPreview;+ }++ public void setLastIntegrationPreview(IntegrationPreview lastIntegrationPreview) {+ this.lastIntegrationPreview = lastIntegrationPreview;+ }++ /**+ * Get effective integration preview of this pull request.+ *+ * @return+ * update to date integration preview of this pull request, or <tt>null</tt> if+ * the integration preview has not been calculated or out dated. In both cases,+ * it will trigger a re-calculation, and client should call this method later+ * to get the calculated result+ */+ @JsonView(ExternalView.class)+ @Nullable+ public IntegrationPreview getIntegrationPreview() {+ return GitPlex.getInstance(PullRequestManager.class).previewIntegration(this);+ }++ /**+ * Get list of sorted updates.+ *+ * @return+ * list of sorted updates ordered by id+ */+ public List<PullRequestUpdate> getSortedUpdates() {+ if (sortedUpdates == null) {+ Preconditions.checkState(updates.size() >= 1);+ sortedUpdates = new ArrayList<PullRequestUpdate>(updates);+ Collections.sort(sortedUpdates);+ }+ return sortedUpdates;+ }++ /**+ * Get list of effective updates reversely sorted by id. Update is considered effective if it is+ * not ancestor of target branch head.+ *+ * @return+ * list of effective updates reversely sorted by id+ */+ public List<PullRequestUpdate> getEffectiveUpdates() {+ Preconditions.checkState(isOpen(), "Can only be called while request is open");+ if (effectiveUpdates == null) {+ effectiveUpdates = new ArrayList<PullRequestUpdate>();++ for (int i=getSortedUpdates().size()-1; i>=0; i--) {+ PullRequestUpdate update = getSortedUpdates().get(i);+ if (!getTargetRepo().isAncestor(update.getHeadCommitHash(), getTarget().getObjectName()))+ effectiveUpdates.add(update);+ else+ break;+ }++ Preconditions.checkState(!effectiveUpdates.isEmpty());+ }+ return effectiveUpdates;+ }++ public IntegrationStrategy getIntegrationStrategy() {+ return integrationStrategy;+ }++ public void setIntegrationStrategy(IntegrationStrategy integrationStrategy) {+ this.integrationStrategy = integrationStrategy;+ }++ @JsonView(ExternalView.class)+ public PullRequestUpdate getLatestUpdate() {+ return getSortedUpdates().get(getSortedUpdates().size()-1);+ }++ public Collection<String> findTouchedFiles() {+ Git git = getTargetRepo().git();+ return git.listChangedFiles(getTarget().getObjectName(), getLatestUpdate().getHeadCommitHash(), null);+ }++ @JsonView(ExternalView.class)+ public String getBaseRef() {+ Preconditions.checkNotNull(getId());+ return Repository.REFS_GITPLEX + "pulls/" + getId() + "/base";+ }++ @JsonView(ExternalView.class)+ public String getIntegrateRef() {+ Preconditions.checkNotNull(getId());+ return Repository.REFS_GITPLEX + "pulls/" + getId() + "/integrate";+ }++ /**+ * Delete refs of this pull request, without touching refs of its updates.+ */+ public void deleteRefs() {+ Git git = getTargetRepo().git();+ git.deleteRef(getBaseRef(), null, null);+ git.deleteRef(getIntegrateRef(), null, null);+ }++ public <T> T lockAndCall(Callable<T> callable) {+ Preconditions.checkNotNull(getId());++ return LockUtils.call("pull request: " + getId(), callable);+ }++ /**+ * Invite specified number of users in candidates to review this request.+ * <p>+ *+ * @param candidates+ * a collection of users to invite users from+ * @param count+ * number of users to invite+ */+ public void pickReviewers(Collection<User> candidates, int count) {+ List<User> pickList = new ArrayList<User>(candidates);++ /*+ * users already reviewed since base update should be excluded from+ * invitation list as their reviews are still valid+ */+ for (Review review: getReferentialUpdate().listReviewsOnwards())+ pickList.remove(review.getReviewer());++ final Map<User, Date> firstChoices = new HashMap<>();+ final Map<User, Date> secondChoices = new HashMap<>();++ for (ReviewInvitation invitation: getReviewInvitations()) {+ if (invitation.isPreferred())+ firstChoices.put(invitation.getReviewer(), invitation.getDate());+ else+ secondChoices.put(invitation.getReviewer(), invitation.getDate());+ }++ // submitter is not preferred+ if (getSubmitter() != null)+ secondChoices.put(getSubmitter(), new Date());++ /* Follow below rules to pick reviewers:+ * 1. If user is excluded previously, it will be considered last.+ * 2. If user is already a reviewer, it will be considered first.+ * 3. Otherwise pick user with least reviews.+ */+ Collections.sort(pickList, new Comparator<User>() {++ @Override+ public int compare(User user1, User user2) {+ if (firstChoices.containsKey(user1)) {+ if (firstChoices.containsKey(user2))+ return user1.getReviewEffort() - user2.getReviewEffort();+ else+ return -1;+ } else if (firstChoices.containsKey(user2)) {+ return 1;+ } else if (secondChoices.containsKey(user1)) {+ if (secondChoices.containsKey(user2))+ return secondChoices.get(user1).compareTo(secondChoices.get(user2));+ else+ return 1;+ } else if (secondChoices.containsKey(user2)) {+ return -1;+ } else {+ return user1.getReviewEffort() - user2.getReviewEffort();+ }+ }++ });++ List<User> picked;+ if (count <= pickList.size())+ picked = pickList.subList(0, count);+ else+ picked = pickList;++ for (User user: picked) {+ boolean found = false;+ for (ReviewInvitation invitation: getReviewInvitations()) {+ if (invitation.getReviewer().equals(user)) {+ invitation.setDate(new Date());+ invitation.setPerferred(true);+ found = true;+ }+ }+ if (!found) {+ ReviewInvitation invitation = new ReviewInvitation();+ invitation.setRequest(this);+ invitation.setReviewer(user);+ getReviewInvitations().add(invitation);+ }+ }++ }++ public static class CriterionHelper {+ public static Criterion ofOpen() {+ return Restrictions.isNull("closeInfo");+ }++ public static Criterion ofClosed() {+ return Restrictions.isNotNull("closeInfo");+ }++ public static Criterion ofTarget(RepoAndBranch target) {+ return Restrictions.and(+ Restrictions.eq("targetRepo", target.getRepository()),+ Restrictions.eq("targetBranch", target.getBranch()));+ }++ public static Criterion ofSource(RepoAndBranch source) {+ return Restrictions.and(+ Restrictions.eq("sourceRepo", source.getRepository()),+ Restrictions.eq("sourceBranch", source.getBranch()));+ }++ public static Criterion ofSubmitter(User submitter) {+ return Restrictions.eq("submitter", submitter);+ }++ }++ public Date getSubmitDate() {+ return submitDate;+ }++ public void setSubmitDate(Date submitDate) {+ this.submitDate = submitDate;+ }++ public Date getLastEventDate() {+ return lastEventDate;+ }++ public void setLastEventDate(Date lastEventDate) {+ this.lastEventDate = lastEventDate;+ }++ public Event getLastEvent() {+ return lastEvent;+ }++ public void setLastEvent(Event lastEvent) {+ this.lastEvent = lastEvent;+ }++ /**+ * Get commits pending integration.+ *+ * @return+ * commits pending integration+ */+ public Set<String> getPendingCommits() {+ if (pendingCommits == null) {+ pendingCommits = new HashSet<>();+ Repository repo = getTargetRepo();+ for (Commit commit: repo.git().log(getTarget().getObjectName(), getLatestUpdate().getHeadCommitHash(), null, 0, 0, false))+ pendingCommits.add(commit.getHash());+ }+ return pendingCommits;+ }++ public List<String> getCommentables() {+ List<String> commentables = new ArrayList<>();+ commentables.add(getBaseCommitHash());+ for (PullRequestUpdate update: getSortedUpdates()) {+ for (Commit commit: update.getCommits())+ commentables.add(commit.getHash());+ }+ return commentables;+ }++ /**+ * Merged commits represent commits already merged to target branch since base commit.+ *+ * @return+ * commits already merged to target branch since base commit+ */+ public Collection<Commit> getMergedCommits() {+ if (mergedCommits == null) {+ mergedCommits = new HashSet<>();++ Repository repo = getTargetRepo();+ for (Commit commit: repo.git().log(getBaseCommitHash(), getTarget().getObjectName(), null, 0, 0, false))+ mergedCommits.add(commit);+ }+ return mergedCommits;+ }++ private Collection<CommentReply> getCommentReplies() {+ if (commentReplies == null) {+ EntityCriteria<CommentReply> criteria = EntityCriteria.of(CommentReply.class);+ criteria.createCriteria("comment").add(Restrictions.eq("request", this));+ commentReplies = GitPlex.getInstance(Dao.class).query(criteria);+ }+ return commentReplies;+ }++ /**+ * This method is here for performance consideration. Often we need to load replies of+ * different comments in a pull request. And we optimize it to load all replies at once+ * for all comments in a pull request to reduce SQL queries.+ *+ * @param comment+ * @return+ */+ public Collection<CommentReply> getCommentReplies(Comment comment) {+ List<CommentReply> replies = new ArrayList<>();+ for (CommentReply reply: getCommentReplies()) {+ if (reply.getComment().equals(comment))+ replies.add(reply);+ }+ return replies;+ }++ public List<Review> getReviews() {+ if (reviews == null) {+ if (!isNew())+ reviews = GitPlex.getInstance(ReviewManager.class).findBy(this);+ else+ reviews = new ArrayList<>();+ }+ return reviews;+ }++ /**+ * This method is here for performance consideration. Often we need to load reviews of+ * different updates in a pull request. And we optimize it to load all reviews at once+ * for all updates in a pull request to reduce SQL queries.+ *+ * @param update+ * @return+ */+ public List<Review> getReviews(PullRequestUpdate update) {+ List<Review> reviews = new ArrayList<>();+ for (Review review: getReviews()) {+ if (review.getUpdate().equals(update))+ reviews.add(review);+ }+ return reviews;+ }++ public boolean isReviewEffective(User user) {+ for (Review review: getReviews()) {+ if (review.getUpdate().equals(getLatestUpdate()) && review.getReviewer().equals(user))+ return true;+ }+ return false;+ }++ /**+ * Calculate list of users can be added as reviewers of this pull request.+ *+ * @return+ * list of potential reviewers+ */+ public List<User> getPotentialReviewers() {+ List<User> reviewers = new ArrayList<>();+ Set<User> alreadyInvited = new HashSet<>();+ for (ReviewInvitation invitation: getReviewInvitations()) {+ if (invitation.isPreferred())+ alreadyInvited.add(invitation.getReviewer());+ }+ ObjectPermission readPerm = ObjectPermission.ofRepoPull(getTargetRepo());+ for (User user: GitPlex.getInstance(Dao.class).allOf(User.class)) {+ if (user.asSubject().isPermitted(readPerm) && !alreadyInvited.contains(user))+ reviewers.add(user);+ }+ return reviewers;+ }++ @Nullable+ public PullRequestWatch getWatch(User user) {+ for (PullRequestWatch watch: getWatches()) {+ if (watch.getUser().equals(user))+ return watch;+ }+ return null;+ }++ @Nullable+ public PullRequestVisit getVisit(User user) {+ for (PullRequestVisit visit: getVisits()) {+ if (visit.getUser().equals(user))+ return visit;+ }+ return null;+ }++ public String getUrl() {+ return GitPlex.getInstance().guessServerUrl() + "/" + getTargetRepo().getFQN()+ + "/pull_requests/" + getId() + "/overview";+ }++ @PrePersist+ public void prePersist() {+ idStr = getId().toString();+ }++ public String getIdStr() {+ return idStr;+ }++ public String getNoSpaceTitle() {+ return noSpaceTitle;+ }++ public long getVersion() {+ return version;+ }++}diff --git a/gitplex.core/src/main/java/com/pmease/gitplex/core/model/PullRequestUpdate.java b/gitplex.core/src/main/java/com/pmease/gitplex/core/model/PullRequestUpdate.javaindex d63c5d759c..44bde03686 100644--- a/gitplex.core/src/main/java/com/pmease/gitplex/core/model/PullRequestUpdate.java+++ b/gitplex.core/src/main/java/com/pmease/gitplex/core/model/PullRequestUpdate.java@@ -1,359 +1,359 @@-package com.pmease.gitplex.core.model;--import java.io.File;-import java.io.Serializable;-import java.util.ArrayList;-import java.util.Collection;-import java.util.Collections;-import java.util.Date;-import java.util.HashMap;-import java.util.LinkedHashMap;-import java.util.List;-import java.util.Map;-import java.util.Stack;-import java.util.concurrent.Callable;--import javax.persistence.Column;-import javax.persistence.Entity;-import javax.persistence.FetchType;-import javax.persistence.JoinColumn;-import javax.persistence.ManyToOne;-import javax.persistence.OneToMany;--import org.hibernate.annotations.OnDelete;-import org.hibernate.annotations.OnDeleteAction;--import com.fasterxml.jackson.annotation.JsonProperty;-import com.google.common.base.Preconditions;-import com.google.common.base.Throwables;-import com.google.common.collect.Lists;-import com.pmease.commons.git.Commit;-import com.pmease.commons.git.Git;-import com.pmease.commons.hibernate.AbstractEntity;-import com.pmease.commons.util.FileUtils;-import com.pmease.gitplex.core.GitPlex;-import com.pmease.gitplex.core.manager.StorageManager;--@SuppressWarnings("serial")-@Entity-public class PullRequestUpdate extends AbstractEntity {-- @ManyToOne(fetch=FetchType.LAZY)- @JoinColumn(nullable=false)- private PullRequest request;-- @Column(nullable=false)- private String headCommitHash;-- @Column(nullable=false)- private Date date;-- @OneToMany(mappedBy="update")- @OnDelete(action=OnDeleteAction.CASCADE)- private Collection<Review> reviews = new ArrayList<Review>();-- private transient List<Commit> commits;-- private transient CachedInfo cachedInfo;-- public PullRequest getRequest() {- return request;- }-- public void setRequest(PullRequest request) {- this.request = request;- }-- public String getHeadCommitHash() {- return headCommitHash;- }-- public void setHeadCommitHash(String headCommitHash) {- this.headCommitHash = headCommitHash;- }-- public Date getDate() {- return date;- }-- public void setDate(Date date) {- this.date = date;- }-- public Collection<Review> getReviews() {- return getRequest().getReviews(this);- }-- @JsonProperty- public String getHeadRef() {- Preconditions.checkNotNull(getId());- return Repository.REFS_GITPLEX + "updates/" + getId();- }-- /**- * List reviews against this update and all subsequent updates.- * <p>- * @return- * list of found reviews, ordered by associated updates reversely- */- public List<Review> listReviewsOnwards() {- List<Review> reviews = new ArrayList<Review>();-- for (PullRequestUpdate update: getRequest().getEffectiveUpdates()) {- reviews.addAll(update.getReviews());- if (update.equals(this))- break;- }-- return reviews;- }-- public void deleteRefs() {- Git git = getRequest().getTargetRepo().git();- git.deleteRef(getHeadRef(), null, null);- }-- public Collection<String> getChangedFiles() {- return getCachedInfo().getChangedFiles();- }-- public String getBaseCommitHash() {- PullRequest request = getRequest();-- int index = request.getSortedUpdates().indexOf(this);- if (index > 0)- return request.getSortedUpdates().get(index-1).getHeadCommitHash();- else- return request.getBaseCommitHash();- }-- /**- * Base commit represents head commit of last update, or base commit of the request- * for the first update. Base commit is used to calculate commits belonging to- * current update.- *- * @return- * base commit of this update- */- public Commit getBaseCommit() {- PullRequest request = getRequest();-- int index = request.getSortedUpdates().indexOf(this);- if (index > 0)- return request.getSortedUpdates().get(index-1).getHeadCommit();- else- return request.getBaseCommit();- }-- private CachedInfo getCachedInfo() {- if (cachedInfo == null) {- Callable<CachedInfo> callable = new Callable<CachedInfo>() {-- @Override- public CachedInfo call() throws Exception {- CachedInfo cachedInfo = new CachedInfo();-- Repository targetRepo = getRequest().getTargetRepo();- Git git = targetRepo.git();- List<Commit> log = git.log(getBaseCommitHash(), getHeadCommitHash(), null, 0, 0, false);- if (log.isEmpty())- log = Lists.newArrayList(targetRepo.getCommit(getHeadCommitHash()));- cachedInfo.setLogCommits(log);-- String mergeBase = git.calcMergeBase(getHeadCommitHash(), getRequest().getTarget().getHead());-- if (targetRepo.isAncestor(getBaseCommitHash(), mergeBase)) {- cachedInfo.setChangedFiles(git.listChangedFiles(mergeBase, getHeadCommitHash(), null));- } else if (targetRepo.isAncestor(mergeBase, getBaseCommitHash())) {- cachedInfo.setChangedFiles(git.listChangedFiles(getBaseCommitHash(), getHeadCommitHash(), null));- } else {- File tempDir = FileUtils.createTempDir();- try {- Git tempGit = new Git(tempDir);-- /*- * Calculate changed files of this update since merged commit of:- *- * 1. merge base of update head and target branch head- * 2. head of previous update- *- * This way changed files of this update will exclude merged changes- * from target branch if there is any.- */- String branchName = getRequest().getTargetBranch();- tempGit.clone(git.repoDir().getAbsolutePath(), false, true, true, branchName);- tempGit.updateRef("HEAD", mergeBase, null, null);- tempGit.reset(null, null);- Preconditions.checkNotNull(tempGit.merge(getBaseCommitHash(), null, null, "ours", null));-- cachedInfo.setChangedFiles(tempGit.listChangedFiles(- tempGit.parseRevision("HEAD", true), getHeadCommitHash(), null));- } finally {- FileUtils.deleteDir(tempDir);- }- }-- return cachedInfo;- }-- };- if (isNew()) {- try {- cachedInfo = callable.call();- } catch (Exception e) {- Throwables.propagate(e);- }- } else {- StorageManager storageManager = GitPlex.getInstance(StorageManager.class);- File cacheFile = new File(storageManager.getCacheDir(this), "cachedInfo");- cachedInfo = FileUtils.readFile(cacheFile, callable);- }- }- return cachedInfo;- }-- /**- * Get commits belonging to this update, ordered by commit id- *- * @return- * commits belonging to this update ordered by commit id- */- public List<Commit> getCommits() {- if (commits == null) {- /*- * This method calculates all commits belonging to this update. You might think that- * the result is obvious, just take log output between last update and current head.- * But that result may include noise commits, for instance, if you merges target- * branch into source branch to resolve merge conflicts, all commits in target- * branch will also appear in log output between last update and current update.- * Now, you might suggest that let's just exclude from the log output those commits- * being ancestor of target branch. But this still can cause issues as target branch- * may merge some intermediate commits from our source branch, and these- * intermediate commits will be ancestor of target branch. We certainly do not want- * to exclude these intermediate commits as it originally belongs to our source- * branch. To solve this contradiction, for those commits belong to both source- * branch and target branch, we calculate affinity score of the commit to each- * branch, and consider the commit to be belonging to a branch if the associated- * affinity score is less.- */- commits = new ArrayList<>();-- Map<String, ScoreAwareCommit> allCommits = new LinkedHashMap<>();- for (Commit commit: getCachedInfo().getLogCommits()) {- ScoreAwareCommit scoreAwareCommit = new ScoreAwareCommit();- scoreAwareCommit.setCommit(commit);- allCommits.put(commit.getHash(), scoreAwareCommit);- }-- ScoreAwareCommit headCommit = allCommits.get(getHeadCommitHash());- if (headCommit != null) {- headCommit.setScore(0);- updateAffinityScores(allCommits, headCommit);- }-- Map<String, ScoreAwareCommit> mergedCommits = new HashMap<>();- for (Commit commit: getRequest().getMergedCommits()) {- ScoreAwareCommit scoredCommit = new ScoreAwareCommit();- scoredCommit.setCommit(commit);- mergedCommits.put(commit.getHash(), scoredCommit);- }-- headCommit = mergedCommits.get(getRequest().getTarget().getHead());- if (headCommit != null) {- headCommit.setScore(0);- updateAffinityScores(mergedCommits, headCommit);- }-- for (ScoreAwareCommit commit: allCommits.values()) {- ScoreAwareCommit mergedCommit = mergedCommits.get(commit.getCommit().getHash());- if (mergedCommit == null || mergedCommit.getScore() >= commit.getScore())- commits.add(commit.getCommit());- }-- getRequest().getTargetRepo().cacheCommits(commits);-- Collections.reverse(commits);- }- return commits;- }-- public Commit getHeadCommit() {- Commit headCommit = getCachedInfo().getLogCommits().get(0);- Preconditions.checkState(headCommit.getHash().equals(getHeadCommitHash()));- return headCommit;- }-- /*- * This method calculates affinity scores of a set of commits against specified head commit (or branch).- * The affinity score reflects the distance between a commit and first-parent chain of the head commit.- * For instance, if a commit can be reached recursively via first-parent of the head commit, its- * affinity score will be 0.- */- private void updateAffinityScores(Map<String, ScoreAwareCommit> commits, ScoreAwareCommit headCommit) {- Stack<ScoreAwareCommit> stack = new Stack<>();- stack.push(headCommit);- while (!stack.isEmpty()) {- ScoreAwareCommit currentCommit = stack.pop();- for (int i=0; i<currentCommit.getCommit().getParentHashes().size(); i++) {- String parentCommitHash = currentCommit.getCommit().getParentHashes().get(i);- ScoreAwareCommit parentCommit = commits.get(parentCommitHash);- if (parentCommit != null && parentCommit.getScore() == Integer.MAX_VALUE) {- /*- * Parent hashes of a commit is ordered in parent number. For instance first-parent is at index 0.- * So the parent score is calculated simply by adding current parent index to the head commit score.- */- parentCommit.setScore(i + currentCommit.getScore());- stack.push(parentCommit);- }- }- }- }-- private static class ScoreAwareCommit {-- private Commit commit;-- private int score = Integer.MAX_VALUE;-- public Commit getCommit() {- return commit;- }-- public void setCommit(Commit commit) {- this.commit = commit;- }-- public int getScore() {- return score;- }-- public void setScore(int score) {- this.score = score;- }-- }-- private static class CachedInfo implements Serializable {-- private Collection<String> changedFiles;-- private List<Commit> logCommits;-- public Collection<String> getChangedFiles() {- return changedFiles;- }-- public void setChangedFiles(Collection<String> changedFiles) {- this.changedFiles = changedFiles;- }-- public List<Commit> getLogCommits() {- return logCommits;- }-- public void setLogCommits(List<Commit> logCommits) {- this.logCommits = logCommits;- }-- }-}+package com.pmease.gitplex.core.model;++import java.io.File;+import java.io.Serializable;+import java.util.ArrayList;+import java.util.Collection;+import java.util.Collections;+import java.util.Date;+import java.util.HashMap;+import java.util.LinkedHashMap;+import java.util.List;+import java.util.Map;+import java.util.Stack;+import java.util.concurrent.Callable;++import javax.persistence.Column;+import javax.persistence.Entity;+import javax.persistence.FetchType;+import javax.persistence.JoinColumn;+import javax.persistence.ManyToOne;+import javax.persistence.OneToMany;++import org.hibernate.annotations.OnDelete;+import org.hibernate.annotations.OnDeleteAction;++import com.fasterxml.jackson.annotation.JsonProperty;+import com.google.common.base.Preconditions;+import com.google.common.base.Throwables;+import com.google.common.collect.Lists;+import com.pmease.commons.git.Commit;+import com.pmease.commons.git.Git;+import com.pmease.commons.hibernate.AbstractEntity;+import com.pmease.commons.util.FileUtils;+import com.pmease.gitplex.core.GitPlex;+import com.pmease.gitplex.core.manager.StorageManager;++@SuppressWarnings("serial")+@Entity+public class PullRequestUpdate extends AbstractEntity {++ @ManyToOne(fetch=FetchType.LAZY)+ @JoinColumn(nullable=false)+ private PullRequest request;++ @Column(nullable=false)+ private String headCommitHash;++ @Column(nullable=false)+ private Date date;++ @OneToMany(mappedBy="update")+ @OnDelete(action=OnDeleteAction.CASCADE)+ private Collection<Review> reviews = new ArrayList<Review>();++ private transient List<Commit> commits;++ private transient CachedInfo cachedInfo;++ public PullRequest getRequest() {+ return request;+ }++ public void setRequest(PullRequest request) {+ this.request = request;+ }++ public String getHeadCommitHash() {+ return headCommitHash;+ }++ public void setHeadCommitHash(String headCommitHash) {+ this.headCommitHash = headCommitHash;+ }++ public Date getDate() {+ return date;+ }++ public void setDate(Date date) {+ this.date = date;+ }++ public Collection<Review> getReviews() {+ return getRequest().getReviews(this);+ }++ @JsonProperty+ public String getHeadRef() {+ Preconditions.checkNotNull(getId());+ return Repository.REFS_GITPLEX + "updates/" + getId();+ }++ /**+ * List reviews against this update and all subsequent updates.+ * <p>+ * @return+ * list of found reviews, ordered by associated updates reversely+ */+ public List<Review> listReviewsOnwards() {+ List<Review> reviews = new ArrayList<Review>();++ for (PullRequestUpdate update: getRequest().getEffectiveUpdates()) {+ reviews.addAll(update.getReviews());+ if (update.equals(this))+ break;+ }++ return reviews;+ }++ public void deleteRefs() {+ Git git = getRequest().getTargetRepo().git();+ git.deleteRef(getHeadRef(), null, null);+ }++ public Collection<String> getChangedFiles() {+ return getCachedInfo().getChangedFiles();+ }++ public String getBaseCommitHash() {+ PullRequest request = getRequest();++ int index = request.getSortedUpdates().indexOf(this);+ if (index > 0)+ return request.getSortedUpdates().get(index-1).getHeadCommitHash();+ else+ return request.getBaseCommitHash();+ }++ /**+ * Base commit represents head commit of last update, or base commit of the request+ * for the first update. Base commit is used to calculate commits belonging to+ * current update.+ *+ * @return+ * base commit of this update+ */+ public Commit getBaseCommit() {+ PullRequest request = getRequest();++ int index = request.getSortedUpdates().indexOf(this);+ if (index > 0)+ return request.getSortedUpdates().get(index-1).getHeadCommit();+ else+ return request.getBaseCommit();+ }++ private CachedInfo getCachedInfo() {+ if (cachedInfo == null) {+ Callable<CachedInfo> callable = new Callable<CachedInfo>() {++ @Override+ public CachedInfo call() throws Exception {+ CachedInfo cachedInfo = new CachedInfo();++ Repository targetRepo = getRequest().getTargetRepo();+ Git git = targetRepo.git();+ List<Commit> log = git.log(getBaseCommitHash(), getHeadCommitHash(), null, 0, 0, false);+ if (log.isEmpty())+ log = Lists.newArrayList(targetRepo.getCommit(getHeadCommitHash()));+ cachedInfo.setLogCommits(log);++ String mergeBase = git.calcMergeBase(getHeadCommitHash(), getRequest().getTarget().getObjectName());++ if (targetRepo.isAncestor(getBaseCommitHash(), mergeBase)) {+ cachedInfo.setChangedFiles(git.listChangedFiles(mergeBase, getHeadCommitHash(), null));+ } else if (targetRepo.isAncestor(mergeBase, getBaseCommitHash())) {+ cachedInfo.setChangedFiles(git.listChangedFiles(getBaseCommitHash(), getHeadCommitHash(), null));+ } else {+ File tempDir = FileUtils.createTempDir();+ try {+ Git tempGit = new Git(tempDir);++ /*+ * Calculate changed files of this update since merged commit of:+ *+ * 1. merge base of update head and target branch head+ * 2. head of previous update+ *+ * This way changed files of this update will exclude merged changes+ * from target branch if there is any.+ */+ String branchName = getRequest().getTargetBranch();+ tempGit.clone(git.repoDir().getAbsolutePath(), false, true, true, branchName);+ tempGit.updateRef("HEAD", mergeBase, null, null);+ tempGit.reset(null, null);+ Preconditions.checkNotNull(tempGit.merge(getBaseCommitHash(), null, null, "ours", null));++ cachedInfo.setChangedFiles(tempGit.listChangedFiles(+ tempGit.parseRevision("HEAD", true), getHeadCommitHash(), null));+ } finally {+ FileUtils.deleteDir(tempDir);+ }+ }++ return cachedInfo;+ }++ };+ if (isNew()) {+ try {+ cachedInfo = callable.call();+ } catch (Exception e) {+ Throwables.propagate(e);+ }+ } else {+ StorageManager storageManager = GitPlex.getInstance(StorageManager.class);+ File cacheFile = new File(storageManager.getCacheDir(this), "cachedInfo");+ cachedInfo = FileUtils.readFile(cacheFile, callable);+ }+ }+ return cachedInfo;+ }++ /**+ * Get commits belonging to this update, ordered by commit id+ *+ * @return+ * commits belonging to this update ordered by commit id+ */+ public List<Commit> getCommits() {+ if (commits == null) {+ /*+ * This method calculates all commits belonging to this update. You might think that+ * the result is obvious, just take log output between last update and current head.+ * But that result may include noise commits, for instance, if you merges target+ * branch into source branch to resolve merge conflicts, all commits in target+ * branch will also appear in log output between last update and current update.+ * Now, you might suggest that let's just exclude from the log output those commits+ * being ancestor of target branch. But this still can cause issues as target branch+ * may merge some intermediate commits from our source branch, and these+ * intermediate commits will be ancestor of target branch. We certainly do not want+ * to exclude these intermediate commits as it originally belongs to our source+ * branch. To solve this contradiction, for those commits belong to both source+ * branch and target branch, we calculate affinity score of the commit to each+ * branch, and consider the commit to be belonging to a branch if the associated+ * affinity score is less.+ */+ commits = new ArrayList<>();++ Map<String, ScoreAwareCommit> allCommits = new LinkedHashMap<>();+ for (Commit commit: getCachedInfo().getLogCommits()) {+ ScoreAwareCommit scoreAwareCommit = new ScoreAwareCommit();+ scoreAwareCommit.setCommit(commit);+ allCommits.put(commit.getHash(), scoreAwareCommit);+ }++ ScoreAwareCommit headCommit = allCommits.get(getHeadCommitHash());+ if (headCommit != null) {+ headCommit.setScore(0);+ updateAffinityScores(allCommits, headCommit);+ }++ Map<String, ScoreAwareCommit> mergedCommits = new HashMap<>();+ for (Commit commit: getRequest().getMergedCommits()) {+ ScoreAwareCommit scoredCommit = new ScoreAwareCommit();+ scoredCommit.setCommit(commit);+ mergedCommits.put(commit.getHash(), scoredCommit);+ }++ headCommit = mergedCommits.get(getRequest().getTarget().getObjectName());+ if (headCommit != null) {+ headCommit.setScore(0);+ updateAffinityScores(mergedCommits, headCommit);+ }++ for (ScoreAwareCommit commit: allCommits.values()) {+ ScoreAwareCommit mergedCommit = mergedCommits.get(commit.getCommit().getHash());+ if (mergedCommit == null || mergedCommit.getScore() >= commit.getScore())+ commits.add(commit.getCommit());+ }++ getRequest().getTargetRepo().cacheCommits(commits);++ Collections.reverse(commits);+ }+ return commits;+ }++ public Commit getHeadCommit() {+ Commit headCommit = getCachedInfo().getLogCommits().get(0);+ Preconditions.checkState(headCommit.getHash().equals(getHeadCommitHash()));+ return headCommit;+ }++ /*+ * This method calculates affinity scores of a set of commits against specified head commit (or branch).+ * The affinity score reflects the distance between a commit and first-parent chain of the head commit.+ * For instance, if a commit can be reached recursively via first-parent of the head commit, its+ * affinity score will be 0.+ */+ private void updateAffinityScores(Map<String, ScoreAwareCommit> commits, ScoreAwareCommit headCommit) {+ Stack<ScoreAwareCommit> stack = new Stack<>();+ stack.push(headCommit);+ while (!stack.isEmpty()) {+ ScoreAwareCommit currentCommit = stack.pop();+ for (int i=0; i<currentCommit.getCommit().getParentHashes().size(); i++) {+ String parentCommitHash = currentCommit.getCommit().getParentHashes().get(i);+ ScoreAwareCommit parentCommit = commits.get(parentCommitHash);+ if (parentCommit != null && parentCommit.getScore() == Integer.MAX_VALUE) {+ /*+ * Parent hashes of a commit is ordered in parent number. For instance first-parent is at index 0.+ * So the parent score is calculated simply by adding current parent index to the head commit score.+ */+ parentCommit.setScore(i + currentCommit.getScore());+ stack.push(parentCommit);+ }+ }+ }+ }++ private static class ScoreAwareCommit {++ private Commit commit;++ private int score = Integer.MAX_VALUE;++ public Commit getCommit() {+ return commit;+ }++ public void setCommit(Commit commit) {+ this.commit = commit;+ }++ public int getScore() {+ return score;+ }++ public void setScore(int score) {+ this.score = score;+ }++ }++ private static class CachedInfo implements Serializable {++ private Collection<String> changedFiles;++ private List<Commit> logCommits;++ public Collection<String> getChangedFiles() {+ return changedFiles;+ }++ public void setChangedFiles(Collection<String> changedFiles) {+ this.changedFiles = changedFiles;+ }++ public List<Commit> getLogCommits() {+ return logCommits;+ }++ public void setLogCommits(List<Commit> logCommits) {+ this.logCommits = logCommits;+ }++ }+}diff --git a/gitplex.core/src/main/java/com/pmease/gitplex/core/model/RepoAndBranch.java b/gitplex.core/src/main/java/com/pmease/gitplex/core/model/RepoAndBranch.javaindex b1ed2f9459..52498661b0 100644--- a/gitplex.core/src/main/java/com/pmease/gitplex/core/model/RepoAndBranch.java+++ b/gitplex.core/src/main/java/com/pmease/gitplex/core/model/RepoAndBranch.java@@ -1,9 +1,5 @@package com.pmease.gitplex.core.model;-import javax.annotation.Nullable;--import org.eclipse.jgit.lib.ObjectId;-import com.pmease.commons.git.GitUtils;public class RepoAndBranch extends RepoAndRevision {@@ -25,15 +21,10 @@ public class RepoAndBranch extends RepoAndRevision {public String getBranch() {return getRevision();}-- @Nullable- public String getHead(boolean mustExist) {- ObjectId commitId = getRepository().getObjectId(GitUtils.branch2ref(getRevision()), mustExist);- return commitId!=null?commitId.name():null;- }-- public String getHead() {- return getHead(true);++ @Override+ protected String normalizeRevision() {+ return GitUtils.branch2ref(getBranch());}}diff --git a/gitplex.core/src/main/java/com/pmease/gitplex/core/model/RepoAndRevision.java b/gitplex.core/src/main/java/com/pmease/gitplex/core/model/RepoAndRevision.javaindex 9ac541d4c5..026ba9aca7 100644--- a/gitplex.core/src/main/java/com/pmease/gitplex/core/model/RepoAndRevision.java+++ b/gitplex.core/src/main/java/com/pmease/gitplex/core/model/RepoAndRevision.java@@ -66,19 +66,32 @@ public class RepoAndRevision implements Serializable {@Nullablepublic ObjectId getObjectId(boolean mustExist) {- return getRepository().getObjectId(revision, mustExist);+ return getRepository().getObjectId(normalizeRevision(), mustExist);}public ObjectId getObjectId() {- return getRepository().getObjectId(revision);+ return getObjectId(true);}- public String getFQN() {- return getRepository().getRevisionFQN(revision);+ public RevCommit getCommit(boolean mustExist) {+ return getRepository().getRevCommit(getObjectId(mustExist), mustExist);}public RevCommit getCommit() {- return getRepository().getRevCommit(getObjectId());+ return getCommit(true);+ }++ public String getObjectName(boolean mustExist) {+ ObjectId objectId = getObjectId(mustExist);+ return objectId!=null?objectId.name():null;+ }++ public String getObjectName() {+ return getObjectName(true);+ }++ public String getFQN() {+ return getRepository().getRevisionFQN(revision);}public static void trim(Collection<String> repoAndBranches) {@@ -104,6 +117,10 @@ public class RepoAndRevision implements Serializable {return repository;}+ protected String normalizeRevision() {+ return revision;+ }+@Overridepublic boolean equals(Object other) {if (!(other instanceof RepoAndRevision))diff --git a/gitplex.web/src/main/java/com/pmease/gitplex/web/component/BranchLink.java b/gitplex.web/src/main/java/com/pmease/gitplex/web/component/BranchLink.javaindex 9714ae6519..2903492d35 100644--- a/gitplex.web/src/main/java/com/pmease/gitplex/web/component/BranchLink.java+++ b/gitplex.web/src/main/java/com/pmease/gitplex/web/component/BranchLink.java@@ -31,7 +31,7 @@ public class BranchLink extends BookmarkablePageLink<Void> {protected void onConfigure() {super.onConfigure();setEnabled(SecurityUtils.canPull(repoAndBranch.getRepository())- && repoAndBranch.getHead(false) != null);+ && repoAndBranch.getObjectName(false) != null);}@Overridediff --git a/gitplex.web/src/main/java/com/pmease/gitplex/web/component/diff/blob/text/TextDiffPanel.java b/gitplex.web/src/main/java/com/pmease/gitplex/web/component/diff/blob/text/TextDiffPanel.javaindex 965addbbfe..22f52a64e5 100644--- a/gitplex.web/src/main/java/com/pmease/gitplex/web/component/diff/blob/text/TextDiffPanel.java+++ b/gitplex.web/src/main/java/com/pmease/gitplex/web/component/diff/blob/text/TextDiffPanel.java@@ -176,7 +176,7 @@ public class TextDiffPanel extends Panel {super.onConfigure();PullRequest request = requestModel.getObject();setVisible(request.getSourceRepo() != null- && change.getBlobIdent().revision.equals(request.getSource().getHead(false)));+ && change.getBlobIdent().revision.equals(request.getSource().getObjectName(false)));}};diff --git a/gitplex.web/src/main/java/com/pmease/gitplex/web/page/repository/file/RepoFilePage.java b/gitplex.web/src/main/java/com/pmease/gitplex/web/page/repository/file/RepoFilePage.javaindex e23a318735..087fc9516f 100644--- a/gitplex.web/src/main/java/com/pmease/gitplex/web/page/repository/file/RepoFilePage.java+++ b/gitplex.web/src/main/java/com/pmease/gitplex/web/page/repository/file/RepoFilePage.java@@ -1,938 +1,938 @@-package com.pmease.gitplex.web.page.repository.file;--import java.io.IOException;-import java.io.Serializable;-import java.util.ArrayList;-import java.util.List;-import java.util.concurrent.atomic.AtomicReference;--import javax.annotation.Nullable;--import org.apache.commons.lang3.StringUtils;-import org.apache.wicket.Component;-import org.apache.wicket.MetaDataKey;-import org.apache.wicket.RestartResponseException;-import org.apache.wicket.ajax.AbstractDefaultAjaxBehavior;-import org.apache.wicket.ajax.AjaxRequestTarget;-import org.apache.wicket.behavior.AttributeAppender;-import org.apache.wicket.extensions.ajax.markup.html.AjaxLazyLoadPanel;-import org.apache.wicket.markup.head.CssHeaderItem;-import org.apache.wicket.markup.head.IHeaderResponse;-import org.apache.wicket.markup.head.JavaScriptHeaderItem;-import org.apache.wicket.markup.html.WebMarkupContainer;-import org.apache.wicket.markup.html.basic.Label;-import org.apache.wicket.markup.html.image.Image;-import org.apache.wicket.model.AbstractReadOnlyModel;-import org.apache.wicket.model.IModel;-import org.apache.wicket.model.LoadableDetachableModel;-import org.apache.wicket.protocol.ws.api.WebSocketRequestHandler;-import org.apache.wicket.request.IRequestHandler;-import org.apache.wicket.request.cycle.RequestCycle;-import org.apache.wicket.request.handler.resource.ResourceReferenceRequestHandler;-import org.apache.wicket.request.mapper.parameter.PageParameters;-import org.apache.wicket.request.resource.CssResourceReference;-import org.apache.wicket.request.resource.JavaScriptResourceReference;-import org.apache.wicket.request.resource.PackageResourceReference;-import org.eclipse.jgit.internal.storage.file.FileRepository;-import org.eclipse.jgit.lib.Constants;-import org.eclipse.jgit.lib.FileMode;-import org.eclipse.jgit.lib.ObjectId;-import org.eclipse.jgit.revwalk.RevTree;-import org.eclipse.jgit.revwalk.RevWalk;-import org.eclipse.jgit.treewalk.TreeWalk;--import com.google.common.base.Objects;-import com.google.common.base.Preconditions;-import com.pmease.commons.git.BlobIdent;-import com.pmease.commons.git.GitUtils;-import com.pmease.commons.git.exception.ObjectNotExistException;-import com.pmease.commons.hibernate.dao.Dao;-import com.pmease.commons.lang.extractors.TokenPosition;-import com.pmease.commons.wicket.assets.closestdescendant.ClosestDescendantResourceReference;-import com.pmease.commons.wicket.assets.cookies.CookiesResourceReference;-import com.pmease.commons.wicket.behavior.TooltipBehavior;-import com.pmease.commons.wicket.component.modal.ModalLink;-import com.pmease.commons.wicket.websocket.WebSocketRenderBehavior;-import com.pmease.commons.wicket.websocket.WebSocketTrait;-import com.pmease.gitplex.core.GitPlex;-import com.pmease.gitplex.core.listeners.RefListener;-import com.pmease.gitplex.core.model.Comment;-import com.pmease.gitplex.core.model.PullRequest;-import com.pmease.gitplex.core.model.Repository;-import com.pmease.gitplex.search.IndexListener;-import com.pmease.gitplex.search.IndexManager;-import com.pmease.gitplex.search.SearchManager;-import com.pmease.gitplex.search.hit.QueryHit;-import com.pmease.gitplex.search.query.BlobQuery;-import com.pmease.gitplex.search.query.TextQuery;-import com.pmease.gitplex.web.WebSession;-import com.pmease.gitplex.web.component.repofile.blobsearch.advanced.AdvancedSearchPanel;-import com.pmease.gitplex.web.component.repofile.blobsearch.instant.InstantSearchPanel;-import com.pmease.gitplex.web.component.repofile.blobsearch.result.SearchResultPanel;-import com.pmease.gitplex.web.component.repofile.blobview.BlobNameChangeCallback;-import com.pmease.gitplex.web.component.repofile.blobview.BlobRenderer;-import com.pmease.gitplex.web.component.repofile.blobview.BlobViewContext;-import com.pmease.gitplex.web.component.repofile.blobview.BlobViewPanel;-import com.pmease.gitplex.web.component.repofile.blobview.source.SourceViewPanel;-import com.pmease.gitplex.web.component.repofile.editsave.CancelListener;-import com.pmease.gitplex.web.component.repofile.editsave.EditSavePanel;-import com.pmease.gitplex.web.component.repofile.fileedit.FileEditPanel;-import com.pmease.gitplex.web.component.repofile.filelist.FileListPanel;-import com.pmease.gitplex.web.component.repofile.filenavigator.FileNavigator;-import com.pmease.gitplex.web.component.revisionpicker.RevisionPicker;-import com.pmease.gitplex.web.page.repository.NoCommitsPage;-import com.pmease.gitplex.web.page.repository.RepositoryPage;-import com.pmease.gitplex.web.websocket.PullRequestChangeRenderer;--import de.agilecoders.wicket.core.markup.html.bootstrap.components.TooltipConfig;-import de.agilecoders.wicket.core.markup.html.bootstrap.components.TooltipConfig.Placement;-import de.agilecoders.wicket.extensions.markup.html.bootstrap.jqueryui.JQueryUIResizableJavaScriptReference;--@SuppressWarnings("serial")-public class RepoFilePage extends RepositoryPage implements BlobViewContext {-- private static class SearchResultKey extends MetaDataKey<ArrayList<QueryHit>> {- };-- public static final SearchResultKey SEARCH_RESULT_KEY = new SearchResultKey();-- private static final String PARAM_REVISION = "revision";-- private static final String PARAM_PATH = "path";-- private static final String PARAM_REQUEST = "request";-- private static final String PARAM_COMMENT = "comment";-- private static final String PARAM_MODE = "mode";-- private static final String PARAM_QUERY = "query";-- private static final String PARAM_CLIENT_STATE = "client_state";-- private static final String PARAM_MARK = "mark";-- private static final String REVISION_PICKER_ID = "revisionPicker";-- private static final String FILE_NAVIGATOR_ID = "fileNavigator";-- private static final String LAST_COMMIT_ID = "lastCommit";-- private static final String FILE_VIEWER_ID = "fileViewer";-- private static final String SEARCH_RESULD_ID = "searchResult";-- private Long requestId;-- private Long commentId;-- private final IModel<Comment> commentModel = new LoadableDetachableModel<Comment>() {-- @Override- protected Comment load() {- if (commentId != null)- return GitPlex.getInstance(Dao.class).load(Comment.class, commentId);- else- return null;- }-- };-- private final IModel<PullRequest> requestModel = new LoadableDetachableModel<PullRequest>() {-- @Override- protected PullRequest load() {- Comment comment = getComment();- if (comment != null)- return comment.getRequest();- else if (requestId != null)- return GitPlex.getInstance(Dao.class).load(PullRequest.class, requestId);- else- return null;- }- };-- private BlobIdent blobIdent = new BlobIdent();-- private Mark mark;-- private Mode mode;-- private Component commentContext;-- private Component revisionIndexing;-- private WebMarkupContainer searchResultContainer;-- private AtomicReference<String> newPathRef;-- private final RevisionIndexed trait = new RevisionIndexed();-- private transient List<QueryHit> queryHits;-- // client state holding CodeMirror cursor, scroll, marks, etc.- private transient String clientState;-- public RepoFilePage(final PageParameters params) {- super(params);-- if (!getRepository().git().hasCommits())- throw new RestartResponseException(NoCommitsPage.class, paramsOf(getRepository()));-- trait.repoId = getRepository().getId();-- commentId = params.get(PARAM_COMMENT).toOptionalLong();- blobIdent.revision = params.get(PARAM_REVISION).toString();- blobIdent.path = GitUtils.normalizePath(params.get(PARAM_PATH).toString());-- Comment comment = commentModel.getObject();- if (comment != null) {- if (blobIdent.revision != null || blobIdent.path != null)- throw new IllegalArgumentException("Revision or path should not be specified if comment is specified");- blobIdent = comment.getBlobIdent();- } else {- requestId = params.get(PARAM_REQUEST).toOptionalLong();-- blobIdent.revision = GitUtils.normalizePath(params.get(PARAM_REVISION).toString());- if (blobIdent.revision == null)- blobIdent.revision = getRepository().getDefaultBranch();-- if (requestId != null && !GitUtils.isHash(blobIdent.revision))- throw new IllegalArgumentException("Pull request can only be associated with a hash revision");- }-- trait.revision = blobIdent.revision;-- if (blobIdent.path != null) {- try ( FileRepository jgitRepo = getRepository().openAsJGitRepo();- RevWalk revWalk = new RevWalk(jgitRepo)) {- RevTree revTree = getRepository().getRevCommit(getCommitId(), true).getTree();- TreeWalk treeWalk = TreeWalk.forPath(jgitRepo, blobIdent.path, revTree);- if (treeWalk == null) {- throw new ObjectNotExistException("Unable to find blob path '" + blobIdent.path- + "' in revision '" + blobIdent.revision + "'");- }- blobIdent.mode = treeWalk.getRawMode(0);- } catch (IOException e) {- throw new RuntimeException(e);- }- } else {- blobIdent.mode = FileMode.TREE.getBits();- }-- String modeStr = params.get(PARAM_MODE).toString();- if (modeStr != null)- mode = Mode.valueOf(modeStr.toUpperCase());- String markStr = params.get(PARAM_MARK).toString();- if (markStr != null)- mark = new Mark(markStr);-- queryHits = WebSession.get().getMetaData(SEARCH_RESULT_KEY);- if (queryHits != null) {- WebSession.get().setMetaData(SEARCH_RESULT_KEY, null);- } else {- String symbol = params.get(PARAM_QUERY).toString();- if (symbol != null) {- BlobQuery query = new TextQuery(symbol, false, true, true,- null, null, SearchResultPanel.MAX_QUERY_ENTRIES);- try {- SearchManager searchManager = GitPlex.getInstance(SearchManager.class);- queryHits = searchManager.search(repoModel.getObject(), blobIdent.revision, query);- } catch (InterruptedException e) {- throw new RuntimeException(e);- }- }- }-- clientState = params.get(PARAM_CLIENT_STATE).toString();- }-- private ObjectId getCommitId() {- return getRepository().getObjectId(blobIdent.revision);- }-- @Override- protected void onInitialize() {- super.onInitialize();-- add(new InstantSearchPanel("instantSearch", repoModel, requestModel, new AbstractReadOnlyModel<String>() {-- @Override- public String getObject() {- return blobIdent.revision;- }-- }) {-- @Override- protected void onSelect(AjaxRequestTarget target, QueryHit hit) {- BlobIdent selected = new BlobIdent(blobIdent.revision, hit.getBlobPath(),- FileMode.REGULAR_FILE.getBits());- RepoFilePage.this.onSelect(target, selected, hit.getTokenPos());- }-- @Override- protected void onMoreQueried(AjaxRequestTarget target, List<QueryHit> hits) {- newSearchResult(target, hits);- resizeWindow(target);- }-- });-- add(new ModalLink("advancedSearch") {-- @Override- protected Component newContent(String id) {- return new AdvancedSearchPanel(id, repoModel, new AbstractReadOnlyModel<String>() {-- @Override- public String getObject() {- return blobIdent.revision;- }-- }) {-- @Override- protected void onSearchComplete(AjaxRequestTarget target, List<QueryHit> hits) {- newSearchResult(target, hits);- resizeWindow(target);- close(target);- }-- @Override- protected void onCancel(AjaxRequestTarget target) {- close(target);- }-- @Override- protected BlobIdent getCurrentBlob() {- return blobIdent;- }-- };- }-- });-- newRevisionPicker(null);-- add(commentContext = new WebMarkupContainer("commentContext") {-- @Override- protected void onConfigure() {- super.onConfigure();-- setVisible(getPullRequest() != null);- }-- @Override- protected void onInitialize() {- super.onInitialize();-- add(new TooltipBehavior(new AbstractReadOnlyModel<String>() {-- @Override- public String getObject() {- PullRequest request = getPullRequest();- String tooltip = String.format("Inline comments added/displayed in "- + "this commit belong to pull request #%d (%s)",- request.getId(), request.getTitle());- return tooltip;- }-- }, new TooltipConfig().withPlacement(Placement.bottom)));-- setOutputMarkupPlaceholderTag(true);- }-- });-- newFileNavigator(null);-- add(revisionIndexing = new WebMarkupContainer("revisionIndexing") {-- @Override- protected void onInitialize() {- super.onInitialize();- add(new Image("icon", new PackageResourceReference(RepoFilePage.class, "indexing.gif")));- setOutputMarkupPlaceholderTag(true);- }-- @Override- protected void onConfigure() {- super.onConfigure();-- IndexManager indexManager = GitPlex.getInstance(IndexManager.class);- if (!indexManager.isIndexed(getRepository(), blobIdent.revision)) {- GitPlex.getInstance(IndexManager.class).index(getRepository(), blobIdent.revision);- setVisible(true);- } else {- setVisible(false);- }- }-- });-- newLastCommit(null);- newFileViewer(null, clientState);-- add(searchResultContainer = new WebMarkupContainer("searchResultContainer"));-- newSearchResult(null, queryHits);-- add(new WebSocketRenderBehavior() {-- @Override- protected WebSocketTrait getTrait() {- return trait;- }-- @Override- protected void onRender(WebSocketRequestHandler handler, WebSocketTrait trait) {- handler.add(revisionIndexing);- resizeWindow(handler);- }-- });- if (getPullRequest() != null) {- add(new PullRequestChangeRenderer() {-- @Override- protected PullRequest getPullRequest() {- return RepoFilePage.this.getPullRequest();- }-- });- }- }-- @Override- public Comment getComment() {- return commentModel.getObject();- }-- @Override- public PullRequest getPullRequest() {- return requestModel.getObject();- }-- private void newFileNavigator(@Nullable AjaxRequestTarget target) {- final BlobNameChangeCallback callback;-- if (mode == Mode.EDIT) {- callback = new BlobNameChangeCallback() {-- @Override- public void onChange(AjaxRequestTarget target, String blobName) {- String newPath;- if (blobIdent.isTree()) {- if (blobIdent.path != null)- newPath = blobIdent.path + "/" + blobName;- else- newPath = blobName;- } else {- if (blobIdent.path.contains("/"))- newPath = StringUtils.substringBeforeLast(blobIdent.path, "/") + "/" + blobName;- else- newPath = blobName;- }- newPathRef.set(GitUtils.normalizePath(newPath));- ((FileEditPanel) get(FILE_VIEWER_ID)).onNewPathChange(target, newPathRef.get());- }-- };- } else {- callback = null;- }-- Component fileNavigator = new FileNavigator(FILE_NAVIGATOR_ID, repoModel, requestModel, blobIdent, callback) {-- @Override- protected void onSelect(AjaxRequestTarget target, BlobIdent file) {- RepoFilePage.this.onSelect(target, file, null);- }-- @Override- protected void onNewFile(AjaxRequestTarget target) {- mode = Mode.EDIT;-- newFileNavigator(target);- newFileViewer(target, null);-- pushState(target);- resizeWindow(target);- }-- };- if (target != null) {- replace(fileNavigator);- target.add(fileNavigator);- } else {- add(fileNavigator);- }- }-- private void newLastCommit(@Nullable AjaxRequestTarget target) {- Component lastCommit = new AjaxLazyLoadPanel(LAST_COMMIT_ID) {-- @Override- public Component getLoadingComponent(String markupId) {- IRequestHandler handler = new ResourceReferenceRequestHandler(AbstractDefaultAjaxBehavior.INDICATOR);- String html = "<img src='" + RequestCycle.get().urlFor(handler) + "' class='loading'/> Loading latest commit...";- return new Label(markupId, html).setEscapeModelStrings(false);- }-- @Override- protected void onComponentLoaded(Component component, AjaxRequestTarget target) {- super.onComponentLoaded(component, target);- resizeWindow(target);- }-- @Override- public Component getLazyLoadComponent(String markupId) {- return new LastCommitPanel(markupId, repoModel, blobIdent);- }-- };- if (target != null) {- replace(lastCommit);- target.add(lastCommit);- } else {- add(lastCommit);- }- }-- private BlobViewPanel renderBlobViewer(String panelId, @Nullable String clientState) {- for (BlobRenderer renderer: GitPlex.getExtensions(BlobRenderer.class)) {- BlobViewPanel panel = renderer.render(panelId, this, clientState);- if (panel != null)- return panel;- }-- throw new IllegalStateException("No applicable blob renderer found.");- }-- private void newFileViewer(@Nullable AjaxRequestTarget target, @Nullable String clientState) {- Component fileViewer;- if (mode == Mode.EDIT) {- final String refName = GitUtils.branch2ref(blobIdent.revision);- newPathRef = new AtomicReference<>(blobIdent.isTree()?null:blobIdent.path);- fileViewer = new FileEditPanel(- FILE_VIEWER_ID, repoModel, refName,- blobIdent.isTree()?null:blobIdent.path,- blobIdent.isTree()?"":getRepository().getBlob(blobIdent).getText().getContent(),- getRepository().getObjectId(blobIdent.revision), mark, clientState) {-- @Override- protected void onCommitted(AjaxRequestTarget target, ObjectId newCommitId) {- Repository repository = getRepository();- String branch = blobIdent.revision;- repository.cacheObjectId(branch, newCommitId);- BlobIdent committed = new BlobIdent(- branch, newPathRef.get(), FileMode.REGULAR_FILE.getBits());- for (RefListener listener: GitPlex.getExtensions(RefListener.class))- listener.onRefUpdate(repository, refName, newCommitId.name());-- RepoFileState state = getState();- state.blobIdent = committed;- state.mode = null;- applyState(target, state);- pushState(target);- resizeWindow(target);- }-- @Override- protected void onCancel(AjaxRequestTarget target) {- mode = null;- newFileNavigator(target);- newFileViewer(target, null);- pushState(target);- resizeWindow(target);- }-- };- } else if (mode == Mode.DELETE) {- final String refName = GitUtils.branch2ref(blobIdent.revision);-- CancelListener cancelListener = new CancelListener() {-- @Override- public void onCancel(AjaxRequestTarget target) {- mode = null;-- newFileViewer(target, null);-- pushState(target);- resizeWindow(target);- }-- };-- fileViewer = new EditSavePanel(FILE_VIEWER_ID, repoModel, refName, blobIdent.path,- null, getRepository().getObjectId(blobIdent.revision), cancelListener) {-- @Override- protected void onCommitted(AjaxRequestTarget target, ObjectId newCommitId) {- Repository repository = getRepository();- String branch = blobIdent.revision;- repository.cacheObjectId(branch, newCommitId);- try ( FileRepository jgitRepo = repository.openAsJGitRepo();- RevWalk revWalk = new RevWalk(jgitRepo)) {- RevTree revTree = getRepository().getRevCommit(newCommitId, true).getTree();- String parentPath = StringUtils.substringBeforeLast(blobIdent.path, "/");- while (TreeWalk.forPath(jgitRepo, parentPath, revTree) == null) {- if (parentPath.contains("/")) {- parentPath = StringUtils.substringBeforeLast(parentPath, "/");- } else {- parentPath = null;- break;- }- }- for (RefListener listener: GitPlex.getExtensions(RefListener.class))- listener.onRefUpdate(repository, refName, newCommitId.name());- BlobIdent parentBlobIdent = new BlobIdent(branch, parentPath, FileMode.TREE.getBits());- RepoFileState state = getState();- state.blobIdent = parentBlobIdent;- state.mode = null;- applyState(target, state);- pushState(target);- resizeWindow(target);- } catch (IOException e) {- throw new RuntimeException(e);- }- }-- };- } else if (blobIdent.path == null || blobIdent.isTree()) {- fileViewer = new FileListPanel(FILE_VIEWER_ID, repoModel, requestModel, blobIdent) {-- @Override- protected void onSelect(AjaxRequestTarget target, BlobIdent file) {- RepoFilePage.this.onSelect(target, file, null);- }-- };- } else {- fileViewer = renderBlobViewer(FILE_VIEWER_ID, clientState);- }- if (target != null) {- replace(fileViewer);- target.add(fileViewer);- } else {- add(fileViewer);- }- }-- private void pushState(AjaxRequestTarget target) {- PageParameters params = paramsOf(getRepository(), getState());- CharSequence url = RequestCycle.get().urlFor(RepoFilePage.class, params);- pushState(target, url.toString(), getState());- }-- private RepoFileState getState() {- RepoFileState state = new RepoFileState();- state.blobIdent = new BlobIdent(blobIdent);- state.commentId = commentId;- state.mark = mark;- state.mode = mode;- state.requestId = requestId;- return state;- }-- private void setState(RepoFileState state) {- blobIdent = new BlobIdent(state.blobIdent);- commentId = state.commentId;- mark = state.mark;- mode = state.mode;- requestId = state.requestId;- }-- private void newRevisionPicker(@Nullable AjaxRequestTarget target) {- Component revisionPicker = new RevisionPicker(REVISION_PICKER_ID, repoModel, blobIdent.revision) {-- @Override- protected String getRevisionUrl(String revision) {- RepoFileState state = new RepoFileState();- state.blobIdent.revision = revision;- PageParameters params = RepoFilePage.paramsOf(repoModel.getObject(), state);- return urlFor(RepoFilePage.class, params).toString();- }-- @Override- protected void onSelect(AjaxRequestTarget target, String revision) {- RepoFileState state = getState();- state.blobIdent.revision = revision;- state.requestId = null;- state.commentId = null;- state.mode = null;- state.mark = null;-- if (state.blobIdent.path != null) {- try ( FileRepository jgitRepo = getRepository().openAsJGitRepo();- RevWalk revWalk = new RevWalk(jgitRepo)) {- RevTree revTree = getRepository().getRevCommit(revision, true).getTree();- TreeWalk treeWalk = TreeWalk.forPath(jgitRepo, blobIdent.path, revTree);- if (treeWalk != null) {- state.blobIdent.mode = treeWalk.getRawMode(0);- } else {- state.blobIdent.path = null;- state.blobIdent.mode = FileMode.TREE.getBits();- }- } catch (IOException e) {- throw new RuntimeException(e);- }- }-- applyState(target, state);- pushState(target);- resizeWindow(target);- }-- };- if (target != null) {- replace(revisionPicker);- target.add(revisionPicker);- } else {- add(revisionPicker);- }- }-- private void applyState(AjaxRequestTarget target, RepoFileState state) {- if (!state.blobIdent.revision.equals(blobIdent.revision))- newSearchResult(target, null);-- setState(state);- trait.revision = blobIdent.revision;-- newRevisionPicker(target);-- target.add(commentContext);-- newFileNavigator(target);-- target.add(revisionIndexing);-- newLastCommit(target);- newFileViewer(target, null);- }-- @Override- public void renderHead(IHeaderResponse response) {- super.renderHead(response);-- response.render(JavaScriptHeaderItem.forReference(ClosestDescendantResourceReference.INSTANCE));- response.render(JavaScriptHeaderItem.forReference(CookiesResourceReference.INSTANCE));- response.render(JQueryUIResizableJavaScriptReference.asHeaderItem());-- response.render(JavaScriptHeaderItem.forReference(- new JavaScriptResourceReference(RepoFilePage.class, "repo-file.js")));- response.render(CssHeaderItem.forReference(- new CssResourceReference(RepoFilePage.class, "repo-file.css")));- }-- public static PageParameters paramsOf(Repository repository, RepoFileState state) {- PageParameters params = paramsOf(repository);- if (state.blobIdent.revision != null)- params.set(PARAM_REVISION, state.blobIdent.revision);- if (state.blobIdent.path != null)- params.set(PARAM_PATH, state.blobIdent.path);- if (state.mark != null)- params.set(PARAM_MARK, state.mark.toString());- if (state.commentId != null)- params.set(PARAM_COMMENT, state.commentId);- if (state.requestId != null)- params.set(PARAM_REQUEST, state.requestId);- if (state.mode != null)- params.set(PARAM_MODE, state.mode.name().toLowerCase());- if (state.query != null)- params.set(PARAM_QUERY, state.query);- if (state.clientState != null)- params.set(PARAM_CLIENT_STATE, state.clientState);- return params;- }-- private void newSearchResult(@Nullable AjaxRequestTarget target, @Nullable List<QueryHit> hits) {- Component searchResult;- if (hits != null) {- searchResult = new SearchResultPanel(SEARCH_RESULD_ID, this, hits) {-- @Override- protected void onClose(AjaxRequestTarget target) {- newSearchResult(target, null);- resizeWindow(target);- }-- };- if (target != null) {- target.appendJavaScript(""- + "$('#repo-file>.search-result').show(); "- + "$('#repo-file .search-result>.body').focus();");- }- } else {- searchResult = new WebMarkupContainer(SEARCH_RESULD_ID).setOutputMarkupId(true);- if (target != null)- target.appendJavaScript("$('#repo-file>.search-result').hide();");- else- searchResultContainer.add(AttributeAppender.replace("style", "display: none;"));- }- if (target != null) {- searchResultContainer.replace(searchResult);- target.add(searchResult);- } else {- searchResultContainer.add(searchResult);- }- }-- @Override- protected void onPopState(AjaxRequestTarget target, Serializable data) {- super.onPopState(target, data);-- applyState(target, (RepoFileState) data);- resizeWindow(target);- }-- private void resizeWindow(AjaxRequestTarget target) {- target.appendJavaScript("$(window).resize();");- }-- @Override- protected void onSelect(AjaxRequestTarget target, Repository repository) {- setResponsePage(RepoFilePage.class, paramsOf(repository));- }-- private static class RevisionIndexed implements WebSocketTrait {-- Long repoId;-- volatile String revision;-- @Override- public boolean is(WebSocketTrait trait) {- if (trait == null || !(trait instanceof RevisionIndexed))- return false;- RevisionIndexed other = (RevisionIndexed) trait;- return Objects.equal(repoId, other.repoId) && Objects.equal(revision, other.revision);- }-- }-- @Override- protected void onDetach() {- requestModel.detach();- commentModel.detach();-- super.onDetach();- }-- public static class IndexedListener implements IndexListener {-- @Override- public void commitIndexed(Repository repository, String revision) {- RevisionIndexed trait = new RevisionIndexed();- trait.repoId = repository.getId();- trait.revision = revision;- WebSocketRenderBehavior.requestToRender(trait);- }-- @Override- public void indexRemoving(Repository repository) {- }-- }-- @Override- public BlobIdent getBlobIdent() {- return blobIdent;- }-- @Override- public Mark getMark() {- return mark;- }-- @Override- public Mode getMode() {- return mode;- }-- @Override- public void onSelect(AjaxRequestTarget target, BlobIdent blobIdent, @Nullable TokenPosition tokenPos) {- Preconditions.checkArgument(blobIdent.revision.equals(this.blobIdent.revision));-- mark = Mark.of(tokenPos);- if (blobIdent.equals(this.blobIdent)) {- if (mark != null) {- Component fileViewer = get(FILE_VIEWER_ID);- if (fileViewer instanceof SourceViewPanel) {- SourceViewPanel sourceViewer = (SourceViewPanel) fileViewer;- sourceViewer.mark(target, mark);- } else if (fileViewer instanceof FileEditPanel) {- FileEditPanel fileEditor = (FileEditPanel) fileViewer;- fileEditor.mark(target, mark);- } else {- newFileViewer(target, null);- resizeWindow(target);- }- }- } else {- this.blobIdent = blobIdent;- mode = null;-- newFileNavigator(target);- newLastCommit(target);- newFileViewer(target, null);-- resizeWindow(target);- }- pushState(target);- }-- @Override- public void onSearchComplete(AjaxRequestTarget target, List<QueryHit> hits) {- newSearchResult(target, hits);- resizeWindow(target);- }-- @Override- public void onBlameChange(AjaxRequestTarget target, @Nullable String cmState) {- if (mode == null)- mode = Mode.BLAME;- else- mode = null;- newFileViewer(target, cmState);- pushState(target);- resizeWindow(target);- }-- @Override- public void onDelete(AjaxRequestTarget target) {- mode = Mode.DELETE;-- newFileViewer(target, null);- pushState(target);- resizeWindow(target);- }-- @Override- public void onEdit(AjaxRequestTarget target, @Nullable String cmState) {- mode = Mode.EDIT;-- newFileNavigator(target);- newFileViewer(target, cmState);- pushState(target);- resizeWindow(target);- }-- @Override- public boolean isOnBranch() {- return getRepository().getRefs(Constants.R_HEADS).containsKey(blobIdent.revision);- }-- @Override- public boolean isAtSourceBranchHead() {- PullRequest request = getPullRequest();- return request != null && request.getSourceRepo() != null- && blobIdent.revision.equals(request.getSource().getHead(false));- }--}+package com.pmease.gitplex.web.page.repository.file;++import java.io.IOException;+import java.io.Serializable;+import java.util.ArrayList;+import java.util.List;+import java.util.concurrent.atomic.AtomicReference;++import javax.annotation.Nullable;++import org.apache.commons.lang3.StringUtils;+import org.apache.wicket.Component;+import org.apache.wicket.MetaDataKey;+import org.apache.wicket.RestartResponseException;+import org.apache.wicket.ajax.AbstractDefaultAjaxBehavior;+import org.apache.wicket.ajax.AjaxRequestTarget;+import org.apache.wicket.behavior.AttributeAppender;+import org.apache.wicket.extensions.ajax.markup.html.AjaxLazyLoadPanel;+import org.apache.wicket.markup.head.CssHeaderItem;+import org.apache.wicket.markup.head.IHeaderResponse;+import org.apache.wicket.markup.head.JavaScriptHeaderItem;+import org.apache.wicket.markup.html.WebMarkupContainer;+import org.apache.wicket.markup.html.basic.Label;+import org.apache.wicket.markup.html.image.Image;+import org.apache.wicket.model.AbstractReadOnlyModel;+import org.apache.wicket.model.IModel;+import org.apache.wicket.model.LoadableDetachableModel;+import org.apache.wicket.protocol.ws.api.WebSocketRequestHandler;+import org.apache.wicket.request.IRequestHandler;+import org.apache.wicket.request.cycle.RequestCycle;+import org.apache.wicket.request.handler.resource.ResourceReferenceRequestHandler;+import org.apache.wicket.request.mapper.parameter.PageParameters;+import org.apache.wicket.request.resource.CssResourceReference;+import org.apache.wicket.request.resource.JavaScriptResourceReference;+import org.apache.wicket.request.resource.PackageResourceReference;+import org.eclipse.jgit.internal.storage.file.FileRepository;+import org.eclipse.jgit.lib.Constants;+import org.eclipse.jgit.lib.FileMode;+import org.eclipse.jgit.lib.ObjectId;+import org.eclipse.jgit.revwalk.RevTree;+import org.eclipse.jgit.revwalk.RevWalk;+import org.eclipse.jgit.treewalk.TreeWalk;++import com.google.common.base.Objects;+import com.google.common.base.Preconditions;+import com.pmease.commons.git.BlobIdent;+import com.pmease.commons.git.GitUtils;+import com.pmease.commons.git.exception.ObjectNotExistException;+import com.pmease.commons.hibernate.dao.Dao;+import com.pmease.commons.lang.extractors.TokenPosition;+import com.pmease.commons.wicket.assets.closestdescendant.ClosestDescendantResourceReference;+import com.pmease.commons.wicket.assets.cookies.CookiesResourceReference;+import com.pmease.commons.wicket.behavior.TooltipBehavior;+import com.pmease.commons.wicket.component.modal.ModalLink;+import com.pmease.commons.wicket.websocket.WebSocketRenderBehavior;+import com.pmease.commons.wicket.websocket.WebSocketTrait;+import com.pmease.gitplex.core.GitPlex;+import com.pmease.gitplex.core.listeners.RefListener;+import com.pmease.gitplex.core.model.Comment;+import com.pmease.gitplex.core.model.PullRequest;+import com.pmease.gitplex.core.model.Repository;+import com.pmease.gitplex.search.IndexListener;+import com.pmease.gitplex.search.IndexManager;+import com.pmease.gitplex.search.SearchManager;+import com.pmease.gitplex.search.hit.QueryHit;+import com.pmease.gitplex.search.query.BlobQuery;+import com.pmease.gitplex.search.query.TextQuery;+import com.pmease.gitplex.web.WebSession;+import com.pmease.gitplex.web.component.repofile.blobsearch.advanced.AdvancedSearchPanel;+import com.pmease.gitplex.web.component.repofile.blobsearch.instant.InstantSearchPanel;+import com.pmease.gitplex.web.component.repofile.blobsearch.result.SearchResultPanel;+import com.pmease.gitplex.web.component.repofile.blobview.BlobNameChangeCallback;+import com.pmease.gitplex.web.component.repofile.blobview.BlobRenderer;+import com.pmease.gitplex.web.component.repofile.blobview.BlobViewContext;+import com.pmease.gitplex.web.component.repofile.blobview.BlobViewPanel;+import com.pmease.gitplex.web.component.repofile.blobview.source.SourceViewPanel;+import com.pmease.gitplex.web.component.repofile.editsave.CancelListener;+import com.pmease.gitplex.web.component.repofile.editsave.EditSavePanel;+import com.pmease.gitplex.web.component.repofile.fileedit.FileEditPanel;+import com.pmease.gitplex.web.component.repofile.filelist.FileListPanel;+import com.pmease.gitplex.web.component.repofile.filenavigator.FileNavigator;+import com.pmease.gitplex.web.component.revisionpicker.RevisionPicker;+import com.pmease.gitplex.web.page.repository.NoCommitsPage;+import com.pmease.gitplex.web.page.repository.RepositoryPage;+import com.pmease.gitplex.web.websocket.PullRequestChangeRenderer;++import de.agilecoders.wicket.core.markup.html.bootstrap.components.TooltipConfig;+import de.agilecoders.wicket.core.markup.html.bootstrap.components.TooltipConfig.Placement;+import de.agilecoders.wicket.extensions.markup.html.bootstrap.jqueryui.JQueryUIResizableJavaScriptReference;++@SuppressWarnings("serial")+public class RepoFilePage extends RepositoryPage implements BlobViewContext {++ private static class SearchResultKey extends MetaDataKey<ArrayList<QueryHit>> {+ };++ public static final SearchResultKey SEARCH_RESULT_KEY = new SearchResultKey();++ private static final String PARAM_REVISION = "revision";++ private static final String PARAM_PATH = "path";++ private static final String PARAM_REQUEST = "request";++ private static final String PARAM_COMMENT = "comment";++ private static final String PARAM_MODE = "mode";++ private static final String PARAM_QUERY = "query";++ private static final String PARAM_CLIENT_STATE = "client_state";++ private static final String PARAM_MARK = "mark";++ private static final String REVISION_PICKER_ID = "revisionPicker";++ private static final String FILE_NAVIGATOR_ID = "fileNavigator";++ private static final String LAST_COMMIT_ID = "lastCommit";++ private static final String FILE_VIEWER_ID = "fileViewer";++ private static final String SEARCH_RESULD_ID = "searchResult";++ private Long requestId;++ private Long commentId;++ private final IModel<Comment> commentModel = new LoadableDetachableModel<Comment>() {++ @Override+ protected Comment load() {+ if (commentId != null)+ return GitPlex.getInstance(Dao.class).load(Comment.class, commentId);+ else+ return null;+ }++ };++ private final IModel<PullRequest> requestModel = new LoadableDetachableModel<PullRequest>() {++ @Override+ protected PullRequest load() {+ Comment comment = getComment();+ if (comment != null)+ return comment.getRequest();+ else if (requestId != null)+ return GitPlex.getInstance(Dao.class).load(PullRequest.class, requestId);+ else+ return null;+ }+ };++ private BlobIdent blobIdent = new BlobIdent();++ private Mark mark;++ private Mode mode;++ private Component commentContext;++ private Component revisionIndexing;++ private WebMarkupContainer searchResultContainer;++ private AtomicReference<String> newPathRef;++ private final RevisionIndexed trait = new RevisionIndexed();++ private transient List<QueryHit> queryHits;++ // client state holding CodeMirror cursor, scroll, marks, etc.+ private transient String clientState;++ public RepoFilePage(final PageParameters params) {+ super(params);++ if (!getRepository().git().hasCommits())+ throw new RestartResponseException(NoCommitsPage.class, paramsOf(getRepository()));++ trait.repoId = getRepository().getId();++ commentId = params.get(PARAM_COMMENT).toOptionalLong();+ blobIdent.revision = params.get(PARAM_REVISION).toString();+ blobIdent.path = GitUtils.normalizePath(params.get(PARAM_PATH).toString());++ Comment comment = commentModel.getObject();+ if (comment != null) {+ if (blobIdent.revision != null || blobIdent.path != null)+ throw new IllegalArgumentException("Revision or path should not be specified if comment is specified");+ blobIdent = comment.getBlobIdent();+ } else {+ requestId = params.get(PARAM_REQUEST).toOptionalLong();++ blobIdent.revision = GitUtils.normalizePath(params.get(PARAM_REVISION).toString());+ if (blobIdent.revision == null)+ blobIdent.revision = getRepository().getDefaultBranch();++ if (requestId != null && !GitUtils.isHash(blobIdent.revision))+ throw new IllegalArgumentException("Pull request can only be associated with a hash revision");+ }++ trait.revision = blobIdent.revision;++ if (blobIdent.path != null) {+ try ( FileRepository jgitRepo = getRepository().openAsJGitRepo();+ RevWalk revWalk = new RevWalk(jgitRepo)) {+ RevTree revTree = getRepository().getRevCommit(getCommitId(), true).getTree();+ TreeWalk treeWalk = TreeWalk.forPath(jgitRepo, blobIdent.path, revTree);+ if (treeWalk == null) {+ throw new ObjectNotExistException("Unable to find blob path '" + blobIdent.path+ + "' in revision '" + blobIdent.revision + "'");+ }+ blobIdent.mode = treeWalk.getRawMode(0);+ } catch (IOException e) {+ throw new RuntimeException(e);+ }+ } else {+ blobIdent.mode = FileMode.TREE.getBits();+ }++ String modeStr = params.get(PARAM_MODE).toString();+ if (modeStr != null)+ mode = Mode.valueOf(modeStr.toUpperCase());+ String markStr = params.get(PARAM_MARK).toString();+ if (markStr != null)+ mark = new Mark(markStr);++ queryHits = WebSession.get().getMetaData(SEARCH_RESULT_KEY);+ if (queryHits != null) {+ WebSession.get().setMetaData(SEARCH_RESULT_KEY, null);+ } else {+ String symbol = params.get(PARAM_QUERY).toString();+ if (symbol != null) {+ BlobQuery query = new TextQuery(symbol, false, true, true,+ null, null, SearchResultPanel.MAX_QUERY_ENTRIES);+ try {+ SearchManager searchManager = GitPlex.getInstance(SearchManager.class);+ queryHits = searchManager.search(repoModel.getObject(), blobIdent.revision, query);+ } catch (InterruptedException e) {+ throw new RuntimeException(e);+ }+ }+ }++ clientState = params.get(PARAM_CLIENT_STATE).toString();+ }++ private ObjectId getCommitId() {+ return getRepository().getObjectId(blobIdent.revision);+ }++ @Override+ protected void onInitialize() {+ super.onInitialize();++ add(new InstantSearchPanel("instantSearch", repoModel, requestModel, new AbstractReadOnlyModel<String>() {++ @Override+ public String getObject() {+ return blobIdent.revision;+ }++ }) {++ @Override+ protected void onSelect(AjaxRequestTarget target, QueryHit hit) {+ BlobIdent selected = new BlobIdent(blobIdent.revision, hit.getBlobPath(),+ FileMode.REGULAR_FILE.getBits());+ RepoFilePage.this.onSelect(target, selected, hit.getTokenPos());+ }++ @Override+ protected void onMoreQueried(AjaxRequestTarget target, List<QueryHit> hits) {+ newSearchResult(target, hits);+ resizeWindow(target);+ }++ });++ add(new ModalLink("advancedSearch") {++ @Override+ protected Component newContent(String id) {+ return new AdvancedSearchPanel(id, repoModel, new AbstractReadOnlyModel<String>() {++ @Override+ public String getObject() {+ return blobIdent.revision;+ }++ }) {++ @Override+ protected void onSearchComplete(AjaxRequestTarget target, List<QueryHit> hits) {+ newSearchResult(target, hits);+ resizeWindow(target);+ close(target);+ }++ @Override+ protected void onCancel(AjaxRequestTarget target) {+ close(target);+ }++ @Override+ protected BlobIdent getCurrentBlob() {+ return blobIdent;+ }++ };+ }++ });++ newRevisionPicker(null);++ add(commentContext = new WebMarkupContainer("commentContext") {++ @Override+ protected void onConfigure() {+ super.onConfigure();++ setVisible(getPullRequest() != null);+ }++ @Override+ protected void onInitialize() {+ super.onInitialize();++ add(new TooltipBehavior(new AbstractReadOnlyModel<String>() {++ @Override+ public String getObject() {+ PullRequest request = getPullRequest();+ String tooltip = String.format("Inline comments added/displayed in "+ + "this commit belong to pull request #%d (%s)",+ request.getId(), request.getTitle());+ return tooltip;+ }++ }, new TooltipConfig().withPlacement(Placement.bottom)));++ setOutputMarkupPlaceholderTag(true);+ }++ });++ newFileNavigator(null);++ add(revisionIndexing = new WebMarkupContainer("revisionIndexing") {++ @Override+ protected void onInitialize() {+ super.onInitialize();+ add(new Image("icon", new PackageResourceReference(RepoFilePage.class, "indexing.gif")));+ setOutputMarkupPlaceholderTag(true);+ }++ @Override+ protected void onConfigure() {+ super.onConfigure();++ IndexManager indexManager = GitPlex.getInstance(IndexManager.class);+ if (!indexManager.isIndexed(getRepository(), blobIdent.revision)) {+ GitPlex.getInstance(IndexManager.class).index(getRepository(), blobIdent.revision);+ setVisible(true);+ } else {+ setVisible(false);+ }+ }++ });++ newLastCommit(null);+ newFileViewer(null, clientState);++ add(searchResultContainer = new WebMarkupContainer("searchResultContainer"));++ newSearchResult(null, queryHits);++ add(new WebSocketRenderBehavior() {++ @Override+ protected WebSocketTrait getTrait() {+ return trait;+ }++ @Override+ protected void onRender(WebSocketRequestHandler handler, WebSocketTrait trait) {+ handler.add(revisionIndexing);+ resizeWindow(handler);+ }++ });+ if (getPullRequest() != null) {+ add(new PullRequestChangeRenderer() {++ @Override+ protected PullRequest getPullRequest() {+ return RepoFilePage.this.getPullRequest();+ }++ });+ }+ }++ @Override+ public Comment getComment() {+ return commentModel.getObject();+ }++ @Override+ public PullRequest getPullRequest() {+ return requestModel.getObject();+ }++ private void newFileNavigator(@Nullable AjaxRequestTarget target) {+ final BlobNameChangeCallback callback;++ if (mode == Mode.EDIT) {+ callback = new BlobNameChangeCallback() {++ @Override+ public void onChange(AjaxRequestTarget target, String blobName) {+ String newPath;+ if (blobIdent.isTree()) {+ if (blobIdent.path != null)+ newPath = blobIdent.path + "/" + blobName;+ else+ newPath = blobName;+ } else {+ if (blobIdent.path.contains("/"))+ newPath = StringUtils.substringBeforeLast(blobIdent.path, "/") + "/" + blobName;+ else+ newPath = blobName;+ }+ newPathRef.set(GitUtils.normalizePath(newPath));+ ((FileEditPanel) get(FILE_VIEWER_ID)).onNewPathChange(target, newPathRef.get());+ }++ };+ } else {+ callback = null;+ }++ Component fileNavigator = new FileNavigator(FILE_NAVIGATOR_ID, repoModel, requestModel, blobIdent, callback) {++ @Override+ protected void onSelect(AjaxRequestTarget target, BlobIdent file) {+ RepoFilePage.this.onSelect(target, file, null);+ }++ @Override+ protected void onNewFile(AjaxRequestTarget target) {+ mode = Mode.EDIT;++ newFileNavigator(target);+ newFileViewer(target, null);++ pushState(target);+ resizeWindow(target);+ }++ };+ if (target != null) {+ replace(fileNavigator);+ target.add(fileNavigator);+ } else {+ add(fileNavigator);+ }+ }++ private void newLastCommit(@Nullable AjaxRequestTarget target) {+ Component lastCommit = new AjaxLazyLoadPanel(LAST_COMMIT_ID) {++ @Override+ public Component getLoadingComponent(String markupId) {+ IRequestHandler handler = new ResourceReferenceRequestHandler(AbstractDefaultAjaxBehavior.INDICATOR);+ String html = "<img src='" + RequestCycle.get().urlFor(handler) + "' class='loading'/> Loading latest commit...";+ return new Label(markupId, html).setEscapeModelStrings(false);+ }++ @Override+ protected void onComponentLoaded(Component component, AjaxRequestTarget target) {+ super.onComponentLoaded(component, target);+ resizeWindow(target);+ }++ @Override+ public Component getLazyLoadComponent(String markupId) {+ return new LastCommitPanel(markupId, repoModel, blobIdent);+ }++ };+ if (target != null) {+ replace(lastCommit);+ target.add(lastCommit);+ } else {+ add(lastCommit);+ }+ }++ private BlobViewPanel renderBlobViewer(String panelId, @Nullable String clientState) {+ for (BlobRenderer renderer: GitPlex.getExtensions(BlobRenderer.class)) {+ BlobViewPanel panel = renderer.render(panelId, this, clientState);+ if (panel != null)+ return panel;+ }++ throw new IllegalStateException("No applicable blob renderer found.");+ }++ private void newFileViewer(@Nullable AjaxRequestTarget target, @Nullable String clientState) {+ Component fileViewer;+ if (mode == Mode.EDIT) {+ final String refName = GitUtils.branch2ref(blobIdent.revision);+ newPathRef = new AtomicReference<>(blobIdent.isTree()?null:blobIdent.path);+ fileViewer = new FileEditPanel(+ FILE_VIEWER_ID, repoModel, refName,+ blobIdent.isTree()?null:blobIdent.path,+ blobIdent.isTree()?"":getRepository().getBlob(blobIdent).getText().getContent(),+ getRepository().getObjectId(blobIdent.revision), mark, clientState) {++ @Override+ protected void onCommitted(AjaxRequestTarget target, ObjectId newCommitId) {+ Repository repository = getRepository();+ String branch = blobIdent.revision;+ repository.cacheObjectId(branch, newCommitId);+ BlobIdent committed = new BlobIdent(+ branch, newPathRef.get(), FileMode.REGULAR_FILE.getBits());+ for (RefListener listener: GitPlex.getExtensions(RefListener.class))+ listener.onRefUpdate(repository, refName, newCommitId.name());++ RepoFileState state = getState();+ state.blobIdent = committed;+ state.mode = null;+ applyState(target, state);+ pushState(target);+ resizeWindow(target);+ }++ @Override+ protected void onCancel(AjaxRequestTarget target) {+ mode = null;+ newFileNavigator(target);+ newFileViewer(target, null);+ pushState(target);+ resizeWindow(target);+ }++ };+ } else if (mode == Mode.DELETE) {+ final String refName = GitUtils.branch2ref(blobIdent.revision);++ CancelListener cancelListener = new CancelListener() {++ @Override+ public void onCancel(AjaxRequestTarget target) {+ mode = null;++ newFileViewer(target, null);++ pushState(target);+ resizeWindow(target);+ }++ };++ fileViewer = new EditSavePanel(FILE_VIEWER_ID, repoModel, refName, blobIdent.path,+ null, getRepository().getObjectId(blobIdent.revision), cancelListener) {++ @Override+ protected void onCommitted(AjaxRequestTarget target, ObjectId newCommitId) {+ Repository repository = getRepository();+ String branch = blobIdent.revision;+ repository.cacheObjectId(branch, newCommitId);+ try ( FileRepository jgitRepo = repository.openAsJGitRepo();+ RevWalk revWalk = new RevWalk(jgitRepo)) {+ RevTree revTree = getRepository().getRevCommit(newCommitId, true).getTree();+ String parentPath = StringUtils.substringBeforeLast(blobIdent.path, "/");+ while (TreeWalk.forPath(jgitRepo, parentPath, revTree) == null) {+ if (parentPath.contains("/")) {+ parentPath = StringUtils.substringBeforeLast(parentPath, "/");+ } else {+ parentPath = null;+ break;+ }+ }+ for (RefListener listener: GitPlex.getExtensions(RefListener.class))+ listener.onRefUpdate(repository, refName, newCommitId.name());+ BlobIdent parentBlobIdent = new BlobIdent(branch, parentPath, FileMode.TREE.getBits());+ RepoFileState state = getState();+ state.blobIdent = parentBlobIdent;+ state.mode = null;+ applyState(target, state);+ pushState(target);+ resizeWindow(target);+ } catch (IOException e) {+ throw new RuntimeException(e);+ }+ }++ };+ } else if (blobIdent.path == null || blobIdent.isTree()) {+ fileViewer = new FileListPanel(FILE_VIEWER_ID, repoModel, requestModel, blobIdent) {++ @Override+ protected void onSelect(AjaxRequestTarget target, BlobIdent file) {+ RepoFilePage.this.onSelect(target, file, null);+ }++ };+ } else {+ fileViewer = renderBlobViewer(FILE_VIEWER_ID, clientState);+ }+ if (target != null) {+ replace(fileViewer);+ target.add(fileViewer);+ } else {+ add(fileViewer);+ }+ }++ private void pushState(AjaxRequestTarget target) {+ PageParameters params = paramsOf(getRepository(), getState());+ CharSequence url = RequestCycle.get().urlFor(RepoFilePage.class, params);+ pushState(target, url.toString(), getState());+ }++ private RepoFileState getState() {+ RepoFileState state = new RepoFileState();+ state.blobIdent = new BlobIdent(blobIdent);+ state.commentId = commentId;+ state.mark = mark;+ state.mode = mode;+ state.requestId = requestId;+ return state;+ }++ private void setState(RepoFileState state) {+ blobIdent = new BlobIdent(state.blobIdent);+ commentId = state.commentId;+ mark = state.mark;+ mode = state.mode;+ requestId = state.requestId;+ }++ private void newRevisionPicker(@Nullable AjaxRequestTarget target) {+ Component revisionPicker = new RevisionPicker(REVISION_PICKER_ID, repoModel, blobIdent.revision) {++ @Override+ protected String getRevisionUrl(String revision) {+ RepoFileState state = new RepoFileState();+ state.blobIdent.revision = revision;+ PageParameters params = RepoFilePage.paramsOf(repoModel.getObject(), state);+ return urlFor(RepoFilePage.class, params).toString();+ }++ @Override+ protected void onSelect(AjaxRequestTarget target, String revision) {+ RepoFileState state = getState();+ state.blobIdent.revision = revision;+ state.requestId = null;+ state.commentId = null;+ state.mode = null;+ state.mark = null;++ if (state.blobIdent.path != null) {+ try ( FileRepository jgitRepo = getRepository().openAsJGitRepo();+ RevWalk revWalk = new RevWalk(jgitRepo)) {+ RevTree revTree = getRepository().getRevCommit(revision, true).getTree();+ TreeWalk treeWalk = TreeWalk.forPath(jgitRepo, blobIdent.path, revTree);+ if (treeWalk != null) {+ state.blobIdent.mode = treeWalk.getRawMode(0);+ } else {+ state.blobIdent.path = null;+ state.blobIdent.mode = FileMode.TREE.getBits();+ }+ } catch (IOException e) {+ throw new RuntimeException(e);+ }+ }++ applyState(target, state);+ pushState(target);+ resizeWindow(target);+ }++ };+ if (target != null) {+ replace(revisionPicker);+ target.add(revisionPicker);+ } else {+ add(revisionPicker);+ }+ }++ private void applyState(AjaxRequestTarget target, RepoFileState state) {+ if (!state.blobIdent.revision.equals(blobIdent.revision))+ newSearchResult(target, null);++ setState(state);+ trait.revision = blobIdent.revision;++ newRevisionPicker(target);++ target.add(commentContext);++ newFileNavigator(target);++ target.add(revisionIndexing);++ newLastCommit(target);+ newFileViewer(target, null);+ }++ @Override+ public void renderHead(IHeaderResponse response) {+ super.renderHead(response);++ response.render(JavaScriptHeaderItem.forReference(ClosestDescendantResourceReference.INSTANCE));+ response.render(JavaScriptHeaderItem.forReference(CookiesResourceReference.INSTANCE));+ response.render(JQueryUIResizableJavaScriptReference.asHeaderItem());++ response.render(JavaScriptHeaderItem.forReference(+ new JavaScriptResourceReference(RepoFilePage.class, "repo-file.js")));+ response.render(CssHeaderItem.forReference(+ new CssResourceReference(RepoFilePage.class, "repo-file.css")));+ }++ public static PageParameters paramsOf(Repository repository, RepoFileState state) {+ PageParameters params = paramsOf(repository);+ if (state.blobIdent.revision != null)+ params.set(PARAM_REVISION, state.blobIdent.revision);+ if (state.blobIdent.path != null)+ params.set(PARAM_PATH, state.blobIdent.path);+ if (state.mark != null)+ params.set(PARAM_MARK, state.mark.toString());+ if (state.commentId != null)+ params.set(PARAM_COMMENT, state.commentId);+ if (state.requestId != null)+ params.set(PARAM_REQUEST, state.requestId);+ if (state.mode != null)+ params.set(PARAM_MODE, state.mode.name().toLowerCase());+ if (state.query != null)+ params.set(PARAM_QUERY, state.query);+ if (state.clientState != null)+ params.set(PARAM_CLIENT_STATE, state.clientState);+ return params;+ }++ private void newSearchResult(@Nullable AjaxRequestTarget target, @Nullable List<QueryHit> hits) {+ Component searchResult;+ if (hits != null) {+ searchResult = new SearchResultPanel(SEARCH_RESULD_ID, this, hits) {++ @Override+ protected void onClose(AjaxRequestTarget target) {+ newSearchResult(target, null);+ resizeWindow(target);+ }++ };+ if (target != null) {+ target.appendJavaScript(""+ + "$('#repo-file>.search-result').show(); "+ + "$('#repo-file .search-result>.body').focus();");+ }+ } else {+ searchResult = new WebMarkupContainer(SEARCH_RESULD_ID).setOutputMarkupId(true);+ if (target != null)+ target.appendJavaScript("$('#repo-file>.search-result').hide();");+ else+ searchResultContainer.add(AttributeAppender.replace("style", "display: none;"));+ }+ if (target != null) {+ searchResultContainer.replace(searchResult);+ target.add(searchResult);+ } else {+ searchResultContainer.add(searchResult);+ }+ }++ @Override+ protected void onPopState(AjaxRequestTarget target, Serializable data) {+ super.onPopState(target, data);++ applyState(target, (RepoFileState) data);+ resizeWindow(target);+ }++ private void resizeWindow(AjaxRequestTarget target) {+ target.appendJavaScript("$(window).resize();");+ }++ @Override+ protected void onSelect(AjaxRequestTarget target, Repository repository) {+ setResponsePage(RepoFilePage.class, paramsOf(repository));+ }++ private static class RevisionIndexed implements WebSocketTrait {++ Long repoId;++ volatile String revision;++ @Override+ public boolean is(WebSocketTrait trait) {+ if (trait == null || !(trait instanceof RevisionIndexed))+ return false;+ RevisionIndexed other = (RevisionIndexed) trait;+ return Objects.equal(repoId, other.repoId) && Objects.equal(revision, other.revision);+ }++ }++ @Override+ protected void onDetach() {+ requestModel.detach();+ commentModel.detach();++ super.onDetach();+ }++ public static class IndexedListener implements IndexListener {++ @Override+ public void commitIndexed(Repository repository, String revision) {+ RevisionIndexed trait = new RevisionIndexed();+ trait.repoId = repository.getId();+ trait.revision = revision;+ WebSocketRenderBehavior.requestToRender(trait);+ }++ @Override+ public void indexRemoving(Repository repository) {+ }++ }++ @Override+ public BlobIdent getBlobIdent() {+ return blobIdent;+ }++ @Override+ public Mark getMark() {+ return mark;+ }++ @Override+ public Mode getMode() {+ return mode;+ }++ @Override+ public void onSelect(AjaxRequestTarget target, BlobIdent blobIdent, @Nullable TokenPosition tokenPos) {+ Preconditions.checkArgument(blobIdent.revision.equals(this.blobIdent.revision));++ mark = Mark.of(tokenPos);+ if (blobIdent.equals(this.blobIdent)) {+ if (mark != null) {+ Component fileViewer = get(FILE_VIEWER_ID);+ if (fileViewer instanceof SourceViewPanel) {+ SourceViewPanel sourceViewer = (SourceViewPanel) fileViewer;+ sourceViewer.mark(target, mark);+ } else if (fileViewer instanceof FileEditPanel) {+ FileEditPanel fileEditor = (FileEditPanel) fileViewer;+ fileEditor.mark(target, mark);+ } else {+ newFileViewer(target, null);+ resizeWindow(target);+ }+ }+ } else {+ this.blobIdent = blobIdent;+ mode = null;++ newFileNavigator(target);+ newLastCommit(target);+ newFileViewer(target, null);++ resizeWindow(target);+ }+ pushState(target);+ }++ @Override+ public void onSearchComplete(AjaxRequestTarget target, List<QueryHit> hits) {+ newSearchResult(target, hits);+ resizeWindow(target);+ }++ @Override+ public void onBlameChange(AjaxRequestTarget target, @Nullable String cmState) {+ if (mode == null)+ mode = Mode.BLAME;+ else+ mode = null;+ newFileViewer(target, cmState);+ pushState(target);+ resizeWindow(target);+ }++ @Override+ public void onDelete(AjaxRequestTarget target) {+ mode = Mode.DELETE;++ newFileViewer(target, null);+ pushState(target);+ resizeWindow(target);+ }++ @Override+ public void onEdit(AjaxRequestTarget target, @Nullable String cmState) {+ mode = Mode.EDIT;++ newFileNavigator(target);+ newFileViewer(target, cmState);+ pushState(target);+ resizeWindow(target);+ }++ @Override+ public boolean isOnBranch() {+ return getRepository().getRefs(Constants.R_HEADS).containsKey(blobIdent.revision);+ }++ @Override+ public boolean isAtSourceBranchHead() {+ PullRequest request = getPullRequest();+ return request != null && request.getSourceRepo() != null+ && blobIdent.revision.equals(request.getSource().getObjectName(false));+ }++}diff --git a/gitplex.web/src/main/java/com/pmease/gitplex/web/page/repository/pullrequest/newrequest/NewRequestPage.java b/gitplex.web/src/main/java/com/pmease/gitplex/web/page/repository/pullrequest/newrequest/NewRequestPage.javaindex e5ea92858a..1aff5116f3 100644--- a/gitplex.web/src/main/java/com/pmease/gitplex/web/page/repository/pullrequest/newrequest/NewRequestPage.java+++ b/gitplex.web/src/main/java/com/pmease/gitplex/web/page/repository/pullrequest/newrequest/NewRequestPage.java@@ -141,7 +141,7 @@ public class NewRequestPage extends PullRequestPage {PullRequestUpdate update = new PullRequestUpdate();pullRequest.addUpdate(update);update.setRequest(pullRequest);- update.setHeadCommitHash(source.getHead());+ update.setHeadCommitHash(source.getObjectName());pullRequest.setLastEventDate(new Date());PullRequestManager pullRequestManager = GitPlex.getInstance(PullRequestManager.class);@@ -157,8 +157,8 @@ public class NewRequestPage extends PullRequestPage {if (target.getRepository().equals(source.getRepository())) {pullRequest.setBaseCommitHash(pullRequest.git().calcMergeBase(- target.getHead(), source.getHead()));- if (target.getRepository().isAncestor(source.getHead(), target.getHead())) {+ target.getObjectName(), source.getObjectName()));+ if (target.getRepository().isAncestor(source.getObjectName(), target.getObjectName())) {CloseInfo closeInfo = new CloseInfo();closeInfo.setCloseDate(new Date());closeInfo.setCloseStatus(CloseInfo.Status.INTEGRATED);@@ -172,9 +172,9 @@ public class NewRequestPage extends PullRequestPage {sandbox.fetch(source.getRepository().git(), source.getBranch());- pullRequest.setBaseCommitHash(pullRequest.git().calcMergeBase(target.getHead(), source.getHead()));+ pullRequest.setBaseCommitHash(pullRequest.git().calcMergeBase(target.getObjectName(), source.getObjectName()));- if (sandbox.isAncestor(source.getHead(), target.getHead())) {+ if (sandbox.isAncestor(source.getObjectName(), target.getObjectName())) {CloseInfo closeInfo = new CloseInfo();closeInfo.setCloseDate(new Date());closeInfo.setCloseStatus(CloseInfo.Status.INTEGRATED);@@ -459,8 +459,8 @@ public class NewRequestPage extends PullRequestPage {Dao dao = GitPlex.getInstance(Dao.class);RepoAndBranch target = getPullRequest().getTarget();RepoAndBranch source = getPullRequest().getSource();- if (!target.getHead().equals(getPullRequest().getTarget().getHead())- || !source.getHead().equals(getPullRequest().getSource().getHead())) {+ if (!target.getObjectName().equals(getPullRequest().getTarget().getObjectName())+ || !source.getObjectName().equals(getPullRequest().getSource().getObjectName())) {getSession().warn("Either target branch or source branch has new commits just now, please re-check.");setResponsePage(NewRequestPage.class, paramsOf(getRepository(), target, source));} else {diff --git a/gitplex.web/src/main/java/com/pmease/gitplex/web/page/repository/pullrequest/requestdetail/PullRequestOperation.java b/gitplex.web/src/main/java/com/pmease/gitplex/web/page/repository/pullrequest/requestdetail/PullRequestOperation.javaindex 805914c92a..65f894ced9 100644--- a/gitplex.web/src/main/java/com/pmease/gitplex/web/page/repository/pullrequest/requestdetail/PullRequestOperation.java+++ b/gitplex.web/src/main/java/com/pmease/gitplex/web/page/repository/pullrequest/requestdetail/PullRequestOperation.java@@ -1,172 +1,172 @@-package com.pmease.gitplex.web.page.repository.pullrequest.requestdetail;--import javax.annotation.Nullable;--import com.pmease.commons.git.Git;-import com.pmease.gitplex.core.GitPlex;-import com.pmease.gitplex.core.manager.PullRequestManager;-import com.pmease.gitplex.core.manager.ReviewManager;-import com.pmease.gitplex.core.manager.UserManager;-import com.pmease.gitplex.core.model.IntegrationPreview;-import com.pmease.gitplex.core.model.PullRequest;-import com.pmease.gitplex.core.model.PullRequest.Status;-import com.pmease.gitplex.core.model.Review;-import com.pmease.gitplex.core.model.ReviewInvitation;-import com.pmease.gitplex.core.model.User;-import com.pmease.gitplex.core.permission.ObjectPermission;-import com.pmease.gitplex.core.security.SecurityUtils;--public enum PullRequestOperation {- INTEGRATE {-- @Override- public boolean canOperate(PullRequest request) {- if (!SecurityUtils.getSubject().isPermitted(- ObjectPermission.ofRepoPush(request.getTargetRepo()))) {- return false;- } else {- return GitPlex.getInstance(PullRequestManager.class).canIntegrate(request);- }- }-- @Override- public void operate(PullRequest request, String comment) {- GitPlex.getInstance(PullRequestManager.class).integrate(request, comment);- }-- },- DISCARD {-- @Override- public boolean canOperate(PullRequest request) {- if (!SecurityUtils.canModify(request))- return false;- else- return request.isOpen();- }-- @Override- public void operate(PullRequest request, String comment) {- GitPlex.getInstance(PullRequestManager.class).discard(request, comment);- }-- },- APPROVE {-- @Override- public boolean canOperate(PullRequest request) {- return canReview(request);- }-- @Override- public void operate(PullRequest request, String comment) {- User user = GitPlex.getInstance(UserManager.class).getCurrent();- GitPlex.getInstance(ReviewManager.class).review(- request, user, Review.Result.APPROVE, comment);- }-- },- DISAPPROVE {-- @Override- public boolean canOperate(PullRequest request) {- return canReview(request);- }-- @Override- public void operate(PullRequest request, String comment) {- User user = GitPlex.getInstance(UserManager.class).getCurrent();- GitPlex.getInstance(ReviewManager.class).review(- request, user, Review.Result.DISAPPROVE, comment);- }-- },- REOPEN {-- @Override- public boolean canOperate(PullRequest request) {- PullRequestManager pullRequestManager = GitPlex.getInstance(PullRequestManager.class);- if (request.isOpen()- || !SecurityUtils.canModify(request)- || request.getTarget().getHead(false) == null- || request.getSourceRepo() == null- || request.getSource().getHead(false) == null- || pullRequestManager.findOpen(request.getTarget(), request.getSource()) != null) {- return false;- }-- // now check if source branch is integrated into target branch- Git git = request.getTargetRepo().git();- String sourceHead = request.getSource().getHead();- return git.parseRevision(sourceHead, false) == null- || !request.getTargetRepo().isAncestor(sourceHead, request.getTarget().getHead());- }-- @Override- public void operate(PullRequest request, String comment) {- GitPlex.getInstance(PullRequestManager.class).reopen(request, comment);- }-- },- DELETE_SOURCE_BRANCH {-- @Override- public void operate(PullRequest request, String comment) {- GitPlex.getInstance(PullRequestManager.class).deleteSourceBranch(request);- }-- @Override- public boolean canOperate(PullRequest request) {- IntegrationPreview preview = request.getLastIntegrationPreview();- PullRequestManager pullRequestManager = GitPlex.getInstance(PullRequestManager.class);- return request.getStatus() == Status.INTEGRATED- && request.getSourceRepo() != null- && request.getSource().getHead(false) != null- && !request.getSource().isDefault()- && preview != null- && (request.getSource().getHead().equals(preview.getRequestHead())- || request.getSource().getHead().equals(preview.getIntegrated()))- && SecurityUtils.canModify(request)- && SecurityUtils.canModify(request.getSource())- && pullRequestManager.queryOpenTo(request.getSource(), null).isEmpty();- }-- },- RESTORE_SOURCE_BRANCH {-- @Override- public void operate(PullRequest request, String comment) {- GitPlex.getInstance(PullRequestManager.class).restoreSourceBranch(request);- }-- @Override- public boolean canOperate(PullRequest request) {- return request.getSourceRepo() != null && request.getSource().getHead(false) == null- && SecurityUtils.canModify(request) && SecurityUtils.canCreate(request.getSource());- }-- };-- private static boolean canReview(PullRequest request) {- User user = GitPlex.getInstance(UserManager.class).getCurrent();-- // call request.getStatus() in order to trigger generation of review- // integrations which will be used in else condition- if (user == null- || request.getStatus() == PullRequest.Status.INTEGRATED- || request.getStatus() == PullRequest.Status.DISCARDED- || request.isReviewEffective(user)) {- return false;- } else {- for (ReviewInvitation invitation: request.getReviewInvitations()) {- if (invitation.isPreferred() && invitation.getReviewer().equals(user))- return true;- }- return false;- }- }-- public abstract void operate(PullRequest request, @Nullable String comment);-- public abstract boolean canOperate(PullRequest request);-}+package com.pmease.gitplex.web.page.repository.pullrequest.requestdetail;++import javax.annotation.Nullable;++import com.pmease.commons.git.Git;+import com.pmease.gitplex.core.GitPlex;+import com.pmease.gitplex.core.manager.PullRequestManager;+import com.pmease.gitplex.core.manager.ReviewManager;+import com.pmease.gitplex.core.manager.UserManager;+import com.pmease.gitplex.core.model.IntegrationPreview;+import com.pmease.gitplex.core.model.PullRequest;+import com.pmease.gitplex.core.model.PullRequest.Status;+import com.pmease.gitplex.core.model.Review;+import com.pmease.gitplex.core.model.ReviewInvitation;+import com.pmease.gitplex.core.model.User;+import com.pmease.gitplex.core.permission.ObjectPermission;+import com.pmease.gitplex.core.security.SecurityUtils;++public enum PullRequestOperation {+ INTEGRATE {++ @Override+ public boolean canOperate(PullRequest request) {+ if (!SecurityUtils.getSubject().isPermitted(+ ObjectPermission.ofRepoPush(request.getTargetRepo()))) {+ return false;+ } else {+ return GitPlex.getInstance(PullRequestManager.class).canIntegrate(request);+ }+ }++ @Override+ public void operate(PullRequest request, String comment) {+ GitPlex.getInstance(PullRequestManager.class).integrate(request, comment);+ }++ },+ DISCARD {++ @Override+ public boolean canOperate(PullRequest request) {+ if (!SecurityUtils.canModify(request))+ return false;+ else+ return request.isOpen();+ }++ @Override+ public void operate(PullRequest request, String comment) {+ GitPlex.getInstance(PullRequestManager.class).discard(request, comment);+ }++ },+ APPROVE {++ @Override+ public boolean canOperate(PullRequest request) {+ return canReview(request);+ }++ @Override+ public void operate(PullRequest request, String comment) {+ User user = GitPlex.getInstance(UserManager.class).getCurrent();+ GitPlex.getInstance(ReviewManager.class).review(+ request, user, Review.Result.APPROVE, comment);+ }++ },+ DISAPPROVE {++ @Override+ public boolean canOperate(PullRequest request) {+ return canReview(request);+ }++ @Override+ public void operate(PullRequest request, String comment) {+ User user = GitPlex.getInstance(UserManager.class).getCurrent();+ GitPlex.getInstance(ReviewManager.class).review(+ request, user, Review.Result.DISAPPROVE, comment);+ }++ },+ REOPEN {++ @Override+ public boolean canOperate(PullRequest request) {+ PullRequestManager pullRequestManager = GitPlex.getInstance(PullRequestManager.class);+ if (request.isOpen()+ || !SecurityUtils.canModify(request)+ || request.getTarget().getObjectName(false) == null+ || request.getSourceRepo() == null+ || request.getSource().getObjectName(false) == null+ || pullRequestManager.findOpen(request.getTarget(), request.getSource()) != null) {+ return false;+ }++ // now check if source branch is integrated into target branch+ Git git = request.getTargetRepo().git();+ String sourceHead = request.getSource().getObjectName();+ return git.parseRevision(sourceHead, false) == null+ || !request.getTargetRepo().isAncestor(sourceHead, request.getTarget().getObjectName());+ }++ @Override+ public void operate(PullRequest request, String comment) {+ GitPlex.getInstance(PullRequestManager.class).reopen(request, comment);+ }++ },+ DELETE_SOURCE_BRANCH {++ @Override+ public void operate(PullRequest request, String comment) {+ GitPlex.getInstance(PullRequestManager.class).deleteSourceBranch(request);+ }++ @Override+ public boolean canOperate(PullRequest request) {+ IntegrationPreview preview = request.getLastIntegrationPreview();+ PullRequestManager pullRequestManager = GitPlex.getInstance(PullRequestManager.class);+ return request.getStatus() == Status.INTEGRATED+ && request.getSourceRepo() != null+ && request.getSource().getObjectName(false) != null+ && !request.getSource().isDefault()+ && preview != null+ && (request.getSource().getObjectName().equals(preview.getRequestHead())+ || request.getSource().getObjectName().equals(preview.getIntegrated()))+ && SecurityUtils.canModify(request)+ && SecurityUtils.canModify(request.getSource())+ && pullRequestManager.queryOpenTo(request.getSource(), null).isEmpty();+ }++ },+ RESTORE_SOURCE_BRANCH {++ @Override+ public void operate(PullRequest request, String comment) {+ GitPlex.getInstance(PullRequestManager.class).restoreSourceBranch(request);+ }++ @Override+ public boolean canOperate(PullRequest request) {+ return request.getSourceRepo() != null && request.getSource().getObjectName(false) == null+ && SecurityUtils.canModify(request) && SecurityUtils.canCreate(request.getSource());+ }++ };++ private static boolean canReview(PullRequest request) {+ User user = GitPlex.getInstance(UserManager.class).getCurrent();++ // call request.getStatus() in order to trigger generation of review+ // integrations which will be used in else condition+ if (user == null+ || request.getStatus() == PullRequest.Status.INTEGRATED+ || request.getStatus() == PullRequest.Status.DISCARDED+ || request.isReviewEffective(user)) {+ return false;+ } else {+ for (ReviewInvitation invitation: request.getReviewInvitations()) {+ if (invitation.isPreferred() && invitation.getReviewer().equals(user))+ return true;+ }+ return false;+ }+ }++ public abstract void operate(PullRequest request, @Nullable String comment);++ public abstract boolean canOperate(PullRequest request);+}diff --git a/gitplex.web/src/main/java/com/pmease/gitplex/web/page/repository/pullrequest/requestdetail/compare/RequestComparePage.java b/gitplex.web/src/main/java/com/pmease/gitplex/web/page/repository/pullrequest/requestdetail/compare/RequestComparePage.javaindex 372a671f8a..fe043d675c 100644--- a/gitplex.web/src/main/java/com/pmease/gitplex/web/page/repository/pullrequest/requestdetail/compare/RequestComparePage.java+++ b/gitplex.web/src/main/java/com/pmease/gitplex/web/page/repository/pullrequest/requestdetail/compare/RequestComparePage.java@@ -140,7 +140,7 @@ public class RequestComparePage extends RequestDetailPage {}if (request.isOpen()) {- String targetHead = request.getTarget().getHead();+ String targetHead = request.getTarget().getObjectName();if (!choices.containsKey(targetHead)) {description = new CommitDescription("Target Branch Head",getRepository().getCommit(targetHead).getSubject());@@ -197,7 +197,7 @@ public class RequestComparePage extends RequestDetailPage {if (updates.get(i).getHeadCommitHash().equals(commitHash))return REV_UPDATE_PREFIX + (i+1);}- if (commitHash.equals(request.getTarget().getHead(false))) {+ if (commitHash.equals(request.getTarget().getObjectName(false))) {return REV_TARGET_BRANCH;} else {IntegrationPreview preview = request.getIntegrationPreview();@@ -222,7 +222,7 @@ public class RequestComparePage extends RequestDetailPage {elsereturn preview.getIntegrated();} else if (revision.equals(REV_TARGET_BRANCH)) {- return request.getTarget().getHead();+ return request.getTarget().getObjectName();} else if (revision.startsWith(REV_UPDATE_PREFIX)) {int updateNo = Integer.parseInt(revision.substring(REV_UPDATE_PREFIX.length()));if (updateNo == 0)