Skip to content

The Unified and Autonomous Development Platform

In the middle of refactoring mark

robin shine48045ff7e83a
diff --git a/gitplex.core/src/main/java/com/pmease/gitplex/core/entity/CodeComment.java b/gitplex.core/src/main/java/com/pmease/gitplex/core/entity/CodeComment.java
index 47b68fd41e..c2ffdb6bb6 100644
--- a/gitplex.core/src/main/java/com/pmease/gitplex/core/entity/CodeComment.java
+++ b/gitplex.core/src/main/java/com/pmease/gitplex/core/entity/CodeComment.java
@@ -23,6 +23,7 @@ import org.hibernate.annotations.OptimisticLock;
import com.pmease.commons.hibernate.AbstractEntity;
import com.pmease.commons.hibernate.dao.Dao;
import com.pmease.gitplex.core.GitPlex;
+import com.pmease.gitplex.core.entity.component.CompareContext;
import com.pmease.gitplex.core.entity.component.Mark;
/*
@@ -63,10 +64,9 @@ public class CodeComment extends AbstractEntity {
@OptimisticLock(excluded=true)
@Embedded
private Mark mark;
-
- @OptimisticLock(excluded=true)
- @Column(nullable=false)
- private String compareCommit;
+
+ @Embedded
+ private CompareContext compareContext;
@OneToMany(mappedBy="comment")
@OnDelete(action=OnDeleteAction.CASCADE)
@@ -137,12 +137,12 @@ public class CodeComment extends AbstractEntity {
this.mark = mark;
}
- public String getCompareCommit() {
- return compareCommit;
+ public CompareContext getCompareContext() {
+ return compareContext;
}
- public void setCompareCommit(String compareCommit) {
- this.compareCommit = compareCommit;
+ public void setCompareContext(CompareContext compareContext) {
+ this.compareContext = compareContext;
}
public Collection<CodeCommentReply> getReplies() {
diff --git a/gitplex.core/src/main/java/com/pmease/gitplex/core/entity/Depot.java b/gitplex.core/src/main/java/com/pmease/gitplex/core/entity/Depot.java
index 2a6af56268..907847ff54 100644
--- a/gitplex.core/src/main/java/com/pmease/gitplex/core/entity/Depot.java
+++ b/gitplex.core/src/main/java/com/pmease/gitplex/core/entity/Depot.java
@@ -673,9 +673,9 @@ public class Depot extends AbstractEntity implements AccountBelonging {
diffFormatter.setDetectRenames(true);
diffFormatter.setDiffAlgorithm(MyersDiff.INSTANCE);
diffFormatter.setDiffComparator(RawTextComparator.DEFAULT);
- AnyObjectId oldCommitId = getObjectId(oldRev);
- AnyObjectId newCommitId = getObjectId(newRev);
- for (DiffEntry entry: diffFormatter.scan(oldCommitId, newCommitId)) {
+ AnyObjectId oldRevId = getObjectId(oldRev);
+ AnyObjectId newRevId = getObjectId(newRev);
+ for (DiffEntry entry: diffFormatter.scan(oldRevId, newRevId)) {
if (!Objects.equal(entry.getOldPath(), entry.getNewPath())
|| !Objects.equal(entry.getOldMode(), entry.getNewMode())
|| entry.getOldId()==null || !entry.getOldId().isComplete()
diff --git a/gitplex.core/src/main/java/com/pmease/gitplex/core/entity/PullRequest.java b/gitplex.core/src/main/java/com/pmease/gitplex/core/entity/PullRequest.java
index 6fcaae3402..a623b0a42b 100644
--- a/gitplex.core/src/main/java/com/pmease/gitplex/core/entity/PullRequest.java
+++ b/gitplex.core/src/main/java/com/pmease/gitplex/core/entity/PullRequest.java
@@ -1,955 +1,939 @@
-package com.pmease.gitplex.core.entity;
-
-import java.util.ArrayList;
-import java.util.Collection;
-import java.util.Collections;
-import java.util.Date;
-import java.util.HashMap;
-import java.util.HashSet;
-import java.util.List;
-import java.util.Map;
-import java.util.Set;
-import java.util.concurrent.Callable;
-
-import javax.annotation.Nullable;
-import javax.persistence.Column;
-import javax.persistence.Embedded;
-import javax.persistence.Entity;
-import javax.persistence.FetchType;
-import javax.persistence.Index;
-import javax.persistence.JoinColumn;
-import javax.persistence.Lob;
-import javax.persistence.ManyToOne;
-import javax.persistence.OneToMany;
-import javax.persistence.PrePersist;
-import javax.persistence.Table;
-import javax.persistence.Transient;
-import javax.persistence.Version;
-
-import org.apache.commons.lang3.StringUtils;
-import org.hibernate.annotations.DynamicUpdate;
-import org.hibernate.annotations.OnDelete;
-import org.hibernate.annotations.OnDeleteAction;
-import org.hibernate.annotations.OptimisticLock;
-import org.hibernate.criterion.Criterion;
-import org.hibernate.criterion.Restrictions;
-
-import com.fasterxml.jackson.annotation.JsonView;
-import com.google.common.base.Preconditions;
-import com.pmease.commons.git.Commit;
-import com.pmease.commons.git.Git;
-import com.pmease.commons.git.GitUtils;
-import com.pmease.commons.hibernate.AbstractEntity;
-import com.pmease.commons.hibernate.dao.Dao;
-import com.pmease.commons.jackson.ExternalView;
-import com.pmease.commons.util.LockUtils;
-import com.pmease.gitplex.core.GitPlex;
-import com.pmease.gitplex.core.entity.component.CloseInfo;
-import com.pmease.gitplex.core.entity.component.DepotAndBranch;
-import com.pmease.gitplex.core.entity.component.IntegrationPreview;
-import com.pmease.gitplex.core.gatekeeper.checkresult.Blocking;
-import com.pmease.gitplex.core.gatekeeper.checkresult.CheckResult;
-import com.pmease.gitplex.core.gatekeeper.checkresult.Failed;
-import com.pmease.gitplex.core.gatekeeper.checkresult.Pending;
-import com.pmease.gitplex.core.manager.ConfigManager;
-import com.pmease.gitplex.core.manager.PullRequestManager;
-import com.pmease.gitplex.core.manager.ReviewManager;
-import com.pmease.gitplex.core.security.ObjectPermission;
-
-@Entity
-/*
- * @DynamicUpdate annotation here along with various @OptimisticLock annotations
- * on certain fields tell Hibernate not to perform version check on those fields
- * which can be updated from background thread.
- */
-@DynamicUpdate
-@Table(indexes={@Index(columnList="title"), @Index(columnList="idStr"), @Index(columnList="noSpaceTitle")})
-public class PullRequest extends AbstractEntity {
-
- private static final long serialVersionUID = 1L;
-
- public enum Status {
- PENDING_APPROVAL("Pending Approval"),
- PENDING_UPDATE("Pending Update"), PENDING_INTEGRATE("Pending Integration"),
- INTEGRATED("Integrated"), DISCARDED("Discarded");
-
- private final String displayName;
-
- Status(String displayName) {
- this.displayName = displayName;
- }
-
- @Override
- public String toString() {
- return displayName;
- }
-
- }
-
- public enum IntegrationStrategy {
- MERGE_ALWAYS("Merge always",
- "Always create merge commit when integrate into target branch"),
- MERGE_IF_NECESSARY("Merge if necessary",
- "Create merge commit only if target branch can not be fast-forwarded to the pull request"),
- MERGE_WITH_SQUASH("Merge with squash",
- "Squash all commits in the pull request and then merge with target branch"),
- REBASE_SOURCE_ONTO_TARGET("Rebase source onto target",
- "Rebase source branch onto target branch and then fast-forward target branch to source branch"),
- REBASE_TARGET_ONTO_SOURCE("Rebase target onto source",
- "Rebase target branch onto source branch");
-
- private final String displayName;
-
- private final String description;
-
- IntegrationStrategy(String displayName, String description) {
- this.displayName = displayName;
- this.description = description;
- }
-
- public String getDisplayName() {
- return displayName;
- }
-
- public String getDescription() {
- return description;
- }
-
- @Override
- public String toString() {
- return displayName;
- }
-
- }
-
- public enum Event {
- OPENED("Newly opened"),
- REVIEWED("New reviews in"),
- VERIFIED("Build verification is finished for"),
- UPDATED("New commits in"),
- COMMENTED("New comments in"),
- INTEGRATION_STRATEGY_CHANGED("Integration strategy is changed"),
- INTEGRATED("Integration is done for"),
- DISCARDED("Discarded"),
- REOPENED("Reopened"),
- INTEGRATION_PREVIEW_CALCULATED("Integration preview is calculated"),
- ASSIGNED("Assigned"),
- REVIEWER_CHANGED("Reviewer changed"),
- REVIEW_REMOVED("Review removed"),
- COMMENT_REPLIED("Comment is replied");
-
- private final String displayName;
-
- Event(String displayName) {
- this.displayName = displayName;
- }
-
- public String toString() {
- return displayName;
- }
-
- };
-
- @Embedded
- private CloseInfo closeInfo;
-
- @Column(nullable=false)
- private String title;
-
- @Lob
- @Column(length=65535)
- private String description;
-
- @ManyToOne(fetch=FetchType.LAZY)
- private Account submitter;
-
- @ManyToOne(fetch=FetchType.LAZY)
- @JoinColumn(nullable=false)
- private Depot targetDepot;
-
- @Column(nullable=false)
- private String targetBranch;
-
- @ManyToOne(fetch=FetchType.LAZY)
- private Depot sourceDepot;
-
- @Column(nullable=false)
- private String sourceBranch;
-
- @Column(nullable=false)
- private String baseCommitHash;
-
- @ManyToOne(fetch=FetchType.LAZY)
- private Account assignee;
-
- // used for id search in markdown editor
- @Column(nullable=false)
- private String idStr;
-
- // used for title search in markdown editor
- @Column(nullable=false)
- private String noSpaceTitle;
-
- @Version
- private long version;
-
- @Transient
- private Git sandbox;
-
- @OptimisticLock(excluded=true)
- @Embedded
- private IntegrationPreview lastIntegrationPreview;
-
- @Column(nullable=false)
- private Date submitDate = new Date();
-
- @OptimisticLock(excluded=true)
- @Column(nullable=false)
- private Date lastEventDate = new Date();
-
- @OptimisticLock(excluded=true)
- @Column(nullable=false)
- private Event lastEvent = Event.OPENED;
-
- @Column(nullable=false)
- private IntegrationStrategy integrationStrategy;
-
- @OneToMany(mappedBy="request")
- @OnDelete(action=OnDeleteAction.CASCADE)
- private Collection<PullRequestUpdate> updates = new ArrayList<>();
-
- @OneToMany(mappedBy="request")
- @OnDelete(action=OnDeleteAction.CASCADE)
- private Collection<ReviewInvitation> reviewInvitations = new ArrayList<>();
-
- @OneToMany(mappedBy="referenced")
- @OnDelete(action=OnDeleteAction.CASCADE)
- private Collection<PullRequestReference> referencedBy = new ArrayList<>();
-
- @OneToMany(mappedBy="referencedBy")
- @OnDelete(action=OnDeleteAction.CASCADE)
- private Collection<PullRequestReference> referenced = new ArrayList<>();
-
- @OneToMany(mappedBy="request")
- @OnDelete(action=OnDeleteAction.CASCADE)
- private Collection<Verification> verifications = new ArrayList<>();
-
- @OneToMany(mappedBy="request")
- @OnDelete(action=OnDeleteAction.CASCADE)
- private Collection<PullRequestComment> comments = new ArrayList<>();
-
- @OneToMany(mappedBy="request")
- @OnDelete(action=OnDeleteAction.CASCADE)
- private Collection<PullRequestActivity> activities = new ArrayList<>();
-
- @OneToMany(mappedBy="request")
- @OnDelete(action=OnDeleteAction.CASCADE)
- private Collection<Notification> notifications = new ArrayList<>();
-
- @OneToMany(mappedBy="request")
- @OnDelete(action=OnDeleteAction.CASCADE)
- private Collection<PullRequestVisit> visits = new ArrayList<>();
-
- @OneToMany(mappedBy="request")
- @OnDelete(action=OnDeleteAction.CASCADE)
- private Collection<PullRequestWatch> watches = new ArrayList<>();
-
- private transient CheckResult checkResult;
-
- private transient List<PullRequestUpdate> sortedUpdates;
-
- private transient List<PullRequestUpdate> effectiveUpdates;
-
- private transient PullRequestUpdate referentialUpdate;
-
- private transient Set<String> pendingCommits;
-
- private transient Collection<Commit> mergedCommits;
-
- private transient List<Review> reviews;
-
- /**
- * Get title of this merge request.
- *
- * @return user specified title of this merge request, <tt>null</tt> for
- * auto-created merge request.
- */
- public @Nullable String getTitle() {
- return title;
- }
-
- public void setTitle(String title) {
- this.title = title;
- noSpaceTitle = StringUtils.deleteWhitespace(title);
- }
-
- public String getDescription() {
- return description;
- }
-
- public void setDescription(String description) {
- this.description = description;
- }
-
- /**
- * Get the user submitting the pull request.
- *
- * @return
- * the user submitting the pull request, or <tt>null</tt> if unknown
- */
- @Nullable
- public Account getSubmitter() {
- return submitter;
- }
-
- public void setSubmitter(@Nullable Account submitter) {
- this.submitter = submitter;
- }
-
- /**
- * Get the user responsible for integration of the pull request.
- *
- * @return
- * the user responsible for integration of this pull request, or <tt>null</tt> to have the
- * system integrate the pull request automatically
- */
- @Nullable
- public Account getAssignee() {
- return assignee;
- }
-
- public void setAssignee(Account assignee) {
- this.assignee = assignee;
- }
-
- public Depot getTargetDepot() {
- return targetDepot;
- }
-
- public DepotAndBranch getTarget() {
- return new DepotAndBranch(getTargetDepot(), getTargetBranch());
- }
-
- public void setTarget(DepotAndBranch target) {
- setTargetDepot(target.getDepot());
- setTargetBranch(target.getBranch());
- }
-
- public void setSource(DepotAndBranch source) {
- setSourceDepot(source.getDepot());
- setSourceBranch(source.getBranch());
- }
-
- public void setTargetDepot(Depot targetDepot) {
- this.targetDepot = targetDepot;
- }
-
- public String getTargetBranch() {
- return targetBranch;
- }
-
- public void setTargetBranch(String targetBranch) {
- this.targetBranch = targetBranch;
- }
-
- @Nullable
- public Depot getSourceDepot() {
- return sourceDepot;
- }
-
- public void setSourceDepot(Depot sourceDepot) {
- this.sourceDepot = sourceDepot;
- }
-
- public String getSourceBranch() {
- return sourceBranch;
- }
-
- public void setSourceBranch(String sourceBranch) {
- this.sourceBranch = sourceBranch;
- }
-
- public DepotAndBranch getSource() {
- return new DepotAndBranch(getSourceDepot(), getSourceBranch());
- }
-
- public String getTargetRef() {
- return GitUtils.branch2ref(getTargetBranch());
- }
-
- public String getSourceRef() {
- return GitUtils.branch2ref(getSourceBranch());
- }
-
- public String getBaseCommitHash() {
- return baseCommitHash;
- }
-
- public void setBaseCommitHash(String baseCommitHash) {
- this.baseCommitHash = baseCommitHash;
- }
-
- public Commit getBaseCommit() {
- return getTargetDepot().getCommit(getBaseCommitHash());
- }
-
- public Git git() {
- if (sandbox == null)
- return getTargetDepot().git();
- else
- return sandbox;
- }
-
- public Git getSandbox() {
- return sandbox;
- }
-
- public void setSandbox(Git sandbox) {
- this.sandbox = sandbox;
- }
-
- /**
- * Get unmodifiable collection of updates of this pull request. To add update
- * to the pull request, call {@link this#addUpdate(PullRequestUpdate)} instead.
- *
- * @return
- * unmodifiable collection of updates
- */
- public Collection<PullRequestUpdate> getUpdates() {
- return Collections.unmodifiableCollection(updates);
- }
-
- public void setUpdates(Collection<PullRequestUpdate> updates) {
- this.updates = updates;
- sortedUpdates = null;
- effectiveUpdates = null;
- }
-
- public void addUpdate(PullRequestUpdate update) {
- updates.add(update);
- sortedUpdates = null;
- effectiveUpdates = null;
- }
-
- public Collection<ReviewInvitation> getReviewInvitations() {
- return reviewInvitations;
- }
-
- public void setReviewInvitations(Collection<ReviewInvitation> reviewInvitations) {
- this.reviewInvitations = reviewInvitations;
- }
-
- public Collection<Verification> getVerifications() {
- return verifications;
- }
-
- public void setVerifications(Collection<Verification> verifications) {
- this.verifications = verifications;
- }
-
- public Collection<PullRequestReference> getReferencedBy() {
- return referencedBy;
- }
-
- public void setReferencedBy(Collection<PullRequestReference> referencedBy) {
- this.referencedBy = referencedBy;
- }
-
- public Collection<PullRequestReference> getReferenced() {
- return referenced;
- }
-
- public void setReferenced(Collection<PullRequestReference> referenced) {
- this.referenced = referenced;
- }
-
- public Collection<PullRequestComment> getComments() {
- return comments;
- }
-
- public void setComments(Collection<PullRequestComment> comments) {
- this.comments = comments;
- }
-
- public Collection<PullRequestActivity> getActivities() {
- return activities;
- }
-
- public void setActivities(Collection<PullRequestActivity> activities) {
- this.activities = activities;
- }
-
- public Collection<Notification> getNotifications() {
- return notifications;
- }
-
- public void setNotifications(Collection<Notification> notifications) {
- this.notifications = notifications;
- }
-
- public Collection<PullRequestVisit> getVisits() {
- return visits;
- }
-
- public void setVisits(Collection<PullRequestVisit> visits) {
- this.visits = visits;
- }
-
- public Collection<PullRequestWatch> getWatches() {
- return watches;
- }
-
- public void setWatches(Collection<PullRequestWatch> watches) {
- this.watches = watches;
- }
-
- public Status getStatus() {
- if (closeInfo != null) {
- if (closeInfo.getCloseStatus() == CloseInfo.Status.INTEGRATED)
- return Status.INTEGRATED;
- else
- return Status.DISCARDED;
- } else if (getCheckResult() instanceof Pending || getCheckResult() instanceof Blocking)
- return Status.PENDING_APPROVAL;
- else if (getCheckResult() instanceof Failed)
- return Status.PENDING_UPDATE;
- else
- return Status.PENDING_INTEGRATE;
- }
-
- @Nullable
- public CloseInfo getCloseInfo() {
- return closeInfo;
- }
-
- public void setCloseInfo(CloseInfo closeInfo) {
- this.closeInfo = closeInfo;
- }
-
- public boolean isOpen() {
- return closeInfo == null;
- }
-
- public PullRequestUpdate getReferentialUpdate() {
- if (referentialUpdate != null)
- return referentialUpdate;
- else
- return getEffectiveUpdates().get(0);
- }
-
- public void setReferentialUpdate(PullRequestUpdate referentiralUpdate) {
- this.referentialUpdate = referentiralUpdate;
- }
-
- /**
- * Get gate keeper check result.
- *
- * @return
- * check result of this pull request has not been refreshed yet
- */
- public CheckResult getCheckResult() {
- if (checkResult == null)
- checkResult = getTargetDepot().getGateKeeper().checkRequest(this);
- return checkResult;
- }
-
- /**
- * Get last integration preview of this pull request. Note that this method may return an
- * out dated integration preview. Refer to {@link this#getIntegrationPreview()}
- * if you'd like to get an update-to-date integration preview
- *
- * @return
- * integration preview of this pull request, or <tt>null</tt> if integration
- * preview has not been calculated yet.
- */
- @Nullable
- public IntegrationPreview getLastIntegrationPreview() {
- return lastIntegrationPreview;
- }
-
- public void setLastIntegrationPreview(IntegrationPreview lastIntegrationPreview) {
- this.lastIntegrationPreview = lastIntegrationPreview;
- }
-
- /**
- * Get effective integration preview of this pull request.
- *
- * @return
- * update to date integration preview of this pull request, or <tt>null</tt> if
- * the integration preview has not been calculated or out dated. In both cases,
- * it will trigger a re-calculation, and client should call this method later
- * to get the calculated result
- */
- @JsonView(ExternalView.class)
- @Nullable
- public IntegrationPreview getIntegrationPreview() {
- return GitPlex.getInstance(PullRequestManager.class).previewIntegration(this);
- }
-
- /**
- * Get list of sorted updates.
- *
- * @return
- * list of sorted updates ordered by id
- */
- public List<PullRequestUpdate> getSortedUpdates() {
- if (sortedUpdates == null) {
- Preconditions.checkState(updates.size() >= 1);
- sortedUpdates = new ArrayList<PullRequestUpdate>(updates);
- Collections.sort(sortedUpdates);
- }
- return sortedUpdates;
- }
-
- /**
- * Get list of effective updates reversely sorted by id. Update is considered effective if it is
- * not ancestor of target branch head.
- *
- * @return
- * list of effective updates reversely sorted by id
- */
- public List<PullRequestUpdate> getEffectiveUpdates() {
- Preconditions.checkState(isOpen(), "Can only be called while request is open");
- if (effectiveUpdates == null) {
- effectiveUpdates = new ArrayList<PullRequestUpdate>();
-
- for (int i=getSortedUpdates().size()-1; i>=0; i--) {
- PullRequestUpdate update = getSortedUpdates().get(i);
- if (!getTargetDepot().isAncestor(update.getHeadCommitHash(), getTarget().getObjectName()))
- effectiveUpdates.add(update);
- else
- break;
- }
-
- Preconditions.checkState(!effectiveUpdates.isEmpty());
- }
- return effectiveUpdates;
- }
-
- public IntegrationStrategy getIntegrationStrategy() {
- return integrationStrategy;
- }
-
- public void setIntegrationStrategy(IntegrationStrategy integrationStrategy) {
- this.integrationStrategy = integrationStrategy;
- }
-
- @JsonView(ExternalView.class)
- public PullRequestUpdate getLatestUpdate() {
- return getSortedUpdates().get(getSortedUpdates().size()-1);
- }
-
- public Collection<String> findTouchedFiles() {
- Git git = getTargetDepot().git();
- return git.listChangedFiles(getTarget().getObjectName(), getLatestUpdate().getHeadCommitHash(), null);
- }
-
- @JsonView(ExternalView.class)
- public String getBaseRef() {
- Preconditions.checkNotNull(getId());
- return Depot.REFS_GITPLEX + "pulls/" + getId() + "/base";
- }
-
- @JsonView(ExternalView.class)
- public String getIntegrateRef() {
- Preconditions.checkNotNull(getId());
- return Depot.REFS_GITPLEX + "pulls/" + getId() + "/integrate";
- }
-
- /**
- * Delete refs of this pull request, without touching refs of its updates.
- */
- public void deleteRefs() {
- Git git = getTargetDepot().git();
- git.deleteRef(getBaseRef(), null, null);
- git.deleteRef(getIntegrateRef(), null, null);
- }
-
- public <T> T lockAndCall(Callable<T> callable) {
- Preconditions.checkNotNull(getId());
-
- return LockUtils.call("pull request: " + getId(), callable);
- }
-
- /**
- * Invite specified number of users in candidates to review this request.
- * <p>
- *
- * @param candidates
- * a collection of users to invite users from
- * @param count
- * number of users to invite
- */
- public void pickReviewers(Collection<Account> candidates, int count) {
- List<Account> pickList = new ArrayList<Account>(candidates);
-
- /*
- * users already reviewed since base update should be excluded from
- * invitation list as their reviews are still valid
- */
- for (Review review: getReferentialUpdate().listReviewsOnwards())
- pickList.remove(review.getReviewer());
-
- final Map<Account, Date> firstChoices = new HashMap<>();
- final Map<Account, Date> secondChoices = new HashMap<>();
-
- for (ReviewInvitation invitation: getReviewInvitations()) {
- if (invitation.isPreferred())
- firstChoices.put(invitation.getReviewer(), invitation.getDate());
- else
- secondChoices.put(invitation.getReviewer(), invitation.getDate());
- }
-
- // submitter is not preferred
- if (getSubmitter() != null)
- secondChoices.put(getSubmitter(), new Date());
-
- /* Follow below rules to pick reviewers:
- * 1. If user is excluded previously, it will be considered last.
- * 2. If user is already a reviewer, it will be considered first.
- * 3. Otherwise pick user with least reviews.
- */
- pickList.sort((user1, user2) -> {
- if (firstChoices.containsKey(user1)) {
- if (firstChoices.containsKey(user2))
- return user1.getReviewEffort() - user2.getReviewEffort();
- else
- return -1;
- } else if (firstChoices.containsKey(user2)) {
- return 1;
- } else if (secondChoices.containsKey(user1)) {
- if (secondChoices.containsKey(user2))
- return secondChoices.get(user1).compareTo(secondChoices.get(user2));
- else
- return 1;
- } else if (secondChoices.containsKey(user2)) {
- return -1;
- } else {
- return user1.getReviewEffort() - user2.getReviewEffort();
- }
- });
-
- List<Account> picked;
- if (count <= pickList.size())
- picked = pickList.subList(0, count);
- else
- picked = pickList;
-
- for (Account user: picked) {
- boolean found = false;
- for (ReviewInvitation invitation: getReviewInvitations()) {
- if (invitation.getReviewer().equals(user)) {
- invitation.setDate(new Date());
- invitation.setPerferred(true);
- found = true;
- }
- }
- if (!found) {
- ReviewInvitation invitation = new ReviewInvitation();
- invitation.setRequest(this);
- invitation.setReviewer(user);
- getReviewInvitations().add(invitation);
- }
- }
-
- }
-
- public static class CriterionHelper {
- public static Criterion ofOpen() {
- return Restrictions.isNull("closeInfo");
- }
-
- public static Criterion ofClosed() {
- return Restrictions.isNotNull("closeInfo");
- }
-
- public static Criterion ofTarget(DepotAndBranch target) {
- return Restrictions.and(
- Restrictions.eq("targetDepot", target.getDepot()),
- Restrictions.eq("targetBranch", target.getBranch()));
- }
-
- public static Criterion ofTargetDepot(Depot target) {
- return Restrictions.eq("targetDepot", target);
- }
-
- public static Criterion ofSource(DepotAndBranch source) {
- return Restrictions.and(
- Restrictions.eq("sourceDepot", source.getDepot()),
- Restrictions.eq("sourceBranch", source.getBranch()));
- }
-
- public static Criterion ofSourceDepot(Depot source) {
- return Restrictions.eq("sourceDepot", source);
- }
-
- public static Criterion ofSubmitter(Account submitter) {
- return Restrictions.eq("submitter", submitter);
- }
-
- }
-
- public Date getSubmitDate() {
- return submitDate;
- }
-
- public void setSubmitDate(Date submitDate) {
- this.submitDate = submitDate;
- }
-
- public Date getLastEventDate() {
- return lastEventDate;
- }
-
- public void setLastEventDate(Date lastEventDate) {
- this.lastEventDate = lastEventDate;
- }
-
- public Event getLastEvent() {
- return lastEvent;
- }
-
- public void setLastEvent(Event lastEvent) {
- this.lastEvent = lastEvent;
- }
-
- /**
- * Get commits pending integration.
- *
- * @return
- * commits pending integration
- */
- public Set<String> getPendingCommits() {
- if (pendingCommits == null) {
- pendingCommits = new HashSet<>();
- Depot repo = getTargetDepot();
- for (Commit commit: repo.git().log(getTarget().getObjectName(), getLatestUpdate().getHeadCommitHash(), null, 0, 0, false))
- pendingCommits.add(commit.getHash());
- }
- return pendingCommits;
- }
-
- public List<String> getCommentables() {
- List<String> commentables = new ArrayList<>();
- commentables.add(getBaseCommitHash());
- for (PullRequestUpdate update: getSortedUpdates()) {
- for (Commit commit: update.getCommits())
- commentables.add(commit.getHash());
- }
- return commentables;
- }
-
- /**
- * Merged commits represent commits already merged to target branch since base commit.
- *
- * @return
- * commits already merged to target branch since base commit
- */
- public Collection<Commit> getMergedCommits() {
- if (mergedCommits == null) {
- mergedCommits = new HashSet<>();
-
- Depot repo = getTargetDepot();
- for (Commit commit: repo.git().log(getBaseCommitHash(), getTarget().getObjectName(), null, 0, 0, false))
- mergedCommits.add(commit);
- }
- return mergedCommits;
- }
-
- public List<Review> getReviews() {
- if (reviews == null) {
- if (!isNew())
- reviews = GitPlex.getInstance(ReviewManager.class).findBy(this);
- else
- reviews = new ArrayList<>();
- }
- return reviews;
- }
-
- /**
- * This method is here for performance consideration. Often we need to load reviews of
- * different updates in a pull request. And we optimize it to load all reviews at once
- * for all updates in a pull request to reduce SQL queries.
- *
- * @param update
- * @return
- */
- public List<Review> getReviews(PullRequestUpdate update) {
- List<Review> reviews = new ArrayList<>();
- for (Review review: getReviews()) {
- if (review.getUpdate().equals(update))
- reviews.add(review);
- }
- return reviews;
- }
-
- public boolean isReviewEffective(Account user) {
- for (Review review: getReviews()) {
- if (review.getUpdate().equals(getLatestUpdate()) && review.getReviewer().equals(user))
- return true;
- }
- return false;
- }
-
- /**
- * Calculate list of users can be added as reviewers of this pull request.
- *
- * @return
- * list of potential reviewers
- */
- public List<Account> getPotentialReviewers() {
- List<Account> reviewers = new ArrayList<>();
- Set<Account> alreadyInvited = new HashSet<>();
- for (ReviewInvitation invitation: getReviewInvitations()) {
- if (invitation.isPreferred())
- alreadyInvited.add(invitation.getReviewer());
- }
- ObjectPermission readPerm = ObjectPermission.ofDepotRead(getTargetDepot());
- for (Account user: GitPlex.getInstance(Dao.class).allOf(Account.class)) {
- if (user.asSubject().isPermitted(readPerm) && !alreadyInvited.contains(user))
- reviewers.add(user);
- }
- return reviewers;
- }
-
- @Nullable
- public PullRequestWatch getWatch(Account user) {
- for (PullRequestWatch watch: getWatches()) {
- if (watch.getUser().equals(user))
- return watch;
- }
- return null;
- }
-
- @Nullable
- public PullRequestVisit getVisit(Account user) {
- for (PullRequestVisit visit: getVisits()) {
- if (visit.getUser().equals(user))
- return visit;
- }
- return null;
- }
-
- public String getUrl() {
- return GitPlex.getInstance(ConfigManager.class).getSystemSetting().getServerUrl()
- + "/" + getTargetDepot().getFQN() + "/pull_requests/" + getId() + "/overview";
- }
-
- @PrePersist
- public void prePersist() {
- idStr = getId().toString();
- }
-
- public String getIdStr() {
- return idStr;
- }
-
- public String getNoSpaceTitle() {
- return noSpaceTitle;
- }
-
- public long getVersion() {
- return version;
- }
-
-}
+package com.pmease.gitplex.core.entity;
+
+import java.util.ArrayList;
+import java.util.Collection;
+import java.util.Collections;
+import java.util.Date;
+import java.util.HashMap;
+import java.util.HashSet;
+import java.util.List;
+import java.util.Map;
+import java.util.Set;
+import java.util.concurrent.Callable;
+
+import javax.annotation.Nullable;
+import javax.persistence.Column;
+import javax.persistence.Embedded;
+import javax.persistence.Entity;
+import javax.persistence.FetchType;
+import javax.persistence.Index;
+import javax.persistence.JoinColumn;
+import javax.persistence.Lob;
+import javax.persistence.ManyToOne;
+import javax.persistence.OneToMany;
+import javax.persistence.PrePersist;
+import javax.persistence.Table;
+import javax.persistence.Version;
+
+import org.apache.commons.lang3.StringUtils;
+import org.hibernate.annotations.DynamicUpdate;
+import org.hibernate.annotations.OnDelete;
+import org.hibernate.annotations.OnDeleteAction;
+import org.hibernate.annotations.OptimisticLock;
+import org.hibernate.criterion.Criterion;
+import org.hibernate.criterion.Restrictions;
+
+import com.fasterxml.jackson.annotation.JsonView;
+import com.google.common.base.Preconditions;
+import com.pmease.commons.git.Commit;
+import com.pmease.commons.git.Git;
+import com.pmease.commons.git.GitUtils;
+import com.pmease.commons.hibernate.AbstractEntity;
+import com.pmease.commons.hibernate.dao.Dao;
+import com.pmease.commons.jackson.ExternalView;
+import com.pmease.commons.util.LockUtils;
+import com.pmease.gitplex.core.GitPlex;
+import com.pmease.gitplex.core.entity.component.CloseInfo;
+import com.pmease.gitplex.core.entity.component.DepotAndBranch;
+import com.pmease.gitplex.core.entity.component.IntegrationPreview;
+import com.pmease.gitplex.core.gatekeeper.checkresult.Blocking;
+import com.pmease.gitplex.core.gatekeeper.checkresult.CheckResult;
+import com.pmease.gitplex.core.gatekeeper.checkresult.Failed;
+import com.pmease.gitplex.core.gatekeeper.checkresult.Pending;
+import com.pmease.gitplex.core.manager.ConfigManager;
+import com.pmease.gitplex.core.manager.PullRequestManager;
+import com.pmease.gitplex.core.manager.ReviewManager;
+import com.pmease.gitplex.core.security.ObjectPermission;
+
+@Entity
+/*
+ * @DynamicUpdate annotation here along with various @OptimisticLock annotations
+ * on certain fields tell Hibernate not to perform version check on those fields
+ * which can be updated from background thread.
+ */
+@DynamicUpdate
+@Table(indexes={@Index(columnList="title"), @Index(columnList="idStr"), @Index(columnList="noSpaceTitle")})
+public class PullRequest extends AbstractEntity {
+
+ private static final long serialVersionUID = 1L;
+
+ public enum Status {
+ PENDING_APPROVAL("Pending Approval"),
+ PENDING_UPDATE("Pending Update"), PENDING_INTEGRATE("Pending Integration"),
+ INTEGRATED("Integrated"), DISCARDED("Discarded");
+
+ private final String displayName;
+
+ Status(String displayName) {
+ this.displayName = displayName;
+ }
+
+ @Override
+ public String toString() {
+ return displayName;
+ }
+
+ }
+
+ public enum IntegrationStrategy {
+ MERGE_ALWAYS("Merge always",
+ "Always create merge commit when integrate into target branch"),
+ MERGE_IF_NECESSARY("Merge if necessary",
+ "Create merge commit only if target branch can not be fast-forwarded to the pull request"),
+ MERGE_WITH_SQUASH("Merge with squash",
+ "Squash all commits in the pull request and then merge with target branch"),
+ REBASE_SOURCE_ONTO_TARGET("Rebase source onto target",
+ "Rebase source branch onto target branch and then fast-forward target branch to source branch"),
+ REBASE_TARGET_ONTO_SOURCE("Rebase target onto source",
+ "Rebase target branch onto source branch");
+
+ private final String displayName;
+
+ private final String description;
+
+ IntegrationStrategy(String displayName, String description) {
+ this.displayName = displayName;
+ this.description = description;
+ }
+
+ public String getDisplayName() {
+ return displayName;
+ }
+
+ public String getDescription() {
+ return description;
+ }
+
+ @Override
+ public String toString() {
+ return displayName;
+ }
+
+ }
+
+ public enum Event {
+ OPENED("Newly opened"),
+ REVIEWED("New reviews in"),
+ VERIFIED("Build verification is finished for"),
+ UPDATED("New commits in"),
+ COMMENTED("New comments in"),
+ INTEGRATION_STRATEGY_CHANGED("Integration strategy is changed"),
+ INTEGRATED("Integration is done for"),
+ DISCARDED("Discarded"),
+ REOPENED("Reopened"),
+ INTEGRATION_PREVIEW_CALCULATED("Integration preview is calculated"),
+ ASSIGNED("Assigned"),
+ REVIEWER_CHANGED("Reviewer changed"),
+ REVIEW_REMOVED("Review removed"),
+ COMMENT_REPLIED("Comment is replied");
+
+ private final String displayName;
+
+ Event(String displayName) {
+ this.displayName = displayName;
+ }
+
+ public String toString() {
+ return displayName;
+ }
+
+ };
+
+ @Embedded
+ private CloseInfo closeInfo;
+
+ @Column(nullable=false)
+ private String title;
+
+ @Lob
+ @Column(length=65535)
+ private String description;
+
+ @ManyToOne(fetch=FetchType.LAZY)
+ private Account submitter;
+
+ @ManyToOne(fetch=FetchType.LAZY)
+ @JoinColumn(nullable=false)
+ private Depot targetDepot;
+
+ @Column(nullable=false)
+ private String targetBranch;
+
+ @ManyToOne(fetch=FetchType.LAZY)
+ private Depot sourceDepot;
+
+ @Column(nullable=false)
+ private String sourceBranch;
+
+ @Column(nullable=false)
+ private String baseCommitHash;
+
+ @ManyToOne(fetch=FetchType.LAZY)
+ private Account assignee;
+
+ // used for id search in markdown editor
+ @Column(nullable=false)
+ private String idStr;
+
+ // used for title search in markdown editor
+ @Column(nullable=false)
+ private String noSpaceTitle;
+
+ @Version
+ private long version;
+
+ @OptimisticLock(excluded=true)
+ @Embedded
+ private IntegrationPreview lastIntegrationPreview;
+
+ @Column(nullable=false)
+ private Date submitDate = new Date();
+
+ @OptimisticLock(excluded=true)
+ @Column(nullable=false)
+ private Date lastEventDate = new Date();
+
+ @OptimisticLock(excluded=true)
+ @Column(nullable=false)
+ private Event lastEvent = Event.OPENED;
+
+ @Column(nullable=false)
+ private IntegrationStrategy integrationStrategy;
+
+ @OneToMany(mappedBy="request")
+ @OnDelete(action=OnDeleteAction.CASCADE)
+ private Collection<PullRequestUpdate> updates = new ArrayList<>();
+
+ @OneToMany(mappedBy="request")
+ @OnDelete(action=OnDeleteAction.CASCADE)
+ private Collection<ReviewInvitation> reviewInvitations = new ArrayList<>();
+
+ @OneToMany(mappedBy="referenced")
+ @OnDelete(action=OnDeleteAction.CASCADE)
+ private Collection<PullRequestReference> referencedBy = new ArrayList<>();
+
+ @OneToMany(mappedBy="referencedBy")
+ @OnDelete(action=OnDeleteAction.CASCADE)
+ private Collection<PullRequestReference> referenced = new ArrayList<>();
+
+ @OneToMany(mappedBy="request")
+ @OnDelete(action=OnDeleteAction.CASCADE)
+ private Collection<Verification> verifications = new ArrayList<>();
+
+ @OneToMany(mappedBy="request")
+ @OnDelete(action=OnDeleteAction.CASCADE)
+ private Collection<PullRequestComment> comments = new ArrayList<>();
+
+ @OneToMany(mappedBy="request")
+ @OnDelete(action=OnDeleteAction.CASCADE)
+ private Collection<PullRequestActivity> activities = new ArrayList<>();
+
+ @OneToMany(mappedBy="request")
+ @OnDelete(action=OnDeleteAction.CASCADE)
+ private Collection<Notification> notifications = new ArrayList<>();
+
+ @OneToMany(mappedBy="request")
+ @OnDelete(action=OnDeleteAction.CASCADE)
+ private Collection<PullRequestVisit> visits = new ArrayList<>();
+
+ @OneToMany(mappedBy="request")
+ @OnDelete(action=OnDeleteAction.CASCADE)
+ private Collection<PullRequestWatch> watches = new ArrayList<>();
+
+ private transient CheckResult checkResult;
+
+ private transient List<PullRequestUpdate> sortedUpdates;
+
+ private transient List<PullRequestUpdate> effectiveUpdates;
+
+ private transient PullRequestUpdate referentialUpdate;
+
+ private transient Set<String> pendingCommits;
+
+ private transient Collection<Commit> mergedCommits;
+
+ private transient List<Review> reviews;
+
+ /**
+ * Get title of this merge request.
+ *
+ * @return user specified title of this merge request, <tt>null</tt> for
+ * auto-created merge request.
+ */
+ public @Nullable String getTitle() {
+ return title;
+ }
+
+ public void setTitle(String title) {
+ this.title = title;
+ noSpaceTitle = StringUtils.deleteWhitespace(title);
+ }
+
+ public String getDescription() {
+ return description;
+ }
+
+ public void setDescription(String description) {
+ this.description = description;
+ }
+
+ /**
+ * Get the user submitting the pull request.
+ *
+ * @return
+ * the user submitting the pull request, or <tt>null</tt> if unknown
+ */
+ @Nullable
+ public Account getSubmitter() {
+ return submitter;
+ }
+
+ public void setSubmitter(@Nullable Account submitter) {
+ this.submitter = submitter;
+ }
+
+ /**
+ * Get the user responsible for integration of the pull request.
+ *
+ * @return
+ * the user responsible for integration of this pull request, or <tt>null</tt> to have the
+ * system integrate the pull request automatically
+ */
+ @Nullable
+ public Account getAssignee() {
+ return assignee;
+ }
+
+ public void setAssignee(Account assignee) {
+ this.assignee = assignee;
+ }
+
+ public Depot getTargetDepot() {
+ return targetDepot;
+ }
+
+ public DepotAndBranch getTarget() {
+ return new DepotAndBranch(getTargetDepot(), getTargetBranch());
+ }
+
+ public void setTarget(DepotAndBranch target) {
+ setTargetDepot(target.getDepot());
+ setTargetBranch(target.getBranch());
+ }
+
+ public void setSource(DepotAndBranch source) {
+ setSourceDepot(source.getDepot());
+ setSourceBranch(source.getBranch());
+ }
+
+ public void setTargetDepot(Depot targetDepot) {
+ this.targetDepot = targetDepot;
+ }
+
+ public String getTargetBranch() {
+ return targetBranch;
+ }
+
+ public void setTargetBranch(String targetBranch) {
+ this.targetBranch = targetBranch;
+ }
+
+ @Nullable
+ public Depot getSourceDepot() {
+ return sourceDepot;
+ }
+
+ public void setSourceDepot(Depot sourceDepot) {
+ this.sourceDepot = sourceDepot;
+ }
+
+ public String getSourceBranch() {
+ return sourceBranch;
+ }
+
+ public void setSourceBranch(String sourceBranch) {
+ this.sourceBranch = sourceBranch;
+ }
+
+ public DepotAndBranch getSource() {
+ return new DepotAndBranch(getSourceDepot(), getSourceBranch());
+ }
+
+ public String getTargetRef() {
+ return GitUtils.branch2ref(getTargetBranch());
+ }
+
+ public String getSourceRef() {
+ return GitUtils.branch2ref(getSourceBranch());
+ }
+
+ public String getBaseCommitHash() {
+ return baseCommitHash;
+ }
+
+ public void setBaseCommitHash(String baseCommitHash) {
+ this.baseCommitHash = baseCommitHash;
+ }
+
+ public Commit getBaseCommit() {
+ return getTargetDepot().getCommit(getBaseCommitHash());
+ }
+
+ public Git git() {
+ return getTargetDepot().git();
+ }
+ /**
+ * Get unmodifiable collection of updates of this pull request. To add update
+ * to the pull request, call {@link this#addUpdate(PullRequestUpdate)} instead.
+ *
+ * @return
+ * unmodifiable collection of updates
+ */
+ public Collection<PullRequestUpdate> getUpdates() {
+ return Collections.unmodifiableCollection(updates);
+ }
+
+ public void setUpdates(Collection<PullRequestUpdate> updates) {
+ this.updates = updates;
+ sortedUpdates = null;
+ effectiveUpdates = null;
+ }
+
+ public void addUpdate(PullRequestUpdate update) {
+ updates.add(update);
+ sortedUpdates = null;
+ effectiveUpdates = null;
+ }
+
+ public Collection<ReviewInvitation> getReviewInvitations() {
+ return reviewInvitations;
+ }
+
+ public void setReviewInvitations(Collection<ReviewInvitation> reviewInvitations) {
+ this.reviewInvitations = reviewInvitations;
+ }
+
+ public Collection<Verification> getVerifications() {
+ return verifications;
+ }
+
+ public void setVerifications(Collection<Verification> verifications) {
+ this.verifications = verifications;
+ }
+
+ public Collection<PullRequestReference> getReferencedBy() {
+ return referencedBy;
+ }
+
+ public void setReferencedBy(Collection<PullRequestReference> referencedBy) {
+ this.referencedBy = referencedBy;
+ }
+
+ public Collection<PullRequestReference> getReferenced() {
+ return referenced;
+ }
+
+ public void setReferenced(Collection<PullRequestReference> referenced) {
+ this.referenced = referenced;
+ }
+
+ public Collection<PullRequestComment> getComments() {
+ return comments;
+ }
+
+ public void setComments(Collection<PullRequestComment> comments) {
+ this.comments = comments;
+ }
+
+ public Collection<PullRequestActivity> getActivities() {
+ return activities;
+ }
+
+ public void setActivities(Collection<PullRequestActivity> activities) {
+ this.activities = activities;
+ }
+
+ public Collection<Notification> getNotifications() {
+ return notifications;
+ }
+
+ public void setNotifications(Collection<Notification> notifications) {
+ this.notifications = notifications;
+ }
+
+ public Collection<PullRequestVisit> getVisits() {
+ return visits;
+ }
+
+ public void setVisits(Collection<PullRequestVisit> visits) {
+ this.visits = visits;
+ }
+
+ public Collection<PullRequestWatch> getWatches() {
+ return watches;
+ }
+
+ public void setWatches(Collection<PullRequestWatch> watches) {
+ this.watches = watches;
+ }
+
+ public Status getStatus() {
+ if (closeInfo != null) {
+ if (closeInfo.getCloseStatus() == CloseInfo.Status.INTEGRATED)
+ return Status.INTEGRATED;
+ else
+ return Status.DISCARDED;
+ } else if (getCheckResult() instanceof Pending || getCheckResult() instanceof Blocking)
+ return Status.PENDING_APPROVAL;
+ else if (getCheckResult() instanceof Failed)
+ return Status.PENDING_UPDATE;
+ else
+ return Status.PENDING_INTEGRATE;
+ }
+
+ @Nullable
+ public CloseInfo getCloseInfo() {
+ return closeInfo;
+ }
+
+ public void setCloseInfo(CloseInfo closeInfo) {
+ this.closeInfo = closeInfo;
+ }
+
+ public boolean isOpen() {
+ return closeInfo == null;
+ }
+
+ public PullRequestUpdate getReferentialUpdate() {
+ if (referentialUpdate != null)
+ return referentialUpdate;
+ else
+ return getEffectiveUpdates().get(0);
+ }
+
+ public void setReferentialUpdate(PullRequestUpdate referentiralUpdate) {
+ this.referentialUpdate = referentiralUpdate;
+ }
+
+ /**
+ * Get gate keeper check result.
+ *
+ * @return
+ * check result of this pull request has not been refreshed yet
+ */
+ public CheckResult getCheckResult() {
+ if (checkResult == null)
+ checkResult = getTargetDepot().getGateKeeper().checkRequest(this);
+ return checkResult;
+ }
+
+ /**
+ * Get last integration preview of this pull request. Note that this method may return an
+ * out dated integration preview. Refer to {@link this#getIntegrationPreview()}
+ * if you'd like to get an update-to-date integration preview
+ *
+ * @return
+ * integration preview of this pull request, or <tt>null</tt> if integration
+ * preview has not been calculated yet.
+ */
+ @Nullable
+ public IntegrationPreview getLastIntegrationPreview() {
+ return lastIntegrationPreview;
+ }
+
+ public void setLastIntegrationPreview(IntegrationPreview lastIntegrationPreview) {
+ this.lastIntegrationPreview = lastIntegrationPreview;
+ }
+
+ /**
+ * Get effective integration preview of this pull request.
+ *
+ * @return
+ * update to date integration preview of this pull request, or <tt>null</tt> if
+ * the integration preview has not been calculated or out dated. In both cases,
+ * it will trigger a re-calculation, and client should call this method later
+ * to get the calculated result
+ */
+ @JsonView(ExternalView.class)
+ @Nullable
+ public IntegrationPreview getIntegrationPreview() {
+ return GitPlex.getInstance(PullRequestManager.class).previewIntegration(this);
+ }
+
+ /**
+ * Get list of sorted updates.
+ *
+ * @return
+ * list of sorted updates ordered by id
+ */
+ public List<PullRequestUpdate> getSortedUpdates() {
+ if (sortedUpdates == null) {
+ Preconditions.checkState(updates.size() >= 1);
+ sortedUpdates = new ArrayList<PullRequestUpdate>(updates);
+ Collections.sort(sortedUpdates);
+ }
+ return sortedUpdates;
+ }
+
+ /**
+ * Get list of effective updates reversely sorted by id. Update is considered effective if it is
+ * not ancestor of target branch head.
+ *
+ * @return
+ * list of effective updates reversely sorted by id
+ */
+ public List<PullRequestUpdate> getEffectiveUpdates() {
+ Preconditions.checkState(isOpen(), "Can only be called while request is open");
+ if (effectiveUpdates == null) {
+ effectiveUpdates = new ArrayList<PullRequestUpdate>();
+
+ for (int i=getSortedUpdates().size()-1; i>=0; i--) {
+ PullRequestUpdate update = getSortedUpdates().get(i);
+ if (!getTargetDepot().isAncestor(update.getHeadCommitHash(), getTarget().getObjectName()))
+ effectiveUpdates.add(update);
+ else
+ break;
+ }
+
+ Preconditions.checkState(!effectiveUpdates.isEmpty());
+ }
+ return effectiveUpdates;
+ }
+
+ public IntegrationStrategy getIntegrationStrategy() {
+ return integrationStrategy;
+ }
+
+ public void setIntegrationStrategy(IntegrationStrategy integrationStrategy) {
+ this.integrationStrategy = integrationStrategy;
+ }
+
+ @JsonView(ExternalView.class)
+ public PullRequestUpdate getLatestUpdate() {
+ return getSortedUpdates().get(getSortedUpdates().size()-1);
+ }
+
+ public Collection<String> findTouchedFiles() {
+ Git git = getTargetDepot().git();
+ return git.listChangedFiles(getTarget().getObjectName(), getLatestUpdate().getHeadCommitHash(), null);
+ }
+
+ @JsonView(ExternalView.class)
+ public String getBaseRef() {
+ Preconditions.checkNotNull(getId());
+ return Depot.REFS_GITPLEX + "pulls/" + getId() + "/base";
+ }
+
+ @JsonView(ExternalView.class)
+ public String getIntegrateRef() {
+ Preconditions.checkNotNull(getId());
+ return Depot.REFS_GITPLEX + "pulls/" + getId() + "/integrate";
+ }
+
+ /**
+ * Delete refs of this pull request, without touching refs of its updates.
+ */
+ public void deleteRefs() {
+ Git git = getTargetDepot().git();
+ git.deleteRef(getBaseRef(), null, null);
+ git.deleteRef(getIntegrateRef(), null, null);
+ }
+
+ public <T> T lockAndCall(Callable<T> callable) {
+ Preconditions.checkNotNull(getId());
+
+ return LockUtils.call("pull request: " + getId(), callable);
+ }
+
+ /**
+ * Invite specified number of users in candidates to review this request.
+ * <p>
+ *
+ * @param candidates
+ * a collection of users to invite users from
+ * @param count
+ * number of users to invite
+ */
+ public void pickReviewers(Collection<Account> candidates, int count) {
+ List<Account> pickList = new ArrayList<Account>(candidates);
+
+ /*
+ * users already reviewed since base update should be excluded from
+ * invitation list as their reviews are still valid
+ */
+ for (Review review: getReferentialUpdate().listReviewsOnwards())
+ pickList.remove(review.getReviewer());
+
+ final Map<Account, Date> firstChoices = new HashMap<>();
+ final Map<Account, Date> secondChoices = new HashMap<>();
+
+ for (ReviewInvitation invitation: getReviewInvitations()) {
+ if (invitation.isPreferred())
+ firstChoices.put(invitation.getReviewer(), invitation.getDate());
+ else
+ secondChoices.put(invitation.getReviewer(), invitation.getDate());
+ }
+
+ // submitter is not preferred
+ if (getSubmitter() != null)
+ secondChoices.put(getSubmitter(), new Date());
+
+ /* Follow below rules to pick reviewers:
+ * 1. If user is excluded previously, it will be considered last.
+ * 2. If user is already a reviewer, it will be considered first.
+ * 3. Otherwise pick user with least reviews.
+ */
+ pickList.sort((user1, user2) -> {
+ if (firstChoices.containsKey(user1)) {
+ if (firstChoices.containsKey(user2))
+ return user1.getReviewEffort() - user2.getReviewEffort();
+ else
+ return -1;
+ } else if (firstChoices.containsKey(user2)) {
+ return 1;
+ } else if (secondChoices.containsKey(user1)) {
+ if (secondChoices.containsKey(user2))
+ return secondChoices.get(user1).compareTo(secondChoices.get(user2));
+ else
+ return 1;
+ } else if (secondChoices.containsKey(user2)) {
+ return -1;
+ } else {
+ return user1.getReviewEffort() - user2.getReviewEffort();
+ }
+ });
+
+ List<Account> picked;
+ if (count <= pickList.size())
+ picked = pickList.subList(0, count);
+ else
+ picked = pickList;
+
+ for (Account user: picked) {
+ boolean found = false;
+ for (ReviewInvitation invitation: getReviewInvitations()) {
+ if (invitation.getReviewer().equals(user)) {
+ invitation.setDate(new Date());
+ invitation.setPerferred(true);
+ found = true;
+ }
+ }
+ if (!found) {
+ ReviewInvitation invitation = new ReviewInvitation();
+ invitation.setRequest(this);
+ invitation.setReviewer(user);
+ getReviewInvitations().add(invitation);
+ }
+ }
+
+ }
+
+ public static class CriterionHelper {
+ public static Criterion ofOpen() {
+ return Restrictions.isNull("closeInfo");
+ }
+
+ public static Criterion ofClosed() {
+ return Restrictions.isNotNull("closeInfo");
+ }
+
+ public static Criterion ofTarget(DepotAndBranch target) {
+ return Restrictions.and(
+ Restrictions.eq("targetDepot", target.getDepot()),
+ Restrictions.eq("targetBranch", target.getBranch()));
+ }
+
+ public static Criterion ofTargetDepot(Depot target) {
+ return Restrictions.eq("targetDepot", target);
+ }
+
+ public static Criterion ofSource(DepotAndBranch source) {
+ return Restrictions.and(
+ Restrictions.eq("sourceDepot", source.getDepot()),
+ Restrictions.eq("sourceBranch", source.getBranch()));
+ }
+
+ public static Criterion ofSourceDepot(Depot source) {
+ return Restrictions.eq("sourceDepot", source);
+ }
+
+ public static Criterion ofSubmitter(Account submitter) {
+ return Restrictions.eq("submitter", submitter);
+ }
+
+ }
+
+ public Date getSubmitDate() {
+ return submitDate;
+ }
+
+ public void setSubmitDate(Date submitDate) {
+ this.submitDate = submitDate;
+ }
+
+ public Date getLastEventDate() {
+ return lastEventDate;
+ }
+
+ public void setLastEventDate(Date lastEventDate) {
+ this.lastEventDate = lastEventDate;
+ }
+
+ public Event getLastEvent() {
+ return lastEvent;
+ }
+
+ public void setLastEvent(Event lastEvent) {
+ this.lastEvent = lastEvent;
+ }
+
+ /**
+ * Get commits pending integration.
+ *
+ * @return
+ * commits pending integration
+ */
+ public Set<String> getPendingCommits() {
+ if (pendingCommits == null) {
+ pendingCommits = new HashSet<>();
+ Depot repo = getTargetDepot();
+ for (Commit commit: repo.git().log(getTarget().getObjectName(), getLatestUpdate().getHeadCommitHash(), null, 0, 0, false))
+ pendingCommits.add(commit.getHash());
+ }
+ return pendingCommits;
+ }
+
+ public List<String> getCommentables() {
+ List<String> commentables = new ArrayList<>();
+ commentables.add(getBaseCommitHash());
+ for (PullRequestUpdate update: getSortedUpdates()) {
+ for (Commit commit: update.getCommits())
+ commentables.add(commit.getHash());
+ }
+ return commentables;
+ }
+
+ /**
+ * Merged commits represent commits already merged to target branch since base commit.
+ *
+ * @return
+ * commits already merged to target branch since base commit
+ */
+ public Collection<Commit> getMergedCommits() {
+ if (mergedCommits == null) {
+ mergedCommits = new HashSet<>();
+
+ Depot repo = getTargetDepot();
+ for (Commit commit: repo.git().log(getBaseCommitHash(), getTarget().getObjectName(), null, 0, 0, false))
+ mergedCommits.add(commit);
+ }
+ return mergedCommits;
+ }
+
+ public List<Review> getReviews() {
+ if (reviews == null) {
+ if (!isNew())
+ reviews = GitPlex.getInstance(ReviewManager.class).findBy(this);
+ else
+ reviews = new ArrayList<>();
+ }
+ return reviews;
+ }
+
+ /**
+ * This method is here for performance consideration. Often we need to load reviews of
+ * different updates in a pull request. And we optimize it to load all reviews at once
+ * for all updates in a pull request to reduce SQL queries.
+ *
+ * @param update
+ * @return
+ */
+ public List<Review> getReviews(PullRequestUpdate update) {
+ List<Review> reviews = new ArrayList<>();
+ for (Review review: getReviews()) {
+ if (review.getUpdate().equals(update))
+ reviews.add(review);
+ }
+ return reviews;
+ }
+
+ public boolean isReviewEffective(Account user) {
+ for (Review review: getReviews()) {
+ if (review.getUpdate().equals(getLatestUpdate()) && review.getReviewer().equals(user))
+ return true;
+ }
+ return false;
+ }
+
+ /**
+ * Calculate list of users can be added as reviewers of this pull request.
+ *
+ * @return
+ * list of potential reviewers
+ */
+ public List<Account> getPotentialReviewers() {
+ List<Account> reviewers = new ArrayList<>();
+ Set<Account> alreadyInvited = new HashSet<>();
+ for (ReviewInvitation invitation: getReviewInvitations()) {
+ if (invitation.isPreferred())
+ alreadyInvited.add(invitation.getReviewer());
+ }
+ ObjectPermission readPerm = ObjectPermission.ofDepotRead(getTargetDepot());
+ for (Account user: GitPlex.getInstance(Dao.class).allOf(Account.class)) {
+ if (user.asSubject().isPermitted(readPerm) && !alreadyInvited.contains(user))
+ reviewers.add(user);
+ }
+ return reviewers;
+ }
+
+ @Nullable
+ public PullRequestWatch getWatch(Account user) {
+ for (PullRequestWatch watch: getWatches()) {
+ if (watch.getUser().equals(user))
+ return watch;
+ }
+ return null;
+ }
+
+ @Nullable
+ public PullRequestVisit getVisit(Account user) {
+ for (PullRequestVisit visit: getVisits()) {
+ if (visit.getUser().equals(user))
+ return visit;
+ }
+ return null;
+ }
+
+ public String getUrl() {
+ return GitPlex.getInstance(ConfigManager.class).getSystemSetting().getServerUrl()
+ + "/" + getTargetDepot().getFQN() + "/pull_requests/" + getId() + "/overview";
+ }
+
+ @PrePersist
+ public void prePersist() {
+ idStr = getId().toString();
+ }
+
+ public String getIdStr() {
+ return idStr;
+ }
+
+ public String getNoSpaceTitle() {
+ return noSpaceTitle;
+ }
+
+ public long getVersion() {
+ return version;
+ }
+
+}
diff --git a/gitplex.core/src/main/java/com/pmease/gitplex/core/entity/component/CompareContext.java b/gitplex.core/src/main/java/com/pmease/gitplex/core/entity/component/CompareContext.java
new file mode 100644
index 0000000000..28bec7b1e7
--- /dev/null
+++ b/gitplex.core/src/main/java/com/pmease/gitplex/core/entity/component/CompareContext.java
@@ -0,0 +1,60 @@
+package com.pmease.gitplex.core.entity.component;
+
+import java.io.Serializable;
+
+import javax.persistence.Embeddable;
+
+import org.hibernate.annotations.OptimisticLock;
+
+import com.pmease.commons.lang.diff.WhitespaceOption;
+
+@Embeddable
+public class CompareContext implements Serializable {
+
+ private static final long serialVersionUID = 1L;
+
+ @OptimisticLock(excluded=true)
+ private String compareCommit;
+
+ @OptimisticLock(excluded=true)
+ private Boolean leftSide;
+
+ @OptimisticLock(excluded=true)
+ private String pathFilter;
+
+ @OptimisticLock(excluded=true)
+ private WhitespaceOption whitespaceOption;
+
+ public String getCompareCommit() {
+ return compareCommit;
+ }
+
+ public void setCompareCommit(String compareCommit) {
+ this.compareCommit = compareCommit;
+ }
+
+ public boolean isLeftSide() {
+ return leftSide;
+ }
+
+ public void setLeftSide(boolean leftSide) {
+ this.leftSide = leftSide;
+ }
+
+ public String getPathFilter() {
+ return pathFilter;
+ }
+
+ public void setPathFilter(String pathFilter) {
+ this.pathFilter = pathFilter;
+ }
+
+ public WhitespaceOption getWhitespaceOption() {
+ return whitespaceOption;
+ }
+
+ public void setWhitespaceOption(WhitespaceOption whitespaceOption) {
+ this.whitespaceOption = whitespaceOption;
+ }
+
+}
diff --git a/gitplex.core/src/main/java/com/pmease/gitplex/core/entity/component/Mark.java b/gitplex.core/src/main/java/com/pmease/gitplex/core/entity/component/Mark.java
index b3b54d3b6e..613b762fb2 100644
--- a/gitplex.core/src/main/java/com/pmease/gitplex/core/entity/component/Mark.java
+++ b/gitplex.core/src/main/java/com/pmease/gitplex/core/entity/component/Mark.java
@@ -103,7 +103,7 @@ public class Mark implements Serializable {
return null;
}
- public String toJSON() {
+ public String toJson() {
try {
return GitPlex.getInstance(ObjectMapper.class).writeValueAsString(this);
} catch (JsonProcessingException e) {
diff --git a/gitplex.product/src/test/java/gitplex/product/Test.java b/gitplex.product/src/test/java/gitplex/product/Test.java
index 654bc704e3..a92117ff35 100644
--- a/gitplex.product/src/test/java/gitplex/product/Test.java
+++ b/gitplex.product/src/test/java/gitplex/product/Test.java
@@ -1,14 +1,9 @@
package gitplex.product;
-import com.pmease.commons.util.Range;
-import com.pmease.commons.util.match.WildcardUtils;
-
public class Test {
@org.junit.Test
public void test() {
- Range range = WildcardUtils.rangeOfMatch("*hello*r", "hello world");
- System.out.println(range);
}
}
\ No newline at end of file
diff --git a/gitplex.web/src/main/java/com/pmease/gitplex/web/component/depotfile/blobview/BlobViewContext.java b/gitplex.web/src/main/java/com/pmease/gitplex/web/component/depotfile/blobview/BlobViewContext.java
index c256dd2c2a..3d5a46d386 100644
--- a/gitplex.web/src/main/java/com/pmease/gitplex/web/component/depotfile/blobview/BlobViewContext.java
+++ b/gitplex.web/src/main/java/com/pmease/gitplex/web/component/depotfile/blobview/BlobViewContext.java
@@ -33,8 +33,6 @@ public interface BlobViewContext extends Serializable {
@Nullable
Mark getMark();
- void onMark(AjaxRequestTarget target, ObjectId commitId, @Nullable Mark mark);
-
String getMarkUrl(ObjectId commitId, Mark mark);
Mode getMode();
@@ -53,8 +51,6 @@ public interface BlobViewContext extends Serializable {
void onEdit(AjaxRequestTarget target, @Nullable String viewState);
- void onOpenComment(AjaxRequestTarget target, @Nullable CodeComment comment);
-
@Nullable
CodeComment getComment();
diff --git a/gitplex.web/src/main/java/com/pmease/gitplex/web/component/depotfile/blobview/source/SourceViewPanel.java b/gitplex.web/src/main/java/com/pmease/gitplex/web/component/depotfile/blobview/source/SourceViewPanel.java
index 0260b3e24b..4d4c335fc1 100644
--- a/gitplex.web/src/main/java/com/pmease/gitplex/web/component/depotfile/blobview/source/SourceViewPanel.java
+++ b/gitplex.web/src/main/java/com/pmease/gitplex/web/component/depotfile/blobview/source/SourceViewPanel.java
@@ -43,7 +43,6 @@ import org.apache.wicket.request.mapper.parameter.PageParameters;
import org.apache.wicket.request.resource.CssResourceReference;
import org.apache.wicket.request.resource.JavaScriptResourceReference;
import org.eclipse.jgit.lib.FileMode;
-import org.eclipse.jgit.lib.ObjectId;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.unbescape.html.HtmlEscape;
@@ -232,7 +231,7 @@ public class SourceViewPanel extends BlobViewPanel {
public void mark(AjaxRequestTarget target, Mark mark, boolean scroll) {
String script = String.format("gitplex.sourceview.mark(%s, %s);",
- mark.toJSON(), scroll);
+ mark.toJson(), scroll);
target.appendJavaScript(script);
}
@@ -254,8 +253,6 @@ public class SourceViewPanel extends BlobViewPanel {
@Override
public void onClick(AjaxRequestTarget target) {
mark(target, context.getComment().getMark(), true);
- context.onMark(target, ObjectId.fromString(context.getComment().getCommit()),
- context.getComment().getMark());
target.appendJavaScript(String.format("$('#%s').blur();", getMarkupId()));
}
@@ -277,7 +274,6 @@ public class SourceViewPanel extends BlobViewPanel {
@Override
public void onClick(AjaxRequestTarget target) {
hideComment(target);
- context.onOpenComment(target, null);
}
});
@@ -317,13 +313,12 @@ public class SourceViewPanel extends BlobViewPanel {
case "openSelectionPopup":
Mark mark = getMark(params, "param1", "param2", "param3", "param4");
String script = String.format("gitplex.sourceview.openSelectionPopup(%s, '%s', %s);",
- mark.toJSON(), context.getMarkUrl(context.getCommit(), mark),
+ mark.toJson(), context.getMarkUrl(context.getCommit(), mark),
SecurityUtils.getAccount()!=null);
target.appendJavaScript(script);
break;
case "mark":
mark = getMark(params, "param1", "param2", "param3", "param4");
- context.onMark(target, context.getCommit(), mark);
break;
case "addComment":
Preconditions.checkNotNull(SecurityUtils.getAccount());
@@ -411,7 +406,6 @@ public class SourceViewPanel extends BlobViewPanel {
comment.getMark().getBeginLine(),
getJsonOfComment(comment));
target.appendJavaScript(script);
- context.onOpenComment(target, comment);
}
});
@@ -446,7 +440,6 @@ public class SourceViewPanel extends BlobViewPanel {
script = String.format("gitplex.sourceview.onOpenComment(%s);",
getJsonOfComment(commentModel.getObject()));
target.appendJavaScript(script);
- context.onOpenComment(target, commentModel.getObject());
break;
}
}
@@ -621,7 +614,6 @@ public class SourceViewPanel extends BlobViewPanel {
String script = String.format("gitplex.sourceview.onCommentDeleted(%d, %d);",
comment.getMark().getBeginLine(), comment.getId());
target.appendJavaScript(script);
- context.onOpenComment(target, null);
}
private void hideComment(AjaxRequestTarget target) {
@@ -722,7 +714,7 @@ public class SourceViewPanel extends BlobViewPanel {
+ "%s, %s, %s, %s, %s);",
JavaScriptEscape.escapeJavaScript(blob.getText().getContent()),
JavaScriptEscape.escapeJavaScript(context.getBlobIdent().path),
- context.getMark()!=null?context.getMark().toJSON():"undefined",
+ context.getMark()!=null?context.getMark().toJson():"undefined",
symbolTooltip.getMarkupId(),
context.getBlobIdent().revision,
jsonOfBlameInfos,
diff --git a/gitplex.web/src/main/java/com/pmease/gitplex/web/component/depotfile/blobview/source/source-view.js b/gitplex.web/src/main/java/com/pmease/gitplex/web/component/depotfile/blobview/source/source-view.js
index 02fcb7a787..2768b21b9e 100644
--- a/gitplex.web/src/main/java/com/pmease/gitplex/web/component/depotfile/blobview/source/source-view.js
+++ b/gitplex.web/src/main/java/com/pmease/gitplex/web/component/depotfile/blobview/source/source-view.js
@@ -140,8 +140,10 @@ gitplex.sourceview = {
}
});
cm.setSize($code.width(), $code.height());
- if (mark)
+ if (mark) {
+ $sourceView.data("mark", mark);
pmease.commons.codemirror.mark(cm, mark, true);
+ }
if (initState)
pmease.commons.codemirror.initState(cm, viewState);
cm.on("scroll", function() {
@@ -207,19 +209,8 @@ gitplex.sourceview = {
});
},
restoreMark: function() {
- var cm = $(".source-view>.code>.CodeMirror")[0].CodeMirror;
- var uri = new URI(window.location.href);
- var markStr = uri.search(true).mark;
- if (markStr) {
- var splitted = markStr.split("-");
- var fromInfo = splitted[0].split(".");
- var toInfo = splitted[1].split(".");
- var mark = {
- beginLine: parseInt(fromInfo[0])-1,
- beginChar: parseInt(fromInfo[1]),
- endLine: parseInt(toInfo[0])-1,
- endChar: parseInt(toInfo[1])
- }
+ var mark = $(".source-view").data("mark");
+ if (mark) {
pmease.commons.codemirror.mark(cm, mark, false);
} else {
pmease.commons.codemirror.clearMark(cm);
@@ -295,15 +286,7 @@ gitplex.sourceview = {
var ch = (mark.beginChar + mark.endChar)/2;
var position = cm.charCoords({line:mark.beginLine, ch:ch});
var permanentLinkCallback = function($permanentLink) {
- $permanentLink.off("click");
$permanentLink.attr("href", markUrl);
- $permanentLink.click(function(e) {
- e.preventDefault();
- $("#selection-popup").hide();
- pmease.commons.codemirror.clearSelection(cm);
- pmease.commons.codemirror.mark(cm, mark, false);
- sourceCllback("mark", mark.beginLine, mark.beginChar, mark.endLine, mark.endChar);
- });
};
var commentLinkCallback = function($commentLink) {
$commentLink.off("click");
@@ -316,6 +299,7 @@ gitplex.sourceview = {
$("#selection-popup").hide();
pmease.commons.codemirror.clearSelection(cm);
pmease.commons.codemirror.mark(cm, mark, false);
+ $sourceView.data("mark", mark);
sourceCllback("addComment", mark.beginLine, mark.beginChar, mark.endLine, mark.endChar);
});
} else {
diff --git a/gitplex.web/src/main/java/com/pmease/gitplex/web/component/depotfile/fileedit/FileEditPanel.java b/gitplex.web/src/main/java/com/pmease/gitplex/web/component/depotfile/fileedit/FileEditPanel.java
index 30dfe16517..9372d8aae2 100644
--- a/gitplex.web/src/main/java/com/pmease/gitplex/web/component/depotfile/fileedit/FileEditPanel.java
+++ b/gitplex.web/src/main/java/com/pmease/gitplex/web/component/depotfile/fileedit/FileEditPanel.java
@@ -221,7 +221,7 @@ public abstract class FileEditPanel extends Panel {
getMarkupId(), getNewPathParam(), StringEscapeUtils.escapeEcmaScript(content),
previewBehavior.getCallbackFunction(CallbackParameter.explicit("content")),
saveBehavior.getCallbackFunction(CallbackParameter.explicit("content")),
- mark!=null?mark.toJSON():"undefined",
+ mark!=null?mark.toJson():"undefined",
viewState!=null?"JSON.parse('"+viewState+"')":"undefined");
response.render(OnDomReadyHeaderItem.forScript(script));
}
@@ -250,7 +250,7 @@ public abstract class FileEditPanel extends Panel {
public void mark(AjaxRequestTarget target, Mark mark) {
String script = String.format("gitplex.fileedit.mark('%s', %s);",
- getMarkupId(), mark.toJSON());
+ getMarkupId(), mark.toJson());
target.appendJavaScript(script);
}
diff --git a/gitplex.web/src/main/java/com/pmease/gitplex/web/component/diff/blob/text/text-diff.js b/gitplex.web/src/main/java/com/pmease/gitplex/web/component/diff/blob/text/text-diff.js
index 5bc74cc225..88292cc737 100644
--- a/gitplex.web/src/main/java/com/pmease/gitplex/web/component/diff/blob/text/text-diff.js
+++ b/gitplex.web/src/main/java/com/pmease/gitplex/web/component/diff/blob/text/text-diff.js
@@ -436,7 +436,6 @@ gitplex.textdiff = {
return;
}
var permanentCallback = function($permanentLink) {
- $permanentLink.off("click");
var uri = URI(window.location.href);
var markFile = $container.data("markfile");
uri.removeSearch("jump-file");
@@ -444,19 +443,6 @@ gitplex.textdiff = {
uri.removeSearch("mark-pos").addSearch("mark-pos", markPos);
$permanentLink.attr("href", uri.toString());
$permanentLink.html("<i class='fa fa-link'></i> Permanent link of this selection");
- $permanentLink.click(function(e) {
- e.preventDefault();
- window.getSelection().removeAllRanges();
- $container.data("callback")("storeUrl", uri.toString());
- // continue to operate DOM in a timer to give browser a chance to
- // clear selections
- setTimeout(function() {
- gitplex.textdiff.clearMarks();
- $("#selection-popup").hide();
- pmease.commons.history.pushState(uri.toString());
- gitplex.textdiff.mark(markFile, markPos);
- }, 100);
- });
};
var commentCallback = function($commentLink) {
$commentLink.removeAttr("href");
diff --git a/gitplex.web/src/main/java/com/pmease/gitplex/web/component/diff/revision/DiffMark.java b/gitplex.web/src/main/java/com/pmease/gitplex/web/component/diff/revision/DiffMark.java
new file mode 100644
index 0000000000..f6e2c5c043
--- /dev/null
+++ b/gitplex.web/src/main/java/com/pmease/gitplex/web/component/diff/revision/DiffMark.java
@@ -0,0 +1,95 @@
+package com.pmease.gitplex.web.component.diff.revision;
+
+import org.apache.commons.lang3.StringUtils;
+import org.apache.commons.lang3.builder.EqualsBuilder;
+import org.apache.commons.lang3.builder.HashCodeBuilder;
+
+import com.fasterxml.jackson.core.JsonProcessingException;
+import com.fasterxml.jackson.databind.ObjectMapper;
+import com.pmease.gitplex.core.GitPlex;
+import com.pmease.gitplex.core.entity.component.Mark;
+
+public class DiffMark extends Mark {
+
+ private static final long serialVersionUID = 1L;
+
+ private final String path;
+
+ private final boolean leftSide;
+
+ public DiffMark(String path, boolean leftSide, int beginLine, int beginChar,
+ int endLine, int endChar) {
+ super(beginLine, beginChar, endLine, endChar);
+ this.path = path;
+ this.leftSide = leftSide;
+ }
+
+ public DiffMark(String path, boolean leftSide, Mark mark) {
+ super(mark);
+ this.path = path;
+ this.leftSide = leftSide;
+ }
+
+ public String getPath() {
+ return path;
+ }
+
+ public boolean isLeftSide() {
+ return leftSide;
+ }
+
+ public DiffMark(String str) {
+ super(str.substring(getMarkIndex(str)+1));
+ String tempStr = str.substring(0, getMarkIndex(str));
+ path = StringUtils.substringBeforeLast(tempStr, "-");
+ leftSide = Boolean.valueOf(StringUtils.substringAfterLast(tempStr, "-"));
+ }
+
+ private static int getMarkIndex(String str) {
+ return str.substring(0, str.lastIndexOf('-')).lastIndexOf('-');
+ }
+
+ @Override
+ public String toString() {
+ return path + "-" + leftSide + "-" + super.toString();
+ }
+
+ @Override
+ public boolean equals(Object other) {
+ if (!(other instanceof DiffMark))
+ return false;
+ if (this == other)
+ return true;
+ DiffMark otherMark = (DiffMark) other;
+ return new EqualsBuilder()
+ .append(path, otherMark.path)
+ .append(leftSide, otherMark.leftSide)
+ .append(beginLine, otherMark.beginLine)
+ .append(beginChar, otherMark.beginChar)
+ .append(endLine, otherMark.endLine)
+ .append(endChar, otherMark.endChar)
+ .isEquals();
+ }
+
+ @Override
+ public int hashCode() {
+ return new HashCodeBuilder(17, 37)
+ .append(path)
+ .append(leftSide)
+ .append(beginLine)
+ .append(beginChar)
+ .append(endLine)
+ .append(endChar)
+ .toHashCode();
+ }
+
+ @Override
+ public String toJson() {
+ try {
+ return GitPlex.getInstance(ObjectMapper.class).writeValueAsString(this);
+ } catch (JsonProcessingException e) {
+ throw new RuntimeException(e);
+ }
+ }
+
+}
diff --git a/gitplex.web/src/main/java/com/pmease/gitplex/web/component/diff/revision/RevisionDiffPanel.java b/gitplex.web/src/main/java/com/pmease/gitplex/web/component/diff/revision/RevisionDiffPanel.java
index 8868b693c7..2e116460ae 100644
--- a/gitplex.web/src/main/java/com/pmease/gitplex/web/component/diff/revision/RevisionDiffPanel.java
+++ b/gitplex.web/src/main/java/com/pmease/gitplex/web/component/diff/revision/RevisionDiffPanel.java
@@ -65,7 +65,6 @@ import com.pmease.commons.wicket.behavior.inputassist.InputAssistBehavior;
import com.pmease.commons.wicket.component.menu.MenuItem;
import com.pmease.commons.wicket.component.menu.MenuLink;
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.web.Constants;
@@ -100,13 +99,13 @@ public abstract class RevisionDiffPanel extends Panel {
private Long commentId;
+ private DiffMark mark;
+
private IModel<List<DiffEntry>> diffEntriesModel = new LoadableDetachableModel<List<DiffEntry>>() {
@Override
protected List<DiffEntry> load() {
- String oldCommitHash = depotModel.getObject().getObjectId(oldRev).name();
- String newCommitHash = depotModel.getObject().getObjectId(newRev).name();
- return depotModel.getObject().getDiffs(oldCommitHash, newCommitHash);
+ return depotModel.getObject().getDiffs(oldRev, newRev);
}
};
@@ -258,7 +257,8 @@ public abstract class RevisionDiffPanel extends Panel {
public RevisionDiffPanel(String id, IModel<Depot> depotModel, IModel<PullRequest> requestModel,
String oldRev, String newRev, @Nullable String pathFilter,
- WhitespaceOption whitespaceOption, @Nullable Long commentId) {
+ WhitespaceOption whitespaceOption, @Nullable Long commentId,
+ @Nullable DiffMark mark) {
super(id);
this.depotModel = depotModel;
@@ -268,6 +268,7 @@ public abstract class RevisionDiffPanel extends Panel {
this.pathFilter = pathFilter;
this.whitespaceOption = whitespaceOption;
this.commentId = commentId;
+ this.mark = mark;
WebRequest request = (WebRequest) RequestCycle.get().getRequest();
Cookie cookie = request.getCookie(COOKIE_VIEW_MODE);
@@ -502,7 +503,6 @@ public abstract class RevisionDiffPanel extends Panel {
@Override
public void onClick(AjaxRequestTarget target) {
hideComment(target);
- onOpenComment(target, null);
}
});
@@ -610,6 +610,22 @@ public abstract class RevisionDiffPanel extends Panel {
setOutputMarkupId(true);
}
+ protected String getPathFilter() {
+ return pathFilter;
+ }
+
+ protected WhitespaceOption getWhitespaceOption() {
+ return whitespaceOption;
+ }
+
+ protected Long getCommentId() {
+ return commentId;
+ }
+
+ protected DiffMark getMark() {
+ return mark;
+ }
+
private void hideComment(AjaxRequestTarget target) {
commentContainer.replace(new WebMarkupContainer("body"));
commentContainer.setVisible(false);
@@ -644,8 +660,6 @@ public abstract class RevisionDiffPanel extends Panel {
protected abstract void onWhitespaceOptionChange(AjaxRequestTarget target,
WhitespaceOption whitespaceOption);
- protected abstract void onOpenComment(AjaxRequestTarget target, @Nullable CodeComment comment);
-
private static class ChangesAndCount {
private final List<BlobChange> changes;
diff --git a/gitplex.web/src/main/java/com/pmease/gitplex/web/component/pullrequest/requestassignee/AssigneeChoice.java b/gitplex.web/src/main/java/com/pmease/gitplex/web/component/pullrequest/requestassignee/AssigneeChoice.java
index 5f4ca35caa..736aac13ed 100644
--- a/gitplex.web/src/main/java/com/pmease/gitplex/web/component/pullrequest/requestassignee/AssigneeChoice.java
+++ b/gitplex.web/src/main/java/com/pmease/gitplex/web/component/pullrequest/requestassignee/AssigneeChoice.java
@@ -1,60 +1,60 @@
-package com.pmease.gitplex.web.component.pullrequest.requestassignee;
-
-import org.apache.wicket.markup.head.IHeaderResponse;
-import org.apache.wicket.markup.head.JavaScriptHeaderItem;
-import org.apache.wicket.model.IModel;
-
-import com.pmease.commons.wicket.component.select2.Select2Choice;
-import com.pmease.gitplex.core.entity.Depot;
-import com.pmease.gitplex.web.component.accountchoice.AccountChoiceResourceReference;
-import com.pmease.gitplex.core.entity.Account;
-
-@SuppressWarnings("serial")
-public class AssigneeChoice extends Select2Choice<Assignee> {
-
- public AssigneeChoice(String id, IModel<Depot> depotModel, final IModel<Account> assigneeModel) {
- super(id, new IModel<Assignee>() {
-
- @Override
- public void detach() {
- }
-
- @Override
- public Assignee getObject() {
- Account user = assigneeModel.getObject();
- if (user != null)
- return new Assignee(user, null);
- else
- return null;
- }
-
- @Override
- public void setObject(Assignee object) {
- if (object != null)
- assigneeModel.setObject(object.getUser());
- else
- assigneeModel.setObject(null);
- }
-
- }, new AssigneeProvider(depotModel));
- }
-
- @Override
- protected void onInitialize() {
- super.onInitialize();
-
- // getSettings().setMinimumInputLength(1);
- getSettings().setPlaceholder("Type to find an assignee");
- getSettings().setFormatResult("gitplex.userChoiceFormatter.formatResult");
- getSettings().setFormatSelection("gitplex.userChoiceFormatter.formatSelection");
- getSettings().setEscapeMarkup("gitplex.userChoiceFormatter.escapeMarkup");
- }
-
- @Override
- public void renderHead(IHeaderResponse response) {
- super.renderHead(response);
-
- response.render(JavaScriptHeaderItem.forReference(AccountChoiceResourceReference.INSTANCE));
- }
-
-}
+package com.pmease.gitplex.web.component.pullrequest.requestassignee;
+
+import org.apache.wicket.markup.head.IHeaderResponse;
+import org.apache.wicket.markup.head.JavaScriptHeaderItem;
+import org.apache.wicket.model.IModel;
+
+import com.pmease.commons.wicket.component.select2.Select2Choice;
+import com.pmease.gitplex.core.entity.Depot;
+import com.pmease.gitplex.web.component.accountchoice.AccountChoiceResourceReference;
+import com.pmease.gitplex.core.entity.Account;
+
+@SuppressWarnings("serial")
+public class AssigneeChoice extends Select2Choice<Assignee> {
+
+ public AssigneeChoice(String id, IModel<Depot> depotModel, final IModel<Account> assigneeModel) {
+ super(id, new IModel<Assignee>() {
+
+ @Override
+ public void detach() {
+ }
+
+ @Override
+ public Assignee getObject() {
+ Account user = assigneeModel.getObject();
+ if (user != null)
+ return new Assignee(user, null);
+ else
+ return null;
+ }
+
+ @Override
+ public void setObject(Assignee object) {
+ if (object != null)
+ assigneeModel.setObject(object.getUser());
+ else
+ assigneeModel.setObject(null);
+ }
+
+ }, new AssigneeProvider(depotModel));
+ }
+
+ @Override
+ protected void onInitialize() {
+ super.onInitialize();
+
+ // getSettings().setMinimumInputLength(1);
+ getSettings().setPlaceholder("Type to find an assignee");
+ getSettings().setFormatResult("gitplex.accountChoiceFormatter.formatResult");
+ getSettings().setFormatSelection("gitplex.accountChoiceFormatter.formatSelection");
+ getSettings().setEscapeMarkup("gitplex.accountChoiceFormatter.escapeMarkup");
+ }
+
+ @Override
+ public void renderHead(IHeaderResponse response) {
+ super.renderHead(response);
+
+ response.render(JavaScriptHeaderItem.forReference(AccountChoiceResourceReference.INSTANCE));
+ }
+
+}
diff --git a/gitplex.web/src/main/java/com/pmease/gitplex/web/page/depot/commit/CommitDetailPage.java b/gitplex.web/src/main/java/com/pmease/gitplex/web/page/depot/commit/CommitDetailPage.java
index b106ad9c03..d7e0a21b8c 100644
--- a/gitplex.web/src/main/java/com/pmease/gitplex/web/page/depot/commit/CommitDetailPage.java
+++ b/gitplex.web/src/main/java/com/pmease/gitplex/web/page/depot/commit/CommitDetailPage.java
@@ -42,7 +42,6 @@ import com.pmease.commons.git.GitUtils;
import com.pmease.commons.lang.diff.WhitespaceOption;
import com.pmease.commons.wicket.assets.oneline.OnelineResourceReference;
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.manager.AuxiliaryManager;
@@ -50,6 +49,7 @@ import com.pmease.gitplex.web.component.avatar.ContributorAvatars;
import com.pmease.gitplex.web.component.contributorpanel.ContributorPanel;
import com.pmease.gitplex.web.component.createbranch.CreateBranchLink;
import com.pmease.gitplex.web.component.createtag.CreateTagLink;
+import com.pmease.gitplex.web.component.diff.revision.DiffMark;
import com.pmease.gitplex.web.component.diff.revision.RevisionDiffPanel;
import com.pmease.gitplex.web.component.hashandcode.HashAndCodePanel;
import com.pmease.gitplex.web.page.depot.DepotPage;
@@ -72,6 +72,8 @@ public class CommitDetailPage extends DepotPage {
private static final String PARAM_COMMENT = "comment";
+ private static final String PARAM_MARK = "mark";
+
protected String revision;
private HistoryState state;
@@ -298,7 +300,8 @@ public class CommitDetailPage extends DepotPage {
private void newRevisionDiff(@Nullable AjaxRequestTarget target) {
revisionDiff = new RevisionDiffPanel("revisionDiff", depotModel,
Model.of((PullRequest)null), getCompareWith(),
- getCommit().name(), state.pathFilter, state.whitespaceOption, state.commentId) {
+ getCommit().name(), state.pathFilter, state.whitespaceOption,
+ state.commentId, state.mark) {
@Override
protected void onPathFilterChange(AjaxRequestTarget target, String pathFilter) {
@@ -313,12 +316,6 @@ public class CommitDetailPage extends DepotPage {
pushState(target);
}
- @Override
- protected void onOpenComment(AjaxRequestTarget target, CodeComment comment) {
- state.commentId = CodeComment.idOf(comment);
- pushState(target);
- }
-
};
revisionDiff.setOutputMarkupId(true);
if (target != null) {
@@ -395,6 +392,8 @@ public class CommitDetailPage extends DepotPage {
public String pathFilter;
+ public DiffMark mark;
+
public HistoryState() {
}
@@ -403,6 +402,9 @@ public class CommitDetailPage extends DepotPage {
whitespaceOption = WhitespaceOption.of(params.get(PARAM_WHITESPACE_OPTION).toString());
pathFilter = params.get(PARAM_PATH_FILTER).toString();
commentId = params.get(PARAM_COMMENT).toOptionalLong();
+ String markStr = params.get(PARAM_MARK).toString();
+ if (markStr != null)
+ mark = new DiffMark(markStr);
}
}
diff --git a/gitplex.web/src/main/java/com/pmease/gitplex/web/page/depot/compare/RevisionComparePage.java b/gitplex.web/src/main/java/com/pmease/gitplex/web/page/depot/compare/RevisionComparePage.java
index 98f2eea2c4..2eabb7a0f9 100644
--- a/gitplex.web/src/main/java/com/pmease/gitplex/web/page/depot/compare/RevisionComparePage.java
+++ b/gitplex.web/src/main/java/com/pmease/gitplex/web/page/depot/compare/RevisionComparePage.java
@@ -32,13 +32,13 @@ import com.pmease.commons.wicket.component.tabbable.AjaxActionTab;
import com.pmease.commons.wicket.component.tabbable.Tab;
import com.pmease.commons.wicket.component.tabbable.Tabbable;
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.component.DepotAndBranch;
import com.pmease.gitplex.core.entity.component.DepotAndRevision;
import com.pmease.gitplex.core.manager.PullRequestManager;
import com.pmease.gitplex.web.component.commitlist.CommitListPanel;
+import com.pmease.gitplex.web.component.diff.revision.DiffMark;
import com.pmease.gitplex.web.component.diff.revision.RevisionDiffPanel;
import com.pmease.gitplex.web.component.revisionpicker.AffinalRevisionPicker;
import com.pmease.gitplex.web.page.depot.DepotPage;
@@ -131,14 +131,14 @@ public class RevisionComparePage extends DepotPage {
Depot leftDepot = state.leftSide.getDepot();
Depot rightDepot = state.rightSide.getDepot();
if (!leftDepot.equals(rightDepot)) {
- Git sandbox = new Git(FileUtils.createTempDir());
+ Git tempGit = new Git(FileUtils.createTempDir());
try {
- sandbox.clone(leftDepot.git(), false, true, true, state.leftSide.getRevision());
- sandbox.reset(null, null);
- sandbox.fetch(rightDepot.git(), state.rightSide.getRevision());
- return sandbox.calcMergeBase(state.leftSide.getCommit().name(), state.rightSide.getCommit().name());
+ tempGit.clone(leftDepot.git(), false, true, true, state.leftSide.getRevision());
+ tempGit.reset(null, null);
+ tempGit.fetch(rightDepot.git(), state.rightSide.getRevision());
+ return tempGit.calcMergeBase(state.leftSide.getCommit().name(), state.rightSide.getCommit().name());
} finally {
- FileUtils.deleteDir(sandbox.depotDir());
+ FileUtils.deleteDir(tempGit.depotDir());
}
} else {
return leftDepot.getMergeBase(state.leftSide.getRevision(), state.rightSide.getRevision()).name();
@@ -152,7 +152,11 @@ public class RevisionComparePage extends DepotPage {
@Override
protected List<Commit> load() {
Depot rightDepot = state.rightSide.getDepot();
- return rightDepot.git().log(mergeBaseModel.getObject(), state.rightSide.getRevision(), null, 0, 0, false);
+
+ // for right side, we use resolved commit name instead of revision
+ // to make sure that revision is resolved consistently
+ return rightDepot.git().log(mergeBaseModel.getObject(),
+ state.rightSide.getCommit().name(), null, 0, 0, false);
}
};
@@ -177,18 +181,7 @@ public class RevisionComparePage extends DepotPage {
}
});
- add(new AffinalRevisionPicker("rightSide", state.rightSide.getDepotId(), state.rightSide.getRevision()) {
-
- @Override
- protected void onSelect(AjaxRequestTarget target, Depot depot, String revision) {
- HistoryState state = new HistoryState(RevisionComparePage.this.state);
- state.rightSide = new DepotAndRevision(depot, revision);
-
- PageParameters params = paramsOf(getDepot(), state);
- setResponsePage(RevisionComparePage.class, params);
- }
-
- });
+ newRightSideRevisionPicker(null);
add(new Link<Void>("swap") {
@@ -349,6 +342,28 @@ public class RevisionComparePage extends DepotPage {
add(new BackToTop("backToTop"));
}
+ private void newRightSideRevisionPicker(@Nullable AjaxRequestTarget target) {
+ AffinalRevisionPicker revisionPicker = new AffinalRevisionPicker("rightSide",
+ state.rightSide.getDepotId(), state.rightSide.getRevision()) {
+
+ @Override
+ protected void onSelect(AjaxRequestTarget target, Depot depot, String revision) {
+ HistoryState state = new HistoryState(RevisionComparePage.this.state);
+ state.rightSide = new DepotAndRevision(depot, revision);
+
+ PageParameters params = paramsOf(getDepot(), state);
+ setResponsePage(RevisionComparePage.class, params);
+ }
+
+ };
+ if (target != null) {
+ replace(revisionPicker);
+ target.add(revisionPicker);
+ } else {
+ add(revisionPicker);
+ }
+ }
+
private boolean hasChanges() {
return !mergeBaseModel.getObject().equals(state.rightSide.getCommit().name());
}
@@ -376,7 +391,13 @@ public class RevisionComparePage extends DepotPage {
tabPanel = new RevisionDiffPanel(TAB_PANEL_ID, depotModel,
new Model<PullRequest>(null), mergeBaseModel.getObject(),
state.rightSide.getRevision(), state.pathFilter,
- state.whitespaceOption, state.commentId) {
+ state.whitespaceOption, state.commentId, state.mark) {
+
+ @Override
+ protected void onConfigure() {
+ super.onConfigure();
+ setVisible(hasChanges());
+ }
@Override
protected void onPathFilterChange(AjaxRequestTarget target, String pathFilter) {
@@ -391,18 +412,6 @@ public class RevisionComparePage extends DepotPage {
pushState(target);
}
- @Override
- protected void onConfigure() {
- super.onConfigure();
- setVisible(hasChanges());
- }
-
- @Override
- protected void onOpenComment(AjaxRequestTarget target, CodeComment comment) {
- state.commentId = CodeComment.idOf(comment);
- pushState(target);
- }
-
};
commitsTab.setSelected(false);
filesTab.setSelected(true);
@@ -460,17 +469,6 @@ public class RevisionComparePage extends DepotPage {
private static final long serialVersionUID = 1L;
- public HistoryState() {
- }
-
- public HistoryState(HistoryState copy) {
- leftSide = copy.leftSide;
- rightSide = copy.rightSide;
- whitespaceOption = copy.whitespaceOption;
- pathFilter = copy.pathFilter;
- commentId = copy.commentId;
- }
-
public DepotAndRevision leftSide;
public DepotAndRevision rightSide;
@@ -482,6 +480,21 @@ public class RevisionComparePage extends DepotPage {
@Nullable
public Long commentId;
+
+ @Nullable
+ public DiffMark mark;
+
+ public HistoryState() {
+ }
+
+ public HistoryState(HistoryState state) {
+ leftSide = state.leftSide;
+ rightSide = state.rightSide;
+ whitespaceOption = state.whitespaceOption;
+ pathFilter = state.pathFilter;
+ commentId = state.commentId;
+ mark = state.mark;
+ }
}
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 20eb8dfbcd..6a572e9179 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
@@ -833,16 +833,6 @@ public class DepotFilePage extends DepotPage implements BlobViewContext {
return mark;
}
- @Override
- public void onMark(AjaxRequestTarget target, ObjectId commitId, Mark mark) {
- this.mark = mark;
- if (!blobIdent.revision.equals(resolvedRevision.name())) {
- blobIdent.revision = resolvedRevision.name();
- newRevisionPicker(target);
- }
- pushState(target);
- }
-
@Override
public String getMarkUrl(ObjectId commitId, Mark mark) {
HistoryState state = getState();
@@ -927,21 +917,6 @@ public class DepotFilePage extends DepotPage implements BlobViewContext {
resizeWindow(target);
}
- @Override
- public void onOpenComment(AjaxRequestTarget target, CodeComment comment) {
- if (comment != null) {
- commentId = comment.getId();
- mark = comment.getMark();
- } else {
- commentId = null;
- }
- if (!blobIdent.revision.equals(resolvedRevision.name())) {
- blobIdent.revision = resolvedRevision.name();
- newRevisionPicker(target);
- }
- pushState(target);
- }
-
private void resolveRevision() {
/*
* a hack to reset resolved revision to null to disable getObjectIdCache()
diff --git a/gitplex.web/src/main/java/com/pmease/gitplex/web/page/depot/pullrequest/newrequest/NewRequestPage.java b/gitplex.web/src/main/java/com/pmease/gitplex/web/page/depot/pullrequest/newrequest/NewRequestPage.java
index 97e0062c33..ba9097ab49 100644
--- a/gitplex.web/src/main/java/com/pmease/gitplex/web/page/depot/pullrequest/newrequest/NewRequestPage.java
+++ b/gitplex.web/src/main/java/com/pmease/gitplex/web/page/depot/pullrequest/newrequest/NewRequestPage.java
@@ -31,6 +31,7 @@ import org.apache.wicket.model.Model;
import org.apache.wicket.model.PropertyModel;
import org.apache.wicket.request.mapper.parameter.PageParameters;
import org.apache.wicket.request.resource.CssResourceReference;
+import org.eclipse.jgit.lib.ObjectId;
import com.google.common.base.Preconditions;
import com.pmease.commons.git.Commit;
@@ -46,7 +47,6 @@ import com.pmease.commons.wicket.component.tabbable.Tabbable;
import com.pmease.commons.wicket.websocket.WebSocketRenderBehavior.PageId;
import com.pmease.gitplex.core.GitPlex;
import com.pmease.gitplex.core.entity.Account;
-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.PullRequest.IntegrationStrategy;
@@ -59,8 +59,8 @@ import com.pmease.gitplex.core.manager.PullRequestManager;
import com.pmease.gitplex.core.security.ObjectPermission;
import com.pmease.gitplex.web.component.BranchLink;
import com.pmease.gitplex.web.component.branchpicker.AffinalBranchPicker;
-import com.pmease.gitplex.web.component.comment.DepotAttachmentSupport;
import com.pmease.gitplex.web.component.comment.CommentInput;
+import com.pmease.gitplex.web.component.comment.DepotAttachmentSupport;
import com.pmease.gitplex.web.component.commitlist.CommitListPanel;
import com.pmease.gitplex.web.component.diff.revision.RevisionDiffPanel;
import com.pmease.gitplex.web.component.pullrequest.requestassignee.AssigneeChoice;
@@ -162,16 +162,16 @@ public class NewRequestPage extends PullRequestPage {
pullRequest.setCloseInfo(closeInfo);
}
} else {
- Git sandbox = new Git(FileUtils.createTempDir());
- pullRequest.setSandbox(sandbox);
- sandbox.clone(target.getDepot().git(), false, true, true, pullRequest.getTarget().getBranch());
- sandbox.reset(null, null);
-
- sandbox.fetch(source.getDepot().git(), source.getBranch());
-
- pullRequest.setBaseCommitHash(pullRequest.git().calcMergeBase(target.getObjectName(), source.getObjectName()));
-
- if (sandbox.isAncestor(source.getObjectName(), target.getObjectName())) {
+ Git tempGit = new Git(FileUtils.createTempDir());
+ try {
+ tempGit.clone(target.getDepot().git(), false, true, true, pullRequest.getTarget().getBranch());
+ tempGit.reset(null, null);
+ tempGit.fetch(source.getDepot().git(), source.getBranch());
+ pullRequest.setBaseCommitHash(tempGit.calcMergeBase(target.getObjectName(), source.getObjectName()));
+ } finally {
+ FileUtils.deleteDir(tempGit.depotDir());
+ }
+ if (pullRequest.getBaseCommitHash().equals(source.getObjectName())) {
CloseInfo closeInfo = new CloseInfo();
closeInfo.setCloseDate(new Date());
closeInfo.setCloseStatus(CloseInfo.Status.INTEGRATED);
@@ -180,12 +180,12 @@ public class NewRequestPage extends PullRequestPage {
}
requestModel = Model.of(pullRequest);
} else {
- final Long requestId = pullRequest.getId();
+ Long requestId = pullRequest.getId();
requestModel = new LoadableDetachableModel<PullRequest>() {
@Override
protected PullRequest load() {
- return GitPlex.getInstance(Dao.class).load(PullRequest.class, requestId);
+ return GitPlex.getInstance(PullRequestManager.class).load(requestId);
}
};
@@ -197,7 +197,7 @@ public class NewRequestPage extends PullRequestPage {
@Override
protected List<Commit> load() {
PullRequest request = getPullRequest();
- List<Commit> commits = request.git().log(request.getBaseCommitHash(),
+ List<Commit> commits = source.getDepot().git().log(request.getBaseCommitHash(),
request.getLatestUpdate().getHeadCommitHash(), null, 0, 0, false);
Collections.reverse(commits);
return commits;
@@ -309,11 +309,28 @@ public class NewRequestPage extends PullRequestPage {
private RevisionDiffPanel newRevDiffPanel() {
PullRequest request = getPullRequest();
- String oldRev = request.getBaseCommitHash();
- String newRev = request.getLatestUpdate().getHeadCommitHash();
- RevisionDiffPanel diffPanel = new RevisionDiffPanel("revisionDiff", depotModel,
- new Model<PullRequest>(null), oldRev, newRev, null, WhitespaceOption.DEFAULT, null) {
+ IModel<Depot> depotModel = new LoadableDetachableModel<Depot>() {
+
+ @Override
+ protected Depot load() {
+ Depot depot = source.getDepot();
+ depot.cacheObjectId(source.getRevision(),
+ ObjectId.fromString(getPullRequest().getLatestUpdate().getHeadCommitHash()));
+ return depot;
+ }
+
+ };
+
+ /*
+ * we are passing source revision here instead of head commit hash of latest update
+ * as we want to preserve the branch name in case they are useful at some point
+ * later. Also it is guaranteed to be resolved to the same commit has as we've cached
+ * it above when loading the depot
+ */
+ RevisionDiffPanel diffPanel = new RevisionDiffPanel(TAB_PANEL_ID, depotModel,
+ new Model<PullRequest>(null), request.getBaseCommitHash(),
+ source.getRevision(), null, WhitespaceOption.DEFAULT, null, null) {
@Override
protected void onPathFilterChange(AjaxRequestTarget target, String pathFilter) {
@@ -324,10 +341,6 @@ public class NewRequestPage extends PullRequestPage {
WhitespaceOption whitespaceOption) {
}
- @Override
- protected void onOpenComment(AjaxRequestTarget target, CodeComment comment) {
- }
-
};
diffPanel.setOutputMarkupId(true);
return diffPanel;
@@ -512,7 +525,7 @@ public class NewRequestPage extends PullRequestPage {
WebMarkupContainer assigneeContainer = new WebMarkupContainer("assignee");
form.add(assigneeContainer);
IModel<Account> assigneeModel = new PropertyModel<>(getPullRequest(), "assignee");
- final AssigneeChoice assigneeChoice = new AssigneeChoice("assignee", depotModel, assigneeModel);
+ AssigneeChoice assigneeChoice = new AssigneeChoice("assignee", depotModel, assigneeModel);
assigneeChoice.setRequired(true);
assigneeContainer.add(assigneeChoice);
@@ -527,7 +540,7 @@ public class NewRequestPage extends PullRequestPage {
}));
- final WebMarkupContainer reviewersContainer = new WebMarkupContainer("reviewers") {
+ WebMarkupContainer reviewersContainer = new WebMarkupContainer("reviewers") {
@Override
protected void onBeforeRender() {
@@ -591,12 +604,6 @@ public class NewRequestPage extends PullRequestPage {
@Override
protected void onDetach() {
commitsModel.detach();
-
- if (getPullRequest() != null && getPullRequest().getSandbox() != null) {
- FileUtils.deleteDir(getPullRequest().getSandbox().depotDir());
- getPullRequest().setSandbox(null);
- }
-
requestModel.detach();
super.onDetach();
diff --git a/gitplex.web/src/main/java/com/pmease/gitplex/web/page/depot/pullrequest/requestdetail/compare/HistoryState.java b/gitplex.web/src/main/java/com/pmease/gitplex/web/page/depot/pullrequest/requestdetail/compare/HistoryState.java
index 2ba8b17d89..73b9ec9b02 100644
--- a/gitplex.web/src/main/java/com/pmease/gitplex/web/page/depot/pullrequest/requestdetail/compare/HistoryState.java
+++ b/gitplex.web/src/main/java/com/pmease/gitplex/web/page/depot/pullrequest/requestdetail/compare/HistoryState.java
@@ -3,6 +3,7 @@ package com.pmease.gitplex.web.page.depot.pullrequest.requestdetail.compare;
import java.io.Serializable;
import com.pmease.commons.lang.diff.WhitespaceOption;
+import com.pmease.gitplex.web.component.diff.revision.DiffMark;
public class HistoryState implements Serializable {
@@ -18,4 +19,6 @@ public class HistoryState implements Serializable {
public Long commentId;
+ public DiffMark mark;
+
}
diff --git a/gitplex.web/src/main/java/com/pmease/gitplex/web/page/depot/pullrequest/requestdetail/compare/RequestComparePage.java b/gitplex.web/src/main/java/com/pmease/gitplex/web/page/depot/pullrequest/requestdetail/compare/RequestComparePage.java
index 8a8363fd95..38692f059f 100644
--- a/gitplex.web/src/main/java/com/pmease/gitplex/web/page/depot/pullrequest/requestdetail/compare/RequestComparePage.java
+++ b/gitplex.web/src/main/java/com/pmease/gitplex/web/page/depot/pullrequest/requestdetail/compare/RequestComparePage.java
@@ -44,11 +44,11 @@ import com.pmease.commons.wicket.component.floating.AlignPlacement;
import com.pmease.commons.wicket.component.floating.FloatingPanel;
import com.pmease.commons.wicket.component.menu.MenuItem;
import com.pmease.commons.wicket.component.menu.MenuLink;
-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.component.IntegrationPreview;
+import com.pmease.gitplex.web.component.diff.revision.DiffMark;
import com.pmease.gitplex.web.component.diff.revision.RevisionDiffPanel;
import com.pmease.gitplex.web.page.depot.pullrequest.requestdetail.RequestDetailPage;
import com.pmease.gitplex.web.page.depot.pullrequest.requestlist.RequestListPage;
@@ -67,6 +67,8 @@ public class RequestComparePage extends RequestDetailPage {
private static final String PARAM_COMMENT = "comment";
+ private static final String PARAM_MARK = "mark";
+
public static final String REV_BASE = "base";
public static final String REV_UPDATE_PREFIX = "update";
@@ -95,6 +97,8 @@ public class RequestComparePage extends RequestDetailPage {
private Long commentId;
+ private DiffMark mark;
+
private WebMarkupContainer compareHead;
private Component revisionDiff;
@@ -152,6 +156,9 @@ public class RequestComparePage extends RequestDetailPage {
state.pathFilter = params.get(PARAM_PATH_FILTER).toString();
state.whitespaceOption = WhitespaceOption.of(params.get(PARAM_WHITESPACE_OPTION).toString());
state.commentId = params.get(PARAM_COMMENT).toOptionalLong();
+ String markStr = params.get(PARAM_MARK).toString();
+ if (markStr != null)
+ state.mark = new DiffMark(markStr);
initFromState(state);
}
@@ -162,6 +169,7 @@ public class RequestComparePage extends RequestDetailPage {
whitespaceOption = state.whitespaceOption;
pathFilter = state.pathFilter;
commentId = state.commentId;
+ mark = state.mark;
}
private String getRevision(String commitHash) {
@@ -486,6 +494,8 @@ public class RequestComparePage extends RequestDetailPage {
params.set(PARAM_PATH_FILTER, state.pathFilter);
if (state.commentId != null)
params.set(PARAM_COMMENT, state.commentId);
+ if (state.mark != null)
+ params.set(PARAM_MARK, state.mark);
return params;
}
@@ -644,7 +654,7 @@ public class RequestComparePage extends RequestDetailPage {
private void newCompareResult(@Nullable IPartialPageRequestHandler partialPageRequestHandler) {
revisionDiff = new RevisionDiffPanel("revisionDiff", depotModel,
requestModel, oldCommitHash, newCommitHash, pathFilter,
- whitespaceOption, commentId) {
+ whitespaceOption, commentId, mark) {
@Override
protected void onPathFilterChange(AjaxRequestTarget target, String pathFilter) {
@@ -659,11 +669,6 @@ public class RequestComparePage extends RequestDetailPage {
pushState(target);
}
- @Override
- protected void onOpenComment(AjaxRequestTarget target, CodeComment comment) {
- commentId = state.commentId = CodeComment.idOf(comment);
- }
-
};
revisionDiff.setOutputMarkupId(true);
if (partialPageRequestHandler != null) {
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 0d9854548d..b47194918b 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,16 +1,2 @@
<wicket:extend>
- <div class="content" style="width: 200px; border: 1px solid red;">
- hello world
- </div>
- <script type="text/javascript">
- $(".content").resizable({
- autoHide: false,
- minWidth: 200,
- resize: function(e, ui) {
- },
- stop: function(e, ui) {
- $(window).resize();
- }
- });
- </script>
</wicket:extend>
\ No newline at end of file