Skip to content

The Unified and Autonomous Development Platform

Refactor and fix some bugs of reviewer section of pull request

robin shinefa20f9cd1f4a
diff --git a/commons.wicket/src/main/java/com/pmease/commons/wicket/CommonPage.java b/commons.wicket/src/main/java/com/pmease/commons/wicket/CommonPage.java
index a93e12f5f4..d8453f6f67 100644
--- a/commons.wicket/src/main/java/com/pmease/commons/wicket/CommonPage.java
+++ b/commons.wicket/src/main/java/com/pmease/commons/wicket/CommonPage.java
@@ -1,141 +1,140 @@
-package com.pmease.commons.wicket;
-
-import static org.apache.wicket.ajax.attributes.CallbackParameter.explicit;
-
-import java.io.Serializable;
-import java.util.ArrayList;
-import java.util.Collection;
-
-import org.apache.commons.codec.binary.Base64;
-import org.apache.commons.lang3.SerializationUtils;
-import org.apache.wicket.Component;
-import org.apache.wicket.ajax.AbstractDefaultAjaxBehavior;
-import org.apache.wicket.ajax.AjaxRequestTarget;
-import org.apache.wicket.ajax.AjaxSelfUpdatingTimerBehavior;
-import org.apache.wicket.ajax.attributes.AjaxRequestAttributes;
-import org.apache.wicket.ajax.attributes.AjaxRequestAttributes.Method;
-import org.apache.wicket.core.request.handler.IPartialPageRequestHandler;
-import org.apache.wicket.markup.head.IHeaderResponse;
-import org.apache.wicket.markup.head.JavaScriptHeaderItem;
-import org.apache.wicket.markup.head.OnDomReadyHeaderItem;
-import org.apache.wicket.markup.head.PriorityHeaderItem;
-import org.apache.wicket.markup.html.WebMarkupContainer;
-import org.apache.wicket.markup.html.WebPage;
-import org.apache.wicket.markup.html.panel.FeedbackPanel;
-import org.apache.wicket.markup.repeater.RepeatingView;
-import org.apache.wicket.model.IModel;
-import org.apache.wicket.request.IRequestParameters;
-import org.apache.wicket.request.cycle.RequestCycle;
-import org.apache.wicket.request.mapper.parameter.PageParameters;
-import org.apache.wicket.util.time.Duration;
-import org.eclipse.jetty.server.SessionManager;
-
-import com.pmease.commons.loader.AppLoader;
-import com.pmease.commons.wicket.websocket.WebSocketManager;
-import com.pmease.commons.wicket.websocket.WebSocketRegion;
-
-@SuppressWarnings("serial")
-public abstract class CommonPage extends WebPage {
-
- private FeedbackPanel sessionFeedback;
-
- private RepeatingView rootComponents;
-
- public CommonPage() {
- }
-
- public CommonPage(IModel<?> model) {
- super(model);
- }
-
- public CommonPage(PageParameters params) {
- super(params);
- }
-
- @Override
- protected void onInitialize() {
- super.onInitialize();
-
- add(new AbstractDefaultAjaxBehavior() {
-
- @Override
- protected void updateAjaxAttributes(AjaxRequestAttributes attributes) {
- super.updateAjaxAttributes(attributes);
- attributes.setMethod(Method.POST);
- }
-
- @Override
- protected void respond(AjaxRequestTarget target) {
- IRequestParameters params = RequestCycle.get().getRequest().getPostParameters();
- String encodedData = params.getParameterValue("data").toString();
-
- byte[] bytes = Base64.decodeBase64(encodedData.getBytes());
- Serializable data = (Serializable) SerializationUtils.deserialize(bytes);
- onPopState(target, data);
- }
-
- @Override
- public void renderHead(Component component, IHeaderResponse response) {
- super.renderHead(component, response);
-
- String script = String.format("pmease.commons.history.init(%s);",
- getCallbackFunction(explicit("data")));
- response.render(OnDomReadyHeaderItem.forScript(script));
- }
-
- });
-
- sessionFeedback = new SessionFeedbackPanel("sessionFeedback");
- add(sessionFeedback);
- sessionFeedback.setOutputMarkupId(true);
-
- int sessionTimeout = AppLoader.getInstance(SessionManager.class).getMaxInactiveInterval();
- add(new WebMarkupContainer("keepSessionAlive").add(
- new AjaxSelfUpdatingTimerBehavior(Duration.milliseconds(sessionTimeout*500L))));
-
- add(rootComponents = new RepeatingView("rootComponents"));
- }
-
- public FeedbackPanel getSessionFeedback() {
- return sessionFeedback;
- }
-
- @Override
- protected void onBeforeRender() {
- AppLoader.getInstance(WebSocketManager.class).onRenderPage(this);
- rootComponents.removeAll();
- super.onBeforeRender();
- }
-
- public void pushState(IPartialPageRequestHandler partialPageRequestHandler, String url, Serializable data) {
- String encodedData = new String(Base64.encodeBase64(SerializationUtils.serialize(data)));
- String script = String.format("pmease.commons.history.pushState('%s', '%s');", url, encodedData);
- partialPageRequestHandler.prependJavaScript(script);
- }
-
- @Override
- public void renderHead(IHeaderResponse response) {
- super.renderHead(response);
-
- response.render(new PriorityHeaderItem(JavaScriptHeaderItem.forReference(CommonResourceReference.INSTANCE)));
- }
-
- protected void onPopState(AjaxRequestTarget target, Serializable data) {
- }
-
- public RepeatingView getRootComponents() {
- return rootComponents;
- }
-
- @Override
- protected void onAfterRender() {
- if (getWebSocketRegions() != null)
- AppLoader.getInstance(WebSocketManager.class).onRegionChange(this);
- super.onAfterRender();
- }
-
- public Collection<WebSocketRegion> getWebSocketRegions() {
- return new ArrayList<>();
- }
-
-}
+package com.pmease.commons.wicket;
+
+import static org.apache.wicket.ajax.attributes.CallbackParameter.explicit;
+
+import java.io.Serializable;
+import java.util.ArrayList;
+import java.util.Collection;
+
+import org.apache.commons.codec.binary.Base64;
+import org.apache.commons.lang3.SerializationUtils;
+import org.apache.wicket.Component;
+import org.apache.wicket.ajax.AbstractDefaultAjaxBehavior;
+import org.apache.wicket.ajax.AjaxRequestTarget;
+import org.apache.wicket.ajax.AjaxSelfUpdatingTimerBehavior;
+import org.apache.wicket.ajax.attributes.AjaxRequestAttributes;
+import org.apache.wicket.ajax.attributes.AjaxRequestAttributes.Method;
+import org.apache.wicket.core.request.handler.IPartialPageRequestHandler;
+import org.apache.wicket.markup.head.IHeaderResponse;
+import org.apache.wicket.markup.head.JavaScriptHeaderItem;
+import org.apache.wicket.markup.head.OnDomReadyHeaderItem;
+import org.apache.wicket.markup.head.PriorityHeaderItem;
+import org.apache.wicket.markup.html.WebMarkupContainer;
+import org.apache.wicket.markup.html.WebPage;
+import org.apache.wicket.markup.html.panel.FeedbackPanel;
+import org.apache.wicket.markup.repeater.RepeatingView;
+import org.apache.wicket.model.IModel;
+import org.apache.wicket.request.IRequestParameters;
+import org.apache.wicket.request.cycle.RequestCycle;
+import org.apache.wicket.request.mapper.parameter.PageParameters;
+import org.apache.wicket.util.time.Duration;
+import org.eclipse.jetty.server.SessionManager;
+
+import com.pmease.commons.loader.AppLoader;
+import com.pmease.commons.wicket.websocket.WebSocketManager;
+import com.pmease.commons.wicket.websocket.WebSocketRegion;
+
+@SuppressWarnings("serial")
+public abstract class CommonPage extends WebPage {
+
+ private FeedbackPanel sessionFeedback;
+
+ private RepeatingView rootComponents;
+
+ public CommonPage() {
+ }
+
+ public CommonPage(IModel<?> model) {
+ super(model);
+ }
+
+ public CommonPage(PageParameters params) {
+ super(params);
+ }
+
+ @Override
+ protected void onInitialize() {
+ super.onInitialize();
+
+ add(new AbstractDefaultAjaxBehavior() {
+
+ @Override
+ protected void updateAjaxAttributes(AjaxRequestAttributes attributes) {
+ super.updateAjaxAttributes(attributes);
+ attributes.setMethod(Method.POST);
+ }
+
+ @Override
+ protected void respond(AjaxRequestTarget target) {
+ IRequestParameters params = RequestCycle.get().getRequest().getPostParameters();
+ String encodedData = params.getParameterValue("data").toString();
+
+ byte[] bytes = Base64.decodeBase64(encodedData.getBytes());
+ Serializable data = (Serializable) SerializationUtils.deserialize(bytes);
+ onPopState(target, data);
+ }
+
+ @Override
+ public void renderHead(Component component, IHeaderResponse response) {
+ super.renderHead(component, response);
+
+ String script = String.format("pmease.commons.history.init(%s);",
+ getCallbackFunction(explicit("data")));
+ response.render(OnDomReadyHeaderItem.forScript(script));
+ }
+
+ });
+
+ sessionFeedback = new SessionFeedbackPanel("sessionFeedback");
+ add(sessionFeedback);
+ sessionFeedback.setOutputMarkupId(true);
+
+ int sessionTimeout = AppLoader.getInstance(SessionManager.class).getMaxInactiveInterval();
+ add(new WebMarkupContainer("keepSessionAlive").add(
+ new AjaxSelfUpdatingTimerBehavior(Duration.milliseconds(sessionTimeout*500L))));
+
+ add(rootComponents = new RepeatingView("rootComponents"));
+ }
+
+ public FeedbackPanel getSessionFeedback() {
+ return sessionFeedback;
+ }
+
+ @Override
+ protected void onBeforeRender() {
+ rootComponents.removeAll();
+ super.onBeforeRender();
+ }
+
+ public void pushState(IPartialPageRequestHandler partialPageRequestHandler, String url, Serializable data) {
+ String encodedData = new String(Base64.encodeBase64(SerializationUtils.serialize(data)));
+ String script = String.format("pmease.commons.history.pushState('%s', '%s');", url, encodedData);
+ partialPageRequestHandler.prependJavaScript(script);
+ }
+
+ @Override
+ public void renderHead(IHeaderResponse response) {
+ super.renderHead(response);
+
+ response.render(new PriorityHeaderItem(JavaScriptHeaderItem.forReference(CommonResourceReference.INSTANCE)));
+ }
+
+ protected void onPopState(AjaxRequestTarget target, Serializable data) {
+ }
+
+ public RepeatingView getRootComponents() {
+ return rootComponents;
+ }
+
+ @Override
+ protected void onAfterRender() {
+ if (getWebSocketRegions() != null)
+ AppLoader.getInstance(WebSocketManager.class).onRegionChange(this);
+ super.onAfterRender();
+ }
+
+ public Collection<WebSocketRegion> getWebSocketRegions() {
+ return new ArrayList<>();
+ }
+
+}
diff --git a/commons.wicket/src/main/java/com/pmease/commons/wicket/assets/common.css b/commons.wicket/src/main/java/com/pmease/commons/wicket/assets/common.css
index 525d173d6d..006f164d07 100644
--- a/commons.wicket/src/main/java/com/pmease/commons/wicket/assets/common.css
+++ b/commons.wicket/src/main/java/com/pmease/commons/wicket/assets/common.css
@@ -35,23 +35,22 @@
}
#session-feedback.success {
background: #DFF0D8;
- color: #3C763D;
- border-color: #D6E9C6;
+ color: #204021;
}
#session-feedback.error {
background: #F2DEDE;
color: #A94442;
- border-color: #EBCCD1;
+ border-color: #622726;
}
#session-feedback.warning {
background: #FCF8E3;
color: #8A6D3B;
- border-color: #FAEBCC;
+ border-color: #815A0D;
}
#session-feedback.info {
background: #D9EDF7;
color: #31708F;
- border-color: #BCE8F1;
+ border-color: #145562;
}
#session-feedback ul {
padding: 0; margin: 0;
diff --git a/commons.wicket/src/main/java/com/pmease/commons/wicket/behavior/dropdown/dropdown-hover.js b/commons.wicket/src/main/java/com/pmease/commons/wicket/behavior/dropdown/dropdown-hover.js
index f06ca794c9..aed1a9e3d8 100644
--- a/commons.wicket/src/main/java/com/pmease/commons/wicket/behavior/dropdown/dropdown-hover.js
+++ b/commons.wicket/src/main/java/com/pmease/commons/wicket/behavior/dropdown/dropdown-hover.js
@@ -1,70 +1,70 @@
-pmease.commons.dropdownhover = {
- init: function(triggerId, hoverDelay, openCallback) {
- var $trigger = $("#" + triggerId);
- $trigger.addClass("dropdown-hover");
-
- $trigger.data("hide", function() {
- if ($trigger.data("dropdown"))
- pmease.commons.floating.close($trigger.data("dropdown"), true);
- $trigger.data("hideTimer", null);
- });
- $trigger.data("prepareToHide", function() {
- if ($trigger.data("hideTimer"))
- clearTimeout($trigger.data("hideTimer"));
- $trigger.data("hideTimer", setTimeout(function(){
- if ($trigger.hasClass("dropdown-open"))
- $trigger.data("hide")();
- }, hoverDelay));
- });
- $trigger.data("cancelHide", function() {
- if ($trigger.data("hideTimer")) {
- clearTimeout($trigger.data("hideTimer"));
- $trigger.data("hideTimer", null);
- }
- });
- $trigger.data("cancelShow", function() {
- if ($trigger.data("showTimer")) {
- clearTimeout($trigger.data("showTimer"));
- $trigger.data("showTimer", null);
- }
- });
- $trigger.mouseover(function(mouse) {
- if (!$trigger.data("showTimer")) {
- $trigger.data("showTimer", setTimeout(function() {
- if (!$trigger.hasClass("dropdown-open")) {
- openCallback();
- $trigger.data("cancelHide")();
- }
- $trigger.data("showTimer", null);
- }, hoverDelay));
- }
- });
- $trigger.mouseout(function() {
- $trigger.data("prepareToHide")();
- $trigger.data("cancelShow")();
- });
- $trigger.mousemove(function() {
- $trigger.data("cancelHide")();
- });
- },
- opened: function(triggerId, dropdownId) {
- var $dropdown = $("#" + dropdownId);
- var $trigger = $("#" + triggerId);
- $trigger.addClass("dropdown-open");
- $trigger.data("dropdown", $dropdown);
- $dropdown.mouseover(function() {
- $trigger.data("cancelHide")();
- });
- $dropdown.mouseout(function(event) {
- if (event.pageX<$dropdown.offset().left+5 || event.pageX>$dropdown.offset().left+$dropdown.width()-5
- || event.pageY<$dropdown.offset().top+5 || event.pageY>$dropdown.offset().top+$dropdown.height()-5) {
- $trigger.data("prepareToHide")();
- }
- });
- },
- closed: function(triggerId, dropdownId) {
- var $trigger = $("#" + triggerId);
- $trigger.removeClass("dropdown-open");
- $trigger.data("dropdown", null);
- }
+pmease.commons.dropdownhover = {
+ init: function(triggerId, hoverDelay, openCallback) {
+ var $trigger = $("#" + triggerId);
+ $trigger.addClass("dropdown-hover");
+
+ $trigger.data("hide", function() {
+ if ($trigger.data("dropdown"))
+ pmease.commons.floating.close($trigger.data("dropdown"), true);
+ $trigger.data("hideTimer", null);
+ });
+ $trigger.data("prepareToHide", function() {
+ if ($trigger.data("hideTimer"))
+ clearTimeout($trigger.data("hideTimer"));
+ $trigger.data("hideTimer", setTimeout(function(){
+ if ($trigger.hasClass("dropdown-open"))
+ $trigger.data("hide")();
+ }, hoverDelay));
+ });
+ $trigger.data("cancelHide", function() {
+ if ($trigger.data("hideTimer")) {
+ clearTimeout($trigger.data("hideTimer"));
+ $trigger.data("hideTimer", null);
+ }
+ });
+ $trigger.data("cancelShow", function() {
+ if ($trigger.data("showTimer")) {
+ clearTimeout($trigger.data("showTimer"));
+ $trigger.data("showTimer", null);
+ }
+ });
+ $trigger.mouseover(function(mouse) {
+ if (!$trigger.data("showTimer")) {
+ $trigger.data("showTimer", setTimeout(function() {
+ if (!$trigger.hasClass("dropdown-open")) {
+ openCallback();
+ $trigger.data("cancelHide")();
+ }
+ $trigger.data("showTimer", null);
+ }, hoverDelay));
+ }
+ });
+ $trigger.mouseout(function() {
+ $trigger.data("prepareToHide")();
+ $trigger.data("cancelShow")();
+ });
+ $trigger.mousemove(function() {
+ $trigger.data("cancelHide")();
+ });
+ },
+ opened: function(triggerId, dropdownId) {
+ var $dropdown = $("#" + dropdownId);
+ var $trigger = $("#" + triggerId);
+ $trigger.addClass("dropdown-open");
+ $trigger.data("dropdown", $dropdown);
+ $dropdown.mouseover(function() {
+ $trigger.data("cancelHide")();
+ });
+ $dropdown.mouseout(function(event) {
+ if (event.pageX<$dropdown.offset().left+5 || event.pageX>$dropdown.offset().left+$dropdown.width()-5
+ || event.pageY<$dropdown.offset().top+5 || event.pageY>$dropdown.offset().top+$dropdown.height()-5) {
+ $trigger.data("prepareToHide")();
+ }
+ });
+ },
+ closed: function(triggerId, dropdownId) {
+ var $trigger = $("#" + triggerId);
+ $trigger.removeClass("dropdown-open");
+ $trigger.data("dropdown", null);
+ }
}
\ No newline at end of file
diff --git a/commons.wicket/src/main/java/com/pmease/commons/wicket/websocket/DefaultWebSocketManager.java b/commons.wicket/src/main/java/com/pmease/commons/wicket/websocket/DefaultWebSocketManager.java
index 8d350c7b5e..0af3d60dd4 100644
--- a/commons.wicket/src/main/java/com/pmease/commons/wicket/websocket/DefaultWebSocketManager.java
+++ b/commons.wicket/src/main/java/com/pmease/commons/wicket/websocket/DefaultWebSocketManager.java
@@ -1,14 +1,10 @@
package com.pmease.commons.wicket.websocket;
import java.io.IOException;
-import java.util.ArrayList;
import java.util.Collection;
-import java.util.Date;
import java.util.Iterator;
import java.util.Map;
-import java.util.Queue;
import java.util.concurrent.ConcurrentHashMap;
-import java.util.concurrent.ConcurrentLinkedQueue;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
@@ -23,7 +19,6 @@ import org.apache.wicket.protocol.ws.api.IWebSocketConnection;
import org.apache.wicket.protocol.ws.api.registry.IWebSocketConnectionRegistry;
import org.apache.wicket.protocol.ws.api.registry.SimpleWebSocketConnectionRegistry;
import org.eclipse.jetty.websocket.api.WebSocketPolicy;
-import org.joda.time.DateTime;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
@@ -42,16 +37,10 @@ public class DefaultWebSocketManager implements WebSocketManager {
private final WebSocketPolicy webSocketPolicy;
- private final int WEBSOCKET_TOLERENCE = 5;
-
private final Map<PageKey, Collection<WebSocketRegion>> regions = new ConcurrentHashMap<>();
private final IWebSocketConnectionRegistry connectionRegistry = new SimpleWebSocketConnectionRegistry();
- private final Map<PageKey, Date> recentRenderedPages = new ConcurrentHashMap<>();
-
- private final Queue<RecentRenderRequest> recentRenderRequests = new ConcurrentLinkedQueue<>();
-
@Inject
public DefaultWebSocketManager(Application application,
ExecutorService executorService, WebSocketPolicy webSocketPolicy) {
@@ -96,8 +85,6 @@ public class DefaultWebSocketManager implements WebSocketManager {
connection.sendMessage(RENDER_CALLBACK);
}
}
-
- recentRenderRequests.add(new RecentRenderRequest(region, sourcePageKey, new Date()));
} catch (Exception e) {
logger.error("Error sending websocket message", e);
}
@@ -118,57 +105,12 @@ public class DefaultWebSocketManager implements WebSocketManager {
@Override
public void onConnect(WebSocketConnection connection) {
- /*
- * When a new websocket connection arrives, we re-send all sent websocket messages since
- * rendering of its hosting page as otherwise the host page might be missing some
- * important websocket messages. For instance, when a pull request is opened, a pull
- * request integration preview is calculating in the background, and the request page
- * will be rendered, and then a websocket connection is established after browser renders
- * the page. If integration preview calculation finishes after rendering of the request
- * detail page and before websocket establishing of request detail page, the integration
- * preview area of the page will not be refreshed without below code as it will miss the
- * websocket message sent upon completion of integration preview.
- *
- */
- PageKey connectionPageKey = connection.getPageKey();
- Date renderDate = recentRenderedPages.get(connectionPageKey);
- if (renderDate != null) {
- Collection<String> messagesToSend = new ArrayList<>();
- for (RecentRenderRequest request: recentRenderRequests) {
- WebSocketRegion region = request.getRegion();
- if (request.getDate().getTime() > renderDate.getTime()
- && containsRegion(connection, region)) {
- PageKey sourcePageKey = request.getSourcePageKey();
- if (sourcePageKey == null || !sourcePageKey.equals(connectionPageKey)) {
- messagesToSend.add(RENDER_CALLBACK);
- }
- }
- }
-
- if (!messagesToSend.isEmpty()) {
- executorService.execute(new Runnable() {
-
- @Override
- public void run() {
- for (String message: messagesToSend) {
- try {
- connection.sendMessage(message);
- } catch (IOException e) {
- logger.error("Error sending websocket message");
- }
- }
- }
-
- });
- }
+ try {
+ connection.sendMessage(RENDER_CALLBACK);
+ } catch (IOException e) {
}
}
- @Override
- public void onRenderPage(CommonPage page) {
- recentRenderedPages.put(new PageKey(page), new Date());
- }
-
@Override
public void start() {
scheduledExecutorService.scheduleWithFixedDelay(new Runnable() {
@@ -187,24 +129,6 @@ public class DefaultWebSocketManager implements WebSocketManager {
}
}, 0, webSocketPolicy.getIdleTimeout()/2, TimeUnit.MILLISECONDS);
-
- scheduledExecutorService.scheduleWithFixedDelay(new Runnable() {
-
- @Override
- public void run() {
- Date tillDate = new DateTime().minusMinutes(WEBSOCKET_TOLERENCE).toDate();
- for (Iterator<Map.Entry<PageKey, Date>> it = recentRenderedPages.entrySet().iterator(); it.hasNext();) {
- Map.Entry<PageKey, Date> entry = it.next();
- if (entry.getValue().getTime() < tillDate.getTime())
- it.remove();
- }
- for (Iterator<RecentRenderRequest> it = recentRenderRequests.iterator(); it.hasNext();) {
- if (it.next().getDate().getTime() < tillDate.getTime())
- it.remove();
- }
- }
-
- }, 0, WEBSOCKET_TOLERENCE, TimeUnit.MINUTES);
}
@Override
diff --git a/commons.wicket/src/main/java/com/pmease/commons/wicket/websocket/WebSocketManager.java b/commons.wicket/src/main/java/com/pmease/commons/wicket/websocket/WebSocketManager.java
index 4deea55680..de0b5997c5 100644
--- a/commons.wicket/src/main/java/com/pmease/commons/wicket/websocket/WebSocketManager.java
+++ b/commons.wicket/src/main/java/com/pmease/commons/wicket/websocket/WebSocketManager.java
@@ -14,8 +14,6 @@ public interface WebSocketManager {
void onRegionChange(CommonPage page);
- void onRenderPage(CommonPage page);
-
void onDestroySession(String sessionId);
void onConnect(WebSocketConnection connection);
diff --git a/gitplex.core/src/main/java/com/pmease/gitplex/core/entity/PullRequest.java b/gitplex.core/src/main/java/com/pmease/gitplex/core/entity/PullRequest.java
index bb17618d7e..67accffdcd 100644
--- a/gitplex.core/src/main/java/com/pmease/gitplex/core/entity/PullRequest.java
+++ b/gitplex.core/src/main/java/com/pmease/gitplex/core/entity/PullRequest.java
@@ -1,1015 +1,1009 @@
-package com.pmease.gitplex.core.entity;
-
-import java.io.IOException;
-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.HashSet;
-import java.util.List;
-import java.util.Map;
-import java.util.Set;
-import java.util.UUID;
-import java.util.stream.Collectors;
-
-import javax.annotation.Nullable;
-import javax.persistence.CascadeType;
-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.Table;
-import javax.persistence.UniqueConstraint;
-import javax.persistence.Version;
-
-import org.apache.commons.lang3.StringUtils;
-import org.eclipse.jgit.lib.ObjectId;
-import org.eclipse.jgit.revwalk.RevCommit;
-import org.eclipse.jgit.revwalk.RevWalk;
-import org.hibernate.annotations.DynamicUpdate;
-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.GitUtils;
-import com.pmease.commons.hibernate.AbstractEntity;
-import com.pmease.commons.hibernate.dao.Dao;
-import com.pmease.commons.jackson.ExternalView;
-import com.pmease.commons.lang.diff.WhitespaceOption;
-import com.pmease.gitplex.core.GitPlex;
-import com.pmease.gitplex.core.entity.support.CloseInfo;
-import com.pmease.gitplex.core.entity.support.CompareContext;
-import com.pmease.gitplex.core.entity.support.DepotAndBranch;
-import com.pmease.gitplex.core.entity.support.IntegrationPreview;
-import com.pmease.gitplex.core.entity.support.LastEvent;
-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.CodeCommentRelationManager;
-import com.pmease.gitplex.core.manager.PullRequestManager;
-import com.pmease.gitplex.core.manager.PullRequestReviewManager;
-import com.pmease.gitplex.core.manager.VisitInfoManager;
-import com.pmease.gitplex.core.security.ObjectPermission;
-import com.pmease.gitplex.core.security.SecurityUtils;
-
-@Entity
-/*
- * @DynamicUpdate annotation here along with various @OptimisticLock annotations
- * on certain fields tell Hibernate not to perform version check on those fields
- * which can be updated from background thread.
- */
-@DynamicUpdate
-@Table(indexes={@Index(columnList="title"), @Index(columnList="uuid"), @Index(columnList="numberStr"), @Index(columnList="noSpaceTitle")},
- uniqueConstraints={@UniqueConstraint(columnNames={"g_targetdepot_id", "number"})})
-public class PullRequest extends AbstractEntity {
-
- private static final long serialVersionUID = 1L;
-
- public static final int MAX_CODE_COMMENTS = 1000;
-
- 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;
- }
-
- }
-
- @Embedded
- private CloseInfo closeInfo;
-
- @Column(nullable=false)
- private String title;
-
- @Lob
- @Column(length=65535)
- private String description;
-
- @ManyToOne(fetch=FetchType.LAZY)
- private Account submitter;
-
- @ManyToOne(fetch=FetchType.LAZY)
- @JoinColumn(nullable=false)
- private Depot targetDepot;
-
- @Column(nullable=false)
- private String targetBranch;
-
- @ManyToOne(fetch=FetchType.LAZY)
- private Depot sourceDepot;
-
- @Column(nullable=false)
- private String sourceBranch;
-
- @Column(nullable=false)
- private String baseCommitHash;
-
- @ManyToOne(fetch=FetchType.LAZY)
- private Account assignee;
-
- @Embedded
- private LastEvent lastEvent;
-
- @Column(nullable=true)
- private Date lastCodeCommentEventDate;
-
- // used for number search in markdown editor
- @Column(nullable=false)
- private String numberStr;
-
- // used for title search in markdown editor
- @Column(nullable=false)
- private String noSpaceTitle;
-
- @Version
- private long version;
-
- @OptimisticLock(excluded=true)
- @Embedded
- private IntegrationPreview lastIntegrationPreview;
-
- @Column(nullable=false)
- private Date submitDate = new Date();
-
- @Column(nullable=false)
- private IntegrationStrategy integrationStrategy;
-
- @Column(nullable=false)
- private String uuid = UUID.randomUUID().toString();
-
- private long number;
-
- @OneToMany(mappedBy="request", cascade=CascadeType.REMOVE)
- private Collection<PullRequestUpdate> updates = new ArrayList<>();
-
- @OneToMany(mappedBy="request", cascade=CascadeType.REMOVE)
- private Collection<CodeCommentRelation> codeCommentRelations = new ArrayList<>();
-
- @OneToMany(mappedBy="request", cascade=CascadeType.REMOVE)
- private Collection<PullRequestReviewInvitation> reviewInvitations = new ArrayList<>();
-
- @OneToMany(mappedBy="referenced", cascade=CascadeType.REMOVE)
- private Collection<PullRequestReference> referencedBy = new ArrayList<>();
-
- @OneToMany(mappedBy="referencedBy",cascade=CascadeType.REMOVE)
- private Collection<PullRequestReference> referenced = new ArrayList<>();
-
- @OneToMany(mappedBy="request", cascade=CascadeType.REMOVE)
- private Collection<PullRequestVerification> verifications = new ArrayList<>();
-
- @OneToMany(mappedBy="request", cascade=CascadeType.REMOVE)
- private Collection<PullRequestComment> comments = new ArrayList<>();
-
- @OneToMany(mappedBy="request", cascade=CascadeType.REMOVE)
- private Collection<PullRequestStatusChange> statusChanges = new ArrayList<>();
-
- @OneToMany(mappedBy="request", cascade=CascadeType.REMOVE)
- private Collection<PullRequestNotification> notifications = new ArrayList<>();
-
- @OneToMany(mappedBy="request", cascade=CascadeType.REMOVE)
- 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 Collection<RevCommit> pendingCommits;
-
- private transient Collection<RevCommit> mergedCommits;
-
- private transient List<PullRequestReview> reviews;
-
- private transient IntegrationPreview integrationPreview;
-
- private transient List<CodeComment> codeComments;
-
- /**
- * Get title of this merge request.
- *
- * @return user specified title of this merge request, <tt>null</tt> for
- * auto-created merge request.
- */
- public @Nullable String getTitle() {
- return title;
- }
-
- public void setTitle(String title) {
- this.title = title;
- noSpaceTitle = StringUtils.deleteWhitespace(title);
- }
-
- public String getDescription() {
- return description;
- }
-
- public void setDescription(String description) {
- this.description = description;
- }
-
- /**
- * Get the user submitting the pull request.
- *
- * @return
- * the user submitting the pull request, or <tt>null</tt> if unknown
- */
- @Nullable
- public Account getSubmitter() {
- return submitter;
- }
-
- public void setSubmitter(@Nullable Account submitter) {
- this.submitter = submitter;
- }
-
- /**
- * Get the user responsible for integration of the pull request.
- *
- * @return
- * the user responsible for integration of this pull request, or <tt>null</tt> to have the
- * system integrate the pull request automatically
- */
- @Nullable
- public Account getAssignee() {
- return assignee;
- }
-
- public void setAssignee(Account assignee) {
- this.assignee = assignee;
- }
-
- public Depot getTargetDepot() {
- return targetDepot;
- }
-
- public DepotAndBranch getTarget() {
- return new DepotAndBranch(getTargetDepot(), getTargetBranch());
- }
-
- public void setTarget(DepotAndBranch target) {
- setTargetDepot(target.getDepot());
- setTargetBranch(target.getBranch());
- }
-
- public void setSource(DepotAndBranch source) {
- setSourceDepot(source.getDepot());
- setSourceBranch(source.getBranch());
- }
-
- public void setTargetDepot(Depot targetDepot) {
- this.targetDepot = targetDepot;
- }
-
- public String getTargetBranch() {
- return targetBranch;
- }
-
- public void setTargetBranch(String targetBranch) {
- this.targetBranch = targetBranch;
- }
-
- @Nullable
- public Depot getSourceDepot() {
- return sourceDepot;
- }
-
- public void setSourceDepot(Depot sourceDepot) {
- this.sourceDepot = sourceDepot;
- }
-
- public String getSourceBranch() {
- return sourceBranch;
- }
-
- public void setSourceBranch(String sourceBranch) {
- this.sourceBranch = sourceBranch;
- }
-
- public DepotAndBranch getSource() {
- return new DepotAndBranch(getSourceDepot(), getSourceBranch());
- }
-
- public String getTargetRef() {
- return GitUtils.branch2ref(getTargetBranch());
- }
-
- public String getSourceRef() {
- return GitUtils.branch2ref(getSourceBranch());
- }
-
- public String getBaseCommitHash() {
- return baseCommitHash;
- }
-
- public void setBaseCommitHash(String baseCommitHash) {
- this.baseCommitHash = baseCommitHash;
- }
-
- public RevCommit getBaseCommit() {
- return getTargetDepot().getRevCommit(ObjectId.fromString(getBaseCommitHash()));
- }
-
- /**
- * 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<CodeCommentRelation> getCodeCommentRelations() {
- return codeCommentRelations;
- }
-
- public void setCodeCommentRelations(Collection<CodeCommentRelation> codeCommentRelations) {
- this.codeCommentRelations = codeCommentRelations;
- }
-
- public Collection<PullRequestReviewInvitation> getReviewInvitations() {
- return reviewInvitations;
- }
-
- public void setReviewInvitations(Collection<PullRequestReviewInvitation> reviewInvitations) {
- this.reviewInvitations = reviewInvitations;
- }
-
- public Collection<PullRequestVerification> getVerifications() {
- return verifications;
- }
-
- public void setVerifications(Collection<PullRequestVerification> verifications) {
- this.verifications = verifications;
- }
-
- public Collection<PullRequestReference> getReferencedBy() {
- return referencedBy;
- }
-
- public void setReferencedBy(Collection<PullRequestReference> referencedBy) {
- this.referencedBy = referencedBy;
- }
-
- public Collection<PullRequestReference> getReferenced() {
- return referenced;
- }
-
- public void setReferenced(Collection<PullRequestReference> referenced) {
- this.referenced = referenced;
- }
-
- public Collection<PullRequestComment> getComments() {
- return comments;
- }
-
- public void setComments(Collection<PullRequestComment> comments) {
- this.comments = comments;
- }
-
- public Collection<PullRequestStatusChange> getStatusChanges() {
- return statusChanges;
- }
-
- public void setStatusChanges(Collection<PullRequestStatusChange> statusChanges) {
- this.statusChanges = statusChanges;
- }
-
- public Collection<PullRequestNotification> getNotifications() {
- return notifications;
- }
-
- public void setNotifications(Collection<PullRequestNotification> notifications) {
- this.notifications = notifications;
- }
-
- 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() {
- if (integrationPreview == null)
- integrationPreview = GitPlex.getInstance(PullRequestManager.class).previewIntegration(this);
- return integrationPreview;
- }
-
- /**
- * 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().isMergedInto(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);
- }
-
- @JsonView(ExternalView.class)
- public String getBaseRef() {
- Preconditions.checkNotNull(getId());
- return Depot.REFS_GITPLEX + "pulls/" + getNumber() + "/base";
- }
-
- @JsonView(ExternalView.class)
- public String getIntegrateRef() {
- Preconditions.checkNotNull(getId());
- return Depot.REFS_GITPLEX + "pulls/" + getNumber() + "/integrate";
- }
-
- /**
- * Delete refs of this pull request, without touching refs of its updates.
- */
- public void deleteRefs() {
- GitUtils.deleteRef(getTargetDepot().updateRef(getBaseRef()));
- GitUtils.deleteRef(getTargetDepot().updateRef(getIntegrateRef()));
- }
-
- /**
- * Invite specified number of users in candidates to review this request.
- * <p>
- *
- * @param candidates
- * a collection of users to invite users from
- * @param count
- * number of users to invite
- */
- public void pickReviewers(Collection<Account> candidates, int count) {
- List<Account> pickList = new ArrayList<Account>(candidates);
-
- /*
- * users already reviewed since base update should be excluded from
- * invitation list as their reviews are still valid
- */
- for (PullRequestReview review: getReferentialUpdate().listReviewsOnwards())
- pickList.remove(review.getUser());
-
- final Map<Account, Date> firstChoices = new HashMap<>();
- final Map<Account, Date> secondChoices = new HashMap<>();
-
- for (PullRequestReviewInvitation invitation: getReviewInvitations()) {
- if (invitation.isPreferred())
- firstChoices.put(invitation.getUser(), invitation.getDate());
- else
- secondChoices.put(invitation.getUser(), invitation.getDate());
- }
-
- // submitter is not preferred
- if (getSubmitter() != null)
- secondChoices.put(getSubmitter(), new Date());
-
- /* Follow below rules to pick reviewers:
- * 1. If user is excluded previously, it will be considered last.
- * 2. If user is already a reviewer, it will be considered first.
- * 3. Otherwise pick user with least reviews.
- */
- pickList.sort((user1, user2) -> {
- if (firstChoices.containsKey(user1)) {
- if (firstChoices.containsKey(user2))
- return user1.getReviewEffort() - user2.getReviewEffort();
- else
- return -1;
- } else if (firstChoices.containsKey(user2)) {
- return 1;
- } else if (secondChoices.containsKey(user1)) {
- if (secondChoices.containsKey(user2))
- return secondChoices.get(user1).compareTo(secondChoices.get(user2));
- else
- return 1;
- } else if (secondChoices.containsKey(user2)) {
- return -1;
- } else {
- return user1.getReviewEffort() - user2.getReviewEffort();
- }
- });
-
- List<Account> picked;
- if (count <= pickList.size())
- picked = pickList.subList(0, count);
- else
- picked = pickList;
-
- for (Account user: picked) {
- boolean found = false;
- for (PullRequestReviewInvitation invitation: getReviewInvitations()) {
- if (invitation.getUser().equals(user)) {
- invitation.setDate(new Date());
- invitation.setPerferred(true);
- found = true;
- }
- }
- if (!found) {
- PullRequestReviewInvitation invitation = new PullRequestReviewInvitation();
- invitation.setRequest(this);
- invitation.setUser(user);
- getReviewInvitations().add(invitation);
- }
- }
-
- }
-
- public static class CriterionHelper {
- public static Criterion ofOpen() {
- return Restrictions.isNull("closeInfo");
- }
-
- public static Criterion ofClosed() {
- return Restrictions.isNotNull("closeInfo");
- }
-
- public static Criterion ofTarget(DepotAndBranch target) {
- return Restrictions.and(
- Restrictions.eq("targetDepot", target.getDepot()),
- Restrictions.eq("targetBranch", target.getBranch()));
- }
-
- public static Criterion ofTargetDepot(Depot target) {
- return Restrictions.eq("targetDepot", target);
- }
-
- public static Criterion ofSource(DepotAndBranch source) {
- return Restrictions.and(
- Restrictions.eq("sourceDepot", source.getDepot()),
- Restrictions.eq("sourceBranch", source.getBranch()));
- }
-
- public static Criterion ofSourceDepot(Depot source) {
- return Restrictions.eq("sourceDepot", source);
- }
-
- public static Criterion ofSubmitter(Account submitter) {
- return Restrictions.eq("submitter", submitter);
- }
-
- }
-
- public Date getSubmitDate() {
- return submitDate;
- }
-
- public void setSubmitDate(Date submitDate) {
- this.submitDate = submitDate;
- }
-
- /**
- * Get commits pending integration.
- *
- * @return
- * commits pending integration
- */
- public Collection<RevCommit> getPendingCommits() {
- if (pendingCommits == null) {
- pendingCommits = new HashSet<>();
- Depot depot = getTargetDepot();
- try (RevWalk revWalk = new RevWalk(depot.getRepository())) {
- revWalk.markStart(revWalk.parseCommit(ObjectId.fromString(getLatestUpdate().getHeadCommitHash())));
- revWalk.markUninteresting(revWalk.parseCommit(ObjectId.fromString(getTarget().getObjectName())));
- revWalk.forEach(c->pendingCommits.add(c));
- } catch (IOException e) {
- throw new RuntimeException(e);
- }
- }
- return pendingCommits;
- }
-
- /**
- * Merged commits represent commits already merged to target branch since base commit.
- *
- * @return
- * commits already merged to target branch since base commit
- */
- public Collection<RevCommit> getMergedCommits() {
- if (mergedCommits == null) {
- mergedCommits = new HashSet<>();
- Depot depot = getTargetDepot();
- try (RevWalk revWalk = new RevWalk(depot.getRepository())) {
- revWalk.markStart(revWalk.parseCommit(ObjectId.fromString(getTarget().getObjectName())));
- revWalk.markUninteresting(revWalk.parseCommit(ObjectId.fromString(getBaseCommitHash())));
- revWalk.forEach(c->mergedCommits.add(c));
- } catch (IOException e) {
- throw new RuntimeException(e);
- }
- }
- return mergedCommits;
- }
-
- public List<PullRequestReview> getReviews() {
- if (reviews == null) {
- if (!isNew())
- reviews = GitPlex.getInstance(PullRequestReviewManager.class).findAll(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<PullRequestReview> getReviews(PullRequestUpdate update) {
- List<PullRequestReview> reviews = new ArrayList<>();
- for (PullRequestReview review: getReviews()) {
- if (review.getUpdate().equals(update))
- reviews.add(review);
- }
- return reviews;
- }
-
- public boolean isReviewEffective(Account user) {
- for (PullRequestReview review: getReviews()) {
- if (review.getUpdate().equals(getLatestUpdate()) && review.getUser().equals(user))
- return true;
- }
- return false;
- }
-
- /**
- * Calculate list of users can be added as reviewers of this pull request.
- *
- * @return
- * list of potential reviewers
- */
- public List<Account> getPotentialReviewers() {
- List<Account> reviewers = new ArrayList<>();
- Set<Account> alreadyInvited = new HashSet<>();
- for (PullRequestReviewInvitation invitation: getReviewInvitations()) {
- if (invitation.isPreferred())
- alreadyInvited.add(invitation.getUser());
- }
- ObjectPermission readPerm = ObjectPermission.ofDepotRead(getTargetDepot());
- for (Account user: GitPlex.getInstance(Dao.class).findAll(Account.class)) {
- if (user.asSubject().isPermitted(readPerm) && !alreadyInvited.contains(user))
- reviewers.add(user);
- }
- return reviewers;
- }
-
- @Nullable
- public PullRequestWatch getWatch(Account user) {
- for (PullRequestWatch watch: getWatches()) {
- if (watch.getUser().equals(user))
- return watch;
- }
- return null;
- }
-
- public String getNumberStr() {
- return numberStr;
- }
-
- public String getNoSpaceTitle() {
- return noSpaceTitle;
- }
-
- public long getVersion() {
- return version;
- }
-
- public String getUUID() {
- return uuid;
- }
-
- public void setUUID(String uuid) {
- this.uuid = uuid;
- }
-
- public long getNumber() {
- return number;
- }
-
- public void setNumber(long number) {
- this.number = number;
- numberStr = String.valueOf(number);
- }
-
- public List<CodeComment> getCodeComments() {
- if (codeComments == null) {
- codeComments = GitPlex.getInstance(CodeCommentRelationManager.class).findAllCodeComments(this);
- }
- return codeComments;
- }
-
- @Nullable
- public ComparingInfo getRequestComparingInfo(CodeComment.ComparingInfo commentComparingInfo) {
- List<String> commits = new ArrayList<>();
- commits.add(getBaseCommitHash());
- for (PullRequestUpdate update: getSortedUpdates()) {
- commits.addAll(update.getCommits().stream().map(RevCommit::getName).collect(Collectors.toList()));
- }
- String commit = commentComparingInfo.getCommit();
- CompareContext compareContext = commentComparingInfo.getCompareContext();
- if (commit.equals(compareContext.getCompareCommit())) {
- int index = commits.indexOf(commit);
- if (index == 0) {
- return null;
- } else {
- return new ComparingInfo(commits.get(index-1), commit,
- compareContext.getWhitespaceOption(), compareContext.getPathFilter());
- }
- } else {
- int commitIndex = commits.indexOf(commit);
- int compareCommitIndex = commits.indexOf(compareContext.getCompareCommit());
- if (commitIndex == -1 || compareCommitIndex == -1) {
- return null;
- } else if (compareContext.isLeftSide()) {
- if (compareCommitIndex < commitIndex) {
- return new ComparingInfo(compareContext.getCompareCommit(), commit,
- compareContext.getWhitespaceOption(), compareContext.getPathFilter());
- } else {
- return null;
- }
- } else {
- if (commitIndex < compareCommitIndex) {
- return new ComparingInfo(commit, compareContext.getCompareCommit(),
- compareContext.getWhitespaceOption(), compareContext.getPathFilter());
- } else {
- return null;
- }
- }
- }
- }
-
- public List<RevCommit> getCommits() {
- List<RevCommit> commits = new ArrayList<>();
- getSortedUpdates().forEach(update->commits.addAll(update.getCommits()));
- return commits;
- }
-
- public String getCommitMessage() {
- String commitMessage = getTitle() + "\n\n";
- if (getDescription() != null)
- commitMessage += getDescription() + "\n\n";
- commitMessage += "This commit is created as result of integrating pull request #" + getNumber();
- return commitMessage;
- }
-
- public LastEvent getLastEvent() {
- return lastEvent;
- }
-
- public void setLastEvent(LastEvent lastEvent) {
- this.lastEvent = lastEvent;
- }
-
- public Date getLastCodeCommentEventDate() {
- return lastCodeCommentEventDate;
- }
-
- public void setLastCodeCommentEventDate(Date lastCodeCommentEventDate) {
- this.lastCodeCommentEventDate = lastCodeCommentEventDate;
- }
-
- public boolean isVisitedAfter(Date date) {
- Account user = SecurityUtils.getAccount();
- if (user != null) {
- Date visitDate = GitPlex.getInstance(VisitInfoManager.class).getVisitDate(user, this);
- return visitDate != null && visitDate.getTime()>date.getTime();
- } else {
- return true;
- }
- }
-
- public boolean isMerged() {
- return getTargetDepot().isMergedInto(
- getLatestUpdate().getHeadCommitHash(),
- getTarget().getObjectName());
- }
-
- public static class ComparingInfo implements Serializable {
-
- private static final long serialVersionUID = 1L;
-
- private final String oldCommit;
-
- private final String newCommit;
-
- private final String pathFilter;
-
- private final WhitespaceOption whitespaceOption;
-
- public ComparingInfo(String oldCommit, String newCommit, WhitespaceOption whitespaceOption, @Nullable String pathFilter) {
- this.oldCommit = oldCommit;
- this.newCommit = newCommit;
- this.whitespaceOption = whitespaceOption;
- this.pathFilter = pathFilter;
- }
-
- public String getOldCommit() {
- return oldCommit;
- }
-
- public String getNewCommit() {
- return newCommit;
- }
-
- public String getPathFilter() {
- return pathFilter;
- }
-
- public WhitespaceOption getWhitespaceOption() {
- return whitespaceOption;
- }
-
- }
-}
+package com.pmease.gitplex.core.entity;
+
+import java.io.IOException;
+import java.io.Serializable;
+import java.util.ArrayList;
+import java.util.Collection;
+import java.util.Collections;
+import java.util.Comparator;
+import java.util.Date;
+import java.util.HashSet;
+import java.util.List;
+import java.util.Set;
+import java.util.UUID;
+import java.util.stream.Collectors;
+
+import javax.annotation.Nullable;
+import javax.persistence.CascadeType;
+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.Table;
+import javax.persistence.UniqueConstraint;
+import javax.persistence.Version;
+
+import org.apache.commons.lang3.StringUtils;
+import org.eclipse.jgit.lib.ObjectId;
+import org.eclipse.jgit.revwalk.RevCommit;
+import org.eclipse.jgit.revwalk.RevWalk;
+import org.hibernate.annotations.DynamicUpdate;
+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.GitUtils;
+import com.pmease.commons.hibernate.AbstractEntity;
+import com.pmease.commons.hibernate.dao.Dao;
+import com.pmease.commons.jackson.ExternalView;
+import com.pmease.commons.lang.diff.WhitespaceOption;
+import com.pmease.gitplex.core.GitPlex;
+import com.pmease.gitplex.core.entity.support.CloseInfo;
+import com.pmease.gitplex.core.entity.support.CompareContext;
+import com.pmease.gitplex.core.entity.support.DepotAndBranch;
+import com.pmease.gitplex.core.entity.support.IntegrationPreview;
+import com.pmease.gitplex.core.entity.support.LastEvent;
+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.CodeCommentRelationManager;
+import com.pmease.gitplex.core.manager.PullRequestManager;
+import com.pmease.gitplex.core.manager.PullRequestReviewManager;
+import com.pmease.gitplex.core.manager.VisitInfoManager;
+import com.pmease.gitplex.core.security.ObjectPermission;
+import com.pmease.gitplex.core.security.SecurityUtils;
+
+@Entity
+/*
+ * @DynamicUpdate annotation here along with various @OptimisticLock annotations
+ * on certain fields tell Hibernate not to perform version check on those fields
+ * which can be updated from background thread.
+ */
+@DynamicUpdate
+@Table(indexes={@Index(columnList="title"), @Index(columnList="uuid"), @Index(columnList="numberStr"), @Index(columnList="noSpaceTitle")},
+ uniqueConstraints={@UniqueConstraint(columnNames={"g_targetdepot_id", "number"})})
+public class PullRequest extends AbstractEntity {
+
+ private static final long serialVersionUID = 1L;
+
+ public static final int MAX_CODE_COMMENTS = 1000;
+
+ 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;
+ }
+
+ }
+
+ @Embedded
+ private CloseInfo closeInfo;
+
+ @Column(nullable=false)
+ private String title;
+
+ @Lob
+ @Column(length=65535)
+ private String description;
+
+ @ManyToOne(fetch=FetchType.LAZY)
+ private Account submitter;
+
+ @ManyToOne(fetch=FetchType.LAZY)
+ @JoinColumn(nullable=false)
+ private Depot targetDepot;
+
+ @Column(nullable=false)
+ private String targetBranch;
+
+ @ManyToOne(fetch=FetchType.LAZY)
+ private Depot sourceDepot;
+
+ @Column(nullable=false)
+ private String sourceBranch;
+
+ @Column(nullable=false)
+ private String baseCommitHash;
+
+ @ManyToOne(fetch=FetchType.LAZY)
+ private Account assignee;
+
+ @Embedded
+ private LastEvent lastEvent;
+
+ @Column(nullable=true)
+ private Date lastCodeCommentEventDate;
+
+ // used for number search in markdown editor
+ @Column(nullable=false)
+ private String numberStr;
+
+ // used for title search in markdown editor
+ @Column(nullable=false)
+ private String noSpaceTitle;
+
+ @Version
+ private long version;
+
+ @OptimisticLock(excluded=true)
+ @Embedded
+ private IntegrationPreview lastIntegrationPreview;
+
+ @Column(nullable=false)
+ private Date submitDate = new Date();
+
+ @Column(nullable=false)
+ private IntegrationStrategy integrationStrategy;
+
+ @Column(nullable=false)
+ private String uuid = UUID.randomUUID().toString();
+
+ private long number;
+
+ @OneToMany(mappedBy="request", cascade=CascadeType.REMOVE)
+ private Collection<PullRequestUpdate> updates = new ArrayList<>();
+
+ @OneToMany(mappedBy="request", cascade=CascadeType.REMOVE)
+ private Collection<CodeCommentRelation> codeCommentRelations = new ArrayList<>();
+
+ @OneToMany(mappedBy="request", cascade=CascadeType.REMOVE)
+ private Collection<PullRequestReviewInvitation> reviewInvitations = new ArrayList<>();
+
+ @OneToMany(mappedBy="referenced", cascade=CascadeType.REMOVE)
+ private Collection<PullRequestReference> referencedBy = new ArrayList<>();
+
+ @OneToMany(mappedBy="referencedBy",cascade=CascadeType.REMOVE)
+ private Collection<PullRequestReference> referenced = new ArrayList<>();
+
+ @OneToMany(mappedBy="request", cascade=CascadeType.REMOVE)
+ private Collection<PullRequestVerification> verifications = new ArrayList<>();
+
+ @OneToMany(mappedBy="request", cascade=CascadeType.REMOVE)
+ private Collection<PullRequestComment> comments = new ArrayList<>();
+
+ @OneToMany(mappedBy="request", cascade=CascadeType.REMOVE)
+ private Collection<PullRequestStatusChange> statusChanges = new ArrayList<>();
+
+ @OneToMany(mappedBy="request", cascade=CascadeType.REMOVE)
+ private Collection<PullRequestNotification> notifications = new ArrayList<>();
+
+ @OneToMany(mappedBy="request", cascade=CascadeType.REMOVE)
+ 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 Collection<RevCommit> pendingCommits;
+
+ private transient Collection<RevCommit> mergedCommits;
+
+ private transient List<PullRequestReview> reviews;
+
+ private transient IntegrationPreview integrationPreview;
+
+ private transient List<CodeComment> codeComments;
+
+ /**
+ * Get title of this merge request.
+ *
+ * @return user specified title of this merge request, <tt>null</tt> for
+ * auto-created merge request.
+ */
+ public @Nullable String getTitle() {
+ return title;
+ }
+
+ public void setTitle(String title) {
+ this.title = title;
+ noSpaceTitle = StringUtils.deleteWhitespace(title);
+ }
+
+ public String getDescription() {
+ return description;
+ }
+
+ public void setDescription(String description) {
+ this.description = description;
+ }
+
+ /**
+ * Get the user submitting the pull request.
+ *
+ * @return
+ * the user submitting the pull request, or <tt>null</tt> if unknown
+ */
+ @Nullable
+ public Account getSubmitter() {
+ return submitter;
+ }
+
+ public void setSubmitter(@Nullable Account submitter) {
+ this.submitter = submitter;
+ }
+
+ /**
+ * Get the user responsible for integration of the pull request.
+ *
+ * @return
+ * the user responsible for integration of this pull request, or <tt>null</tt> to have the
+ * system integrate the pull request automatically
+ */
+ @Nullable
+ public Account getAssignee() {
+ return assignee;
+ }
+
+ public void setAssignee(Account assignee) {
+ this.assignee = assignee;
+ }
+
+ public Depot getTargetDepot() {
+ return targetDepot;
+ }
+
+ public DepotAndBranch getTarget() {
+ return new DepotAndBranch(getTargetDepot(), getTargetBranch());
+ }
+
+ public void setTarget(DepotAndBranch target) {
+ setTargetDepot(target.getDepot());
+ setTargetBranch(target.getBranch());
+ }
+
+ public void setSource(DepotAndBranch source) {
+ setSourceDepot(source.getDepot());
+ setSourceBranch(source.getBranch());
+ }
+
+ public void setTargetDepot(Depot targetDepot) {
+ this.targetDepot = targetDepot;
+ }
+
+ public String getTargetBranch() {
+ return targetBranch;
+ }
+
+ public void setTargetBranch(String targetBranch) {
+ this.targetBranch = targetBranch;
+ }
+
+ @Nullable
+ public Depot getSourceDepot() {
+ return sourceDepot;
+ }
+
+ public void setSourceDepot(Depot sourceDepot) {
+ this.sourceDepot = sourceDepot;
+ }
+
+ public String getSourceBranch() {
+ return sourceBranch;
+ }
+
+ public void setSourceBranch(String sourceBranch) {
+ this.sourceBranch = sourceBranch;
+ }
+
+ public DepotAndBranch getSource() {
+ return new DepotAndBranch(getSourceDepot(), getSourceBranch());
+ }
+
+ public String getTargetRef() {
+ return GitUtils.branch2ref(getTargetBranch());
+ }
+
+ public String getSourceRef() {
+ return GitUtils.branch2ref(getSourceBranch());
+ }
+
+ public String getBaseCommitHash() {
+ return baseCommitHash;
+ }
+
+ public void setBaseCommitHash(String baseCommitHash) {
+ this.baseCommitHash = baseCommitHash;
+ }
+
+ public RevCommit getBaseCommit() {
+ return getTargetDepot().getRevCommit(ObjectId.fromString(getBaseCommitHash()));
+ }
+
+ /**
+ * 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<CodeCommentRelation> getCodeCommentRelations() {
+ return codeCommentRelations;
+ }
+
+ public void setCodeCommentRelations(Collection<CodeCommentRelation> codeCommentRelations) {
+ this.codeCommentRelations = codeCommentRelations;
+ }
+
+ public Collection<PullRequestReviewInvitation> getReviewInvitations() {
+ return reviewInvitations;
+ }
+
+ public void setReviewInvitations(Collection<PullRequestReviewInvitation> reviewInvitations) {
+ this.reviewInvitations = reviewInvitations;
+ }
+
+ public Collection<PullRequestVerification> getVerifications() {
+ return verifications;
+ }
+
+ public void setVerifications(Collection<PullRequestVerification> verifications) {
+ this.verifications = verifications;
+ }
+
+ public Collection<PullRequestReference> getReferencedBy() {
+ return referencedBy;
+ }
+
+ public void setReferencedBy(Collection<PullRequestReference> referencedBy) {
+ this.referencedBy = referencedBy;
+ }
+
+ public Collection<PullRequestReference> getReferenced() {
+ return referenced;
+ }
+
+ public void setReferenced(Collection<PullRequestReference> referenced) {
+ this.referenced = referenced;
+ }
+
+ public Collection<PullRequestComment> getComments() {
+ return comments;
+ }
+
+ public void setComments(Collection<PullRequestComment> comments) {
+ this.comments = comments;
+ }
+
+ public Collection<PullRequestStatusChange> getStatusChanges() {
+ return statusChanges;
+ }
+
+ public void setStatusChanges(Collection<PullRequestStatusChange> statusChanges) {
+ this.statusChanges = statusChanges;
+ }
+
+ public Collection<PullRequestNotification> getNotifications() {
+ return notifications;
+ }
+
+ public void setNotifications(Collection<PullRequestNotification> notifications) {
+ this.notifications = notifications;
+ }
+
+ 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() {
+ if (integrationPreview == null)
+ integrationPreview = GitPlex.getInstance(PullRequestManager.class).previewIntegration(this);
+ return integrationPreview;
+ }
+
+ /**
+ * 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().isMergedInto(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);
+ }
+
+ @JsonView(ExternalView.class)
+ public String getBaseRef() {
+ Preconditions.checkNotNull(getId());
+ return Depot.REFS_GITPLEX + "pulls/" + getNumber() + "/base";
+ }
+
+ @JsonView(ExternalView.class)
+ public String getIntegrateRef() {
+ Preconditions.checkNotNull(getId());
+ return Depot.REFS_GITPLEX + "pulls/" + getNumber() + "/integrate";
+ }
+
+ /**
+ * Delete refs of this pull request, without touching refs of its updates.
+ */
+ public void deleteRefs() {
+ GitUtils.deleteRef(getTargetDepot().updateRef(getBaseRef()));
+ GitUtils.deleteRef(getTargetDepot().updateRef(getIntegrateRef()));
+ }
+
+ /**
+ * Invite specified number of users in candidates to review this request.
+ * <p>
+ *
+ * @param candidates
+ * a collection of users to invite users from
+ * @param count
+ * number of users to invite
+ */
+ public void pickReviewers(Collection<Account> candidates, int count) {
+ List<Account> pickList = new ArrayList<Account>(candidates);
+
+ /*
+ * users already reviewed since base update should be excluded from
+ * invitation list as their reviews are still valid
+ */
+ for (PullRequestReview review: getReferentialUpdate().listReviewsOnwards()) {
+ pickList.remove(review.getUser());
+ }
+
+ Set<Account> firstChoices = new HashSet<>();
+ Set<Account> lastChoices = new HashSet<>();
+
+ for (PullRequestReviewInvitation invitation: getReviewInvitations()) {
+ if (!invitation.isExcluded())
+ firstChoices.add(invitation.getUser());
+ else
+ lastChoices.add(invitation.getUser());
+ }
+
+ // submitter is not preferred
+ if (getSubmitter() != null)
+ lastChoices.add(getSubmitter());
+
+ List<Account> firstPickList = new ArrayList<>();
+ List<Account> lastPickList = new ArrayList<>();
+ List<Account> otherPickList = new ArrayList<>();
+ for (Account user: pickList) {
+ if (firstChoices.contains(user))
+ firstPickList.add(user);
+ else if (lastChoices.contains(user))
+ lastPickList.add(user);
+ else
+ otherPickList.add(user);
+ }
+ firstPickList.sort(Comparator.comparing(Account::getReviewEffort));
+ lastPickList.sort(Comparator.comparing(Account::getReviewEffort));
+ otherPickList.sort(Comparator.comparing(Account::getReviewEffort));
+ pickList.clear();
+ pickList.addAll(firstPickList);
+ pickList.addAll(lastPickList);
+ pickList.addAll(otherPickList);
+
+ List<Account> picked;
+ if (count <= pickList.size())
+ picked = pickList.subList(0, count);
+ else
+ picked = pickList;
+
+ for (Account user: picked) {
+ boolean found = false;
+ for (PullRequestReviewInvitation invitation: getReviewInvitations()) {
+ if (invitation.getUser().equals(user)) {
+ invitation.setDate(new Date());
+ invitation.setExcluded(false);
+ found = true;
+ }
+ }
+ if (!found) {
+ PullRequestReviewInvitation invitation = new PullRequestReviewInvitation();
+ invitation.setRequest(this);
+ invitation.setUser(user);
+ getReviewInvitations().add(invitation);
+ }
+ }
+
+ }
+
+ public static class CriterionHelper {
+ public static Criterion ofOpen() {
+ return Restrictions.isNull("closeInfo");
+ }
+
+ public static Criterion ofClosed() {
+ return Restrictions.isNotNull("closeInfo");
+ }
+
+ public static Criterion ofTarget(DepotAndBranch target) {
+ return Restrictions.and(
+ Restrictions.eq("targetDepot", target.getDepot()),
+ Restrictions.eq("targetBranch", target.getBranch()));
+ }
+
+ public static Criterion ofTargetDepot(Depot target) {
+ return Restrictions.eq("targetDepot", target);
+ }
+
+ public static Criterion ofSource(DepotAndBranch source) {
+ return Restrictions.and(
+ Restrictions.eq("sourceDepot", source.getDepot()),
+ Restrictions.eq("sourceBranch", source.getBranch()));
+ }
+
+ public static Criterion ofSourceDepot(Depot source) {
+ return Restrictions.eq("sourceDepot", source);
+ }
+
+ public static Criterion ofSubmitter(Account submitter) {
+ return Restrictions.eq("submitter", submitter);
+ }
+
+ }
+
+ public Date getSubmitDate() {
+ return submitDate;
+ }
+
+ public void setSubmitDate(Date submitDate) {
+ this.submitDate = submitDate;
+ }
+
+ /**
+ * Get commits pending integration.
+ *
+ * @return
+ * commits pending integration
+ */
+ public Collection<RevCommit> getPendingCommits() {
+ if (pendingCommits == null) {
+ pendingCommits = new HashSet<>();
+ Depot depot = getTargetDepot();
+ try (RevWalk revWalk = new RevWalk(depot.getRepository())) {
+ revWalk.markStart(revWalk.parseCommit(ObjectId.fromString(getLatestUpdate().getHeadCommitHash())));
+ revWalk.markUninteresting(revWalk.parseCommit(ObjectId.fromString(getTarget().getObjectName())));
+ revWalk.forEach(c->pendingCommits.add(c));
+ } catch (IOException e) {
+ throw new RuntimeException(e);
+ }
+ }
+ return pendingCommits;
+ }
+
+ /**
+ * Merged commits represent commits already merged to target branch since base commit.
+ *
+ * @return
+ * commits already merged to target branch since base commit
+ */
+ public Collection<RevCommit> getMergedCommits() {
+ if (mergedCommits == null) {
+ mergedCommits = new HashSet<>();
+ Depot depot = getTargetDepot();
+ try (RevWalk revWalk = new RevWalk(depot.getRepository())) {
+ revWalk.markStart(revWalk.parseCommit(ObjectId.fromString(getTarget().getObjectName())));
+ revWalk.markUninteresting(revWalk.parseCommit(ObjectId.fromString(getBaseCommitHash())));
+ revWalk.forEach(c->mergedCommits.add(c));
+ } catch (IOException e) {
+ throw new RuntimeException(e);
+ }
+ }
+ return mergedCommits;
+ }
+
+ public List<PullRequestReview> getReviews() {
+ if (reviews == null) {
+ if (!isNew())
+ reviews = GitPlex.getInstance(PullRequestReviewManager.class).findAll(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<PullRequestReview> getReviews(PullRequestUpdate update) {
+ List<PullRequestReview> reviews = new ArrayList<>();
+ for (PullRequestReview review: getReviews()) {
+ if (review.getUpdate().equals(update))
+ reviews.add(review);
+ }
+ return reviews;
+ }
+
+ public boolean isReviewEffective(Account user) {
+ for (PullRequestReview review: getReviews()) {
+ if (review.getUpdate().equals(getLatestUpdate()) && review.getUser().equals(user))
+ return true;
+ }
+ return false;
+ }
+
+ /**
+ * Calculate list of users can be added as reviewers of this pull request.
+ *
+ * @return
+ * list of potential reviewers
+ */
+ public List<Account> getPotentialReviewers() {
+ List<Account> reviewers = new ArrayList<>();
+ Set<Account> alreadyInvited = new HashSet<>();
+ for (PullRequestReviewInvitation invitation: getReviewInvitations()) {
+ if (!invitation.isExcluded())
+ alreadyInvited.add(invitation.getUser());
+ }
+ ObjectPermission readPerm = ObjectPermission.ofDepotRead(getTargetDepot());
+ for (Account user: GitPlex.getInstance(Dao.class).findAll(Account.class)) {
+ if (user.asSubject().isPermitted(readPerm) && !alreadyInvited.contains(user))
+ reviewers.add(user);
+ }
+ return reviewers;
+ }
+
+ @Nullable
+ public PullRequestWatch getWatch(Account user) {
+ for (PullRequestWatch watch: getWatches()) {
+ if (watch.getUser().equals(user))
+ return watch;
+ }
+ return null;
+ }
+
+ public String getNumberStr() {
+ return numberStr;
+ }
+
+ public String getNoSpaceTitle() {
+ return noSpaceTitle;
+ }
+
+ public long getVersion() {
+ return version;
+ }
+
+ public String getUUID() {
+ return uuid;
+ }
+
+ public void setUUID(String uuid) {
+ this.uuid = uuid;
+ }
+
+ public long getNumber() {
+ return number;
+ }
+
+ public void setNumber(long number) {
+ this.number = number;
+ numberStr = String.valueOf(number);
+ }
+
+ public List<CodeComment> getCodeComments() {
+ if (codeComments == null) {
+ codeComments = GitPlex.getInstance(CodeCommentRelationManager.class).findAllCodeComments(this);
+ }
+ return codeComments;
+ }
+
+ @Nullable
+ public ComparingInfo getRequestComparingInfo(CodeComment.ComparingInfo commentComparingInfo) {
+ List<String> commits = new ArrayList<>();
+ commits.add(getBaseCommitHash());
+ for (PullRequestUpdate update: getSortedUpdates()) {
+ commits.addAll(update.getCommits().stream().map(RevCommit::getName).collect(Collectors.toList()));
+ }
+ String commit = commentComparingInfo.getCommit();
+ CompareContext compareContext = commentComparingInfo.getCompareContext();
+ if (commit.equals(compareContext.getCompareCommit())) {
+ int index = commits.indexOf(commit);
+ if (index == 0) {
+ return null;
+ } else {
+ return new ComparingInfo(commits.get(index-1), commit,
+ compareContext.getWhitespaceOption(), compareContext.getPathFilter());
+ }
+ } else {
+ int commitIndex = commits.indexOf(commit);
+ int compareCommitIndex = commits.indexOf(compareContext.getCompareCommit());
+ if (commitIndex == -1 || compareCommitIndex == -1) {
+ return null;
+ } else if (compareContext.isLeftSide()) {
+ if (compareCommitIndex < commitIndex) {
+ return new ComparingInfo(compareContext.getCompareCommit(), commit,
+ compareContext.getWhitespaceOption(), compareContext.getPathFilter());
+ } else {
+ return null;
+ }
+ } else {
+ if (commitIndex < compareCommitIndex) {
+ return new ComparingInfo(commit, compareContext.getCompareCommit(),
+ compareContext.getWhitespaceOption(), compareContext.getPathFilter());
+ } else {
+ return null;
+ }
+ }
+ }
+ }
+
+ public List<RevCommit> getCommits() {
+ List<RevCommit> commits = new ArrayList<>();
+ getSortedUpdates().forEach(update->commits.addAll(update.getCommits()));
+ return commits;
+ }
+
+ public String getCommitMessage() {
+ String commitMessage = getTitle() + "\n\n";
+ if (getDescription() != null)
+ commitMessage += getDescription() + "\n\n";
+ commitMessage += "This commit is created as result of integrating pull request #" + getNumber();
+ return commitMessage;
+ }
+
+ public LastEvent getLastEvent() {
+ return lastEvent;
+ }
+
+ public void setLastEvent(LastEvent lastEvent) {
+ this.lastEvent = lastEvent;
+ }
+
+ public Date getLastCodeCommentEventDate() {
+ return lastCodeCommentEventDate;
+ }
+
+ public void setLastCodeCommentEventDate(Date lastCodeCommentEventDate) {
+ this.lastCodeCommentEventDate = lastCodeCommentEventDate;
+ }
+
+ public boolean isVisitedAfter(Date date) {
+ Account user = SecurityUtils.getAccount();
+ if (user != null) {
+ Date visitDate = GitPlex.getInstance(VisitInfoManager.class).getVisitDate(user, this);
+ return visitDate != null && visitDate.getTime()>date.getTime();
+ } else {
+ return true;
+ }
+ }
+
+ public boolean isMerged() {
+ return getTargetDepot().isMergedInto(
+ getLatestUpdate().getHeadCommitHash(),
+ getTarget().getObjectName());
+ }
+
+ public static class ComparingInfo implements Serializable {
+
+ private static final long serialVersionUID = 1L;
+
+ private final String oldCommit;
+
+ private final String newCommit;
+
+ private final String pathFilter;
+
+ private final WhitespaceOption whitespaceOption;
+
+ public ComparingInfo(String oldCommit, String newCommit, WhitespaceOption whitespaceOption, @Nullable String pathFilter) {
+ this.oldCommit = oldCommit;
+ this.newCommit = newCommit;
+ this.whitespaceOption = whitespaceOption;
+ this.pathFilter = pathFilter;
+ }
+
+ public String getOldCommit() {
+ return oldCommit;
+ }
+
+ public String getNewCommit() {
+ return newCommit;
+ }
+
+ public String getPathFilter() {
+ return pathFilter;
+ }
+
+ public WhitespaceOption getWhitespaceOption() {
+ return whitespaceOption;
+ }
+
+ }
+}
diff --git a/gitplex.core/src/main/java/com/pmease/gitplex/core/entity/PullRequestReviewInvitation.java b/gitplex.core/src/main/java/com/pmease/gitplex/core/entity/PullRequestReviewInvitation.java
index d3c89b00be..7876117482 100644
--- a/gitplex.core/src/main/java/com/pmease/gitplex/core/entity/PullRequestReviewInvitation.java
+++ b/gitplex.core/src/main/java/com/pmease/gitplex/core/entity/PullRequestReviewInvitation.java
@@ -1,68 +1,68 @@
-package com.pmease.gitplex.core.entity;
-
-import java.util.Date;
-
-import javax.persistence.Column;
-import javax.persistence.Entity;
-import javax.persistence.FetchType;
-import javax.persistence.JoinColumn;
-import javax.persistence.ManyToOne;
-import javax.persistence.Table;
-import javax.persistence.UniqueConstraint;
-
-import com.pmease.commons.hibernate.AbstractEntity;
-
-@Entity
-@Table(uniqueConstraints={
- @UniqueConstraint(columnNames={"g_user_id", "g_request_id"})
-})
-public class PullRequestReviewInvitation extends AbstractEntity {
-
- private static final long serialVersionUID = 1L;
-
- @ManyToOne(fetch=FetchType.LAZY)
- @JoinColumn(nullable=false)
- private Account user;
-
- @ManyToOne(fetch=FetchType.LAZY)
- @JoinColumn(nullable=false)
- private PullRequest request;
-
- private boolean perferred = true;
-
- @Column(nullable=false)
- private Date date = new Date();
-
- public Account getUser() {
- return user;
- }
-
- public void setUser(Account user) {
- this.user = user;
- }
-
- public PullRequest getRequest() {
- return request;
- }
-
- public void setRequest(PullRequest request) {
- this.request = request;
- }
-
- public boolean isPreferred() {
- return perferred;
- }
-
- public void setPerferred(boolean preferred) {
- this.perferred = preferred;
- }
-
- public Date getDate() {
- return date;
- }
-
- public void setDate(Date date) {
- this.date = date;
- }
-
-}
+package com.pmease.gitplex.core.entity;
+
+import java.util.Date;
+
+import javax.persistence.Column;
+import javax.persistence.Entity;
+import javax.persistence.FetchType;
+import javax.persistence.JoinColumn;
+import javax.persistence.ManyToOne;
+import javax.persistence.Table;
+import javax.persistence.UniqueConstraint;
+
+import com.pmease.commons.hibernate.AbstractEntity;
+
+@Entity
+@Table(uniqueConstraints={
+ @UniqueConstraint(columnNames={"g_user_id", "g_request_id"})
+})
+public class PullRequestReviewInvitation extends AbstractEntity {
+
+ private static final long serialVersionUID = 1L;
+
+ @ManyToOne(fetch=FetchType.LAZY)
+ @JoinColumn(nullable=false)
+ private Account user;
+
+ @ManyToOne(fetch=FetchType.LAZY)
+ @JoinColumn(nullable=false)
+ private PullRequest request;
+
+ private boolean excluded;
+
+ @Column(nullable=false)
+ private Date date = new Date();
+
+ public Account getUser() {
+ return user;
+ }
+
+ public void setUser(Account user) {
+ this.user = user;
+ }
+
+ public PullRequest getRequest() {
+ return request;
+ }
+
+ public void setRequest(PullRequest request) {
+ this.request = request;
+ }
+
+ public boolean isExcluded() {
+ return excluded;
+ }
+
+ public void setExcluded(boolean excluded) {
+ this.excluded = excluded;
+ }
+
+ 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/entity/PullRequestUpdate.java b/gitplex.core/src/main/java/com/pmease/gitplex/core/entity/PullRequestUpdate.java
index dfb61ea17f..9caedaafe6 100644
--- a/gitplex.core/src/main/java/com/pmease/gitplex/core/entity/PullRequestUpdate.java
+++ b/gitplex.core/src/main/java/com/pmease/gitplex/core/entity/PullRequestUpdate.java
@@ -1,280 +1,288 @@
-package com.pmease.gitplex.core.entity;
-
-import java.io.IOException;
-import java.util.ArrayList;
-import java.util.Collection;
-import java.util.Collections;
-import java.util.Date;
-import java.util.HashSet;
-import java.util.List;
-import java.util.UUID;
-
-import javax.persistence.CascadeType;
-import javax.persistence.Column;
-import javax.persistence.Entity;
-import javax.persistence.FetchType;
-import javax.persistence.Index;
-import javax.persistence.JoinColumn;
-import javax.persistence.ManyToOne;
-import javax.persistence.OneToMany;
-import javax.persistence.Table;
-
-import org.eclipse.jgit.errors.IncorrectObjectTypeException;
-import org.eclipse.jgit.errors.MissingObjectException;
-import org.eclipse.jgit.lib.ObjectId;
-import org.eclipse.jgit.lib.Repository;
-import org.eclipse.jgit.revwalk.RevCommit;
-import org.eclipse.jgit.revwalk.RevWalk;
-import org.eclipse.jgit.revwalk.filter.RevFilter;
-import org.eclipse.jgit.treewalk.TreeWalk;
-import org.eclipse.jgit.treewalk.filter.TreeFilter;
-
-import com.fasterxml.jackson.annotation.JsonProperty;
-import com.google.common.base.Preconditions;
-import com.pmease.commons.git.GitUtils;
-import com.pmease.commons.hibernate.AbstractEntity;
-import com.pmease.gitplex.core.manager.impl.DefaultCodeCommentRelationManager;
-
-@Entity
-@Table(indexes={@Index(columnList="uuid"), @Index(columnList="date")})
-public class PullRequestUpdate extends AbstractEntity {
-
- private static final long serialVersionUID = 1L;
-
- @ManyToOne(fetch=FetchType.LAZY)
- @JoinColumn(nullable=false)
- private PullRequest request;
-
- @Column(nullable=false)
- private String headCommitHash;
-
- @Column(nullable=false)
- private String mergeCommitHash;
-
- @Column(nullable=false)
- private Date date = new Date();
-
- @OneToMany(mappedBy="update", cascade=CascadeType.REMOVE)
- private Collection<PullRequestReview> reviews = new ArrayList<PullRequestReview>();
-
- @Column(nullable=false)
- private String uuid = UUID.randomUUID().toString();
-
- private transient List<RevCommit> commits;
-
- private transient Collection<String> changedFiles;
-
- 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 String getMergeCommitHash() {
- return mergeCommitHash;
- }
-
- public void setMergeCommitHash(String mergeCommitHash) {
- this.mergeCommitHash = mergeCommitHash;
- }
-
- public Date getDate() {
- return date;
- }
-
- public void setDate(Date date) {
- this.date = date;
- }
-
- public Collection<PullRequestReview> 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<PullRequestReview> listReviewsOnwards() {
- List<PullRequestReview> reviews = new ArrayList<PullRequestReview>();
-
- for (PullRequestUpdate update: getRequest().getEffectiveUpdates()) {
- reviews.addAll(update.getReviews());
- if (update.equals(this))
- break;
- }
-
- return reviews;
- }
-
- public void deleteRefs() {
- GitUtils.deleteRef(getRequest().getTargetDepot().updateRef(getHeadRef()));
- }
-
- /**
- * Get changed files of this update since previous update. This calculation
- * excludes changes introduced by commits from target branch (this will
- * happen if some commits were merged from target branch to source branch)
- */
- public Collection<String> getChangedFiles() {
- if (changedFiles == null) {
- changedFiles = new HashSet<>();
- Repository repository = getRequest().getTargetDepot().getRepository();
- try ( RevWalk revWalk = new RevWalk(repository);
- TreeWalk treeWalk = new TreeWalk(repository)) {
- RevCommit mergeCommit = revWalk.parseCommit(ObjectId.fromString(getMergeCommitHash()));
- RevCommit baseCommit = revWalk.parseCommit(ObjectId.fromString(getBaseCommitHash()));
- RevCommit headCommit = revWalk.parseCommit(ObjectId.fromString(getHeadCommitHash()));
- revWalk.markStart(mergeCommit);
- revWalk.markStart(baseCommit);
- revWalk.setRevFilter(RevFilter.MERGE_BASE);
- RevCommit mergeBase = Preconditions.checkNotNull(revWalk.next());
- treeWalk.setRecursive(true);
- if (mergeBase.equals(baseCommit)) {
- treeWalk.addTree(mergeCommit.getTree());
- treeWalk.addTree(headCommit.getTree());
- treeWalk.setFilter(TreeFilter.ANY_DIFF);
- while (treeWalk.next())
- changedFiles.add(treeWalk.getPathString());
- } else if (mergeBase.equals(mergeCommit)) {
- treeWalk.addTree(baseCommit.getTree());
- treeWalk.addTree(headCommit.getTree());
- treeWalk.setFilter(TreeFilter.ANY_DIFF);
- while (treeWalk.next())
- changedFiles.add(treeWalk.getPathString());
- } else {
- treeWalk.addTree(headCommit.getTree());
- treeWalk.addTree(baseCommit.getTree());
- treeWalk.addTree(mergeCommit.getTree());
- treeWalk.setFilter(new TreeFilter() {
-
- @Override
- public boolean include(TreeWalk walker)
- throws MissingObjectException, IncorrectObjectTypeException, IOException {
- int m0 = walker.getRawMode(0);
-
- // only include the path if the file is modified in head commit
- // compared to base commit and that modification is not introduced
- // by commit from target branch
- return (walker.getRawMode(1) != m0 || !walker.idEqual(1, 0))
- && (walker.getRawMode(2) != m0 || !walker.idEqual(2, 0));
- }
-
- @Override
- public boolean shouldBeRecursive() {
- return false;
- }
-
- @Override
- public TreeFilter clone() {
- return this;
- }
-
- });
- while (treeWalk.next()) {
- changedFiles.add(treeWalk.getPathString());
- }
- }
- } catch (IOException e) {
- throw new RuntimeException(e);
- }
- }
- return changedFiles;
- }
-
- 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 RevCommit getBaseCommit() {
- PullRequest request = getRequest();
-
- int index = request.getSortedUpdates().indexOf(this);
- if (index > 0)
- return request.getSortedUpdates().get(index-1).getHeadCommit();
- else
- return request.getBaseCommit();
- }
-
- public String getUUID() {
- return uuid;
- }
-
- public void setUUID(String uuid) {
- this.uuid = uuid;
- }
-
- /**
- * Get commits belonging to this update, reversely ordered by commit traversing. The list of commit will remain
- * unchanged even if tip of target branch changes. This assumption is key to our caching of code comment to
- * to pull request relations. Check {@link DefaultCodeCommentRelationManager#findAllCodeComments(PullRequest)} for
- * details
- *
- * @return
- * commits belonging to this update ordered by commit id
- */
- public List<RevCommit> getCommits() {
- if (commits == null) {
- commits = new ArrayList<>();
-
- try (RevWalk revWalk = new RevWalk(getRequest().getTargetDepot().getRepository())) {
- RevCommit headCommit = revWalk.parseCommit(ObjectId.fromString(getHeadCommitHash()));
- revWalk.markStart(headCommit);
- revWalk.markUninteresting(revWalk.parseCommit(ObjectId.fromString(getBaseCommitHash())));
-
- /*
- * Instead of excluding commits reachable from target branch, we exclude commits reachable
- * from the merge commit to achieve two purposes:
- * 1. commits merged back into target branch after this update can still be included in this
- * update
- * 2. commits of this update will remain unchanged even if tip of the target branch changes
- */
- revWalk.markUninteresting(revWalk.parseCommit(ObjectId.fromString(getMergeCommitHash())));
-
- revWalk.forEach(c->commits.add(c));
- if (commits.isEmpty())
- commits.add(headCommit);
- } catch (IOException e) {
- throw new RuntimeException(e);
- }
- Collections.reverse(commits);
- }
- return commits;
- }
-
- public RevCommit getHeadCommit() {
- return request.getTargetDepot().getRevCommit(ObjectId.fromString(getHeadCommitHash()));
- }
-
-}
+package com.pmease.gitplex.core.entity;
+
+import java.io.IOException;
+import java.util.ArrayList;
+import java.util.Collection;
+import java.util.Collections;
+import java.util.Date;
+import java.util.HashSet;
+import java.util.List;
+import java.util.Set;
+import java.util.UUID;
+
+import javax.persistence.CascadeType;
+import javax.persistence.Column;
+import javax.persistence.Entity;
+import javax.persistence.FetchType;
+import javax.persistence.Index;
+import javax.persistence.JoinColumn;
+import javax.persistence.ManyToOne;
+import javax.persistence.OneToMany;
+import javax.persistence.Table;
+
+import org.eclipse.jgit.errors.IncorrectObjectTypeException;
+import org.eclipse.jgit.errors.MissingObjectException;
+import org.eclipse.jgit.lib.ObjectId;
+import org.eclipse.jgit.lib.Repository;
+import org.eclipse.jgit.revwalk.RevCommit;
+import org.eclipse.jgit.revwalk.RevWalk;
+import org.eclipse.jgit.revwalk.filter.RevFilter;
+import org.eclipse.jgit.treewalk.TreeWalk;
+import org.eclipse.jgit.treewalk.filter.TreeFilter;
+
+import com.fasterxml.jackson.annotation.JsonProperty;
+import com.google.common.base.Preconditions;
+import com.pmease.commons.git.GitUtils;
+import com.pmease.commons.hibernate.AbstractEntity;
+import com.pmease.gitplex.core.manager.impl.DefaultCodeCommentRelationManager;
+
+@Entity
+@Table(indexes={@Index(columnList="uuid"), @Index(columnList="date")})
+public class PullRequestUpdate extends AbstractEntity {
+
+ private static final long serialVersionUID = 1L;
+
+ @ManyToOne(fetch=FetchType.LAZY)
+ @JoinColumn(nullable=false)
+ private PullRequest request;
+
+ @Column(nullable=false)
+ private String headCommitHash;
+
+ @Column(nullable=false)
+ private String mergeCommitHash;
+
+ @Column(nullable=false)
+ private Date date = new Date();
+
+ @OneToMany(mappedBy="update", cascade=CascadeType.REMOVE)
+ private Collection<PullRequestReview> reviews = new ArrayList<PullRequestReview>();
+
+ @Column(nullable=false)
+ private String uuid = UUID.randomUUID().toString();
+
+ private transient List<RevCommit> commits;
+
+ private transient Collection<String> changedFiles;
+
+ 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 String getMergeCommitHash() {
+ return mergeCommitHash;
+ }
+
+ public void setMergeCommitHash(String mergeCommitHash) {
+ this.mergeCommitHash = mergeCommitHash;
+ }
+
+ public Date getDate() {
+ return date;
+ }
+
+ public void setDate(Date date) {
+ this.date = date;
+ }
+
+ public Collection<PullRequestReview> 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<PullRequestReview> listReviewsOnwards() {
+ List<PullRequestReview> reviews = new ArrayList<PullRequestReview>();
+ Set<Account> excludedReviewers = new HashSet<>();
+ for (PullRequestReviewInvitation invitation: getRequest().getReviewInvitations()) {
+ if (invitation.isExcluded())
+ excludedReviewers.add(invitation.getUser());
+ }
+ for (PullRequestUpdate update: getRequest().getEffectiveUpdates()) {
+ for (PullRequestReview review: update.getReviews()) {
+ if (!excludedReviewers.contains(review.getUser()))
+ reviews.add(review);
+ }
+ if (update.equals(this))
+ break;
+ }
+
+ return reviews;
+ }
+
+ public void deleteRefs() {
+ GitUtils.deleteRef(getRequest().getTargetDepot().updateRef(getHeadRef()));
+ }
+
+ /**
+ * Get changed files of this update since previous update. This calculation
+ * excludes changes introduced by commits from target branch (this will
+ * happen if some commits were merged from target branch to source branch)
+ */
+ public Collection<String> getChangedFiles() {
+ if (changedFiles == null) {
+ changedFiles = new HashSet<>();
+ Repository repository = getRequest().getTargetDepot().getRepository();
+ try ( RevWalk revWalk = new RevWalk(repository);
+ TreeWalk treeWalk = new TreeWalk(repository)) {
+ RevCommit mergeCommit = revWalk.parseCommit(ObjectId.fromString(getMergeCommitHash()));
+ RevCommit baseCommit = revWalk.parseCommit(ObjectId.fromString(getBaseCommitHash()));
+ RevCommit headCommit = revWalk.parseCommit(ObjectId.fromString(getHeadCommitHash()));
+ revWalk.markStart(mergeCommit);
+ revWalk.markStart(baseCommit);
+ revWalk.setRevFilter(RevFilter.MERGE_BASE);
+ RevCommit mergeBase = Preconditions.checkNotNull(revWalk.next());
+ treeWalk.setRecursive(true);
+ if (mergeBase.equals(baseCommit)) {
+ treeWalk.addTree(mergeCommit.getTree());
+ treeWalk.addTree(headCommit.getTree());
+ treeWalk.setFilter(TreeFilter.ANY_DIFF);
+ while (treeWalk.next())
+ changedFiles.add(treeWalk.getPathString());
+ } else if (mergeBase.equals(mergeCommit)) {
+ treeWalk.addTree(baseCommit.getTree());
+ treeWalk.addTree(headCommit.getTree());
+ treeWalk.setFilter(TreeFilter.ANY_DIFF);
+ while (treeWalk.next())
+ changedFiles.add(treeWalk.getPathString());
+ } else {
+ treeWalk.addTree(headCommit.getTree());
+ treeWalk.addTree(baseCommit.getTree());
+ treeWalk.addTree(mergeCommit.getTree());
+ treeWalk.setFilter(new TreeFilter() {
+
+ @Override
+ public boolean include(TreeWalk walker)
+ throws MissingObjectException, IncorrectObjectTypeException, IOException {
+ int m0 = walker.getRawMode(0);
+
+ // only include the path if the file is modified in head commit
+ // compared to base commit and that modification is not introduced
+ // by commit from target branch
+ return (walker.getRawMode(1) != m0 || !walker.idEqual(1, 0))
+ && (walker.getRawMode(2) != m0 || !walker.idEqual(2, 0));
+ }
+
+ @Override
+ public boolean shouldBeRecursive() {
+ return false;
+ }
+
+ @Override
+ public TreeFilter clone() {
+ return this;
+ }
+
+ });
+ while (treeWalk.next()) {
+ changedFiles.add(treeWalk.getPathString());
+ }
+ }
+ } catch (IOException e) {
+ throw new RuntimeException(e);
+ }
+ }
+ return changedFiles;
+ }
+
+ 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 RevCommit getBaseCommit() {
+ PullRequest request = getRequest();
+
+ int index = request.getSortedUpdates().indexOf(this);
+ if (index > 0)
+ return request.getSortedUpdates().get(index-1).getHeadCommit();
+ else
+ return request.getBaseCommit();
+ }
+
+ public String getUUID() {
+ return uuid;
+ }
+
+ public void setUUID(String uuid) {
+ this.uuid = uuid;
+ }
+
+ /**
+ * Get commits belonging to this update, reversely ordered by commit traversing. The list of commit will remain
+ * unchanged even if tip of target branch changes. This assumption is key to our caching of code comment to
+ * to pull request relations. Check {@link DefaultCodeCommentRelationManager#findAllCodeComments(PullRequest)} for
+ * details
+ *
+ * @return
+ * commits belonging to this update ordered by commit id
+ */
+ public List<RevCommit> getCommits() {
+ if (commits == null) {
+ commits = new ArrayList<>();
+
+ try (RevWalk revWalk = new RevWalk(getRequest().getTargetDepot().getRepository())) {
+ RevCommit headCommit = revWalk.parseCommit(ObjectId.fromString(getHeadCommitHash()));
+ revWalk.markStart(headCommit);
+ revWalk.markUninteresting(revWalk.parseCommit(ObjectId.fromString(getBaseCommitHash())));
+
+ /*
+ * Instead of excluding commits reachable from target branch, we exclude commits reachable
+ * from the merge commit to achieve two purposes:
+ * 1. commits merged back into target branch after this update can still be included in this
+ * update
+ * 2. commits of this update will remain unchanged even if tip of the target branch changes
+ */
+ revWalk.markUninteresting(revWalk.parseCommit(ObjectId.fromString(getMergeCommitHash())));
+
+ revWalk.forEach(c->commits.add(c));
+ if (commits.isEmpty())
+ commits.add(headCommit);
+ } catch (IOException e) {
+ throw new RuntimeException(e);
+ }
+ Collections.reverse(commits);
+ }
+ return commits;
+ }
+
+ public RevCommit getHeadCommit() {
+ return request.getTargetDepot().getRevCommit(ObjectId.fromString(getHeadCommitHash()));
+ }
+
+}
diff --git a/gitplex.core/src/main/java/com/pmease/gitplex/core/gatekeeper/IfApprovedBySpecifiedUser.java b/gitplex.core/src/main/java/com/pmease/gitplex/core/gatekeeper/IfApprovedBySpecifiedUser.java
index 0d55d00a0c..6effae8560 100644
--- a/gitplex.core/src/main/java/com/pmease/gitplex/core/gatekeeper/IfApprovedBySpecifiedUser.java
+++ b/gitplex.core/src/main/java/com/pmease/gitplex/core/gatekeeper/IfApprovedBySpecifiedUser.java
@@ -24,7 +24,7 @@ public class IfApprovedBySpecifiedUser extends AbstractGateKeeper {
private String userName;
- @Editable(name="Select User Below")
+ @Editable(name="Select User")
@AccountChoice
@NotEmpty
public String getUserName() {
diff --git a/gitplex.core/src/main/java/com/pmease/gitplex/core/gatekeeper/IfDisapprovedBySpecifiedUser.java b/gitplex.core/src/main/java/com/pmease/gitplex/core/gatekeeper/IfDisapprovedBySpecifiedUser.java
index ae7de136de..1ae4f50870 100644
--- a/gitplex.core/src/main/java/com/pmease/gitplex/core/gatekeeper/IfDisapprovedBySpecifiedUser.java
+++ b/gitplex.core/src/main/java/com/pmease/gitplex/core/gatekeeper/IfDisapprovedBySpecifiedUser.java
@@ -25,7 +25,7 @@ public class IfDisapprovedBySpecifiedUser extends AbstractGateKeeper {
private String userName;
- @Editable(name="Select User Below")
+ @Editable(name="Select User")
@AccountChoice
@NotEmpty
public String getUserName() {
diff --git a/gitplex.core/src/main/java/com/pmease/gitplex/core/gatekeeper/IfSubmittedBySpecifiedUser.java b/gitplex.core/src/main/java/com/pmease/gitplex/core/gatekeeper/IfSubmittedBySpecifiedUser.java
index 0876e273a9..feca78aa3e 100644
--- a/gitplex.core/src/main/java/com/pmease/gitplex/core/gatekeeper/IfSubmittedBySpecifiedUser.java
+++ b/gitplex.core/src/main/java/com/pmease/gitplex/core/gatekeeper/IfSubmittedBySpecifiedUser.java
@@ -22,7 +22,7 @@ public class IfSubmittedBySpecifiedUser extends AbstractGateKeeper {
private String userName;
- @Editable(name="Select User Below")
+ @Editable(name="Select User")
@AccountChoice
@NotEmpty
public String getUserName() {
diff --git a/gitplex.core/src/main/java/com/pmease/gitplex/core/manager/PullRequestReviewInvitationManager.java b/gitplex.core/src/main/java/com/pmease/gitplex/core/manager/PullRequestReviewInvitationManager.java
index bb574c566b..86769fc51d 100644
--- a/gitplex.core/src/main/java/com/pmease/gitplex/core/manager/PullRequestReviewInvitationManager.java
+++ b/gitplex.core/src/main/java/com/pmease/gitplex/core/manager/PullRequestReviewInvitationManager.java
@@ -1,12 +1,17 @@
-package com.pmease.gitplex.core.manager;
-
-import com.pmease.commons.hibernate.dao.EntityManager;
-import com.pmease.gitplex.core.entity.Account;
-import com.pmease.gitplex.core.entity.PullRequest;
-import com.pmease.gitplex.core.entity.PullRequestReviewInvitation;
-
-public interface PullRequestReviewInvitationManager extends EntityManager<PullRequestReviewInvitation> {
-
- PullRequestReviewInvitation find(Account reviewer, PullRequest request);
-
-}
+package com.pmease.gitplex.core.manager;
+
+import java.util.Collection;
+import java.util.Date;
+
+import com.pmease.commons.hibernate.dao.EntityManager;
+import com.pmease.gitplex.core.entity.Account;
+import com.pmease.gitplex.core.entity.PullRequest;
+import com.pmease.gitplex.core.entity.PullRequestReviewInvitation;
+
+public interface PullRequestReviewInvitationManager extends EntityManager<PullRequestReviewInvitation> {
+
+ PullRequestReviewInvitation find(Account reviewer, PullRequest request);
+
+ void update(Collection<PullRequestReviewInvitation> invitations, Date since);
+
+}
diff --git a/gitplex.core/src/main/java/com/pmease/gitplex/core/manager/PullRequestReviewManager.java b/gitplex.core/src/main/java/com/pmease/gitplex/core/manager/PullRequestReviewManager.java
index dba417f4ba..2c9def94e9 100644
--- a/gitplex.core/src/main/java/com/pmease/gitplex/core/manager/PullRequestReviewManager.java
+++ b/gitplex.core/src/main/java/com/pmease/gitplex/core/manager/PullRequestReviewManager.java
@@ -1,29 +1,31 @@
-package com.pmease.gitplex.core.manager;
-
-import java.util.List;
-
-import javax.annotation.Nullable;
-
-import com.pmease.commons.hibernate.dao.EntityManager;
-import com.pmease.gitplex.core.entity.Account;
-import com.pmease.gitplex.core.entity.PullRequest;
-import com.pmease.gitplex.core.entity.PullRequestUpdate;
-import com.pmease.gitplex.core.entity.PullRequestReview;
-
-public interface PullRequestReviewManager extends EntityManager<PullRequestReview> {
-
- PullRequestReview find(Account user, PullRequestUpdate update);
-
- void review(PullRequest request, PullRequestReview.Result result, @Nullable String note);
-
- /**
- * Find list of reviews ordered by review date for specified pull request.
- *
- * @param request
- * pull request to find review for
- * @return
- * list of reviews ordered by review date
- */
- List<PullRequestReview> findAll(PullRequest request);
-
-}
+package com.pmease.gitplex.core.manager;
+
+import java.util.List;
+
+import javax.annotation.Nullable;
+
+import com.pmease.commons.hibernate.dao.EntityManager;
+import com.pmease.gitplex.core.entity.Account;
+import com.pmease.gitplex.core.entity.PullRequest;
+import com.pmease.gitplex.core.entity.PullRequestUpdate;
+import com.pmease.gitplex.core.entity.PullRequestReview;
+
+public interface PullRequestReviewManager extends EntityManager<PullRequestReview> {
+
+ PullRequestReview find(Account user, PullRequestUpdate update);
+
+ void review(PullRequest request, PullRequestReview.Result result, @Nullable String note);
+
+ /**
+ * Find list of reviews ordered by review date for specified pull request.
+ *
+ * @param request
+ * pull request to find review for
+ * @return
+ * list of reviews ordered by review date
+ */
+ List<PullRequestReview> findAll(PullRequest request);
+
+ void deleteAll(Account user, PullRequest request);
+
+}
diff --git a/gitplex.core/src/main/java/com/pmease/gitplex/core/manager/impl/DefaultPullRequestManager.java b/gitplex.core/src/main/java/com/pmease/gitplex/core/manager/impl/DefaultPullRequestManager.java
index bcc6db80f2..1d2d48fdf7 100644
--- a/gitplex.core/src/main/java/com/pmease/gitplex/core/manager/impl/DefaultPullRequestManager.java
+++ b/gitplex.core/src/main/java/com/pmease/gitplex/core/manager/impl/DefaultPullRequestManager.java
@@ -459,6 +459,8 @@ public class DefaultPullRequestManager extends AbstractEntityManager<PullRequest
PullRequestUpdate update = new PullRequestUpdate();
update.setRequest(request);
update.setHeadCommitHash(request.getSource().getObjectName());
+ update.setMergeCommitHash(GitUtils.getMergeBase(request.getTargetDepot().getRepository(),
+ request.getTarget().getObjectId(), ObjectId.fromString(update.getHeadCommitHash())).name());
request.addUpdate(update);
pullRequestUpdateManager.save(update, notifyListeners);
}
@@ -476,6 +478,7 @@ public class DefaultPullRequestManager extends AbstractEntityManager<PullRequest
if (request.isMerged()) {
closeAsIntegrated(request, true, null);
} else {
+ Date timeBeforeCheck = new Date();
if (request.getStatus() == PENDING_UPDATE) {
listenerRegistry.notify(new PullRequestPendingUpdate(request));
} else if (request.getStatus() == PENDING_INTEGRATE) {
@@ -488,9 +491,8 @@ public class DefaultPullRequestManager extends AbstractEntityManager<PullRequest
listenerRegistry.notify(new PullRequestPendingIntegration(request));
}
} else if (request.getStatus() == PENDING_APPROVAL) {
- Date now = new Date();
for (PullRequestReviewInvitation invitation: request.getReviewInvitations()) {
- if (invitation.getDate().getTime()>=now.getTime())
+ if (invitation.getDate().getTime()>=timeBeforeCheck.getTime())
reviewInvitationManager.save(invitation);
}
listenerRegistry.notify(new PullRequestPendingApproval(request));
diff --git a/gitplex.core/src/main/java/com/pmease/gitplex/core/manager/impl/DefaultPullRequestNotificationManager.java b/gitplex.core/src/main/java/com/pmease/gitplex/core/manager/impl/DefaultPullRequestNotificationManager.java
index 27a451875f..420e360d4b 100644
--- a/gitplex.core/src/main/java/com/pmease/gitplex/core/manager/impl/DefaultPullRequestNotificationManager.java
+++ b/gitplex.core/src/main/java/com/pmease/gitplex/core/manager/impl/DefaultPullRequestNotificationManager.java
@@ -1,278 +1,278 @@
-package com.pmease.gitplex.core.manager.impl;
-
-import static com.pmease.gitplex.core.entity.PullRequestNotification.Task.INTEGRATE;
-import static com.pmease.gitplex.core.entity.PullRequestNotification.Task.REVIEW;
-import static com.pmease.gitplex.core.entity.PullRequestNotification.Task.UPDATE;
-import static com.pmease.gitplex.core.entity.PullRequest.Status.PENDING_INTEGRATE;
-
-import javax.inject.Inject;
-import javax.inject.Singleton;
-
-import org.hibernate.Query;
-import org.hibernate.criterion.Restrictions;
-
-import com.google.common.base.Preconditions;
-import com.google.common.collect.Sets;
-import com.pmease.commons.hibernate.Transactional;
-import com.pmease.commons.hibernate.dao.AbstractEntityManager;
-import com.pmease.commons.hibernate.dao.Dao;
-import com.pmease.commons.hibernate.dao.EntityCriteria;
-import com.pmease.commons.loader.Listen;
-import com.pmease.commons.markdown.MarkdownManager;
-import com.pmease.gitplex.core.entity.Account;
-import com.pmease.gitplex.core.entity.PullRequestNotification;
-import com.pmease.gitplex.core.entity.PullRequest;
-import com.pmease.gitplex.core.entity.PullRequestComment;
-import com.pmease.gitplex.core.entity.PullRequestReview;
-import com.pmease.gitplex.core.entity.PullRequestReviewInvitation;
-import com.pmease.gitplex.core.event.pullrequest.AccountMentioned;
-import com.pmease.gitplex.core.event.pullrequest.AccountMentionedInComment;
-import com.pmease.gitplex.core.event.pullrequest.InvitingPullRequestReview;
-import com.pmease.gitplex.core.event.pullrequest.PullRequestApproved;
-import com.pmease.gitplex.core.event.pullrequest.PullRequestAssigned;
-import com.pmease.gitplex.core.event.pullrequest.PullRequestDisapproved;
-import com.pmease.gitplex.core.event.pullrequest.PullRequestDiscarded;
-import com.pmease.gitplex.core.event.pullrequest.PullRequestIntegrated;
-import com.pmease.gitplex.core.event.pullrequest.PullRequestPendingApproval;
-import com.pmease.gitplex.core.event.pullrequest.PullRequestPendingIntegration;
-import com.pmease.gitplex.core.event.pullrequest.PullRequestPendingUpdate;
-import com.pmease.gitplex.core.event.pullrequest.PullRequestUpdated;
-import com.pmease.gitplex.core.manager.MailManager;
-import com.pmease.gitplex.core.manager.NotificationManager;
-import com.pmease.gitplex.core.manager.UrlManager;
-
-/**
- * This class manages pull request task notifications and send email to relevant users. This
- * notification does not correlate with pull request watch notifications and can not be
- * suppressed.
- *
- * @author robin
- *
- */
-@Singleton
-public class DefaultPullRequestNotificationManager extends AbstractEntityManager<PullRequestNotification>
- implements NotificationManager {
-
- private final MailManager mailManager;
-
- private final UrlManager urlManager;
-
- private final MarkdownManager markdownManager;
-
- @Inject
- public DefaultPullRequestNotificationManager(Dao dao, MailManager mailManager,
- UrlManager urlManager, MarkdownManager markdownManager) {
- super(dao);
-
- this.mailManager = mailManager;
- this.urlManager = urlManager;
- this.markdownManager = markdownManager;
- }
-
- @Transactional
- @Listen
- public void on(PullRequestUpdated event) {
- Query query = getSession().createQuery("delete from PullRequestNotification "
- + "where request=:request and task=:task");
- query.setParameter("request", event.getRequest());
- query.setParameter("task", UPDATE);
- query.executeUpdate();
- }
-
- @Transactional
- @Listen
- public void on(PullRequestAssigned event) {
- PullRequest request = event.getRequest();
- Preconditions.checkNotNull(request.getAssignee());
-
- if (request.getStatus() == PENDING_INTEGRATE) {
- Query query = getSession().createQuery("delete from PullRequestNotification "
- + "where request=:request and task=:task and user!=:user");
- query.setParameter("request", request);
- query.setParameter("task", INTEGRATE);
- query.setParameter("user", request.getAssignee());
- query.executeUpdate();
-
- requestIntegration(request);
- }
- }
-
- @Transactional
- @Listen
- public void on(PullRequestIntegrated event) {
- Query query = getSession().createQuery("delete from PullRequestNotification "
- + "where request=:request");
- query.setParameter("request", event.getRequest());
- query.executeUpdate();
- }
-
- @Transactional
- @Listen
- public void on(PullRequestDiscarded event) {
- Query query = getSession().createQuery("delete from PullRequestNotification "
- + "where request=:request");
- query.setParameter("request", event.getRequest());
- query.executeUpdate();
- }
-
- @Transactional
- @Listen
- public void on(InvitingPullRequestReview event) {
- PullRequestReviewInvitation invitation = event.getInvitation();
- PullRequest request = invitation.getRequest();
- Account user = invitation.getUser();
- if (!invitation.isPreferred()) {
- Query query = getSession().createQuery("delete from PullRequestNotification "
- + "where request=:request and user=:user and task=:task");
- query.setParameter("request", request);
- query.setParameter("user", user);
- query.setParameter("task", REVIEW);
- query.executeUpdate();
- } else {
- PullRequestNotification notification = new PullRequestNotification();
- notification.setRequest(request);
- notification.setUser(user);
- notification.setTask(REVIEW);
- EntityCriteria<PullRequestNotification> criteria = EntityCriteria.of(PullRequestNotification.class);
- criteria.add(Restrictions.eq("request", request))
- .add(Restrictions.eq("user", user))
- .add(Restrictions.eq("task", notification.getTask()));
- if (find(criteria) == null) {
- dao.persist(notification);
- String subject = String.format("Please review pull request #%d (%s)",
- request.getId(), request.getTitle());
- String url = urlManager.urlFor(request);
- String body = String.format("You are invited to review pull request #%d (%s). Please visit "
- + "<a href='%s'>%s</a> to add your comments.",
- request.getId(), request.getTitle(), url, url);
- mailManager.sendMail(Sets.newHashSet(notification.getUser()), subject, decorateMail(user, body));
- }
- }
-
- }
-
- private String decorateMail(Account user, String body) {
- return String.format("Dear %s, "
- + "<p style='margin: 16px 0;'>"
- + "%s"
- + "<p style='margin: 16px 0;'>"
- + "-- Sent by GitPlex",
- user.getDisplayName(), body);
- }
-
- @Transactional
- @Listen
- public void on(PullRequestPendingApproval event) {
- Query query = getSession().createQuery("delete from PullRequestNotification "
- + "where request=:request and (task=:update or task=:integrate)");
- query.setParameter("request", event.getRequest());
- query.setParameter("update", UPDATE);
- query.setParameter("integrate", INTEGRATE);
- query.executeUpdate();
- }
-
- @Transactional
- @Listen
- public void on(AccountMentioned event) {
- PullRequest request = event.getRequest();
- Account user = event.getUser();
- String subject = String.format("You are mentioned in pull request #%d (%s)",
- request.getId(), request.getTitle());
- String url = urlManager.urlFor(request);
- String body = String.format("%s."
- + "<p style='margin: 16px 0; padding-left: 16px; border-left: 4px solid #CCC;'>%s"
- + "<p style='margin: 16px 0;'>"
- + "For details, please visit <a href='%s'>%s</a>",
- subject, markdownManager.escape(request.getDescription()), url, url);
-
- mailManager.sendMail(Sets.newHashSet(user), subject, decorateMail(user, body));
- }
-
- @Transactional
- @Listen
- public void on(AccountMentionedInComment event) {
- PullRequestComment comment = event.getComment();
- Account user = event.getUser();
- String subject = String.format("You are mentioned in comment of pull request #%d (%s)",
- comment.getRequest().getId(), comment.getRequest().getTitle());
- String url = urlManager.urlFor(comment);
- String body = String.format("%s."
- + "<p style='margin: 16px 0; padding-left: 16px; border-left: 4px solid #CCC;'>%s"
- + "<p style='margin: 16px 0;'>"
- + "For details, please visit <a href='%s'>%s</a>",
- subject, markdownManager.escape(comment.getContent()), url, url);
-
- mailManager.sendMail(Sets.newHashSet(user), subject, decorateMail(user, body));
- }
-
- private void requestIntegration(PullRequest request) {
- Account user = request.getAssignee();
- PullRequestNotification notification = new PullRequestNotification();
- notification.setRequest(request);
- notification.setUser(user);
- notification.setTask(INTEGRATE);
- EntityCriteria<PullRequestNotification> criteria = EntityCriteria.of(PullRequestNotification.class);
- criteria.add(Restrictions.eq("request", notification.getRequest()))
- .add(Restrictions.eq("user", user))
- .add(Restrictions.eq("task", notification.getTask()));
- if (find(criteria) == null) {
- dao.persist(notification);
- String subject = String.format("Please integrate pull request #%d (%s)",
- request.getId(), request.getTitle());
- String url = urlManager.urlFor(request);
- String body = String.format("You are assignee of pull request #%d (%s). "
- + "Please visit <a href='%s'>%s</a> to integrate it into target branch.",
- request.getId(), request.getTitle(), url, url);
-
- mailManager.sendMail(Sets.newHashSet(notification.getUser()), subject, decorateMail(user, body));
- }
- }
-
- @Transactional
- @Listen
- public void on(PullRequestPendingIntegration event) {
- PullRequest request = event.getRequest();
- if (request.getAssignee() != null)
- requestIntegration(request);
- }
-
- @Transactional
- @Listen
- public void on(PullRequestPendingUpdate event) {
- PullRequest request = event.getRequest();
- if (request.getSubmitter() != null) {
- PullRequestNotification notification = new PullRequestNotification();
- notification.setRequest(request);
- notification.setUser(request.getSubmitter());
- notification.setTask(UPDATE);
- EntityCriteria<PullRequestNotification> criteria = EntityCriteria.of(PullRequestNotification.class);
- criteria.add(Restrictions.eq("request", notification.getRequest()))
- .add(Restrictions.eq("user", notification.getUser()))
- .add(Restrictions.eq("task", notification.getTask()));
- if (find(criteria) == null)
- dao.persist(notification);
- }
- }
-
- @Transactional
- @Listen
- public void on(PullRequestApproved event) {
- onReviewed(event.getReview());
- }
-
- @Transactional
- @Listen
- public void on(PullRequestDisapproved event) {
- onReviewed(event.getReview());
- }
-
- private void onReviewed(PullRequestReview review) {
- Query query = getSession().createQuery("delete from PullRequestNotification "
- + "where request=:request and user=:user and task=:task");
- query.setParameter("request", review.getUpdate().getRequest());
- query.setParameter("user", review.getUser());
- query.setParameter("task", REVIEW);
- query.executeUpdate();
- }
-
+package com.pmease.gitplex.core.manager.impl;
+
+import static com.pmease.gitplex.core.entity.PullRequestNotification.Task.INTEGRATE;
+import static com.pmease.gitplex.core.entity.PullRequestNotification.Task.REVIEW;
+import static com.pmease.gitplex.core.entity.PullRequestNotification.Task.UPDATE;
+import static com.pmease.gitplex.core.entity.PullRequest.Status.PENDING_INTEGRATE;
+
+import javax.inject.Inject;
+import javax.inject.Singleton;
+
+import org.hibernate.Query;
+import org.hibernate.criterion.Restrictions;
+
+import com.google.common.base.Preconditions;
+import com.google.common.collect.Sets;
+import com.pmease.commons.hibernate.Transactional;
+import com.pmease.commons.hibernate.dao.AbstractEntityManager;
+import com.pmease.commons.hibernate.dao.Dao;
+import com.pmease.commons.hibernate.dao.EntityCriteria;
+import com.pmease.commons.loader.Listen;
+import com.pmease.commons.markdown.MarkdownManager;
+import com.pmease.gitplex.core.entity.Account;
+import com.pmease.gitplex.core.entity.PullRequestNotification;
+import com.pmease.gitplex.core.entity.PullRequest;
+import com.pmease.gitplex.core.entity.PullRequestComment;
+import com.pmease.gitplex.core.entity.PullRequestReview;
+import com.pmease.gitplex.core.entity.PullRequestReviewInvitation;
+import com.pmease.gitplex.core.event.pullrequest.AccountMentioned;
+import com.pmease.gitplex.core.event.pullrequest.AccountMentionedInComment;
+import com.pmease.gitplex.core.event.pullrequest.InvitingPullRequestReview;
+import com.pmease.gitplex.core.event.pullrequest.PullRequestApproved;
+import com.pmease.gitplex.core.event.pullrequest.PullRequestAssigned;
+import com.pmease.gitplex.core.event.pullrequest.PullRequestDisapproved;
+import com.pmease.gitplex.core.event.pullrequest.PullRequestDiscarded;
+import com.pmease.gitplex.core.event.pullrequest.PullRequestIntegrated;
+import com.pmease.gitplex.core.event.pullrequest.PullRequestPendingApproval;
+import com.pmease.gitplex.core.event.pullrequest.PullRequestPendingIntegration;
+import com.pmease.gitplex.core.event.pullrequest.PullRequestPendingUpdate;
+import com.pmease.gitplex.core.event.pullrequest.PullRequestUpdated;
+import com.pmease.gitplex.core.manager.MailManager;
+import com.pmease.gitplex.core.manager.NotificationManager;
+import com.pmease.gitplex.core.manager.UrlManager;
+
+/**
+ * This class manages pull request task notifications and send email to relevant users. This
+ * notification does not correlate with pull request watch notifications and can not be
+ * suppressed.
+ *
+ * @author robin
+ *
+ */
+@Singleton
+public class DefaultPullRequestNotificationManager extends AbstractEntityManager<PullRequestNotification>
+ implements NotificationManager {
+
+ private final MailManager mailManager;
+
+ private final UrlManager urlManager;
+
+ private final MarkdownManager markdownManager;
+
+ @Inject
+ public DefaultPullRequestNotificationManager(Dao dao, MailManager mailManager,
+ UrlManager urlManager, MarkdownManager markdownManager) {
+ super(dao);
+
+ this.mailManager = mailManager;
+ this.urlManager = urlManager;
+ this.markdownManager = markdownManager;
+ }
+
+ @Transactional
+ @Listen
+ public void on(PullRequestUpdated event) {
+ Query query = getSession().createQuery("delete from PullRequestNotification "
+ + "where request=:request and task=:task");
+ query.setParameter("request", event.getRequest());
+ query.setParameter("task", UPDATE);
+ query.executeUpdate();
+ }
+
+ @Transactional
+ @Listen
+ public void on(PullRequestAssigned event) {
+ PullRequest request = event.getRequest();
+ Preconditions.checkNotNull(request.getAssignee());
+
+ if (request.getStatus() == PENDING_INTEGRATE) {
+ Query query = getSession().createQuery("delete from PullRequestNotification "
+ + "where request=:request and task=:task and user!=:user");
+ query.setParameter("request", request);
+ query.setParameter("task", INTEGRATE);
+ query.setParameter("user", request.getAssignee());
+ query.executeUpdate();
+
+ requestIntegration(request);
+ }
+ }
+
+ @Transactional
+ @Listen
+ public void on(PullRequestIntegrated event) {
+ Query query = getSession().createQuery("delete from PullRequestNotification "
+ + "where request=:request");
+ query.setParameter("request", event.getRequest());
+ query.executeUpdate();
+ }
+
+ @Transactional
+ @Listen
+ public void on(PullRequestDiscarded event) {
+ Query query = getSession().createQuery("delete from PullRequestNotification "
+ + "where request=:request");
+ query.setParameter("request", event.getRequest());
+ query.executeUpdate();
+ }
+
+ @Transactional
+ @Listen
+ public void on(InvitingPullRequestReview event) {
+ PullRequestReviewInvitation invitation = event.getInvitation();
+ PullRequest request = invitation.getRequest();
+ Account user = invitation.getUser();
+ if (invitation.isExcluded()) {
+ Query query = getSession().createQuery("delete from PullRequestNotification "
+ + "where request=:request and user=:user and task=:task");
+ query.setParameter("request", request);
+ query.setParameter("user", user);
+ query.setParameter("task", REVIEW);
+ query.executeUpdate();
+ } else {
+ PullRequestNotification notification = new PullRequestNotification();
+ notification.setRequest(request);
+ notification.setUser(user);
+ notification.setTask(REVIEW);
+ EntityCriteria<PullRequestNotification> criteria = EntityCriteria.of(PullRequestNotification.class);
+ criteria.add(Restrictions.eq("request", request))
+ .add(Restrictions.eq("user", user))
+ .add(Restrictions.eq("task", notification.getTask()));
+ if (find(criteria) == null) {
+ dao.persist(notification);
+ String subject = String.format("Please review pull request #%d (%s)",
+ request.getId(), request.getTitle());
+ String url = urlManager.urlFor(request);
+ String body = String.format("You are invited to review pull request #%d (%s). Please visit "
+ + "<a href='%s'>%s</a> to add your comments.",
+ request.getId(), request.getTitle(), url, url);
+ mailManager.sendMail(Sets.newHashSet(notification.getUser()), subject, decorateMail(user, body));
+ }
+ }
+
+ }
+
+ private String decorateMail(Account user, String body) {
+ return String.format("Dear %s, "
+ + "<p style='margin: 16px 0;'>"
+ + "%s"
+ + "<p style='margin: 16px 0;'>"
+ + "-- Sent by GitPlex",
+ user.getDisplayName(), body);
+ }
+
+ @Transactional
+ @Listen
+ public void on(PullRequestPendingApproval event) {
+ Query query = getSession().createQuery("delete from PullRequestNotification "
+ + "where request=:request and (task=:update or task=:integrate)");
+ query.setParameter("request", event.getRequest());
+ query.setParameter("update", UPDATE);
+ query.setParameter("integrate", INTEGRATE);
+ query.executeUpdate();
+ }
+
+ @Transactional
+ @Listen
+ public void on(AccountMentioned event) {
+ PullRequest request = event.getRequest();
+ Account user = event.getUser();
+ String subject = String.format("You are mentioned in pull request #%d (%s)",
+ request.getId(), request.getTitle());
+ String url = urlManager.urlFor(request);
+ String body = String.format("%s."
+ + "<p style='margin: 16px 0; padding-left: 16px; border-left: 4px solid #CCC;'>%s"
+ + "<p style='margin: 16px 0;'>"
+ + "For details, please visit <a href='%s'>%s</a>",
+ subject, markdownManager.escape(request.getDescription()), url, url);
+
+ mailManager.sendMail(Sets.newHashSet(user), subject, decorateMail(user, body));
+ }
+
+ @Transactional
+ @Listen
+ public void on(AccountMentionedInComment event) {
+ PullRequestComment comment = event.getComment();
+ Account user = event.getUser();
+ String subject = String.format("You are mentioned in comment of pull request #%d (%s)",
+ comment.getRequest().getId(), comment.getRequest().getTitle());
+ String url = urlManager.urlFor(comment);
+ String body = String.format("%s."
+ + "<p style='margin: 16px 0; padding-left: 16px; border-left: 4px solid #CCC;'>%s"
+ + "<p style='margin: 16px 0;'>"
+ + "For details, please visit <a href='%s'>%s</a>",
+ subject, markdownManager.escape(comment.getContent()), url, url);
+
+ mailManager.sendMail(Sets.newHashSet(user), subject, decorateMail(user, body));
+ }
+
+ private void requestIntegration(PullRequest request) {
+ Account user = request.getAssignee();
+ PullRequestNotification notification = new PullRequestNotification();
+ notification.setRequest(request);
+ notification.setUser(user);
+ notification.setTask(INTEGRATE);
+ EntityCriteria<PullRequestNotification> criteria = EntityCriteria.of(PullRequestNotification.class);
+ criteria.add(Restrictions.eq("request", notification.getRequest()))
+ .add(Restrictions.eq("user", user))
+ .add(Restrictions.eq("task", notification.getTask()));
+ if (find(criteria) == null) {
+ dao.persist(notification);
+ String subject = String.format("Please integrate pull request #%d (%s)",
+ request.getId(), request.getTitle());
+ String url = urlManager.urlFor(request);
+ String body = String.format("You are assignee of pull request #%d (%s). "
+ + "Please visit <a href='%s'>%s</a> to integrate it into target branch.",
+ request.getId(), request.getTitle(), url, url);
+
+ mailManager.sendMail(Sets.newHashSet(notification.getUser()), subject, decorateMail(user, body));
+ }
+ }
+
+ @Transactional
+ @Listen
+ public void on(PullRequestPendingIntegration event) {
+ PullRequest request = event.getRequest();
+ if (request.getAssignee() != null)
+ requestIntegration(request);
+ }
+
+ @Transactional
+ @Listen
+ public void on(PullRequestPendingUpdate event) {
+ PullRequest request = event.getRequest();
+ if (request.getSubmitter() != null) {
+ PullRequestNotification notification = new PullRequestNotification();
+ notification.setRequest(request);
+ notification.setUser(request.getSubmitter());
+ notification.setTask(UPDATE);
+ EntityCriteria<PullRequestNotification> criteria = EntityCriteria.of(PullRequestNotification.class);
+ criteria.add(Restrictions.eq("request", notification.getRequest()))
+ .add(Restrictions.eq("user", notification.getUser()))
+ .add(Restrictions.eq("task", notification.getTask()));
+ if (find(criteria) == null)
+ dao.persist(notification);
+ }
+ }
+
+ @Transactional
+ @Listen
+ public void on(PullRequestApproved event) {
+ onReviewed(event.getReview());
+ }
+
+ @Transactional
+ @Listen
+ public void on(PullRequestDisapproved event) {
+ onReviewed(event.getReview());
+ }
+
+ private void onReviewed(PullRequestReview review) {
+ Query query = getSession().createQuery("delete from PullRequestNotification "
+ + "where request=:request and user=:user and task=:task");
+ query.setParameter("request", review.getUpdate().getRequest());
+ query.setParameter("user", review.getUser());
+ query.setParameter("task", REVIEW);
+ query.executeUpdate();
+ }
+
}
\ No newline at end of file
diff --git a/gitplex.core/src/main/java/com/pmease/gitplex/core/manager/impl/DefaultPullRequestReviewInvitationManager.java b/gitplex.core/src/main/java/com/pmease/gitplex/core/manager/impl/DefaultPullRequestReviewInvitationManager.java
index a01a1f9cde..171bc3320d 100644
--- a/gitplex.core/src/main/java/com/pmease/gitplex/core/manager/impl/DefaultPullRequestReviewInvitationManager.java
+++ b/gitplex.core/src/main/java/com/pmease/gitplex/core/manager/impl/DefaultPullRequestReviewInvitationManager.java
@@ -1,49 +1,68 @@
-package com.pmease.gitplex.core.manager.impl;
-
-import javax.inject.Inject;
-import javax.inject.Singleton;
-
-import org.hibernate.criterion.Restrictions;
-
-import com.pmease.commons.hibernate.Sessional;
-import com.pmease.commons.hibernate.Transactional;
-import com.pmease.commons.hibernate.dao.AbstractEntityManager;
-import com.pmease.commons.hibernate.dao.Dao;
-import com.pmease.commons.hibernate.dao.EntityCriteria;
-import com.pmease.commons.loader.ListenerRegistry;
-import com.pmease.gitplex.core.entity.Account;
-import com.pmease.gitplex.core.entity.PullRequest;
-import com.pmease.gitplex.core.entity.PullRequestReviewInvitation;
-import com.pmease.gitplex.core.event.pullrequest.InvitingPullRequestReview;
-import com.pmease.gitplex.core.manager.PullRequestReviewInvitationManager;
-
-@Singleton
-public class DefaultPullRequestReviewInvitationManager extends AbstractEntityManager<PullRequestReviewInvitation>
- implements PullRequestReviewInvitationManager {
-
- private final ListenerRegistry listenerRegistry;
-
- @Inject
- public DefaultPullRequestReviewInvitationManager(Dao dao, ListenerRegistry listenerRegistry) {
- super(dao);
-
- this.listenerRegistry = listenerRegistry;
- }
-
- @Sessional
- @Override
- public PullRequestReviewInvitation find(Account reviewer, PullRequest request) {
- return find(EntityCriteria.of(PullRequestReviewInvitation.class)
- .add(Restrictions.eq("reviewer", reviewer))
- .add(Restrictions.eq("request", request)));
- }
-
- @Transactional
- @Override
- public void save(PullRequestReviewInvitation invitation) {
- dao.persist(invitation);
-
- listenerRegistry.notify(new InvitingPullRequestReview(invitation));
- }
-
-}
+package com.pmease.gitplex.core.manager.impl;
+
+import java.util.Collection;
+import java.util.Date;
+
+import javax.inject.Inject;
+import javax.inject.Singleton;
+
+import org.hibernate.criterion.Restrictions;
+
+import com.pmease.commons.hibernate.Sessional;
+import com.pmease.commons.hibernate.Transactional;
+import com.pmease.commons.hibernate.dao.AbstractEntityManager;
+import com.pmease.commons.hibernate.dao.Dao;
+import com.pmease.commons.hibernate.dao.EntityCriteria;
+import com.pmease.commons.loader.ListenerRegistry;
+import com.pmease.gitplex.core.entity.Account;
+import com.pmease.gitplex.core.entity.PullRequest;
+import com.pmease.gitplex.core.entity.PullRequestReviewInvitation;
+import com.pmease.gitplex.core.event.pullrequest.InvitingPullRequestReview;
+import com.pmease.gitplex.core.manager.PullRequestReviewInvitationManager;
+import com.pmease.gitplex.core.manager.PullRequestReviewManager;
+
+@Singleton
+public class DefaultPullRequestReviewInvitationManager extends AbstractEntityManager<PullRequestReviewInvitation>
+ implements PullRequestReviewInvitationManager {
+
+ private final PullRequestReviewManager reviewManager;
+
+ private final ListenerRegistry listenerRegistry;
+
+ @Inject
+ public DefaultPullRequestReviewInvitationManager(Dao dao, PullRequestReviewManager reviewManager,
+ ListenerRegistry listenerRegistry) {
+ super(dao);
+
+ this.reviewManager = reviewManager;
+ this.listenerRegistry = listenerRegistry;
+ }
+
+ @Sessional
+ @Override
+ public PullRequestReviewInvitation find(Account reviewer, PullRequest request) {
+ return find(EntityCriteria.of(PullRequestReviewInvitation.class)
+ .add(Restrictions.eq("reviewer", reviewer))
+ .add(Restrictions.eq("request", request)));
+ }
+
+ @Transactional
+ @Override
+ public void save(PullRequestReviewInvitation invitation) {
+ dao.persist(invitation);
+
+ listenerRegistry.notify(new InvitingPullRequestReview(invitation));
+ }
+
+ @Transactional
+ @Override
+ public void update(Collection<PullRequestReviewInvitation> invitations, Date since) {
+ for (PullRequestReviewInvitation invitation: invitations) {
+ if (invitation.getDate().getTime()>=since.getTime()) {
+ save(invitation);
+ if (invitation.isExcluded())
+ reviewManager.deleteAll(invitation.getUser(), invitation.getRequest());
+ }
+ }
+ }
+}
diff --git a/gitplex.core/src/main/java/com/pmease/gitplex/core/manager/impl/DefaultPullRequestReviewManager.java b/gitplex.core/src/main/java/com/pmease/gitplex/core/manager/impl/DefaultPullRequestReviewManager.java
index 0eb8a22cfd..75b9c93f0c 100644
--- a/gitplex.core/src/main/java/com/pmease/gitplex/core/manager/impl/DefaultPullRequestReviewManager.java
+++ b/gitplex.core/src/main/java/com/pmease/gitplex/core/manager/impl/DefaultPullRequestReviewManager.java
@@ -1,83 +1,96 @@
-package com.pmease.gitplex.core.manager.impl;
-
-import java.util.Date;
-import java.util.List;
-
-import javax.inject.Inject;
-import javax.inject.Singleton;
-
-import org.hibernate.criterion.Order;
-import org.hibernate.criterion.Restrictions;
-
-import com.pmease.commons.hibernate.Sessional;
-import com.pmease.commons.hibernate.Transactional;
-import com.pmease.commons.hibernate.dao.AbstractEntityManager;
-import com.pmease.commons.hibernate.dao.Dao;
-import com.pmease.commons.hibernate.dao.EntityCriteria;
-import com.pmease.commons.loader.ListenerRegistry;
-import com.pmease.gitplex.core.entity.Account;
-import com.pmease.gitplex.core.entity.PullRequest;
-import com.pmease.gitplex.core.entity.PullRequestUpdate;
-import com.pmease.gitplex.core.entity.PullRequestReview;
-import com.pmease.gitplex.core.event.pullrequest.PullRequestApproved;
-import com.pmease.gitplex.core.event.pullrequest.PullRequestDisapproved;
-import com.pmease.gitplex.core.event.pullrequest.PullRequestReviewDeleted;
-import com.pmease.gitplex.core.manager.AccountManager;
-import com.pmease.gitplex.core.manager.PullRequestReviewManager;
-
-@Singleton
-public class DefaultPullRequestReviewManager extends AbstractEntityManager<PullRequestReview> implements PullRequestReviewManager {
-
- private final AccountManager accountManager;
-
- private final ListenerRegistry listenerRegistry;
-
- @Inject
- public DefaultPullRequestReviewManager(Dao dao, AccountManager accountManager, ListenerRegistry listenerRegistry) {
- super(dao);
-
- this.accountManager = accountManager;
- this.listenerRegistry = listenerRegistry;
- }
-
- @Sessional
- @Override
- public PullRequestReview find(Account user, PullRequestUpdate update) {
- return find(EntityCriteria.of(PullRequestReview.class)
- .add(Restrictions.eq("user", user))
- .add(Restrictions.eq("update", update)));
- }
-
- @Transactional
- @Override
- public void review(PullRequest request, PullRequestReview.Result result, String note) {
- PullRequestReview review = new PullRequestReview();
- review.setUpdate(request.getLatestUpdate());
- review.setResult(result);
- review.setUser(accountManager.getCurrent());
- review.setDate(new Date());
- save(review);
-
- if (result == PullRequestReview.Result.APPROVE)
- listenerRegistry.notify(new PullRequestApproved(review, note));
- else
- listenerRegistry.notify(new PullRequestDisapproved(review, note));
- }
-
- @Transactional
- @Override
- public void delete(PullRequestReview entity) {
- super.delete(entity);
- listenerRegistry.notify(new PullRequestReviewDeleted(entity, accountManager.getCurrent(), null));
- }
-
- @Sessional
- @Override
- public List<PullRequestReview> findAll(PullRequest request) {
- EntityCriteria<PullRequestReview> criteria = EntityCriteria.of(PullRequestReview.class);
- criteria.createCriteria("update").add(Restrictions.eq("request", request));
- criteria.addOrder(Order.asc("date"));
- return findAll(criteria);
- }
-
-}
+package com.pmease.gitplex.core.manager.impl;
+
+import java.util.Date;
+import java.util.Iterator;
+import java.util.List;
+
+import javax.inject.Inject;
+import javax.inject.Singleton;
+
+import org.hibernate.criterion.Order;
+import org.hibernate.criterion.Restrictions;
+
+import com.pmease.commons.hibernate.Sessional;
+import com.pmease.commons.hibernate.Transactional;
+import com.pmease.commons.hibernate.dao.AbstractEntityManager;
+import com.pmease.commons.hibernate.dao.Dao;
+import com.pmease.commons.hibernate.dao.EntityCriteria;
+import com.pmease.commons.loader.ListenerRegistry;
+import com.pmease.gitplex.core.entity.Account;
+import com.pmease.gitplex.core.entity.PullRequest;
+import com.pmease.gitplex.core.entity.PullRequestReview;
+import com.pmease.gitplex.core.entity.PullRequestUpdate;
+import com.pmease.gitplex.core.event.pullrequest.PullRequestApproved;
+import com.pmease.gitplex.core.event.pullrequest.PullRequestDisapproved;
+import com.pmease.gitplex.core.event.pullrequest.PullRequestReviewDeleted;
+import com.pmease.gitplex.core.manager.AccountManager;
+import com.pmease.gitplex.core.manager.PullRequestReviewManager;
+
+@Singleton
+public class DefaultPullRequestReviewManager extends AbstractEntityManager<PullRequestReview> implements PullRequestReviewManager {
+
+ private final AccountManager accountManager;
+
+ private final ListenerRegistry listenerRegistry;
+
+ @Inject
+ public DefaultPullRequestReviewManager(Dao dao, AccountManager accountManager, ListenerRegistry listenerRegistry) {
+ super(dao);
+
+ this.accountManager = accountManager;
+ this.listenerRegistry = listenerRegistry;
+ }
+
+ @Sessional
+ @Override
+ public PullRequestReview find(Account user, PullRequestUpdate update) {
+ return find(EntityCriteria.of(PullRequestReview.class)
+ .add(Restrictions.eq("user", user))
+ .add(Restrictions.eq("update", update)));
+ }
+
+ @Transactional
+ @Override
+ public void review(PullRequest request, PullRequestReview.Result result, String note) {
+ PullRequestReview review = new PullRequestReview();
+ review.setUpdate(request.getLatestUpdate());
+ review.setResult(result);
+ review.setUser(accountManager.getCurrent());
+ review.setDate(new Date());
+ save(review);
+
+ if (result == PullRequestReview.Result.APPROVE)
+ listenerRegistry.notify(new PullRequestApproved(review, note));
+ else
+ listenerRegistry.notify(new PullRequestDisapproved(review, note));
+ }
+
+ @Transactional
+ @Override
+ public void delete(PullRequestReview entity) {
+ super.delete(entity);
+ listenerRegistry.notify(new PullRequestReviewDeleted(entity, accountManager.getCurrent(), null));
+ }
+
+ @Sessional
+ @Override
+ public List<PullRequestReview> findAll(PullRequest request) {
+ EntityCriteria<PullRequestReview> criteria = EntityCriteria.of(PullRequestReview.class);
+ criteria.createCriteria("update").add(Restrictions.eq("request", request));
+ criteria.addOrder(Order.asc("date"));
+ return findAll(criteria);
+ }
+
+ @Transactional
+ @Override
+ public void deleteAll(Account user, PullRequest request) {
+ for (Iterator<PullRequestReview> it = request.getReviews().iterator(); it.hasNext();) {
+ PullRequestReview review = it.next();
+ if (review.getUser().equals(user)) {
+ delete(review);
+ it.remove();
+ }
+ }
+ }
+
+}
diff --git a/gitplex.core/src/main/java/com/pmease/gitplex/core/manager/impl/DefaultPullRequestUpdateManager.java b/gitplex.core/src/main/java/com/pmease/gitplex/core/manager/impl/DefaultPullRequestUpdateManager.java
index 443b923e1f..9c06bfc3f2 100644
--- a/gitplex.core/src/main/java/com/pmease/gitplex/core/manager/impl/DefaultPullRequestUpdateManager.java
+++ b/gitplex.core/src/main/java/com/pmease/gitplex/core/manager/impl/DefaultPullRequestUpdateManager.java
@@ -53,9 +53,6 @@ public class DefaultPullRequestUpdateManager extends AbstractEntityManager<PullR
String sourceHead = request.getSource().getObjectName();
- update.setMergeCommitHash(GitUtils.getMergeBase(request.getTargetDepot().getRepository(),
- request.getTarget().getObjectId(), ObjectId.fromString(update.getHeadCommitHash())).name());
-
dao.persist(update);
if (!request.getTargetDepot().equals(request.getSourceDepot())) {
diff --git a/gitplex.core/src/main/java/com/pmease/gitplex/core/security/SecurityUtils.java b/gitplex.core/src/main/java/com/pmease/gitplex/core/security/SecurityUtils.java
index 002e298fc1..de0a33faaf 100644
--- a/gitplex.core/src/main/java/com/pmease/gitplex/core/security/SecurityUtils.java
+++ b/gitplex.core/src/main/java/com/pmease/gitplex/core/security/SecurityUtils.java
@@ -34,12 +34,12 @@ public class SecurityUtils extends org.apache.shiro.SecurityUtils {
public static boolean canModify(PullRequest request) {
Depot depot = request.getTargetDepot();
- if (SecurityUtils.getSubject().isPermitted(ObjectPermission.ofDepotAdmin(depot))) {
+ if (canManage(depot)) {
return true;
} else {
Account currentUser = getAccount();
- Account submitter = request.getSubmitter();
- return currentUser != null && currentUser.equals(submitter);
+ return currentUser != null &&
+ (currentUser.equals(request.getSubmitter()) || currentUser.equals(request.getAssignee()));
}
}
@@ -49,7 +49,7 @@ public class SecurityUtils extends org.apache.shiro.SecurityUtils {
public static boolean canModify(PullRequestReview review) {
Depot depot = review.getUpdate().getRequest().getTargetDepot();
- if (SecurityUtils.getSubject().isPermitted(ObjectPermission.ofDepotAdmin(depot))) {
+ if (canManage(depot)) {
return true;
} else {
return review.getUser().equals(getAccount());
diff --git a/gitplex.web/src/main/java/com/pmease/gitplex/web/component/avatar/RemoveableAvatar.java b/gitplex.web/src/main/java/com/pmease/gitplex/web/component/avatar/RemoveableAvatar.java
index eed26d07fc..c68ba5e5d4 100644
--- a/gitplex.web/src/main/java/com/pmease/gitplex/web/component/avatar/RemoveableAvatar.java
+++ b/gitplex.web/src/main/java/com/pmease/gitplex/web/component/avatar/RemoveableAvatar.java
@@ -1,87 +1,68 @@
-package com.pmease.gitplex.web.component.avatar;
-
-import org.apache.commons.lang3.StringEscapeUtils;
-import org.apache.wicket.ajax.AjaxRequestTarget;
-import org.apache.wicket.ajax.markup.html.AjaxLink;
-import org.apache.wicket.markup.head.CssHeaderItem;
-import org.apache.wicket.markup.head.IHeaderResponse;
-import org.apache.wicket.markup.html.panel.Panel;
-import org.apache.wicket.model.IModel;
-import org.apache.wicket.model.LoadableDetachableModel;
-import org.apache.wicket.request.resource.CssResourceReference;
-
-import com.pmease.commons.wicket.behavior.TooltipBehavior;
-import com.pmease.gitplex.core.entity.Account;
-
-@SuppressWarnings("serial")
-public abstract class RemoveableAvatar extends Panel {
-
- private final IModel<Account> userModel;
-
- private final String actionName;
-
- public RemoveableAvatar(String id, IModel<Account> userModel, String actionName) {
- super(id);
-
- this.userModel = userModel;
- this.actionName = actionName;
- }
-
- @Override
- protected void onInitialize() {
- super.onInitialize();
-
- AjaxLink<Void> link = new AjaxLink<Void>("remove") {
-
- @Override
- public void onClick(AjaxRequestTarget target) {
- onAvatarRemove(target);
- }
-
- };
-
- link.add(new Avatar("avatar", userModel.getObject(), null));
- link.add(new TooltipBehavior(new LoadableDetachableModel<String>() {
-
- @Override
- protected String load() {
- // Force nowrap here when display tooltip as otherwise user name will be wrapped inside
- // an element with position set to relative
- String tooltip;
- if (isEnabled()) {
- if (actionName != null)
- tooltip = actionName + " " + userModel.getObject().getDisplayName();
- else
- tooltip = userModel.getObject().getDisplayName();
- } else {
- tooltip = userModel.getObject().getDisplayName();
- }
- return "<span style='white-space: nowrap;'>" + StringEscapeUtils.escapeHtml4(tooltip) + "</span>";
- }
-
- }));
-
- add(link);
- }
-
- protected Account getUser() {
- return userModel.getObject();
- }
-
- protected abstract void onAvatarRemove(AjaxRequestTarget target);
-
- @Override
- protected void onDetach() {
- userModel.detach();
-
- super.onDetach();
- }
-
- @Override
- public void renderHead(IHeaderResponse response) {
- super.renderHead(response);
- response.render(CssHeaderItem.forReference(
- new CssResourceReference(RemoveableAvatar.class, "avatar.css")));
- }
-
-}
+package com.pmease.gitplex.web.component.avatar;
+
+import org.apache.commons.lang3.StringEscapeUtils;
+import org.apache.wicket.ajax.markup.html.AjaxLink;
+import org.apache.wicket.behavior.AttributeAppender;
+import org.apache.wicket.markup.ComponentTag;
+import org.apache.wicket.markup.head.CssHeaderItem;
+import org.apache.wicket.markup.head.IHeaderResponse;
+import org.apache.wicket.model.IModel;
+import org.apache.wicket.model.Model;
+import org.apache.wicket.request.resource.CssResourceReference;
+
+import com.pmease.commons.wicket.behavior.TooltipBehavior;
+import com.pmease.gitplex.core.GitPlex;
+import com.pmease.gitplex.core.entity.Account;
+import com.pmease.gitplex.web.avatar.AvatarManager;
+
+@SuppressWarnings("serial")
+public abstract class RemoveableAvatar extends AjaxLink<Account> {
+
+ public RemoveableAvatar(String id, IModel<Account> model) {
+ super(id, model);
+ }
+
+ @Override
+ protected void onInitialize() {
+ super.onInitialize();
+
+ configure();
+
+ Account user = getModelObject();
+ String tooltip;
+ // Force nowrap here when display tooltip as otherwise user name will be wrapped inside
+ // an element with position set to relative
+ if (isEnabled()) {
+ tooltip = "Remove reviewer " + user.getDisplayName();
+ } else {
+ tooltip = user.getDisplayName();
+ }
+ add(new TooltipBehavior(Model.of("<span style='white-space: nowrap;'>"
+ + StringEscapeUtils.escapeHtml4(tooltip) + "</span>")));
+ add(AttributeAppender.append("class", "removeable-avatar"));
+ add(AttributeAppender.append("data-html", "true"));
+
+ setEscapeModelStrings(false);
+ }
+
+ @Override
+ public IModel<?> getBody() {
+ String url = GitPlex.getInstance(AvatarManager.class).getAvatarUrl(getModelObject());
+ return Model.of("<img src='" + url + "' class='avatar'></img> <i class='fa fa-times'></i>");
+ }
+
+ @Override
+ protected void onComponentTag(ComponentTag tag) {
+ super.onComponentTag(tag);
+ if (!isEnabled())
+ tag.setName("span");
+ }
+
+ @Override
+ public void renderHead(IHeaderResponse response) {
+ super.renderHead(response);
+ response.render(CssHeaderItem.forReference(
+ new CssResourceReference(RemoveableAvatar.class, "avatar.css")));
+ }
+
+}
diff --git a/gitplex.web/src/main/java/com/pmease/gitplex/web/component/avatar/avatar.css b/gitplex.web/src/main/java/com/pmease/gitplex/web/component/avatar/avatar.css
index 39a7752ccc..5f57d5ff42 100644
--- a/gitplex.web/src/main/java/com/pmease/gitplex/web/component/avatar/avatar.css
+++ b/gitplex.web/src/main/java/com/pmease/gitplex/web/component/avatar/avatar.css
@@ -1,38 +1,39 @@
-img.avatar {
- border-radius: 3px;
- height: 24px;
- width: 24px;
-}
-.contributor-avatars {
- position: relative;
-}
-.contributor-avatars .author .avatar {
- height: 36px;
- width: 36px;
-}
-.contributor-avatars .committer .avatar {
- position: absolute;
- height: 16px;
- width: 16px;
- left: 22px;
- top: 13px;
-}
-
-.removeable-avatar {
- position: relative;
-}
-.removeable-avatar img {
- width: 32px !important;
- height: 32px !important;
-}
-.removeable-avatar i {
- display: none;
- color: red;
- font-size: 30px;
- position: absolute;
- left: 4px;
- top: -6px;
-}
-a.removeable-avatar:hover i {
- display: inline;
-}
+img.avatar {
+ border-radius: 3px;
+ height: 24px;
+ width: 24px;
+}
+.contributor-avatars {
+ position: relative;
+}
+.contributor-avatars .author .avatar {
+ height: 36px;
+ width: 36px;
+}
+.contributor-avatars .committer .avatar {
+ position: absolute;
+ height: 16px;
+ width: 16px;
+ left: 22px;
+ top: 13px;
+}
+
+.removeable-avatar {
+ position: relative;
+ display: block;
+}
+.removeable-avatar img {
+ width: 32px !important;
+ height: 32px !important;
+}
+.removeable-avatar i {
+ display: none;
+ color: red;
+ font-size: 30px;
+ position: absolute;
+ left: 4px;
+ top: 1px;
+}
+a.removeable-avatar:hover i {
+ display: inline;
+}
diff --git a/gitplex.web/src/main/java/com/pmease/gitplex/web/component/pullrequest/requestreviewer/ReviewerAvatar.java b/gitplex.web/src/main/java/com/pmease/gitplex/web/component/pullrequest/requestreviewer/ReviewerAvatar.java
index 6fa124958e..b7659fde42 100644
--- a/gitplex.web/src/main/java/com/pmease/gitplex/web/component/pullrequest/requestreviewer/ReviewerAvatar.java
+++ b/gitplex.web/src/main/java/com/pmease/gitplex/web/component/pullrequest/requestreviewer/ReviewerAvatar.java
@@ -1,97 +1,88 @@
-package com.pmease.gitplex.web.component.pullrequest.requestreviewer;
-
-import java.util.Date;
-import java.util.HashSet;
-import java.util.Set;
-
-import org.apache.wicket.ajax.AjaxRequestTarget;
-import org.apache.wicket.model.IModel;
-
-import com.pmease.gitplex.core.GitPlex;
-import com.pmease.gitplex.core.entity.PullRequest;
-import com.pmease.gitplex.core.entity.PullRequestReviewInvitation;
-import com.pmease.gitplex.core.entity.Account;
-import com.pmease.gitplex.core.manager.PullRequestReviewInvitationManager;
-import com.pmease.gitplex.core.manager.AccountManager;
-import com.pmease.gitplex.core.security.SecurityUtils;
-import com.pmease.gitplex.web.component.avatar.RemoveableAvatar;
-import com.pmease.gitplex.web.model.EntityModel;
-import com.pmease.gitplex.web.model.UserModel;
-
-@SuppressWarnings("serial")
-public class ReviewerAvatar extends RemoveableAvatar {
-
- private final PullRequestReviewInvitation invitation;
-
- private final IModel<PullRequest> requestModel;
-
- public ReviewerAvatar(String id, PullRequestReviewInvitation invitation) {
- super(id, new UserModel(invitation.getUser()), "Remove reviewer");
-
- this.invitation = invitation;
- requestModel = new EntityModel<PullRequest>(invitation.getRequest());
- }
-
- @Override
- protected void onConfigure() {
- super.onConfigure();
-
- PullRequest request = requestModel.getObject();
- Account currentUser = GitPlex.getInstance(AccountManager.class).getCurrent();
-
- boolean reviewEffective = false;
- if (!request.isNew())
- reviewEffective = request.isReviewEffective(getUser());
- setEnabled(request.isOpen() && !reviewEffective
- && (currentUser!= null && currentUser.equals(request.getSubmitter()) || SecurityUtils.canManage(request.getTargetDepot())));
- }
-
- @Override
- protected void onAvatarRemove(AjaxRequestTarget target) {
- Date now = new Date();
- PullRequest request = requestModel.getObject();
- Set<Account> prevInvited = new HashSet<>();
- for (PullRequestReviewInvitation each: request.getReviewInvitations()) {
- if (each.isPreferred())
- prevInvited.add(each.getUser());
- if (each.getUser().equals(invitation.getUser())) {
- each.setPerferred(false);
- each.setDate(new Date());
- }
- }
- request.getTargetDepot().getGateKeeper().checkRequest(request);
-
- Set<Account> nowInvited = new HashSet<>();
- for (PullRequestReviewInvitation each: request.getReviewInvitations()) {
- if (each.isPreferred())
- nowInvited.add(each.getUser());
- }
-
- if (nowInvited.contains(invitation.getUser())) {
- getSession().warn("Reviewer '" + invitation.getUser().getDisplayName()
- + "' is required by gate keeper and can not be removed");
- } else {
- nowInvited.removeAll(prevInvited);
- if (!nowInvited.isEmpty()) {
- getSession().warn("Reviewer '" + invitation.getUser().getDisplayName()
- + "' is removed and user '" + nowInvited.iterator().next().getDisplayName()
- + "' is added as reviewer automatically to satisfy gate keeper requirement.");
- }
- }
- if (!request.isNew()) {
- PullRequestReviewInvitationManager reviewInvitationManager = GitPlex.getInstance(PullRequestReviewInvitationManager.class);
- for (PullRequestReviewInvitation invitation: request.getReviewInvitations()) {
- if (invitation.getDate().getTime()>=now.getTime())
- reviewInvitationManager.save(invitation);
- }
- }
- }
-
- @Override
- protected void onDetach() {
- requestModel.detach();
-
- super.onDetach();
- }
-
-}
+package com.pmease.gitplex.web.component.pullrequest.requestreviewer;
+
+import java.util.Date;
+import java.util.HashSet;
+import java.util.Set;
+
+import org.apache.wicket.ajax.AjaxRequestTarget;
+import org.apache.wicket.model.IModel;
+
+import com.pmease.gitplex.core.GitPlex;
+import com.pmease.gitplex.core.entity.Account;
+import com.pmease.gitplex.core.entity.PullRequest;
+import com.pmease.gitplex.core.entity.PullRequestReviewInvitation;
+import com.pmease.gitplex.core.manager.PullRequestReviewInvitationManager;
+import com.pmease.gitplex.core.security.SecurityUtils;
+import com.pmease.gitplex.web.component.avatar.RemoveableAvatar;
+import com.pmease.gitplex.web.model.EntityModel;
+import com.pmease.gitplex.web.model.UserModel;
+
+@SuppressWarnings("serial")
+public class ReviewerAvatar extends RemoveableAvatar {
+
+ private final PullRequestReviewInvitation invitation;
+
+ private final IModel<PullRequest> requestModel;
+
+ public ReviewerAvatar(String id, PullRequestReviewInvitation invitation) {
+ super(id, new UserModel(invitation.getUser()));
+
+ this.invitation = invitation;
+ requestModel = new EntityModel<PullRequest>(invitation.getRequest());
+ }
+
+ @Override
+ protected void onConfigure() {
+ super.onConfigure();
+
+ PullRequest request = requestModel.getObject();
+ setEnabled(request.isOpen() && SecurityUtils.canModify(request));
+ }
+
+ @Override
+ public void onClick(AjaxRequestTarget target) {
+ Date now = new Date();
+ PullRequest request = requestModel.getObject();
+ Set<Account> prevInvited = new HashSet<>();
+ for (PullRequestReviewInvitation each: request.getReviewInvitations()) {
+ if (!each.isExcluded())
+ prevInvited.add(each.getUser());
+ if (each.getUser().equals(invitation.getUser())) {
+ each.setExcluded(true);
+ each.setDate(new Date());
+ }
+ }
+ request.getTargetDepot().getGateKeeper().checkRequest(request);
+
+ Set<Account> nowInvited = new HashSet<>();
+ for (PullRequestReviewInvitation each: request.getReviewInvitations()) {
+ if (!each.isExcluded())
+ nowInvited.add(each.getUser());
+ }
+
+ if (nowInvited.contains(invitation.getUser())) {
+ getSession().warn("Reviewer '" + invitation.getUser().getDisplayName()
+ + "' is required by gate keeper and can not be removed");
+ } else {
+ nowInvited.removeAll(prevInvited);
+ if (!nowInvited.isEmpty()) {
+ getSession().warn("Reviewer '" + invitation.getUser().getDisplayName()
+ + "' is removed and user '" + nowInvited.iterator().next().getDisplayName()
+ + "' is added as reviewer automatically to satisfy gate keeper requirement.");
+ }
+ }
+ if (!request.isNew()) {
+ PullRequestReviewInvitationManager reviewInvitationManager =
+ GitPlex.getInstance(PullRequestReviewInvitationManager.class);
+ reviewInvitationManager.update(request.getReviewInvitations(), now);
+ }
+ }
+
+ @Override
+ protected void onDetach() {
+ requestModel.detach();
+
+ super.onDetach();
+ }
+
+}
diff --git a/gitplex.web/src/main/java/com/pmease/gitplex/web/component/pullrequest/requestreviewer/ReviewerChoice.java b/gitplex.web/src/main/java/com/pmease/gitplex/web/component/pullrequest/requestreviewer/ReviewerChoice.java
index d65c246104..63cbbe3017 100644
--- a/gitplex.web/src/main/java/com/pmease/gitplex/web/component/pullrequest/requestreviewer/ReviewerChoice.java
+++ b/gitplex.web/src/main/java/com/pmease/gitplex/web/component/pullrequest/requestreviewer/ReviewerChoice.java
@@ -1,87 +1,87 @@
-package com.pmease.gitplex.web.component.pullrequest.requestreviewer;
-
-import java.util.Date;
-
-import org.apache.wicket.ajax.AjaxRequestTarget;
-import org.apache.wicket.markup.head.IHeaderResponse;
-import org.apache.wicket.markup.head.JavaScriptHeaderItem;
-import org.apache.wicket.model.IModel;
-
-import com.pmease.commons.wicket.component.select2.SelectToAddChoice;
-import com.pmease.gitplex.core.GitPlex;
-import com.pmease.gitplex.core.entity.PullRequest;
-import com.pmease.gitplex.core.entity.PullRequestReviewInvitation;
-import com.pmease.gitplex.core.entity.Account;
-import com.pmease.gitplex.core.manager.PullRequestReviewInvitationManager;
-import com.pmease.gitplex.core.manager.AccountManager;
-import com.pmease.gitplex.core.security.SecurityUtils;
-import com.pmease.gitplex.web.component.accountchoice.AccountChoiceResourceReference;
-
-@SuppressWarnings("serial")
-public abstract class ReviewerChoice extends SelectToAddChoice<Account> {
-
- private final IModel<PullRequest> requestModel;
-
- public ReviewerChoice(String id, IModel<PullRequest> requestModel) {
- super(id, new ReviewerProvider(requestModel));
-
- this.requestModel = requestModel;
- }
-
- @Override
- protected void onConfigure() {
- super.onConfigure();
-
- PullRequest request = requestModel.getObject();
- Account currentUser = GitPlex.getInstance(AccountManager.class).getCurrent();
- setVisible(request.isOpen()
- && !request.getPotentialReviewers().isEmpty()
- && (currentUser != null && currentUser.equals(request.getSubmitter()) || SecurityUtils.canManage(request.getTargetDepot())));
- }
-
- @Override
- protected void onInitialize() {
- super.onInitialize();
-
- getSettings().setPlaceholder("Select user to add as reviewer...");
- getSettings().setFormatResult("gitplex.accountChoiceFormatter.formatResult");
- getSettings().setFormatSelection("gitplex.accountChoiceFormatter.formatSelection");
- getSettings().setEscapeMarkup("gitplex.accountChoiceFormatter.escapeMarkup");
- }
-
- @Override
- public void renderHead(IHeaderResponse response) {
- super.renderHead(response);
-
- response.render(JavaScriptHeaderItem.forReference(AccountChoiceResourceReference.INSTANCE));
- }
-
- @Override
- protected void onDetach() {
- requestModel.detach();
-
- super.onDetach();
- }
-
- protected void onSelect(AjaxRequestTarget target, Account user) {
- PullRequest request = requestModel.getObject();
- PullRequestReviewInvitation invitation = null;
- for(PullRequestReviewInvitation each: request.getReviewInvitations()) {
- if (each.getUser().equals(user)) {
- invitation = each;
- break;
- }
- }
- if (invitation != null) {
- invitation.setPerferred(true);
- invitation.setDate(new Date());
- } else {
- invitation = new PullRequestReviewInvitation();
- invitation.setRequest(request);
- invitation.setUser(user);
- request.getReviewInvitations().add(invitation);
- }
- if (!request.isNew())
- GitPlex.getInstance(PullRequestReviewInvitationManager.class).save(invitation);
- };
-}
+package com.pmease.gitplex.web.component.pullrequest.requestreviewer;
+
+import java.util.Date;
+
+import org.apache.wicket.ajax.AjaxRequestTarget;
+import org.apache.wicket.markup.head.IHeaderResponse;
+import org.apache.wicket.markup.head.JavaScriptHeaderItem;
+import org.apache.wicket.model.IModel;
+
+import com.pmease.commons.wicket.component.select2.SelectToAddChoice;
+import com.pmease.gitplex.core.GitPlex;
+import com.pmease.gitplex.core.entity.PullRequest;
+import com.pmease.gitplex.core.entity.PullRequestReviewInvitation;
+import com.pmease.gitplex.core.entity.Account;
+import com.pmease.gitplex.core.manager.PullRequestReviewInvitationManager;
+import com.pmease.gitplex.core.manager.AccountManager;
+import com.pmease.gitplex.core.security.SecurityUtils;
+import com.pmease.gitplex.web.component.accountchoice.AccountChoiceResourceReference;
+
+@SuppressWarnings("serial")
+public abstract class ReviewerChoice extends SelectToAddChoice<Account> {
+
+ private final IModel<PullRequest> requestModel;
+
+ public ReviewerChoice(String id, IModel<PullRequest> requestModel) {
+ super(id, new ReviewerProvider(requestModel));
+
+ this.requestModel = requestModel;
+ }
+
+ @Override
+ protected void onConfigure() {
+ super.onConfigure();
+
+ PullRequest request = requestModel.getObject();
+ Account currentUser = GitPlex.getInstance(AccountManager.class).getCurrent();
+ setVisible(request.isOpen()
+ && !request.getPotentialReviewers().isEmpty()
+ && (currentUser != null && currentUser.equals(request.getSubmitter()) || SecurityUtils.canManage(request.getTargetDepot())));
+ }
+
+ @Override
+ protected void onInitialize() {
+ super.onInitialize();
+
+ getSettings().setPlaceholder("Select user to add as reviewer...");
+ getSettings().setFormatResult("gitplex.accountChoiceFormatter.formatResult");
+ getSettings().setFormatSelection("gitplex.accountChoiceFormatter.formatSelection");
+ getSettings().setEscapeMarkup("gitplex.accountChoiceFormatter.escapeMarkup");
+ }
+
+ @Override
+ public void renderHead(IHeaderResponse response) {
+ super.renderHead(response);
+
+ response.render(JavaScriptHeaderItem.forReference(AccountChoiceResourceReference.INSTANCE));
+ }
+
+ @Override
+ protected void onDetach() {
+ requestModel.detach();
+
+ super.onDetach();
+ }
+
+ protected void onSelect(AjaxRequestTarget target, Account user) {
+ PullRequest request = requestModel.getObject();
+ PullRequestReviewInvitation invitation = null;
+ for(PullRequestReviewInvitation each: request.getReviewInvitations()) {
+ if (each.getUser().equals(user)) {
+ invitation = each;
+ break;
+ }
+ }
+ if (invitation != null) {
+ invitation.setExcluded(false);
+ invitation.setDate(new Date());
+ } else {
+ invitation = new PullRequestReviewInvitation();
+ invitation.setRequest(request);
+ invitation.setUser(user);
+ request.getReviewInvitations().add(invitation);
+ }
+ if (!request.isNew())
+ GitPlex.getInstance(PullRequestReviewInvitationManager.class).save(invitation);
+ };
+}
diff --git a/gitplex.web/src/main/java/com/pmease/gitplex/web/component/pullrequest/ReviewResultIcon.java b/gitplex.web/src/main/java/com/pmease/gitplex/web/component/pullrequest/reviewresult/ReviewResultIcon.java
similarity index 63%
rename from gitplex.web/src/main/java/com/pmease/gitplex/web/component/pullrequest/ReviewResultIcon.java
rename to gitplex.web/src/main/java/com/pmease/gitplex/web/component/pullrequest/reviewresult/ReviewResultIcon.java
index c86d8ab4f4..7e9bc6fc6b 100644
--- a/gitplex.web/src/main/java/com/pmease/gitplex/web/component/pullrequest/ReviewResultIcon.java
+++ b/gitplex.web/src/main/java/com/pmease/gitplex/web/component/pullrequest/reviewresult/ReviewResultIcon.java
@@ -1,53 +1,65 @@
-package com.pmease.gitplex.web.component.pullrequest;
-
-import org.apache.wicket.behavior.AttributeAppender;
-import org.apache.wicket.markup.head.CssHeaderItem;
-import org.apache.wicket.markup.head.IHeaderResponse;
-import org.apache.wicket.markup.html.WebComponent;
-import org.apache.wicket.model.IModel;
-import org.apache.wicket.model.Model;
-import org.apache.wicket.request.resource.CssResourceReference;
-
-import com.pmease.commons.wicket.behavior.TooltipBehavior;
-import com.pmease.gitplex.core.entity.PullRequestReview;
-
-@SuppressWarnings("serial")
-public class ReviewResultIcon extends WebComponent {
-
- public ReviewResultIcon(String id, IModel<PullRequestReview> reviewModel) {
- super(id, reviewModel);
- }
-
- @Override
- protected void onInitialize() {
- super.onInitialize();
-
- PullRequestReview review = (PullRequestReview) getDefaultModelObject();
- String css;
- String tooltip;
- if (review.getUpdate().equals(review.getUpdate().getRequest().getLatestUpdate())) {
- if (review.getResult() == PullRequestReview.Result.APPROVE) {
- css = " review-result approved current fa fa-check-circle";
- tooltip = "Approved";
- } else {
- css = " review-result disapproved current fa fa-times-circle";
- tooltip = "Disapproved";
- }
- } else if (review.getResult() == PullRequestReview.Result.APPROVE) {
- css = " review-result approved previous fa fa-check-circle";
- tooltip = "Approved on previous updates";
- } else {
- css = " review-result disapproved previous fa fa-times-circle";
- tooltip = "Disapproved on previous updates";
- }
- add(AttributeAppender.append("class", css));
- add(new TooltipBehavior(Model.of(tooltip)));
- }
-
- @Override
- public void renderHead(IHeaderResponse response) {
- super.renderHead(response);
- response.render(CssHeaderItem.forReference(new CssResourceReference(ReviewResultIcon.class, "review-result.css")));
- }
-
-}
+package com.pmease.gitplex.web.component.pullrequest.reviewresult;
+
+import org.apache.wicket.Component;
+import org.apache.wicket.behavior.AttributeAppender;
+import org.apache.wicket.markup.head.CssHeaderItem;
+import org.apache.wicket.markup.head.IHeaderResponse;
+import org.apache.wicket.markup.html.WebComponent;
+import org.apache.wicket.model.IModel;
+import org.apache.wicket.request.resource.CssResourceReference;
+
+import com.pmease.commons.wicket.behavior.dropdown.DropdownHover;
+import com.pmease.commons.wicket.component.floating.AlignPlacement;
+import com.pmease.gitplex.core.entity.PullRequestReview;
+
+@SuppressWarnings("serial")
+public class ReviewResultIcon extends WebComponent {
+
+ private final IModel<PullRequestReview> model;
+
+ public ReviewResultIcon(String id, IModel<PullRequestReview> model) {
+ super(id);
+ this.model = model;
+ }
+
+ @Override
+ protected void onInitialize() {
+ super.onInitialize();
+
+ PullRequestReview review = model.getObject();
+ String css;
+ if (review.getUpdate().equals(review.getUpdate().getRequest().getLatestUpdate())) {
+ if (review.getResult() == PullRequestReview.Result.APPROVE) {
+ css = " review-result approved current fa fa-check-circle";
+ } else {
+ css = " review-result disapproved current fa fa-times-circle";
+ }
+ } else if (review.getResult() == PullRequestReview.Result.APPROVE) {
+ css = " review-result approved previous fa fa-check-circle";
+ } else {
+ css = " review-result disapproved previous fa fa-times-circle";
+ }
+ add(AttributeAppender.append("class", css));
+
+ add(new DropdownHover(new AlignPlacement(100, 0, 0, 100, 0)) {
+
+ @Override
+ protected Component newContent(String id) {
+ return new ReviewResultTooltip(id, model);
+ }
+ });
+ }
+
+ @Override
+ protected void onDetach() {
+ model.detach();
+ super.onDetach();
+ }
+
+ @Override
+ public void renderHead(IHeaderResponse response) {
+ super.renderHead(response);
+ response.render(CssHeaderItem.forReference(new CssResourceReference(ReviewResultIcon.class, "review-result.css")));
+ }
+
+}
diff --git a/gitplex.web/src/main/java/com/pmease/gitplex/web/component/pullrequest/reviewresult/ReviewResultTooltip.html b/gitplex.web/src/main/java/com/pmease/gitplex/web/component/pullrequest/reviewresult/ReviewResultTooltip.html
new file mode 100644
index 0000000000..1574b3e29c
--- /dev/null
+++ b/gitplex.web/src/main/java/com/pmease/gitplex/web/component/pullrequest/reviewresult/ReviewResultTooltip.html
@@ -0,0 +1,9 @@
+<wicket:panel>
+ <div class="review-result-tooltip">
+ <span wicket:id="description"></span>
+ <wicket:enclosure child="delete">
+ <span class="middot"></span>
+ <a wicket:id="delete">delete</a>
+ </wicket:enclosure>
+ </div>
+</wicket:panel>
\ No newline at end of file
diff --git a/gitplex.web/src/main/java/com/pmease/gitplex/web/component/pullrequest/reviewresult/ReviewResultTooltip.java b/gitplex.web/src/main/java/com/pmease/gitplex/web/component/pullrequest/reviewresult/ReviewResultTooltip.java
new file mode 100644
index 0000000000..bbc1a7ca50
--- /dev/null
+++ b/gitplex.web/src/main/java/com/pmease/gitplex/web/component/pullrequest/reviewresult/ReviewResultTooltip.java
@@ -0,0 +1,61 @@
+package com.pmease.gitplex.web.component.pullrequest.reviewresult;
+
+import org.apache.wicket.markup.html.basic.Label;
+import org.apache.wicket.markup.html.link.Link;
+import org.apache.wicket.markup.html.panel.GenericPanel;
+import org.apache.wicket.model.IModel;
+
+import com.pmease.gitplex.core.GitPlex;
+import com.pmease.gitplex.core.entity.PullRequest;
+import com.pmease.gitplex.core.entity.PullRequestReview;
+import com.pmease.gitplex.core.manager.PullRequestReviewManager;
+import com.pmease.gitplex.core.security.SecurityUtils;
+
+@SuppressWarnings("serial")
+class ReviewResultTooltip extends GenericPanel<PullRequestReview> {
+
+ public ReviewResultTooltip(String id, IModel<PullRequestReview> model) {
+ super(id, model);
+ }
+
+ @Override
+ protected void onInitialize() {
+ super.onInitialize();
+
+ PullRequestReview review = getModelObject();
+ String description;
+ if (review.getUpdate().equals(review.getUpdate().getRequest().getLatestUpdate())) {
+ if (review.getResult() == PullRequestReview.Result.APPROVE) {
+ description = "Approved";
+ } else {
+ description = "Disapproved";
+ }
+ } else if (review.getResult() == PullRequestReview.Result.APPROVE) {
+ description = "Approved on a previous update";
+ } else {
+ description = "Disapproved on a previous update";
+ }
+
+ add(new Label("description", description));
+
+ add(new Link<Void>("delete") {
+
+ @Override
+ protected void onConfigure() {
+ super.onConfigure();
+ PullRequestReview review = ReviewResultTooltip.this.getModelObject();
+ setVisible(review.getUser().equals(SecurityUtils.getAccount())
+ || SecurityUtils.canManage(review.getUpdate().getRequest().getTargetDepot()));
+ }
+
+ @Override
+ public void onClick() {
+ PullRequestReview review = ReviewResultTooltip.this.getModelObject();
+ PullRequest request = review.getUpdate().getRequest();
+ GitPlex.getInstance(PullRequestReviewManager.class).deleteAll(review.getUser(), request);
+ }
+
+ });
+ }
+
+}
diff --git a/gitplex.web/src/main/java/com/pmease/gitplex/web/component/pullrequest/review-result.css b/gitplex.web/src/main/java/com/pmease/gitplex/web/component/pullrequest/reviewresult/review-result.css
similarity index 76%
rename from gitplex.web/src/main/java/com/pmease/gitplex/web/component/pullrequest/review-result.css
rename to gitplex.web/src/main/java/com/pmease/gitplex/web/component/pullrequest/reviewresult/review-result.css
index 632497b3cc..8fbec9c392 100644
--- a/gitplex.web/src/main/java/com/pmease/gitplex/web/component/pullrequest/review-result.css
+++ b/gitplex.web/src/main/java/com/pmease/gitplex/web/component/pullrequest/reviewresult/review-result.css
@@ -1,17 +1,23 @@
-.review-result {
- font-size: 16px;
- position: absolute;
- left: 30px;
- top: -11px;
- cursor: pointer;
- opacity: 100;
-}
-.review-result.current.approved {
- color: #35A612;
-}
-.review-result.current.disapproved {
- color: #F93333;
-}
-.review-result.previous.approved, .review-result.previous.disapproved {
- color: #888;
-}
+.review-result {
+ font-size: 16px;
+ position: absolute;
+ left: 30px;
+ top: -11px;
+ cursor: pointer;
+ opacity: 100;
+}
+.review-result.current.approved {
+ color: #35A612;
+}
+.review-result.current.disapproved {
+ color: #F93333;
+}
+.review-result.previous.approved, .review-result.previous.disapproved {
+ color: #888;
+}
+
+.review-result-tooltip {
+ padding: 4px 8px;
+}
+.review-result-tooltip a {
+}
\ No newline at end of file
diff --git a/gitplex.web/src/main/java/com/pmease/gitplex/web/model/ReviewersModel.java b/gitplex.web/src/main/java/com/pmease/gitplex/web/model/ReviewersModel.java
index c5d098a5ce..d94d2f8608 100644
--- a/gitplex.web/src/main/java/com/pmease/gitplex/web/model/ReviewersModel.java
+++ b/gitplex.web/src/main/java/com/pmease/gitplex/web/model/ReviewersModel.java
@@ -1,6 +1,7 @@
package com.pmease.gitplex.web.model;
import java.util.ArrayList;
+import java.util.Comparator;
import java.util.List;
import org.apache.wicket.model.IModel;
@@ -22,10 +23,10 @@ public class ReviewersModel extends LoadableDetachableModel<List<PullRequestRevi
protected List<PullRequestReviewInvitation> load() {
List<PullRequestReviewInvitation> invitations = new ArrayList<>();
for (PullRequestReviewInvitation invitation: requestModel.getObject().getReviewInvitations()) {
- if (invitation.isPreferred())
+ if (!invitation.isExcluded())
invitations.add(invitation);
}
- invitations.sort((invitation1, invitation2) -> invitation1.getDate().compareTo(invitation2.getDate()));
+ invitations.sort(Comparator.comparing(PullRequestReviewInvitation::getDate));
return invitations;
}
diff --git a/gitplex.web/src/main/java/com/pmease/gitplex/web/page/depot/pullrequest/newrequest/NewRequestPage.html b/gitplex.web/src/main/java/com/pmease/gitplex/web/page/depot/pullrequest/newrequest/NewRequestPage.html
index 45b2fc869f..8248eb5e65 100644
--- a/gitplex.web/src/main/java/com/pmease/gitplex/web/page/depot/pullrequest/newrequest/NewRequestPage.html
+++ b/gitplex.web/src/main/java/com/pmease/gitplex/web/page/depot/pullrequest/newrequest/NewRequestPage.html
@@ -86,7 +86,7 @@
<td wicket:id="reviewers" class="value">
<ul class="clearfix list-unstyled">
<li wicket:id="reviewers" class="pull-left">
- <span wicket:id="avatar"></span>
+ <a wicket:id="avatar"></a>
</li>
<wicket:enclosure child="addReviewer">
<li class="pull-left"><input wicket:id="addReviewer" type="hidden"></input></li>
diff --git a/gitplex.web/src/main/java/com/pmease/gitplex/web/page/depot/pullrequest/newrequest/NewRequestPage.java b/gitplex.web/src/main/java/com/pmease/gitplex/web/page/depot/pullrequest/newrequest/NewRequestPage.java
index 6a47d51357..e9cb6ccb9a 100644
--- a/gitplex.web/src/main/java/com/pmease/gitplex/web/page/depot/pullrequest/newrequest/NewRequestPage.java
+++ b/gitplex.web/src/main/java/com/pmease/gitplex/web/page/depot/pullrequest/newrequest/NewRequestPage.java
@@ -158,6 +158,8 @@ public class NewRequestPage extends PullRequestPage implements CommentSupport {
pullRequest.addUpdate(update);
update.setRequest(pullRequest);
update.setHeadCommitHash(source.getObjectName());
+ update.setMergeCommitHash(GitUtils.getMergeBase(target.getDepot().getRepository(),
+ target.getObjectId(), ObjectId.fromString(update.getHeadCommitHash())).name());
PullRequestManager pullRequestManager = GitPlex.getInstance(PullRequestManager.class);
List<IntegrationStrategy> strategies = pullRequestManager.getApplicableIntegrationStrategies(pullRequest);
@@ -644,8 +646,8 @@ public class NewRequestPage extends PullRequestPage implements CommentSupport {
item.add(new ReviewerAvatar("avatar", invitation) {
@Override
- protected void onAvatarRemove(AjaxRequestTarget target) {
- super.onAvatarRemove(target);
+ public void onClick(AjaxRequestTarget target) {
+ super.onClick(target);
target.add(reviewersContainer);
}
diff --git a/gitplex.web/src/main/java/com/pmease/gitplex/web/page/depot/pullrequest/requestdetail/PullRequestOperation.java b/gitplex.web/src/main/java/com/pmease/gitplex/web/page/depot/pullrequest/requestdetail/PullRequestOperation.java
index 4825334cdf..bcb6936efc 100644
--- a/gitplex.web/src/main/java/com/pmease/gitplex/web/page/depot/pullrequest/requestdetail/PullRequestOperation.java
+++ b/gitplex.web/src/main/java/com/pmease/gitplex/web/page/depot/pullrequest/requestdetail/PullRequestOperation.java
@@ -1,205 +1,205 @@
-package com.pmease.gitplex.web.page.depot.pullrequest.requestdetail;
-
-import javax.annotation.Nullable;
-
-import org.apache.wicket.Component;
-import org.apache.wicket.markup.html.WebMarkupContainer;
-import org.apache.wicket.model.LoadableDetachableModel;
-import org.eclipse.jgit.lib.ObjectId;
-
-import com.pmease.gitplex.core.GitPlex;
-import com.pmease.gitplex.core.entity.Account;
-import com.pmease.gitplex.core.entity.PullRequest;
-import com.pmease.gitplex.core.entity.PullRequest.Status;
-import com.pmease.gitplex.core.entity.PullRequestReview;
-import com.pmease.gitplex.core.entity.PullRequestReviewInvitation;
-import com.pmease.gitplex.core.entity.support.IntegrationPreview;
-import com.pmease.gitplex.core.manager.AccountManager;
-import com.pmease.gitplex.core.manager.PullRequestManager;
-import com.pmease.gitplex.core.manager.PullRequestReviewManager;
-import com.pmease.gitplex.core.security.ObjectPermission;
-import com.pmease.gitplex.core.security.SecurityUtils;
-
-@SuppressWarnings("serial")
-public enum PullRequestOperation {
- INTEGRATE {
-
- @Override
- public boolean canOperate(PullRequest request) {
- if (!SecurityUtils.getSubject().isPermitted(
- ObjectPermission.ofDepotWrite(request.getTargetDepot()))) {
- return false;
- } else {
- return GitPlex.getInstance(PullRequestManager.class).canIntegrate(request);
- }
- }
-
- @Override
- public void operate(PullRequest request, String comment) {
- GitPlex.getInstance(PullRequestManager.class).integrate(request, comment);
- }
-
- @Override
- public Component newHinter(String id, PullRequest request) {
- Long requestId = request.getId();
- return new IntegrationHintPanel(id, new LoadableDetachableModel<PullRequest>() {
-
- @Override
- protected PullRequest load() {
- return GitPlex.getInstance(PullRequestManager.class).load(requestId);
- }
-
- });
- }
-
- },
- DISCARD {
-
- @Override
- public boolean canOperate(PullRequest request) {
- if (!SecurityUtils.canModify(request))
- return false;
- else
- return request.isOpen();
- }
-
- @Override
- public void operate(PullRequest request, String comment) {
- GitPlex.getInstance(PullRequestManager.class).discard(request, comment);
- }
-
- },
- APPROVE {
-
- @Override
- public boolean canOperate(PullRequest request) {
- return canReview(request);
- }
-
- @Override
- public void operate(PullRequest request, String comment) {
- GitPlex.getInstance(PullRequestReviewManager.class).review(request, PullRequestReview.Result.APPROVE, comment);
- }
-
- @Override
- public Component newHinter(String id, PullRequest request) {
- Long requestId = request.getId();
- return new ApprovalHintPanel(id, new LoadableDetachableModel<PullRequest>() {
-
- @Override
- protected PullRequest load() {
- return GitPlex.getInstance(PullRequestManager.class).load(requestId);
- }
-
- });
- }
-
- },
- DISAPPROVE {
-
- @Override
- public boolean canOperate(PullRequest request) {
- return canReview(request);
- }
-
- @Override
- public void operate(PullRequest request, String comment) {
- GitPlex.getInstance(PullRequestReviewManager.class).review(request, PullRequestReview.Result.DISAPPROVE, comment);
- }
-
- },
- REOPEN {
-
- @Override
- public boolean canOperate(PullRequest request) {
- PullRequestManager pullRequestManager = GitPlex.getInstance(PullRequestManager.class);
- if (request.isOpen()
- || !SecurityUtils.canModify(request)
- || request.getTarget().getObjectName(false) == null
- || request.getSourceDepot() == null
- || request.getSource().getObjectName(false) == null
- || pullRequestManager.findOpen(request.getTarget(), request.getSource()) != null) {
- return false;
- }
-
- // now check if source branch is integrated into target branch
- String sourceHead = request.getSource().getObjectName();
- return request.getTargetDepot().getObjectId(sourceHead, false) == null
- || !request.getTargetDepot().isMergedInto(sourceHead, request.getTarget().getObjectName());
- }
-
- @Override
- public void operate(PullRequest request, String comment) {
- GitPlex.getInstance(PullRequestManager.class).reopen(request, comment);
- }
-
- },
- DELETE_SOURCE_BRANCH {
-
- @Override
- public void operate(PullRequest request, String comment) {
- GitPlex.getInstance(PullRequestManager.class).deleteSourceBranch(request, comment);
- }
-
- @Override
- public boolean canOperate(PullRequest request) {
- IntegrationPreview preview = request.getLastIntegrationPreview();
- PullRequestManager pullRequestManager = GitPlex.getInstance(PullRequestManager.class);
- return request.getStatus() == Status.INTEGRATED
- && request.getSourceDepot() != null
- && request.getSource().getObjectName(false) != null
- && !request.getSource().isDefault()
- && preview != null
- && (request.getSource().getObjectName().equals(preview.getRequestHead())
- || request.getSource().getObjectName().equals(preview.getIntegrated()))
- && SecurityUtils.canModify(request)
- && SecurityUtils.canPushRef(request.getSourceDepot(), request.getSourceRef(), request.getSource().getObjectId(), ObjectId.zeroId())
- && pullRequestManager.findAllOpenTo(request.getSource(), null).isEmpty();
- }
-
- },
- RESTORE_SOURCE_BRANCH {
-
- @Override
- public void operate(PullRequest request, String comment) {
- GitPlex.getInstance(PullRequestManager.class).restoreSourceBranch(request, comment);
- }
-
- @Override
- public boolean canOperate(PullRequest request) {
- return request.getSourceDepot() != null
- && request.getSource().getObjectName(false) == null
- && SecurityUtils.canModify(request)
- && SecurityUtils.canPushRef(request.getSourceDepot(), request.getSourceRef(), ObjectId.zeroId(), ObjectId.fromString(request.getLatestUpdate().getHeadCommitHash()));
- }
-
- };
-
- private static boolean canReview(PullRequest request) {
- Account user = GitPlex.getInstance(AccountManager.class).getCurrent();
-
- // call request.getStatus() in order to trigger generation of review
- // integrations which will be used in else condition
- if (user == null
- || request.getStatus() == PullRequest.Status.INTEGRATED
- || request.getStatus() == PullRequest.Status.DISCARDED
- || request.isReviewEffective(user)) {
- return false;
- } else {
- for (PullRequestReviewInvitation invitation: request.getReviewInvitations()) {
- if (invitation.isPreferred() && invitation.getUser().equals(user))
- return true;
- }
- return false;
- }
- }
-
- public abstract void operate(PullRequest request, @Nullable String comment);
-
- public abstract boolean canOperate(PullRequest request);
-
- public Component newHinter(String id, PullRequest request) {
- return new WebMarkupContainer(id).setVisible(false);
- }
-
-}
+package com.pmease.gitplex.web.page.depot.pullrequest.requestdetail;
+
+import javax.annotation.Nullable;
+
+import org.apache.wicket.Component;
+import org.apache.wicket.markup.html.WebMarkupContainer;
+import org.apache.wicket.model.LoadableDetachableModel;
+import org.eclipse.jgit.lib.ObjectId;
+
+import com.pmease.gitplex.core.GitPlex;
+import com.pmease.gitplex.core.entity.Account;
+import com.pmease.gitplex.core.entity.PullRequest;
+import com.pmease.gitplex.core.entity.PullRequest.Status;
+import com.pmease.gitplex.core.entity.PullRequestReview;
+import com.pmease.gitplex.core.entity.PullRequestReviewInvitation;
+import com.pmease.gitplex.core.entity.support.IntegrationPreview;
+import com.pmease.gitplex.core.manager.AccountManager;
+import com.pmease.gitplex.core.manager.PullRequestManager;
+import com.pmease.gitplex.core.manager.PullRequestReviewManager;
+import com.pmease.gitplex.core.security.ObjectPermission;
+import com.pmease.gitplex.core.security.SecurityUtils;
+
+@SuppressWarnings("serial")
+public enum PullRequestOperation {
+ INTEGRATE {
+
+ @Override
+ public boolean canOperate(PullRequest request) {
+ if (!SecurityUtils.getSubject().isPermitted(
+ ObjectPermission.ofDepotWrite(request.getTargetDepot()))) {
+ return false;
+ } else {
+ return GitPlex.getInstance(PullRequestManager.class).canIntegrate(request);
+ }
+ }
+
+ @Override
+ public void operate(PullRequest request, String comment) {
+ GitPlex.getInstance(PullRequestManager.class).integrate(request, comment);
+ }
+
+ @Override
+ public Component newHinter(String id, PullRequest request) {
+ Long requestId = request.getId();
+ return new IntegrationHintPanel(id, new LoadableDetachableModel<PullRequest>() {
+
+ @Override
+ protected PullRequest load() {
+ return GitPlex.getInstance(PullRequestManager.class).load(requestId);
+ }
+
+ });
+ }
+
+ },
+ DISCARD {
+
+ @Override
+ public boolean canOperate(PullRequest request) {
+ if (!SecurityUtils.canModify(request))
+ return false;
+ else
+ return request.isOpen();
+ }
+
+ @Override
+ public void operate(PullRequest request, String comment) {
+ GitPlex.getInstance(PullRequestManager.class).discard(request, comment);
+ }
+
+ },
+ APPROVE {
+
+ @Override
+ public boolean canOperate(PullRequest request) {
+ return canReview(request);
+ }
+
+ @Override
+ public void operate(PullRequest request, String comment) {
+ GitPlex.getInstance(PullRequestReviewManager.class).review(request, PullRequestReview.Result.APPROVE, comment);
+ }
+
+ @Override
+ public Component newHinter(String id, PullRequest request) {
+ Long requestId = request.getId();
+ return new ApprovalHintPanel(id, new LoadableDetachableModel<PullRequest>() {
+
+ @Override
+ protected PullRequest load() {
+ return GitPlex.getInstance(PullRequestManager.class).load(requestId);
+ }
+
+ });
+ }
+
+ },
+ DISAPPROVE {
+
+ @Override
+ public boolean canOperate(PullRequest request) {
+ return canReview(request);
+ }
+
+ @Override
+ public void operate(PullRequest request, String comment) {
+ GitPlex.getInstance(PullRequestReviewManager.class).review(request, PullRequestReview.Result.DISAPPROVE, comment);
+ }
+
+ },
+ REOPEN {
+
+ @Override
+ public boolean canOperate(PullRequest request) {
+ PullRequestManager pullRequestManager = GitPlex.getInstance(PullRequestManager.class);
+ if (request.isOpen()
+ || !SecurityUtils.canModify(request)
+ || request.getTarget().getObjectName(false) == null
+ || request.getSourceDepot() == null
+ || request.getSource().getObjectName(false) == null
+ || pullRequestManager.findOpen(request.getTarget(), request.getSource()) != null) {
+ return false;
+ }
+
+ // now check if source branch is integrated into target branch
+ String sourceHead = request.getSource().getObjectName();
+ return request.getTargetDepot().getObjectId(sourceHead, false) == null
+ || !request.getTargetDepot().isMergedInto(sourceHead, request.getTarget().getObjectName());
+ }
+
+ @Override
+ public void operate(PullRequest request, String comment) {
+ GitPlex.getInstance(PullRequestManager.class).reopen(request, comment);
+ }
+
+ },
+ DELETE_SOURCE_BRANCH {
+
+ @Override
+ public void operate(PullRequest request, String comment) {
+ GitPlex.getInstance(PullRequestManager.class).deleteSourceBranch(request, comment);
+ }
+
+ @Override
+ public boolean canOperate(PullRequest request) {
+ IntegrationPreview preview = request.getLastIntegrationPreview();
+ PullRequestManager pullRequestManager = GitPlex.getInstance(PullRequestManager.class);
+ return request.getStatus() == Status.INTEGRATED
+ && request.getSourceDepot() != null
+ && request.getSource().getObjectName(false) != null
+ && !request.getSource().isDefault()
+ && preview != null
+ && (request.getSource().getObjectName().equals(preview.getRequestHead())
+ || request.getSource().getObjectName().equals(preview.getIntegrated()))
+ && SecurityUtils.canModify(request)
+ && SecurityUtils.canPushRef(request.getSourceDepot(), request.getSourceRef(), request.getSource().getObjectId(), ObjectId.zeroId())
+ && pullRequestManager.findAllOpenTo(request.getSource(), null).isEmpty();
+ }
+
+ },
+ RESTORE_SOURCE_BRANCH {
+
+ @Override
+ public void operate(PullRequest request, String comment) {
+ GitPlex.getInstance(PullRequestManager.class).restoreSourceBranch(request, comment);
+ }
+
+ @Override
+ public boolean canOperate(PullRequest request) {
+ return request.getSourceDepot() != null
+ && request.getSource().getObjectName(false) == null
+ && SecurityUtils.canModify(request)
+ && SecurityUtils.canPushRef(request.getSourceDepot(), request.getSourceRef(), ObjectId.zeroId(), ObjectId.fromString(request.getLatestUpdate().getHeadCommitHash()));
+ }
+
+ };
+
+ private static boolean canReview(PullRequest request) {
+ Account user = GitPlex.getInstance(AccountManager.class).getCurrent();
+
+ // call request.getStatus() in order to trigger generation of review
+ // integrations which will be used in else condition
+ if (user == null
+ || request.getStatus() == PullRequest.Status.INTEGRATED
+ || request.getStatus() == PullRequest.Status.DISCARDED
+ || request.isReviewEffective(user)) {
+ return false;
+ } else {
+ for (PullRequestReviewInvitation invitation: request.getReviewInvitations()) {
+ if (!invitation.isExcluded() && invitation.getUser().equals(user))
+ return true;
+ }
+ return false;
+ }
+ }
+
+ public abstract void operate(PullRequest request, @Nullable String comment);
+
+ public abstract boolean canOperate(PullRequest request);
+
+ public Component newHinter(String id, PullRequest request) {
+ return new WebMarkupContainer(id).setVisible(false);
+ }
+
+}
diff --git a/gitplex.web/src/main/java/com/pmease/gitplex/web/page/depot/pullrequest/requestdetail/RequestDetailPage.html b/gitplex.web/src/main/java/com/pmease/gitplex/web/page/depot/pullrequest/requestdetail/RequestDetailPage.html
index 3205dc19d6..a9ad514788 100644
--- a/gitplex.web/src/main/java/com/pmease/gitplex/web/page/depot/pullrequest/requestdetail/RequestDetailPage.html
+++ b/gitplex.web/src/main/java/com/pmease/gitplex/web/page/depot/pullrequest/requestdetail/RequestDetailPage.html
@@ -21,11 +21,11 @@
<div wicket:id="discardedNote">
<i class="fa fa-info-circle"></i> This pull request has been discarded.
</div>
- <div wicket:id="pendingUpdateNote">
+ <div wicket:id="pendingUpdateNote" class="note">
<i class="fa fa-exclamation-triangle"></i> This pull request does not pass gate keeper
checks below, and needs to be updated with new commits.
</div>
- <div wicket:id="pendingApprovalNote">
+ <div wicket:id="pendingApprovalNote" class="note">
<i class="fa fa-exclamation-triangle"></i> This pull request needs to be approved before it can
be integrated.
</div>
diff --git a/gitplex.web/src/main/java/com/pmease/gitplex/web/page/depot/pullrequest/requestdetail/overview/RequestOverviewPage.html b/gitplex.web/src/main/java/com/pmease/gitplex/web/page/depot/pullrequest/requestdetail/overview/RequestOverviewPage.html
index a7191a00e9..38ec046035 100644
--- a/gitplex.web/src/main/java/com/pmease/gitplex/web/page/depot/pullrequest/requestdetail/overview/RequestOverviewPage.html
+++ b/gitplex.web/src/main/java/com/pmease/gitplex/web/page/depot/pullrequest/requestdetail/overview/RequestOverviewPage.html
@@ -1,78 +1,78 @@
-<wicket:extend>
- <table class="overview">
- <tr>
- <td class="activities">
- <table>
- <tr wicket:id="requestActivities" class="activity">
- <td wicket:id="avatar" class="avatar"><a wicket:id="avatar"></a></td>
- <td class="spacer"></td>
- <td wicket:id="content" class="content"></td>
- </tr>
- </table>
- <div wicket:id="addComment" class="add-comment">
- <form wicket:id="form" class="leave-confirm">
- <div wicket:id="feedback"></div>
- <textarea wicket:id="input" class="form-control" rows="5" placeholder="Leave a comment"></textarea>
- <div class="actions">
- <button wicket:id="comment" class="dirty-aware btn btn-primary">Comment</button>
- </div>
- </form>
- </div>
- </td>
- <td class="info">
- <div class="well">
- <div wicket:id="assignee" class="assignee"></div>
- <div wicket:id="reviewers" class="reviewers">
- <label>Reviewers:</label>
- <ul class="clearfix list-unstyled">
- <li wicket:id="reviewers" class="pull-left">
- <span wicket:id="avatar"></span>
- <span wicket:id="result"></span>
- </li>
- </ul>
- <wicket:enclosure child="addReviewer">
- <div>
- <input wicket:id="addReviewer" type="hidden"></input>
- </div>
- </wicket:enclosure>
- </div>
- <div wicket:id="integrationStrategy" class="integration-strategy">
- <label>
- Integration Strategy:
- <span wicket:id="help" class="fa fa-question-circle pointer small"></span>
- </label>
- <div>
- <select wicket:id="editor"></select>
- <span wicket:id="viewer"></span>
- </div>
- </div>
- <div wicket:id="watch" class="watch">
- <div>
- <label>Watch Status:</label>
- <select wicket:id="option"></select>
- </div>
- <div class="help-block"><i class="fa fa-info-circle small"></i> <span wicket:id="help"></span></div>
- </div>
- </div>
- </td>
- </tr>
- </table>
- <wicket:fragment wicket:id="assigneeEditFrag">
- <label>Assigned To: <span wicket:id="help" class="fa fa-question-circle pointer small"></span></label>
- <div>
- <input wicket:id="assignee" type="hidden"></input>
- </div>
- </wicket:fragment>
- <wicket:fragment wicket:id="assigneeViewFrag">
- <label>Assigned To: <span wicket:id="help" class="fa fa-question-circle pointer small"></span></label>
- <span wicket:id="assignee" class="avatar"></span>
- </wicket:fragment>
- <wicket:fragment wicket:id="noAssigneeFrag">
- This pull request will be integrated automatically as long as it passes gate keeper check.
- </wicket:fragment>
- <wicket:fragment wicket:id="sinceChangesRowContentFrag">
- <div>
- <span class="icon fa fa-ext fa-file-diff"></span> <a wicket:id="sinceChanges">Changes since last visit</a>
- </div>
- </wicket:fragment>
+<wicket:extend>
+ <table class="overview">
+ <tr>
+ <td class="activities">
+ <table>
+ <tr wicket:id="requestActivities" class="activity">
+ <td wicket:id="avatar" class="avatar"><a wicket:id="avatar"></a></td>
+ <td class="spacer"></td>
+ <td wicket:id="content" class="content"></td>
+ </tr>
+ </table>
+ <div wicket:id="addComment" class="add-comment">
+ <form wicket:id="form" class="leave-confirm">
+ <div wicket:id="feedback"></div>
+ <textarea wicket:id="input" class="form-control" rows="5" placeholder="Leave a comment"></textarea>
+ <div class="actions">
+ <button wicket:id="comment" class="dirty-aware btn btn-primary">Comment</button>
+ </div>
+ </form>
+ </div>
+ </td>
+ <td class="info">
+ <div class="well">
+ <div wicket:id="assignee" class="assignee"></div>
+ <div wicket:id="reviewers" class="reviewers">
+ <label>Reviewers:</label>
+ <ul class="clearfix list-unstyled">
+ <li wicket:id="reviewers" class="pull-left">
+ <a wicket:id="avatar"></a>
+ <span wicket:id="result"></span>
+ </li>
+ </ul>
+ <wicket:enclosure child="addReviewer">
+ <div>
+ <input wicket:id="addReviewer" type="hidden"></input>
+ </div>
+ </wicket:enclosure>
+ </div>
+ <div wicket:id="integrationStrategy" class="integration-strategy">
+ <label>
+ Integration Strategy:
+ <span wicket:id="help" class="fa fa-question-circle pointer small"></span>
+ </label>
+ <div>
+ <select wicket:id="editor"></select>
+ <span wicket:id="viewer"></span>
+ </div>
+ </div>
+ <div wicket:id="watch" class="watch">
+ <div>
+ <label>Watch Status:</label>
+ <select wicket:id="option"></select>
+ </div>
+ <div class="help-block"><i class="fa fa-info-circle small"></i> <span wicket:id="help"></span></div>
+ </div>
+ </div>
+ </td>
+ </tr>
+ </table>
+ <wicket:fragment wicket:id="assigneeEditFrag">
+ <label>Assigned To: <span wicket:id="help" class="fa fa-question-circle pointer small"></span></label>
+ <div>
+ <input wicket:id="assignee" type="hidden"></input>
+ </div>
+ </wicket:fragment>
+ <wicket:fragment wicket:id="assigneeViewFrag">
+ <label>Assigned To: <span wicket:id="help" class="fa fa-question-circle pointer small"></span></label>
+ <span wicket:id="assignee" class="avatar"></span>
+ </wicket:fragment>
+ <wicket:fragment wicket:id="noAssigneeFrag">
+ This pull request will be integrated automatically as long as it passes gate keeper check.
+ </wicket:fragment>
+ <wicket:fragment wicket:id="sinceChangesRowContentFrag">
+ <div>
+ <span class="icon fa fa-ext fa-file-diff"></span> <a wicket:id="sinceChanges">Changes since last visit</a>
+ </div>
+ </wicket:fragment>
</wicket:extend>
\ No newline at end of file
diff --git a/gitplex.web/src/main/java/com/pmease/gitplex/web/page/depot/pullrequest/requestdetail/overview/RequestOverviewPage.java b/gitplex.web/src/main/java/com/pmease/gitplex/web/page/depot/pullrequest/requestdetail/overview/RequestOverviewPage.java
index 6b4096d784..0996c6f4f0 100644
--- a/gitplex.web/src/main/java/com/pmease/gitplex/web/page/depot/pullrequest/requestdetail/overview/RequestOverviewPage.java
+++ b/gitplex.web/src/main/java/com/pmease/gitplex/web/page/depot/pullrequest/requestdetail/overview/RequestOverviewPage.java
@@ -58,10 +58,10 @@ import com.pmease.gitplex.web.component.avatar.Avatar;
import com.pmease.gitplex.web.component.avatar.AvatarLink;
import com.pmease.gitplex.web.component.comment.CommentInput;
import com.pmease.gitplex.web.component.comment.DepotAttachmentSupport;
-import com.pmease.gitplex.web.component.pullrequest.ReviewResultIcon;
import com.pmease.gitplex.web.component.pullrequest.requestassignee.AssigneeChoice;
import com.pmease.gitplex.web.component.pullrequest.requestreviewer.ReviewerAvatar;
import com.pmease.gitplex.web.component.pullrequest.requestreviewer.ReviewerChoice;
+import com.pmease.gitplex.web.component.pullrequest.reviewresult.ReviewResultIcon;
import com.pmease.gitplex.web.model.EntityModel;
import com.pmease.gitplex.web.model.ReviewersModel;
import com.pmease.gitplex.web.page.depot.pullrequest.requestdetail.RequestDetailPage;
@@ -645,7 +645,7 @@ public class RequestOverviewPage extends RequestDetailPage {
}
private WebMarkupContainer newReviewersContainer() {
- final WebMarkupContainer reviewersContainer = new WebMarkupContainer("reviewers") {
+ WebMarkupContainer reviewersContainer = new WebMarkupContainer("reviewers") {
@Override
protected void onConfigure() {
@@ -653,10 +653,9 @@ public class RequestOverviewPage extends RequestDetailPage {
PullRequest request = getPullRequest();
if (request.getReviewInvitations().isEmpty()) {
- Account currentUser = GitPlex.getInstance(AccountManager.class).getCurrent();
setVisible(request.isOpen()
&& !request.getPotentialReviewers().isEmpty()
- && (currentUser != null && currentUser.equals(request.getSubmitter()) || SecurityUtils.getSubject().isPermitted(ObjectPermission.ofDepotAdmin(request.getTarget().getDepot()))));
+ && SecurityUtils.canModify(request));
} else {
setVisible(true);
}
@@ -672,8 +671,8 @@ public class RequestOverviewPage extends RequestDetailPage {
item.add(new ReviewerAvatar("avatar", invitation) {
@Override
- protected void onAvatarRemove(AjaxRequestTarget target) {
- super.onAvatarRemove(target);
+ public void onClick(AjaxRequestTarget target) {
+ super.onClick(target);
target.add(reviewersContainer);
send(getPage(), Broadcast.BREADTH, new PullRequestChanged(target));
diff --git a/gitplex.web/src/main/java/com/pmease/gitplex/web/page/depot/pullrequest/requestdetail/overview/request-overview.css b/gitplex.web/src/main/java/com/pmease/gitplex/web/page/depot/pullrequest/requestdetail/overview/request-overview.css
index cada6a4b43..fcdf9551ef 100644
--- a/gitplex.web/src/main/java/com/pmease/gitplex/web/page/depot/pullrequest/requestdetail/overview/request-overview.css
+++ b/gitplex.web/src/main/java/com/pmease/gitplex/web/page/depot/pullrequest/requestdetail/overview/request-overview.css
@@ -1,313 +1,316 @@
-#request-detail>.overview>tbody>tr>td.activities {
- width: 75%;
- padding-right: 16px;
-}
-#request-detail .activities>table {
- margin-bottom: 20px;
- table-layout: fixed;
- border-bottom: 1px solid #CCC;
-}
-#request-detail tr.activity>td.spacer {
- border-right: 1px solid #E8E8E8;
-}
-#request-detail td.avatar {
- width: 48px;
- border-left: 4px solid white;
- padding-left: 8px;
-}
-#request-detail td.spacer {
- width: 30px;
-}
-#request-detail .discussion>td.content>div.activity {
- position: relative;
- border: 1px solid #CCC;
- border-radius: 4px;
- background: white;
- margin-left: -15px;
-}
-#request-detail .discussion>td.content>div.activity:before {
- display: inline-block;
- position: absolute;
- top: 10px;
- left: -8px;
- border-top: 8px solid transparent;
- border-bottom: 8px solid transparent;
- border-right: 8px solid #CBCBCB;
- content: "";
-}
-#request-detail .discussion>td.content>.activity:after {
- display: inline-block;
- position: absolute;
- top: 11px;
- left: -7px;
- border-top: 7px solid transparent;
- border-bottom: 7px solid transparent;
- border-right: 7px solid #F5F5F5;
- content: "";
-}
-#request-detail div.activity>.body>.actions {
- margin-top: 8px;
-}
-#request-detail div.activity>.body>.actions>a {
- margin-right: 0;
- font-size: 13px;
-}
-#request-detail .discussion+.discussion>td {
- padding-top: 30px;
-}
-#request-detail .discussion:last-child>td {
- padding-bottom: 20px;
-}
-#request-detail .non-discussion:last-child>td.content {
- padding-bottom: 20px;
-}
-#request-detail .non-discussion>td.content {
- border-top: 1px solid #EEE;
-}
-#request-detail .discussion+.non-discussion>td.content,
-#request-detail .update+.update>td.content {
- border-top: none;
-}
-#request-detail .discussion>.avatar img {
- width: 40px;
- height: 40px;
-}
-#request-detail .non-discussion>td.content {
- font-size: 13px;
- padding: 10px 0;
-}
-
-#request-detail div.activity, #request-detail div.activity a {
- color: #999;
-}
-#request-detail div.activity>div.body {
- color: #444;
-}
-
-#request-detail div.activity .operations>* {
- color: #DDD;
- margin-left: 4px;
-}
-#request-detail div.activity:hover .operations>* {
- color: #999;
-}
-#request-detail div.activity .user a {
- color: #666;
- font-weight: bold;
- font-style: normal;
-}
-#request-detail tr.activity.since-changes {
- display: none;
-}
-#request-detail tr.activity.since-changes.visible {
- display: table-row;
-}
-#request-detail .non-discussion div.activity,
-#request-detail tr.activity.since-changes td.content>div {
- margin-left: -14px;
-}
-#request-detail tr.activity.since-changes td.content>div a {
- font-size: 16px;
-}
-
-#request-detail .non-discussion div.activity>.head>.icon,
-#request-detail tr.activity.since-changes .icon {
- border-radius: 13px;
- background: #5CA7F8;
- width: 26px;
- height: 26px;
- color: white;
- padding: 6px;
- margin-right: 4px;
-}
-#request-detail .discussion div.activity>.head {
- padding: 10px;
- border-radius: 4px 4px 0 0;
- background: #F5F5F5;
-}
-#request-detail .discussion div.activity>.body {
- padding: 12px;
-}
-#request-detail .non-discussion div.activity>.body {
- margin: 8px 0 0 36px;
-}
-#request-detail .non-discussion div.activity .user a {
- font-weight: normal;
-}
-
-#request-detail .non-discussion>td.avatar img {
- display: none;
-}
-#request-detail .activities tr.activity>.content>.update {
- color: #777;
- margin-left: -7px;
-}
-#request-detail .activities tr.activity>.content>.update>.alert {
- margin: 0 0 8px 28px;
-}
-#request-detail .activities tr.activity>.content>.update a {
- color: #555;
-}
-#request-detail .activities tr.activity>.content>.update td {
- padding: 4px 0;
-}
-#request-detail .activities tr.activity>.content>.update td.status {
- width: 120px;
-}
-#request-detail .update+.update>td.content>div {
- margin-top: -16px;
-}
-#request-detail .update+.update>td.content>div>.alert {
- margin-top: 16px;
-}
-#request-detail .discussion+.non-discussion>td.content {
- padding-top: 16px;
-}
-#request-detail .non-discussion+.discussion>td {
- padding-top: 8px;
-}
-
-#request-detail .activities tr.activity>.content>.update td.detail {
- padding-left: 13px;
- padding-right: 8px;
-}
-#request-detail .activities tr.activity>.content>.update td.detail .commit-message {
- padding-left: 4px;
-}
-#request-detail .activities tr.activity>.content>.update td.icon {
- width: 1px;
- padding-top: 7px;
-}
-#request-detail .activities tr.activity>.content>.update td.status {
- text-align: right;
- white-space: nowrap;
-}
-#request-detail .activities tr.activity>.content>.update tr:hover td {
- background: #F5F5F5;
-}
-#request-detail .activities tr.activity>.content>.update tr.integrated td.icon .fa {
- color: #35A612;
-}
-#request-detail .activities tr.activity>.content>.update tr.rebased td a {
- color: #AAA;
-}
-#request-detail .activities tr.activity>.content>.update tr.rebased td.icon .fa {
- color: #CCC;
-}
-#request-detail .activities tr.activity>.content>.update tr.rebased img.avatar {
- opacity: 0.5;
-}
-#request-detail .activities tr.activity>.content>.update td.status .successful {
- color: #35A612;
-}
-#request-detail .activities tr.activity>.content>.update td.status .failed {
- color: #F93333;
-}
-#request-detail .activities tr.activity>.content>.update td.status .running {
- color: #AFAD1F;
-}
-#request-detail .activities tr.activity.new>.avatar {
- border-color: #4667EE;
-}
-
-#request-detail .activities tr.activity>.content>.assigned>.head>.icon {
- padding-left: 8px;
-}
-#request-detail .activities tr.activity>.content>.discarded>.head>.icon {
- background: #F93333;
- padding-left: 7px;
-}
-#request-detail .activities tr.activity>.content>.integrated>.head>.icon {
- background: #35A612;
-}
-#request-detail .activities tr.activity>.content>.approved>.head>.icon,
-#request-detail .activities tr.activity>.content>.verification-succeeded>.head>.icon {
- background: #35A612;
-}
-#request-detail .activities tr.activity>.content>.disapproved>.head>.icon,
-#request-detail .activities tr.activity>.content>.verification-failed>.head>.icon {
- background: #F93333;
-}
-#request-detail .activities tr.activity>.content>.deleted-review>.head>.icon,
-#request-detail .activities tr.activity>.content>.deleted-verification>.head>.icon,
-#request-detail .activities tr.activity>.content>.deleted-source-branch>.head>.icon {
- padding-top: 6px;
- padding-left: 8px;
-}
-#request-detail .activities tr.activity>.content>.restored-source-branch>.head>.icon,
-#request-detail .activities tr.activity>.content>.reopened>.head>.icon {
- padding-left: 8px;
-}
-#request-detail .activities tr.activity>.content>.reference>.head>.icon {
- padding-left: 8px;
-}
-#request-detail .activities tr.activity>.content>.reference>.head {
- margin-bottom: 10px;
-}
-#request-detail .activities tr.activity>.content>.reference>.body {
- margin-left: 36px;
- font-size: 15px;
-}
-#request-detail .activities tr.activity>.content>.reference>.body a {
- color: #333;
-}
-#request-detail .activities tr.activity>.content>.reference>.body a .number {
- color: #999;
-}
-#request-detail .activities tr.activity>.content>.reference>.body .status .help {
- display: none;
-}
-#request-detail .activities tr.activity>.content>.open .feedback .alert {
- margin-bottom: 8px;
-}
-
-#request-detail .info>div>div {
- border-bottom: 1px dotted #BBB;
- margin-bottom: 16px;
- padding-bottom: 16px;
- color: #666;
-}
-#request-detail .info>div>div:last-child {
- border-bottom: none;
- margin-bottom: 0;
- padding-bottom: 0;
-}
-#request-detail .info .help-block {
- margin-bottom: 0;
- color: #888;
-}
-#request-detail .info .fa.small {
- font-size: 14px;
- vertical-align: middle;
-}
-#request-detail .info label {
- margin-right: 4px;
- font-weight: normal;
-}
-#request-detail .info .select2-container {
- width: 100%;
-}
-#request-detail .info .avatar {
- width: 24px;
- height: 24px;
-}
-#request-detail .info .select2-container .avatar {
- width: 20px;
- height: 20px;
-}
-
-#request-detail .info .reviewers ul {
- margin-bottom: 0;
-}
-#request-detail .info .reviewers li {
- margin-right: 20px;
- margin-bottom: 10px;
- position: relative;
-}
-#request-detail .info .reviewers li a:hover {
- text-decoration: none;
-}
-
-#request-detail .info .reviewers .review-result {
- top: -4px;
-}
+#request-detail>.overview>tbody>tr>td.activities {
+ width: 75%;
+ padding-right: 16px;
+}
+#request-detail .activities>table {
+ margin-bottom: 20px;
+ table-layout: fixed;
+ border-bottom: 1px solid #CCC;
+}
+#request-detail tr.activity>td.spacer {
+ border-right: 1px solid #E8E8E8;
+}
+#request-detail td.avatar {
+ width: 48px;
+ border-left: 4px solid white;
+ padding-left: 8px;
+}
+#request-detail td.spacer {
+ width: 30px;
+}
+#request-detail .discussion>td.content>div.activity {
+ position: relative;
+ border: 1px solid #CCC;
+ border-radius: 4px;
+ background: white;
+ margin-left: -15px;
+}
+#request-detail .discussion>td.content>div.activity:before {
+ display: inline-block;
+ position: absolute;
+ top: 10px;
+ left: -8px;
+ border-top: 8px solid transparent;
+ border-bottom: 8px solid transparent;
+ border-right: 8px solid #CBCBCB;
+ content: "";
+}
+#request-detail .discussion>td.content>.activity:after {
+ display: inline-block;
+ position: absolute;
+ top: 11px;
+ left: -7px;
+ border-top: 7px solid transparent;
+ border-bottom: 7px solid transparent;
+ border-right: 7px solid #F5F5F5;
+ content: "";
+}
+#request-detail div.activity>.body>.actions {
+ margin-top: 8px;
+}
+#request-detail div.activity>.body>.actions>a {
+ margin-right: 0;
+ font-size: 13px;
+}
+#request-detail .discussion+.discussion>td {
+ padding-top: 30px;
+}
+#request-detail .discussion:last-child>td {
+ padding-bottom: 20px;
+}
+#request-detail .non-discussion:last-child>td.content {
+ padding-bottom: 20px;
+}
+#request-detail .non-discussion>td.content {
+ border-top: 1px solid #EEE;
+}
+#request-detail .discussion+.non-discussion>td.content,
+#request-detail .update+.update>td.content {
+ border-top: none;
+}
+#request-detail .discussion>.avatar img {
+ width: 40px;
+ height: 40px;
+}
+#request-detail .non-discussion>td.content {
+ font-size: 13px;
+ padding: 10px 0;
+}
+
+#request-detail div.activity, #request-detail div.activity a {
+ color: #999;
+}
+#request-detail div.activity>div.body {
+ color: #444;
+}
+
+#request-detail div.activity .operations>* {
+ color: #DDD;
+ margin-left: 4px;
+}
+#request-detail div.activity:hover .operations>* {
+ color: #999;
+}
+#request-detail div.activity .user a {
+ color: #666;
+ font-weight: bold;
+ font-style: normal;
+}
+#request-detail tr.activity.since-changes {
+ display: none;
+}
+#request-detail tr.activity.since-changes.visible {
+ display: table-row;
+}
+#request-detail .non-discussion div.activity,
+#request-detail tr.activity.since-changes td.content>div {
+ margin-left: -14px;
+}
+#request-detail tr.activity.since-changes td.content>div a {
+ font-size: 16px;
+}
+
+#request-detail .non-discussion div.activity>.head>.icon,
+#request-detail tr.activity.since-changes .icon {
+ border-radius: 13px;
+ background: #5CA7F8;
+ width: 26px;
+ height: 26px;
+ color: white;
+ padding: 6px;
+ margin-right: 4px;
+}
+#request-detail .discussion div.activity>.head {
+ padding: 10px;
+ border-radius: 4px 4px 0 0;
+ background: #F5F5F5;
+}
+#request-detail .discussion div.activity>.body {
+ padding: 12px;
+}
+#request-detail .non-discussion div.activity>.body {
+ margin: 8px 0 0 36px;
+}
+#request-detail .non-discussion div.activity .user a {
+ font-weight: normal;
+}
+
+#request-detail .non-discussion>td.avatar img {
+ display: none;
+}
+#request-detail .activities tr.activity>.content>.update {
+ color: #777;
+ margin-left: -7px;
+}
+#request-detail .activities tr.activity>.content>.update>.alert {
+ margin: 0 0 8px 28px;
+}
+#request-detail .activities tr.activity>.content>.update a {
+ color: #555;
+}
+#request-detail .activities tr.activity>.content>.update td {
+ padding: 4px 0;
+}
+#request-detail .activities tr.activity>.content>.update td.status {
+ width: 120px;
+}
+#request-detail .update+.update>td.content>div {
+ margin-top: -16px;
+}
+#request-detail .update+.update>td.content>div>.alert {
+ margin-top: 16px;
+}
+#request-detail .discussion+.non-discussion>td.content {
+ padding-top: 16px;
+}
+#request-detail .non-discussion+.discussion>td {
+ padding-top: 8px;
+}
+
+#request-detail .activities tr.activity>.content>.update td.detail {
+ padding-left: 13px;
+ padding-right: 8px;
+}
+#request-detail .activities tr.activity>.content>.update td.detail .commit-message {
+ padding-left: 4px;
+}
+#request-detail .activities tr.activity>.content>.update td.icon {
+ width: 1px;
+ padding-top: 7px;
+}
+#request-detail .activities tr.activity>.content>.update td.status {
+ text-align: right;
+ white-space: nowrap;
+}
+#request-detail .activities tr.activity>.content>.update tr:hover td {
+ background: #F5F5F5;
+}
+#request-detail .activities tr.activity>.content>.update tr.integrated td.icon .fa {
+ color: #35A612;
+}
+#request-detail .activities tr.activity>.content>.update tr.rebased td a {
+ color: #AAA;
+}
+#request-detail .activities tr.activity>.content>.update tr.rebased td.icon .fa {
+ color: #CCC;
+}
+#request-detail .activities tr.activity>.content>.update tr.rebased img.avatar {
+ opacity: 0.5;
+}
+#request-detail .activities tr.activity>.content>.update td.status .successful {
+ color: #35A612;
+}
+#request-detail .activities tr.activity>.content>.update td.status .failed {
+ color: #F93333;
+}
+#request-detail .activities tr.activity>.content>.update td.status .running {
+ color: #AFAD1F;
+}
+#request-detail .activities tr.activity.new>.avatar {
+ border-color: #4667EE;
+}
+
+#request-detail .activities tr.activity>.content>.assigned>.head>.icon {
+ padding-left: 8px;
+}
+#request-detail .activities tr.activity>.content>.discarded>.head>.icon {
+ background: #F93333;
+ padding-left: 7px;
+}
+#request-detail .activities tr.activity>.content>.integrated>.head>.icon {
+ background: #35A612;
+}
+#request-detail .activities tr.activity>.content>.approved>.head>.icon,
+#request-detail .activities tr.activity>.content>.verification-succeeded>.head>.icon {
+ background: #35A612;
+}
+#request-detail .activities tr.activity>.content>.disapproved>.head>.icon,
+#request-detail .activities tr.activity>.content>.verification-failed>.head>.icon {
+ background: #F93333;
+}
+#request-detail .activities tr.activity>.content>.deleted-review>.head>.icon,
+#request-detail .activities tr.activity>.content>.deleted-verification>.head>.icon,
+#request-detail .activities tr.activity>.content>.deleted-source-branch>.head>.icon {
+ padding-top: 6px;
+ padding-left: 8px;
+}
+#request-detail .activities tr.activity>.content>.restored-source-branch>.head>.icon,
+#request-detail .activities tr.activity>.content>.reopened>.head>.icon {
+ padding-left: 8px;
+}
+#request-detail .activities tr.activity>.content>.reference>.head>.icon {
+ padding-left: 8px;
+}
+#request-detail .activities tr.activity>.content>.reference>.head {
+ margin-bottom: 10px;
+}
+#request-detail .activities tr.activity>.content>.reference>.body {
+ margin-left: 36px;
+ font-size: 15px;
+}
+#request-detail .activities tr.activity>.content>.reference>.body a {
+ color: #333;
+}
+#request-detail .activities tr.activity>.content>.reference>.body a .number {
+ color: #999;
+}
+#request-detail .activities tr.activity>.content>.reference>.body .status .help {
+ display: none;
+}
+#request-detail .activities tr.activity>.content>.open .feedback .alert {
+ margin-bottom: 8px;
+}
+
+#request-detail .info>div>div {
+ border-bottom: 1px dotted #BBB;
+ margin-bottom: 20px;
+ color: #666;
+}
+#request-detail .info>div>div:last-child {
+ border-bottom: none;
+ margin-bottom: 0;
+}
+#request-detail .info>div>.assignee, #request-detail .info>div>.reviewers>div,
+#request-detail .info>div>.integration-strategy, #request-detail .info>div>.watch {
+ padding-bottom: 20px;
+}
+
+#request-detail .info .help-block {
+ margin-bottom: 0;
+ color: #888;
+}
+#request-detail .info .fa.small {
+ font-size: 14px;
+ vertical-align: middle;
+}
+#request-detail .info label {
+ margin-right: 4px;
+ font-weight: normal;
+}
+#request-detail .info .select2-container {
+ width: 100%;
+}
+#request-detail .info .avatar {
+ width: 24px;
+ height: 24px;
+}
+#request-detail .info .select2-container .avatar {
+ width: 20px;
+ height: 20px;
+}
+
+#request-detail .info .reviewers ul {
+ margin-bottom: 0;
+}
+#request-detail .info .reviewers li {
+ margin-right: 16px;
+ margin-bottom: 20px;
+ position: relative;
+}
+#request-detail .info .reviewers li a:hover {
+ text-decoration: none;
+}
+
+#request-detail .info .reviewers .review-result {
+ top: -4px;
+}
diff --git a/gitplex.web/src/main/java/com/pmease/gitplex/web/page/depot/pullrequest/requestdetail/request-detail.css b/gitplex.web/src/main/java/com/pmease/gitplex/web/page/depot/pullrequest/requestdetail/request-detail.css
index 89b0e798fa..d8bf827d8b 100644
--- a/gitplex.web/src/main/java/com/pmease/gitplex/web/page/depot/pullrequest/requestdetail/request-detail.css
+++ b/gitplex.web/src/main/java/com/pmease/gitplex/web/page/depot/pullrequest/requestdetail/request-detail.css
@@ -53,6 +53,9 @@
padding: 2px 4px;
border-radius: 2px;
}
+#request-detail>.summary>.note {
+ font-size: 16px;
+}
#request-detail>.summary>.status-reasons ul {
margin-bottom: 0;
padding-left: 16px;
diff --git a/gitplex.web/src/main/java/com/pmease/gitplex/web/websocket/PullRequestChangeBroadcaster.java b/gitplex.web/src/main/java/com/pmease/gitplex/web/websocket/PullRequestChangeBroadcaster.java
index 8fbeee60d9..dc1c236fc9 100644
--- a/gitplex.web/src/main/java/com/pmease/gitplex/web/websocket/PullRequestChangeBroadcaster.java
+++ b/gitplex.web/src/main/java/com/pmease/gitplex/web/websocket/PullRequestChangeBroadcaster.java
@@ -41,12 +41,12 @@ public class PullRequestChangeBroadcaster {
@Override
public void run() {
- webSocketManager.render(region, sourcePageKey);
+ webSocketManager.renderAsync(region, sourcePageKey);
}
});
} else {
- webSocketManager.render(region, sourcePageKey);
+ webSocketManager.renderAsync(region, sourcePageKey);
}
}