Skip to content

The Unified and Autonomous Development Platform

midwork

robin shine4136390382d9
diff --git a/commons.hibernate/src/main/java/com/pmease/commons/hibernate/PrefixedNamingStrategy.java b/commons.hibernate/src/main/java/com/pmease/commons/hibernate/PrefixedNamingStrategy.java
index f7d6877210..bd5ef0a1dc 100644
--- a/commons.hibernate/src/main/java/com/pmease/commons/hibernate/PrefixedNamingStrategy.java
+++ b/commons.hibernate/src/main/java/com/pmease/commons/hibernate/PrefixedNamingStrategy.java
@@ -24,17 +24,17 @@ public class PrefixedNamingStrategy extends PhysicalNamingStrategyStandardImpl {
@Override
public Identifier toPhysicalTableName(Identifier name, JdbcEnvironment context) {
- return super.toPhysicalSequenceName(name, context);
+ return new Identifier(prefix+name.getText(), name.isQuoted());
}
@Override
public Identifier toPhysicalSequenceName(Identifier name, JdbcEnvironment context) {
- return super.toPhysicalSequenceName(name, context);
+ return new Identifier(prefix+name.getText(), name.isQuoted());
}
@Override
public Identifier toPhysicalColumnName(Identifier name, JdbcEnvironment context) {
- return super.toPhysicalColumnName(name, context);
+ return new Identifier(prefix+name.getText(), name.isQuoted());
}
}
diff --git a/gitplex.core/src/main/java/com/pmease/gitplex/core/CoreModule.java b/gitplex.core/src/main/java/com/pmease/gitplex/core/CoreModule.java
index c2ffaa7b6a..3805607eb7 100644
--- a/gitplex.core/src/main/java/com/pmease/gitplex/core/CoreModule.java
+++ b/gitplex.core/src/main/java/com/pmease/gitplex/core/CoreModule.java
@@ -83,7 +83,7 @@ public class CoreModule extends AbstractPluginModule {
protected void configure() {
super.configure();
- bind(PhysicalNamingStrategy.class).toInstance(new PrefixedNamingStrategy("G"));
+ bind(PhysicalNamingStrategy.class).toInstance(new PrefixedNamingStrategy("g_"));
contribute(ModelProvider.class, new ModelProvider() {
diff --git a/gitplex.core/src/main/java/com/pmease/gitplex/core/model/Authorization.java b/gitplex.core/src/main/java/com/pmease/gitplex/core/model/Authorization.java
index 4056cd3917..c5f2d0f292 100644
--- a/gitplex.core/src/main/java/com/pmease/gitplex/core/model/Authorization.java
+++ b/gitplex.core/src/main/java/com/pmease/gitplex/core/model/Authorization.java
@@ -12,6 +12,9 @@ import com.pmease.gitplex.core.permission.operation.DepotOperation;
@SuppressWarnings("serial")
@Entity
+@Table(uniqueConstraints={
+ @UniqueConstraint(columnNames={"g_team_id", "g_depot_id"})
+})
public class Authorization extends AbstractEntity {
@ManyToOne(fetch=FetchType.LAZY)
diff --git a/gitplex.core/src/main/java/com/pmease/gitplex/core/model/BranchWatch.java b/gitplex.core/src/main/java/com/pmease/gitplex/core/model/BranchWatch.java
index b17f330639..bd1bc5f048 100644
--- a/gitplex.core/src/main/java/com/pmease/gitplex/core/model/BranchWatch.java
+++ b/gitplex.core/src/main/java/com/pmease/gitplex/core/model/BranchWatch.java
@@ -12,6 +12,9 @@ import com.pmease.commons.hibernate.AbstractEntity;
@SuppressWarnings("serial")
@Entity
+@Table(uniqueConstraints={
+ @UniqueConstraint(columnNames={"branch", "g_user_id"})
+})
public class BranchWatch extends AbstractEntity {
@ManyToOne(fetch=FetchType.LAZY)
diff --git a/gitplex.core/src/main/java/com/pmease/gitplex/core/model/CloseInfo.java b/gitplex.core/src/main/java/com/pmease/gitplex/core/model/CloseInfo.java
index ec60da6864..f62a81a16b 100644
--- a/gitplex.core/src/main/java/com/pmease/gitplex/core/model/CloseInfo.java
+++ b/gitplex.core/src/main/java/com/pmease/gitplex/core/model/CloseInfo.java
@@ -1,53 +1,53 @@
-package com.pmease.gitplex.core.model;
-
-import java.io.Serializable;
-import java.util.Date;
-
-import javax.persistence.Embeddable;
-import javax.persistence.FetchType;
-import javax.persistence.ManyToOne;
-
-import org.hibernate.annotations.OptimisticLock;
-
-@Embeddable
-public class CloseInfo implements Serializable {
-
- private static final long serialVersionUID = 1L;
-
- public enum Status {INTEGRATED, DISCARDED};
-
- @OptimisticLock(excluded=true)
- @ManyToOne(fetch=FetchType.LAZY)
- private User closedBy;
-
- @OptimisticLock(excluded=true)
- private Date closeDate;
-
- @OptimisticLock(excluded=true)
- private Status closeStatus;
-
- public User getClosedBy() {
- return closedBy;
- }
-
- public void setClosedBy(User closedBy) {
- this.closedBy = closedBy;
- }
-
- public Date getCloseDate() {
- return closeDate;
- }
-
- public void setCloseDate(Date closeDate) {
- this.closeDate = closeDate;
- }
-
- public Status getCloseStatus() {
- return closeStatus;
- }
-
- public void setCloseStatus(Status closeStatus) {
- this.closeStatus = closeStatus;
- }
-
-}
+package com.pmease.gitplex.core.model;
+
+import java.io.Serializable;
+import java.util.Date;
+
+import javax.persistence.Embeddable;
+import javax.persistence.FetchType;
+import javax.persistence.ManyToOne;
+
+import org.hibernate.annotations.OptimisticLock;
+
+@Embeddable
+public class CloseInfo implements Serializable {
+
+ private static final long serialVersionUID = 1L;
+
+ public enum Status {INTEGRATED, DISCARDED};
+
+ @OptimisticLock(excluded=true)
+ @ManyToOne(fetch=FetchType.LAZY)
+ private User closedBy;
+
+ @OptimisticLock(excluded=true)
+ private Date closeDate;
+
+ @OptimisticLock(excluded=true)
+ private Status closeStatus;
+
+ public User getClosedBy() {
+ return closedBy;
+ }
+
+ public void setClosedBy(User closedBy) {
+ this.closedBy = closedBy;
+ }
+
+ public Date getCloseDate() {
+ return closeDate;
+ }
+
+ public void setCloseDate(Date closeDate) {
+ this.closeDate = closeDate;
+ }
+
+ public Status getCloseStatus() {
+ return closeStatus;
+ }
+
+ public void setCloseStatus(Status closeStatus) {
+ this.closeStatus = closeStatus;
+ }
+
+}
diff --git a/gitplex.core/src/main/java/com/pmease/gitplex/core/model/CommentReply.java b/gitplex.core/src/main/java/com/pmease/gitplex/core/model/CommentReply.java
index 81e40e95d3..731b90b815 100644
--- a/gitplex.core/src/main/java/com/pmease/gitplex/core/model/CommentReply.java
+++ b/gitplex.core/src/main/java/com/pmease/gitplex/core/model/CommentReply.java
@@ -1,76 +1,76 @@
-package com.pmease.gitplex.core.model;
-
-import java.util.Date;
-
-import javax.annotation.Nullable;
-import javax.persistence.Column;
-import javax.persistence.Entity;
-import javax.persistence.FetchType;
-import javax.persistence.JoinColumn;
-import javax.persistence.Lob;
-import javax.persistence.ManyToOne;
-import javax.persistence.Version;
-
-import com.pmease.commons.hibernate.AbstractEntity;
-import com.pmease.commons.hibernate.dao.Dao;
-import com.pmease.gitplex.core.GitPlex;
-
-@SuppressWarnings("serial")
-@Entity
-public class CommentReply extends AbstractEntity {
-
- @Version
- private long version;
-
- @ManyToOne(fetch=FetchType.LAZY)
- private User user;
-
- @Column(nullable=false)
- private Date date = new Date();
-
- @Lob
- @Column(nullable=false, length=65535)
- private String content;
-
- public long getVersion() {
- return version;
- }
-
- @ManyToOne(fetch=FetchType.LAZY)
- @JoinColumn(nullable=false)
- private Comment comment;
-
- @Nullable
- public User getUser() {
- return user;
- }
-
- public void setUser(User user) {
- this.user = user;
- }
-
- public Date getDate() {
- return date;
- }
-
- public String getContent() {
- return content;
- }
-
- public void setContent(String content) {
- this.content = content;
- }
-
- public void delete() {
- GitPlex.getInstance(Dao.class).remove(this);
- }
-
- public Comment getComment() {
- return comment;
- }
-
- public void setComment(Comment comment) {
- this.comment = comment;
- }
-
-}
+package com.pmease.gitplex.core.model;
+
+import java.util.Date;
+
+import javax.annotation.Nullable;
+import javax.persistence.Column;
+import javax.persistence.Entity;
+import javax.persistence.FetchType;
+import javax.persistence.JoinColumn;
+import javax.persistence.Lob;
+import javax.persistence.ManyToOne;
+import javax.persistence.Version;
+
+import com.pmease.commons.hibernate.AbstractEntity;
+import com.pmease.commons.hibernate.dao.Dao;
+import com.pmease.gitplex.core.GitPlex;
+
+@SuppressWarnings("serial")
+@Entity
+public class CommentReply extends AbstractEntity {
+
+ @Version
+ private long version;
+
+ @ManyToOne(fetch=FetchType.LAZY)
+ private User user;
+
+ @Column(nullable=false)
+ private Date date = new Date();
+
+ @Lob
+ @Column(nullable=false, length=65535)
+ private String content;
+
+ public long getVersion() {
+ return version;
+ }
+
+ @ManyToOne(fetch=FetchType.LAZY)
+ @JoinColumn(nullable=false)
+ private Comment comment;
+
+ @Nullable
+ public User getUser() {
+ return user;
+ }
+
+ public void setUser(User user) {
+ this.user = user;
+ }
+
+ public Date getDate() {
+ return date;
+ }
+
+ public String getContent() {
+ return content;
+ }
+
+ public void setContent(String content) {
+ this.content = content;
+ }
+
+ public void delete() {
+ GitPlex.getInstance(Dao.class).remove(this);
+ }
+
+ public Comment getComment() {
+ return comment;
+ }
+
+ public void setComment(Comment comment) {
+ this.comment = comment;
+ }
+
+}
diff --git a/gitplex.core/src/main/java/com/pmease/gitplex/core/model/Config.java b/gitplex.core/src/main/java/com/pmease/gitplex/core/model/Config.java
index 0f7354aaee..fb54e5df08 100644
--- a/gitplex.core/src/main/java/com/pmease/gitplex/core/model/Config.java
+++ b/gitplex.core/src/main/java/com/pmease/gitplex/core/model/Config.java
@@ -1,56 +1,56 @@
-package com.pmease.gitplex.core.model;
-
-import java.io.Serializable;
-
-import javax.persistence.Column;
-import javax.persistence.Entity;
-import javax.persistence.Lob;
-
-import org.hibernate.annotations.Cache;
-import org.hibernate.annotations.CacheConcurrencyStrategy;
-
-import com.pmease.commons.hibernate.AbstractEntity;
-
-/**
- * This entity stores object in serialized form, with one entity
- * representing one object.
- *
- */
-@SuppressWarnings("serial")
-@Entity
-@Cache(usage=CacheConcurrencyStrategy.READ_WRITE)
-public class Config extends AbstractEntity {
-
- public enum Key {SYSTEM, MAIL, QOS};
-
- @Column(nullable=false, unique=true)
- private Key key;
-
- /*
- * This field is allowed to be null to indicate particular setting is not
- * available (the record will always be available after interactive setup
- * to indicate that the setting has been prompted (although the user may
- * skipped the setting), so we can not use existence of record to indicate
- * a null setting.
- */
- @Lob
- @Column(length=65535)
- private Serializable setting;
-
- public Key getKey() {
- return key;
- }
-
- public void setKey(Key key) {
- this.key = key;
- }
-
- public Serializable getSetting() {
- return setting;
- }
-
- public void setSetting(Serializable setting) {
- this.setting = setting;
- }
-
-}
+package com.pmease.gitplex.core.model;
+
+import java.io.Serializable;
+
+import javax.persistence.Column;
+import javax.persistence.Entity;
+import javax.persistence.Lob;
+
+import org.hibernate.annotations.Cache;
+import org.hibernate.annotations.CacheConcurrencyStrategy;
+
+import com.pmease.commons.hibernate.AbstractEntity;
+
+/**
+ * This entity stores object in serialized form, with one entity
+ * representing one object.
+ *
+ */
+@SuppressWarnings("serial")
+@Entity
+@Cache(usage=CacheConcurrencyStrategy.READ_WRITE)
+public class Config extends AbstractEntity {
+
+ public enum Key {SYSTEM, MAIL, QOS};
+
+ @Column(nullable=false, unique=true)
+ private Key key;
+
+ /*
+ * This field is allowed to be null to indicate particular setting is not
+ * available (the record will always be available after interactive setup
+ * to indicate that the setting has been prompted (although the user may
+ * skipped the setting), so we can not use existence of record to indicate
+ * a null setting.
+ */
+ @Lob
+ @Column(length=65535)
+ private Serializable setting;
+
+ public Key getKey() {
+ return key;
+ }
+
+ public void setKey(Key key) {
+ this.key = key;
+ }
+
+ public Serializable getSetting() {
+ return setting;
+ }
+
+ public void setSetting(Serializable setting) {
+ this.setting = setting;
+ }
+
+}
diff --git a/gitplex.core/src/main/java/com/pmease/gitplex/core/model/Depot.java b/gitplex.core/src/main/java/com/pmease/gitplex/core/model/Depot.java
index 13cc870148..0e01bff75c 100644
--- a/gitplex.core/src/main/java/com/pmease/gitplex/core/model/Depot.java
+++ b/gitplex.core/src/main/java/com/pmease/gitplex/core/model/Depot.java
@@ -96,6 +96,7 @@ import com.pmease.gitplex.core.permission.object.UserBelonging;
import com.pmease.gitplex.core.util.validation.DepotName;
@Entity
+@Table(uniqueConstraints={@UniqueConstraint(columnNames={"g_owner_id", "name"})})
@Cache(usage=CacheConcurrencyStrategy.READ_WRITE)
@Editable
@SuppressWarnings("serial")
diff --git a/gitplex.core/src/main/java/com/pmease/gitplex/core/model/InlineInfo.java b/gitplex.core/src/main/java/com/pmease/gitplex/core/model/InlineInfo.java
index 0bc4963398..971c72ccef 100644
--- a/gitplex.core/src/main/java/com/pmease/gitplex/core/model/InlineInfo.java
+++ b/gitplex.core/src/main/java/com/pmease/gitplex/core/model/InlineInfo.java
@@ -1,64 +1,64 @@
-package com.pmease.gitplex.core.model;
-
-import java.io.Serializable;
-
-import javax.persistence.AttributeOverride;
-import javax.persistence.AttributeOverrides;
-import javax.persistence.Column;
-import javax.persistence.Embeddable;
-import javax.persistence.Embedded;
-
-import com.pmease.commons.git.BlobIdent;
-
-@Embeddable
-public class InlineInfo implements Serializable {
-
- private static final long serialVersionUID = 1L;
-
- @Embedded
- @AttributeOverrides({
- @AttributeOverride(name="revision", column=@Column(name="G_BLOB_REV")),
- @AttributeOverride(name="path", column=@Column(name="G_BLOB_PATH")),
- @AttributeOverride(name="mode", column=@Column(name="G_BLOB_MODE")),
- @AttributeOverride(name="id", column=@Column(name="G_BLOB_ID"))
- })
- private BlobIdent blobIdent;
-
- @Embedded
- @AttributeOverrides({
- @AttributeOverride(name="revision", column=@Column(name="G_COMPARE_REV") ),
- @AttributeOverride(name="path", column=@Column(name="G_COMPARE_PATH")),
- @AttributeOverride(name="mode", column=@Column(name="G_COMPARE_MODE")),
- @AttributeOverride(name="id", column=@Column(name="G_COMPARE_ID"))
- })
- private BlobIdent compareWith;
-
- // Use Integer instead of int here in order to allow this class to be
- // embedded as nullable property of JPA entities
- private Integer line;
-
- public BlobIdent getBlobIdent() {
- return blobIdent;
- }
-
- public void setBlobIdent(BlobIdent blobIdent) {
- this.blobIdent = blobIdent;
- }
-
- public BlobIdent getCompareWith() {
- return compareWith;
- }
-
- public void setCompareWith(BlobIdent compareWith) {
- this.compareWith = compareWith;
- }
-
- public int getLine() {
- return line;
- }
-
- public void setLine(int line) {
- this.line = line;
- }
-
-}
+package com.pmease.gitplex.core.model;
+
+import java.io.Serializable;
+
+import javax.persistence.AttributeOverride;
+import javax.persistence.AttributeOverrides;
+import javax.persistence.Column;
+import javax.persistence.Embeddable;
+import javax.persistence.Embedded;
+
+import com.pmease.commons.git.BlobIdent;
+
+@Embeddable
+public class InlineInfo implements Serializable {
+
+ private static final long serialVersionUID = 1L;
+
+ @Embedded
+ @AttributeOverrides({
+ @AttributeOverride(name="revision", column=@Column(name="G_BLOB_REV")),
+ @AttributeOverride(name="path", column=@Column(name="G_BLOB_PATH")),
+ @AttributeOverride(name="mode", column=@Column(name="G_BLOB_MODE")),
+ @AttributeOverride(name="id", column=@Column(name="G_BLOB_ID"))
+ })
+ private BlobIdent blobIdent;
+
+ @Embedded
+ @AttributeOverrides({
+ @AttributeOverride(name="revision", column=@Column(name="G_COMPARE_REV") ),
+ @AttributeOverride(name="path", column=@Column(name="G_COMPARE_PATH")),
+ @AttributeOverride(name="mode", column=@Column(name="G_COMPARE_MODE")),
+ @AttributeOverride(name="id", column=@Column(name="G_COMPARE_ID"))
+ })
+ private BlobIdent compareWith;
+
+ // Use Integer instead of int here in order to allow this class to be
+ // embedded as nullable property of JPA entities
+ private Integer line;
+
+ public BlobIdent getBlobIdent() {
+ return blobIdent;
+ }
+
+ public void setBlobIdent(BlobIdent blobIdent) {
+ this.blobIdent = blobIdent;
+ }
+
+ public BlobIdent getCompareWith() {
+ return compareWith;
+ }
+
+ public void setCompareWith(BlobIdent compareWith) {
+ this.compareWith = compareWith;
+ }
+
+ public int getLine() {
+ return line;
+ }
+
+ public void setLine(int line) {
+ this.line = line;
+ }
+
+}
diff --git a/gitplex.core/src/main/java/com/pmease/gitplex/core/model/IntegrationPreview.java b/gitplex.core/src/main/java/com/pmease/gitplex/core/model/IntegrationPreview.java
index 462ee67890..b8c28c7b9f 100644
--- a/gitplex.core/src/main/java/com/pmease/gitplex/core/model/IntegrationPreview.java
+++ b/gitplex.core/src/main/java/com/pmease/gitplex/core/model/IntegrationPreview.java
@@ -1,91 +1,91 @@
-package com.pmease.gitplex.core.model;
-
-import java.io.Serializable;
-
-import javax.annotation.Nullable;
-import javax.persistence.Column;
-import javax.persistence.Embeddable;
-
-import org.eclipse.jgit.lib.ObjectId;
-
-import com.pmease.gitplex.core.model.PullRequest.IntegrationStrategy;
-
-@SuppressWarnings("serial")
-@Embeddable
-public class IntegrationPreview implements Serializable {
-
- @Column(name="G_PV_TARGET_HEAD")
- private String targetHead;
-
- @Column(name="G_PV_REQUEST_HEAD")
- private String requestHead;
-
- @Column(name="G_PV_INT_STRATEGY")
- private IntegrationStrategy integrationStrategy;
-
- @Column(name="G_PV_INTEGRATED")
- private String integrated;
-
- @SuppressWarnings("unused")
- private IntegrationPreview() {
- }
-
- public IntegrationPreview(String targetHead, String requestHead,
- IntegrationStrategy integrationStrategy, @Nullable String integrated) {
- this.targetHead = targetHead;
- this.requestHead = requestHead;
- this.integrationStrategy = integrationStrategy;
- this.integrated = integrated;
- }
-
- public String getTargetHead() {
- return targetHead;
- }
-
- public String getRequestHead() {
- return requestHead;
- }
-
- public IntegrationStrategy getIntegrationStrategy() {
- return integrationStrategy;
- }
-
- public void setTargetHead(String targetHead) {
- this.targetHead = targetHead;
- }
-
- public void setRequestHead(String requestHead) {
- this.requestHead = requestHead;
- }
-
- public void setIntegrationStrategy(IntegrationStrategy integrationStrategy) {
- this.integrationStrategy = integrationStrategy;
- }
-
- /**
- * Integrated commit hash
- *
- * @return
- * null if there are conflicts
- */
- @Nullable
- public String getIntegrated() {
- return integrated;
- }
-
- public void setIntegrated(String integrated) {
- this.integrated = integrated;
- }
-
- public boolean isObsolete(PullRequest request) {
- if (getRequestHead().equals(request.getLatestUpdate().getHeadCommitHash())
- && getTargetHead().equals(request.getTarget().getObjectName())
- && getIntegrationStrategy() == request.getIntegrationStrategy()
- && (getIntegrated() == null || ObjectId.fromString(getIntegrated()).equals((request.getTargetDepot().getObjectId(request.getIntegrateRef(), false))))) {
- return false;
- } else {
- return true;
- }
- }
-
+package com.pmease.gitplex.core.model;
+
+import java.io.Serializable;
+
+import javax.annotation.Nullable;
+import javax.persistence.Column;
+import javax.persistence.Embeddable;
+
+import org.eclipse.jgit.lib.ObjectId;
+
+import com.pmease.gitplex.core.model.PullRequest.IntegrationStrategy;
+
+@SuppressWarnings("serial")
+@Embeddable
+public class IntegrationPreview implements Serializable {
+
+ @Column(name="G_PV_TARGET_HEAD")
+ private String targetHead;
+
+ @Column(name="G_PV_REQUEST_HEAD")
+ private String requestHead;
+
+ @Column(name="G_PV_INT_STRATEGY")
+ private IntegrationStrategy integrationStrategy;
+
+ @Column(name="G_PV_INTEGRATED")
+ private String integrated;
+
+ @SuppressWarnings("unused")
+ private IntegrationPreview() {
+ }
+
+ public IntegrationPreview(String targetHead, String requestHead,
+ IntegrationStrategy integrationStrategy, @Nullable String integrated) {
+ this.targetHead = targetHead;
+ this.requestHead = requestHead;
+ this.integrationStrategy = integrationStrategy;
+ this.integrated = integrated;
+ }
+
+ public String getTargetHead() {
+ return targetHead;
+ }
+
+ public String getRequestHead() {
+ return requestHead;
+ }
+
+ public IntegrationStrategy getIntegrationStrategy() {
+ return integrationStrategy;
+ }
+
+ public void setTargetHead(String targetHead) {
+ this.targetHead = targetHead;
+ }
+
+ public void setRequestHead(String requestHead) {
+ this.requestHead = requestHead;
+ }
+
+ public void setIntegrationStrategy(IntegrationStrategy integrationStrategy) {
+ this.integrationStrategy = integrationStrategy;
+ }
+
+ /**
+ * Integrated commit hash
+ *
+ * @return
+ * null if there are conflicts
+ */
+ @Nullable
+ public String getIntegrated() {
+ return integrated;
+ }
+
+ public void setIntegrated(String integrated) {
+ this.integrated = integrated;
+ }
+
+ public boolean isObsolete(PullRequest request) {
+ if (getRequestHead().equals(request.getLatestUpdate().getHeadCommitHash())
+ && getTargetHead().equals(request.getTarget().getObjectName())
+ && getIntegrationStrategy() == request.getIntegrationStrategy()
+ && (getIntegrated() == null || ObjectId.fromString(getIntegrated()).equals((request.getTargetDepot().getObjectId(request.getIntegrateRef(), false))))) {
+ return false;
+ } else {
+ return true;
+ }
+ }
+
}
\ No newline at end of file
diff --git a/gitplex.core/src/main/java/com/pmease/gitplex/core/model/IntegrationSetting.java b/gitplex.core/src/main/java/com/pmease/gitplex/core/model/IntegrationSetting.java
index 6c120e200d..45381dc4c3 100644
--- a/gitplex.core/src/main/java/com/pmease/gitplex/core/model/IntegrationSetting.java
+++ b/gitplex.core/src/main/java/com/pmease/gitplex/core/model/IntegrationSetting.java
@@ -1,43 +1,43 @@
-package com.pmease.gitplex.core.model;
-
-import java.io.Serializable;
-import java.util.ArrayList;
-import java.util.List;
-
-import javax.validation.Valid;
-import javax.validation.constraints.NotNull;
-
-import com.pmease.commons.wicket.editable.annotation.Editable;
-import com.pmease.gitplex.core.model.PullRequest.IntegrationStrategy;
-
-@SuppressWarnings("serial")
-@Editable
-public class IntegrationSetting implements Serializable {
-
- private List<IntegrationPolicy> branchStrategies = new ArrayList<>();
-
- private IntegrationStrategy defaultStrategy = IntegrationStrategy.MERGE_ALWAYS;
-
- @Editable
- @Valid
- @NotNull
- public List<IntegrationPolicy> getBranchStrategies() {
- return branchStrategies;
- }
-
- public void setBranchStrategies(List<IntegrationPolicy> branchStrategies) {
- this.branchStrategies = branchStrategies;
- }
-
- @Editable
- @Valid
- @NotNull
- public IntegrationStrategy getDefaultStrategy() {
- return defaultStrategy;
- }
-
- public void setDefaultStrategy(IntegrationStrategy defaultStrategy) {
- this.defaultStrategy = defaultStrategy;
- }
-
-}
+package com.pmease.gitplex.core.model;
+
+import java.io.Serializable;
+import java.util.ArrayList;
+import java.util.List;
+
+import javax.validation.Valid;
+import javax.validation.constraints.NotNull;
+
+import com.pmease.commons.wicket.editable.annotation.Editable;
+import com.pmease.gitplex.core.model.PullRequest.IntegrationStrategy;
+
+@SuppressWarnings("serial")
+@Editable
+public class IntegrationSetting implements Serializable {
+
+ private List<IntegrationPolicy> branchStrategies = new ArrayList<>();
+
+ private IntegrationStrategy defaultStrategy = IntegrationStrategy.MERGE_ALWAYS;
+
+ @Editable
+ @Valid
+ @NotNull
+ public List<IntegrationPolicy> getBranchStrategies() {
+ return branchStrategies;
+ }
+
+ public void setBranchStrategies(List<IntegrationPolicy> branchStrategies) {
+ this.branchStrategies = branchStrategies;
+ }
+
+ @Editable
+ @Valid
+ @NotNull
+ public IntegrationStrategy getDefaultStrategy() {
+ return defaultStrategy;
+ }
+
+ public void setDefaultStrategy(IntegrationStrategy defaultStrategy) {
+ this.defaultStrategy = defaultStrategy;
+ }
+
+}
diff --git a/gitplex.core/src/main/java/com/pmease/gitplex/core/model/Membership.java b/gitplex.core/src/main/java/com/pmease/gitplex/core/model/Membership.java
index 7606558c81..d06b3497d1 100644
--- a/gitplex.core/src/main/java/com/pmease/gitplex/core/model/Membership.java
+++ b/gitplex.core/src/main/java/com/pmease/gitplex/core/model/Membership.java
@@ -11,6 +11,9 @@ import com.pmease.commons.hibernate.AbstractEntity;
@SuppressWarnings("serial")
@Entity
+@Table(uniqueConstraints={
+ @UniqueConstraint(columnNames={"g_user_id", "g_team_id"})
+})
public class Membership extends AbstractEntity {
@ManyToOne(fetch=FetchType.LAZY)
diff --git a/gitplex.core/src/main/java/com/pmease/gitplex/core/model/ModelLocator.java b/gitplex.core/src/main/java/com/pmease/gitplex/core/model/ModelLocator.java
index 7c2fe62192..a5d18d52de 100644
--- a/gitplex.core/src/main/java/com/pmease/gitplex/core/model/ModelLocator.java
+++ b/gitplex.core/src/main/java/com/pmease/gitplex/core/model/ModelLocator.java
@@ -1,5 +1,5 @@
-package com.pmease.gitplex.core.model;
-
-public class ModelLocator {
-
-}
+package com.pmease.gitplex.core.model;
+
+public class ModelLocator {
+
+}
diff --git a/gitplex.core/src/main/java/com/pmease/gitplex/core/model/Notification.java b/gitplex.core/src/main/java/com/pmease/gitplex/core/model/Notification.java
index 3971b85c8f..5c5f1e812d 100644
--- a/gitplex.core/src/main/java/com/pmease/gitplex/core/model/Notification.java
+++ b/gitplex.core/src/main/java/com/pmease/gitplex/core/model/Notification.java
@@ -14,6 +14,9 @@ import com.pmease.commons.hibernate.AbstractEntity;
@SuppressWarnings("serial")
@Entity
+@Table(uniqueConstraints={
+ @UniqueConstraint(columnNames={"g_request_id", "g_user_id", "task"})
+})
public class Notification extends AbstractEntity {
public enum Task {
diff --git a/gitplex.core/src/main/java/com/pmease/gitplex/core/model/PullRequest.java b/gitplex.core/src/main/java/com/pmease/gitplex/core/model/PullRequest.java
index e156b0dfc6..9caf2a47b3 100644
--- a/gitplex.core/src/main/java/com/pmease/gitplex/core/model/PullRequest.java
+++ b/gitplex.core/src/main/java/com/pmease/gitplex/core/model/PullRequest.java
@@ -1,977 +1,977 @@
-package com.pmease.gitplex.core.model;
-
-import java.util.ArrayList;
-import java.util.Collection;
-import java.util.Collections;
-import java.util.Comparator;
-import java.util.Date;
-import java.util.HashMap;
-import java.util.HashSet;
-import java.util.List;
-import java.util.Map;
-import java.util.Set;
-import java.util.concurrent.Callable;
-
-import javax.annotation.Nullable;
-import javax.persistence.Column;
-import javax.persistence.Embedded;
-import javax.persistence.Entity;
-import javax.persistence.FetchType;
-import javax.persistence.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.hibernate.dao.EntityCriteria;
-import com.pmease.commons.jackson.ExternalView;
-import com.pmease.commons.util.LockUtils;
-import com.pmease.gitplex.core.GitPlex;
-import com.pmease.gitplex.core.gatekeeper.checkresult.Blocking;
-import com.pmease.gitplex.core.gatekeeper.checkresult.CheckResult;
-import com.pmease.gitplex.core.gatekeeper.checkresult.Failed;
-import com.pmease.gitplex.core.gatekeeper.checkresult.Pending;
-import com.pmease.gitplex.core.manager.PullRequestManager;
-import com.pmease.gitplex.core.manager.ReviewManager;
-import com.pmease.gitplex.core.permission.ObjectPermission;
-
-/*
- * @DynamicUpdate annotation here along with various @OptimisticLock annotations
- * on certain fields tell Hibernate not to perform version check on those fields
- * which can be updated from background thread.
- */
-@SuppressWarnings("serial")
-@Entity
-@DynamicUpdate
-@Table(indexes={@Index(columnList="title"), @Index(columnList="idStr"), @Index(columnList="noSpaceTitle")})
-public class PullRequest extends AbstractEntity {
-
- public enum Status {
- PENDING_APPROVAL("Pending Approval"),
- PENDING_UPDATE("Pending Update"), PENDING_INTEGRATE("Pending Integration"),
- INTEGRATED("Integrated"), DISCARDED("Discarded");
-
- private final String displayName;
-
- Status(String displayName) {
- this.displayName = displayName;
- }
-
- @Override
- public String toString() {
- return displayName;
- }
-
- }
-
- public enum IntegrationStrategy {
- MERGE_ALWAYS("Merge always",
- "Always create merge commit when integrate into target branch"),
- MERGE_IF_NECESSARY("Merge if necessary",
- "Create merge commit only if target branch can not be fast-forwarded to the pull request"),
- MERGE_WITH_SQUASH("Merge with squash",
- "Squash all commits in the pull request and then merge with target branch"),
- REBASE_SOURCE_ONTO_TARGET("Rebase source onto target",
- "Rebase source branch onto target branch and then fast-forward target branch to source branch"),
- REBASE_TARGET_ONTO_SOURCE("Rebase target onto source",
- "Rebase target branch onto source branch");
-
- private final String displayName;
-
- private final String description;
-
- IntegrationStrategy(String displayName, String description) {
- this.displayName = displayName;
- this.description = description;
- }
-
- public String getDisplayName() {
- return displayName;
- }
-
- public String getDescription() {
- return description;
- }
-
- @Override
- public String toString() {
- return displayName;
- }
-
- }
-
- public enum Event {
- OPENED("Newly opened"),
- REVIEWED("New reviews in"),
- VERIFIED("Build verification is finished for"),
- UPDATED("New commits in"),
- COMMENTED("New comments in"),
- INTEGRATION_STRATEGY_CHANGED("Integration strategy is changed"),
- INTEGRATED("Integration is done for"),
- DISCARDED("Discarded"),
- REOPENED("Reopened"),
- INTEGRATION_PREVIEW_CALCULATED("Integration preview is calculated"),
- ASSIGNED("Assigned"),
- REVIEWER_CHANGED("Reviewer changed"),
- REVIEW_REMOVED("Review removed"),
- COMMENT_REPLIED("Comment is replied");
-
- private final String displayName;
-
- Event(String displayName) {
- this.displayName = displayName;
- }
-
- public String toString() {
- return displayName;
- }
-
- };
-
- @Embedded
- private CloseInfo closeInfo;
-
- @Column(nullable=false)
- private String title;
-
- @Lob
- @Column(length=65535)
- private String description;
-
- @ManyToOne(fetch=FetchType.LAZY)
- private User submitter;
-
- @ManyToOne(fetch=FetchType.LAZY)
- @JoinColumn(nullable=false)
- private 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 User 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<Comment> comments = new ArrayList<>();
-
- @OneToMany(mappedBy="request")
- @OnDelete(action=OnDeleteAction.CASCADE)
- private Collection<PullRequestActivity> activities = new ArrayList<>();
-
- @OneToMany(mappedBy="request")
- @OnDelete(action=OnDeleteAction.CASCADE)
- private Collection<Notification> notifications = new ArrayList<>();
-
- @OneToMany(mappedBy="request")
- @OnDelete(action=OnDeleteAction.CASCADE)
- private Collection<PullRequestVisit> visits = new ArrayList<>();
-
- @OneToMany(mappedBy="request")
- @OnDelete(action=OnDeleteAction.CASCADE)
- private Collection<PullRequestWatch> watches = new ArrayList<>();
-
- private transient CheckResult checkResult;
-
- private transient List<PullRequestUpdate> sortedUpdates;
-
- private transient List<PullRequestUpdate> effectiveUpdates;
-
- private transient PullRequestUpdate referentialUpdate;
-
- private transient Set<String> pendingCommits;
-
- private transient Collection<Commit> mergedCommits;
-
- private transient Collection<CommentReply> commentReplies;
-
- private transient List<Review> reviews;
-
- /**
- * Get title of this merge request.
- *
- * @return user specified title of this merge request, <tt>null</tt> for
- * auto-created merge request.
- */
- public @Nullable String getTitle() {
- return title;
- }
-
- public void setTitle(String title) {
- this.title = title;
- noSpaceTitle = StringUtils.deleteWhitespace(title);
- }
-
- public String getDescription() {
- return description;
- }
-
- public void setDescription(String description) {
- this.description = description;
- }
-
- /**
- * Get the user submitting the pull request.
- *
- * @return
- * the user submitting the pull request, or <tt>null</tt> if unknown
- */
- @Nullable
- public User getSubmitter() {
- return submitter;
- }
-
- public void setSubmitter(@Nullable User submitter) {
- this.submitter = submitter;
- }
-
- /**
- * Get the user responsible for integration of the pull request.
- *
- * @return
- * the user responsible for integration of this pull request, or <tt>null</tt> to have the
- * system integrate the pull request automatically
- */
- @Nullable
- public User getAssignee() {
- return assignee;
- }
-
- public void setAssignee(User assignee) {
- this.assignee = assignee;
- }
-
- public 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<Comment> getComments() {
- return comments;
- }
-
- public void setComments(Collection<Comment> comments) {
- this.comments = comments;
- }
-
- public Collection<PullRequestActivity> getActivities() {
- return activities;
- }
-
- public void setActivities(Collection<PullRequestActivity> activities) {
- this.activities = activities;
- }
-
- public Collection<Notification> getNotifications() {
- return notifications;
- }
-
- public void setNotifications(Collection<Notification> notifications) {
- this.notifications = notifications;
- }
-
- public Collection<PullRequestVisit> getVisits() {
- return visits;
- }
-
- public void setVisits(Collection<PullRequestVisit> visits) {
- this.visits = visits;
- }
-
- public Collection<PullRequestWatch> getWatches() {
- return watches;
- }
-
- public void setWatches(Collection<PullRequestWatch> watches) {
- this.watches = watches;
- }
-
- public Status getStatus() {
- if (closeInfo != null) {
- if (closeInfo.getCloseStatus() == CloseInfo.Status.INTEGRATED)
- return Status.INTEGRATED;
- else
- return Status.DISCARDED;
- } else if (getCheckResult() instanceof Pending || getCheckResult() instanceof Blocking)
- return Status.PENDING_APPROVAL;
- else if (getCheckResult() instanceof Failed)
- return Status.PENDING_UPDATE;
- else
- return Status.PENDING_INTEGRATE;
- }
-
- @Nullable
- public CloseInfo getCloseInfo() {
- return closeInfo;
- }
-
- public void setCloseInfo(CloseInfo closeInfo) {
- this.closeInfo = closeInfo;
- }
-
- public boolean isOpen() {
- return closeInfo == null;
- }
-
- public PullRequestUpdate getReferentialUpdate() {
- if (referentialUpdate != null)
- return referentialUpdate;
- else
- return getEffectiveUpdates().get(0);
- }
-
- public void setReferentialUpdate(PullRequestUpdate referentiralUpdate) {
- this.referentialUpdate = referentiralUpdate;
- }
-
- /**
- * Get gate keeper check result.
- *
- * @return
- * check result of this pull request has not been refreshed yet
- */
- public CheckResult getCheckResult() {
- if (checkResult == null)
- checkResult = 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<User> candidates, int count) {
- List<User> pickList = new ArrayList<User>(candidates);
-
- /*
- * users already reviewed since base update should be excluded from
- * invitation list as their reviews are still valid
- */
- for (Review review: getReferentialUpdate().listReviewsOnwards())
- pickList.remove(review.getReviewer());
-
- final Map<User, Date> firstChoices = new HashMap<>();
- final Map<User, Date> secondChoices = new HashMap<>();
-
- for (ReviewInvitation invitation: getReviewInvitations()) {
- if (invitation.isPreferred())
- firstChoices.put(invitation.getReviewer(), invitation.getDate());
- else
- secondChoices.put(invitation.getReviewer(), invitation.getDate());
- }
-
- // submitter is not preferred
- if (getSubmitter() != null)
- secondChoices.put(getSubmitter(), new Date());
-
- /* Follow below rules to pick reviewers:
- * 1. If user is excluded previously, it will be considered last.
- * 2. If user is already a reviewer, it will be considered first.
- * 3. Otherwise pick user with least reviews.
- */
- Collections.sort(pickList, new Comparator<User>() {
-
- @Override
- public int compare(User user1, User user2) {
- if (firstChoices.containsKey(user1)) {
- if (firstChoices.containsKey(user2))
- return user1.getReviewEffort() - user2.getReviewEffort();
- else
- return -1;
- } else if (firstChoices.containsKey(user2)) {
- return 1;
- } else if (secondChoices.containsKey(user1)) {
- if (secondChoices.containsKey(user2))
- return secondChoices.get(user1).compareTo(secondChoices.get(user2));
- else
- return 1;
- } else if (secondChoices.containsKey(user2)) {
- return -1;
- } else {
- return user1.getReviewEffort() - user2.getReviewEffort();
- }
- }
-
- });
-
- List<User> picked;
- if (count <= pickList.size())
- picked = pickList.subList(0, count);
- else
- picked = pickList;
-
- for (User user: picked) {
- boolean found = false;
- for (ReviewInvitation invitation: getReviewInvitations()) {
- if (invitation.getReviewer().equals(user)) {
- invitation.setDate(new Date());
- invitation.setPerferred(true);
- found = true;
- }
- }
- if (!found) {
- ReviewInvitation invitation = new ReviewInvitation();
- invitation.setRequest(this);
- invitation.setReviewer(user);
- getReviewInvitations().add(invitation);
- }
- }
-
- }
-
- public static class CriterionHelper {
- public static Criterion ofOpen() {
- return Restrictions.isNull("closeInfo");
- }
-
- public static Criterion ofClosed() {
- return Restrictions.isNotNull("closeInfo");
- }
-
- public static Criterion ofTarget(DepotAndBranch target) {
- return Restrictions.and(
- Restrictions.eq("targetDepot", target.getDepot()),
- Restrictions.eq("targetBranch", target.getBranch()));
- }
-
- public static Criterion ofSource(DepotAndBranch source) {
- return Restrictions.and(
- Restrictions.eq("sourceDepot", source.getDepot()),
- Restrictions.eq("sourceBranch", source.getBranch()));
- }
-
- public static Criterion ofSubmitter(User submitter) {
- return Restrictions.eq("submitter", submitter);
- }
-
- }
-
- public Date getSubmitDate() {
- return submitDate;
- }
-
- public void setSubmitDate(Date submitDate) {
- this.submitDate = submitDate;
- }
-
- public Date getLastEventDate() {
- return lastEventDate;
- }
-
- public void setLastEventDate(Date lastEventDate) {
- this.lastEventDate = lastEventDate;
- }
-
- public Event getLastEvent() {
- return lastEvent;
- }
-
- public void setLastEvent(Event lastEvent) {
- this.lastEvent = lastEvent;
- }
-
- /**
- * Get commits pending integration.
- *
- * @return
- * commits pending integration
- */
- public Set<String> getPendingCommits() {
- if (pendingCommits == null) {
- pendingCommits = new HashSet<>();
- 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;
- }
-
- private Collection<CommentReply> getCommentReplies() {
- if (commentReplies == null) {
- EntityCriteria<CommentReply> criteria = EntityCriteria.of(CommentReply.class);
- criteria.createCriteria("comment").add(Restrictions.eq("request", this));
- commentReplies = GitPlex.getInstance(Dao.class).query(criteria);
- }
- return commentReplies;
- }
-
- /**
- * This method is here for performance consideration. Often we need to load replies of
- * different comments in a pull request. And we optimize it to load all replies at once
- * for all comments in a pull request to reduce SQL queries.
- *
- * @param comment
- * @return
- */
- public Collection<CommentReply> getCommentReplies(Comment comment) {
- List<CommentReply> replies = new ArrayList<>();
- for (CommentReply reply: getCommentReplies()) {
- if (reply.getComment().equals(comment))
- replies.add(reply);
- }
- return replies;
- }
-
- public List<Review> getReviews() {
- if (reviews == null) {
- if (!isNew())
- reviews = GitPlex.getInstance(ReviewManager.class).findBy(this);
- else
- reviews = new ArrayList<>();
- }
- return reviews;
- }
-
- /**
- * This method is here for performance consideration. Often we need to load reviews of
- * different updates in a pull request. And we optimize it to load all reviews at once
- * for all updates in a pull request to reduce SQL queries.
- *
- * @param update
- * @return
- */
- public List<Review> getReviews(PullRequestUpdate update) {
- List<Review> reviews = new ArrayList<>();
- for (Review review: getReviews()) {
- if (review.getUpdate().equals(update))
- reviews.add(review);
- }
- return reviews;
- }
-
- public boolean isReviewEffective(User user) {
- for (Review review: getReviews()) {
- if (review.getUpdate().equals(getLatestUpdate()) && review.getReviewer().equals(user))
- return true;
- }
- return false;
- }
-
- /**
- * Calculate list of users can be added as reviewers of this pull request.
- *
- * @return
- * list of potential reviewers
- */
- public List<User> getPotentialReviewers() {
- List<User> reviewers = new ArrayList<>();
- Set<User> alreadyInvited = new HashSet<>();
- for (ReviewInvitation invitation: getReviewInvitations()) {
- if (invitation.isPreferred())
- alreadyInvited.add(invitation.getReviewer());
- }
- ObjectPermission readPerm = ObjectPermission.ofDepotPull(getTargetDepot());
- for (User user: GitPlex.getInstance(Dao.class).allOf(User.class)) {
- if (user.asSubject().isPermitted(readPerm) && !alreadyInvited.contains(user))
- reviewers.add(user);
- }
- return reviewers;
- }
-
- @Nullable
- public PullRequestWatch getWatch(User user) {
- for (PullRequestWatch watch: getWatches()) {
- if (watch.getUser().equals(user))
- return watch;
- }
- return null;
- }
-
- @Nullable
- public PullRequestVisit getVisit(User user) {
- for (PullRequestVisit visit: getVisits()) {
- if (visit.getUser().equals(user))
- return visit;
- }
- return null;
- }
-
- public String getUrl() {
- return GitPlex.getInstance().guessServerUrl() + "/" + 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.model;
+
+import java.util.ArrayList;
+import java.util.Collection;
+import java.util.Collections;
+import java.util.Comparator;
+import java.util.Date;
+import java.util.HashMap;
+import java.util.HashSet;
+import java.util.List;
+import java.util.Map;
+import java.util.Set;
+import java.util.concurrent.Callable;
+
+import javax.annotation.Nullable;
+import javax.persistence.Column;
+import javax.persistence.Embedded;
+import javax.persistence.Entity;
+import javax.persistence.FetchType;
+import javax.persistence.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.hibernate.dao.EntityCriteria;
+import com.pmease.commons.jackson.ExternalView;
+import com.pmease.commons.util.LockUtils;
+import com.pmease.gitplex.core.GitPlex;
+import com.pmease.gitplex.core.gatekeeper.checkresult.Blocking;
+import com.pmease.gitplex.core.gatekeeper.checkresult.CheckResult;
+import com.pmease.gitplex.core.gatekeeper.checkresult.Failed;
+import com.pmease.gitplex.core.gatekeeper.checkresult.Pending;
+import com.pmease.gitplex.core.manager.PullRequestManager;
+import com.pmease.gitplex.core.manager.ReviewManager;
+import com.pmease.gitplex.core.permission.ObjectPermission;
+
+/*
+ * @DynamicUpdate annotation here along with various @OptimisticLock annotations
+ * on certain fields tell Hibernate not to perform version check on those fields
+ * which can be updated from background thread.
+ */
+@SuppressWarnings("serial")
+@Entity
+@DynamicUpdate
+@Table(indexes={@Index(columnList="title"), @Index(columnList="idStr"), @Index(columnList="noSpaceTitle")})
+public class PullRequest extends AbstractEntity {
+
+ public enum Status {
+ PENDING_APPROVAL("Pending Approval"),
+ PENDING_UPDATE("Pending Update"), PENDING_INTEGRATE("Pending Integration"),
+ INTEGRATED("Integrated"), DISCARDED("Discarded");
+
+ private final String displayName;
+
+ Status(String displayName) {
+ this.displayName = displayName;
+ }
+
+ @Override
+ public String toString() {
+ return displayName;
+ }
+
+ }
+
+ public enum IntegrationStrategy {
+ MERGE_ALWAYS("Merge always",
+ "Always create merge commit when integrate into target branch"),
+ MERGE_IF_NECESSARY("Merge if necessary",
+ "Create merge commit only if target branch can not be fast-forwarded to the pull request"),
+ MERGE_WITH_SQUASH("Merge with squash",
+ "Squash all commits in the pull request and then merge with target branch"),
+ REBASE_SOURCE_ONTO_TARGET("Rebase source onto target",
+ "Rebase source branch onto target branch and then fast-forward target branch to source branch"),
+ REBASE_TARGET_ONTO_SOURCE("Rebase target onto source",
+ "Rebase target branch onto source branch");
+
+ private final String displayName;
+
+ private final String description;
+
+ IntegrationStrategy(String displayName, String description) {
+ this.displayName = displayName;
+ this.description = description;
+ }
+
+ public String getDisplayName() {
+ return displayName;
+ }
+
+ public String getDescription() {
+ return description;
+ }
+
+ @Override
+ public String toString() {
+ return displayName;
+ }
+
+ }
+
+ public enum Event {
+ OPENED("Newly opened"),
+ REVIEWED("New reviews in"),
+ VERIFIED("Build verification is finished for"),
+ UPDATED("New commits in"),
+ COMMENTED("New comments in"),
+ INTEGRATION_STRATEGY_CHANGED("Integration strategy is changed"),
+ INTEGRATED("Integration is done for"),
+ DISCARDED("Discarded"),
+ REOPENED("Reopened"),
+ INTEGRATION_PREVIEW_CALCULATED("Integration preview is calculated"),
+ ASSIGNED("Assigned"),
+ REVIEWER_CHANGED("Reviewer changed"),
+ REVIEW_REMOVED("Review removed"),
+ COMMENT_REPLIED("Comment is replied");
+
+ private final String displayName;
+
+ Event(String displayName) {
+ this.displayName = displayName;
+ }
+
+ public String toString() {
+ return displayName;
+ }
+
+ };
+
+ @Embedded
+ private CloseInfo closeInfo;
+
+ @Column(nullable=false)
+ private String title;
+
+ @Lob
+ @Column(length=65535)
+ private String description;
+
+ @ManyToOne(fetch=FetchType.LAZY)
+ private User submitter;
+
+ @ManyToOne(fetch=FetchType.LAZY)
+ @JoinColumn(nullable=false)
+ private 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 User 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<Comment> comments = new ArrayList<>();
+
+ @OneToMany(mappedBy="request")
+ @OnDelete(action=OnDeleteAction.CASCADE)
+ private Collection<PullRequestActivity> activities = new ArrayList<>();
+
+ @OneToMany(mappedBy="request")
+ @OnDelete(action=OnDeleteAction.CASCADE)
+ private Collection<Notification> notifications = new ArrayList<>();
+
+ @OneToMany(mappedBy="request")
+ @OnDelete(action=OnDeleteAction.CASCADE)
+ private Collection<PullRequestVisit> visits = new ArrayList<>();
+
+ @OneToMany(mappedBy="request")
+ @OnDelete(action=OnDeleteAction.CASCADE)
+ private Collection<PullRequestWatch> watches = new ArrayList<>();
+
+ private transient CheckResult checkResult;
+
+ private transient List<PullRequestUpdate> sortedUpdates;
+
+ private transient List<PullRequestUpdate> effectiveUpdates;
+
+ private transient PullRequestUpdate referentialUpdate;
+
+ private transient Set<String> pendingCommits;
+
+ private transient Collection<Commit> mergedCommits;
+
+ private transient Collection<CommentReply> commentReplies;
+
+ private transient List<Review> reviews;
+
+ /**
+ * Get title of this merge request.
+ *
+ * @return user specified title of this merge request, <tt>null</tt> for
+ * auto-created merge request.
+ */
+ public @Nullable String getTitle() {
+ return title;
+ }
+
+ public void setTitle(String title) {
+ this.title = title;
+ noSpaceTitle = StringUtils.deleteWhitespace(title);
+ }
+
+ public String getDescription() {
+ return description;
+ }
+
+ public void setDescription(String description) {
+ this.description = description;
+ }
+
+ /**
+ * Get the user submitting the pull request.
+ *
+ * @return
+ * the user submitting the pull request, or <tt>null</tt> if unknown
+ */
+ @Nullable
+ public User getSubmitter() {
+ return submitter;
+ }
+
+ public void setSubmitter(@Nullable User submitter) {
+ this.submitter = submitter;
+ }
+
+ /**
+ * Get the user responsible for integration of the pull request.
+ *
+ * @return
+ * the user responsible for integration of this pull request, or <tt>null</tt> to have the
+ * system integrate the pull request automatically
+ */
+ @Nullable
+ public User getAssignee() {
+ return assignee;
+ }
+
+ public void setAssignee(User assignee) {
+ this.assignee = assignee;
+ }
+
+ public 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<Comment> getComments() {
+ return comments;
+ }
+
+ public void setComments(Collection<Comment> comments) {
+ this.comments = comments;
+ }
+
+ public Collection<PullRequestActivity> getActivities() {
+ return activities;
+ }
+
+ public void setActivities(Collection<PullRequestActivity> activities) {
+ this.activities = activities;
+ }
+
+ public Collection<Notification> getNotifications() {
+ return notifications;
+ }
+
+ public void setNotifications(Collection<Notification> notifications) {
+ this.notifications = notifications;
+ }
+
+ public Collection<PullRequestVisit> getVisits() {
+ return visits;
+ }
+
+ public void setVisits(Collection<PullRequestVisit> visits) {
+ this.visits = visits;
+ }
+
+ public Collection<PullRequestWatch> getWatches() {
+ return watches;
+ }
+
+ public void setWatches(Collection<PullRequestWatch> watches) {
+ this.watches = watches;
+ }
+
+ public Status getStatus() {
+ if (closeInfo != null) {
+ if (closeInfo.getCloseStatus() == CloseInfo.Status.INTEGRATED)
+ return Status.INTEGRATED;
+ else
+ return Status.DISCARDED;
+ } else if (getCheckResult() instanceof Pending || getCheckResult() instanceof Blocking)
+ return Status.PENDING_APPROVAL;
+ else if (getCheckResult() instanceof Failed)
+ return Status.PENDING_UPDATE;
+ else
+ return Status.PENDING_INTEGRATE;
+ }
+
+ @Nullable
+ public CloseInfo getCloseInfo() {
+ return closeInfo;
+ }
+
+ public void setCloseInfo(CloseInfo closeInfo) {
+ this.closeInfo = closeInfo;
+ }
+
+ public boolean isOpen() {
+ return closeInfo == null;
+ }
+
+ public PullRequestUpdate getReferentialUpdate() {
+ if (referentialUpdate != null)
+ return referentialUpdate;
+ else
+ return getEffectiveUpdates().get(0);
+ }
+
+ public void setReferentialUpdate(PullRequestUpdate referentiralUpdate) {
+ this.referentialUpdate = referentiralUpdate;
+ }
+
+ /**
+ * Get gate keeper check result.
+ *
+ * @return
+ * check result of this pull request has not been refreshed yet
+ */
+ public CheckResult getCheckResult() {
+ if (checkResult == null)
+ checkResult = 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<User> candidates, int count) {
+ List<User> pickList = new ArrayList<User>(candidates);
+
+ /*
+ * users already reviewed since base update should be excluded from
+ * invitation list as their reviews are still valid
+ */
+ for (Review review: getReferentialUpdate().listReviewsOnwards())
+ pickList.remove(review.getReviewer());
+
+ final Map<User, Date> firstChoices = new HashMap<>();
+ final Map<User, Date> secondChoices = new HashMap<>();
+
+ for (ReviewInvitation invitation: getReviewInvitations()) {
+ if (invitation.isPreferred())
+ firstChoices.put(invitation.getReviewer(), invitation.getDate());
+ else
+ secondChoices.put(invitation.getReviewer(), invitation.getDate());
+ }
+
+ // submitter is not preferred
+ if (getSubmitter() != null)
+ secondChoices.put(getSubmitter(), new Date());
+
+ /* Follow below rules to pick reviewers:
+ * 1. If user is excluded previously, it will be considered last.
+ * 2. If user is already a reviewer, it will be considered first.
+ * 3. Otherwise pick user with least reviews.
+ */
+ Collections.sort(pickList, new Comparator<User>() {
+
+ @Override
+ public int compare(User user1, User user2) {
+ if (firstChoices.containsKey(user1)) {
+ if (firstChoices.containsKey(user2))
+ return user1.getReviewEffort() - user2.getReviewEffort();
+ else
+ return -1;
+ } else if (firstChoices.containsKey(user2)) {
+ return 1;
+ } else if (secondChoices.containsKey(user1)) {
+ if (secondChoices.containsKey(user2))
+ return secondChoices.get(user1).compareTo(secondChoices.get(user2));
+ else
+ return 1;
+ } else if (secondChoices.containsKey(user2)) {
+ return -1;
+ } else {
+ return user1.getReviewEffort() - user2.getReviewEffort();
+ }
+ }
+
+ });
+
+ List<User> picked;
+ if (count <= pickList.size())
+ picked = pickList.subList(0, count);
+ else
+ picked = pickList;
+
+ for (User user: picked) {
+ boolean found = false;
+ for (ReviewInvitation invitation: getReviewInvitations()) {
+ if (invitation.getReviewer().equals(user)) {
+ invitation.setDate(new Date());
+ invitation.setPerferred(true);
+ found = true;
+ }
+ }
+ if (!found) {
+ ReviewInvitation invitation = new ReviewInvitation();
+ invitation.setRequest(this);
+ invitation.setReviewer(user);
+ getReviewInvitations().add(invitation);
+ }
+ }
+
+ }
+
+ public static class CriterionHelper {
+ public static Criterion ofOpen() {
+ return Restrictions.isNull("closeInfo");
+ }
+
+ public static Criterion ofClosed() {
+ return Restrictions.isNotNull("closeInfo");
+ }
+
+ public static Criterion ofTarget(DepotAndBranch target) {
+ return Restrictions.and(
+ Restrictions.eq("targetDepot", target.getDepot()),
+ Restrictions.eq("targetBranch", target.getBranch()));
+ }
+
+ public static Criterion ofSource(DepotAndBranch source) {
+ return Restrictions.and(
+ Restrictions.eq("sourceDepot", source.getDepot()),
+ Restrictions.eq("sourceBranch", source.getBranch()));
+ }
+
+ public static Criterion ofSubmitter(User submitter) {
+ return Restrictions.eq("submitter", submitter);
+ }
+
+ }
+
+ public Date getSubmitDate() {
+ return submitDate;
+ }
+
+ public void setSubmitDate(Date submitDate) {
+ this.submitDate = submitDate;
+ }
+
+ public Date getLastEventDate() {
+ return lastEventDate;
+ }
+
+ public void setLastEventDate(Date lastEventDate) {
+ this.lastEventDate = lastEventDate;
+ }
+
+ public Event getLastEvent() {
+ return lastEvent;
+ }
+
+ public void setLastEvent(Event lastEvent) {
+ this.lastEvent = lastEvent;
+ }
+
+ /**
+ * Get commits pending integration.
+ *
+ * @return
+ * commits pending integration
+ */
+ public Set<String> getPendingCommits() {
+ if (pendingCommits == null) {
+ pendingCommits = new HashSet<>();
+ 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;
+ }
+
+ private Collection<CommentReply> getCommentReplies() {
+ if (commentReplies == null) {
+ EntityCriteria<CommentReply> criteria = EntityCriteria.of(CommentReply.class);
+ criteria.createCriteria("comment").add(Restrictions.eq("request", this));
+ commentReplies = GitPlex.getInstance(Dao.class).query(criteria);
+ }
+ return commentReplies;
+ }
+
+ /**
+ * This method is here for performance consideration. Often we need to load replies of
+ * different comments in a pull request. And we optimize it to load all replies at once
+ * for all comments in a pull request to reduce SQL queries.
+ *
+ * @param comment
+ * @return
+ */
+ public Collection<CommentReply> getCommentReplies(Comment comment) {
+ List<CommentReply> replies = new ArrayList<>();
+ for (CommentReply reply: getCommentReplies()) {
+ if (reply.getComment().equals(comment))
+ replies.add(reply);
+ }
+ return replies;
+ }
+
+ public List<Review> getReviews() {
+ if (reviews == null) {
+ if (!isNew())
+ reviews = GitPlex.getInstance(ReviewManager.class).findBy(this);
+ else
+ reviews = new ArrayList<>();
+ }
+ return reviews;
+ }
+
+ /**
+ * This method is here for performance consideration. Often we need to load reviews of
+ * different updates in a pull request. And we optimize it to load all reviews at once
+ * for all updates in a pull request to reduce SQL queries.
+ *
+ * @param update
+ * @return
+ */
+ public List<Review> getReviews(PullRequestUpdate update) {
+ List<Review> reviews = new ArrayList<>();
+ for (Review review: getReviews()) {
+ if (review.getUpdate().equals(update))
+ reviews.add(review);
+ }
+ return reviews;
+ }
+
+ public boolean isReviewEffective(User user) {
+ for (Review review: getReviews()) {
+ if (review.getUpdate().equals(getLatestUpdate()) && review.getReviewer().equals(user))
+ return true;
+ }
+ return false;
+ }
+
+ /**
+ * Calculate list of users can be added as reviewers of this pull request.
+ *
+ * @return
+ * list of potential reviewers
+ */
+ public List<User> getPotentialReviewers() {
+ List<User> reviewers = new ArrayList<>();
+ Set<User> alreadyInvited = new HashSet<>();
+ for (ReviewInvitation invitation: getReviewInvitations()) {
+ if (invitation.isPreferred())
+ alreadyInvited.add(invitation.getReviewer());
+ }
+ ObjectPermission readPerm = ObjectPermission.ofDepotPull(getTargetDepot());
+ for (User user: GitPlex.getInstance(Dao.class).allOf(User.class)) {
+ if (user.asSubject().isPermitted(readPerm) && !alreadyInvited.contains(user))
+ reviewers.add(user);
+ }
+ return reviewers;
+ }
+
+ @Nullable
+ public PullRequestWatch getWatch(User user) {
+ for (PullRequestWatch watch: getWatches()) {
+ if (watch.getUser().equals(user))
+ return watch;
+ }
+ return null;
+ }
+
+ @Nullable
+ public PullRequestVisit getVisit(User user) {
+ for (PullRequestVisit visit: getVisits()) {
+ if (visit.getUser().equals(user))
+ return visit;
+ }
+ return null;
+ }
+
+ public String getUrl() {
+ return GitPlex.getInstance().guessServerUrl() + "/" + 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/model/PullRequestActivity.java b/gitplex.core/src/main/java/com/pmease/gitplex/core/model/PullRequestActivity.java
index 894dd11827..32d6a1c6aa 100644
--- a/gitplex.core/src/main/java/com/pmease/gitplex/core/model/PullRequestActivity.java
+++ b/gitplex.core/src/main/java/com/pmease/gitplex/core/model/PullRequestActivity.java
@@ -1,67 +1,67 @@
-package com.pmease.gitplex.core.model;
-
-import java.util.Date;
-
-import javax.annotation.Nullable;
-import javax.persistence.Column;
-import javax.persistence.Entity;
-import javax.persistence.FetchType;
-import javax.persistence.JoinColumn;
-import javax.persistence.ManyToOne;
-
-import com.pmease.commons.hibernate.AbstractEntity;
-
-@SuppressWarnings("serial")
-@Entity
-public class PullRequestActivity extends AbstractEntity {
-
- public enum Action {OPEN, INTEGRATE, DISCARD, APPROVE, DISAPPROVE, UNDO_REVIEW,
- REOPEN, DELETE_SOURCE_BRANCH, RESTORE_SOURCE_BRANCH};
-
- @ManyToOne
- @JoinColumn(nullable=false)
- private PullRequest request;
-
- @Column(nullable=false)
- private Action action;
-
- @ManyToOne(fetch=FetchType.LAZY)
- private User user;
-
- @Column(nullable=false)
- private Date date = new Date();
-
- public PullRequest getRequest() {
- return request;
- }
-
- public void setRequest(PullRequest request) {
- this.request = request;
- }
-
- public Action getAction() {
- return action;
- }
-
- public void setAction(Action action) {
- this.action = action;
- }
-
- @Nullable
- public User getUser() {
- return user;
- }
-
- public void setUser(User user) {
- this.user = user;
- }
-
- public Date getDate() {
- return date;
- }
-
- public void setDate(Date date) {
- this.date = date;
- }
-
-}
+package com.pmease.gitplex.core.model;
+
+import java.util.Date;
+
+import javax.annotation.Nullable;
+import javax.persistence.Column;
+import javax.persistence.Entity;
+import javax.persistence.FetchType;
+import javax.persistence.JoinColumn;
+import javax.persistence.ManyToOne;
+
+import com.pmease.commons.hibernate.AbstractEntity;
+
+@SuppressWarnings("serial")
+@Entity
+public class PullRequestActivity extends AbstractEntity {
+
+ public enum Action {OPEN, INTEGRATE, DISCARD, APPROVE, DISAPPROVE, UNDO_REVIEW,
+ REOPEN, DELETE_SOURCE_BRANCH, RESTORE_SOURCE_BRANCH};
+
+ @ManyToOne
+ @JoinColumn(nullable=false)
+ private PullRequest request;
+
+ @Column(nullable=false)
+ private Action action;
+
+ @ManyToOne(fetch=FetchType.LAZY)
+ private User user;
+
+ @Column(nullable=false)
+ private Date date = new Date();
+
+ public PullRequest getRequest() {
+ return request;
+ }
+
+ public void setRequest(PullRequest request) {
+ this.request = request;
+ }
+
+ public Action getAction() {
+ return action;
+ }
+
+ public void setAction(Action action) {
+ this.action = action;
+ }
+
+ @Nullable
+ public User getUser() {
+ return user;
+ }
+
+ public void setUser(User user) {
+ this.user = user;
+ }
+
+ public Date getDate() {
+ return date;
+ }
+
+ public void setDate(Date date) {
+ this.date = date;
+ }
+
+}
diff --git a/gitplex.core/src/main/java/com/pmease/gitplex/core/model/PullRequestReference.java b/gitplex.core/src/main/java/com/pmease/gitplex/core/model/PullRequestReference.java
index 6925c880bb..c543de4963 100644
--- a/gitplex.core/src/main/java/com/pmease/gitplex/core/model/PullRequestReference.java
+++ b/gitplex.core/src/main/java/com/pmease/gitplex/core/model/PullRequestReference.java
@@ -16,6 +16,9 @@ import org.hibernate.annotations.FetchMode;
import com.pmease.commons.hibernate.AbstractEntity;
@SuppressWarnings("serial")
+@Table(uniqueConstraints={
+ @UniqueConstraint(columnNames={"g_referenced_id", "g_referencedBy_id"})
+})
@Entity
public class PullRequestReference extends AbstractEntity {
diff --git a/gitplex.core/src/main/java/com/pmease/gitplex/core/model/PullRequestUpdate.java b/gitplex.core/src/main/java/com/pmease/gitplex/core/model/PullRequestUpdate.java
index 4d2bc1776d..c0e8fa5b66 100644
--- a/gitplex.core/src/main/java/com/pmease/gitplex/core/model/PullRequestUpdate.java
+++ b/gitplex.core/src/main/java/com/pmease/gitplex/core/model/PullRequestUpdate.java
@@ -1,359 +1,359 @@
-package com.pmease.gitplex.core.model;
-
-import java.io.File;
-import java.io.Serializable;
-import java.util.ArrayList;
-import java.util.Collection;
-import java.util.Collections;
-import java.util.Date;
-import java.util.HashMap;
-import java.util.LinkedHashMap;
-import java.util.List;
-import java.util.Map;
-import java.util.Stack;
-import java.util.concurrent.Callable;
-
-import javax.persistence.Column;
-import javax.persistence.Entity;
-import javax.persistence.FetchType;
-import javax.persistence.JoinColumn;
-import javax.persistence.ManyToOne;
-import javax.persistence.OneToMany;
-
-import org.hibernate.annotations.OnDelete;
-import org.hibernate.annotations.OnDeleteAction;
-
-import com.fasterxml.jackson.annotation.JsonProperty;
-import com.google.common.base.Preconditions;
-import com.google.common.base.Throwables;
-import com.google.common.collect.Lists;
-import com.pmease.commons.git.Commit;
-import com.pmease.commons.git.Git;
-import com.pmease.commons.hibernate.AbstractEntity;
-import com.pmease.commons.util.FileUtils;
-import com.pmease.gitplex.core.GitPlex;
-import com.pmease.gitplex.core.manager.StorageManager;
-
-@SuppressWarnings("serial")
-@Entity
-public class PullRequestUpdate extends AbstractEntity {
-
- @ManyToOne(fetch=FetchType.LAZY)
- @JoinColumn(nullable=false)
- private PullRequest request;
-
- @Column(nullable=false)
- private String headCommitHash;
-
- @Column(nullable=false)
- private Date date;
-
- @OneToMany(mappedBy="update")
- @OnDelete(action=OnDeleteAction.CASCADE)
- private Collection<Review> reviews = new ArrayList<Review>();
-
- private transient List<Commit> commits;
-
- private transient CachedInfo cachedInfo;
-
- public PullRequest getRequest() {
- return request;
- }
-
- public void setRequest(PullRequest request) {
- this.request = request;
- }
-
- public String getHeadCommitHash() {
- return headCommitHash;
- }
-
- public void setHeadCommitHash(String headCommitHash) {
- this.headCommitHash = headCommitHash;
- }
-
- public Date getDate() {
- return date;
- }
-
- public void setDate(Date date) {
- this.date = date;
- }
-
- public Collection<Review> getReviews() {
- return getRequest().getReviews(this);
- }
-
- @JsonProperty
- public String getHeadRef() {
- Preconditions.checkNotNull(getId());
- return Depot.REFS_GITPLEX + "updates/" + getId();
- }
-
- /**
- * List reviews against this update and all subsequent updates.
- * <p>
- * @return
- * list of found reviews, ordered by associated updates reversely
- */
- public List<Review> listReviewsOnwards() {
- List<Review> reviews = new ArrayList<Review>();
-
- for (PullRequestUpdate update: getRequest().getEffectiveUpdates()) {
- reviews.addAll(update.getReviews());
- if (update.equals(this))
- break;
- }
-
- return reviews;
- }
-
- public void deleteRefs() {
- Git git = getRequest().getTargetDepot().git();
- git.deleteRef(getHeadRef(), null, null);
- }
-
- public Collection<String> getChangedFiles() {
- return getCachedInfo().getChangedFiles();
- }
-
- public String getBaseCommitHash() {
- PullRequest request = getRequest();
-
- int index = request.getSortedUpdates().indexOf(this);
- if (index > 0)
- return request.getSortedUpdates().get(index-1).getHeadCommitHash();
- else
- return request.getBaseCommitHash();
- }
-
- /**
- * Base commit represents head commit of last update, or base commit of the request
- * for the first update. Base commit is used to calculate commits belonging to
- * current update.
- *
- * @return
- * base commit of this update
- */
- public Commit getBaseCommit() {
- PullRequest request = getRequest();
-
- int index = request.getSortedUpdates().indexOf(this);
- if (index > 0)
- return request.getSortedUpdates().get(index-1).getHeadCommit();
- else
- return request.getBaseCommit();
- }
-
- private CachedInfo getCachedInfo() {
- if (cachedInfo == null) {
- Callable<CachedInfo> callable = new Callable<CachedInfo>() {
-
- @Override
- public CachedInfo call() throws Exception {
- CachedInfo cachedInfo = new CachedInfo();
-
- Depot targetDepot = getRequest().getTargetDepot();
- Git git = targetDepot.git();
- List<Commit> log = git.log(getBaseCommitHash(), getHeadCommitHash(), null, 0, 0, false);
- if (log.isEmpty())
- log = Lists.newArrayList(targetDepot.getCommit(getHeadCommitHash()));
- cachedInfo.setLogCommits(log);
-
- String mergeBase = git.calcMergeBase(getHeadCommitHash(), getRequest().getTarget().getObjectName());
-
- if (targetDepot.isAncestor(getBaseCommitHash(), mergeBase)) {
- cachedInfo.setChangedFiles(git.listChangedFiles(mergeBase, getHeadCommitHash(), null));
- } else if (targetDepot.isAncestor(mergeBase, getBaseCommitHash())) {
- cachedInfo.setChangedFiles(git.listChangedFiles(getBaseCommitHash(), getHeadCommitHash(), null));
- } else {
- File tempDir = FileUtils.createTempDir();
- try {
- Git tempGit = new Git(tempDir);
-
- /*
- * Calculate changed files of this update since merged commit of:
- *
- * 1. merge base of update head and target branch head
- * 2. head of previous update
- *
- * This way changed files of this update will exclude merged changes
- * from target branch if there is any.
- */
- String branchName = getRequest().getTargetBranch();
- tempGit.clone(git.depotDir().getAbsolutePath(), false, true, true, branchName);
- tempGit.updateRef("HEAD", mergeBase, null, null);
- tempGit.reset(null, null);
- Preconditions.checkNotNull(tempGit.merge(getBaseCommitHash(), null, null, "ours", null));
-
- cachedInfo.setChangedFiles(tempGit.listChangedFiles(
- tempGit.parseRevision("HEAD", true), getHeadCommitHash(), null));
- } finally {
- FileUtils.deleteDir(tempDir);
- }
- }
-
- return cachedInfo;
- }
-
- };
- if (isNew()) {
- try {
- cachedInfo = callable.call();
- } catch (Exception e) {
- Throwables.propagate(e);
- }
- } else {
- StorageManager storageManager = GitPlex.getInstance(StorageManager.class);
- File cacheFile = new File(storageManager.getCacheDir(this), "cachedInfo");
- cachedInfo = FileUtils.readFile(cacheFile, callable);
- }
- }
- return cachedInfo;
- }
-
- /**
- * Get commits belonging to this update, ordered by commit id
- *
- * @return
- * commits belonging to this update ordered by commit id
- */
- public List<Commit> getCommits() {
- if (commits == null) {
- /*
- * This method calculates all commits belonging to this update. You might think that
- * the result is obvious, just take log output between last update and current head.
- * But that result may include noise commits, for instance, if you merges target
- * branch into source branch to resolve merge conflicts, all commits in target
- * branch will also appear in log output between last update and current update.
- * Now, you might suggest that let's just exclude from the log output those commits
- * being ancestor of target branch. But this still can cause issues as target branch
- * may merge some intermediate commits from our source branch, and these
- * intermediate commits will be ancestor of target branch. We certainly do not want
- * to exclude these intermediate commits as it originally belongs to our source
- * branch. To solve this contradiction, for those commits belong to both source
- * branch and target branch, we calculate affinity score of the commit to each
- * branch, and consider the commit to be belonging to a branch if the associated
- * affinity score is less.
- */
- commits = new ArrayList<>();
-
- Map<String, ScoreAwareCommit> allCommits = new LinkedHashMap<>();
- for (Commit commit: getCachedInfo().getLogCommits()) {
- ScoreAwareCommit scoreAwareCommit = new ScoreAwareCommit();
- scoreAwareCommit.setCommit(commit);
- allCommits.put(commit.getHash(), scoreAwareCommit);
- }
-
- ScoreAwareCommit headCommit = allCommits.get(getHeadCommitHash());
- if (headCommit != null) {
- headCommit.setScore(0);
- updateAffinityScores(allCommits, headCommit);
- }
-
- Map<String, ScoreAwareCommit> mergedCommits = new HashMap<>();
- for (Commit commit: getRequest().getMergedCommits()) {
- ScoreAwareCommit scoredCommit = new ScoreAwareCommit();
- scoredCommit.setCommit(commit);
- mergedCommits.put(commit.getHash(), scoredCommit);
- }
-
- headCommit = mergedCommits.get(getRequest().getTarget().getObjectName());
- if (headCommit != null) {
- headCommit.setScore(0);
- updateAffinityScores(mergedCommits, headCommit);
- }
-
- for (ScoreAwareCommit commit: allCommits.values()) {
- ScoreAwareCommit mergedCommit = mergedCommits.get(commit.getCommit().getHash());
- if (mergedCommit == null || mergedCommit.getScore() >= commit.getScore())
- commits.add(commit.getCommit());
- }
-
- getRequest().getTargetDepot().cacheCommits(commits);
-
- Collections.reverse(commits);
- }
- return commits;
- }
-
- public Commit getHeadCommit() {
- Commit headCommit = getCachedInfo().getLogCommits().get(0);
- Preconditions.checkState(headCommit.getHash().equals(getHeadCommitHash()));
- return headCommit;
- }
-
- /*
- * This method calculates affinity scores of a set of commits against specified head commit (or branch).
- * The affinity score reflects the distance between a commit and first-parent chain of the head commit.
- * For instance, if a commit can be reached recursively via first-parent of the head commit, its
- * affinity score will be 0.
- */
- private void updateAffinityScores(Map<String, ScoreAwareCommit> commits, ScoreAwareCommit headCommit) {
- Stack<ScoreAwareCommit> stack = new Stack<>();
- stack.push(headCommit);
- while (!stack.isEmpty()) {
- ScoreAwareCommit currentCommit = stack.pop();
- for (int i=0; i<currentCommit.getCommit().getParentHashes().size(); i++) {
- String parentCommitHash = currentCommit.getCommit().getParentHashes().get(i);
- ScoreAwareCommit parentCommit = commits.get(parentCommitHash);
- if (parentCommit != null && parentCommit.getScore() == Integer.MAX_VALUE) {
- /*
- * Parent hashes of a commit is ordered in parent number. For instance first-parent is at index 0.
- * So the parent score is calculated simply by adding current parent index to the head commit score.
- */
- parentCommit.setScore(i + currentCommit.getScore());
- stack.push(parentCommit);
- }
- }
- }
- }
-
- private static class ScoreAwareCommit {
-
- private Commit commit;
-
- private int score = Integer.MAX_VALUE;
-
- public Commit getCommit() {
- return commit;
- }
-
- public void setCommit(Commit commit) {
- this.commit = commit;
- }
-
- public int getScore() {
- return score;
- }
-
- public void setScore(int score) {
- this.score = score;
- }
-
- }
-
- private static class CachedInfo implements Serializable {
-
- private Collection<String> changedFiles;
-
- private List<Commit> logCommits;
-
- public Collection<String> getChangedFiles() {
- return changedFiles;
- }
-
- public void setChangedFiles(Collection<String> changedFiles) {
- this.changedFiles = changedFiles;
- }
-
- public List<Commit> getLogCommits() {
- return logCommits;
- }
-
- public void setLogCommits(List<Commit> logCommits) {
- this.logCommits = logCommits;
- }
-
- }
-}
+package com.pmease.gitplex.core.model;
+
+import java.io.File;
+import java.io.Serializable;
+import java.util.ArrayList;
+import java.util.Collection;
+import java.util.Collections;
+import java.util.Date;
+import java.util.HashMap;
+import java.util.LinkedHashMap;
+import java.util.List;
+import java.util.Map;
+import java.util.Stack;
+import java.util.concurrent.Callable;
+
+import javax.persistence.Column;
+import javax.persistence.Entity;
+import javax.persistence.FetchType;
+import javax.persistence.JoinColumn;
+import javax.persistence.ManyToOne;
+import javax.persistence.OneToMany;
+
+import org.hibernate.annotations.OnDelete;
+import org.hibernate.annotations.OnDeleteAction;
+
+import com.fasterxml.jackson.annotation.JsonProperty;
+import com.google.common.base.Preconditions;
+import com.google.common.base.Throwables;
+import com.google.common.collect.Lists;
+import com.pmease.commons.git.Commit;
+import com.pmease.commons.git.Git;
+import com.pmease.commons.hibernate.AbstractEntity;
+import com.pmease.commons.util.FileUtils;
+import com.pmease.gitplex.core.GitPlex;
+import com.pmease.gitplex.core.manager.StorageManager;
+
+@SuppressWarnings("serial")
+@Entity
+public class PullRequestUpdate extends AbstractEntity {
+
+ @ManyToOne(fetch=FetchType.LAZY)
+ @JoinColumn(nullable=false)
+ private PullRequest request;
+
+ @Column(nullable=false)
+ private String headCommitHash;
+
+ @Column(nullable=false)
+ private Date date;
+
+ @OneToMany(mappedBy="update")
+ @OnDelete(action=OnDeleteAction.CASCADE)
+ private Collection<Review> reviews = new ArrayList<Review>();
+
+ private transient List<Commit> commits;
+
+ private transient CachedInfo cachedInfo;
+
+ public PullRequest getRequest() {
+ return request;
+ }
+
+ public void setRequest(PullRequest request) {
+ this.request = request;
+ }
+
+ public String getHeadCommitHash() {
+ return headCommitHash;
+ }
+
+ public void setHeadCommitHash(String headCommitHash) {
+ this.headCommitHash = headCommitHash;
+ }
+
+ public Date getDate() {
+ return date;
+ }
+
+ public void setDate(Date date) {
+ this.date = date;
+ }
+
+ public Collection<Review> getReviews() {
+ return getRequest().getReviews(this);
+ }
+
+ @JsonProperty
+ public String getHeadRef() {
+ Preconditions.checkNotNull(getId());
+ return Depot.REFS_GITPLEX + "updates/" + getId();
+ }
+
+ /**
+ * List reviews against this update and all subsequent updates.
+ * <p>
+ * @return
+ * list of found reviews, ordered by associated updates reversely
+ */
+ public List<Review> listReviewsOnwards() {
+ List<Review> reviews = new ArrayList<Review>();
+
+ for (PullRequestUpdate update: getRequest().getEffectiveUpdates()) {
+ reviews.addAll(update.getReviews());
+ if (update.equals(this))
+ break;
+ }
+
+ return reviews;
+ }
+
+ public void deleteRefs() {
+ Git git = getRequest().getTargetDepot().git();
+ git.deleteRef(getHeadRef(), null, null);
+ }
+
+ public Collection<String> getChangedFiles() {
+ return getCachedInfo().getChangedFiles();
+ }
+
+ public String getBaseCommitHash() {
+ PullRequest request = getRequest();
+
+ int index = request.getSortedUpdates().indexOf(this);
+ if (index > 0)
+ return request.getSortedUpdates().get(index-1).getHeadCommitHash();
+ else
+ return request.getBaseCommitHash();
+ }
+
+ /**
+ * Base commit represents head commit of last update, or base commit of the request
+ * for the first update. Base commit is used to calculate commits belonging to
+ * current update.
+ *
+ * @return
+ * base commit of this update
+ */
+ public Commit getBaseCommit() {
+ PullRequest request = getRequest();
+
+ int index = request.getSortedUpdates().indexOf(this);
+ if (index > 0)
+ return request.getSortedUpdates().get(index-1).getHeadCommit();
+ else
+ return request.getBaseCommit();
+ }
+
+ private CachedInfo getCachedInfo() {
+ if (cachedInfo == null) {
+ Callable<CachedInfo> callable = new Callable<CachedInfo>() {
+
+ @Override
+ public CachedInfo call() throws Exception {
+ CachedInfo cachedInfo = new CachedInfo();
+
+ Depot targetDepot = getRequest().getTargetDepot();
+ Git git = targetDepot.git();
+ List<Commit> log = git.log(getBaseCommitHash(), getHeadCommitHash(), null, 0, 0, false);
+ if (log.isEmpty())
+ log = Lists.newArrayList(targetDepot.getCommit(getHeadCommitHash()));
+ cachedInfo.setLogCommits(log);
+
+ String mergeBase = git.calcMergeBase(getHeadCommitHash(), getRequest().getTarget().getObjectName());
+
+ if (targetDepot.isAncestor(getBaseCommitHash(), mergeBase)) {
+ cachedInfo.setChangedFiles(git.listChangedFiles(mergeBase, getHeadCommitHash(), null));
+ } else if (targetDepot.isAncestor(mergeBase, getBaseCommitHash())) {
+ cachedInfo.setChangedFiles(git.listChangedFiles(getBaseCommitHash(), getHeadCommitHash(), null));
+ } else {
+ File tempDir = FileUtils.createTempDir();
+ try {
+ Git tempGit = new Git(tempDir);
+
+ /*
+ * Calculate changed files of this update since merged commit of:
+ *
+ * 1. merge base of update head and target branch head
+ * 2. head of previous update
+ *
+ * This way changed files of this update will exclude merged changes
+ * from target branch if there is any.
+ */
+ String branchName = getRequest().getTargetBranch();
+ tempGit.clone(git.depotDir().getAbsolutePath(), false, true, true, branchName);
+ tempGit.updateRef("HEAD", mergeBase, null, null);
+ tempGit.reset(null, null);
+ Preconditions.checkNotNull(tempGit.merge(getBaseCommitHash(), null, null, "ours", null));
+
+ cachedInfo.setChangedFiles(tempGit.listChangedFiles(
+ tempGit.parseRevision("HEAD", true), getHeadCommitHash(), null));
+ } finally {
+ FileUtils.deleteDir(tempDir);
+ }
+ }
+
+ return cachedInfo;
+ }
+
+ };
+ if (isNew()) {
+ try {
+ cachedInfo = callable.call();
+ } catch (Exception e) {
+ Throwables.propagate(e);
+ }
+ } else {
+ StorageManager storageManager = GitPlex.getInstance(StorageManager.class);
+ File cacheFile = new File(storageManager.getCacheDir(this), "cachedInfo");
+ cachedInfo = FileUtils.readFile(cacheFile, callable);
+ }
+ }
+ return cachedInfo;
+ }
+
+ /**
+ * Get commits belonging to this update, ordered by commit id
+ *
+ * @return
+ * commits belonging to this update ordered by commit id
+ */
+ public List<Commit> getCommits() {
+ if (commits == null) {
+ /*
+ * This method calculates all commits belonging to this update. You might think that
+ * the result is obvious, just take log output between last update and current head.
+ * But that result may include noise commits, for instance, if you merges target
+ * branch into source branch to resolve merge conflicts, all commits in target
+ * branch will also appear in log output between last update and current update.
+ * Now, you might suggest that let's just exclude from the log output those commits
+ * being ancestor of target branch. But this still can cause issues as target branch
+ * may merge some intermediate commits from our source branch, and these
+ * intermediate commits will be ancestor of target branch. We certainly do not want
+ * to exclude these intermediate commits as it originally belongs to our source
+ * branch. To solve this contradiction, for those commits belong to both source
+ * branch and target branch, we calculate affinity score of the commit to each
+ * branch, and consider the commit to be belonging to a branch if the associated
+ * affinity score is less.
+ */
+ commits = new ArrayList<>();
+
+ Map<String, ScoreAwareCommit> allCommits = new LinkedHashMap<>();
+ for (Commit commit: getCachedInfo().getLogCommits()) {
+ ScoreAwareCommit scoreAwareCommit = new ScoreAwareCommit();
+ scoreAwareCommit.setCommit(commit);
+ allCommits.put(commit.getHash(), scoreAwareCommit);
+ }
+
+ ScoreAwareCommit headCommit = allCommits.get(getHeadCommitHash());
+ if (headCommit != null) {
+ headCommit.setScore(0);
+ updateAffinityScores(allCommits, headCommit);
+ }
+
+ Map<String, ScoreAwareCommit> mergedCommits = new HashMap<>();
+ for (Commit commit: getRequest().getMergedCommits()) {
+ ScoreAwareCommit scoredCommit = new ScoreAwareCommit();
+ scoredCommit.setCommit(commit);
+ mergedCommits.put(commit.getHash(), scoredCommit);
+ }
+
+ headCommit = mergedCommits.get(getRequest().getTarget().getObjectName());
+ if (headCommit != null) {
+ headCommit.setScore(0);
+ updateAffinityScores(mergedCommits, headCommit);
+ }
+
+ for (ScoreAwareCommit commit: allCommits.values()) {
+ ScoreAwareCommit mergedCommit = mergedCommits.get(commit.getCommit().getHash());
+ if (mergedCommit == null || mergedCommit.getScore() >= commit.getScore())
+ commits.add(commit.getCommit());
+ }
+
+ getRequest().getTargetDepot().cacheCommits(commits);
+
+ Collections.reverse(commits);
+ }
+ return commits;
+ }
+
+ public Commit getHeadCommit() {
+ Commit headCommit = getCachedInfo().getLogCommits().get(0);
+ Preconditions.checkState(headCommit.getHash().equals(getHeadCommitHash()));
+ return headCommit;
+ }
+
+ /*
+ * This method calculates affinity scores of a set of commits against specified head commit (or branch).
+ * The affinity score reflects the distance between a commit and first-parent chain of the head commit.
+ * For instance, if a commit can be reached recursively via first-parent of the head commit, its
+ * affinity score will be 0.
+ */
+ private void updateAffinityScores(Map<String, ScoreAwareCommit> commits, ScoreAwareCommit headCommit) {
+ Stack<ScoreAwareCommit> stack = new Stack<>();
+ stack.push(headCommit);
+ while (!stack.isEmpty()) {
+ ScoreAwareCommit currentCommit = stack.pop();
+ for (int i=0; i<currentCommit.getCommit().getParentHashes().size(); i++) {
+ String parentCommitHash = currentCommit.getCommit().getParentHashes().get(i);
+ ScoreAwareCommit parentCommit = commits.get(parentCommitHash);
+ if (parentCommit != null && parentCommit.getScore() == Integer.MAX_VALUE) {
+ /*
+ * Parent hashes of a commit is ordered in parent number. For instance first-parent is at index 0.
+ * So the parent score is calculated simply by adding current parent index to the head commit score.
+ */
+ parentCommit.setScore(i + currentCommit.getScore());
+ stack.push(parentCommit);
+ }
+ }
+ }
+ }
+
+ private static class ScoreAwareCommit {
+
+ private Commit commit;
+
+ private int score = Integer.MAX_VALUE;
+
+ public Commit getCommit() {
+ return commit;
+ }
+
+ public void setCommit(Commit commit) {
+ this.commit = commit;
+ }
+
+ public int getScore() {
+ return score;
+ }
+
+ public void setScore(int score) {
+ this.score = score;
+ }
+
+ }
+
+ private static class CachedInfo implements Serializable {
+
+ private Collection<String> changedFiles;
+
+ private List<Commit> logCommits;
+
+ public Collection<String> getChangedFiles() {
+ return changedFiles;
+ }
+
+ public void setChangedFiles(Collection<String> changedFiles) {
+ this.changedFiles = changedFiles;
+ }
+
+ public List<Commit> getLogCommits() {
+ return logCommits;
+ }
+
+ public void setLogCommits(List<Commit> logCommits) {
+ this.logCommits = logCommits;
+ }
+
+ }
+}
diff --git a/gitplex.core/src/main/java/com/pmease/gitplex/core/model/PullRequestVisit.java b/gitplex.core/src/main/java/com/pmease/gitplex/core/model/PullRequestVisit.java
index 613deacddc..723ce759d3 100644
--- a/gitplex.core/src/main/java/com/pmease/gitplex/core/model/PullRequestVisit.java
+++ b/gitplex.core/src/main/java/com/pmease/gitplex/core/model/PullRequestVisit.java
@@ -14,6 +14,7 @@ import com.pmease.commons.hibernate.AbstractEntity;
@SuppressWarnings("serial")
@Entity
+@Table(uniqueConstraints={@UniqueConstraint(columnNames={"g_request_id", "g_user_id"})})
public class PullRequestVisit extends AbstractEntity {
@ManyToOne(fetch=FetchType.LAZY)
diff --git a/gitplex.core/src/main/java/com/pmease/gitplex/core/model/PullRequestWatch.java b/gitplex.core/src/main/java/com/pmease/gitplex/core/model/PullRequestWatch.java
index a508df163f..f4b821df08 100644
--- a/gitplex.core/src/main/java/com/pmease/gitplex/core/model/PullRequestWatch.java
+++ b/gitplex.core/src/main/java/com/pmease/gitplex/core/model/PullRequestWatch.java
@@ -12,6 +12,9 @@ import com.pmease.commons.hibernate.AbstractEntity;
@SuppressWarnings("serial")
@Entity
+@Table(uniqueConstraints={
+ @UniqueConstraint(columnNames={"g_request_id", "g_user_id"})
+})
public class PullRequestWatch extends AbstractEntity {
@ManyToOne(fetch=FetchType.LAZY)
diff --git a/gitplex.core/src/main/java/com/pmease/gitplex/core/model/Review.java b/gitplex.core/src/main/java/com/pmease/gitplex/core/model/Review.java
index 3f9d2fd818..bb68a44f63 100644
--- a/gitplex.core/src/main/java/com/pmease/gitplex/core/model/Review.java
+++ b/gitplex.core/src/main/java/com/pmease/gitplex/core/model/Review.java
@@ -14,6 +14,9 @@ import com.pmease.commons.hibernate.AbstractEntity;
@SuppressWarnings("serial")
@Entity
+@Table(uniqueConstraints={
+ @UniqueConstraint(columnNames={"g_reviewer_id", "g_update_id"})
+})
public class Review extends AbstractEntity {
public static enum Result {APPROVE, DISAPPROVE};
diff --git a/gitplex.core/src/main/java/com/pmease/gitplex/core/model/ReviewInvitation.java b/gitplex.core/src/main/java/com/pmease/gitplex/core/model/ReviewInvitation.java
index 90e7b30be2..18c11b5f34 100644
--- a/gitplex.core/src/main/java/com/pmease/gitplex/core/model/ReviewInvitation.java
+++ b/gitplex.core/src/main/java/com/pmease/gitplex/core/model/ReviewInvitation.java
@@ -14,6 +14,9 @@ import com.pmease.commons.hibernate.AbstractEntity;
@SuppressWarnings("serial")
@Entity
+@Table(uniqueConstraints={
+ @UniqueConstraint(columnNames={"g_reviewer_id", "g_request_id"})
+})
public class ReviewInvitation extends AbstractEntity {
@ManyToOne(fetch=FetchType.LAZY)
diff --git a/gitplex.core/src/main/java/com/pmease/gitplex/core/model/Team.java b/gitplex.core/src/main/java/com/pmease/gitplex/core/model/Team.java
index b50bf3104a..68cd1f9204 100644
--- a/gitplex.core/src/main/java/com/pmease/gitplex/core/model/Team.java
+++ b/gitplex.core/src/main/java/com/pmease/gitplex/core/model/Team.java
@@ -24,6 +24,9 @@ import com.pmease.gitplex.core.permission.operation.DepotOperation;
import com.pmease.gitplex.core.util.validation.TeamName;
@Entity
+@Table(uniqueConstraints={
+ @UniqueConstraint(columnNames={"g_owner_id", "name"})
+})
@Cache(usage=CacheConcurrencyStrategy.READ_WRITE)
@SuppressWarnings("serial")
public class Team extends AbstractEntity {
diff --git a/gitplex.core/src/main/java/com/pmease/gitplex/core/model/Verification.java b/gitplex.core/src/main/java/com/pmease/gitplex/core/model/Verification.java
index 1b550458e2..0b76d551c9 100644
--- a/gitplex.core/src/main/java/com/pmease/gitplex/core/model/Verification.java
+++ b/gitplex.core/src/main/java/com/pmease/gitplex/core/model/Verification.java
@@ -12,6 +12,9 @@ import com.pmease.commons.hibernate.AbstractEntity;
@SuppressWarnings("serial")
@Entity
+@Table(uniqueConstraints={
+ @UniqueConstraint(columnNames={"g_request_id", "commit", "configuration"})
+})
public class Verification extends AbstractEntity {
public enum Status {ONGOING, PASSED, NOT_PASSED}