Skip to content

The Unified and Autonomous Development Platform

Suppress some non-necessary warning logs from wicket and hibernate

robin shine0883f51c85bb
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.java
index 4d7228280f..6e3c62c751 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,779 +1,779 @@
-package com.pmease.gitplex.core.manager.impl;
-
-import static com.pmease.gitplex.core.entity.PullRequest.CriterionHelper.ofOpen;
-import static com.pmease.gitplex.core.entity.PullRequest.CriterionHelper.ofSource;
-import static com.pmease.gitplex.core.entity.PullRequest.CriterionHelper.ofSourceDepot;
-import static com.pmease.gitplex.core.entity.PullRequest.CriterionHelper.ofSubmitter;
-import static com.pmease.gitplex.core.entity.PullRequest.CriterionHelper.ofTarget;
-import static com.pmease.gitplex.core.entity.PullRequest.CriterionHelper.ofTargetDepot;
-import static com.pmease.gitplex.core.entity.PullRequest.IntegrationStrategy.MERGE_ALWAYS;
-import static com.pmease.gitplex.core.entity.PullRequest.IntegrationStrategy.MERGE_IF_NECESSARY;
-import static com.pmease.gitplex.core.entity.PullRequest.IntegrationStrategy.MERGE_WITH_SQUASH;
-import static com.pmease.gitplex.core.entity.PullRequest.IntegrationStrategy.REBASE_SOURCE_ONTO_TARGET;
-import static com.pmease.gitplex.core.entity.PullRequest.IntegrationStrategy.REBASE_TARGET_ONTO_SOURCE;
-
-import java.util.Collection;
-import java.util.Date;
-import java.util.HashMap;
-import java.util.List;
-import java.util.Map;
-import java.util.concurrent.Callable;
-import java.util.concurrent.atomic.AtomicLong;
-
-import javax.annotation.Nullable;
-import javax.inject.Inject;
-import javax.inject.Singleton;
-
-import org.apache.shiro.subject.Subject;
-import org.apache.shiro.util.ThreadContext;
-import org.apache.wicket.request.cycle.RequestCycle;
-import org.eclipse.jgit.api.errors.GitAPIException;
-import org.eclipse.jgit.lib.CommitBuilder;
-import org.eclipse.jgit.lib.ObjectId;
-import org.eclipse.jgit.lib.ObjectInserter;
-import org.eclipse.jgit.lib.PersonIdent;
-import org.eclipse.jgit.lib.RefUpdate;
-import org.eclipse.jgit.revwalk.RevCommit;
-import org.eclipse.jgit.revwalk.RevWalk;
-import org.eclipse.jgit.transport.RefSpec;
-import org.hibernate.Query;
-import org.hibernate.criterion.Criterion;
-import org.hibernate.criterion.Order;
-import org.hibernate.criterion.Restrictions;
-import org.hibernate.resource.transaction.spi.TransactionStatus;
-import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
-
-import com.google.common.base.Preconditions;
-import com.google.common.base.Throwables;
-import com.google.common.collect.Lists;
-import com.pmease.commons.git.GitUtils;
-import com.pmease.commons.hibernate.Sessional;
-import com.pmease.commons.hibernate.Transactional;
-import com.pmease.commons.hibernate.UnitOfWork;
-import com.pmease.commons.hibernate.dao.AbstractEntityManager;
-import com.pmease.commons.hibernate.dao.Dao;
-import com.pmease.commons.hibernate.dao.EntityCriteria;
-import com.pmease.commons.loader.Listen;
-import com.pmease.commons.loader.ListenerRegistry;
-import com.pmease.commons.markdown.MarkdownManager;
-import com.pmease.commons.util.concurrent.Prioritized;
-import com.pmease.commons.util.match.PatternMatcher;
-import com.pmease.gitplex.core.entity.Account;
-import com.pmease.gitplex.core.entity.Depot;
-import com.pmease.gitplex.core.entity.PullRequest;
-import com.pmease.gitplex.core.entity.PullRequest.IntegrationStrategy;
-import com.pmease.gitplex.core.entity.PullRequestReviewInvitation;
-import com.pmease.gitplex.core.entity.PullRequestStatusChange;
-import com.pmease.gitplex.core.entity.PullRequestStatusChange.Type;
-import com.pmease.gitplex.core.entity.PullRequestUpdate;
-import com.pmease.gitplex.core.entity.support.CloseInfo;
-import com.pmease.gitplex.core.entity.support.DepotAndBranch;
-import com.pmease.gitplex.core.entity.support.IntegrationPolicy;
-import com.pmease.gitplex.core.entity.support.IntegrationPreview;
-import com.pmease.gitplex.core.event.RefUpdated;
-import com.pmease.gitplex.core.event.depot.DepotDeleted;
-import com.pmease.gitplex.core.event.pullrequest.IntegrationPreviewCalculated;
-import com.pmease.gitplex.core.event.pullrequest.PullRequestOpened;
-import com.pmease.gitplex.core.event.pullrequest.PullRequestPendingApproval;
-import com.pmease.gitplex.core.event.pullrequest.PullRequestPendingIntegration;
-import com.pmease.gitplex.core.event.pullrequest.PullRequestPendingUpdate;
-import com.pmease.gitplex.core.event.pullrequest.PullRequestStatusChangeEvent;
-import com.pmease.gitplex.core.gatekeeper.checkresult.Failed;
-import com.pmease.gitplex.core.gatekeeper.checkresult.GateCheckResult;
-import com.pmease.gitplex.core.gatekeeper.checkresult.Pending;
-import com.pmease.gitplex.core.manager.AccountManager;
-import com.pmease.gitplex.core.manager.BatchWorkManager;
-import com.pmease.gitplex.core.manager.PullRequestManager;
-import com.pmease.gitplex.core.manager.PullRequestReviewInvitationManager;
-import com.pmease.gitplex.core.manager.PullRequestStatusChangeManager;
-import com.pmease.gitplex.core.manager.PullRequestUpdateManager;
-import com.pmease.gitplex.core.manager.support.BatchWorker;
-import com.pmease.gitplex.core.security.SecurityUtils;
-import com.pmease.gitplex.core.util.ChildAwareMatcher;
-import com.pmease.gitplex.core.util.fullbranchmatch.FullBranchMatchUtils;
-import com.pmease.gitplex.core.util.includeexclude.IncludeExcludeUtils;
-
-@Singleton
-public class DefaultPullRequestManager extends AbstractEntityManager<PullRequest> implements PullRequestManager {
-
- 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 static final PatternMatcher BRANCH_MATCHER = new ChildAwareMatcher();
-
- private final PullRequestUpdateManager pullRequestUpdateManager;
-
- private final AccountManager accountManager;
-
- private final UnitOfWork unitOfWork;
-
- private final ListenerRegistry listenerRegistry;
-
- private final PullRequestReviewInvitationManager reviewInvitationManager;
-
- private final BatchWorkManager batchWorkManager;
-
- private final PullRequestStatusChangeManager pullRequestStatusChangeManager;
-
- private final Map<String, AtomicLong> nextNumbers = new HashMap<>();
-
- @Inject
- public DefaultPullRequestManager(Dao dao, PullRequestUpdateManager pullRequestUpdateManager,
- PullRequestReviewInvitationManager reviewInvitationManager, AccountManager accountManager,
- MarkdownManager markdownManager, BatchWorkManager batchWorkManager,
- ListenerRegistry listenerRegistry, UnitOfWork unitOfWork,
- PullRequestStatusChangeManager pullRequestStatusChangeManager) {
- super(dao);
-
- this.pullRequestUpdateManager = pullRequestUpdateManager;
- this.reviewInvitationManager = reviewInvitationManager;
- this.accountManager = accountManager;
- this.batchWorkManager = batchWorkManager;
- this.unitOfWork = unitOfWork;
- this.listenerRegistry = listenerRegistry;
- this.pullRequestStatusChangeManager = pullRequestStatusChangeManager;
- }
-
- @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, String note) {
- Preconditions.checkState(!request.isOpen() && request.getSourceDepot() != null);
- if (request.getSource().getObjectName(false) == null) {
- RevCommit latestCommit = request.getHeadCommit();
- try {
- request.getSourceDepot().git().branchCreate().setName(request.getSourceBranch()).setStartPoint(latestCommit).call();
- } catch (Exception e) {
- Throwables.propagate(e);
- }
- request.getSourceDepot().cacheObjectId(request.getSourceBranch(), latestCommit.copy());
-
- PullRequestStatusChange statusChange = new PullRequestStatusChange();
- statusChange.setDate(new Date());
- statusChange.setNote(note);
- statusChange.setRequest(request);
- statusChange.setType(Type.SOURCE_BRANCH_RESTORED);
- statusChange.setUser(accountManager.getCurrent());
- pullRequestStatusChangeManager.save(statusChange);
-
- request.setLastEvent(statusChange);
- save(request);
- }
- }
-
- @Transactional
- @Override
- public void deleteSourceBranch(PullRequest request, String note) {
- Preconditions.checkState(!request.isOpen() && request.getSourceDepot() != null);
-
- if (request.getSource().getObjectName(false) != null) {
- request.getSource().delete();
-
- PullRequestStatusChange statusChange = new PullRequestStatusChange();
- statusChange.setDate(new Date());
- statusChange.setNote(note);
- statusChange.setRequest(request);
- statusChange.setType(Type.SOURCE_BRANCH_DELETED);
- statusChange.setUser(accountManager.getCurrent());
- pullRequestStatusChangeManager.save(statusChange);
-
- request.setLastEvent(statusChange);
- save(request);
- }
- }
-
- @Transactional
- @Override
- public void reopen(PullRequest request, String note) {
- Account user = accountManager.getCurrent();
- request.setCloseInfo(null);
-
- PullRequestStatusChange statusChange = new PullRequestStatusChange();
- statusChange.setDate(new Date());
- statusChange.setNote(note);
- statusChange.setRequest(request);
- statusChange.setType(Type.REOPENED);
- statusChange.setUser(user);
- pullRequestStatusChangeManager.save(statusChange);
-
- request.setLastEvent(statusChange);
- save(request);
- checkAsync(request);
- }
-
- @Transactional
- @Override
- public void discard(PullRequest request, String note) {
- Account user = accountManager.getCurrent();
- Date date = new Date();
-
- CloseInfo closeInfo = new CloseInfo();
- closeInfo.setCloseDate(date);
- closeInfo.setClosedBy(user);
- closeInfo.setCloseStatus(CloseInfo.Status.DISCARDED);
- request.setCloseInfo(closeInfo);
-
- PullRequestStatusChange statusChange = new PullRequestStatusChange();
- statusChange.setDate(date);
- statusChange.setNote(note);
- statusChange.setRequest(request);
- statusChange.setType(Type.DISCARDED);
- statusChange.setUser(user);
- pullRequestStatusChangeManager.save(statusChange);
-
- request.setLastEvent(statusChange);
- save(request);
- }
-
- @Transactional
- @Override
- public void integrate(PullRequest request, String note) {
- 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.");
-
- Account user = accountManager.getCurrent();
-
- ObjectId integratedId = ObjectId.fromString(integrated);
- RevCommit integratedCommit = request.getTargetDepot().getRevCommit(integratedId);
-
- Depot targetDepot = request.getTargetDepot();
- IntegrationStrategy strategy = request.getIntegrationStrategy();
- if ((strategy == MERGE_ALWAYS || strategy == MERGE_IF_NECESSARY || strategy == MERGE_WITH_SQUASH)
- && !preview.getIntegrated().equals(preview.getRequestHead())
- && !integratedCommit.getFullMessage().equals(request.getCommitMessage())) {
- try ( RevWalk revWalk = new RevWalk(targetDepot.getRepository());
- ObjectInserter inserter = targetDepot.getRepository().newObjectInserter()) {
- CommitBuilder newCommit = new CommitBuilder();
- newCommit.setAuthor(integratedCommit.getAuthorIdent());
- newCommit.setCommitter(user.asPerson());
- newCommit.setMessage(request.getCommitMessage());
- newCommit.setTreeId(integratedCommit.getTree());
- newCommit.setParentIds(integratedCommit.getParents());
- integratedId = inserter.insert(newCommit);
- integrated = integratedId.name();
- inserter.flush();
- } catch (Exception e) {
- Throwables.propagate(e);
- }
- preview = new IntegrationPreview(preview.getTargetHead(), preview.getRequestHead(),
- preview.getIntegrationStrategy(), integrated);
- request.setLastIntegrationPreview(preview);
- RefUpdate refUpdate = targetDepot.updateRef(request.getIntegrateRef());
- refUpdate.setNewObjectId(integratedId);
- GitUtils.updateRef(refUpdate);
- }
-
- closeAsIntegrated(request, false, note);
-
- if (strategy == REBASE_SOURCE_ONTO_TARGET || strategy == MERGE_WITH_SQUASH) {
- Depot sourceDepot = request.getSourceDepot();
- if (!sourceDepot.equals(targetDepot)) {
- try {
- sourceDepot.git().fetch()
- .setRemote(targetDepot.getDirectory().getAbsolutePath())
- .setRefSpecs(new RefSpec(request.getIntegrateRef()))
- .call();
- } catch (GitAPIException e) {
- throw new RuntimeException(e);
- }
- }
- RefUpdate refUpdate = sourceDepot.updateRef(request.getSourceRef());
- refUpdate.setNewObjectId(integratedId);
- ObjectId requestHeadId = ObjectId.fromString(preview.getRequestHead());
- refUpdate.setExpectedOldObjectId(requestHeadId);
- refUpdate.setRefLogMessage("Pull request #" + request.getNumber(), true);
- GitUtils.updateRef(refUpdate);
-
- checkUpdate(request, false);
-
- Long requestId = request.getId();
- ObjectId newSourceHeadId = integratedId;
- Subject subject = SecurityUtils.getSubject();
- doUnitOfWorkAsyncAfterCommit(new Runnable() {
-
- @Override
- public void run() {
- ThreadContext.bind(subject);
- try {
- PullRequest request = load(requestId);
- request.getSourceDepot().cacheObjectId(request.getSourceRef(), newSourceHeadId);
- listenerRegistry.post(new RefUpdated(
- request.getSourceDepot(), request.getSourceRef(), requestHeadId, newSourceHeadId));
- } finally {
- ThreadContext.unbindSubject();
- }
- }
-
- });
- }
-
- String targetRef = request.getTargetRef();
- ObjectId targetHeadId = ObjectId.fromString(preview.getTargetHead());
- RefUpdate refUpdate = targetDepot.updateRef(targetRef);
- refUpdate.setRefLogIdent(user.asPerson());
- refUpdate.setRefLogMessage("Pull request #" + request.getNumber(), true);
- refUpdate.setExpectedOldObjectId(targetHeadId);
- refUpdate.setNewObjectId(integratedId);
- GitUtils.updateRef(refUpdate);
-
- Long requestId = request.getId();
- Subject subject = SecurityUtils.getSubject();
- ObjectId newTargetHeadId = integratedId;
- doUnitOfWorkAsyncAfterCommit(new Runnable() {
-
- @Override
- public void run() {
- ThreadContext.bind(subject);
- try {
- PullRequest request = load(requestId);
- request.getTargetDepot().cacheObjectId(request.getTargetRef(), newTargetHeadId);
- listenerRegistry.post(new RefUpdated(request.getTargetDepot(), targetRef,
- targetHeadId, newTargetHeadId));
- } finally {
- ThreadContext.unbindSubject();
- }
- }
-
- });
- }
-
- private long getNextNumber(Depot depot) {
- AtomicLong nextNumber;
- synchronized (nextNumbers) {
- nextNumber = nextNumbers.get(depot.getUUID());
- }
- if (nextNumber == null) {
- long maxNumber;
- Query query = getSession().createQuery("select max(number) from PullRequest where targetDepot=:depot");
- query.setParameter("depot", depot);
- Object result = query.uniqueResult();
- if (result != null) {
- maxNumber = (Long)result;
- } else {
- maxNumber = 0;
- }
-
- /*
- * do not put the whole method in synchronized block to avoid possible deadlocks
- * if there are limited connections.
- */
- synchronized (nextNumbers) {
- nextNumber = nextNumbers.get(depot.getUUID());
- if (nextNumber == null) {
- nextNumber = new AtomicLong(maxNumber+1);
- nextNumbers.put(depot.getUUID(), nextNumber);
- }
- }
- }
- return nextNumber.getAndIncrement();
- }
-
- @Transactional
- @Override
- public void open(PullRequest request) {
- request.setNumber(getNextNumber(request.getTargetDepot()));
- dao.persist(request);
-
- RefUpdate refUpdate = request.getTargetDepot().updateRef(request.getBaseRef());
- refUpdate.setNewObjectId(ObjectId.fromString(request.getBaseCommitHash()));
- GitUtils.updateRef(refUpdate);
-
- for (PullRequestUpdate update: request.getUpdates()) {
- pullRequestUpdateManager.save(update, false);
- }
-
- for (PullRequestReviewInvitation invitation: request.getReviewInvitations())
- reviewInvitationManager.save(invitation);
-
- checkAsync(request);
-
- listenerRegistry.post(new PullRequestOpened(request));
- }
-
- @Override
- public List<IntegrationStrategy> getApplicableIntegrationStrategies(PullRequest request) {
- List<IntegrationStrategy> strategies = null;
- for (IntegrationPolicy policy: request.getTargetDepot().getIntegrationPolicies()) {
- if (IncludeExcludeUtils.getIncludeExclude(policy.getTargetBranchMatch()).matches(BRANCH_MATCHER, request.getTargetBranch())
- && FullBranchMatchUtils.matches(policy.getSourceBranchMatch(), request.getTargetDepot(), request.getSource())) {
- strategies = policy.getIntegrationStrategies();
- break;
- }
- }
- if (strategies == null)
- strategies = Lists.newArrayList(IntegrationStrategy.MERGE_ALWAYS);
- return strategies;
- }
-
- @Transactional
- @Override
- public void changeAssignee(PullRequest request) {
- if (request.isOpen()) {
- String note = request.getAssignee().getDisplayName() + " is expected to integrate the pull request";
-
- PullRequestStatusChange statusChange = new PullRequestStatusChange();
- statusChange.setDate(new Date());
- statusChange.setNote(note);
- statusChange.setRequest(request);
- statusChange.setType(Type.ASSIGNED);
- statusChange.setUser(accountManager.getCurrent());
- pullRequestStatusChangeManager.save(statusChange);
-
- request.setLastEvent(statusChange);
- }
- save(request);
- }
-
- private void closeAsIntegrated(PullRequest request, boolean dueToMerged, String note) {
- Account user = accountManager.getCurrent();
- Date date = new Date();
-
- if (dueToMerged)
- request.setLastIntegrationPreview(null);
-
- CloseInfo closeInfo = new CloseInfo();
- closeInfo.setCloseDate(date);
- closeInfo.setClosedBy(user);
- closeInfo.setCloseStatus(CloseInfo.Status.INTEGRATED);
- request.setCloseInfo(closeInfo);
-
- if (dueToMerged)
- note = "Source branch is already merged to target branch by some one";
-
- PullRequestStatusChange statusChange = new PullRequestStatusChange();
- statusChange.setDate(date);
- statusChange.setNote(note);
- statusChange.setRequest(request);
- statusChange.setType(Type.INTEGRATED);
- statusChange.setUser(user);
- pullRequestStatusChangeManager.save(statusChange);
- request.setLastEvent(statusChange);
-
- save(request);
- }
-
- private void checkUpdate(PullRequest request, boolean independent) {
- if (!request.getHeadCommitHash().equals(request.getSource().getObjectName())) {
- PullRequestUpdate update = new PullRequestUpdate();
- update.setRequest(request);
- update.setHeadCommitHash(request.getSource().getObjectName());
- ObjectId mergeBase = GitUtils.getMergeBase(
- request.getTargetDepot().getRepository(), request.getTarget().getObjectId(),
- request.getSourceDepot().getRepository(), request.getSource().getObjectId(),
- GitUtils.branch2ref(request.getSourceBranch()));
- update.setMergeCommitHash(mergeBase.name());
- request.addUpdate(update);
- pullRequestUpdateManager.save(update, independent);
- }
- }
-
- @Transactional
- @Override
- public void check(PullRequest request) {
- if (request.isOpen()) {
- if (request.getSourceDepot() == null) {
- discard(request, "Source repository no longer exists");
- } else if (request.getSource().getObjectId(false) == null) {
- discard(request, "Source branch no longer exists");
- } else if (request.getTarget().getObjectId(false) == null) {
- discard(request, "Target branch no longer exists");
- } else {
- checkUpdate(request, true);
- if (request.isMerged()) {
- closeAsIntegrated(request, true, null);
- } else {
- IntegrationPreview integrationPreview = request.getIntegrationPreview();
- Date timeBeforeCheck = new Date();
- GateCheckResult result = request.checkGates(false);
- if (result instanceof Pending) {
- for (PullRequestReviewInvitation invitation: request.getReviewInvitations()) {
- if (invitation.getDate().getTime()>=timeBeforeCheck.getTime())
- reviewInvitationManager.save(invitation);
- }
- listenerRegistry.post(new PullRequestPendingApproval(request));
- } else if (result instanceof Failed) {
- listenerRegistry.post(new PullRequestPendingUpdate(request));
- } else if (integrationPreview != null
- && integrationPreview.getIntegrated() != null
- && request.getAssignee() == null) {
- integrate(request, "Integrated automatically by GitPlex");
- } else {
- listenerRegistry.post(new PullRequestPendingIntegration(request));
- }
- }
- }
- }
- }
-
- @Override
- public IntegrationPreview previewIntegration(PullRequest request) {
- IntegrationPreview preview = request.getLastIntegrationPreview();
- if (request.isOpen() && !request.isMerged() && (preview == null || preview.isObsolete(request))) {
- int priority = RequestCycle.get() != null?UI_PREVIEW_PRIORITY:BACKEND_PREVIEW_PRIORITY;
- if (dao.getSession().getTransaction().getStatus() == TransactionStatus.ACTIVE) {
- doAfterCommit(new Runnable() {
-
- @Override
- public void run() {
- batchWorkManager.submit(getIntegrationPreviewer(request), new Prioritized(priority));
- }
-
- });
- } else {
- batchWorkManager.submit(getIntegrationPreviewer(request), new Prioritized(priority));
- }
- return null;
- } else {
- return preview;
- }
- }
-
- private BatchWorker getIntegrationPreviewer(PullRequest request) {
- Long requestId = request.getId();
- return new BatchWorker("request-" + requestId + "-previewIntegration", 1) {
-
- @Override
- public void doWork(Collection<Prioritized> works) {
- Preconditions.checkState(works.size() == 1);
- unitOfWork.call(new Callable<Void>() {
-
- @Override
- public Void call() throws Exception {
- PullRequest request = load(requestId);
- try {
- IntegrationPreview preview = request.getLastIntegrationPreview();
- if (request.isOpen() && !request.isMerged() && (preview == null || preview.isObsolete(request))) {
- logger.info("Calculating integration preview of pull request #{} in repository '{}'...",
- request.getNumber(), request.getTargetDepot());
- String requestHead = request.getHeadCommitHash();
- String targetHead = request.getTarget().getObjectName();
- Depot targetDepot = request.getTargetDepot();
- preview = new IntegrationPreview(targetHead, requestHead, request.getIntegrationStrategy(), null);
- request.setLastIntegrationPreview(preview);
- String integrateRef = request.getIntegrateRef();
- ObjectId requestHeadId = ObjectId.fromString(requestHead);
- ObjectId targetHeadId = ObjectId.fromString(targetHead);
- if (preview.getIntegrationStrategy() == MERGE_IF_NECESSARY
- && GitUtils.isMergedInto(targetDepot.getRepository(), targetHeadId, requestHeadId)) {
- preview.setIntegrated(requestHead);
- RefUpdate refUpdate = targetDepot.updateRef(integrateRef);
- refUpdate.setNewObjectId(ObjectId.fromString(requestHead));
- GitUtils.updateRef(refUpdate);
- } else {
- PersonIdent user = accountManager.getRoot().asPerson();
- ObjectId integrated;
- if (preview.getIntegrationStrategy() == REBASE_TARGET_ONTO_SOURCE) {
- integrated = GitUtils.rebase(targetDepot.getRepository(), targetHeadId, requestHeadId, user);
- } else if (preview.getIntegrationStrategy() == REBASE_SOURCE_ONTO_TARGET) {
- integrated = GitUtils.rebase(targetDepot.getRepository(), requestHeadId, targetHeadId, user);
- } else if (preview.getIntegrationStrategy() == MERGE_WITH_SQUASH) {
- integrated = GitUtils.merge(targetDepot.getRepository(),
- requestHeadId, targetHeadId, true, user, request.getCommitMessage());
- } else {
- integrated = GitUtils.merge(targetDepot.getRepository(),
- requestHeadId, targetHeadId, false, user, request.getCommitMessage());
- }
-
- if (integrated != null) {
- preview.setIntegrated(integrated.name());
- RefUpdate refUpdate = targetDepot.updateRef(integrateRef);
- refUpdate.setNewObjectId(integrated);
- GitUtils.updateRef(refUpdate);
- } else {
- RefUpdate refUpdate = targetDepot.updateRef(integrateRef);
- GitUtils.deleteRef(refUpdate);
- }
- }
- dao.persist(request);
-
- listenerRegistry.post(new IntegrationPreviewCalculated(request));
- logger.info("Integration preview of pull request #{} in repository '{}' is calculated.",
- request.getNumber(), request.getTargetDepot());
- }
- } catch (Exception e) {
- logger.error("Error calculating pull request integration preview", e);
- }
- return null;
- }
-
- });
- }
-
- };
- }
-
- @Transactional
- @Listen
- public void on(DepotDeleted event) {
- for (PullRequest request: event.getDepot().getOutgoingRequests()) {
- if (!request.getTargetDepot().equals(event.getDepot()) && request.isOpen())
- discard(request, "Source repository is deleted.");
- }
-
- Query query = getSession().createQuery("update PullRequest set sourceDepot=null where "
- + "sourceDepot=:depot");
- query.setParameter("depot", event.getDepot());
- query.executeUpdate();
- }
-
- @Transactional
- @Listen
- public void on(RefUpdated event) {
- String branch = GitUtils.ref2branch(event.getRefName());
- if (branch != null) {
- DepotAndBranch depotAndBranch = new DepotAndBranch(event.getDepot(), branch);
- Criterion criterion = Restrictions.and(
- ofOpen(),
- Restrictions.or(ofSource(depotAndBranch), ofTarget(depotAndBranch)));
- for (PullRequest request: findAll(EntityCriteria.of(PullRequest.class).add(criterion))) {
- check(request);
- }
- }
- }
-
- @Sessional
- @Override
- public PullRequest findOpen(DepotAndBranch target, DepotAndBranch source) {
- return find(EntityCriteria.of(PullRequest.class)
- .add(ofTarget(target)).add(ofSource(source)).add(ofOpen()));
- }
-
- @Sessional
- @Override
- public PullRequest findLatest(Depot depot, Account submitter) {
- EntityCriteria<PullRequest> criteria = EntityCriteria.of(PullRequest.class);
- criteria.add(ofOpen());
- criteria.add(Restrictions.or(ofSourceDepot(depot), ofTargetDepot(depot)));
- criteria.add(ofSubmitter(submitter));
- criteria.addOrder(Order.desc("id"));
- return find(criteria);
- }
-
- @Sessional
- @Override
- public Collection<PullRequest> findAllOpenTo(DepotAndBranch target, @Nullable Depot sourceDepot) {
- EntityCriteria<PullRequest> criteria = EntityCriteria.of(PullRequest.class);
- criteria.add(ofTarget(target));
-
- if (sourceDepot != null)
- criteria.add(Restrictions.eq("sourceDepot", sourceDepot));
- criteria.add(ofOpen());
- return findAll(criteria);
- }
-
- @Sessional
- @Override
- public Collection<PullRequest> findAllOpenFrom(DepotAndBranch source, @Nullable Depot targetDepot) {
- EntityCriteria<PullRequest> criteria = EntityCriteria.of(PullRequest.class);
- criteria.add(ofSource(source));
-
- if (targetDepot != null)
- criteria.add(Restrictions.eq("targetDepot", targetDepot));
- criteria.add(ofOpen());
- return findAll(criteria);
- }
-
- @Sessional
- @Override
- public Collection<PullRequest> findAllOpen(DepotAndBranch sourceOrTarget) {
- EntityCriteria<PullRequest> criteria = EntityCriteria.of(PullRequest.class);
- criteria.add(ofOpen());
- criteria.add(Restrictions.or(ofSource(sourceOrTarget), ofTarget(sourceOrTarget)));
- return findAll(criteria);
- }
-
- @Sessional
- @Override
- public int countOpen(Depot depot) {
- EntityCriteria<PullRequest> criteria = newCriteria();
- criteria.add(PullRequest.CriterionHelper.ofOpen());
- criteria.add(PullRequest.CriterionHelper.ofTargetDepot(depot));
- return count(criteria);
- }
-
- @Sessional
- @Override
- public PullRequest find(Depot target, long number) {
- EntityCriteria<PullRequest> criteria = newCriteria();
- criteria.add(Restrictions.eq("targetDepot", target));
- criteria.add(Restrictions.eq("number", number));
- return find(criteria);
- }
-
- @Sessional
- @Override
- public PullRequest find(String uuid) {
- EntityCriteria<PullRequest> criteria = newCriteria();
- criteria.add(Restrictions.eq("uuid", uuid));
- return find(criteria);
- }
-
- @Listen
- public void on(PullRequestStatusChangeEvent event) {
- Type type = event.getStatusChange().getType();
- if (type == Type.APPROVED || type == Type.DISAPPROVED || type == Type.REVIEW_DELETED
- || type == Type.VERIFICATION_DELETED || type == Type.VERIFICATION_SUCCEEDED
- || type == Type.VERIFICATION_FAILED) {
- checkAsync(event.getRequest());
- }
- }
-
- @Listen
- public void on(IntegrationPreviewCalculated event) {
- checkAsync(event.getRequest());
- }
-
- private Runnable newCheckRunnable(Long requestId, Subject subject) {
- return new Runnable() {
-
- @Override
- public void run() {
- try {
- ThreadContext.bind(subject);
- check(load(requestId));
- } catch (Exception e) {
- logger.error("Error checking pull request", e);
- } finally {
- ThreadContext.unbindSubject();
- }
- }
-
- };
- }
-
- @Sessional
- protected void checkAsync(PullRequest request) {
- Long requestId = request.getId();
- Subject subject = SecurityUtils.getSubject();
- if (dao.getSession().getTransaction().getStatus() == TransactionStatus.ACTIVE) {
- doUnitOfWorkAsyncAfterCommit(newCheckRunnable(requestId, subject));
- } else {
- unitOfWork.doAsync(newCheckRunnable(requestId, subject));
- }
- }
-
-}
+package com.pmease.gitplex.core.manager.impl;
+
+import static com.pmease.gitplex.core.entity.PullRequest.CriterionHelper.ofOpen;
+import static com.pmease.gitplex.core.entity.PullRequest.CriterionHelper.ofSource;
+import static com.pmease.gitplex.core.entity.PullRequest.CriterionHelper.ofSourceDepot;
+import static com.pmease.gitplex.core.entity.PullRequest.CriterionHelper.ofSubmitter;
+import static com.pmease.gitplex.core.entity.PullRequest.CriterionHelper.ofTarget;
+import static com.pmease.gitplex.core.entity.PullRequest.CriterionHelper.ofTargetDepot;
+import static com.pmease.gitplex.core.entity.PullRequest.IntegrationStrategy.MERGE_ALWAYS;
+import static com.pmease.gitplex.core.entity.PullRequest.IntegrationStrategy.MERGE_IF_NECESSARY;
+import static com.pmease.gitplex.core.entity.PullRequest.IntegrationStrategy.MERGE_WITH_SQUASH;
+import static com.pmease.gitplex.core.entity.PullRequest.IntegrationStrategy.REBASE_SOURCE_ONTO_TARGET;
+import static com.pmease.gitplex.core.entity.PullRequest.IntegrationStrategy.REBASE_TARGET_ONTO_SOURCE;
+
+import java.util.Collection;
+import java.util.Date;
+import java.util.HashMap;
+import java.util.List;
+import java.util.Map;
+import java.util.concurrent.Callable;
+import java.util.concurrent.atomic.AtomicLong;
+
+import javax.annotation.Nullable;
+import javax.inject.Inject;
+import javax.inject.Singleton;
+
+import org.apache.shiro.subject.Subject;
+import org.apache.shiro.util.ThreadContext;
+import org.apache.wicket.request.cycle.RequestCycle;
+import org.eclipse.jgit.api.errors.GitAPIException;
+import org.eclipse.jgit.lib.CommitBuilder;
+import org.eclipse.jgit.lib.ObjectId;
+import org.eclipse.jgit.lib.ObjectInserter;
+import org.eclipse.jgit.lib.PersonIdent;
+import org.eclipse.jgit.lib.RefUpdate;
+import org.eclipse.jgit.revwalk.RevCommit;
+import org.eclipse.jgit.revwalk.RevWalk;
+import org.eclipse.jgit.transport.RefSpec;
+import org.hibernate.Query;
+import org.hibernate.criterion.Criterion;
+import org.hibernate.criterion.Order;
+import org.hibernate.criterion.Restrictions;
+import org.hibernate.resource.transaction.spi.TransactionStatus;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+import com.google.common.base.Preconditions;
+import com.google.common.base.Throwables;
+import com.google.common.collect.Lists;
+import com.pmease.commons.git.GitUtils;
+import com.pmease.commons.hibernate.Sessional;
+import com.pmease.commons.hibernate.Transactional;
+import com.pmease.commons.hibernate.UnitOfWork;
+import com.pmease.commons.hibernate.dao.AbstractEntityManager;
+import com.pmease.commons.hibernate.dao.Dao;
+import com.pmease.commons.hibernate.dao.EntityCriteria;
+import com.pmease.commons.loader.Listen;
+import com.pmease.commons.loader.ListenerRegistry;
+import com.pmease.commons.markdown.MarkdownManager;
+import com.pmease.commons.util.concurrent.Prioritized;
+import com.pmease.commons.util.match.PatternMatcher;
+import com.pmease.gitplex.core.entity.Account;
+import com.pmease.gitplex.core.entity.Depot;
+import com.pmease.gitplex.core.entity.PullRequest;
+import com.pmease.gitplex.core.entity.PullRequest.IntegrationStrategy;
+import com.pmease.gitplex.core.entity.PullRequestReviewInvitation;
+import com.pmease.gitplex.core.entity.PullRequestStatusChange;
+import com.pmease.gitplex.core.entity.PullRequestStatusChange.Type;
+import com.pmease.gitplex.core.entity.PullRequestUpdate;
+import com.pmease.gitplex.core.entity.support.CloseInfo;
+import com.pmease.gitplex.core.entity.support.DepotAndBranch;
+import com.pmease.gitplex.core.entity.support.IntegrationPolicy;
+import com.pmease.gitplex.core.entity.support.IntegrationPreview;
+import com.pmease.gitplex.core.event.RefUpdated;
+import com.pmease.gitplex.core.event.depot.DepotDeleted;
+import com.pmease.gitplex.core.event.pullrequest.IntegrationPreviewCalculated;
+import com.pmease.gitplex.core.event.pullrequest.PullRequestOpened;
+import com.pmease.gitplex.core.event.pullrequest.PullRequestPendingApproval;
+import com.pmease.gitplex.core.event.pullrequest.PullRequestPendingIntegration;
+import com.pmease.gitplex.core.event.pullrequest.PullRequestPendingUpdate;
+import com.pmease.gitplex.core.event.pullrequest.PullRequestStatusChangeEvent;
+import com.pmease.gitplex.core.gatekeeper.checkresult.Failed;
+import com.pmease.gitplex.core.gatekeeper.checkresult.GateCheckResult;
+import com.pmease.gitplex.core.gatekeeper.checkresult.Pending;
+import com.pmease.gitplex.core.manager.AccountManager;
+import com.pmease.gitplex.core.manager.BatchWorkManager;
+import com.pmease.gitplex.core.manager.PullRequestManager;
+import com.pmease.gitplex.core.manager.PullRequestReviewInvitationManager;
+import com.pmease.gitplex.core.manager.PullRequestStatusChangeManager;
+import com.pmease.gitplex.core.manager.PullRequestUpdateManager;
+import com.pmease.gitplex.core.manager.support.BatchWorker;
+import com.pmease.gitplex.core.security.SecurityUtils;
+import com.pmease.gitplex.core.util.ChildAwareMatcher;
+import com.pmease.gitplex.core.util.fullbranchmatch.FullBranchMatchUtils;
+import com.pmease.gitplex.core.util.includeexclude.IncludeExcludeUtils;
+
+@Singleton
+public class DefaultPullRequestManager extends AbstractEntityManager<PullRequest> implements PullRequestManager {
+
+ 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 static final PatternMatcher BRANCH_MATCHER = new ChildAwareMatcher();
+
+ private final PullRequestUpdateManager pullRequestUpdateManager;
+
+ private final AccountManager accountManager;
+
+ private final UnitOfWork unitOfWork;
+
+ private final ListenerRegistry listenerRegistry;
+
+ private final PullRequestReviewInvitationManager reviewInvitationManager;
+
+ private final BatchWorkManager batchWorkManager;
+
+ private final PullRequestStatusChangeManager pullRequestStatusChangeManager;
+
+ private final Map<String, AtomicLong> nextNumbers = new HashMap<>();
+
+ @Inject
+ public DefaultPullRequestManager(Dao dao, PullRequestUpdateManager pullRequestUpdateManager,
+ PullRequestReviewInvitationManager reviewInvitationManager, AccountManager accountManager,
+ MarkdownManager markdownManager, BatchWorkManager batchWorkManager,
+ ListenerRegistry listenerRegistry, UnitOfWork unitOfWork,
+ PullRequestStatusChangeManager pullRequestStatusChangeManager) {
+ super(dao);
+
+ this.pullRequestUpdateManager = pullRequestUpdateManager;
+ this.reviewInvitationManager = reviewInvitationManager;
+ this.accountManager = accountManager;
+ this.batchWorkManager = batchWorkManager;
+ this.unitOfWork = unitOfWork;
+ this.listenerRegistry = listenerRegistry;
+ this.pullRequestStatusChangeManager = pullRequestStatusChangeManager;
+ }
+
+ @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, String note) {
+ Preconditions.checkState(!request.isOpen() && request.getSourceDepot() != null);
+ if (request.getSource().getObjectName(false) == null) {
+ RevCommit latestCommit = request.getHeadCommit();
+ try {
+ request.getSourceDepot().git().branchCreate().setName(request.getSourceBranch()).setStartPoint(latestCommit).call();
+ } catch (Exception e) {
+ Throwables.propagate(e);
+ }
+ request.getSourceDepot().cacheObjectId(request.getSourceBranch(), latestCommit.copy());
+
+ PullRequestStatusChange statusChange = new PullRequestStatusChange();
+ statusChange.setDate(new Date());
+ statusChange.setNote(note);
+ statusChange.setRequest(request);
+ statusChange.setType(Type.SOURCE_BRANCH_RESTORED);
+ statusChange.setUser(accountManager.getCurrent());
+ pullRequestStatusChangeManager.save(statusChange);
+
+ request.setLastEvent(statusChange);
+ save(request);
+ }
+ }
+
+ @Transactional
+ @Override
+ public void deleteSourceBranch(PullRequest request, String note) {
+ Preconditions.checkState(!request.isOpen() && request.getSourceDepot() != null);
+
+ if (request.getSource().getObjectName(false) != null) {
+ request.getSource().delete();
+
+ PullRequestStatusChange statusChange = new PullRequestStatusChange();
+ statusChange.setDate(new Date());
+ statusChange.setNote(note);
+ statusChange.setRequest(request);
+ statusChange.setType(Type.SOURCE_BRANCH_DELETED);
+ statusChange.setUser(accountManager.getCurrent());
+ pullRequestStatusChangeManager.save(statusChange);
+
+ request.setLastEvent(statusChange);
+ save(request);
+ }
+ }
+
+ @Transactional
+ @Override
+ public void reopen(PullRequest request, String note) {
+ Account user = accountManager.getCurrent();
+ request.setCloseInfo(null);
+
+ PullRequestStatusChange statusChange = new PullRequestStatusChange();
+ statusChange.setDate(new Date());
+ statusChange.setNote(note);
+ statusChange.setRequest(request);
+ statusChange.setType(Type.REOPENED);
+ statusChange.setUser(user);
+ pullRequestStatusChangeManager.save(statusChange);
+
+ request.setLastEvent(statusChange);
+ save(request);
+ checkAsync(request);
+ }
+
+ @Transactional
+ @Override
+ public void discard(PullRequest request, String note) {
+ Account user = accountManager.getCurrent();
+ Date date = new Date();
+
+ CloseInfo closeInfo = new CloseInfo();
+ closeInfo.setCloseDate(date);
+ closeInfo.setClosedBy(user);
+ closeInfo.setCloseStatus(CloseInfo.Status.DISCARDED);
+ request.setCloseInfo(closeInfo);
+
+ PullRequestStatusChange statusChange = new PullRequestStatusChange();
+ statusChange.setDate(date);
+ statusChange.setNote(note);
+ statusChange.setRequest(request);
+ statusChange.setType(Type.DISCARDED);
+ statusChange.setUser(user);
+ pullRequestStatusChangeManager.save(statusChange);
+
+ request.setLastEvent(statusChange);
+ save(request);
+ }
+
+ @Transactional
+ @Override
+ public void integrate(PullRequest request, String note) {
+ 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.");
+
+ Account user = accountManager.getCurrent();
+
+ ObjectId integratedId = ObjectId.fromString(integrated);
+ RevCommit integratedCommit = request.getTargetDepot().getRevCommit(integratedId);
+
+ Depot targetDepot = request.getTargetDepot();
+ IntegrationStrategy strategy = request.getIntegrationStrategy();
+ if ((strategy == MERGE_ALWAYS || strategy == MERGE_IF_NECESSARY || strategy == MERGE_WITH_SQUASH)
+ && !preview.getIntegrated().equals(preview.getRequestHead())
+ && !integratedCommit.getFullMessage().equals(request.getCommitMessage())) {
+ try ( RevWalk revWalk = new RevWalk(targetDepot.getRepository());
+ ObjectInserter inserter = targetDepot.getRepository().newObjectInserter()) {
+ CommitBuilder newCommit = new CommitBuilder();
+ newCommit.setAuthor(integratedCommit.getAuthorIdent());
+ newCommit.setCommitter(user.asPerson());
+ newCommit.setMessage(request.getCommitMessage());
+ newCommit.setTreeId(integratedCommit.getTree());
+ newCommit.setParentIds(integratedCommit.getParents());
+ integratedId = inserter.insert(newCommit);
+ integrated = integratedId.name();
+ inserter.flush();
+ } catch (Exception e) {
+ Throwables.propagate(e);
+ }
+ preview = new IntegrationPreview(preview.getTargetHead(), preview.getRequestHead(),
+ preview.getIntegrationStrategy(), integrated);
+ request.setLastIntegrationPreview(preview);
+ RefUpdate refUpdate = targetDepot.updateRef(request.getIntegrateRef());
+ refUpdate.setNewObjectId(integratedId);
+ GitUtils.updateRef(refUpdate);
+ }
+
+ closeAsIntegrated(request, false, note);
+
+ if (strategy == REBASE_SOURCE_ONTO_TARGET || strategy == MERGE_WITH_SQUASH) {
+ Depot sourceDepot = request.getSourceDepot();
+ if (!sourceDepot.equals(targetDepot)) {
+ try {
+ sourceDepot.git().fetch()
+ .setRemote(targetDepot.getDirectory().getAbsolutePath())
+ .setRefSpecs(new RefSpec(request.getIntegrateRef()))
+ .call();
+ } catch (GitAPIException e) {
+ throw new RuntimeException(e);
+ }
+ }
+ RefUpdate refUpdate = sourceDepot.updateRef(request.getSourceRef());
+ refUpdate.setNewObjectId(integratedId);
+ ObjectId requestHeadId = ObjectId.fromString(preview.getRequestHead());
+ refUpdate.setExpectedOldObjectId(requestHeadId);
+ refUpdate.setRefLogMessage("Pull request #" + request.getNumber(), true);
+ GitUtils.updateRef(refUpdate);
+
+ checkUpdate(request, false);
+
+ Long requestId = request.getId();
+ ObjectId newSourceHeadId = integratedId;
+ Subject subject = SecurityUtils.getSubject();
+ doUnitOfWorkAsyncAfterCommit(new Runnable() {
+
+ @Override
+ public void run() {
+ ThreadContext.bind(subject);
+ try {
+ PullRequest request = load(requestId);
+ request.getSourceDepot().cacheObjectId(request.getSourceRef(), newSourceHeadId);
+ listenerRegistry.post(new RefUpdated(
+ request.getSourceDepot(), request.getSourceRef(), requestHeadId, newSourceHeadId));
+ } finally {
+ ThreadContext.unbindSubject();
+ }
+ }
+
+ });
+ }
+
+ String targetRef = request.getTargetRef();
+ ObjectId targetHeadId = ObjectId.fromString(preview.getTargetHead());
+ RefUpdate refUpdate = targetDepot.updateRef(targetRef);
+ refUpdate.setRefLogIdent(user.asPerson());
+ refUpdate.setRefLogMessage("Pull request #" + request.getNumber(), true);
+ refUpdate.setExpectedOldObjectId(targetHeadId);
+ refUpdate.setNewObjectId(integratedId);
+ GitUtils.updateRef(refUpdate);
+
+ Long requestId = request.getId();
+ Subject subject = SecurityUtils.getSubject();
+ ObjectId newTargetHeadId = integratedId;
+ doUnitOfWorkAsyncAfterCommit(new Runnable() {
+
+ @Override
+ public void run() {
+ ThreadContext.bind(subject);
+ try {
+ PullRequest request = load(requestId);
+ request.getTargetDepot().cacheObjectId(request.getTargetRef(), newTargetHeadId);
+ listenerRegistry.post(new RefUpdated(request.getTargetDepot(), targetRef,
+ targetHeadId, newTargetHeadId));
+ } finally {
+ ThreadContext.unbindSubject();
+ }
+ }
+
+ });
+ }
+
+ private long getNextNumber(Depot depot) {
+ AtomicLong nextNumber;
+ synchronized (nextNumbers) {
+ nextNumber = nextNumbers.get(depot.getUUID());
+ }
+ if (nextNumber == null) {
+ long maxNumber;
+ Query query = getSession().createQuery("select max(number) from PullRequest where targetDepot=:depot");
+ query.setParameter("depot", depot);
+ Object result = query.uniqueResult();
+ if (result != null) {
+ maxNumber = (Long)result;
+ } else {
+ maxNumber = 0;
+ }
+
+ /*
+ * do not put the whole method in synchronized block to avoid possible deadlocks
+ * if there are limited connections.
+ */
+ synchronized (nextNumbers) {
+ nextNumber = nextNumbers.get(depot.getUUID());
+ if (nextNumber == null) {
+ nextNumber = new AtomicLong(maxNumber+1);
+ nextNumbers.put(depot.getUUID(), nextNumber);
+ }
+ }
+ }
+ return nextNumber.getAndIncrement();
+ }
+
+ @Transactional
+ @Override
+ public void open(PullRequest request) {
+ request.setNumber(getNextNumber(request.getTargetDepot()));
+ dao.persist(request);
+
+ RefUpdate refUpdate = request.getTargetDepot().updateRef(request.getBaseRef());
+ refUpdate.setNewObjectId(ObjectId.fromString(request.getBaseCommitHash()));
+ GitUtils.updateRef(refUpdate);
+
+ for (PullRequestUpdate update: request.getUpdates()) {
+ pullRequestUpdateManager.save(update, false);
+ }
+
+ for (PullRequestReviewInvitation invitation: request.getReviewInvitations())
+ reviewInvitationManager.save(invitation);
+
+ checkAsync(request);
+
+ listenerRegistry.post(new PullRequestOpened(request));
+ }
+
+ @Override
+ public List<IntegrationStrategy> getApplicableIntegrationStrategies(PullRequest request) {
+ List<IntegrationStrategy> strategies = null;
+ for (IntegrationPolicy policy: request.getTargetDepot().getIntegrationPolicies()) {
+ if (IncludeExcludeUtils.getIncludeExclude(policy.getTargetBranchMatch()).matches(BRANCH_MATCHER, request.getTargetBranch())
+ && FullBranchMatchUtils.matches(policy.getSourceBranchMatch(), request.getTargetDepot(), request.getSource())) {
+ strategies = policy.getIntegrationStrategies();
+ break;
+ }
+ }
+ if (strategies == null)
+ strategies = Lists.newArrayList(IntegrationStrategy.MERGE_ALWAYS);
+ return strategies;
+ }
+
+ @Transactional
+ @Override
+ public void changeAssignee(PullRequest request) {
+ if (request.isOpen()) {
+ String note = request.getAssignee().getDisplayName() + " is expected to integrate the pull request";
+
+ PullRequestStatusChange statusChange = new PullRequestStatusChange();
+ statusChange.setDate(new Date());
+ statusChange.setNote(note);
+ statusChange.setRequest(request);
+ statusChange.setType(Type.ASSIGNED);
+ statusChange.setUser(accountManager.getCurrent());
+ pullRequestStatusChangeManager.save(statusChange);
+
+ request.setLastEvent(statusChange);
+ }
+ save(request);
+ }
+
+ private void closeAsIntegrated(PullRequest request, boolean dueToMerged, String note) {
+ Account user = accountManager.getCurrent();
+ Date date = new Date();
+
+ if (dueToMerged)
+ request.setLastIntegrationPreview(null);
+
+ CloseInfo closeInfo = new CloseInfo();
+ closeInfo.setCloseDate(date);
+ closeInfo.setClosedBy(user);
+ closeInfo.setCloseStatus(CloseInfo.Status.INTEGRATED);
+ request.setCloseInfo(closeInfo);
+
+ if (dueToMerged)
+ note = "Source branch is already merged to target branch by some one";
+
+ PullRequestStatusChange statusChange = new PullRequestStatusChange();
+ statusChange.setDate(date);
+ statusChange.setNote(note);
+ statusChange.setRequest(request);
+ statusChange.setType(Type.INTEGRATED);
+ statusChange.setUser(user);
+ pullRequestStatusChangeManager.save(statusChange);
+ request.setLastEvent(statusChange);
+
+ save(request);
+ }
+
+ private void checkUpdate(PullRequest request, boolean independent) {
+ if (!request.getHeadCommitHash().equals(request.getSource().getObjectName())) {
+ PullRequestUpdate update = new PullRequestUpdate();
+ update.setRequest(request);
+ update.setHeadCommitHash(request.getSource().getObjectName());
+ ObjectId mergeBase = GitUtils.getMergeBase(
+ request.getTargetDepot().getRepository(), request.getTarget().getObjectId(),
+ request.getSourceDepot().getRepository(), request.getSource().getObjectId(),
+ GitUtils.branch2ref(request.getSourceBranch()));
+ update.setMergeCommitHash(mergeBase.name());
+ request.addUpdate(update);
+ pullRequestUpdateManager.save(update, independent);
+ }
+ }
+
+ @Transactional
+ @Override
+ public void check(PullRequest request) {
+ if (request.isOpen()) {
+ if (request.getSourceDepot() == null) {
+ discard(request, "Source repository no longer exists");
+ } else if (request.getSource().getObjectId(false) == null) {
+ discard(request, "Source branch no longer exists");
+ } else if (request.getTarget().getObjectId(false) == null) {
+ discard(request, "Target branch no longer exists");
+ } else {
+ checkUpdate(request, true);
+ if (request.isMerged()) {
+ closeAsIntegrated(request, true, null);
+ } else {
+ IntegrationPreview integrationPreview = request.getIntegrationPreview();
+ Date timeBeforeCheck = new Date();
+ GateCheckResult result = request.checkGates(false);
+ if (result instanceof Pending) {
+ for (PullRequestReviewInvitation invitation: request.getReviewInvitations()) {
+ if (invitation.getDate().getTime()>=timeBeforeCheck.getTime())
+ reviewInvitationManager.save(invitation);
+ }
+ listenerRegistry.post(new PullRequestPendingApproval(request));
+ } else if (result instanceof Failed) {
+ listenerRegistry.post(new PullRequestPendingUpdate(request));
+ } else if (integrationPreview != null
+ && integrationPreview.getIntegrated() != null
+ && request.getAssignee() == null) {
+ integrate(request, "Integrated automatically by GitPlex");
+ } else {
+ listenerRegistry.post(new PullRequestPendingIntegration(request));
+ }
+ }
+ }
+ }
+ }
+
+ @Override
+ public IntegrationPreview previewIntegration(PullRequest request) {
+ IntegrationPreview preview = request.getLastIntegrationPreview();
+ if (request.isOpen() && !request.isMerged() && (preview == null || preview.isObsolete(request))) {
+ int priority = RequestCycle.get() != null?UI_PREVIEW_PRIORITY:BACKEND_PREVIEW_PRIORITY;
+ if (dao.getSession().getTransaction().getStatus() == TransactionStatus.ACTIVE) {
+ doAfterCommit(new Runnable() {
+
+ @Override
+ public void run() {
+ batchWorkManager.submit(getIntegrationPreviewer(request), new Prioritized(priority));
+ }
+
+ });
+ } else {
+ batchWorkManager.submit(getIntegrationPreviewer(request), new Prioritized(priority));
+ }
+ return null;
+ } else {
+ return preview;
+ }
+ }
+
+ private BatchWorker getIntegrationPreviewer(PullRequest request) {
+ Long requestId = request.getId();
+ return new BatchWorker("request-" + requestId + "-previewIntegration", 1) {
+
+ @Override
+ public void doWork(Collection<Prioritized> works) {
+ Preconditions.checkState(works.size() == 1);
+ unitOfWork.call(new Callable<Void>() {
+
+ @Override
+ public Void call() throws Exception {
+ PullRequest request = load(requestId);
+ try {
+ IntegrationPreview preview = request.getLastIntegrationPreview();
+ if (request.isOpen() && !request.isMerged() && (preview == null || preview.isObsolete(request))) {
+ logger.info("Calculating integration preview of pull request #{} in repository '{}'...",
+ request.getNumber(), request.getTargetDepot());
+ String requestHead = request.getHeadCommitHash();
+ String targetHead = request.getTarget().getObjectName();
+ Depot targetDepot = request.getTargetDepot();
+ preview = new IntegrationPreview(targetHead, requestHead, request.getIntegrationStrategy(), null);
+ request.setLastIntegrationPreview(preview);
+ String integrateRef = request.getIntegrateRef();
+ ObjectId requestHeadId = ObjectId.fromString(requestHead);
+ ObjectId targetHeadId = ObjectId.fromString(targetHead);
+ if (preview.getIntegrationStrategy() == MERGE_IF_NECESSARY
+ && GitUtils.isMergedInto(targetDepot.getRepository(), targetHeadId, requestHeadId)) {
+ preview.setIntegrated(requestHead);
+ RefUpdate refUpdate = targetDepot.updateRef(integrateRef);
+ refUpdate.setNewObjectId(ObjectId.fromString(requestHead));
+ GitUtils.updateRef(refUpdate);
+ } else {
+ PersonIdent user = accountManager.getRoot().asPerson();
+ ObjectId integrated;
+ if (preview.getIntegrationStrategy() == REBASE_TARGET_ONTO_SOURCE) {
+ integrated = GitUtils.rebase(targetDepot.getRepository(), targetHeadId, requestHeadId, user);
+ } else if (preview.getIntegrationStrategy() == REBASE_SOURCE_ONTO_TARGET) {
+ integrated = GitUtils.rebase(targetDepot.getRepository(), requestHeadId, targetHeadId, user);
+ } else if (preview.getIntegrationStrategy() == MERGE_WITH_SQUASH) {
+ integrated = GitUtils.merge(targetDepot.getRepository(),
+ requestHeadId, targetHeadId, true, user, request.getCommitMessage());
+ } else {
+ integrated = GitUtils.merge(targetDepot.getRepository(),
+ requestHeadId, targetHeadId, false, user, request.getCommitMessage());
+ }
+
+ if (integrated != null) {
+ preview.setIntegrated(integrated.name());
+ RefUpdate refUpdate = targetDepot.updateRef(integrateRef);
+ refUpdate.setNewObjectId(integrated);
+ GitUtils.updateRef(refUpdate);
+ } else {
+ RefUpdate refUpdate = targetDepot.updateRef(integrateRef);
+ GitUtils.deleteRef(refUpdate);
+ }
+ }
+ dao.persist(request);
+
+ listenerRegistry.post(new IntegrationPreviewCalculated(request));
+ logger.info("Integration preview of pull request #{} in repository '{}' is calculated.",
+ request.getNumber(), request.getTargetDepot());
+ }
+ } catch (Exception e) {
+ logger.error("Error calculating pull request integration preview", e);
+ }
+ return null;
+ }
+
+ });
+ }
+
+ };
+ }
+
+ @Transactional
+ @Listen
+ public void on(DepotDeleted event) {
+ for (PullRequest request: event.getDepot().getOutgoingRequests()) {
+ if (!request.getTargetDepot().equals(event.getDepot()) && request.isOpen())
+ discard(request, "Source repository is deleted.");
+ }
+
+ Query query = getSession().createQuery("update PullRequest set sourceDepot=null where "
+ + "sourceDepot=:depot");
+ query.setParameter("depot", event.getDepot());
+ query.executeUpdate();
+ }
+
+ @Transactional
+ @Listen
+ public void on(RefUpdated event) {
+ String branch = GitUtils.ref2branch(event.getRefName());
+ if (branch != null) {
+ DepotAndBranch depotAndBranch = new DepotAndBranch(event.getDepot(), branch);
+ Criterion criterion = Restrictions.and(
+ ofOpen(),
+ Restrictions.or(ofSource(depotAndBranch), ofTarget(depotAndBranch)));
+ for (PullRequest request: findAll(EntityCriteria.of(PullRequest.class).add(criterion))) {
+ check(request);
+ }
+ }
+ }
+
+ @Sessional
+ @Override
+ public PullRequest findOpen(DepotAndBranch target, DepotAndBranch source) {
+ return find(EntityCriteria.of(PullRequest.class)
+ .add(ofTarget(target)).add(ofSource(source)).add(ofOpen()));
+ }
+
+ @Sessional
+ @Override
+ public PullRequest findLatest(Depot depot, Account submitter) {
+ EntityCriteria<PullRequest> criteria = EntityCriteria.of(PullRequest.class);
+ criteria.add(ofOpen());
+ criteria.add(Restrictions.or(ofSourceDepot(depot), ofTargetDepot(depot)));
+ criteria.add(ofSubmitter(submitter));
+ criteria.addOrder(Order.desc("id"));
+ return find(criteria);
+ }
+
+ @Sessional
+ @Override
+ public Collection<PullRequest> findAllOpenTo(DepotAndBranch target, @Nullable Depot sourceDepot) {
+ EntityCriteria<PullRequest> criteria = EntityCriteria.of(PullRequest.class);
+ criteria.add(ofTarget(target));
+
+ if (sourceDepot != null)
+ criteria.add(Restrictions.eq("sourceDepot", sourceDepot));
+ criteria.add(ofOpen());
+ return findAll(criteria);
+ }
+
+ @Sessional
+ @Override
+ public Collection<PullRequest> findAllOpenFrom(DepotAndBranch source, @Nullable Depot targetDepot) {
+ EntityCriteria<PullRequest> criteria = EntityCriteria.of(PullRequest.class);
+ criteria.add(ofSource(source));
+
+ if (targetDepot != null)
+ criteria.add(Restrictions.eq("targetDepot", targetDepot));
+ criteria.add(ofOpen());
+ return findAll(criteria);
+ }
+
+ @Sessional
+ @Override
+ public Collection<PullRequest> findAllOpen(DepotAndBranch sourceOrTarget) {
+ EntityCriteria<PullRequest> criteria = EntityCriteria.of(PullRequest.class);
+ criteria.add(ofOpen());
+ criteria.add(Restrictions.or(ofSource(sourceOrTarget), ofTarget(sourceOrTarget)));
+ return findAll(criteria);
+ }
+
+ @Sessional
+ @Override
+ public int countOpen(Depot depot) {
+ EntityCriteria<PullRequest> criteria = newCriteria();
+ criteria.add(PullRequest.CriterionHelper.ofOpen());
+ criteria.add(PullRequest.CriterionHelper.ofTargetDepot(depot));
+ return count(criteria);
+ }
+
+ @Sessional
+ @Override
+ public PullRequest find(Depot target, long number) {
+ EntityCriteria<PullRequest> criteria = newCriteria();
+ criteria.add(Restrictions.eq("targetDepot", target));
+ criteria.add(Restrictions.eq("number", number));
+ return find(criteria);
+ }
+
+ @Sessional
+ @Override
+ public PullRequest find(String uuid) {
+ EntityCriteria<PullRequest> criteria = newCriteria();
+ criteria.add(Restrictions.eq("uuid", uuid));
+ return find(criteria);
+ }
+
+ @Listen
+ public void on(PullRequestStatusChangeEvent event) {
+ Type type = event.getStatusChange().getType();
+ if (type == Type.APPROVED || type == Type.DISAPPROVED || type == Type.REVIEW_DELETED
+ || type == Type.VERIFICATION_DELETED || type == Type.VERIFICATION_SUCCEEDED
+ || type == Type.VERIFICATION_FAILED) {
+ checkAsync(event.getRequest());
+ }
+ }
+
+ @Listen
+ public void on(IntegrationPreviewCalculated event) {
+ checkAsync(event.getRequest());
+ }
+
+ private Runnable newCheckRunnable(Long requestId, Subject subject) {
+ return new Runnable() {
+
+ @Override
+ public void run() {
+ try {
+ ThreadContext.bind(subject);
+ check(load(requestId));
+ } catch (Exception e) {
+ logger.error("Error checking pull request", e);
+ } finally {
+ ThreadContext.unbindSubject();
+ }
+ }
+
+ };
+ }
+
+ @Sessional
+ protected void checkAsync(PullRequest request) {
+ Long requestId = request.getId();
+ Subject subject = SecurityUtils.getSubject();
+ if (dao.getSession().getTransaction().getStatus() == TransactionStatus.ACTIVE) {
+ doUnitOfWorkAsyncAfterCommit(newCheckRunnable(requestId, subject));
+ } else {
+ unitOfWork.doAsync(newCheckRunnable(requestId, subject));
+ }
+ }
+
+}
diff --git a/gitplex.core/src/main/java/com/pmease/gitplex/core/manager/impl/DefaultPullRequestTaskManager.java b/gitplex.core/src/main/java/com/pmease/gitplex/core/manager/impl/DefaultPullRequestTaskManager.java
index b60a8ca736..f0a1937afd 100644
--- a/gitplex.core/src/main/java/com/pmease/gitplex/core/manager/impl/DefaultPullRequestTaskManager.java
+++ b/gitplex.core/src/main/java/com/pmease/gitplex/core/manager/impl/DefaultPullRequestTaskManager.java
@@ -1,230 +1,230 @@
-package com.pmease.gitplex.core.manager.impl;
-
-import static com.pmease.gitplex.core.entity.PullRequest.Status.PENDING_INTEGRATE;
-import static com.pmease.gitplex.core.entity.PullRequestTask.Type.INTEGRATE;
-import static com.pmease.gitplex.core.entity.PullRequestTask.Type.REVIEW;
-import static com.pmease.gitplex.core.entity.PullRequestTask.Type.UPDATE;
-
-import javax.inject.Inject;
-import javax.inject.Singleton;
-
-import org.hibernate.Query;
-import org.hibernate.criterion.Restrictions;
-
-import com.google.common.base.Preconditions;
-import com.google.common.collect.Sets;
-import com.pmease.commons.hibernate.Transactional;
-import com.pmease.commons.hibernate.dao.AbstractEntityManager;
-import com.pmease.commons.hibernate.dao.Dao;
-import com.pmease.commons.hibernate.dao.EntityCriteria;
-import com.pmease.commons.loader.Listen;
-import com.pmease.gitplex.core.entity.Account;
-import com.pmease.gitplex.core.entity.PullRequest;
-import com.pmease.gitplex.core.entity.PullRequestTask;
-import com.pmease.gitplex.core.entity.PullRequestReviewInvitation;
-import com.pmease.gitplex.core.entity.PullRequestStatusChange;
-import com.pmease.gitplex.core.event.pullrequest.PullRequestPendingApproval;
-import com.pmease.gitplex.core.event.pullrequest.PullRequestPendingIntegration;
-import com.pmease.gitplex.core.event.pullrequest.PullRequestPendingUpdate;
-import com.pmease.gitplex.core.event.pullrequest.PullRequestReviewInvitationChanged;
-import com.pmease.gitplex.core.event.pullrequest.PullRequestStatusChangeEvent;
-import com.pmease.gitplex.core.event.pullrequest.PullRequestUpdated;
-import com.pmease.gitplex.core.manager.MailManager;
-import com.pmease.gitplex.core.manager.PullRequestTaskManager;
-import com.pmease.gitplex.core.manager.UrlManager;
-
-/**
- * This class manages pull request tasks and send task notifications if necessary.
- * Unlike watch based notifications, task notifications can not be suppressed.
- *
- * @author robin
- *
- */
-@Singleton
-public class DefaultPullRequestTaskManager extends AbstractEntityManager<PullRequestTask> implements PullRequestTaskManager {
-
- private final MailManager mailManager;
-
- private final UrlManager urlManager;
-
- @Inject
- public DefaultPullRequestTaskManager(Dao dao, MailManager mailManager, UrlManager urlManager) {
- super(dao);
-
- this.mailManager = mailManager;
- this.urlManager = urlManager;
- }
-
- @Transactional
- @Listen
- public void on(PullRequestUpdated event) {
- Query query = getSession().createQuery("delete from PullRequestTask "
- + "where request=:request and type=:type");
- query.setParameter("request", event.getRequest());
- query.setParameter("type", UPDATE);
- query.executeUpdate();
- }
-
- private void onClosed(PullRequest request) {
- Query query = getSession().createQuery("delete from PullRequestTask "
- + "where request=:request");
- query.setParameter("request", request);
- query.executeUpdate();
- }
-
- @Transactional
- @Listen
- public void on(PullRequestReviewInvitationChanged event) {
- PullRequestReviewInvitation invitation = event.getInvitation();
- PullRequest request = invitation.getRequest();
- Account user = invitation.getUser();
- if (invitation.getStatus() == PullRequestReviewInvitation.Status.EXCLUDED) {
- Query query = getSession().createQuery("delete from PullRequestTask "
- + "where request=:request and user=:user and type=:type");
- query.setParameter("request", request);
- query.setParameter("user", user);
- query.setParameter("type", REVIEW);
- query.executeUpdate();
- } else if (invitation.getStatus() == PullRequestReviewInvitation.Status.ADDED_BY_RULE) {
- PullRequestTask task = new PullRequestTask();
- task.setRequest(request);
- task.setUser(user);
- task.setType(REVIEW);
- EntityCriteria<PullRequestTask> criteria = EntityCriteria.of(PullRequestTask.class);
- criteria.add(Restrictions.eq("request", request))
- .add(Restrictions.eq("user", user))
- .add(Restrictions.eq("type", task.getType()));
- if (find(criteria) == null) {
- save(task);
-
- String subject = String.format("Please review pull request #%d (%s)",
- request.getNumber(), request.getTitle());
- String url = urlManager.urlFor(request);
- String body = String.format("You are designated to review pull request #%d (%s).<br>"
- + "Please visit <a href='%s'>%s</a> to do the review.",
- request.getNumber(), request.getTitle(), url, url);
- mailManager.sendMailAsync(Sets.newHashSet(task.getUser()), subject, decorate(user, body));
- }
- } else {
- String subject = String.format("You are invited to review pull request #%d (%s)",
- request.getNumber(), request.getTitle());
- String url = urlManager.urlFor(request);
- String body = String.format("You are invited to review pull request #%d (%s).<br>"
- + "Please visit <a href='%s'>%s</a> to do the review.",
- request.getNumber(), request.getTitle(), url, url);
- mailManager.sendMailAsync(Sets.newHashSet(invitation.getUser()), subject, decorate(user, body));
- }
- }
-
- private String decorate(Account user, String body) {
- return String.format("Dear %s, "
- + "<p style='margin: 16px 0;'>"
- + "%s"
- + "<p style='margin: 16px 0;'>"
- + "-- Sent by GitPlex",
- user.getDisplayName(), body);
- }
-
- @Transactional
- @Listen
- public void on(PullRequestPendingApproval event) {
- Query query = getSession().createQuery("delete from PullRequestTask "
- + "where request=:request and (type=:update or type=:integrate)");
- query.setParameter("request", event.getRequest());
- query.setParameter("update", UPDATE);
- query.setParameter("integrate", INTEGRATE);
- query.executeUpdate();
- }
-
- private void requestIntegration(PullRequest request) {
- Account user = request.getAssignee();
- PullRequestTask task = new PullRequestTask();
- task.setRequest(request);
- task.setUser(user);
- task.setType(INTEGRATE);
- EntityCriteria<PullRequestTask> criteria = EntityCriteria.of(PullRequestTask.class);
- criteria.add(Restrictions.eq("request", task.getRequest()))
- .add(Restrictions.eq("user", user))
- .add(Restrictions.eq("type", task.getType()));
- if (find(criteria) == null) {
- save(task);
- String subject = String.format("Please integrate pull request #%d (%s)",
- request.getNumber(), request.getTitle());
- String url = urlManager.urlFor(request);
- String body = String.format("Pull request #%d (%s) is pending integration.<br>"
- + "Please visit <a href='%s'>%s</a> to check and integrate.",
- request.getNumber(), request.getTitle(), url, url);
-
- mailManager.sendMailAsync(Sets.newHashSet(task.getUser()), subject, decorate(user, body));
- }
- }
-
- @Transactional
- @Listen
- public void on(PullRequestPendingIntegration event) {
- PullRequest request = event.getRequest();
- if (request.getAssignee() != null)
- requestIntegration(request);
- }
-
- @Transactional
- @Listen
- public void on(PullRequestPendingUpdate event) {
- PullRequest request = event.getRequest();
- PullRequestTask task = new PullRequestTask();
- task.setRequest(request);
- task.setUser(request.getSubmitter());
- task.setType(UPDATE);
- EntityCriteria<PullRequestTask> criteria = EntityCriteria.of(PullRequestTask.class);
- criteria.add(Restrictions.eq("request", task.getRequest()))
- .add(Restrictions.eq("user", task.getUser()))
- .add(Restrictions.eq("type", task.getType()));
- if (find(criteria) == null) {
- save(task);
- String subject = String.format("New commits are expected in pull request #%d (%s)",
- request.getNumber(), request.getTitle());
- String url = urlManager.urlFor(request);
- String body = String.format("Next commits are expected for next round of review in pull request #%d (%s).<br>"
- + "Please visit <a href='%s'>%s</a> for details",
- request.getNumber(), request.getTitle(), url, url);
- mailManager.sendMailAsync(Sets.newHashSet(request.getSubmitter()), subject,
- decorate(request.getSubmitter(), body));
- }
- }
-
- @Transactional
- @Listen
- public void on(PullRequestStatusChangeEvent event) {
- PullRequestStatusChange statusChange = event.getStatusChange();
- PullRequestStatusChange.Type type = statusChange.getType();
- if (type == PullRequestStatusChange.Type.APPROVED || type == PullRequestStatusChange.Type.DISAPPROVED) {
- onReviewed(statusChange);
- } else if (type == PullRequestStatusChange.Type.ASSIGNED) {
- PullRequest request = event.getRequest();
- Preconditions.checkNotNull(request.getAssignee());
-
- if (request.getStatus() == PENDING_INTEGRATE) {
- Query query = getSession().createQuery("delete from PullRequestTask "
- + "where request=:request and type=:type and user!=:user");
- query.setParameter("request", request);
- query.setParameter("type", INTEGRATE);
- query.setParameter("user", request.getAssignee());
- query.executeUpdate();
-
- requestIntegration(request);
- }
- } else if (type == PullRequestStatusChange.Type.INTEGRATED || type == PullRequestStatusChange.Type.DISCARDED) {
- onClosed(event.getRequest());
- }
- }
-
- private void onReviewed(PullRequestStatusChange statusChange) {
- Query query = getSession().createQuery("delete from PullRequestTask "
- + "where request=:request and user=:user and type=:type");
- query.setParameter("request", statusChange.getRequest());
- query.setParameter("user", statusChange.getUser());
- query.setParameter("type", REVIEW);
- query.executeUpdate();
- }
-
+package com.pmease.gitplex.core.manager.impl;
+
+import static com.pmease.gitplex.core.entity.PullRequest.Status.PENDING_INTEGRATE;
+import static com.pmease.gitplex.core.entity.PullRequestTask.Type.INTEGRATE;
+import static com.pmease.gitplex.core.entity.PullRequestTask.Type.REVIEW;
+import static com.pmease.gitplex.core.entity.PullRequestTask.Type.UPDATE;
+
+import javax.inject.Inject;
+import javax.inject.Singleton;
+
+import org.hibernate.Query;
+import org.hibernate.criterion.Restrictions;
+
+import com.google.common.base.Preconditions;
+import com.google.common.collect.Sets;
+import com.pmease.commons.hibernate.Transactional;
+import com.pmease.commons.hibernate.dao.AbstractEntityManager;
+import com.pmease.commons.hibernate.dao.Dao;
+import com.pmease.commons.hibernate.dao.EntityCriteria;
+import com.pmease.commons.loader.Listen;
+import com.pmease.gitplex.core.entity.Account;
+import com.pmease.gitplex.core.entity.PullRequest;
+import com.pmease.gitplex.core.entity.PullRequestTask;
+import com.pmease.gitplex.core.entity.PullRequestReviewInvitation;
+import com.pmease.gitplex.core.entity.PullRequestStatusChange;
+import com.pmease.gitplex.core.event.pullrequest.PullRequestPendingApproval;
+import com.pmease.gitplex.core.event.pullrequest.PullRequestPendingIntegration;
+import com.pmease.gitplex.core.event.pullrequest.PullRequestPendingUpdate;
+import com.pmease.gitplex.core.event.pullrequest.PullRequestReviewInvitationChanged;
+import com.pmease.gitplex.core.event.pullrequest.PullRequestStatusChangeEvent;
+import com.pmease.gitplex.core.event.pullrequest.PullRequestUpdated;
+import com.pmease.gitplex.core.manager.MailManager;
+import com.pmease.gitplex.core.manager.PullRequestTaskManager;
+import com.pmease.gitplex.core.manager.UrlManager;
+
+/**
+ * This class manages pull request tasks and send task notifications if necessary.
+ * Unlike watch based notifications, task notifications can not be suppressed.
+ *
+ * @author robin
+ *
+ */
+@Singleton
+public class DefaultPullRequestTaskManager extends AbstractEntityManager<PullRequestTask> implements PullRequestTaskManager {
+
+ private final MailManager mailManager;
+
+ private final UrlManager urlManager;
+
+ @Inject
+ public DefaultPullRequestTaskManager(Dao dao, MailManager mailManager, UrlManager urlManager) {
+ super(dao);
+
+ this.mailManager = mailManager;
+ this.urlManager = urlManager;
+ }
+
+ @Transactional
+ @Listen
+ public void on(PullRequestUpdated event) {
+ Query query = getSession().createQuery("delete from PullRequestTask "
+ + "where request=:request and type=:type");
+ query.setParameter("request", event.getRequest());
+ query.setParameter("type", UPDATE);
+ query.executeUpdate();
+ }
+
+ private void onClosed(PullRequest request) {
+ Query query = getSession().createQuery("delete from PullRequestTask "
+ + "where request=:request");
+ query.setParameter("request", request);
+ query.executeUpdate();
+ }
+
+ @Transactional
+ @Listen
+ public void on(PullRequestReviewInvitationChanged event) {
+ PullRequestReviewInvitation invitation = event.getInvitation();
+ PullRequest request = invitation.getRequest();
+ Account user = invitation.getUser();
+ if (invitation.getStatus() == PullRequestReviewInvitation.Status.EXCLUDED) {
+ Query query = getSession().createQuery("delete from PullRequestTask "
+ + "where request=:request and user=:user and type=:type");
+ query.setParameter("request", request);
+ query.setParameter("user", user);
+ query.setParameter("type", REVIEW);
+ query.executeUpdate();
+ } else if (invitation.getStatus() == PullRequestReviewInvitation.Status.ADDED_BY_RULE) {
+ PullRequestTask task = new PullRequestTask();
+ task.setRequest(request);
+ task.setUser(user);
+ task.setType(REVIEW);
+ EntityCriteria<PullRequestTask> criteria = EntityCriteria.of(PullRequestTask.class);
+ criteria.add(Restrictions.eq("request", request))
+ .add(Restrictions.eq("user", user))
+ .add(Restrictions.eq("type", task.getType()));
+ if (find(criteria) == null) {
+ save(task);
+
+ String subject = String.format("Please review pull request #%d (%s)",
+ request.getNumber(), request.getTitle());
+ String url = urlManager.urlFor(request);
+ String body = String.format("You are designated to review pull request #%d (%s).<br>"
+ + "Please visit <a href='%s'>%s</a> to do the review.",
+ request.getNumber(), request.getTitle(), url, url);
+ mailManager.sendMailAsync(Sets.newHashSet(task.getUser()), subject, decorate(user, body));
+ }
+ } else {
+ String subject = String.format("You are invited to review pull request #%d (%s)",
+ request.getNumber(), request.getTitle());
+ String url = urlManager.urlFor(request);
+ String body = String.format("You are invited to review pull request #%d (%s).<br>"
+ + "Please visit <a href='%s'>%s</a> to do the review.",
+ request.getNumber(), request.getTitle(), url, url);
+ mailManager.sendMailAsync(Sets.newHashSet(invitation.getUser()), subject, decorate(user, body));
+ }
+ }
+
+ private String decorate(Account user, String body) {
+ return String.format("Dear %s, "
+ + "<p style='margin: 16px 0;'>"
+ + "%s"
+ + "<p style='margin: 16px 0;'>"
+ + "-- Sent by GitPlex",
+ user.getDisplayName(), body);
+ }
+
+ @Transactional
+ @Listen
+ public void on(PullRequestPendingApproval event) {
+ Query query = getSession().createQuery("delete from PullRequestTask "
+ + "where request=:request and (type=:update or type=:integrate)");
+ query.setParameter("request", event.getRequest());
+ query.setParameter("update", UPDATE);
+ query.setParameter("integrate", INTEGRATE);
+ query.executeUpdate();
+ }
+
+ private void requestIntegration(PullRequest request) {
+ Account user = request.getAssignee();
+ PullRequestTask task = new PullRequestTask();
+ task.setRequest(request);
+ task.setUser(user);
+ task.setType(INTEGRATE);
+ EntityCriteria<PullRequestTask> criteria = EntityCriteria.of(PullRequestTask.class);
+ criteria.add(Restrictions.eq("request", task.getRequest()))
+ .add(Restrictions.eq("user", user))
+ .add(Restrictions.eq("type", task.getType()));
+ if (find(criteria) == null) {
+ save(task);
+ String subject = String.format("Please integrate pull request #%d (%s)",
+ request.getNumber(), request.getTitle());
+ String url = urlManager.urlFor(request);
+ String body = String.format("Pull request #%d (%s) is pending integration.<br>"
+ + "Please visit <a href='%s'>%s</a> to check and integrate.",
+ request.getNumber(), request.getTitle(), url, url);
+
+ mailManager.sendMailAsync(Sets.newHashSet(task.getUser()), subject, decorate(user, body));
+ }
+ }
+
+ @Transactional
+ @Listen
+ public void on(PullRequestPendingIntegration event) {
+ PullRequest request = event.getRequest();
+ if (request.getAssignee() != null)
+ requestIntegration(request);
+ }
+
+ @Transactional
+ @Listen
+ public void on(PullRequestPendingUpdate event) {
+ PullRequest request = event.getRequest();
+ PullRequestTask task = new PullRequestTask();
+ task.setRequest(request);
+ task.setUser(request.getSubmitter());
+ task.setType(UPDATE);
+ EntityCriteria<PullRequestTask> criteria = EntityCriteria.of(PullRequestTask.class);
+ criteria.add(Restrictions.eq("request", task.getRequest()))
+ .add(Restrictions.eq("user", task.getUser()))
+ .add(Restrictions.eq("type", task.getType()));
+ if (find(criteria) == null) {
+ save(task);
+ String subject = String.format("New commits are expected in pull request #%d (%s)",
+ request.getNumber(), request.getTitle());
+ String url = urlManager.urlFor(request);
+ String body = String.format("Next commits are expected for next round of review in pull request #%d (%s).<br>"
+ + "Please visit <a href='%s'>%s</a> for details",
+ request.getNumber(), request.getTitle(), url, url);
+ mailManager.sendMailAsync(Sets.newHashSet(request.getSubmitter()), subject,
+ decorate(request.getSubmitter(), body));
+ }
+ }
+
+ @Transactional
+ @Listen
+ public void on(PullRequestStatusChangeEvent event) {
+ PullRequestStatusChange statusChange = event.getStatusChange();
+ PullRequestStatusChange.Type type = statusChange.getType();
+ if (type == PullRequestStatusChange.Type.APPROVED || type == PullRequestStatusChange.Type.DISAPPROVED) {
+ onReviewed(statusChange);
+ } else if (type == PullRequestStatusChange.Type.ASSIGNED) {
+ PullRequest request = event.getRequest();
+ Preconditions.checkNotNull(request.getAssignee());
+
+ if (request.getStatus() == PENDING_INTEGRATE) {
+ Query query = getSession().createQuery("delete from PullRequestTask "
+ + "where request=:request and type=:type and user!=:user");
+ query.setParameter("request", request);
+ query.setParameter("type", INTEGRATE);
+ query.setParameter("user", request.getAssignee());
+ query.executeUpdate();
+
+ requestIntegration(request);
+ }
+ } else if (type == PullRequestStatusChange.Type.INTEGRATED || type == PullRequestStatusChange.Type.DISCARDED) {
+ onClosed(event.getRequest());
+ }
+ }
+
+ private void onReviewed(PullRequestStatusChange statusChange) {
+ Query query = getSession().createQuery("delete from PullRequestTask "
+ + "where request=:request and user=:user and type=:type");
+ query.setParameter("request", statusChange.getRequest());
+ query.setParameter("user", statusChange.getUser());
+ query.setParameter("type", REVIEW);
+ query.executeUpdate();
+ }
+
}
\ No newline at end of file
diff --git a/gitplex.product/system/conf/logback.xml b/gitplex.product/system/conf/logback.xml
index 7a0eaf05ee..5e5716dd49 100644
--- a/gitplex.product/system/conf/logback.xml
+++ b/gitplex.product/system/conf/logback.xml
@@ -1,41 +1,43 @@
-<?xml version="1.0" encoding="UTF-8"?>
-
-<configuration scan="true">
- <appender name="CONSOLE" class="ch.qos.logback.core.ConsoleAppender">
- <encoder class="ch.qos.logback.classic.encoder.PatternLayoutEncoder">
- <pattern>${logback.consoleLogPattern}</pattern>
- </encoder>
- </appender>
-
- <appender name="FILE" class="ch.qos.logback.core.rolling.RollingFileAppender">
- <file>${logback.logFile}</file>
- <encoder class="ch.qos.logback.classic.encoder.PatternLayoutEncoder">
- <pattern>${logback.fileLogPattern}</pattern>
- </encoder>
- <rollingPolicy class="ch.qos.logback.core.rolling.FixedWindowRollingPolicy">
- <maxIndex>3</maxIndex>
- <FileNamePattern>${logback.logFile}.%i</FileNamePattern>
- </rollingPolicy>
- <triggeringPolicy class="ch.qos.logback.core.rolling.SizeBasedTriggeringPolicy"/>
- </appender>
-
- <logger name="org.apache.wicket" level="WARN" />
- <logger name="org.eclipse" level="WARN" />
- <logger name="org.hibernate" level="WARN" />
- <logger name="java.sql.DatabaseMetaData" level="WARN"></logger>
- <logger name="org.hibernate.cache.ehcache.AbstractEhcacheRegionFactory" level="ERROR"></logger>
- <logger name="com.jolbox.bonecp.BoneCPConfig" level="WARN" />
- <logger name="com.sun.jersey" level="WARN" ></logger>
- <logger name="org.hibernate.engine.jdbc.internal.JdbcCoordinatorImpl" level="ERROR"></logger>
- <logger name="org.reflections" level="WARN"></logger>
- <logger name="org.apache.shiro.realm.AuthorizingRealm" level="WARN"></logger>
- <logger name="jetbrains.exodus" level="WARN"></logger>
- <logger name="com.zaxxer.hikari.HikariDataSource" level="ERROR"></logger>
- <logger name="com.pmease" level="INFO"></logger>
-
- <root level="WARN">
- <appender-ref ref="FILE" />
- <appender-ref ref="CONSOLE" />
- </root>
-
+<?xml version="1.0" encoding="UTF-8"?>
+
+<configuration scan="true">
+ <appender name="CONSOLE" class="ch.qos.logback.core.ConsoleAppender">
+ <encoder class="ch.qos.logback.classic.encoder.PatternLayoutEncoder">
+ <pattern>${logback.consoleLogPattern}</pattern>
+ </encoder>
+ </appender>
+
+ <appender name="FILE" class="ch.qos.logback.core.rolling.RollingFileAppender">
+ <file>${logback.logFile}</file>
+ <encoder class="ch.qos.logback.classic.encoder.PatternLayoutEncoder">
+ <pattern>${logback.fileLogPattern}</pattern>
+ </encoder>
+ <rollingPolicy class="ch.qos.logback.core.rolling.FixedWindowRollingPolicy">
+ <maxIndex>3</maxIndex>
+ <FileNamePattern>${logback.logFile}.%i</FileNamePattern>
+ </rollingPolicy>
+ <triggeringPolicy class="ch.qos.logback.core.rolling.SizeBasedTriggeringPolicy"/>
+ </appender>
+
+ <logger name="org.apache.wicket" level="WARN"/>
+ <logger name="org.apache.wicket.page.XmlPartialPageUpdate" level="ERROR"/>
+ <logger name="org.eclipse" level="WARN"/>
+ <logger name="org.hibernate" level="WARN"/>
+ <logger name="java.sql.DatabaseMetaData" level="WARN"/>
+ <logger name="org.hibernate.cache.ehcache.AbstractEhcacheRegionFactory" level="ERROR"/>
+ <logger name="org.hibernate.engine.jdbc.spi.SqlExceptionHelper" level="ERROR"/>
+ <logger name="com.jolbox.bonecp.BoneCPConfig" level="WARN"/>
+ <logger name="com.sun.jersey" level="WARN"/>
+ <logger name="org.hibernate.engine.jdbc.internal.JdbcCoordinatorImpl" level="ERROR"/>
+ <logger name="org.reflections" level="WARN"/>
+ <logger name="org.apache.shiro.realm.AuthorizingRealm" level="WARN"/>
+ <logger name="jetbrains.exodus" level="WARN"/>
+ <logger name="com.zaxxer.hikari.HikariDataSource" level="ERROR"/>
+ <logger name="com.pmease" level="INFO"/>
+
+ <root level="WARN">
+ <appender-ref ref="FILE"/>
+ <appender-ref ref="CONSOLE"/>
+ </root>
+
</configuration>
\ No newline at end of file
diff --git a/gitplex.web/src/main/java/com/pmease/gitplex/web/component/depotfile/editsave/EditSavePanel.java b/gitplex.web/src/main/java/com/pmease/gitplex/web/component/depotfile/editsave/EditSavePanel.java
index 1e8b5ba720..29ed3b525c 100644
--- a/gitplex.web/src/main/java/com/pmease/gitplex/web/component/depotfile/editsave/EditSavePanel.java
+++ b/gitplex.web/src/main/java/com/pmease/gitplex/web/component/depotfile/editsave/EditSavePanel.java
@@ -1,407 +1,407 @@
-package com.pmease.gitplex.web.component.depotfile.editsave;
-
-import java.io.IOException;
-
-import javax.annotation.Nullable;
-
-import org.apache.commons.lang3.StringEscapeUtils;
-import org.apache.commons.lang3.StringUtils;
-import org.apache.wicket.ajax.AjaxRequestTarget;
-import org.apache.wicket.ajax.attributes.AjaxRequestAttributes;
-import org.apache.wicket.ajax.attributes.AjaxRequestAttributes.Method;
-import org.apache.wicket.ajax.markup.html.AjaxLink;
-import org.apache.wicket.ajax.markup.html.form.AjaxButton;
-import org.apache.wicket.markup.ComponentTag;
-import org.apache.wicket.markup.head.IHeaderResponse;
-import org.apache.wicket.markup.head.JavaScriptHeaderItem;
-import org.apache.wicket.markup.head.OnDomReadyHeaderItem;
-import org.apache.wicket.markup.html.WebMarkupContainer;
-import org.apache.wicket.markup.html.form.Form;
-import org.apache.wicket.markup.html.form.TextArea;
-import org.apache.wicket.markup.html.form.TextField;
-import org.apache.wicket.markup.html.panel.FeedbackPanel;
-import org.apache.wicket.markup.html.panel.Panel;
-import org.apache.wicket.model.IModel;
-import org.apache.wicket.model.Model;
-import org.apache.wicket.request.cycle.RequestCycle;
-import org.eclipse.jgit.diff.DiffEntry;
-import org.eclipse.jgit.lib.ObjectId;
-import org.eclipse.jgit.lib.Repository;
-import org.eclipse.jgit.revwalk.RevCommit;
-import org.eclipse.jgit.revwalk.RevWalk;
-import org.eclipse.jgit.treewalk.TreeWalk;
-
-import com.google.common.base.Preconditions;
-import com.pmease.commons.git.Blob;
-import com.pmease.commons.git.BlobChange;
-import com.pmease.commons.git.BlobIdent;
-import com.pmease.commons.git.FileEdit;
-import com.pmease.commons.git.PathAndContent;
-import com.pmease.commons.git.exception.GitObjectAlreadyExistsException;
-import com.pmease.commons.git.exception.NotGitTreeException;
-import com.pmease.commons.git.exception.ObsoleteCommitException;
-import com.pmease.commons.lang.diff.WhitespaceOption;
-import com.pmease.gitplex.core.GitPlex;
-import com.pmease.gitplex.core.entity.Account;
-import com.pmease.gitplex.core.entity.Depot;
-import com.pmease.gitplex.core.entity.PullRequest;
-import com.pmease.gitplex.core.manager.AccountManager;
-import com.pmease.gitplex.web.component.diff.blob.BlobDiffPanel;
-import com.pmease.gitplex.web.component.diff.revision.DiffViewMode;
-import com.pmease.gitplex.web.page.depot.file.DepotFilePage;
-
-import de.agilecoders.wicket.core.markup.html.bootstrap.common.NotificationPanel;
-import jersey.repackaged.com.google.common.base.Objects;
-
-@SuppressWarnings("serial")
-public abstract class EditSavePanel extends Panel {
-
- private final IModel<Depot> depotModel;
-
- private final String refName;
-
- private FileEdit fileEdit;
-
- private final CancelListener cancelListener;
-
- private ObjectId prevCommitId;
-
- private ObjectId currentCommitId;
-
- private String summaryCommitMessage;
-
- private String detailCommitMessage;
-
- private BlobChange change;
-
- private boolean saveInProgress;
-
- public EditSavePanel(String id, IModel<Depot> depotModel, String refName,
- @Nullable String oldPath, @Nullable PathAndContent newFile,
- ObjectId prevCommitId, @Nullable CancelListener cancelListener) {
- super(id);
-
- this.depotModel = depotModel;
- this.refName = refName;
- this.fileEdit = new FileEdit(oldPath, newFile);
- this.cancelListener = cancelListener;
- this.prevCommitId = prevCommitId;
- }
-
- private String getDefaultCommitMessage() {
- String oldPath = fileEdit.getOldPath();
- String oldName;
- if (oldPath != null && oldPath.contains("/"))
- oldName = StringUtils.substringAfterLast(oldPath, "/");
- else
- oldName = oldPath;
-
- PathAndContent newFile = fileEdit.getNewFile();
- if (newFile == null) {
- return "Delete " + oldName;
- } else {
- String newPath = newFile.getPath();
-
- String newName;
- if (newPath != null && newPath.contains("/"))
- newName = StringUtils.substringAfterLast(newPath, "/");
- else
- newName = newPath;
-
- if (oldPath == null) {
- if (newName != null)
- return "Add " + newName;
- else
- return "Add new file";
- } else if (oldPath.equals(newPath)) {
- return "Edit " + oldName;
- } else {
- return "Rename " + oldName;
- }
- }
-
- }
-
- private void newChangedContainer(@Nullable AjaxRequestTarget target) {
- WebMarkupContainer changedContainer = new WebMarkupContainer("changed");
- changedContainer.setVisible(change != null);
- changedContainer.setOutputMarkupPlaceholderTag(true);
- if (change != null) {
- changedContainer.add(new BlobDiffPanel("changes", depotModel,
- new Model<PullRequest>(null), change, DiffViewMode.UNIFIED, null, null));
- } else {
- changedContainer.add(new WebMarkupContainer("changes"));
- }
- if (target != null) {
- replace(changedContainer);
- target.add(changedContainer);
- if (change != null) {
- String script = String.format("$('#%s .edit-save input[type=submit]').val('Commit and overwrite');",
- getMarkupId());
- target.appendJavaScript(script);
- }
- } else {
- add(changedContainer);
- }
- }
-
- @Override
- protected void onInitialize() {
- super.onInitialize();
-
- final NotificationPanel feedback = new NotificationPanel("feedback", this);
- feedback.setOutputMarkupPlaceholderTag(true);
- add(feedback);
-
- newChangedContainer(null);
-
- Form<?> form = new Form<Void>("form");
- add(form);
-
- form.add(new TextField<String>("summaryCommitMessage", new IModel<String>() {
-
- @Override
- public void detach() {
- }
-
- @Override
- public String getObject() {
- return summaryCommitMessage;
- }
-
- @Override
- public void setObject(String object) {
- summaryCommitMessage = object;
- }
-
- }) {
-
- @Override
- protected void onComponentTag(ComponentTag tag) {
- super.onComponentTag(tag);
- tag.put("placeholder", getDefaultCommitMessage());
- }
-
- });
-
- form.add(new TextArea<String>("detailCommitMessage", new IModel<String>() {
-
- @Override
- public void detach() {
- }
-
- @Override
- public String getObject() {
- return detailCommitMessage;
- }
-
- @Override
- public void setObject(String object) {
- detailCommitMessage = object;
- }
-
- }));
-
- AjaxButton saveButton = new AjaxButton("save") {
-
- @Override
- protected void updateAjaxAttributes(AjaxRequestAttributes attributes) {
- super.updateAjaxAttributes(attributes);
- attributes.setMethod(Method.POST);
-
- String script = String.format(""
- + "var viewState = $('#%s').data('viewState');"
- + "return viewState?JSON.stringify(viewState):'';", EditSavePanel.this.getMarkupId());
- attributes.getDynamicExtraParameters().add("return {view_state: function() {" + script + "}}");
- }
-
- @Override
- protected void onComponentTag(ComponentTag tag) {
- super.onComponentTag(tag);
-
- if (saveInProgress || (fileEdit.getOldPath() != null && fileEdit.getNewFile() != null))
- tag.put("disabled", "disabled");
- if (saveInProgress)
- tag.put("value", "Please wait...");
- }
-
- @Override
- protected void onSubmit(AjaxRequestTarget target, Form<?> form) {
- super.onSubmit(target, form);
- save(target, feedback);
- saveInProgress = true;
- target.add(this);
- target.appendJavaScript("pmease.commons.form.markClean($('form'));");
- }
-
- };
- saveButton.setOutputMarkupId(true);
- form.add(saveButton);
-
- form.add(new AjaxLink<Void>("cancel") {
-
- @Override
- protected void onConfigure() {
- super.onConfigure();
- setVisible(cancelListener != null);
- }
-
- @Override
- public void onClick(AjaxRequestTarget target) {
- cancelListener.onCancel(target);
- }
-
- });
-
- setOutputMarkupId(true);
- }
-
- private void save(AjaxRequestTarget target, FeedbackPanel feedback) {
- String viewState = RequestCycle.get().getRequest().getPostParameters()
- .getParameterValue("view_state").toString();
- RequestCycle.get().setMetaData(DepotFilePage.VIEW_STATE_KEY, viewState);
-
- change = null;
-
- PathAndContent newFile = fileEdit.getNewFile();
- if (newFile != null && StringUtils.isBlank(newFile.getPath())) {
- EditSavePanel.this.error("Please specify file name.");
- target.add(feedback);
- } else {
- String commitMessage = summaryCommitMessage;
- if (StringUtils.isBlank(commitMessage))
- commitMessage = getDefaultCommitMessage();
- if (StringUtils.isNotBlank(detailCommitMessage))
- commitMessage += "\n\n" + detailCommitMessage;
- Account user = Preconditions.checkNotNull(GitPlex.getInstance(AccountManager.class).getCurrent());
-
- Repository repository = depotModel.getObject().getRepository();
- ObjectId newCommitId = null;
- while(newCommitId == null) {
- try {
- newCommitId = fileEdit.commit(repository, refName,
- prevCommitId, prevCommitId, user.asPerson(), commitMessage);
- } catch (ObsoleteCommitException e) {
- currentCommitId = e.getOldCommitId();
- try (RevWalk revWalk = new RevWalk(repository)) {
- RevCommit prevCommit = revWalk.parseCommit(prevCommitId);
- RevCommit currentCommit = revWalk.parseCommit(currentCommitId);
- prevCommitId = currentCommitId;
-
- String oldPath = fileEdit.getOldPath();
- if (oldPath != null) {
- TreeWalk treeWalk = TreeWalk.forPath(repository, oldPath,
- prevCommit.getTree().getId(), currentCommit.getTree().getId());
- if (treeWalk != null) {
- if (!treeWalk.getObjectId(0).equals(treeWalk.getObjectId(1))
- || !treeWalk.getFileMode(0).equals(treeWalk.getFileMode(1))) {
- // mark changed if original file exists and content or mode has been modified
- // by others
- if (treeWalk.getObjectId(1).equals(ObjectId.zeroId())) {
- if (newFile != null) {
- fileEdit = new FileEdit(null, newFile);
- change = getChange(treeWalk, prevCommit, currentCommit);
- break;
- } else {
- newCommitId = currentCommitId;
- break;
- }
- } else {
- change = getChange(treeWalk, prevCommit, currentCommit);
- break;
- }
- }
- }
- }
- if (newFile != null && !newFile.getPath().equals(oldPath)) {
- TreeWalk treeWalk = TreeWalk.forPath(repository, newFile.getPath(),
- prevCommit.getTree().getId(), currentCommit.getTree().getId());
- if (treeWalk != null) {
- if (!treeWalk.getObjectId(0).equals(treeWalk.getObjectId(1))
- || !treeWalk.getFileMode(0).equals(treeWalk.getFileMode(1))) {
- // if added/renamed file exists and content or mode has been modified
- // by others
- change = getChange(treeWalk, prevCommit, currentCommit);
- break;
- }
- }
- }
- } catch (IOException e2) {
- throw new RuntimeException(e2);
- }
- } catch (GitObjectAlreadyExistsException e) {
- EditSavePanel.this.error("A file with same name already exists. "
- + "Please choose a different name and try again.");
- target.add(feedback);
- break;
- } catch (NotGitTreeException e) {
- EditSavePanel.this.error("A file exists where you’re trying to create a subdirectory. "
- + "Choose a new path and try again..");
- target.add(feedback);
- break;
- }
- }
- if (newCommitId != null)
- onCommitted(target, prevCommitId, newCommitId);
- else
- newChangedContainer(target);
- }
- }
-
- private BlobChange getChange(TreeWalk treeWalk, RevCommit oldCommit, RevCommit newCommit) {
- DiffEntry.ChangeType changeType = DiffEntry.ChangeType.MODIFY;
- BlobIdent oldBlobIdent = new BlobIdent();
- oldBlobIdent.revision = oldCommit.name();
- if (!treeWalk.getObjectId(0).equals(ObjectId.zeroId())) {
- oldBlobIdent.path = treeWalk.getPathString();
- oldBlobIdent.mode = treeWalk.getRawMode(0);
- } else {
- changeType = DiffEntry.ChangeType.ADD;
- }
-
- BlobIdent newBlobIdent = new BlobIdent();
- newBlobIdent.revision = newCommit.name();
- if (!treeWalk.getObjectId(1).equals(ObjectId.zeroId())) {
- newBlobIdent.path = treeWalk.getPathString();
- newBlobIdent.mode = treeWalk.getRawMode(1);
- } else {
- changeType = DiffEntry.ChangeType.DELETE;
- }
-
- return new BlobChange(changeType, oldBlobIdent, newBlobIdent, WhitespaceOption.DEFAULT) {
-
- @Override
- public Blob getBlob(BlobIdent blobIdent) {
- return depotModel.getObject().getBlob(blobIdent);
- }
-
- };
- }
-
- @Override
- public void renderHead(IHeaderResponse response) {
- super.renderHead(response);
-
- response.render(JavaScriptHeaderItem.forReference(new EditSaveResourceReference()));
-
- String script = String.format("gitplex.editsave.init('%s');", getMarkupId());
- response.render(OnDomReadyHeaderItem.forScript(script));
- }
-
- protected abstract void onCommitted(AjaxRequestTarget target, ObjectId oldCommitId, ObjectId newCommitId);
-
- public void onNewPathChange(AjaxRequestTarget target) {
- String script = String.format("gitplex.editsave.onPathChange('%s', '%s', %b);",
- getMarkupId(), StringEscapeUtils.escapeEcmaScript(getDefaultCommitMessage()),
- Objects.equal(fileEdit.getNewFile().getPath(), fileEdit.getOldPath()));
- target.appendJavaScript(script);
- }
-
- @Override
- protected void onDetach() {
- depotModel.detach();
-
- super.onDetach();
- }
-
-}
+package com.pmease.gitplex.web.component.depotfile.editsave;
+
+import java.io.IOException;
+
+import javax.annotation.Nullable;
+
+import org.apache.commons.lang3.StringEscapeUtils;
+import org.apache.commons.lang3.StringUtils;
+import org.apache.wicket.ajax.AjaxRequestTarget;
+import org.apache.wicket.ajax.attributes.AjaxRequestAttributes;
+import org.apache.wicket.ajax.attributes.AjaxRequestAttributes.Method;
+import org.apache.wicket.ajax.markup.html.AjaxLink;
+import org.apache.wicket.ajax.markup.html.form.AjaxButton;
+import org.apache.wicket.markup.ComponentTag;
+import org.apache.wicket.markup.head.IHeaderResponse;
+import org.apache.wicket.markup.head.JavaScriptHeaderItem;
+import org.apache.wicket.markup.head.OnDomReadyHeaderItem;
+import org.apache.wicket.markup.html.WebMarkupContainer;
+import org.apache.wicket.markup.html.form.Form;
+import org.apache.wicket.markup.html.form.TextArea;
+import org.apache.wicket.markup.html.form.TextField;
+import org.apache.wicket.markup.html.panel.FeedbackPanel;
+import org.apache.wicket.markup.html.panel.Panel;
+import org.apache.wicket.model.IModel;
+import org.apache.wicket.model.Model;
+import org.apache.wicket.request.cycle.RequestCycle;
+import org.eclipse.jgit.diff.DiffEntry;
+import org.eclipse.jgit.lib.ObjectId;
+import org.eclipse.jgit.lib.Repository;
+import org.eclipse.jgit.revwalk.RevCommit;
+import org.eclipse.jgit.revwalk.RevWalk;
+import org.eclipse.jgit.treewalk.TreeWalk;
+
+import com.google.common.base.Preconditions;
+import com.pmease.commons.git.Blob;
+import com.pmease.commons.git.BlobChange;
+import com.pmease.commons.git.BlobIdent;
+import com.pmease.commons.git.FileEdit;
+import com.pmease.commons.git.PathAndContent;
+import com.pmease.commons.git.exception.GitObjectAlreadyExistsException;
+import com.pmease.commons.git.exception.NotGitTreeException;
+import com.pmease.commons.git.exception.ObsoleteCommitException;
+import com.pmease.commons.lang.diff.WhitespaceOption;
+import com.pmease.gitplex.core.GitPlex;
+import com.pmease.gitplex.core.entity.Account;
+import com.pmease.gitplex.core.entity.Depot;
+import com.pmease.gitplex.core.entity.PullRequest;
+import com.pmease.gitplex.core.manager.AccountManager;
+import com.pmease.gitplex.web.component.diff.blob.BlobDiffPanel;
+import com.pmease.gitplex.web.component.diff.revision.DiffViewMode;
+import com.pmease.gitplex.web.page.depot.file.DepotFilePage;
+
+import de.agilecoders.wicket.core.markup.html.bootstrap.common.NotificationPanel;
+import jersey.repackaged.com.google.common.base.Objects;
+
+@SuppressWarnings("serial")
+public abstract class EditSavePanel extends Panel {
+
+ private final IModel<Depot> depotModel;
+
+ private final String refName;
+
+ private FileEdit fileEdit;
+
+ private final CancelListener cancelListener;
+
+ private ObjectId prevCommitId;
+
+ private ObjectId currentCommitId;
+
+ private String summaryCommitMessage;
+
+ private String detailCommitMessage;
+
+ private BlobChange change;
+
+ private boolean saveInProgress;
+
+ public EditSavePanel(String id, IModel<Depot> depotModel, String refName,
+ @Nullable String oldPath, @Nullable PathAndContent newFile,
+ ObjectId prevCommitId, @Nullable CancelListener cancelListener) {
+ super(id);
+
+ this.depotModel = depotModel;
+ this.refName = refName;
+ this.fileEdit = new FileEdit(oldPath, newFile);
+ this.cancelListener = cancelListener;
+ this.prevCommitId = prevCommitId;
+ }
+
+ private String getDefaultCommitMessage() {
+ String oldPath = fileEdit.getOldPath();
+ String oldName;
+ if (oldPath != null && oldPath.contains("/"))
+ oldName = StringUtils.substringAfterLast(oldPath, "/");
+ else
+ oldName = oldPath;
+
+ PathAndContent newFile = fileEdit.getNewFile();
+ if (newFile == null) {
+ return "Delete " + oldName;
+ } else {
+ String newPath = newFile.getPath();
+
+ String newName;
+ if (newPath != null && newPath.contains("/"))
+ newName = StringUtils.substringAfterLast(newPath, "/");
+ else
+ newName = newPath;
+
+ if (oldPath == null) {
+ if (newName != null)
+ return "Add " + newName;
+ else
+ return "Add new file";
+ } else if (oldPath.equals(newPath)) {
+ return "Edit " + oldName;
+ } else {
+ return "Rename " + oldName;
+ }
+ }
+
+ }
+
+ private void newChangedContainer(@Nullable AjaxRequestTarget target) {
+ WebMarkupContainer changedContainer = new WebMarkupContainer("changed");
+ changedContainer.setVisible(change != null);
+ changedContainer.setOutputMarkupPlaceholderTag(true);
+ if (change != null) {
+ changedContainer.add(new BlobDiffPanel("changes", depotModel,
+ new Model<PullRequest>(null), change, DiffViewMode.UNIFIED, null, null));
+ } else {
+ changedContainer.add(new WebMarkupContainer("changes"));
+ }
+ if (target != null) {
+ replace(changedContainer);
+ target.add(changedContainer);
+ if (change != null) {
+ String script = String.format("$('#%s .edit-save input[type=submit]').val('Commit and overwrite');",
+ getMarkupId());
+ target.appendJavaScript(script);
+ }
+ } else {
+ add(changedContainer);
+ }
+ }
+
+ @Override
+ protected void onInitialize() {
+ super.onInitialize();
+
+ final NotificationPanel feedback = new NotificationPanel("feedback", this);
+ feedback.setOutputMarkupPlaceholderTag(true);
+ add(feedback);
+
+ newChangedContainer(null);
+
+ Form<?> form = new Form<Void>("form");
+ add(form);
+
+ form.add(new TextField<String>("summaryCommitMessage", new IModel<String>() {
+
+ @Override
+ public void detach() {
+ }
+
+ @Override
+ public String getObject() {
+ return summaryCommitMessage;
+ }
+
+ @Override
+ public void setObject(String object) {
+ summaryCommitMessage = object;
+ }
+
+ }) {
+
+ @Override
+ protected void onComponentTag(ComponentTag tag) {
+ super.onComponentTag(tag);
+ tag.put("placeholder", getDefaultCommitMessage());
+ }
+
+ });
+
+ form.add(new TextArea<String>("detailCommitMessage", new IModel<String>() {
+
+ @Override
+ public void detach() {
+ }
+
+ @Override
+ public String getObject() {
+ return detailCommitMessage;
+ }
+
+ @Override
+ public void setObject(String object) {
+ detailCommitMessage = object;
+ }
+
+ }));
+
+ AjaxButton saveButton = new AjaxButton("save") {
+
+ @Override
+ protected void updateAjaxAttributes(AjaxRequestAttributes attributes) {
+ super.updateAjaxAttributes(attributes);
+ attributes.setMethod(Method.POST);
+
+ String script = String.format(""
+ + "var viewState = $('#%s').data('viewState');"
+ + "return viewState?JSON.stringify(viewState):'';", EditSavePanel.this.getMarkupId());
+ attributes.getDynamicExtraParameters().add("return {view_state: function() {" + script + "}}");
+ }
+
+ @Override
+ protected void onComponentTag(ComponentTag tag) {
+ super.onComponentTag(tag);
+
+ if (saveInProgress || (fileEdit.getOldPath() != null && fileEdit.getNewFile() != null))
+ tag.put("disabled", "disabled");
+ if (saveInProgress)
+ tag.put("value", "Please wait...");
+ }
+
+ @Override
+ protected void onSubmit(AjaxRequestTarget target, Form<?> form) {
+ super.onSubmit(target, form);
+ save(target, feedback);
+ saveInProgress = true;
+ target.add(this);
+ target.appendJavaScript("pmease.commons.form.markClean($('form'));");
+ }
+
+ };
+ saveButton.setOutputMarkupId(true);
+ form.add(saveButton);
+
+ form.add(new AjaxLink<Void>("cancel") {
+
+ @Override
+ protected void onConfigure() {
+ super.onConfigure();
+ setVisible(cancelListener != null);
+ }
+
+ @Override
+ public void onClick(AjaxRequestTarget target) {
+ cancelListener.onCancel(target);
+ }
+
+ });
+
+ setOutputMarkupId(true);
+ }
+
+ private void save(AjaxRequestTarget target, FeedbackPanel feedback) {
+ String viewState = RequestCycle.get().getRequest().getPostParameters()
+ .getParameterValue("view_state").toString();
+ RequestCycle.get().setMetaData(DepotFilePage.VIEW_STATE_KEY, viewState);
+
+ change = null;
+
+ PathAndContent newFile = fileEdit.getNewFile();
+ if (newFile != null && StringUtils.isBlank(newFile.getPath())) {
+ EditSavePanel.this.error("Please specify file name.");
+ target.add(feedback);
+ } else {
+ String commitMessage = summaryCommitMessage;
+ if (StringUtils.isBlank(commitMessage))
+ commitMessage = getDefaultCommitMessage();
+ if (StringUtils.isNotBlank(detailCommitMessage))
+ commitMessage += "\n\n" + detailCommitMessage;
+ Account user = Preconditions.checkNotNull(GitPlex.getInstance(AccountManager.class).getCurrent());
+
+ Repository repository = depotModel.getObject().getRepository();
+ ObjectId newCommitId = null;
+ while(newCommitId == null) {
+ try {
+ newCommitId = fileEdit.commit(repository, refName,
+ prevCommitId, prevCommitId, user.asPerson(), commitMessage);
+ } catch (ObsoleteCommitException e) {
+ currentCommitId = e.getOldCommitId();
+ try (RevWalk revWalk = new RevWalk(repository)) {
+ RevCommit prevCommit = revWalk.parseCommit(prevCommitId);
+ RevCommit currentCommit = revWalk.parseCommit(currentCommitId);
+ prevCommitId = currentCommitId;
+
+ String oldPath = fileEdit.getOldPath();
+ if (oldPath != null) {
+ TreeWalk treeWalk = TreeWalk.forPath(repository, oldPath,
+ prevCommit.getTree().getId(), currentCommit.getTree().getId());
+ if (treeWalk != null) {
+ if (!treeWalk.getObjectId(0).equals(treeWalk.getObjectId(1))
+ || !treeWalk.getFileMode(0).equals(treeWalk.getFileMode(1))) {
+ // mark changed if original file exists and content or mode has been modified
+ // by others
+ if (treeWalk.getObjectId(1).equals(ObjectId.zeroId())) {
+ if (newFile != null) {
+ fileEdit = new FileEdit(null, newFile);
+ change = getChange(treeWalk, prevCommit, currentCommit);
+ break;
+ } else {
+ newCommitId = currentCommitId;
+ break;
+ }
+ } else {
+ change = getChange(treeWalk, prevCommit, currentCommit);
+ break;
+ }
+ }
+ }
+ }
+ if (newFile != null && !newFile.getPath().equals(oldPath)) {
+ TreeWalk treeWalk = TreeWalk.forPath(repository, newFile.getPath(),
+ prevCommit.getTree().getId(), currentCommit.getTree().getId());
+ if (treeWalk != null) {
+ if (!treeWalk.getObjectId(0).equals(treeWalk.getObjectId(1))
+ || !treeWalk.getFileMode(0).equals(treeWalk.getFileMode(1))) {
+ // if added/renamed file exists and content or mode has been modified
+ // by others
+ change = getChange(treeWalk, prevCommit, currentCommit);
+ break;
+ }
+ }
+ }
+ } catch (IOException e2) {
+ throw new RuntimeException(e2);
+ }
+ } catch (GitObjectAlreadyExistsException e) {
+ EditSavePanel.this.error("A file with same name already exists. "
+ + "Please choose a different name and try again.");
+ target.add(feedback);
+ break;
+ } catch (NotGitTreeException e) {
+ EditSavePanel.this.error("A file exists where you’re trying to create a subdirectory. "
+ + "Choose a new path and try again..");
+ target.add(feedback);
+ break;
+ }
+ }
+ if (newCommitId != null)
+ onCommitted(target, prevCommitId, newCommitId);
+ else
+ newChangedContainer(target);
+ }
+ }
+
+ private BlobChange getChange(TreeWalk treeWalk, RevCommit oldCommit, RevCommit newCommit) {
+ DiffEntry.ChangeType changeType = DiffEntry.ChangeType.MODIFY;
+ BlobIdent oldBlobIdent = new BlobIdent();
+ oldBlobIdent.revision = oldCommit.name();
+ if (!treeWalk.getObjectId(0).equals(ObjectId.zeroId())) {
+ oldBlobIdent.path = treeWalk.getPathString();
+ oldBlobIdent.mode = treeWalk.getRawMode(0);
+ } else {
+ changeType = DiffEntry.ChangeType.ADD;
+ }
+
+ BlobIdent newBlobIdent = new BlobIdent();
+ newBlobIdent.revision = newCommit.name();
+ if (!treeWalk.getObjectId(1).equals(ObjectId.zeroId())) {
+ newBlobIdent.path = treeWalk.getPathString();
+ newBlobIdent.mode = treeWalk.getRawMode(1);
+ } else {
+ changeType = DiffEntry.ChangeType.DELETE;
+ }
+
+ return new BlobChange(changeType, oldBlobIdent, newBlobIdent, WhitespaceOption.DEFAULT) {
+
+ @Override
+ public Blob getBlob(BlobIdent blobIdent) {
+ return depotModel.getObject().getBlob(blobIdent);
+ }
+
+ };
+ }
+
+ @Override
+ public void renderHead(IHeaderResponse response) {
+ super.renderHead(response);
+
+ response.render(JavaScriptHeaderItem.forReference(new EditSaveResourceReference()));
+
+ String script = String.format("gitplex.editsave.init('%s');", getMarkupId());
+ response.render(OnDomReadyHeaderItem.forScript(script));
+ }
+
+ protected abstract void onCommitted(AjaxRequestTarget target, ObjectId oldCommitId, ObjectId newCommitId);
+
+ public void onNewPathChange(AjaxRequestTarget target) {
+ String script = String.format("gitplex.editsave.onPathChange('%s', '%s', %b);",
+ getMarkupId(), StringEscapeUtils.escapeEcmaScript(getDefaultCommitMessage()),
+ Objects.equal(fileEdit.getNewFile().getPath(), fileEdit.getOldPath()));
+ target.appendJavaScript(script);
+ }
+
+ @Override
+ protected void onDetach() {
+ depotModel.detach();
+
+ super.onDetach();
+ }
+
+}
diff --git a/gitplex.web/src/main/java/com/pmease/gitplex/web/page/depot/file/DepotFilePage.java b/gitplex.web/src/main/java/com/pmease/gitplex/web/page/depot/file/DepotFilePage.java
index bc665cdbe9..fe53b546dd 100644
--- a/gitplex.web/src/main/java/com/pmease/gitplex/web/page/depot/file/DepotFilePage.java
+++ b/gitplex.web/src/main/java/com/pmease/gitplex/web/page/depot/file/DepotFilePage.java
@@ -1,1048 +1,1048 @@
-package com.pmease.gitplex.web.page.depot.file;
-
-import java.io.IOException;
-import java.io.Serializable;
-import java.util.ArrayList;
-import java.util.Collection;
-import java.util.HashMap;
-import java.util.List;
-import java.util.Map;
-import java.util.concurrent.atomic.AtomicReference;
-
-import javax.annotation.Nullable;
-
-import org.apache.commons.lang3.SerializationUtils;
-import org.apache.commons.lang3.StringUtils;
-import org.apache.shiro.subject.Subject;
-import org.apache.shiro.util.ThreadContext;
-import org.apache.wicket.Component;
-import org.apache.wicket.MetaDataKey;
-import org.apache.wicket.RestartResponseException;
-import org.apache.wicket.ajax.AjaxRequestTarget;
-import org.apache.wicket.behavior.AttributeAppender;
-import org.apache.wicket.core.request.handler.IPartialPageRequestHandler;
-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.image.Image;
-import org.apache.wicket.markup.html.link.Link;
-import org.apache.wicket.model.AbstractReadOnlyModel;
-import org.apache.wicket.protocol.ws.api.WebSocketRequestHandler;
-import org.apache.wicket.request.cycle.RequestCycle;
-import org.apache.wicket.request.mapper.parameter.PageParameters;
-import org.apache.wicket.request.resource.PackageResourceReference;
-import org.eclipse.jgit.lib.FileMode;
-import org.eclipse.jgit.lib.ObjectId;
-import org.eclipse.jgit.revwalk.RevCommit;
-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.pmease.commons.git.Blob;
-import com.pmease.commons.git.BlobIdent;
-import com.pmease.commons.git.GitUtils;
-import com.pmease.commons.git.exception.GitObjectNotFoundException;
-import com.pmease.commons.hibernate.UnitOfWork;
-import com.pmease.commons.lang.diff.DiffUtils;
-import com.pmease.commons.lang.extractors.TokenPosition;
-import com.pmease.commons.loader.ListenerRegistry;
-import com.pmease.commons.wicket.component.modal.ModalLink;
-import com.pmease.commons.wicket.websocket.WebSocketManager;
-import com.pmease.commons.wicket.websocket.WebSocketRegion;
-import com.pmease.commons.wicket.websocket.WebSocketRenderBehavior;
-import com.pmease.gitplex.core.GitPlex;
-import com.pmease.gitplex.core.entity.CodeComment;
-import com.pmease.gitplex.core.entity.Depot;
-import com.pmease.gitplex.core.entity.PullRequest;
-import com.pmease.gitplex.core.entity.PullRequestUpdate;
-import com.pmease.gitplex.core.entity.support.CommentPos;
-import com.pmease.gitplex.core.entity.support.TextRange;
-import com.pmease.gitplex.core.event.RefUpdated;
-import com.pmease.gitplex.core.manager.CodeCommentManager;
-import com.pmease.gitplex.core.manager.DepotManager;
-import com.pmease.gitplex.core.manager.PullRequestManager;
-import com.pmease.gitplex.core.security.SecurityUtils;
-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.archivemenulink.ArchiveMenuLink;
-import com.pmease.gitplex.web.component.depotfile.blobsearch.advanced.AdvancedSearchPanel;
-import com.pmease.gitplex.web.component.depotfile.blobsearch.instant.InstantSearchPanel;
-import com.pmease.gitplex.web.component.depotfile.blobsearch.result.SearchResultPanel;
-import com.pmease.gitplex.web.component.depotfile.blobview.BlobNameChangeCallback;
-import com.pmease.gitplex.web.component.depotfile.blobview.BlobRenderer;
-import com.pmease.gitplex.web.component.depotfile.blobview.BlobViewContext;
-import com.pmease.gitplex.web.component.depotfile.blobview.BlobViewPanel;
-import com.pmease.gitplex.web.component.depotfile.blobview.source.SourceViewPanel;
-import com.pmease.gitplex.web.component.depotfile.editsave.CancelListener;
-import com.pmease.gitplex.web.component.depotfile.editsave.EditSavePanel;
-import com.pmease.gitplex.web.component.depotfile.fileedit.FileEditPanel;
-import com.pmease.gitplex.web.component.depotfile.filelist.FileListPanel;
-import com.pmease.gitplex.web.component.depotfile.filenavigator.FileNavigator;
-import com.pmease.gitplex.web.component.revisionpicker.RevisionPicker;
-import com.pmease.gitplex.web.page.depot.DepotPage;
-import com.pmease.gitplex.web.page.depot.NoBranchesPage;
-import com.pmease.gitplex.web.page.depot.commit.DepotCommitsPage;
-import com.pmease.gitplex.web.page.depot.pullrequest.requestdetail.changes.RequestChangesPage;
-import com.pmease.gitplex.web.websocket.CodeCommentChangedRegion;
-import com.pmease.gitplex.web.websocket.CommitIndexedRegion;
-import com.pmease.gitplex.web.websocket.PullRequestChangedRegion;
-
-@SuppressWarnings("serial")
-public class DepotFilePage extends DepotPage implements BlobViewContext {
-
- private static class SearchResultKey extends MetaDataKey<ArrayList<QueryHit>> {
- };
-
- public static final SearchResultKey SEARCH_RESULT_KEY = new SearchResultKey();
-
- private static class ViewStateKey extends MetaDataKey<String> {
- };
-
- public static final ViewStateKey VIEW_STATE_KEY = new ViewStateKey();
-
- private static final String PARAM_REVISION = "revision";
-
- private static final String PARAM_PATH = "path";
-
- private static final String PARAM_REQUEST_COMPARE_INFO = "request_compare_info";
-
- 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_VIEW_STATE = "view_state";
-
- private static final String PARAM_MARK = "mark";
-
- private static final String PARAM_ANCHOR = "anchor";
-
- private static final String REVISION_PICKER_ID = "revisionPicker";
-
- private static final String FILE_NAVIGATOR_ID = "fileNavigator";
-
- private static final String FILE_VIEWER_ID = "fileViewer";
-
- private static final String SEARCH_RESULD_ID = "searchResult";
-
- private BlobIdent blobIdent = new BlobIdent();
-
- private ObjectId resolvedRevision;
-
- private TextRange mark;
-
- private String anchor;
-
- private Mode mode;
-
- private RequestCompareInfo requestCompareInfo;
-
- private Long commentId;
-
- private Component revisionIndexing;
-
- private WebMarkupContainer searchResultContainer;
-
- private AtomicReference<String> newPathRef;
-
- private ObjectId commitId;
-
- private transient List<QueryHit> queryHits;
-
- public DepotFilePage(final PageParameters params) {
- super(params);
-
- if (getDepot().getDefaultBranch() == null)
- throw new RestartResponseException(NoBranchesPage.class, paramsOf(getDepot()));
-
- blobIdent.revision = params.get(PARAM_REVISION).toString();
- blobIdent.path = GitUtils.normalizePath(params.get(PARAM_PATH).toString());
-
- blobIdent.revision = GitUtils.normalizePath(params.get(PARAM_REVISION).toString());
- if (blobIdent.revision == null)
- blobIdent.revision = getDepot().getDefaultBranch();
-
- resolvedRevision = getDepot().getObjectId(blobIdent.revision);
-
- RevCommit commit = getDepot().getRevCommit(blobIdent.revision);
- commitId = commit.copy();
-
- if (blobIdent.path != null) {
- try (RevWalk revWalk = new RevWalk(getDepot().getRepository())) {
- RevTree revTree = commit.getTree();
- TreeWalk treeWalk = TreeWalk.forPath(getDepot().getRepository(), blobIdent.path, revTree);
- if (treeWalk == null) {
- throw new GitObjectNotFoundException("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());
- mark = TextRange.of(params.get(PARAM_MARK).toString());
- anchor = params.get(PARAM_ANCHOR).toString();
-
- commentId = params.get(PARAM_COMMENT).toOptionalLong();
-
- requestCompareInfo = RequestCompareInfo.fromString(params.get(PARAM_REQUEST_COMPARE_INFO).toString());
-
- 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(depotModel.getObject(), commitId, query);
- } catch (InterruptedException e) {
- throw new RuntimeException(e);
- }
- }
- }
-
- if (mode == Mode.EDIT || mode == Mode.DELETE) {
- if (!isOnBranch())
- throw new RuntimeException("Files can only be edited on branch");
-
- String path = blobIdent.path;
- if (path != null && blobIdent.isTree())
- path += "/";
- if (!SecurityUtils.canModify(getDepot(), blobIdent.revision, path))
- unauthorized();
- }
-
- String viewStateStr = params.get(PARAM_VIEW_STATE).toString();
- if (viewStateStr == null) {
- CodeComment comment = getOpenComment();
- if (comment != null) {
- int cursorLine;
- CommentPos commentPos = comment.getCommentPos();
- try {
- if (commentPos.getCommit().equals(resolvedRevision.name())) {
- cursorLine = commentPos.getRange().getBeginLine();
- } else {
- BlobIdent commentBlobIdent = new BlobIdent(
- commentPos.getCommit(), commentPos.getPath(), FileMode.TYPE_FILE);
- Blob blob = getDepot().getBlob(commentBlobIdent);
- List<String> oldLines = new ArrayList<>();
- for (String line: blob.getText().getLines()) {
- oldLines.add(comment.getCompareContext().getWhitespaceOption().process(line));
- }
- List<String> newLines = new ArrayList<>();
- for (String line: getDepot().getBlob(blobIdent).getText().getLines()) {
- newLines.add(comment.getCompareContext().getWhitespaceOption().process(line));
- }
- cursorLine = DiffUtils.getNewLineAround(oldLines, newLines, commentPos.getRange().getBeginLine());
- }
- viewStateStr = String.format("{\"cursor\":{\"line\":%d, \"ch\":0}}", cursorLine);
- } catch (GitObjectNotFoundException e) {
- }
- }
- }
- RequestCycle.get().setMetaData(VIEW_STATE_KEY, viewStateStr);
- }
-
- @Override
- protected void onInitialize() {
- super.onInitialize();
-
- add(new InstantSearchPanel("instantSearch", depotModel, 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());
- DepotFilePage.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, depotModel, 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;
- }
-
- };
- }
-
- });
-
- add(new Link<Void>("history") {
-
- @Override
- public void onClick() {
- DepotCommitsPage.State state = new DepotCommitsPage.State();
- state.setCompareWith(resolvedRevision.name());
- if (blobIdent.path != null)
- state.setQuery(String.format("path(%s)", blobIdent.path));
- setResponsePage(DepotCommitsPage.class, DepotCommitsPage.paramsOf(getDepot(), state));
- }
-
- });
-
- add(new ArchiveMenuLink("download", depotModel) {
-
- @Override
- protected String getRevision() {
- return blobIdent.revision;
- }
-
- });
-
- newRevisionPicker(null);
-
- newFileNavigator(null);
-
- add(revisionIndexing = new WebMarkupContainer("revisionIndexing") {
-
- @Override
- protected void onInitialize() {
- super.onInitialize();
- add(new Image("icon", new PackageResourceReference(DepotFilePage.class, "indexing.gif")));
- setOutputMarkupPlaceholderTag(true);
- }
-
- @Override
- protected void onConfigure() {
- super.onConfigure();
-
- IndexManager indexManager = GitPlex.getInstance(IndexManager.class);
- if (!indexManager.isIndexed(getDepot(), commitId)) {
- GitPlex.getInstance(IndexManager.class).indexAsync(getDepot(), commitId);
- setVisible(true);
- } else {
- setVisible(false);
- }
- }
-
- });
-
- newFileViewer(null);
-
- add(searchResultContainer = new WebMarkupContainer("searchResultContainer"));
-
- newSearchResult(null, queryHits);
-
- add(new WebSocketRenderBehavior() {
-
- @Override
- protected void onRender(WebSocketRequestHandler handler) {
- handler.add(revisionIndexing);
- resizeWindow(handler);
- }
-
- });
- }
-
- /*
- * In case we are on a branch, this operation makes sure that the branch resolves
- * to a certain commit during the life cycle of our page, unless the page is
- * refreshed. This can avoid the issue that displayed file content and subsequent
- * operations encounters different commit if someone commits to the branch while
- * we are staying on the page.
- */
- @Override
- protected Map<String, ObjectId> getObjectIdCache() {
- Map<String, ObjectId> objectIdCache = new HashMap<>();
- if (resolvedRevision != null)
- objectIdCache.put(blobIdent.revision, resolvedRevision);
- return objectIdCache;
- }
-
- @Override
- public CodeComment getOpenComment() {
- if (commentId != null)
- return GitPlex.getInstance(CodeCommentManager.class).load(commentId);
- else
- return null;
- }
-
- 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, this, callback) {
-
- @Override
- protected void onNewFile(AjaxRequestTarget target) {
- mode = Mode.EDIT;
-
- newFileNavigator(target);
- newFileViewer(target);
-
- pushState(target);
- resizeWindow(target);
- }
-
- };
- if (target != null) {
- replace(fileNavigator);
- target.add(fileNavigator);
- } else {
- add(fileNavigator);
- }
- }
-
- private BlobViewPanel renderBlobViewer(String panelId) {
- for (BlobRenderer renderer: GitPlex.getExtensions(BlobRenderer.class)) {
- BlobViewPanel panel = renderer.render(panelId, this);
- if (panel != null)
- return panel;
- }
-
- throw new IllegalStateException("No applicable blob renderer found.");
- }
-
- private void newFileViewer(@Nullable AjaxRequestTarget target) {
- 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, depotModel, refName,
- blobIdent.isTree()?null:blobIdent.path,
- blobIdent.isTree()?"":getDepot().getBlob(blobIdent).getText().getContent(),
- getDepot().getObjectId(blobIdent.revision), mark) {
-
- @Override
- protected void onCommitted(AjaxRequestTarget target, ObjectId oldCommit, ObjectId newCommit) {
- Depot depot = getDepot();
- String branch = blobIdent.revision;
- depot.cacheObjectId(branch, newCommit);
- resolvedRevision = newCommit;
- BlobIdent committed = new BlobIdent(
- branch, newPathRef.get(), FileMode.REGULAR_FILE.getBits());
-
- Subject subject = SecurityUtils.getSubject();
-
- Long depotId = depot.getId();
- ObjectId oldCommitId = oldCommit.copy();
- ObjectId newCommitId = newCommit.copy();
- GitPlex.getInstance(UnitOfWork.class).doAsync(new Runnable() {
-
- @Override
- public void run() {
- ThreadContext.bind(subject);
- try {
- Depot depot = GitPlex.getInstance(DepotManager.class).load(depotId);
- depot.cacheObjectId(branch, oldCommitId);
- RefUpdated event = new RefUpdated(depot, refName, oldCommitId, newCommitId);
- GitPlex.getInstance(ListenerRegistry.class).post(event);
- } finally {
- ThreadContext.unbindSubject();
- }
- }
-
- });
-
- if (requestCompareInfo != null) {
- showRequestChanges(target, oldCommitId, newCommitId);
- } else {
- State state = getState();
- state.blobIdent = committed;
- state.mode = null;
- applyState(target, state);
- pushState(target);
- resizeWindow(target);
- }
- // fix the issue that sometimes indexing indicator of new commit does not disappear
- target.appendJavaScript("Wicket.WebSocket.send('RenderCallback');");
- }
-
- @Override
- protected void onCancel(AjaxRequestTarget target) {
- if (requestCompareInfo != null) {
- PullRequest request = GitPlex.getInstance(PullRequestManager.class).load(requestCompareInfo.requestId);
- PageParameters params = RequestChangesPage.paramsOf(request, requestCompareInfo.compareState);
- setResponsePage(RequestChangesPage.class, params);
- } else {
- mode = null;
- newFileNavigator(target);
- newFileViewer(target);
- 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) {
- if (requestCompareInfo != null) {
- PullRequest request = GitPlex.getInstance(PullRequestManager.class).load(requestCompareInfo.requestId);
- PageParameters params = RequestChangesPage.paramsOf(request, requestCompareInfo.compareState);
- setResponsePage(RequestChangesPage.class, params);
- } else {
- mode = null;
- newFileViewer(target);
-
- pushState(target);
- resizeWindow(target);
- }
- }
-
- };
-
- fileViewer = new EditSavePanel(FILE_VIEWER_ID, depotModel, refName, blobIdent.path,
- null, getDepot().getObjectId(blobIdent.revision), cancelListener) {
-
- @Override
- protected void onCommitted(AjaxRequestTarget target, ObjectId oldCommit, ObjectId newCommit) {
- Depot depot = getDepot();
- String branch = blobIdent.revision;
- depot.cacheObjectId(branch, newCommit);
- resolvedRevision = newCommit;
- try (RevWalk revWalk = new RevWalk(getDepot().getRepository())) {
- RevTree revTree = getDepot().getRevCommit(newCommit).getTree();
- String parentPath = StringUtils.substringBeforeLast(blobIdent.path, "/");
- while (TreeWalk.forPath(getDepot().getRepository(), parentPath, revTree) == null) {
- if (parentPath.contains("/")) {
- parentPath = StringUtils.substringBeforeLast(parentPath, "/");
- } else {
- parentPath = null;
- break;
- }
- }
-
- Long depotId = depot.getId();
- Subject subject = SecurityUtils.getSubject();
- ObjectId oldCommitId = oldCommit.copy();
- ObjectId newCommitId = newCommit.copy();
- GitPlex.getInstance(UnitOfWork.class).doAsync(new Runnable() {
-
- @Override
- public void run() {
- ThreadContext.bind(subject);
- try {
- Depot depot = GitPlex.getInstance(DepotManager.class).load(depotId);
- depot.cacheObjectId(branch, newCommitId);
- RefUpdated event = new RefUpdated(depot, refName, oldCommitId, newCommitId);
- GitPlex.getInstance(ListenerRegistry.class).post(event);
- } finally {
- ThreadContext.unbindSubject();
- }
- }
-
- });
-
- if (requestCompareInfo != null) {
- showRequestChanges(target, oldCommitId, newCommitId);
- } else {
- BlobIdent parentBlobIdent = new BlobIdent(branch, parentPath, FileMode.TREE.getBits());
- State state = getState();
- state.blobIdent = parentBlobIdent;
- state.mode = null;
- applyState(target, state);
- pushState(target);
- resizeWindow(target);
- }
- // fix the issue that sometimes indexing indicator of new commit does not disappear
- target.appendJavaScript("Wicket.WebSocket.send('RenderCallback');");
- } catch (IOException e) {
- throw new RuntimeException(e);
- }
- }
-
- };
- } else if (blobIdent.path == null || blobIdent.isTree()) {
- fileViewer = new FileListPanel(FILE_VIEWER_ID, depotModel, blobIdent) {
-
- @Override
- protected void onSelect(AjaxRequestTarget target, BlobIdent blobIdent) {
- DepotFilePage.this.onSelect(target, blobIdent, null);
- }
-
- };
- } else {
- fileViewer = renderBlobViewer(FILE_VIEWER_ID);
- }
- if (target != null) {
- replace(fileViewer);
- target.add(fileViewer);
- } else {
- add(fileViewer);
- }
- }
-
- private void showRequestChanges(AjaxRequestTarget target, ObjectId oldCommitId, ObjectId newCommitId) {
- RequestChangesPage.State state = SerializationUtils.clone(requestCompareInfo.compareState);
- state.newCommit = newCommitId.name();
- state.pathFilter = null;
- if (state.commentId != null) {
- CodeComment comment = GitPlex.getInstance(CodeCommentManager.class).load(state.commentId);
- state.oldCommit = comment.getCommentPos().getCommit();
- } else {
- state.oldCommit = oldCommitId.name();
- }
- get(FILE_VIEWER_ID).add(new WebSocketRenderBehavior() {
-
- @Override
- protected void onRender(WebSocketRequestHandler handler) {
- PullRequest request = GitPlex.getInstance(PullRequestManager.class).load(requestCompareInfo.requestId);
- for (PullRequestUpdate update: request.getUpdates()) {
- if (update.getHeadCommitHash().equals(newCommitId.name())) {
- setResponsePage(RequestChangesPage.class, RequestChangesPage.paramsOf(request, state));
- break;
- }
- }
- }
-
- });
- }
-
- private void pushState(AjaxRequestTarget target) {
- PageParameters params = paramsOf(getDepot(), getState());
- CharSequence url = RequestCycle.get().urlFor(DepotFilePage.class, params);
- pushState(target, url.toString(), getState());
- }
-
- private State getState() {
- State state = new State();
- state.blobIdent = new BlobIdent(blobIdent);
- state.mark = mark;
- state.mode = mode;
- state.anchor = anchor;
- state.commentId = commentId;
- state.requestCompareInfo = requestCompareInfo;
- return state;
- }
-
- private void setState(State state) {
- if (!blobIdent.revision.equals(state.blobIdent.revision)) {
- blobIdent = new BlobIdent(state.blobIdent);
- /*
- * a hack to reset resolved revision to null to disable getObjectIdCache()
- * temporarily as otherwise getObjectId() method below will always
- * resolved to existing value of resolvedRevision
- */
- resolvedRevision = null;
- resolvedRevision = getDepot().getObjectId(blobIdent.revision);
- } else {
- blobIdent = new BlobIdent(state.blobIdent);
- }
- mark = state.mark;
- anchor = state.anchor;
- mode = state.mode;
- commentId = state.commentId;
- requestCompareInfo = state.requestCompareInfo;
- GitPlex.getInstance(WebSocketManager.class).onRegionChange(this);
- }
-
- private void onSelect(AjaxRequestTarget target, String revision) {
- State state = getState();
- state.blobIdent.revision = revision;
- state.requestCompareInfo = null;
- state.commentId = null;
- state.mode = null;
- state.mark = null;
-
- if (state.blobIdent.path != null) {
- try (RevWalk revWalk = new RevWalk(getDepot().getRepository())) {
- RevTree revTree = getDepot().getRevCommit(revision, true).getTree();
- TreeWalk treeWalk = TreeWalk.forPath(getDepot().getRepository(), 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);
- }
-
- private void newRevisionPicker(@Nullable AjaxRequestTarget target) {
- Component revisionPicker = new RevisionPicker(REVISION_PICKER_ID, depotModel, blobIdent.revision, true) {
-
- @Override
- protected String getRevisionUrl(String revision) {
- State state = new State();
- state.blobIdent.revision = revision;
- PageParameters params = DepotFilePage.paramsOf(depotModel.getObject(), state);
- return urlFor(DepotFilePage.class, params).toString();
- }
-
- @Override
- protected void onSelect(AjaxRequestTarget target, String revision) {
- DepotFilePage.this.onSelect(target, revision);
- }
-
- };
- if (target != null) {
- replace(revisionPicker);
- target.add(revisionPicker);
- } else {
- add(revisionPicker);
- }
- }
-
- private void applyState(AjaxRequestTarget target, State state) {
- if (!state.blobIdent.revision.equals(blobIdent.revision))
- newSearchResult(target, null);
-
- setState(state);
- commitId = getDepot().getRevCommit(blobIdent.revision).copy();
- GitPlex.getInstance(WebSocketManager.class).onRegionChange(this);
-
- newRevisionPicker(target);
-
- newFileNavigator(target);
-
- target.add(revisionIndexing);
-
- newFileViewer(target);
- }
-
- @Override
- public void renderHead(IHeaderResponse response) {
- super.renderHead(response);
-
- response.render(JavaScriptHeaderItem.forReference(new DepotFileResourceReference()));
- }
-
- public static PageParameters paramsOf(Depot depot, CodeComment comment, @Nullable String anchor) {
- DepotFilePage.State state = new DepotFilePage.State();
- state.blobIdent.revision = comment.getCommentPos().getCommit();
- state.blobIdent.path = comment.getCommentPos().getPath();
- state.blobIdent.mode = FileMode.TYPE_FILE;
- state.commentId = comment.getId();
- state.mark = comment.getCommentPos().getRange();
- state.anchor = anchor;
- return paramsOf(depot, state);
- }
-
- public static PageParameters paramsOf(Depot depot, State state) {
- PageParameters params = paramsOf(depot);
- 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.anchor != null)
- params.set(PARAM_ANCHOR, state.anchor);
- if (state.requestCompareInfo != null)
- params.set(PARAM_REQUEST_COMPARE_INFO, state.requestCompareInfo.toString());
- if (state.commentId != null)
- params.set(PARAM_COMMENT, state.commentId);
- if (state.mode != null)
- params.set(PARAM_MODE, state.mode.name().toLowerCase());
- if (state.query != null)
- params.set(PARAM_QUERY, state.query);
- if (state.viewState != null)
- params.set(PARAM_VIEW_STATE, state.viewState);
- 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, (State) data);
- resizeWindow(target);
- }
-
- private void resizeWindow(IPartialPageRequestHandler partialPageRequestHandler) {
- partialPageRequestHandler.appendJavaScript("$(window).resize();");
- }
-
- @Override
- protected void onSelect(AjaxRequestTarget target, Depot depot) {
- setResponsePage(DepotFilePage.class, paramsOf(depot));
- }
-
- @Override
- public BlobIdent getBlobIdent() {
- return blobIdent;
- }
-
- @Override
- public TextRange getMark() {
- return mark;
- }
-
- @Override
- public String getAnchor() {
- return anchor;
- }
-
- @Override
- public void onMark(AjaxRequestTarget target, TextRange mark) {
- this.mark = mark;
- pushState(target);
- }
-
- @Override
- public String getMarkUrl(TextRange mark) {
- State state = getState();
- state.blobIdent.revision = resolvedRevision.name();
- state.requestCompareInfo = null;
- state.commentId = null;
- state.mark = mark;
- PageParameters params = paramsOf(getDepot(), state);
- return RequestCycle.get().urlFor(DepotFilePage.class, params).toString();
- }
-
- @Override
- public Mode getMode() {
- return mode;
- }
-
- @Override
- public void onSelect(AjaxRequestTarget target, BlobIdent blobIdent, @Nullable TokenPosition tokenPos) {
- mark = TextRange.of(tokenPos);
- if (Objects.equal(DepotFilePage.this.blobIdent.path, blobIdent.path)) {
- if (mark != null) {
- Component fileViewer = get(FILE_VIEWER_ID);
- if (fileViewer instanceof SourceViewPanel) {
- SourceViewPanel sourceViewer = (SourceViewPanel) fileViewer;
- sourceViewer.mark(target, mark, true);
- } else if (fileViewer instanceof FileEditPanel) {
- FileEditPanel fileEditor = (FileEditPanel) fileViewer;
- fileEditor.mark(target, mark);
- } else {
- newFileViewer(target);
- resizeWindow(target);
- }
- }
- } else {
- DepotFilePage.this.blobIdent.path = blobIdent.path;
- DepotFilePage.this.blobIdent.mode = blobIdent.mode;
-
- mode = null;
- commentId = null;
- GitPlex.getInstance(WebSocketManager.class).onRegionChange(this);
-
- newFileNavigator(target);
- newFileViewer(target);
-
- resizeWindow(target);
- }
- pushState(target);
- }
-
- @Override
- public void onSearchComplete(AjaxRequestTarget target, List<QueryHit> hits) {
- newSearchResult(target, hits);
- resizeWindow(target);
- }
-
- @Override
- public void onBlameChange(AjaxRequestTarget target, boolean blame) {
- mode = (blame?Mode.BLAME:null);
- Component fileViewer = get(FILE_VIEWER_ID);
- if (!(fileViewer instanceof SourceViewPanel)) {
- newFileViewer(target);
- resizeWindow(target);
- }
- pushState(target);
- }
-
- @Override
- public void onDelete(AjaxRequestTarget target) {
- mode = Mode.DELETE;
-
- newFileViewer(target);
- pushState(target);
- resizeWindow(target);
- }
-
- @Override
- public void onEdit(AjaxRequestTarget target) {
- mode = Mode.EDIT;
-
- newFileNavigator(target);
- newFileViewer(target);
- pushState(target);
- resizeWindow(target);
- }
-
- @Override
- public void onCommentOpened(AjaxRequestTarget target, CodeComment comment) {
- if (comment != null) {
- commentId = comment.getId();
- mark = comment.getCommentPos().getRange();
- } else {
- commentId = null;
- mark = null;
- }
- GitPlex.getInstance(WebSocketManager.class).onRegionChange(this);
- pushState(target);
- }
-
- @Override
- public void onAddComment(AjaxRequestTarget target, TextRange mark) {
- commentId = null;
- GitPlex.getInstance(WebSocketManager.class).onRegionChange(this);
- this.mark = mark;
- pushState(target);
- }
-
- @Override
- public boolean isOnBranch() {
- return getDepot().getBranchRef(blobIdent.revision) != null;
- }
-
- @Override
- public RevCommit getCommit() {
- return getDepot().getRevCommit(getBlobIdent().revision);
- }
-
- @Override
- protected boolean isFootVisible() {
- return false;
- }
-
- @Override
- public Collection<WebSocketRegion> getWebSocketRegions() {
- List<WebSocketRegion> regions = new ArrayList<>();
- regions.add(new CommitIndexedRegion(getDepot().getId(), commitId));
- if (commentId != null)
- regions.add(new CodeCommentChangedRegion(commentId));
- if (requestCompareInfo != null)
- regions.add(new PullRequestChangedRegion(requestCompareInfo.requestId));
- return regions;
- }
-
- public static class State implements Serializable {
-
- private static final long serialVersionUID = 1L;
-
- public Long commentId;
-
- public BlobIdent blobIdent = new BlobIdent();
-
- public TextRange mark;
-
- public String anchor;
-
- public Mode mode;
-
- public RequestCompareInfo requestCompareInfo;
-
- public transient String query;
-
- public transient String viewState;
- }
-
-}
+package com.pmease.gitplex.web.page.depot.file;
+
+import java.io.IOException;
+import java.io.Serializable;
+import java.util.ArrayList;
+import java.util.Collection;
+import java.util.HashMap;
+import java.util.List;
+import java.util.Map;
+import java.util.concurrent.atomic.AtomicReference;
+
+import javax.annotation.Nullable;
+
+import org.apache.commons.lang3.SerializationUtils;
+import org.apache.commons.lang3.StringUtils;
+import org.apache.shiro.subject.Subject;
+import org.apache.shiro.util.ThreadContext;
+import org.apache.wicket.Component;
+import org.apache.wicket.MetaDataKey;
+import org.apache.wicket.RestartResponseException;
+import org.apache.wicket.ajax.AjaxRequestTarget;
+import org.apache.wicket.behavior.AttributeAppender;
+import org.apache.wicket.core.request.handler.IPartialPageRequestHandler;
+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.image.Image;
+import org.apache.wicket.markup.html.link.Link;
+import org.apache.wicket.model.AbstractReadOnlyModel;
+import org.apache.wicket.protocol.ws.api.WebSocketRequestHandler;
+import org.apache.wicket.request.cycle.RequestCycle;
+import org.apache.wicket.request.mapper.parameter.PageParameters;
+import org.apache.wicket.request.resource.PackageResourceReference;
+import org.eclipse.jgit.lib.FileMode;
+import org.eclipse.jgit.lib.ObjectId;
+import org.eclipse.jgit.revwalk.RevCommit;
+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.pmease.commons.git.Blob;
+import com.pmease.commons.git.BlobIdent;
+import com.pmease.commons.git.GitUtils;
+import com.pmease.commons.git.exception.GitObjectNotFoundException;
+import com.pmease.commons.hibernate.UnitOfWork;
+import com.pmease.commons.lang.diff.DiffUtils;
+import com.pmease.commons.lang.extractors.TokenPosition;
+import com.pmease.commons.loader.ListenerRegistry;
+import com.pmease.commons.wicket.component.modal.ModalLink;
+import com.pmease.commons.wicket.websocket.WebSocketManager;
+import com.pmease.commons.wicket.websocket.WebSocketRegion;
+import com.pmease.commons.wicket.websocket.WebSocketRenderBehavior;
+import com.pmease.gitplex.core.GitPlex;
+import com.pmease.gitplex.core.entity.CodeComment;
+import com.pmease.gitplex.core.entity.Depot;
+import com.pmease.gitplex.core.entity.PullRequest;
+import com.pmease.gitplex.core.entity.PullRequestUpdate;
+import com.pmease.gitplex.core.entity.support.CommentPos;
+import com.pmease.gitplex.core.entity.support.TextRange;
+import com.pmease.gitplex.core.event.RefUpdated;
+import com.pmease.gitplex.core.manager.CodeCommentManager;
+import com.pmease.gitplex.core.manager.DepotManager;
+import com.pmease.gitplex.core.manager.PullRequestManager;
+import com.pmease.gitplex.core.security.SecurityUtils;
+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.archivemenulink.ArchiveMenuLink;
+import com.pmease.gitplex.web.component.depotfile.blobsearch.advanced.AdvancedSearchPanel;
+import com.pmease.gitplex.web.component.depotfile.blobsearch.instant.InstantSearchPanel;
+import com.pmease.gitplex.web.component.depotfile.blobsearch.result.SearchResultPanel;
+import com.pmease.gitplex.web.component.depotfile.blobview.BlobNameChangeCallback;
+import com.pmease.gitplex.web.component.depotfile.blobview.BlobRenderer;
+import com.pmease.gitplex.web.component.depotfile.blobview.BlobViewContext;
+import com.pmease.gitplex.web.component.depotfile.blobview.BlobViewPanel;
+import com.pmease.gitplex.web.component.depotfile.blobview.source.SourceViewPanel;
+import com.pmease.gitplex.web.component.depotfile.editsave.CancelListener;
+import com.pmease.gitplex.web.component.depotfile.editsave.EditSavePanel;
+import com.pmease.gitplex.web.component.depotfile.fileedit.FileEditPanel;
+import com.pmease.gitplex.web.component.depotfile.filelist.FileListPanel;
+import com.pmease.gitplex.web.component.depotfile.filenavigator.FileNavigator;
+import com.pmease.gitplex.web.component.revisionpicker.RevisionPicker;
+import com.pmease.gitplex.web.page.depot.DepotPage;
+import com.pmease.gitplex.web.page.depot.NoBranchesPage;
+import com.pmease.gitplex.web.page.depot.commit.DepotCommitsPage;
+import com.pmease.gitplex.web.page.depot.pullrequest.requestdetail.changes.RequestChangesPage;
+import com.pmease.gitplex.web.websocket.CodeCommentChangedRegion;
+import com.pmease.gitplex.web.websocket.CommitIndexedRegion;
+import com.pmease.gitplex.web.websocket.PullRequestChangedRegion;
+
+@SuppressWarnings("serial")
+public class DepotFilePage extends DepotPage implements BlobViewContext {
+
+ private static class SearchResultKey extends MetaDataKey<ArrayList<QueryHit>> {
+ };
+
+ public static final SearchResultKey SEARCH_RESULT_KEY = new SearchResultKey();
+
+ private static class ViewStateKey extends MetaDataKey<String> {
+ };
+
+ public static final ViewStateKey VIEW_STATE_KEY = new ViewStateKey();
+
+ private static final String PARAM_REVISION = "revision";
+
+ private static final String PARAM_PATH = "path";
+
+ private static final String PARAM_REQUEST_COMPARE_INFO = "request_compare_info";
+
+ 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_VIEW_STATE = "view_state";
+
+ private static final String PARAM_MARK = "mark";
+
+ private static final String PARAM_ANCHOR = "anchor";
+
+ private static final String REVISION_PICKER_ID = "revisionPicker";
+
+ private static final String FILE_NAVIGATOR_ID = "fileNavigator";
+
+ private static final String FILE_VIEWER_ID = "fileViewer";
+
+ private static final String SEARCH_RESULD_ID = "searchResult";
+
+ private BlobIdent blobIdent = new BlobIdent();
+
+ private ObjectId resolvedRevision;
+
+ private TextRange mark;
+
+ private String anchor;
+
+ private Mode mode;
+
+ private RequestCompareInfo requestCompareInfo;
+
+ private Long commentId;
+
+ private Component revisionIndexing;
+
+ private WebMarkupContainer searchResultContainer;
+
+ private AtomicReference<String> newPathRef;
+
+ private ObjectId commitId;
+
+ private transient List<QueryHit> queryHits;
+
+ public DepotFilePage(final PageParameters params) {
+ super(params);
+
+ if (getDepot().getDefaultBranch() == null)
+ throw new RestartResponseException(NoBranchesPage.class, paramsOf(getDepot()));
+
+ blobIdent.revision = params.get(PARAM_REVISION).toString();
+ blobIdent.path = GitUtils.normalizePath(params.get(PARAM_PATH).toString());
+
+ blobIdent.revision = GitUtils.normalizePath(params.get(PARAM_REVISION).toString());
+ if (blobIdent.revision == null)
+ blobIdent.revision = getDepot().getDefaultBranch();
+
+ resolvedRevision = getDepot().getObjectId(blobIdent.revision);
+
+ RevCommit commit = getDepot().getRevCommit(blobIdent.revision);
+ commitId = commit.copy();
+
+ if (blobIdent.path != null) {
+ try (RevWalk revWalk = new RevWalk(getDepot().getRepository())) {
+ RevTree revTree = commit.getTree();
+ TreeWalk treeWalk = TreeWalk.forPath(getDepot().getRepository(), blobIdent.path, revTree);
+ if (treeWalk == null) {
+ throw new GitObjectNotFoundException("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());
+ mark = TextRange.of(params.get(PARAM_MARK).toString());
+ anchor = params.get(PARAM_ANCHOR).toString();
+
+ commentId = params.get(PARAM_COMMENT).toOptionalLong();
+
+ requestCompareInfo = RequestCompareInfo.fromString(params.get(PARAM_REQUEST_COMPARE_INFO).toString());
+
+ 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(depotModel.getObject(), commitId, query);
+ } catch (InterruptedException e) {
+ throw new RuntimeException(e);
+ }
+ }
+ }
+
+ if (mode == Mode.EDIT || mode == Mode.DELETE) {
+ if (!isOnBranch())
+ throw new RuntimeException("Files can only be edited on branch");
+
+ String path = blobIdent.path;
+ if (path != null && blobIdent.isTree())
+ path += "/";
+ if (!SecurityUtils.canModify(getDepot(), blobIdent.revision, path))
+ unauthorized();
+ }
+
+ String viewStateStr = params.get(PARAM_VIEW_STATE).toString();
+ if (viewStateStr == null) {
+ CodeComment comment = getOpenComment();
+ if (comment != null) {
+ int cursorLine;
+ CommentPos commentPos = comment.getCommentPos();
+ try {
+ if (commentPos.getCommit().equals(resolvedRevision.name())) {
+ cursorLine = commentPos.getRange().getBeginLine();
+ } else {
+ BlobIdent commentBlobIdent = new BlobIdent(
+ commentPos.getCommit(), commentPos.getPath(), FileMode.TYPE_FILE);
+ Blob blob = getDepot().getBlob(commentBlobIdent);
+ List<String> oldLines = new ArrayList<>();
+ for (String line: blob.getText().getLines()) {
+ oldLines.add(comment.getCompareContext().getWhitespaceOption().process(line));
+ }
+ List<String> newLines = new ArrayList<>();
+ for (String line: getDepot().getBlob(blobIdent).getText().getLines()) {
+ newLines.add(comment.getCompareContext().getWhitespaceOption().process(line));
+ }
+ cursorLine = DiffUtils.getNewLineAround(oldLines, newLines, commentPos.getRange().getBeginLine());
+ }
+ viewStateStr = String.format("{\"cursor\":{\"line\":%d, \"ch\":0}}", cursorLine);
+ } catch (GitObjectNotFoundException e) {
+ }
+ }
+ }
+ RequestCycle.get().setMetaData(VIEW_STATE_KEY, viewStateStr);
+ }
+
+ @Override
+ protected void onInitialize() {
+ super.onInitialize();
+
+ add(new InstantSearchPanel("instantSearch", depotModel, 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());
+ DepotFilePage.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, depotModel, 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;
+ }
+
+ };
+ }
+
+ });
+
+ add(new Link<Void>("history") {
+
+ @Override
+ public void onClick() {
+ DepotCommitsPage.State state = new DepotCommitsPage.State();
+ state.setCompareWith(resolvedRevision.name());
+ if (blobIdent.path != null)
+ state.setQuery(String.format("path(%s)", blobIdent.path));
+ setResponsePage(DepotCommitsPage.class, DepotCommitsPage.paramsOf(getDepot(), state));
+ }
+
+ });
+
+ add(new ArchiveMenuLink("download", depotModel) {
+
+ @Override
+ protected String getRevision() {
+ return blobIdent.revision;
+ }
+
+ });
+
+ newRevisionPicker(null);
+
+ newFileNavigator(null);
+
+ add(revisionIndexing = new WebMarkupContainer("revisionIndexing") {
+
+ @Override
+ protected void onInitialize() {
+ super.onInitialize();
+ add(new Image("icon", new PackageResourceReference(DepotFilePage.class, "indexing.gif")));
+ setOutputMarkupPlaceholderTag(true);
+ }
+
+ @Override
+ protected void onConfigure() {
+ super.onConfigure();
+
+ IndexManager indexManager = GitPlex.getInstance(IndexManager.class);
+ if (!indexManager.isIndexed(getDepot(), commitId)) {
+ GitPlex.getInstance(IndexManager.class).indexAsync(getDepot(), commitId);
+ setVisible(true);
+ } else {
+ setVisible(false);
+ }
+ }
+
+ });
+
+ newFileViewer(null);
+
+ add(searchResultContainer = new WebMarkupContainer("searchResultContainer"));
+
+ newSearchResult(null, queryHits);
+
+ add(new WebSocketRenderBehavior() {
+
+ @Override
+ protected void onRender(WebSocketRequestHandler handler) {
+ handler.add(revisionIndexing);
+ resizeWindow(handler);
+ }
+
+ });
+ }
+
+ /*
+ * In case we are on a branch, this operation makes sure that the branch resolves
+ * to a certain commit during the life cycle of our page, unless the page is
+ * refreshed. This can avoid the issue that displayed file content and subsequent
+ * operations encounters different commit if someone commits to the branch while
+ * we are staying on the page.
+ */
+ @Override
+ protected Map<String, ObjectId> getObjectIdCache() {
+ Map<String, ObjectId> objectIdCache = new HashMap<>();
+ if (resolvedRevision != null)
+ objectIdCache.put(blobIdent.revision, resolvedRevision);
+ return objectIdCache;
+ }
+
+ @Override
+ public CodeComment getOpenComment() {
+ if (commentId != null)
+ return GitPlex.getInstance(CodeCommentManager.class).load(commentId);
+ else
+ return null;
+ }
+
+ 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, this, callback) {
+
+ @Override
+ protected void onNewFile(AjaxRequestTarget target) {
+ mode = Mode.EDIT;
+
+ newFileNavigator(target);
+ newFileViewer(target);
+
+ pushState(target);
+ resizeWindow(target);
+ }
+
+ };
+ if (target != null) {
+ replace(fileNavigator);
+ target.add(fileNavigator);
+ } else {
+ add(fileNavigator);
+ }
+ }
+
+ private BlobViewPanel renderBlobViewer(String panelId) {
+ for (BlobRenderer renderer: GitPlex.getExtensions(BlobRenderer.class)) {
+ BlobViewPanel panel = renderer.render(panelId, this);
+ if (panel != null)
+ return panel;
+ }
+
+ throw new IllegalStateException("No applicable blob renderer found.");
+ }
+
+ private void newFileViewer(@Nullable AjaxRequestTarget target) {
+ 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, depotModel, refName,
+ blobIdent.isTree()?null:blobIdent.path,
+ blobIdent.isTree()?"":getDepot().getBlob(blobIdent).getText().getContent(),
+ getDepot().getObjectId(blobIdent.revision), mark) {
+
+ @Override
+ protected void onCommitted(AjaxRequestTarget target, ObjectId oldCommit, ObjectId newCommit) {
+ Depot depot = getDepot();
+ String branch = blobIdent.revision;
+ depot.cacheObjectId(branch, newCommit);
+ resolvedRevision = newCommit;
+ BlobIdent committed = new BlobIdent(
+ branch, newPathRef.get(), FileMode.REGULAR_FILE.getBits());
+
+ Subject subject = SecurityUtils.getSubject();
+
+ Long depotId = depot.getId();
+ ObjectId oldCommitId = oldCommit.copy();
+ ObjectId newCommitId = newCommit.copy();
+ GitPlex.getInstance(UnitOfWork.class).doAsync(new Runnable() {
+
+ @Override
+ public void run() {
+ ThreadContext.bind(subject);
+ try {
+ Depot depot = GitPlex.getInstance(DepotManager.class).load(depotId);
+ depot.cacheObjectId(branch, oldCommitId);
+ RefUpdated event = new RefUpdated(depot, refName, oldCommitId, newCommitId);
+ GitPlex.getInstance(ListenerRegistry.class).post(event);
+ } finally {
+ ThreadContext.unbindSubject();
+ }
+ }
+
+ });
+
+ if (requestCompareInfo != null) {
+ showRequestChanges(target, oldCommitId, newCommitId);
+ } else {
+ State state = getState();
+ state.blobIdent = committed;
+ state.mode = null;
+ applyState(target, state);
+ pushState(target);
+ resizeWindow(target);
+ }
+ // fix the issue that sometimes indexing indicator of new commit does not disappear
+ target.appendJavaScript("Wicket.WebSocket.send('RenderCallback');");
+ }
+
+ @Override
+ protected void onCancel(AjaxRequestTarget target) {
+ if (requestCompareInfo != null) {
+ PullRequest request = GitPlex.getInstance(PullRequestManager.class).load(requestCompareInfo.requestId);
+ PageParameters params = RequestChangesPage.paramsOf(request, requestCompareInfo.compareState);
+ setResponsePage(RequestChangesPage.class, params);
+ } else {
+ mode = null;
+ newFileNavigator(target);
+ newFileViewer(target);
+ 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) {
+ if (requestCompareInfo != null) {
+ PullRequest request = GitPlex.getInstance(PullRequestManager.class).load(requestCompareInfo.requestId);
+ PageParameters params = RequestChangesPage.paramsOf(request, requestCompareInfo.compareState);
+ setResponsePage(RequestChangesPage.class, params);
+ } else {
+ mode = null;
+ newFileViewer(target);
+
+ pushState(target);
+ resizeWindow(target);
+ }
+ }
+
+ };
+
+ fileViewer = new EditSavePanel(FILE_VIEWER_ID, depotModel, refName, blobIdent.path,
+ null, getDepot().getObjectId(blobIdent.revision), cancelListener) {
+
+ @Override
+ protected void onCommitted(AjaxRequestTarget target, ObjectId oldCommit, ObjectId newCommit) {
+ Depot depot = getDepot();
+ String branch = blobIdent.revision;
+ depot.cacheObjectId(branch, newCommit);
+ resolvedRevision = newCommit;
+ try (RevWalk revWalk = new RevWalk(getDepot().getRepository())) {
+ RevTree revTree = getDepot().getRevCommit(newCommit).getTree();
+ String parentPath = StringUtils.substringBeforeLast(blobIdent.path, "/");
+ while (TreeWalk.forPath(getDepot().getRepository(), parentPath, revTree) == null) {
+ if (parentPath.contains("/")) {
+ parentPath = StringUtils.substringBeforeLast(parentPath, "/");
+ } else {
+ parentPath = null;
+ break;
+ }
+ }
+
+ Long depotId = depot.getId();
+ Subject subject = SecurityUtils.getSubject();
+ ObjectId oldCommitId = oldCommit.copy();
+ ObjectId newCommitId = newCommit.copy();
+ GitPlex.getInstance(UnitOfWork.class).doAsync(new Runnable() {
+
+ @Override
+ public void run() {
+ ThreadContext.bind(subject);
+ try {
+ Depot depot = GitPlex.getInstance(DepotManager.class).load(depotId);
+ depot.cacheObjectId(branch, newCommitId);
+ RefUpdated event = new RefUpdated(depot, refName, oldCommitId, newCommitId);
+ GitPlex.getInstance(ListenerRegistry.class).post(event);
+ } finally {
+ ThreadContext.unbindSubject();
+ }
+ }
+
+ });
+
+ if (requestCompareInfo != null) {
+ showRequestChanges(target, oldCommitId, newCommitId);
+ } else {
+ BlobIdent parentBlobIdent = new BlobIdent(branch, parentPath, FileMode.TREE.getBits());
+ State state = getState();
+ state.blobIdent = parentBlobIdent;
+ state.mode = null;
+ applyState(target, state);
+ pushState(target);
+ resizeWindow(target);
+ }
+ // fix the issue that sometimes indexing indicator of new commit does not disappear
+ target.appendJavaScript("Wicket.WebSocket.send('RenderCallback');");
+ } catch (IOException e) {
+ throw new RuntimeException(e);
+ }
+ }
+
+ };
+ } else if (blobIdent.path == null || blobIdent.isTree()) {
+ fileViewer = new FileListPanel(FILE_VIEWER_ID, depotModel, blobIdent) {
+
+ @Override
+ protected void onSelect(AjaxRequestTarget target, BlobIdent blobIdent) {
+ DepotFilePage.this.onSelect(target, blobIdent, null);
+ }
+
+ };
+ } else {
+ fileViewer = renderBlobViewer(FILE_VIEWER_ID);
+ }
+ if (target != null) {
+ replace(fileViewer);
+ target.add(fileViewer);
+ } else {
+ add(fileViewer);
+ }
+ }
+
+ private void showRequestChanges(AjaxRequestTarget target, ObjectId oldCommitId, ObjectId newCommitId) {
+ RequestChangesPage.State state = SerializationUtils.clone(requestCompareInfo.compareState);
+ state.newCommit = newCommitId.name();
+ state.pathFilter = null;
+ if (state.commentId != null) {
+ CodeComment comment = GitPlex.getInstance(CodeCommentManager.class).load(state.commentId);
+ state.oldCommit = comment.getCommentPos().getCommit();
+ } else {
+ state.oldCommit = oldCommitId.name();
+ }
+ get(FILE_VIEWER_ID).add(new WebSocketRenderBehavior() {
+
+ @Override
+ protected void onRender(WebSocketRequestHandler handler) {
+ PullRequest request = GitPlex.getInstance(PullRequestManager.class).load(requestCompareInfo.requestId);
+ for (PullRequestUpdate update: request.getUpdates()) {
+ if (update.getHeadCommitHash().equals(newCommitId.name())) {
+ setResponsePage(RequestChangesPage.class, RequestChangesPage.paramsOf(request, state));
+ break;
+ }
+ }
+ }
+
+ });
+ }
+
+ private void pushState(AjaxRequestTarget target) {
+ PageParameters params = paramsOf(getDepot(), getState());
+ CharSequence url = RequestCycle.get().urlFor(DepotFilePage.class, params);
+ pushState(target, url.toString(), getState());
+ }
+
+ private State getState() {
+ State state = new State();
+ state.blobIdent = new BlobIdent(blobIdent);
+ state.mark = mark;
+ state.mode = mode;
+ state.anchor = anchor;
+ state.commentId = commentId;
+ state.requestCompareInfo = requestCompareInfo;
+ return state;
+ }
+
+ private void setState(State state) {
+ if (!blobIdent.revision.equals(state.blobIdent.revision)) {
+ blobIdent = new BlobIdent(state.blobIdent);
+ /*
+ * a hack to reset resolved revision to null to disable getObjectIdCache()
+ * temporarily as otherwise getObjectId() method below will always
+ * resolved to existing value of resolvedRevision
+ */
+ resolvedRevision = null;
+ resolvedRevision = getDepot().getObjectId(blobIdent.revision);
+ } else {
+ blobIdent = new BlobIdent(state.blobIdent);
+ }
+ mark = state.mark;
+ anchor = state.anchor;
+ mode = state.mode;
+ commentId = state.commentId;
+ requestCompareInfo = state.requestCompareInfo;
+ GitPlex.getInstance(WebSocketManager.class).onRegionChange(this);
+ }
+
+ private void onSelect(AjaxRequestTarget target, String revision) {
+ State state = getState();
+ state.blobIdent.revision = revision;
+ state.requestCompareInfo = null;
+ state.commentId = null;
+ state.mode = null;
+ state.mark = null;
+
+ if (state.blobIdent.path != null) {
+ try (RevWalk revWalk = new RevWalk(getDepot().getRepository())) {
+ RevTree revTree = getDepot().getRevCommit(revision, true).getTree();
+ TreeWalk treeWalk = TreeWalk.forPath(getDepot().getRepository(), 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);
+ }
+
+ private void newRevisionPicker(@Nullable AjaxRequestTarget target) {
+ Component revisionPicker = new RevisionPicker(REVISION_PICKER_ID, depotModel, blobIdent.revision, true) {
+
+ @Override
+ protected String getRevisionUrl(String revision) {
+ State state = new State();
+ state.blobIdent.revision = revision;
+ PageParameters params = DepotFilePage.paramsOf(depotModel.getObject(), state);
+ return urlFor(DepotFilePage.class, params).toString();
+ }
+
+ @Override
+ protected void onSelect(AjaxRequestTarget target, String revision) {
+ DepotFilePage.this.onSelect(target, revision);
+ }
+
+ };
+ if (target != null) {
+ replace(revisionPicker);
+ target.add(revisionPicker);
+ } else {
+ add(revisionPicker);
+ }
+ }
+
+ private void applyState(AjaxRequestTarget target, State state) {
+ if (!state.blobIdent.revision.equals(blobIdent.revision))
+ newSearchResult(target, null);
+
+ setState(state);
+ commitId = getDepot().getRevCommit(blobIdent.revision).copy();
+ GitPlex.getInstance(WebSocketManager.class).onRegionChange(this);
+
+ newRevisionPicker(target);
+
+ newFileNavigator(target);
+
+ target.add(revisionIndexing);
+
+ newFileViewer(target);
+ }
+
+ @Override
+ public void renderHead(IHeaderResponse response) {
+ super.renderHead(response);
+
+ response.render(JavaScriptHeaderItem.forReference(new DepotFileResourceReference()));
+ }
+
+ public static PageParameters paramsOf(Depot depot, CodeComment comment, @Nullable String anchor) {
+ DepotFilePage.State state = new DepotFilePage.State();
+ state.blobIdent.revision = comment.getCommentPos().getCommit();
+ state.blobIdent.path = comment.getCommentPos().getPath();
+ state.blobIdent.mode = FileMode.TYPE_FILE;
+ state.commentId = comment.getId();
+ state.mark = comment.getCommentPos().getRange();
+ state.anchor = anchor;
+ return paramsOf(depot, state);
+ }
+
+ public static PageParameters paramsOf(Depot depot, State state) {
+ PageParameters params = paramsOf(depot);
+ 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.anchor != null)
+ params.set(PARAM_ANCHOR, state.anchor);
+ if (state.requestCompareInfo != null)
+ params.set(PARAM_REQUEST_COMPARE_INFO, state.requestCompareInfo.toString());
+ if (state.commentId != null)
+ params.set(PARAM_COMMENT, state.commentId);
+ if (state.mode != null)
+ params.set(PARAM_MODE, state.mode.name().toLowerCase());
+ if (state.query != null)
+ params.set(PARAM_QUERY, state.query);
+ if (state.viewState != null)
+ params.set(PARAM_VIEW_STATE, state.viewState);
+ 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, (State) data);
+ resizeWindow(target);
+ }
+
+ private void resizeWindow(IPartialPageRequestHandler partialPageRequestHandler) {
+ partialPageRequestHandler.appendJavaScript("$(window).resize();");
+ }
+
+ @Override
+ protected void onSelect(AjaxRequestTarget target, Depot depot) {
+ setResponsePage(DepotFilePage.class, paramsOf(depot));
+ }
+
+ @Override
+ public BlobIdent getBlobIdent() {
+ return blobIdent;
+ }
+
+ @Override
+ public TextRange getMark() {
+ return mark;
+ }
+
+ @Override
+ public String getAnchor() {
+ return anchor;
+ }
+
+ @Override
+ public void onMark(AjaxRequestTarget target, TextRange mark) {
+ this.mark = mark;
+ pushState(target);
+ }
+
+ @Override
+ public String getMarkUrl(TextRange mark) {
+ State state = getState();
+ state.blobIdent.revision = resolvedRevision.name();
+ state.requestCompareInfo = null;
+ state.commentId = null;
+ state.mark = mark;
+ PageParameters params = paramsOf(getDepot(), state);
+ return RequestCycle.get().urlFor(DepotFilePage.class, params).toString();
+ }
+
+ @Override
+ public Mode getMode() {
+ return mode;
+ }
+
+ @Override
+ public void onSelect(AjaxRequestTarget target, BlobIdent blobIdent, @Nullable TokenPosition tokenPos) {
+ mark = TextRange.of(tokenPos);
+ if (Objects.equal(DepotFilePage.this.blobIdent.path, blobIdent.path)) {
+ if (mark != null) {
+ Component fileViewer = get(FILE_VIEWER_ID);
+ if (fileViewer instanceof SourceViewPanel) {
+ SourceViewPanel sourceViewer = (SourceViewPanel) fileViewer;
+ sourceViewer.mark(target, mark, true);
+ } else if (fileViewer instanceof FileEditPanel) {
+ FileEditPanel fileEditor = (FileEditPanel) fileViewer;
+ fileEditor.mark(target, mark);
+ } else {
+ newFileViewer(target);
+ resizeWindow(target);
+ }
+ }
+ } else {
+ DepotFilePage.this.blobIdent.path = blobIdent.path;
+ DepotFilePage.this.blobIdent.mode = blobIdent.mode;
+
+ mode = null;
+ commentId = null;
+ GitPlex.getInstance(WebSocketManager.class).onRegionChange(this);
+
+ newFileNavigator(target);
+ newFileViewer(target);
+
+ resizeWindow(target);
+ }
+ pushState(target);
+ }
+
+ @Override
+ public void onSearchComplete(AjaxRequestTarget target, List<QueryHit> hits) {
+ newSearchResult(target, hits);
+ resizeWindow(target);
+ }
+
+ @Override
+ public void onBlameChange(AjaxRequestTarget target, boolean blame) {
+ mode = (blame?Mode.BLAME:null);
+ Component fileViewer = get(FILE_VIEWER_ID);
+ if (!(fileViewer instanceof SourceViewPanel)) {
+ newFileViewer(target);
+ resizeWindow(target);
+ }
+ pushState(target);
+ }
+
+ @Override
+ public void onDelete(AjaxRequestTarget target) {
+ mode = Mode.DELETE;
+
+ newFileViewer(target);
+ pushState(target);
+ resizeWindow(target);
+ }
+
+ @Override
+ public void onEdit(AjaxRequestTarget target) {
+ mode = Mode.EDIT;
+
+ newFileNavigator(target);
+ newFileViewer(target);
+ pushState(target);
+ resizeWindow(target);
+ }
+
+ @Override
+ public void onCommentOpened(AjaxRequestTarget target, CodeComment comment) {
+ if (comment != null) {
+ commentId = comment.getId();
+ mark = comment.getCommentPos().getRange();
+ } else {
+ commentId = null;
+ mark = null;
+ }
+ GitPlex.getInstance(WebSocketManager.class).onRegionChange(this);
+ pushState(target);
+ }
+
+ @Override
+ public void onAddComment(AjaxRequestTarget target, TextRange mark) {
+ commentId = null;
+ GitPlex.getInstance(WebSocketManager.class).onRegionChange(this);
+ this.mark = mark;
+ pushState(target);
+ }
+
+ @Override
+ public boolean isOnBranch() {
+ return getDepot().getBranchRef(blobIdent.revision) != null;
+ }
+
+ @Override
+ public RevCommit getCommit() {
+ return getDepot().getRevCommit(getBlobIdent().revision);
+ }
+
+ @Override
+ protected boolean isFootVisible() {
+ return false;
+ }
+
+ @Override
+ public Collection<WebSocketRegion> getWebSocketRegions() {
+ List<WebSocketRegion> regions = new ArrayList<>();
+ regions.add(new CommitIndexedRegion(getDepot().getId(), commitId));
+ if (commentId != null)
+ regions.add(new CodeCommentChangedRegion(commentId));
+ if (requestCompareInfo != null)
+ regions.add(new PullRequestChangedRegion(requestCompareInfo.requestId));
+ return regions;
+ }
+
+ public static class State implements Serializable {
+
+ private static final long serialVersionUID = 1L;
+
+ public Long commentId;
+
+ public BlobIdent blobIdent = new BlobIdent();
+
+ public TextRange mark;
+
+ public String anchor;
+
+ public Mode mode;
+
+ public RequestCompareInfo requestCompareInfo;
+
+ public transient String query;
+
+ public transient String viewState;
+ }
+
+}
diff --git a/gitplex.web/src/main/java/com/pmease/gitplex/web/page/test/TestPage.html b/gitplex.web/src/main/java/com/pmease/gitplex/web/page/test/TestPage.html
index e8a32b1e9a..f8fafd68ce 100644
--- a/gitplex.web/src/main/java/com/pmease/gitplex/web/page/test/TestPage.html
+++ b/gitplex.web/src/main/java/com/pmease/gitplex/web/page/test/TestPage.html
@@ -1,2 +1,3 @@
<wicket:extend>
+ <a wicket:id="test">test</a>
</wicket:extend>
\ No newline at end of file