Skip to content

The Unified and Autonomous Development Platform

midwork

robin shine66e060341b50
diff --git a/commons.git/src/main/java/com/pmease/commons/git/GitUtils.java b/commons.git/src/main/java/com/pmease/commons/git/GitUtils.java
index 52fb0f7ff2..b8afbf8754 100644
--- a/commons.git/src/main/java/com/pmease/commons/git/GitUtils.java
+++ b/commons.git/src/main/java/com/pmease/commons/git/GitUtils.java
@@ -1,239 +1,259 @@
-package com.pmease.commons.git;
-
-import java.util.ArrayList;
-import java.util.Date;
-import java.util.List;
-import java.util.regex.Pattern;
-
-import javax.annotation.Nullable;
-
-import org.apache.commons.lang3.StringUtils;
-import org.eclipse.jgit.diff.DiffEntry;
-import org.eclipse.jgit.diff.DiffEntry.ChangeType;
-import org.eclipse.jgit.lib.AnyObjectId;
-import org.eclipse.jgit.lib.FileMode;
-import org.eclipse.jgit.lib.PersonIdent;
-import org.eclipse.jgit.revwalk.RevCommit;
-import org.eclipse.jgit.util.SystemReader;
-
-import com.google.common.base.Joiner;
-import com.google.common.base.Objects;
-import com.google.common.base.Preconditions;
-import com.google.common.base.Splitter;
-import com.google.common.base.Strings;
-import com.google.common.collect.Iterables;
-
-public class GitUtils {
-
- public static final String NULL_SHA1 = StringUtils.repeat("0", 40);
-
- public static final Pattern PATTERN_HASH = Pattern.compile("[a-z0-9]{40}");
-
- public static final int SHORT_SHA_LENGTH = 8;
-
- public static boolean isHash(String sha) {
- return PATTERN_HASH.matcher(sha).matches();
- }
-
- public static boolean isNullHash(String sha) {
- return Objects.equal(NULL_SHA1, sha);
- }
-
- public static boolean isEmptyPath(String path) {
- return Strings.isNullOrEmpty(path) || Objects.equal(path, DiffEntry.DEV_NULL);
- }
-
- public static String abbreviateSHA(String sha, int length) {
- Preconditions.checkArgument(isHash(sha));
- return sha.substring(0, length);
- }
-
- public static String abbreviateSHA(String sha) {
- return abbreviateSHA(sha, SHORT_SHA_LENGTH);
- }
-
- public static String getShortMessage(RevCommit commit) {
- return StringUtils.substringBefore(commit.getFullMessage(), "\n").trim();
- }
-
- @Nullable
- public static String getDetailMessage(RevCommit commit) {
- String body = StringUtils.substringAfter(commit.getFullMessage(), "\n").trim();
- return body.length()!=0?body:null;
- }
-
- public static String getBlobTypeName(int blobType) {
- if (blobType == FileMode.TYPE_FILE)
- return "File";
- else if (blobType == FileMode.TYPE_GITLINK)
- return "Sub module";
- else if (blobType == FileMode.TYPE_SYMLINK)
- return "Symbol link";
- else
- return "Folder";
- }
-
- public static PersonIdent newPersonIdent(String name, String email, Date when) {
- return new PersonIdent(name, email, when.getTime(),
- SystemReader.getInstance().getTimezone(when.getTime()));
- }
-
- /**
- * Parse the original git raw date to Java date. The raw git date is in
- * unix timestamp with timezone like:
- * 1392312299 -0800
- *
- * @param input the input raw date string
- * @return Java date
- */
- public static Date parseRawDate(String input) {
- String[] pieces = Iterables.toArray(Splitter.on(" ").split(input), String.class);
- return new Date(Long.valueOf(pieces[0]) * 1000L);
- }
-
- /**
- * Parse the raw user information into PersonIdent object, the raw information
- * should be in format <code>[name] [<email>] [epoch timezone]</code>, for
- * example:
- *
- * Jacob Thornton <[email protected]> 1328060294 -0800
- *
- * @param raw
- * @return
- */
- public static @Nullable PersonIdent parsePersonIdent(String raw) {
- if (Strings.isNullOrEmpty(raw))
- return null;
-
- int pos1 = raw.indexOf('<');
- if (pos1 <= 0)
- throw new IllegalArgumentException("Raw " + raw);
-
- String name = raw.substring(0, pos1 - 1);
-
- int pos2 = raw.indexOf('>');
- if (pos2 <= 0)
- throw new IllegalArgumentException("Raw " + raw);
-
- String time = raw.substring(pos2 + 1).trim();
- Date when = parseRawDate(time);
-
- String email = raw.substring(pos1 + 1, pos2 - 1);
-
- return newPersonIdent(name, email, when);
- }
-
- public static int comparePath(@Nullable String path1, @Nullable String path2) {
- List<String> segments1 = splitPath(path1);
- List<String> segments2 = splitPath(path2);
-
- int index = 0;
- for (String segment1: segments1) {
- if (index<segments2.size()) {
- int result = segment1.compareTo(segments2.get(index));
- if (result != 0)
- return result;
- } else {
- return 1;
- }
- index++;
- }
- if (index<segments2.size())
- return -1;
- else
- return 0;
- }
-
- public static List<String> splitPath(@Nullable String path) {
- List<String> pathElements = new ArrayList<>();
- if (path != null) {
- for (String element: Splitter.on("/").split(path)) {
- if (element.length() != 0)
- pathElements.add(element);
- }
- }
- return pathElements;
- }
-
- public static @Nullable String joinPath(List<String> pathSegments) {
- List<String> nonEmptyElements = new ArrayList<>();
- for (String element: pathSegments){
- if (element.length() != 0)
- nonEmptyElements.add(element);
- }
- if (!nonEmptyElements.isEmpty()) {
- return Joiner.on("/").join(nonEmptyElements);
- } else {
- return null;
- }
- }
-
- public static @Nullable String normalizePath(@Nullable String path) {
- return joinPath(splitPath(path));
- }
-
- /**
- * Convert a git reference name to branch name.
- *
- * @param refName
- * name of the git reference
- * @return
- * name of the branch, or <tt>null</tt> if specified ref
- * does not represent a branch
- */
- public static @Nullable String ref2branch(String refName) {
- if (refName.startsWith(Git.REFS_HEADS))
- return refName.substring(Git.REFS_HEADS.length());
- else
- return null;
- }
-
- public static String branch2ref(String branch) {
- return Git.REFS_HEADS + branch;
- }
-
- /**
- * Convert a git reference name to tag name.
- *
- * @param refName
- * name of the git reference
- * @return
- * name of the tag, or <tt>null</tt> if specified ref
- * does not represent a tag
- */
- public static @Nullable String ref2tag(String refName) {
- if (refName.startsWith(Git.REFS_TAGS))
- return refName.substring(Git.REFS_TAGS.length());
- else
- return null;
- }
-
- public static String tag2ref(String tag) {
- return Git.REFS_HEADS + tag;
- }
-
- public static BlobIdent getOldBlobIdent(DiffEntry diffEntry, String oldRev) {
- BlobIdent blobIdent;
- if (diffEntry.getChangeType() != ChangeType.ADD) {
- blobIdent = new BlobIdent(oldRev, diffEntry.getOldPath(), diffEntry.getOldMode().getBits());
- AnyObjectId id = diffEntry.getOldId().toObjectId();
- blobIdent.id = id!=null?id.name():null;
- } else {
- blobIdent = new BlobIdent(oldRev, null, null);
- }
- return blobIdent;
- }
-
- public static BlobIdent getNewBlobIdent(DiffEntry diffEntry, String newRev) {
- BlobIdent blobIdent;
- if (diffEntry.getChangeType() != ChangeType.DELETE) {
- blobIdent = new BlobIdent(newRev, diffEntry.getNewPath(), diffEntry.getNewMode().getBits());
- AnyObjectId id = diffEntry.getNewId().toObjectId();
- blobIdent.id = id!=null?id.name():null;
- } else {
- blobIdent = new BlobIdent(newRev, null, null);
- }
- return blobIdent;
- }
-
-}
+package com.pmease.commons.git;
+
+import java.io.IOException;
+import java.util.ArrayList;
+import java.util.Date;
+import java.util.List;
+import java.util.regex.Pattern;
+
+import javax.annotation.Nullable;
+
+import org.apache.commons.lang3.StringUtils;
+import org.eclipse.jgit.diff.DiffEntry;
+import org.eclipse.jgit.diff.DiffEntry.ChangeType;
+import org.eclipse.jgit.lib.AnyObjectId;
+import org.eclipse.jgit.lib.FileMode;
+import org.eclipse.jgit.lib.ObjectId;
+import org.eclipse.jgit.lib.PersonIdent;
+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.util.SystemReader;
+
+import com.google.common.base.Joiner;
+import com.google.common.base.Objects;
+import com.google.common.base.Preconditions;
+import com.google.common.base.Splitter;
+import com.google.common.base.Strings;
+import com.google.common.collect.Iterables;
+
+public class GitUtils {
+
+ public static final String NULL_SHA1 = StringUtils.repeat("0", 40);
+
+ public static final Pattern PATTERN_HASH = Pattern.compile("[a-z0-9]{40}");
+
+ public static final int SHORT_SHA_LENGTH = 8;
+
+ public static boolean isHash(String sha) {
+ return PATTERN_HASH.matcher(sha).matches();
+ }
+
+ public static boolean isNullHash(String sha) {
+ return Objects.equal(NULL_SHA1, sha);
+ }
+
+ public static boolean isEmptyPath(String path) {
+ return Strings.isNullOrEmpty(path) || Objects.equal(path, DiffEntry.DEV_NULL);
+ }
+
+ public static String abbreviateSHA(String sha, int length) {
+ Preconditions.checkArgument(isHash(sha));
+ return sha.substring(0, length);
+ }
+
+ public static String abbreviateSHA(String sha) {
+ return abbreviateSHA(sha, SHORT_SHA_LENGTH);
+ }
+
+ public static String getShortMessage(RevCommit commit) {
+ return StringUtils.substringBefore(commit.getFullMessage(), "\n").trim();
+ }
+
+ @Nullable
+ public static String getDetailMessage(RevCommit commit) {
+ String body = StringUtils.substringAfter(commit.getFullMessage(), "\n").trim();
+ return body.length()!=0?body:null;
+ }
+
+ public static RevCommit getMergeBase(Repository repository, ObjectId ancestorId, ObjectId descendantId) {
+ try (RevWalk walk = new RevWalk(repository)) {
+ walk.setRevFilter(RevFilter.MERGE_BASE);
+ walk.markStart(walk.lookupCommit(ancestorId));
+ walk.markStart(walk.lookupCommit(descendantId));
+ return walk.next();
+ } catch (IOException e) {
+ throw new RuntimeException(e);
+ }
+ }
+
+ public static boolean isAncestor(Repository repository, ObjectId ancestorId, ObjectId descendantId) {
+ return getMergeBase(repository, ancestorId, descendantId).equals(ancestorId);
+ }
+
+ public static String getBlobTypeName(int blobType) {
+ if (blobType == FileMode.TYPE_FILE)
+ return "File";
+ else if (blobType == FileMode.TYPE_GITLINK)
+ return "Sub module";
+ else if (blobType == FileMode.TYPE_SYMLINK)
+ return "Symbol link";
+ else
+ return "Folder";
+ }
+
+ public static PersonIdent newPersonIdent(String name, String email, Date when) {
+ return new PersonIdent(name, email, when.getTime(),
+ SystemReader.getInstance().getTimezone(when.getTime()));
+ }
+
+ /**
+ * Parse the original git raw date to Java date. The raw git date is in
+ * unix timestamp with timezone like:
+ * 1392312299 -0800
+ *
+ * @param input the input raw date string
+ * @return Java date
+ */
+ public static Date parseRawDate(String input) {
+ String[] pieces = Iterables.toArray(Splitter.on(" ").split(input), String.class);
+ return new Date(Long.valueOf(pieces[0]) * 1000L);
+ }
+
+ /**
+ * Parse the raw user information into PersonIdent object, the raw information
+ * should be in format <code>[name] [<email>] [epoch timezone]</code>, for
+ * example:
+ *
+ * Jacob Thornton <[email protected]> 1328060294 -0800
+ *
+ * @param raw
+ * @return
+ */
+ public static @Nullable PersonIdent parsePersonIdent(String raw) {
+ if (Strings.isNullOrEmpty(raw))
+ return null;
+
+ int pos1 = raw.indexOf('<');
+ if (pos1 <= 0)
+ throw new IllegalArgumentException("Raw " + raw);
+
+ String name = raw.substring(0, pos1 - 1);
+
+ int pos2 = raw.indexOf('>');
+ if (pos2 <= 0)
+ throw new IllegalArgumentException("Raw " + raw);
+
+ String time = raw.substring(pos2 + 1).trim();
+ Date when = parseRawDate(time);
+
+ String email = raw.substring(pos1 + 1, pos2 - 1);
+
+ return newPersonIdent(name, email, when);
+ }
+
+ public static int comparePath(@Nullable String path1, @Nullable String path2) {
+ List<String> segments1 = splitPath(path1);
+ List<String> segments2 = splitPath(path2);
+
+ int index = 0;
+ for (String segment1: segments1) {
+ if (index<segments2.size()) {
+ int result = segment1.compareTo(segments2.get(index));
+ if (result != 0)
+ return result;
+ } else {
+ return 1;
+ }
+ index++;
+ }
+ if (index<segments2.size())
+ return -1;
+ else
+ return 0;
+ }
+
+ public static List<String> splitPath(@Nullable String path) {
+ List<String> pathElements = new ArrayList<>();
+ if (path != null) {
+ for (String element: Splitter.on("/").split(path)) {
+ if (element.length() != 0)
+ pathElements.add(element);
+ }
+ }
+ return pathElements;
+ }
+
+ public static @Nullable String joinPath(List<String> pathSegments) {
+ List<String> nonEmptyElements = new ArrayList<>();
+ for (String element: pathSegments){
+ if (element.length() != 0)
+ nonEmptyElements.add(element);
+ }
+ if (!nonEmptyElements.isEmpty()) {
+ return Joiner.on("/").join(nonEmptyElements);
+ } else {
+ return null;
+ }
+ }
+
+ public static @Nullable String normalizePath(@Nullable String path) {
+ return joinPath(splitPath(path));
+ }
+
+ /**
+ * Convert a git reference name to branch name.
+ *
+ * @param refName
+ * name of the git reference
+ * @return
+ * name of the branch, or <tt>null</tt> if specified ref
+ * does not represent a branch
+ */
+ public static @Nullable String ref2branch(String refName) {
+ if (refName.startsWith(Git.REFS_HEADS))
+ return refName.substring(Git.REFS_HEADS.length());
+ else
+ return null;
+ }
+
+ public static String branch2ref(String branch) {
+ return Git.REFS_HEADS + branch;
+ }
+
+ /**
+ * Convert a git reference name to tag name.
+ *
+ * @param refName
+ * name of the git reference
+ * @return
+ * name of the tag, or <tt>null</tt> if specified ref
+ * does not represent a tag
+ */
+ public static @Nullable String ref2tag(String refName) {
+ if (refName.startsWith(Git.REFS_TAGS))
+ return refName.substring(Git.REFS_TAGS.length());
+ else
+ return null;
+ }
+
+ public static String tag2ref(String tag) {
+ return Git.REFS_HEADS + tag;
+ }
+
+ public static BlobIdent getOldBlobIdent(DiffEntry diffEntry, String oldRev) {
+ BlobIdent blobIdent;
+ if (diffEntry.getChangeType() != ChangeType.ADD) {
+ blobIdent = new BlobIdent(oldRev, diffEntry.getOldPath(), diffEntry.getOldMode().getBits());
+ AnyObjectId id = diffEntry.getOldId().toObjectId();
+ blobIdent.id = id!=null?id.name():null;
+ } else {
+ blobIdent = new BlobIdent(oldRev, null, null);
+ }
+ return blobIdent;
+ }
+
+ public static BlobIdent getNewBlobIdent(DiffEntry diffEntry, String newRev) {
+ BlobIdent blobIdent;
+ if (diffEntry.getChangeType() != ChangeType.DELETE) {
+ blobIdent = new BlobIdent(newRev, diffEntry.getNewPath(), diffEntry.getNewMode().getBits());
+ AnyObjectId id = diffEntry.getNewId().toObjectId();
+ blobIdent.id = id!=null?id.name():null;
+ } else {
+ blobIdent = new BlobIdent(newRev, null, null);
+ }
+ return blobIdent;
+ }
+
+}
diff --git a/commons.git/src/main/java/com/pmease/commons/git/command/IsAncestorCommand.java b/commons.git/src/main/java/com/pmease/commons/git/command/IsAncestorCommand.java
index b6117b0422..e1d428297b 100644
--- a/commons.git/src/main/java/com/pmease/commons/git/command/IsAncestorCommand.java
+++ b/commons.git/src/main/java/com/pmease/commons/git/command/IsAncestorCommand.java
@@ -1,68 +1,68 @@
-package com.pmease.commons.git.command;
-
-import java.io.File;
-
-import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
-
-import com.google.common.base.Preconditions;
-import com.pmease.commons.util.execution.Commandline;
-import com.pmease.commons.util.execution.ExecuteResult;
-import com.pmease.commons.util.execution.LineConsumer;
-
-public class IsAncestorCommand extends GitCommand<Boolean> {
-
- private static final Logger logger = LoggerFactory.getLogger(IsAncestorCommand.class);
-
- private String ancestor;
-
- private String descendant;
-
- public IsAncestorCommand(final File repoDir) {
- super(repoDir);
- }
-
- public IsAncestorCommand ancestor(final String ancestor) {
- this.ancestor = ancestor;
- return this;
- }
-
- public IsAncestorCommand descendant(final String descendant) {
- this.descendant = descendant;
- return this;
- }
-
- @Override
- public Boolean call() {
- Preconditions.checkNotNull(ancestor, "ancestor has to be specified.");
- Preconditions.checkNotNull(descendant, "descendant has to be specified.");
-
- Commandline cmd = cmd();
-
- cmd.addArgs("merge-base", "--is-ancestor", ancestor, descendant);
-
- ExecuteResult result = cmd.execute(new LineConsumer() {
-
- @Override
- public void consume(String line) {
- //logger.info(line);
- }
-
- }, new LineConsumer() {
-
- @Override
- public void consume(String line) {
- logger.error(line);
- }
-
- });
-
- if (result.getReturnCode() == 0)
- return true;
- else if (result.getReturnCode() == 1)
- return false;
- else
- throw result.buildException();
- }
-
-}
+package com.pmease.commons.git.command;
+
+import java.io.File;
+
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+import com.google.common.base.Preconditions;
+import com.pmease.commons.util.execution.Commandline;
+import com.pmease.commons.util.execution.ExecuteResult;
+import com.pmease.commons.util.execution.LineConsumer;
+
+public class IsAncestorCommand extends GitCommand<Boolean> {
+
+ private static final Logger logger = LoggerFactory.getLogger(IsAncestorCommand.class);
+
+ private String ancestor;
+
+ private String descendant;
+
+ public IsAncestorCommand(final File repoDir) {
+ super(repoDir);
+ }
+
+ public IsAncestorCommand ancestor(final String ancestor) {
+ this.ancestor = ancestor;
+ return this;
+ }
+
+ public IsAncestorCommand descendant(final String descendant) {
+ this.descendant = descendant;
+ return this;
+ }
+
+ @Override
+ public Boolean call() {
+ Preconditions.checkNotNull(ancestor, "ancestor has to be specified.");
+ Preconditions.checkNotNull(descendant, "descendant has to be specified.");
+
+ Commandline cmd = cmd();
+
+ cmd.addArgs("merge-base", "--is-ancestor", ancestor, descendant);
+
+ ExecuteResult result = cmd.execute(new LineConsumer() {
+
+ @Override
+ public void consume(String line) {
+ //logger.info(line);
+ }
+
+ }, new LineConsumer() {
+
+ @Override
+ public void consume(String line) {
+ logger.error(line);
+ }
+
+ });
+
+ if (result.getReturnCode() == 0)
+ return true;
+ else if (result.getReturnCode() == 1)
+ return false;
+ else
+ throw result.buildException();
+ }
+
+}
diff --git a/gitplex.core/src/main/java/com/pmease/gitplex/core/gatekeeper/IfPushWithoutRewritingHistory.java b/gitplex.core/src/main/java/com/pmease/gitplex/core/gatekeeper/IfPushWithoutRewritingHistory.java
index d9dcf44495..1aa24e09b5 100644
--- a/gitplex.core/src/main/java/com/pmease/gitplex/core/gatekeeper/IfPushWithoutRewritingHistory.java
+++ b/gitplex.core/src/main/java/com/pmease/gitplex/core/gatekeeper/IfPushWithoutRewritingHistory.java
@@ -1,41 +1,41 @@
-package com.pmease.gitplex.core.gatekeeper;
-
-import com.google.common.collect.Lists;
-import com.pmease.commons.git.GitUtils;
-import com.pmease.commons.wicket.editable.annotation.Editable;
-import com.pmease.gitplex.core.gatekeeper.checkresult.CheckResult;
-import com.pmease.gitplex.core.model.PullRequest;
-import com.pmease.gitplex.core.model.Repository;
-import com.pmease.gitplex.core.model.User;
-
-@Editable(order=100, icon="fa-ext fa-repo-lock", description="This gate keeper will be passed if the push "
- + "operation does not rewrite history of target branch. Rewriting history of public branches "
- + "is dangerous, and it happens when user forces a push without merging/rebasing with the "
- + "branch head.")
-@SuppressWarnings("serial")
-public class IfPushWithoutRewritingHistory extends AbstractGateKeeper {
-
- @Override
- protected CheckResult doCheckRequest(PullRequest request) {
- return ignored();
- }
-
- @Override
- protected CheckResult doCheckFile(User user, Repository repository, String branch, String file) {
- return ignored();
- }
-
- @Override
- protected CheckResult doCheckCommit(User user, Repository repository, String branch, String commit) {
- if (repository.git().isAncestor(repository.getObjectId(GitUtils.branch2ref(branch)).name(), commit))
- return passed(Lists.newArrayList("Push operation does not rewrite history."));
- else
- return failed(Lists.newArrayList("Push operation rewrites history."));
- }
-
- @Override
- protected CheckResult doCheckRef(User user, Repository repository, String refName) {
- return ignored();
- }
-
-}
+package com.pmease.gitplex.core.gatekeeper;
+
+import com.google.common.collect.Lists;
+import com.pmease.commons.git.GitUtils;
+import com.pmease.commons.wicket.editable.annotation.Editable;
+import com.pmease.gitplex.core.gatekeeper.checkresult.CheckResult;
+import com.pmease.gitplex.core.model.PullRequest;
+import com.pmease.gitplex.core.model.Repository;
+import com.pmease.gitplex.core.model.User;
+
+@Editable(order=100, icon="fa-ext fa-repo-lock", description="This gate keeper will be passed if the push "
+ + "operation does not rewrite history of target branch. Rewriting history of public branches "
+ + "is dangerous, and it happens when user forces a push without merging/rebasing with the "
+ + "branch head.")
+@SuppressWarnings("serial")
+public class IfPushWithoutRewritingHistory extends AbstractGateKeeper {
+
+ @Override
+ protected CheckResult doCheckRequest(PullRequest request) {
+ return ignored();
+ }
+
+ @Override
+ protected CheckResult doCheckFile(User user, Repository repository, String branch, String file) {
+ return ignored();
+ }
+
+ @Override
+ protected CheckResult doCheckCommit(User user, Repository repository, String branch, String commit) {
+ if (repository.isAncestor(GitUtils.branch2ref(branch), commit))
+ return passed(Lists.newArrayList("Push operation does not rewrite history."));
+ else
+ return failed(Lists.newArrayList("Push operation rewrites history."));
+ }
+
+ @Override
+ protected CheckResult doCheckRef(User user, Repository repository, String refName) {
+ return ignored();
+ }
+
+}
diff --git a/gitplex.core/src/main/java/com/pmease/gitplex/core/manager/AuxiliaryManager.java b/gitplex.core/src/main/java/com/pmease/gitplex/core/manager/AuxiliaryManager.java
index f351afd982..a537a6640b 100644
--- a/gitplex.core/src/main/java/com/pmease/gitplex/core/manager/AuxiliaryManager.java
+++ b/gitplex.core/src/main/java/com/pmease/gitplex/core/manager/AuxiliaryManager.java
@@ -1,20 +1,20 @@
-package com.pmease.gitplex.core.manager;
-
-import java.util.List;
-import java.util.Map;
-import java.util.Set;
-
-import com.pmease.commons.git.NameAndEmail;
-import com.pmease.gitplex.core.model.Repository;
-
-public interface AuxiliaryManager {
-
- void check(Repository repository, String refName);
-
- List<String> getFiles(Repository repository);
-
- List<NameAndEmail> getContributors(Repository repository);
-
- Map<String, Map<NameAndEmail, Long>> getContributions(Repository repository, Set<String> files);
-
-}
+package com.pmease.gitplex.core.manager;
+
+import java.util.List;
+import java.util.Map;
+import java.util.Set;
+
+import com.pmease.commons.git.NameAndEmail;
+import com.pmease.gitplex.core.model.Repository;
+
+public interface AuxiliaryManager {
+
+ void check(Repository repository, String refName);
+
+ List<String> getFiles(Repository repository);
+
+ List<NameAndEmail> getContributors(Repository repository);
+
+ Map<String, Map<NameAndEmail, Long>> getContributions(Repository repository, Set<String> files);
+
+}
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 1f694e8441..63c8b62703 100644
--- a/gitplex.core/src/main/java/com/pmease/gitplex/core/manager/impl/DefaultPullRequestManager.java
+++ b/gitplex.core/src/main/java/com/pmease/gitplex/core/manager/impl/DefaultPullRequestManager.java
@@ -1,824 +1,824 @@
-package com.pmease.gitplex.core.manager.impl;
-
-import static com.pmease.gitplex.core.model.PullRequest.CriterionHelper.ofOpen;
-import static com.pmease.gitplex.core.model.PullRequest.CriterionHelper.ofSource;
-import static com.pmease.gitplex.core.model.PullRequest.CriterionHelper.ofTarget;
-import static com.pmease.gitplex.core.model.PullRequest.IntegrationStrategy.MERGE_ALWAYS;
-import static com.pmease.gitplex.core.model.PullRequest.IntegrationStrategy.MERGE_IF_NECESSARY;
-import static com.pmease.gitplex.core.model.PullRequest.IntegrationStrategy.MERGE_WITH_SQUASH;
-import static com.pmease.gitplex.core.model.PullRequest.IntegrationStrategy.REBASE_SOURCE_ONTO_TARGET;
-import static com.pmease.gitplex.core.model.PullRequest.IntegrationStrategy.REBASE_TARGET_ONTO_SOURCE;
-import static com.pmease.gitplex.core.model.PullRequest.Status.PENDING_APPROVAL;
-import static com.pmease.gitplex.core.model.PullRequest.Status.PENDING_INTEGRATE;
-import static com.pmease.gitplex.core.model.PullRequest.Status.PENDING_UPDATE;
-
-import java.io.File;
-import java.util.Collection;
-import java.util.Date;
-import java.util.List;
-import java.util.Set;
-
-import javax.annotation.Nullable;
-import javax.inject.Inject;
-import javax.inject.Singleton;
-
-import org.apache.commons.lang3.builder.EqualsBuilder;
-import org.apache.commons.lang3.builder.HashCodeBuilder;
-import org.apache.wicket.request.cycle.RequestCycle;
-import org.eclipse.jetty.util.ConcurrentHashSet;
-import org.eclipse.jgit.lib.ObjectId;
-import org.hibernate.Query;
-import org.hibernate.criterion.Criterion;
-import org.hibernate.criterion.Restrictions;
-import org.joda.time.DateTime;
-import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
-
-import com.google.common.base.Preconditions;
-import com.google.common.collect.Lists;
-import com.pmease.commons.git.Git;
-import com.pmease.commons.git.GitUtils;
-import com.pmease.commons.git.command.MergeCommand.FastForwardMode;
-import com.pmease.commons.hibernate.Sessional;
-import com.pmease.commons.hibernate.Transactional;
-import com.pmease.commons.hibernate.UnitOfWork;
-import com.pmease.commons.hibernate.dao.Dao;
-import com.pmease.commons.hibernate.dao.EntityCriteria;
-import com.pmease.commons.markdown.MarkdownManager;
-import com.pmease.commons.util.FileUtils;
-import com.pmease.commons.util.concurrent.PrioritizedRunnable;
-import com.pmease.gitplex.core.GitPlex;
-import com.pmease.gitplex.core.listeners.LifecycleListener;
-import com.pmease.gitplex.core.listeners.PullRequestListener;
-import com.pmease.gitplex.core.listeners.RefListener;
-import com.pmease.gitplex.core.listeners.RepositoryListener;
-import com.pmease.gitplex.core.manager.CommentManager;
-import com.pmease.gitplex.core.manager.NotificationManager;
-import com.pmease.gitplex.core.manager.PullRequestManager;
-import com.pmease.gitplex.core.manager.PullRequestUpdateManager;
-import com.pmease.gitplex.core.manager.ReviewInvitationManager;
-import com.pmease.gitplex.core.manager.StorageManager;
-import com.pmease.gitplex.core.manager.UserManager;
-import com.pmease.gitplex.core.manager.WorkManager;
-import com.pmease.gitplex.core.model.CloseInfo;
-import com.pmease.gitplex.core.model.Comment;
-import com.pmease.gitplex.core.model.IntegrationPolicy;
-import com.pmease.gitplex.core.model.IntegrationPreview;
-import com.pmease.gitplex.core.model.PullRequest;
-import com.pmease.gitplex.core.model.PullRequest.IntegrationStrategy;
-import com.pmease.gitplex.core.model.PullRequestActivity;
-import com.pmease.gitplex.core.model.PullRequestUpdate;
-import com.pmease.gitplex.core.model.PullRequestVisit;
-import com.pmease.gitplex.core.model.RepoAndBranch;
-import com.pmease.gitplex.core.model.Repository;
-import com.pmease.gitplex.core.model.ReviewInvitation;
-import com.pmease.gitplex.core.model.User;
-
-@Singleton
-public class DefaultPullRequestManager implements PullRequestManager, RepositoryListener, RefListener, LifecycleListener {
-
- private static final Logger logger = LoggerFactory.getLogger(DefaultPullRequestManager.class);
-
- private static final int UI_PREVIEW_PRIORITY = 10;
-
- private static final int BACKEND_PREVIEW_PRIORITY = 50;
-
- private final Dao dao;
-
- private final PullRequestUpdateManager pullRequestUpdateManager;
-
- private final CommentManager commentManager;
-
- private final UserManager userManager;
-
- private final StorageManager storageManager;
-
- private final UnitOfWork unitOfWork;
-
- private final Set<PullRequestListener> pullRequestListeners;
-
- private final ReviewInvitationManager reviewInvitationManager;
-
- private final Set<Long> integrationPreviewCalculatingRequestIds = new ConcurrentHashSet<>();
-
- private final WorkManager workManager;
-
- @Inject
- public DefaultPullRequestManager(Dao dao, PullRequestUpdateManager pullRequestUpdateManager,
- StorageManager storageManager, ReviewInvitationManager reviewInvitationManager,
- UserManager userManager, NotificationManager notificationManager,
- CommentManager commentManager, MarkdownManager markdownManager,
- WorkManager workManager, UnitOfWork unitOfWork,
- Set<PullRequestListener> pullRequestListeners) {
- this.dao = dao;
- this.pullRequestUpdateManager = pullRequestUpdateManager;
- this.storageManager = storageManager;
- this.reviewInvitationManager = reviewInvitationManager;
- this.commentManager = commentManager;
- this.userManager = userManager;
- this.workManager = workManager;
- this.unitOfWork = unitOfWork;
- this.pullRequestListeners = pullRequestListeners;
- }
-
- @Transactional
- @Override
- public void delete(PullRequest request) {
- deleteRefs(request);
-
- dao.remove(request);
- }
-
- @Sessional
- @Override
- public void deleteRefs(PullRequest request) {
- for (PullRequestUpdate update : request.getUpdates())
- update.deleteRefs();
-
- request.deleteRefs();
- }
-
- @Transactional
- @Override
- public void restoreSourceBranch(PullRequest request) {
- Preconditions.checkState(!request.isOpen() && request.getSourceRepo() != null);
-
- if (request.getSource().getHead(false) == null) {
- String latestCommitHash = request.getLatestUpdate().getHeadCommitHash();
- request.getSourceRepo().git().createBranch(
- request.getSourceBranch(), latestCommitHash);
- request.getSourceRepo().cacheObjectId(request.getSourceBranch(), ObjectId.fromString(latestCommitHash));
- PullRequestActivity activity = new PullRequestActivity();
- activity.setRequest(request);
- activity.setAction(PullRequestActivity.Action.RESTORE_SOURCE_BRANCH);
- activity.setDate(new Date());
- activity.setUser(GitPlex.getInstance(UserManager.class).getCurrent());
- dao.persist(activity);
- }
- }
-
- @Transactional
- @Override
- public void deleteSourceBranch(PullRequest request) {
- Preconditions.checkState(!request.isOpen() && request.getSourceRepo() != null);
-
- if (request.getSource().getHead(false) != null) {
- request.getSource().delete();
-
- PullRequestActivity activity = new PullRequestActivity();
- activity.setRequest(request);
- activity.setAction(PullRequestActivity.Action.DELETE_SOURCE_BRANCH);
- activity.setDate(new Date());
- activity.setUser(GitPlex.getInstance(UserManager.class).getCurrent());
- dao.persist(activity);
- }
- }
-
- @Transactional
- @Override
- public void reopen(PullRequest request, String comment) {
- Preconditions.checkState(!request.isOpen());
-
- User user = userManager.getCurrent();
- request.setCloseInfo(null);
- request.setSubmitter(user);
- request.setSubmitDate(new Date());
-
- dao.persist(request);
-
- PullRequestActivity activity = new PullRequestActivity();
- activity.setRequest(request);
- activity.setDate(new DateTime(request.getSubmitDate()).minusSeconds(1).toDate());
- activity.setAction(PullRequestActivity.Action.REOPEN);
- activity.setUser(user);
-
- dao.persist(activity);
-
- if (comment != null) {
- Comment requestComment = new Comment();
- requestComment.setContent(comment);
- requestComment.setRequest(request);
- requestComment.setUser(user);
- commentManager.save(requestComment, false);
- }
-
- onSourceBranchUpdate(request, false);
-
- if (request.isOpen()) {
- for (PullRequestListener listener: pullRequestListeners)
- listener.onReopened(request, user, comment);
- }
- }
-
- @Transactional
- @Override
- public void discard(PullRequest request, final String comment) {
- User user = userManager.getCurrent();
- PullRequestActivity activity = new PullRequestActivity();
- activity.setRequest(request);
- activity.setDate(new Date());
- activity.setAction(PullRequestActivity.Action.DISCARD);
- activity.setUser(user);
-
- dao.persist(activity);
-
- if (comment != null) {
- Comment requestComment = new Comment();
- requestComment.setContent(comment);
- requestComment.setRequest(request);
- requestComment.setUser(user);
-
- commentManager.save(requestComment, false);
- }
-
- CloseInfo closeInfo = new CloseInfo();
- closeInfo.setCloseDate(activity.getDate());
- closeInfo.setClosedBy(user);
- closeInfo.setCloseStatus(CloseInfo.Status.DISCARDED);
- request.setCloseInfo(closeInfo);
- request.setLastEventDate(activity.getDate());
- dao.persist(request);
-
- for (PullRequestListener listener: pullRequestListeners)
- listener.onDiscarded(request, user, comment);
- }
-
- @Transactional
- @Override
- public void integrate(PullRequest request, String comment) {
- if (request.getStatus() != PENDING_INTEGRATE)
- throw new IllegalStateException("Gate keeper disallows integration right now.");
-
- IntegrationPreview preview = request.getIntegrationPreview();
- if (preview == null)
- throw new IllegalStateException("Integration preview has not been calculated yet.");
-
- String integrated = preview.getIntegrated();
- if (integrated == null)
- throw new IllegalStateException("There are integration conflicts.");
-
- User user = userManager.getCurrent();
-
- Repository targetRepo = request.getTargetRepo();
- Git git = targetRepo.git();
- IntegrationStrategy strategy = request.getIntegrationStrategy();
- if ((strategy == MERGE_ALWAYS || strategy == MERGE_IF_NECESSARY || strategy == MERGE_WITH_SQUASH)
- && !preview.getIntegrated().equals(preview.getRequestHead()) && comment != null) {
- File tempDir = FileUtils.createTempDir();
- try {
- Git tempGit = new Git(tempDir);
- tempGit.clone(git.repoDir().getAbsolutePath(), false, true, true, request.getTargetBranch());
- tempGit.updateRef("HEAD", preview.getIntegrated(), null, null);
- tempGit.reset(null, null);
-
- tempGit.commit(comment, false, true);
- integrated = tempGit.parseRevision("HEAD", true);
- git.fetch(tempGit, "+HEAD:" + request.getIntegrateRef());
- comment = null;
- } finally {
- FileUtils.deleteDir(tempDir);
- }
- }
- if (strategy == REBASE_SOURCE_ONTO_TARGET || strategy == MERGE_WITH_SQUASH) {
- Repository sourceRepo = request.getSourceRepo();
- Git sourceGit = sourceRepo.git();
- String sourceRef = request.getSourceRef();
- sourceGit.updateRef(sourceRef, integrated, preview.getRequestHead(),
- "Pull request #" + request.getId());
- sourceRepo.cacheObjectId(request.getSourceRef(), ObjectId.fromString(integrated));
- onRefUpdate(sourceRepo, sourceRef, integrated);
- }
-
- String targetRef = request.getTargetRef();
- git.updateRef(targetRef, integrated, preview.getTargetHead(), "Pull request #" + request.getId());
- targetRepo.cacheObjectId(request.getTargetRef(), ObjectId.fromString(integrated));
- onRefUpdate(targetRepo, targetRef, integrated);
-
- PullRequestActivity activity = new PullRequestActivity();
- activity.setRequest(request);
- activity.setDate(new Date());
- activity.setAction(PullRequestActivity.Action.INTEGRATE);
- activity.setUser(user);
-
- dao.persist(activity);
-
- if (comment != null) {
- Comment requestComment = new Comment();
- requestComment.setContent(comment);
- requestComment.setRequest(request);
- requestComment.setUser(user);
- commentManager.save(requestComment, false);
- }
-
- CloseInfo closeInfo = new CloseInfo();
- closeInfo.setCloseDate(activity.getDate());
- closeInfo.setClosedBy(user);
- closeInfo.setCloseStatus(CloseInfo.Status.INTEGRATED);
- request.setCloseInfo(closeInfo);
-
- request.setLastEventDate(activity.getDate());
-
- dao.persist(request);
-
- for (PullRequestListener listener: pullRequestListeners)
- listener.onIntegrated(request, user, comment);
- }
-
- @Transactional
- @Override
- public void open(final PullRequest request, final Object listenerData) {
- dao.persist(request);
-
- PullRequestActivity activity = new PullRequestActivity();
- activity.setDate(request.getSubmitDate());
- activity.setAction(PullRequestActivity.Action.OPEN);
- activity.setRequest(request);
- activity.setUser(request.getSubmitter());
- dao.persist(activity);
-
- FileUtils.cleanDir(storageManager.getCacheDir(request));
-
- request.git().updateRef(request.getBaseRef(), request.getBaseCommitHash(), null, null);
-
- for (PullRequestUpdate update: request.getUpdates()) {
- update.setDate(new DateTime(activity.getDate()).plusSeconds(1).toDate());
- pullRequestUpdateManager.save(update, false);
- }
-
- for (ReviewInvitation invitation: request.getReviewInvitations())
- reviewInvitationManager.save(invitation);
-
- for (PullRequestListener listener: pullRequestListeners)
- listener.onOpened(request);
-
- dao.afterCommit(new Runnable() {
-
- @Override
- public void run() {
- IntegrationPreviewTask task = new IntegrationPreviewTask(request.getId());
- workManager.remove(task);
- workManager.execute(task);
- }
-
- });
- }
-
- @Override
- public List<IntegrationStrategy> getApplicableIntegrationStrategies(PullRequest request) {
- List<IntegrationStrategy> strategies = null;
- for (IntegrationPolicy policy: request.getTargetRepo().getIntegrationPolicies()) {
- if (policy.getTargetBranches().matches(request.getTargetBranch())
- && policy.getSourceBranches().matches(request.getSourceRepo(), request.getSourceBranch())) {
- strategies = policy.getIntegrationStrategies();
- break;
- }
- }
- if (strategies == null)
- strategies = Lists.newArrayList(IntegrationStrategy.MERGE_ALWAYS);
- return strategies;
- }
-
- @Transactional
- @Override
- public void onAssigneeChange(PullRequest request) {
- dao.persist(request);
- for (PullRequestListener listener: pullRequestListeners)
- listener.onAssigned(request);
- }
-
- @Transactional
- @Override
- public void onTargetBranchUpdate(PullRequest request) {
- closeIfMerged(request);
- if (request.isOpen()) {
- IntegrationPreviewTask task = new IntegrationPreviewTask(request.getId());
- workManager.remove(task);
- workManager.execute(task);
- }
- }
-
- @Transactional
- private void closeIfMerged(PullRequest request) {
- Git git = request.getTargetRepo().git();
- if (git.isAncestor(request.getLatestUpdate().getHeadCommitHash(), request.getTarget().getHead())) {
- PullRequestActivity activity = new PullRequestActivity();
- activity.setRequest(request);
- activity.setUser(GitPlex.getInstance(UserManager.class).getRoot());
- activity.setAction(PullRequestActivity.Action.INTEGRATE);
- activity.setDate(new Date());
- dao.persist(activity);
-
- request.setLastIntegrationPreview(null);
- CloseInfo closeInfo = new CloseInfo();
- closeInfo.setCloseDate(activity.getDate());
- closeInfo.setClosedBy(activity.getUser());
- closeInfo.setCloseStatus(CloseInfo.Status.INTEGRATED);
- request.setCloseInfo(closeInfo);
- request.setLastEventDate(activity.getDate());
-
- dao.persist(request);
-
- for (PullRequestListener listener: pullRequestListeners)
- listener.onIntegrated(request, null, null);
- }
- }
-
- @Transactional
- @Override
- public void onSourceBranchUpdate(PullRequest request, boolean notify) {
- if (request.getLatestUpdate().getHeadCommitHash().equals(request.getSource().getHead()))
- return;
-
- PullRequestUpdate update = new PullRequestUpdate();
- update.setRequest(request);
- update.setDate(new Date());
- update.setHeadCommitHash(request.getSource().getHead());
-
- request.addUpdate(update);
- pullRequestUpdateManager.save(update, notify);
- closeIfMerged(request);
-
- if (request.isOpen()) {
- final Long requestId = request.getId();
- dao.afterCommit(new Runnable() {
-
- @Override
- public void run() {
- unitOfWork.asyncCall(new Runnable() {
-
- @Override
- public void run() {
- check(dao.load(PullRequest.class, requestId));
- }
-
- });
- }
-
- });
- }
- }
-
- /**
- * This method might take some time and is not key to pull request logic (even if we
- * did not call it, we can always call it later), so normally should be called in an
- * executor
- */
- @Transactional
- @Override
- public void check(PullRequest request) {
- Date now = new Date();
- if (request.isOpen()) {
- closeIfMerged(request);
- if (request.isOpen()) {
- if (request.getStatus() == PENDING_UPDATE) {
- for (PullRequestListener listener: pullRequestListeners)
- listener.pendingUpdate(request);
- } else if (request.getStatus() == PENDING_INTEGRATE) {
- for (PullRequestListener listener: pullRequestListeners)
- listener.pendingIntegration(request);
-
- IntegrationPreview integrationPreview = request.getIntegrationPreview();
- if (integrationPreview != null
- && integrationPreview.getIntegrated() != null
- && request.getAssignee() == null) {
- integrate(request, "Integrated automatically by system");
- }
- } else if (request.getStatus() == PENDING_APPROVAL) {
- for (PullRequestListener listener: pullRequestListeners)
- listener.pendingApproval(request);
-
- for (ReviewInvitation invitation: request.getReviewInvitations()) {
- if (!invitation.getDate().before(now))
- reviewInvitationManager.save(invitation);
- }
- }
- }
- }
- }
-
- @Override
- public boolean canIntegrate(PullRequest request) {
- if (request.getStatus() != PENDING_INTEGRATE) {
- return false;
- } else {
- IntegrationPreview integrationPreview = request.getIntegrationPreview();
- return integrationPreview != null && integrationPreview.getIntegrated() != null;
- }
- }
-
- @Override
- public IntegrationPreview previewIntegration(PullRequest request) {
- IntegrationPreview preview = request.getLastIntegrationPreview();
- if (request.isOpen() && (preview == null || preview.isObsolete(request))) {
- IntegrationPreviewTask task = new IntegrationPreviewTask(request.getId());
- workManager.remove(task);
- workManager.execute(task);
- return null;
- } else {
- return preview;
- }
- }
-
- private class IntegrationPreviewTask extends PrioritizedRunnable {
-
- private final Long requestId;
-
- public IntegrationPreviewTask(Long requestId) {
- super(RequestCycle.get() != null?UI_PREVIEW_PRIORITY:BACKEND_PREVIEW_PRIORITY);
- this.requestId = requestId;
- }
-
- @Override
- public void run() {
- unitOfWork.begin();
- try {
- if (!integrationPreviewCalculatingRequestIds.contains(requestId)) {
- integrationPreviewCalculatingRequestIds.add(requestId);
- logger.info("Calculating integration preview of pull request #{}...", requestId);
- try {
- PullRequest request = dao.load(PullRequest.class, requestId);
- IntegrationPreview preview = request.getLastIntegrationPreview();
- if (request.isOpen() && (preview == null || preview.isObsolete(request))) {
- String requestHead = request.getLatestUpdate().getHeadCommitHash();
- String targetHead = request.getTarget().getHead();
- Git git = request.getTargetRepo().git();
- preview = new IntegrationPreview(targetHead,
- request.getLatestUpdate().getHeadCommitHash(), request.getIntegrationStrategy(), null);
- request.setLastIntegrationPreview(preview);
- String integrateRef = request.getIntegrateRef();
- if (preview.getIntegrationStrategy() == MERGE_IF_NECESSARY && git.isAncestor(targetHead, requestHead)
- || preview.getIntegrationStrategy() == MERGE_WITH_SQUASH && git.isAncestor(targetHead, requestHead)
- && git.log(targetHead, requestHead, null, 0, 0, false).size() == 1) {
- preview.setIntegrated(requestHead);
- git.updateRef(integrateRef, requestHead, null, null);
- } else {
- File tempDir = FileUtils.createTempDir();
- try {
- Git tempGit = new Git(tempDir);
- tempGit.clone(git.repoDir().getAbsolutePath(), false, true, true,
- request.getTargetBranch());
-
- String integrated;
-
- if (preview.getIntegrationStrategy() == REBASE_TARGET_ONTO_SOURCE) {
- tempGit.updateRef("HEAD", requestHead, null, null);
- tempGit.reset(null, null);
- List<String> cherries = tempGit.listCherries("HEAD", targetHead);
- integrated = tempGit.cherryPick(cherries.toArray(new String[cherries.size()]));
- } else {
- tempGit.updateRef("HEAD", targetHead, null, null);
- tempGit.reset(null, null);
- if (preview.getIntegrationStrategy() == REBASE_SOURCE_ONTO_TARGET) {
- List<String> cherries = tempGit.listCherries("HEAD", requestHead);
- integrated = tempGit.cherryPick(cherries.toArray(new String[cherries.size()]));
- } else if (preview.getIntegrationStrategy() == MERGE_WITH_SQUASH) {
- String commitMessage = request.getTitle() + "\n\n";
- if (request.getDescription() != null)
- commitMessage += request.getDescription() + "\n\n";
- commitMessage += "(squashed commit of pull request #" + request.getId() + ")\n";
- integrated = tempGit.squash(requestHead, null, null, commitMessage);
- } else {
- FastForwardMode fastForwardMode;
- if (preview.getIntegrationStrategy() == MERGE_ALWAYS)
- fastForwardMode = FastForwardMode.NO_FF;
- else
- fastForwardMode = FastForwardMode.FF;
- String commitMessage = "Merge pull request #" + request.getId()
- + "\n\n" + request.getTitle() + "\n";
- integrated = tempGit.merge(requestHead, fastForwardMode, null, null, commitMessage);
- }
- }
-
- if (integrated != null) {
- preview.setIntegrated(integrated);
- git.fetch(tempGit, "+HEAD:" + integrateRef);
- } else {
- git.deleteRef(integrateRef, null, null);
- }
- } finally {
- FileUtils.deleteDir(tempDir);
- }
- }
- dao.persist(request);
-
- if (request.getStatus() == PENDING_INTEGRATE
- && preview.getIntegrated() != null
- && request.getAssignee() == null) {
- integrate(request, "Integrated automatically by system");
- }
-
- for (PullRequestListener listener: pullRequestListeners)
- listener.onIntegrationPreviewCalculated(request);
- }
- } finally {
- integrationPreviewCalculatingRequestIds.remove(requestId);
- logger.info("Integration preview of pull request #{} is calculated.", requestId);
- }
- }
- } catch (Exception e) {
- logger.error("Error calculating integration preview of pull request #" + requestId, e);
- } finally {
- unitOfWork.end();
- }
- }
-
- @Override
- public boolean equals(Object other) {
- if (!(other instanceof IntegrationPreviewTask))
- return false;
- if (this == other)
- return true;
- IntegrationPreviewTask otherRunnable = (IntegrationPreviewTask) other;
- return new EqualsBuilder().append(requestId, otherRunnable.requestId).isEquals();
- }
-
- @Override
- public int hashCode() {
- return new HashCodeBuilder(17, 37).append(requestId).toHashCode();
- }
-
- }
-
- @Override
- public Date getLastVisitDate(PullRequest request) {
- User user = userManager.getCurrent();
- if (user != null) {
- PullRequestVisit visit = request.getVisit(user);
- if (visit != null)
- return visit.getDate();
- else
- return null;
- } else {
- return null;
- }
- }
-
- @Override
- public void systemStarted() {
- logger.info("Checking pull requests...");
-
- checkSanity();
- }
-
- @Override
- public void systemStopping() {
- }
-
- @Override
- public void systemStopped() {
- }
-
- @Transactional
- @Override
- public void beforeDelete(Repository repository) {
- for (PullRequest request: repository.getOutgoingRequests()) {
- if (!request.getTargetRepo().equals(repository) && request.isOpen())
- discard(request, "Source repository is deleted.");
- }
-
- Query query = dao.getSession().createQuery("update PullRequest set sourceRepo=null where "
- + "sourceRepo = :repo and targetRepo != :repo");
- query.setParameter("repo", repository);
- query.executeUpdate();
- }
-
- @Override
- public void afterDelete(Repository repository) {
- }
-
- @Transactional
- @Override
- public void onRefUpdate(Repository repository, String refName, @Nullable String newCommitHash) {
- final String branch = GitUtils.ref2branch(refName);
- if (branch != null) {
- RepoAndBranch repoAndBranch = new RepoAndBranch(repository, branch);
- if (newCommitHash != null) {
- /**
- * Source branch update is key to the logic as it has to create
- * pull request update, so we should not postpone it to be executed
- * in a executor service like target branch update below
- */
- Criterion criterion = Restrictions.and(ofOpen(), ofSource(repoAndBranch));
- for (PullRequest request: dao.query(EntityCriteria.of(PullRequest.class).add(criterion)))
- onSourceBranchUpdate(request, true);
-
- final Long repoId = repository.getId();
- dao.afterCommit(new Runnable() {
-
- @Override
- public void run() {
- unitOfWork.asyncCall(new Runnable() {
-
- @Override
- public void run() {
- RepoAndBranch repoAndBranch = new RepoAndBranch(repoId, branch);
- Criterion criterion = Restrictions.and(ofOpen(), ofTarget(repoAndBranch));
- for (PullRequest request: dao.query(EntityCriteria.of(PullRequest.class).add(criterion)))
- onTargetBranchUpdate(request);
- }
-
- });
- }
-
- });
- } else {
- Criterion criterion = Restrictions.and(
- ofOpen(),
- Restrictions.or(ofSource(repoAndBranch), ofTarget(repoAndBranch)));
- for (PullRequest request: dao.query(EntityCriteria.of(PullRequest.class).add(criterion))) {
- if (request.getTargetRepo().equals(repository) && request.getTargetBranch().equals(branch))
- discard(request, "Target branch is deleted.");
- else
- discard(request, "Source branch is deleted.");
- }
- }
- }
- }
-
- @Sessional
- @Override
- public PullRequest findOpen(RepoAndBranch target, RepoAndBranch source) {
- return dao.find(EntityCriteria.of(PullRequest.class)
- .add(ofTarget(target)).add(ofSource(source)).add(ofOpen()));
- }
-
- @Sessional
- @Override
- public Collection<PullRequest> queryOpenTo(RepoAndBranch target, @Nullable Repository sourceRepo) {
- EntityCriteria<PullRequest> criteria = EntityCriteria.of(PullRequest.class);
- criteria.add(ofTarget(target));
-
- if (sourceRepo != null)
- criteria.add(Restrictions.eq("sourceRepo", sourceRepo));
- criteria.add(ofOpen());
- return dao.query(criteria);
- }
-
- @Sessional
- @Override
- public Collection<PullRequest> queryOpenFrom(RepoAndBranch source, @Nullable Repository targetRepo) {
- EntityCriteria<PullRequest> criteria = EntityCriteria.of(PullRequest.class);
- criteria.add(ofSource(source));
-
- if (targetRepo != null)
- criteria.add(Restrictions.eq("targetRepo", targetRepo));
- criteria.add(ofOpen());
- return dao.query(criteria);
- }
-
- @Sessional
- @Override
- public Collection<PullRequest> queryOpen(RepoAndBranch sourceOrTarget) {
- EntityCriteria<PullRequest> criteria = EntityCriteria.of(PullRequest.class);
- criteria.add(ofOpen());
- criteria.add(Restrictions.or(ofSource(sourceOrTarget), ofTarget(sourceOrTarget)));
- return dao.query(criteria);
- }
-
- @Transactional
- @Override
- public void checkSanity() {
- EntityCriteria<PullRequest> criteria = EntityCriteria.of(PullRequest.class);
- criteria.add(ofOpen());
- for (PullRequest request: dao.query(criteria)) {
- Repository sourceRepo = request.getSourceRepo();
- if (sourceRepo == null) {
- discard(request, "Source repository is deleted.");
- } else if (sourceRepo.isValid()) {
- String latestUpdateHead = request.getLatestUpdate().getHeadCommitHash();
-
- // only modifies pull request status if source repository is the repository we
- // previously worked with. This avoids disaster of closing all pull requests
- // if repository storage points to a different location by mistake
- if (sourceRepo.getObjectId(latestUpdateHead, false) != null) {
- String sourceHead = request.getSource().getHead(false);
- if (sourceHead == null)
- discard(request, "Source branch is deleted.");
- else if (!sourceHead.equals(latestUpdateHead))
- onSourceBranchUpdate(request, true);
- }
- }
-
- Repository targetRepo = request.getTargetRepo();
- if (targetRepo.isValid()) {
- String latestUpdateHead = request.getLatestUpdate().getHeadCommitHash();
-
- // only modifies pull request status if target repository is the repository we
- // previously worked with. This avoids disaster of closing all pull requests
- // if repository storage points to a different location by mistake
- if (targetRepo.getObjectId(latestUpdateHead, false) != null) {
- String targetHead = request.getTarget().getHead(false);
- if (targetHead == null)
- discard(request, "Target branch is deleted.");
- else
- onTargetBranchUpdate(request);
- }
- }
- }
- }
-
- @Override
- public void systemStarting() {
- }
-
-}
+package com.pmease.gitplex.core.manager.impl;
+
+import static com.pmease.gitplex.core.model.PullRequest.CriterionHelper.ofOpen;
+import static com.pmease.gitplex.core.model.PullRequest.CriterionHelper.ofSource;
+import static com.pmease.gitplex.core.model.PullRequest.CriterionHelper.ofTarget;
+import static com.pmease.gitplex.core.model.PullRequest.IntegrationStrategy.MERGE_ALWAYS;
+import static com.pmease.gitplex.core.model.PullRequest.IntegrationStrategy.MERGE_IF_NECESSARY;
+import static com.pmease.gitplex.core.model.PullRequest.IntegrationStrategy.MERGE_WITH_SQUASH;
+import static com.pmease.gitplex.core.model.PullRequest.IntegrationStrategy.REBASE_SOURCE_ONTO_TARGET;
+import static com.pmease.gitplex.core.model.PullRequest.IntegrationStrategy.REBASE_TARGET_ONTO_SOURCE;
+import static com.pmease.gitplex.core.model.PullRequest.Status.PENDING_APPROVAL;
+import static com.pmease.gitplex.core.model.PullRequest.Status.PENDING_INTEGRATE;
+import static com.pmease.gitplex.core.model.PullRequest.Status.PENDING_UPDATE;
+
+import java.io.File;
+import java.util.Collection;
+import java.util.Date;
+import java.util.List;
+import java.util.Set;
+
+import javax.annotation.Nullable;
+import javax.inject.Inject;
+import javax.inject.Singleton;
+
+import org.apache.commons.lang3.builder.EqualsBuilder;
+import org.apache.commons.lang3.builder.HashCodeBuilder;
+import org.apache.wicket.request.cycle.RequestCycle;
+import org.eclipse.jetty.util.ConcurrentHashSet;
+import org.eclipse.jgit.lib.ObjectId;
+import org.hibernate.Query;
+import org.hibernate.criterion.Criterion;
+import org.hibernate.criterion.Restrictions;
+import org.joda.time.DateTime;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+import com.google.common.base.Preconditions;
+import com.google.common.collect.Lists;
+import com.pmease.commons.git.Git;
+import com.pmease.commons.git.GitUtils;
+import com.pmease.commons.git.command.MergeCommand.FastForwardMode;
+import com.pmease.commons.hibernate.Sessional;
+import com.pmease.commons.hibernate.Transactional;
+import com.pmease.commons.hibernate.UnitOfWork;
+import com.pmease.commons.hibernate.dao.Dao;
+import com.pmease.commons.hibernate.dao.EntityCriteria;
+import com.pmease.commons.markdown.MarkdownManager;
+import com.pmease.commons.util.FileUtils;
+import com.pmease.commons.util.concurrent.PrioritizedRunnable;
+import com.pmease.gitplex.core.GitPlex;
+import com.pmease.gitplex.core.listeners.LifecycleListener;
+import com.pmease.gitplex.core.listeners.PullRequestListener;
+import com.pmease.gitplex.core.listeners.RefListener;
+import com.pmease.gitplex.core.listeners.RepositoryListener;
+import com.pmease.gitplex.core.manager.CommentManager;
+import com.pmease.gitplex.core.manager.NotificationManager;
+import com.pmease.gitplex.core.manager.PullRequestManager;
+import com.pmease.gitplex.core.manager.PullRequestUpdateManager;
+import com.pmease.gitplex.core.manager.ReviewInvitationManager;
+import com.pmease.gitplex.core.manager.StorageManager;
+import com.pmease.gitplex.core.manager.UserManager;
+import com.pmease.gitplex.core.manager.WorkManager;
+import com.pmease.gitplex.core.model.CloseInfo;
+import com.pmease.gitplex.core.model.Comment;
+import com.pmease.gitplex.core.model.IntegrationPolicy;
+import com.pmease.gitplex.core.model.IntegrationPreview;
+import com.pmease.gitplex.core.model.PullRequest;
+import com.pmease.gitplex.core.model.PullRequest.IntegrationStrategy;
+import com.pmease.gitplex.core.model.PullRequestActivity;
+import com.pmease.gitplex.core.model.PullRequestUpdate;
+import com.pmease.gitplex.core.model.PullRequestVisit;
+import com.pmease.gitplex.core.model.RepoAndBranch;
+import com.pmease.gitplex.core.model.Repository;
+import com.pmease.gitplex.core.model.ReviewInvitation;
+import com.pmease.gitplex.core.model.User;
+
+@Singleton
+public class DefaultPullRequestManager implements PullRequestManager, RepositoryListener, RefListener, LifecycleListener {
+
+ private static final Logger logger = LoggerFactory.getLogger(DefaultPullRequestManager.class);
+
+ private static final int UI_PREVIEW_PRIORITY = 10;
+
+ private static final int BACKEND_PREVIEW_PRIORITY = 50;
+
+ private final Dao dao;
+
+ private final PullRequestUpdateManager pullRequestUpdateManager;
+
+ private final CommentManager commentManager;
+
+ private final UserManager userManager;
+
+ private final StorageManager storageManager;
+
+ private final UnitOfWork unitOfWork;
+
+ private final Set<PullRequestListener> pullRequestListeners;
+
+ private final ReviewInvitationManager reviewInvitationManager;
+
+ private final Set<Long> integrationPreviewCalculatingRequestIds = new ConcurrentHashSet<>();
+
+ private final WorkManager workManager;
+
+ @Inject
+ public DefaultPullRequestManager(Dao dao, PullRequestUpdateManager pullRequestUpdateManager,
+ StorageManager storageManager, ReviewInvitationManager reviewInvitationManager,
+ UserManager userManager, NotificationManager notificationManager,
+ CommentManager commentManager, MarkdownManager markdownManager,
+ WorkManager workManager, UnitOfWork unitOfWork,
+ Set<PullRequestListener> pullRequestListeners) {
+ this.dao = dao;
+ this.pullRequestUpdateManager = pullRequestUpdateManager;
+ this.storageManager = storageManager;
+ this.reviewInvitationManager = reviewInvitationManager;
+ this.commentManager = commentManager;
+ this.userManager = userManager;
+ this.workManager = workManager;
+ this.unitOfWork = unitOfWork;
+ this.pullRequestListeners = pullRequestListeners;
+ }
+
+ @Transactional
+ @Override
+ public void delete(PullRequest request) {
+ deleteRefs(request);
+
+ dao.remove(request);
+ }
+
+ @Sessional
+ @Override
+ public void deleteRefs(PullRequest request) {
+ for (PullRequestUpdate update : request.getUpdates())
+ update.deleteRefs();
+
+ request.deleteRefs();
+ }
+
+ @Transactional
+ @Override
+ public void restoreSourceBranch(PullRequest request) {
+ Preconditions.checkState(!request.isOpen() && request.getSourceRepo() != null);
+
+ if (request.getSource().getHead(false) == null) {
+ String latestCommitHash = request.getLatestUpdate().getHeadCommitHash();
+ request.getSourceRepo().git().createBranch(
+ request.getSourceBranch(), latestCommitHash);
+ request.getSourceRepo().cacheObjectId(request.getSourceBranch(), ObjectId.fromString(latestCommitHash));
+ PullRequestActivity activity = new PullRequestActivity();
+ activity.setRequest(request);
+ activity.setAction(PullRequestActivity.Action.RESTORE_SOURCE_BRANCH);
+ activity.setDate(new Date());
+ activity.setUser(GitPlex.getInstance(UserManager.class).getCurrent());
+ dao.persist(activity);
+ }
+ }
+
+ @Transactional
+ @Override
+ public void deleteSourceBranch(PullRequest request) {
+ Preconditions.checkState(!request.isOpen() && request.getSourceRepo() != null);
+
+ if (request.getSource().getHead(false) != null) {
+ request.getSource().delete();
+
+ PullRequestActivity activity = new PullRequestActivity();
+ activity.setRequest(request);
+ activity.setAction(PullRequestActivity.Action.DELETE_SOURCE_BRANCH);
+ activity.setDate(new Date());
+ activity.setUser(GitPlex.getInstance(UserManager.class).getCurrent());
+ dao.persist(activity);
+ }
+ }
+
+ @Transactional
+ @Override
+ public void reopen(PullRequest request, String comment) {
+ Preconditions.checkState(!request.isOpen());
+
+ User user = userManager.getCurrent();
+ request.setCloseInfo(null);
+ request.setSubmitter(user);
+ request.setSubmitDate(new Date());
+
+ dao.persist(request);
+
+ PullRequestActivity activity = new PullRequestActivity();
+ activity.setRequest(request);
+ activity.setDate(new DateTime(request.getSubmitDate()).minusSeconds(1).toDate());
+ activity.setAction(PullRequestActivity.Action.REOPEN);
+ activity.setUser(user);
+
+ dao.persist(activity);
+
+ if (comment != null) {
+ Comment requestComment = new Comment();
+ requestComment.setContent(comment);
+ requestComment.setRequest(request);
+ requestComment.setUser(user);
+ commentManager.save(requestComment, false);
+ }
+
+ onSourceBranchUpdate(request, false);
+
+ if (request.isOpen()) {
+ for (PullRequestListener listener: pullRequestListeners)
+ listener.onReopened(request, user, comment);
+ }
+ }
+
+ @Transactional
+ @Override
+ public void discard(PullRequest request, final String comment) {
+ User user = userManager.getCurrent();
+ PullRequestActivity activity = new PullRequestActivity();
+ activity.setRequest(request);
+ activity.setDate(new Date());
+ activity.setAction(PullRequestActivity.Action.DISCARD);
+ activity.setUser(user);
+
+ dao.persist(activity);
+
+ if (comment != null) {
+ Comment requestComment = new Comment();
+ requestComment.setContent(comment);
+ requestComment.setRequest(request);
+ requestComment.setUser(user);
+
+ commentManager.save(requestComment, false);
+ }
+
+ CloseInfo closeInfo = new CloseInfo();
+ closeInfo.setCloseDate(activity.getDate());
+ closeInfo.setClosedBy(user);
+ closeInfo.setCloseStatus(CloseInfo.Status.DISCARDED);
+ request.setCloseInfo(closeInfo);
+ request.setLastEventDate(activity.getDate());
+ dao.persist(request);
+
+ for (PullRequestListener listener: pullRequestListeners)
+ listener.onDiscarded(request, user, comment);
+ }
+
+ @Transactional
+ @Override
+ public void integrate(PullRequest request, String comment) {
+ if (request.getStatus() != PENDING_INTEGRATE)
+ throw new IllegalStateException("Gate keeper disallows integration right now.");
+
+ IntegrationPreview preview = request.getIntegrationPreview();
+ if (preview == null)
+ throw new IllegalStateException("Integration preview has not been calculated yet.");
+
+ String integrated = preview.getIntegrated();
+ if (integrated == null)
+ throw new IllegalStateException("There are integration conflicts.");
+
+ User user = userManager.getCurrent();
+
+ Repository targetRepo = request.getTargetRepo();
+ Git git = targetRepo.git();
+ IntegrationStrategy strategy = request.getIntegrationStrategy();
+ if ((strategy == MERGE_ALWAYS || strategy == MERGE_IF_NECESSARY || strategy == MERGE_WITH_SQUASH)
+ && !preview.getIntegrated().equals(preview.getRequestHead()) && comment != null) {
+ File tempDir = FileUtils.createTempDir();
+ try {
+ Git tempGit = new Git(tempDir);
+ tempGit.clone(git.repoDir().getAbsolutePath(), false, true, true, request.getTargetBranch());
+ tempGit.updateRef("HEAD", preview.getIntegrated(), null, null);
+ tempGit.reset(null, null);
+
+ tempGit.commit(comment, false, true);
+ integrated = tempGit.parseRevision("HEAD", true);
+ git.fetch(tempGit, "+HEAD:" + request.getIntegrateRef());
+ comment = null;
+ } finally {
+ FileUtils.deleteDir(tempDir);
+ }
+ }
+ if (strategy == REBASE_SOURCE_ONTO_TARGET || strategy == MERGE_WITH_SQUASH) {
+ Repository sourceRepo = request.getSourceRepo();
+ Git sourceGit = sourceRepo.git();
+ String sourceRef = request.getSourceRef();
+ sourceGit.updateRef(sourceRef, integrated, preview.getRequestHead(),
+ "Pull request #" + request.getId());
+ sourceRepo.cacheObjectId(request.getSourceRef(), ObjectId.fromString(integrated));
+ onRefUpdate(sourceRepo, sourceRef, integrated);
+ }
+
+ String targetRef = request.getTargetRef();
+ git.updateRef(targetRef, integrated, preview.getTargetHead(), "Pull request #" + request.getId());
+ targetRepo.cacheObjectId(request.getTargetRef(), ObjectId.fromString(integrated));
+ onRefUpdate(targetRepo, targetRef, integrated);
+
+ PullRequestActivity activity = new PullRequestActivity();
+ activity.setRequest(request);
+ activity.setDate(new Date());
+ activity.setAction(PullRequestActivity.Action.INTEGRATE);
+ activity.setUser(user);
+
+ dao.persist(activity);
+
+ if (comment != null) {
+ Comment requestComment = new Comment();
+ requestComment.setContent(comment);
+ requestComment.setRequest(request);
+ requestComment.setUser(user);
+ commentManager.save(requestComment, false);
+ }
+
+ CloseInfo closeInfo = new CloseInfo();
+ closeInfo.setCloseDate(activity.getDate());
+ closeInfo.setClosedBy(user);
+ closeInfo.setCloseStatus(CloseInfo.Status.INTEGRATED);
+ request.setCloseInfo(closeInfo);
+
+ request.setLastEventDate(activity.getDate());
+
+ dao.persist(request);
+
+ for (PullRequestListener listener: pullRequestListeners)
+ listener.onIntegrated(request, user, comment);
+ }
+
+ @Transactional
+ @Override
+ public void open(final PullRequest request, final Object listenerData) {
+ dao.persist(request);
+
+ PullRequestActivity activity = new PullRequestActivity();
+ activity.setDate(request.getSubmitDate());
+ activity.setAction(PullRequestActivity.Action.OPEN);
+ activity.setRequest(request);
+ activity.setUser(request.getSubmitter());
+ dao.persist(activity);
+
+ FileUtils.cleanDir(storageManager.getCacheDir(request));
+
+ request.git().updateRef(request.getBaseRef(), request.getBaseCommitHash(), null, null);
+
+ for (PullRequestUpdate update: request.getUpdates()) {
+ update.setDate(new DateTime(activity.getDate()).plusSeconds(1).toDate());
+ pullRequestUpdateManager.save(update, false);
+ }
+
+ for (ReviewInvitation invitation: request.getReviewInvitations())
+ reviewInvitationManager.save(invitation);
+
+ for (PullRequestListener listener: pullRequestListeners)
+ listener.onOpened(request);
+
+ dao.afterCommit(new Runnable() {
+
+ @Override
+ public void run() {
+ IntegrationPreviewTask task = new IntegrationPreviewTask(request.getId());
+ workManager.remove(task);
+ workManager.execute(task);
+ }
+
+ });
+ }
+
+ @Override
+ public List<IntegrationStrategy> getApplicableIntegrationStrategies(PullRequest request) {
+ List<IntegrationStrategy> strategies = null;
+ for (IntegrationPolicy policy: request.getTargetRepo().getIntegrationPolicies()) {
+ if (policy.getTargetBranches().matches(request.getTargetBranch())
+ && policy.getSourceBranches().matches(request.getSourceRepo(), request.getSourceBranch())) {
+ strategies = policy.getIntegrationStrategies();
+ break;
+ }
+ }
+ if (strategies == null)
+ strategies = Lists.newArrayList(IntegrationStrategy.MERGE_ALWAYS);
+ return strategies;
+ }
+
+ @Transactional
+ @Override
+ public void onAssigneeChange(PullRequest request) {
+ dao.persist(request);
+ for (PullRequestListener listener: pullRequestListeners)
+ listener.onAssigned(request);
+ }
+
+ @Transactional
+ @Override
+ public void onTargetBranchUpdate(PullRequest request) {
+ closeIfMerged(request);
+ if (request.isOpen()) {
+ IntegrationPreviewTask task = new IntegrationPreviewTask(request.getId());
+ workManager.remove(task);
+ workManager.execute(task);
+ }
+ }
+
+ @Transactional
+ private void closeIfMerged(PullRequest request) {
+ if (request.getTargetRepo().isAncestor(request.getLatestUpdate().getHeadCommitHash(), request.getTarget().getHead())) {
+ PullRequestActivity activity = new PullRequestActivity();
+ activity.setRequest(request);
+ activity.setUser(GitPlex.getInstance(UserManager.class).getRoot());
+ activity.setAction(PullRequestActivity.Action.INTEGRATE);
+ activity.setDate(new Date());
+ dao.persist(activity);
+
+ request.setLastIntegrationPreview(null);
+ CloseInfo closeInfo = new CloseInfo();
+ closeInfo.setCloseDate(activity.getDate());
+ closeInfo.setClosedBy(activity.getUser());
+ closeInfo.setCloseStatus(CloseInfo.Status.INTEGRATED);
+ request.setCloseInfo(closeInfo);
+ request.setLastEventDate(activity.getDate());
+
+ dao.persist(request);
+
+ for (PullRequestListener listener: pullRequestListeners)
+ listener.onIntegrated(request, null, null);
+ }
+ }
+
+ @Transactional
+ @Override
+ public void onSourceBranchUpdate(PullRequest request, boolean notify) {
+ if (request.getLatestUpdate().getHeadCommitHash().equals(request.getSource().getHead()))
+ return;
+
+ PullRequestUpdate update = new PullRequestUpdate();
+ update.setRequest(request);
+ update.setDate(new Date());
+ update.setHeadCommitHash(request.getSource().getHead());
+
+ request.addUpdate(update);
+ pullRequestUpdateManager.save(update, notify);
+ closeIfMerged(request);
+
+ if (request.isOpen()) {
+ final Long requestId = request.getId();
+ dao.afterCommit(new Runnable() {
+
+ @Override
+ public void run() {
+ unitOfWork.asyncCall(new Runnable() {
+
+ @Override
+ public void run() {
+ check(dao.load(PullRequest.class, requestId));
+ }
+
+ });
+ }
+
+ });
+ }
+ }
+
+ /**
+ * This method might take some time and is not key to pull request logic (even if we
+ * did not call it, we can always call it later), so normally should be called in an
+ * executor
+ */
+ @Transactional
+ @Override
+ public void check(PullRequest request) {
+ Date now = new Date();
+ if (request.isOpen()) {
+ closeIfMerged(request);
+ if (request.isOpen()) {
+ if (request.getStatus() == PENDING_UPDATE) {
+ for (PullRequestListener listener: pullRequestListeners)
+ listener.pendingUpdate(request);
+ } else if (request.getStatus() == PENDING_INTEGRATE) {
+ for (PullRequestListener listener: pullRequestListeners)
+ listener.pendingIntegration(request);
+
+ IntegrationPreview integrationPreview = request.getIntegrationPreview();
+ if (integrationPreview != null
+ && integrationPreview.getIntegrated() != null
+ && request.getAssignee() == null) {
+ integrate(request, "Integrated automatically by system");
+ }
+ } else if (request.getStatus() == PENDING_APPROVAL) {
+ for (PullRequestListener listener: pullRequestListeners)
+ listener.pendingApproval(request);
+
+ for (ReviewInvitation invitation: request.getReviewInvitations()) {
+ if (!invitation.getDate().before(now))
+ reviewInvitationManager.save(invitation);
+ }
+ }
+ }
+ }
+ }
+
+ @Override
+ public boolean canIntegrate(PullRequest request) {
+ if (request.getStatus() != PENDING_INTEGRATE) {
+ return false;
+ } else {
+ IntegrationPreview integrationPreview = request.getIntegrationPreview();
+ return integrationPreview != null && integrationPreview.getIntegrated() != null;
+ }
+ }
+
+ @Override
+ public IntegrationPreview previewIntegration(PullRequest request) {
+ IntegrationPreview preview = request.getLastIntegrationPreview();
+ if (request.isOpen() && (preview == null || preview.isObsolete(request))) {
+ IntegrationPreviewTask task = new IntegrationPreviewTask(request.getId());
+ workManager.remove(task);
+ workManager.execute(task);
+ return null;
+ } else {
+ return preview;
+ }
+ }
+
+ private class IntegrationPreviewTask extends PrioritizedRunnable {
+
+ private final Long requestId;
+
+ public IntegrationPreviewTask(Long requestId) {
+ super(RequestCycle.get() != null?UI_PREVIEW_PRIORITY:BACKEND_PREVIEW_PRIORITY);
+ this.requestId = requestId;
+ }
+
+ @Override
+ public void run() {
+ unitOfWork.begin();
+ try {
+ if (!integrationPreviewCalculatingRequestIds.contains(requestId)) {
+ integrationPreviewCalculatingRequestIds.add(requestId);
+ logger.info("Calculating integration preview of pull request #{}...", requestId);
+ try {
+ PullRequest request = dao.load(PullRequest.class, requestId);
+ IntegrationPreview preview = request.getLastIntegrationPreview();
+ if (request.isOpen() && (preview == null || preview.isObsolete(request))) {
+ String requestHead = request.getLatestUpdate().getHeadCommitHash();
+ String targetHead = request.getTarget().getHead();
+ Repository targetRepo = request.getTargetRepo();
+ Git git = request.getTargetRepo().git();
+ preview = new IntegrationPreview(targetHead,
+ request.getLatestUpdate().getHeadCommitHash(), request.getIntegrationStrategy(), null);
+ request.setLastIntegrationPreview(preview);
+ String integrateRef = request.getIntegrateRef();
+ if (preview.getIntegrationStrategy() == MERGE_IF_NECESSARY && targetRepo.isAncestor(targetHead, requestHead)
+ || preview.getIntegrationStrategy() == MERGE_WITH_SQUASH && targetRepo.isAncestor(targetHead, requestHead)
+ && git.log(targetHead, requestHead, null, 0, 0, false).size() == 1) {
+ preview.setIntegrated(requestHead);
+ git.updateRef(integrateRef, requestHead, null, null);
+ } else {
+ File tempDir = FileUtils.createTempDir();
+ try {
+ Git tempGit = new Git(tempDir);
+ tempGit.clone(git.repoDir().getAbsolutePath(), false, true, true,
+ request.getTargetBranch());
+
+ String integrated;
+
+ if (preview.getIntegrationStrategy() == REBASE_TARGET_ONTO_SOURCE) {
+ tempGit.updateRef("HEAD", requestHead, null, null);
+ tempGit.reset(null, null);
+ List<String> cherries = tempGit.listCherries("HEAD", targetHead);
+ integrated = tempGit.cherryPick(cherries.toArray(new String[cherries.size()]));
+ } else {
+ tempGit.updateRef("HEAD", targetHead, null, null);
+ tempGit.reset(null, null);
+ if (preview.getIntegrationStrategy() == REBASE_SOURCE_ONTO_TARGET) {
+ List<String> cherries = tempGit.listCherries("HEAD", requestHead);
+ integrated = tempGit.cherryPick(cherries.toArray(new String[cherries.size()]));
+ } else if (preview.getIntegrationStrategy() == MERGE_WITH_SQUASH) {
+ String commitMessage = request.getTitle() + "\n\n";
+ if (request.getDescription() != null)
+ commitMessage += request.getDescription() + "\n\n";
+ commitMessage += "(squashed commit of pull request #" + request.getId() + ")\n";
+ integrated = tempGit.squash(requestHead, null, null, commitMessage);
+ } else {
+ FastForwardMode fastForwardMode;
+ if (preview.getIntegrationStrategy() == MERGE_ALWAYS)
+ fastForwardMode = FastForwardMode.NO_FF;
+ else
+ fastForwardMode = FastForwardMode.FF;
+ String commitMessage = "Merge pull request #" + request.getId()
+ + "\n\n" + request.getTitle() + "\n";
+ integrated = tempGit.merge(requestHead, fastForwardMode, null, null, commitMessage);
+ }
+ }
+
+ if (integrated != null) {
+ preview.setIntegrated(integrated);
+ git.fetch(tempGit, "+HEAD:" + integrateRef);
+ } else {
+ git.deleteRef(integrateRef, null, null);
+ }
+ } finally {
+ FileUtils.deleteDir(tempDir);
+ }
+ }
+ dao.persist(request);
+
+ if (request.getStatus() == PENDING_INTEGRATE
+ && preview.getIntegrated() != null
+ && request.getAssignee() == null) {
+ integrate(request, "Integrated automatically by system");
+ }
+
+ for (PullRequestListener listener: pullRequestListeners)
+ listener.onIntegrationPreviewCalculated(request);
+ }
+ } finally {
+ integrationPreviewCalculatingRequestIds.remove(requestId);
+ logger.info("Integration preview of pull request #{} is calculated.", requestId);
+ }
+ }
+ } catch (Exception e) {
+ logger.error("Error calculating integration preview of pull request #" + requestId, e);
+ } finally {
+ unitOfWork.end();
+ }
+ }
+
+ @Override
+ public boolean equals(Object other) {
+ if (!(other instanceof IntegrationPreviewTask))
+ return false;
+ if (this == other)
+ return true;
+ IntegrationPreviewTask otherRunnable = (IntegrationPreviewTask) other;
+ return new EqualsBuilder().append(requestId, otherRunnable.requestId).isEquals();
+ }
+
+ @Override
+ public int hashCode() {
+ return new HashCodeBuilder(17, 37).append(requestId).toHashCode();
+ }
+
+ }
+
+ @Override
+ public Date getLastVisitDate(PullRequest request) {
+ User user = userManager.getCurrent();
+ if (user != null) {
+ PullRequestVisit visit = request.getVisit(user);
+ if (visit != null)
+ return visit.getDate();
+ else
+ return null;
+ } else {
+ return null;
+ }
+ }
+
+ @Override
+ public void systemStarted() {
+ logger.info("Checking pull requests...");
+
+ checkSanity();
+ }
+
+ @Override
+ public void systemStopping() {
+ }
+
+ @Override
+ public void systemStopped() {
+ }
+
+ @Transactional
+ @Override
+ public void beforeDelete(Repository repository) {
+ for (PullRequest request: repository.getOutgoingRequests()) {
+ if (!request.getTargetRepo().equals(repository) && request.isOpen())
+ discard(request, "Source repository is deleted.");
+ }
+
+ Query query = dao.getSession().createQuery("update PullRequest set sourceRepo=null where "
+ + "sourceRepo = :repo and targetRepo != :repo");
+ query.setParameter("repo", repository);
+ query.executeUpdate();
+ }
+
+ @Override
+ public void afterDelete(Repository repository) {
+ }
+
+ @Transactional
+ @Override
+ public void onRefUpdate(Repository repository, String refName, @Nullable String newCommitHash) {
+ final String branch = GitUtils.ref2branch(refName);
+ if (branch != null) {
+ RepoAndBranch repoAndBranch = new RepoAndBranch(repository, branch);
+ if (newCommitHash != null) {
+ /**
+ * Source branch update is key to the logic as it has to create
+ * pull request update, so we should not postpone it to be executed
+ * in a executor service like target branch update below
+ */
+ Criterion criterion = Restrictions.and(ofOpen(), ofSource(repoAndBranch));
+ for (PullRequest request: dao.query(EntityCriteria.of(PullRequest.class).add(criterion)))
+ onSourceBranchUpdate(request, true);
+
+ final Long repoId = repository.getId();
+ dao.afterCommit(new Runnable() {
+
+ @Override
+ public void run() {
+ unitOfWork.asyncCall(new Runnable() {
+
+ @Override
+ public void run() {
+ RepoAndBranch repoAndBranch = new RepoAndBranch(repoId, branch);
+ Criterion criterion = Restrictions.and(ofOpen(), ofTarget(repoAndBranch));
+ for (PullRequest request: dao.query(EntityCriteria.of(PullRequest.class).add(criterion)))
+ onTargetBranchUpdate(request);
+ }
+
+ });
+ }
+
+ });
+ } else {
+ Criterion criterion = Restrictions.and(
+ ofOpen(),
+ Restrictions.or(ofSource(repoAndBranch), ofTarget(repoAndBranch)));
+ for (PullRequest request: dao.query(EntityCriteria.of(PullRequest.class).add(criterion))) {
+ if (request.getTargetRepo().equals(repository) && request.getTargetBranch().equals(branch))
+ discard(request, "Target branch is deleted.");
+ else
+ discard(request, "Source branch is deleted.");
+ }
+ }
+ }
+ }
+
+ @Sessional
+ @Override
+ public PullRequest findOpen(RepoAndBranch target, RepoAndBranch source) {
+ return dao.find(EntityCriteria.of(PullRequest.class)
+ .add(ofTarget(target)).add(ofSource(source)).add(ofOpen()));
+ }
+
+ @Sessional
+ @Override
+ public Collection<PullRequest> queryOpenTo(RepoAndBranch target, @Nullable Repository sourceRepo) {
+ EntityCriteria<PullRequest> criteria = EntityCriteria.of(PullRequest.class);
+ criteria.add(ofTarget(target));
+
+ if (sourceRepo != null)
+ criteria.add(Restrictions.eq("sourceRepo", sourceRepo));
+ criteria.add(ofOpen());
+ return dao.query(criteria);
+ }
+
+ @Sessional
+ @Override
+ public Collection<PullRequest> queryOpenFrom(RepoAndBranch source, @Nullable Repository targetRepo) {
+ EntityCriteria<PullRequest> criteria = EntityCriteria.of(PullRequest.class);
+ criteria.add(ofSource(source));
+
+ if (targetRepo != null)
+ criteria.add(Restrictions.eq("targetRepo", targetRepo));
+ criteria.add(ofOpen());
+ return dao.query(criteria);
+ }
+
+ @Sessional
+ @Override
+ public Collection<PullRequest> queryOpen(RepoAndBranch sourceOrTarget) {
+ EntityCriteria<PullRequest> criteria = EntityCriteria.of(PullRequest.class);
+ criteria.add(ofOpen());
+ criteria.add(Restrictions.or(ofSource(sourceOrTarget), ofTarget(sourceOrTarget)));
+ return dao.query(criteria);
+ }
+
+ @Transactional
+ @Override
+ public void checkSanity() {
+ EntityCriteria<PullRequest> criteria = EntityCriteria.of(PullRequest.class);
+ criteria.add(ofOpen());
+ for (PullRequest request: dao.query(criteria)) {
+ Repository sourceRepo = request.getSourceRepo();
+ if (sourceRepo == null) {
+ discard(request, "Source repository is deleted.");
+ } else if (sourceRepo.isValid()) {
+ String latestUpdateHead = request.getLatestUpdate().getHeadCommitHash();
+
+ // only modifies pull request status if source repository is the repository we
+ // previously worked with. This avoids disaster of closing all pull requests
+ // if repository storage points to a different location by mistake
+ if (sourceRepo.getObjectId(latestUpdateHead, false) != null) {
+ String sourceHead = request.getSource().getHead(false);
+ if (sourceHead == null)
+ discard(request, "Source branch is deleted.");
+ else if (!sourceHead.equals(latestUpdateHead))
+ onSourceBranchUpdate(request, true);
+ }
+ }
+
+ Repository targetRepo = request.getTargetRepo();
+ if (targetRepo.isValid()) {
+ String latestUpdateHead = request.getLatestUpdate().getHeadCommitHash();
+
+ // only modifies pull request status if target repository is the repository we
+ // previously worked with. This avoids disaster of closing all pull requests
+ // if repository storage points to a different location by mistake
+ if (targetRepo.getObjectId(latestUpdateHead, false) != null) {
+ String targetHead = request.getTarget().getHead(false);
+ if (targetHead == null)
+ discard(request, "Target branch is deleted.");
+ else
+ onTargetBranchUpdate(request);
+ }
+ }
+ }
+ }
+
+ @Override
+ public void systemStarting() {
+ }
+
+}
diff --git a/gitplex.core/src/main/java/com/pmease/gitplex/core/model/PullRequest.java b/gitplex.core/src/main/java/com/pmease/gitplex/core/model/PullRequest.java
index 8856614dd9..c75ed69063 100644
--- a/gitplex.core/src/main/java/com/pmease/gitplex/core/model/PullRequest.java
+++ b/gitplex.core/src/main/java/com/pmease/gitplex/core/model/PullRequest.java
@@ -1,979 +1,978 @@
-package com.pmease.gitplex.core.model;
-
-import java.util.ArrayList;
-import java.util.Collection;
-import java.util.Collections;
-import java.util.Comparator;
-import java.util.Date;
-import java.util.HashMap;
-import java.util.HashSet;
-import java.util.List;
-import java.util.Map;
-import java.util.Set;
-import java.util.concurrent.Callable;
-
-import javax.annotation.Nullable;
-import javax.persistence.Column;
-import javax.persistence.Embedded;
-import javax.persistence.Entity;
-import javax.persistence.FetchType;
-import javax.persistence.JoinColumn;
-import javax.persistence.Lob;
-import javax.persistence.ManyToOne;
-import javax.persistence.OneToMany;
-import javax.persistence.PrePersist;
-import javax.persistence.Transient;
-import javax.persistence.Version;
-
-import org.apache.commons.lang3.StringUtils;
-import org.hibernate.annotations.DynamicUpdate;
-import org.hibernate.annotations.Index;
-import org.hibernate.annotations.OnDelete;
-import org.hibernate.annotations.OnDeleteAction;
-import org.hibernate.annotations.OptimisticLock;
-import org.hibernate.criterion.Criterion;
-import org.hibernate.criterion.Restrictions;
-
-import com.fasterxml.jackson.annotation.JsonView;
-import com.google.common.base.Preconditions;
-import com.pmease.commons.git.Commit;
-import com.pmease.commons.git.Git;
-import com.pmease.commons.git.GitUtils;
-import com.pmease.commons.hibernate.AbstractEntity;
-import com.pmease.commons.hibernate.dao.Dao;
-import com.pmease.commons.hibernate.dao.EntityCriteria;
-import com.pmease.commons.jackson.ExternalView;
-import com.pmease.commons.util.LockUtils;
-import com.pmease.gitplex.core.GitPlex;
-import com.pmease.gitplex.core.gatekeeper.checkresult.Blocking;
-import com.pmease.gitplex.core.gatekeeper.checkresult.CheckResult;
-import com.pmease.gitplex.core.gatekeeper.checkresult.Failed;
-import com.pmease.gitplex.core.gatekeeper.checkresult.Pending;
-import com.pmease.gitplex.core.manager.PullRequestManager;
-import com.pmease.gitplex.core.manager.ReviewManager;
-import com.pmease.gitplex.core.permission.ObjectPermission;
-
-/*
- * @DynamicUpdate annotation here along with various @OptimisticLock annotations
- * on certain fields tell Hibernate not to perform version check on those fields
- * which can be updated from background thread.
- */
-@SuppressWarnings("serial")
-@Entity
-@DynamicUpdate
-public class PullRequest extends AbstractEntity {
-
- public enum Status {
- PENDING_APPROVAL("Pending Approval"),
- PENDING_UPDATE("Pending Update"), PENDING_INTEGRATE("Pending Integration"),
- INTEGRATED("Integrated"), DISCARDED("Discarded");
-
- private final String displayName;
-
- Status(String displayName) {
- this.displayName = displayName;
- }
-
- @Override
- public String toString() {
- return displayName;
- }
-
- }
-
- public enum IntegrationStrategy {
- MERGE_ALWAYS("Merge always",
- "Always create merge commit when integrate into target branch"),
- MERGE_IF_NECESSARY("Merge if necessary",
- "Create merge commit only if target branch can not be fast-forwarded to the pull request"),
- MERGE_WITH_SQUASH("Merge with squash",
- "Squash all commits in the pull request and then merge with target branch"),
- REBASE_SOURCE_ONTO_TARGET("Rebase source onto target",
- "Rebase source branch onto target branch and then fast-forward target branch to source branch"),
- REBASE_TARGET_ONTO_SOURCE("Rebase target onto source",
- "Rebase target branch onto source branch");
-
- private final String displayName;
-
- private final String description;
-
- IntegrationStrategy(String displayName, String description) {
- this.displayName = displayName;
- this.description = description;
- }
-
- public String getDisplayName() {
- return displayName;
- }
-
- public String getDescription() {
- return description;
- }
-
- @Override
- public String toString() {
- return displayName;
- }
-
- }
-
- public enum Event {
- OPENED("Newly opened"),
- REVIEWED("New reviews in"),
- VERIFIED("Build verification is finished for"),
- UPDATED("New commits in"),
- COMMENTED("New comments in"),
- INTEGRATION_STRATEGY_CHANGED("Integration strategy is changed"),
- INTEGRATED("Integration is done for"),
- DISCARDED("Discarded"),
- REOPENED("Reopened"),
- INTEGRATION_PREVIEW_CALCULATED("Integration preview is calculated"),
- ASSIGNED("Assigned"),
- REVIEWER_CHANGED("Reviewer changed"),
- REVIEW_REMOVED("Review removed"),
- COMMENT_REPLIED("Comment is replied");
-
- private final String displayName;
-
- Event(String displayName) {
- this.displayName = displayName;
- }
-
- public String toString() {
- return displayName;
- }
-
- };
-
- @Embedded
- private CloseInfo closeInfo;
-
- @Index(name="PR_TITLE")
- @Column(nullable=false)
- private String title;
-
- @Lob
- @Column(length=65535)
- private String description;
-
- @ManyToOne(fetch=FetchType.LAZY)
- private User submitter;
-
- @ManyToOne(fetch=FetchType.LAZY)
- @JoinColumn(nullable=false)
- private Repository targetRepo;
-
- @Column(nullable=false)
- private String targetBranch;
-
- @ManyToOne(fetch=FetchType.LAZY)
- private Repository sourceRepo;
-
- @Column(nullable=false)
- private String sourceBranch;
-
- @Column(nullable=false)
- private String baseCommitHash;
-
- @ManyToOne(fetch=FetchType.LAZY)
- private User assignee;
-
- // used for id search in markdown editor
- @Index(name="PR_ID_STR")
- @Column(nullable=false)
- private String idStr;
-
- // used for title search in markdown editor
- @Index(name="PR_NO_SP_TITLE")
- @Column(nullable=false)
- private String noSpaceTitle;
-
- @Version
- private long version;
-
- @Transient
- private Git sandbox;
-
- @OptimisticLock(excluded=true)
- @Embedded
- private IntegrationPreview lastIntegrationPreview;
-
- @Column(nullable=false)
- private Date submitDate = new Date();
-
- @OptimisticLock(excluded=true)
- @Column(nullable=false)
- private Date lastEventDate = new Date();
-
- @OptimisticLock(excluded=true)
- @Column(nullable=false)
- private Event lastEvent = Event.OPENED;
-
- @Column(nullable=false)
- private IntegrationStrategy integrationStrategy;
-
- @OneToMany(mappedBy="request")
- @OnDelete(action=OnDeleteAction.CASCADE)
- private Collection<PullRequestUpdate> updates = new ArrayList<>();
-
- @OneToMany(mappedBy="request")
- @OnDelete(action=OnDeleteAction.CASCADE)
- private Collection<ReviewInvitation> reviewInvitations = new ArrayList<>();
-
- @OneToMany(mappedBy="referenced")
- @OnDelete(action=OnDeleteAction.CASCADE)
- private Collection<PullRequestReference> referencedBy = new ArrayList<>();
-
- @OneToMany(mappedBy="referencedBy")
- @OnDelete(action=OnDeleteAction.CASCADE)
- private Collection<PullRequestReference> referenced = new ArrayList<>();
-
- @OneToMany(mappedBy="request")
- @OnDelete(action=OnDeleteAction.CASCADE)
- private Collection<Verification> verifications = new ArrayList<>();
-
- @OneToMany(mappedBy="request")
- @OnDelete(action=OnDeleteAction.CASCADE)
- private Collection<Comment> comments = new ArrayList<>();
-
- @OneToMany(mappedBy="request")
- @OnDelete(action=OnDeleteAction.CASCADE)
- private Collection<PullRequestActivity> activities = new ArrayList<>();
-
- @OneToMany(mappedBy="request")
- @OnDelete(action=OnDeleteAction.CASCADE)
- private Collection<Notification> notifications = new ArrayList<>();
-
- @OneToMany(mappedBy="request")
- @OnDelete(action=OnDeleteAction.CASCADE)
- private Collection<PullRequestVisit> visits = new ArrayList<>();
-
- @OneToMany(mappedBy="request")
- @OnDelete(action=OnDeleteAction.CASCADE)
- private Collection<PullRequestWatch> watches = new ArrayList<>();
-
- private transient CheckResult checkResult;
-
- private transient List<PullRequestUpdate> sortedUpdates;
-
- private transient List<PullRequestUpdate> effectiveUpdates;
-
- private transient PullRequestUpdate referentialUpdate;
-
- private transient Set<String> pendingCommits;
-
- private transient Collection<Commit> mergedCommits;
-
- private transient Collection<CommentReply> commentReplies;
-
- private transient List<Review> reviews;
-
- /**
- * Get title of this merge request.
- *
- * @return user specified title of this merge request, <tt>null</tt> for
- * auto-created merge request.
- */
- public @Nullable String getTitle() {
- return title;
- }
-
- public void setTitle(String title) {
- this.title = title;
- noSpaceTitle = StringUtils.deleteWhitespace(title);
- }
-
- public String getDescription() {
- return description;
- }
-
- public void setDescription(String description) {
- this.description = description;
- }
-
- /**
- * Get the user submitting the pull request.
- *
- * @return
- * the user submitting the pull request, or <tt>null</tt> if unknown
- */
- @Nullable
- public User getSubmitter() {
- return submitter;
- }
-
- public void setSubmitter(@Nullable User submitter) {
- this.submitter = submitter;
- }
-
- /**
- * Get the user responsible for integration of the pull request.
- *
- * @return
- * the user responsible for integration of this pull request, or <tt>null</tt> to have the
- * system integrate the pull request automatically
- */
- @Nullable
- public User getAssignee() {
- return assignee;
- }
-
- public void setAssignee(User assignee) {
- this.assignee = assignee;
- }
-
- public Repository getTargetRepo() {
- return targetRepo;
- }
-
- public RepoAndBranch getTarget() {
- return new RepoAndBranch(getTargetRepo(), getTargetBranch());
- }
-
- public void setTarget(RepoAndBranch target) {
- setTargetRepo(target.getRepository());
- setTargetBranch(target.getBranch());
- }
-
- public void setSource(RepoAndBranch source) {
- setSourceRepo(source.getRepository());
- setSourceBranch(source.getBranch());
- }
-
- public void setTargetRepo(Repository targetRepo) {
- this.targetRepo = targetRepo;
- }
-
- public String getTargetBranch() {
- return targetBranch;
- }
-
- public void setTargetBranch(String targetBranch) {
- this.targetBranch = targetBranch;
- }
-
- @Nullable
- public Repository getSourceRepo() {
- return sourceRepo;
- }
-
- public void setSourceRepo(Repository sourceRepo) {
- this.sourceRepo = sourceRepo;
- }
-
- public String getSourceBranch() {
- return sourceBranch;
- }
-
- public void setSourceBranch(String sourceBranch) {
- this.sourceBranch = sourceBranch;
- }
-
- public RepoAndBranch getSource() {
- return new RepoAndBranch(getSourceRepo(), getSourceBranch());
- }
-
- public String getTargetRef() {
- return GitUtils.branch2ref(getTargetBranch());
- }
-
- public String getSourceRef() {
- return GitUtils.branch2ref(getSourceBranch());
- }
-
- public String getBaseCommitHash() {
- return baseCommitHash;
- }
-
- public void setBaseCommitHash(String baseCommitHash) {
- this.baseCommitHash = baseCommitHash;
- }
-
- public Commit getBaseCommit() {
- return getTargetRepo().getCommit(getBaseCommitHash());
- }
-
- public Git git() {
- if (sandbox == null)
- return getTargetRepo().git();
- else
- return sandbox;
- }
-
- public Git getSandbox() {
- return sandbox;
- }
-
- public void setSandbox(Git sandbox) {
- this.sandbox = sandbox;
- }
-
- /**
- * Get unmodifiable collection of updates of this pull request. To add update
- * to the pull request, call {@link this#addUpdate(PullRequestUpdate)} instead.
- *
- * @return
- * unmodifiable collection of updates
- */
- public Collection<PullRequestUpdate> getUpdates() {
- return Collections.unmodifiableCollection(updates);
- }
-
- public void setUpdates(Collection<PullRequestUpdate> updates) {
- this.updates = updates;
- sortedUpdates = null;
- effectiveUpdates = null;
- }
-
- public void addUpdate(PullRequestUpdate update) {
- updates.add(update);
- sortedUpdates = null;
- effectiveUpdates = null;
- }
-
- public Collection<ReviewInvitation> getReviewInvitations() {
- return reviewInvitations;
- }
-
- public void setReviewInvitations(Collection<ReviewInvitation> reviewInvitations) {
- this.reviewInvitations = reviewInvitations;
- }
-
- public Collection<Verification> getVerifications() {
- return verifications;
- }
-
- public void setVerifications(Collection<Verification> verifications) {
- this.verifications = verifications;
- }
-
- public Collection<PullRequestReference> getReferencedBy() {
- return referencedBy;
- }
-
- public void setReferencedBy(Collection<PullRequestReference> referencedBy) {
- this.referencedBy = referencedBy;
- }
-
- public Collection<PullRequestReference> getReferenced() {
- return referenced;
- }
-
- public void setReferenced(Collection<PullRequestReference> referenced) {
- this.referenced = referenced;
- }
-
- public Collection<Comment> getComments() {
- return comments;
- }
-
- public void setComments(Collection<Comment> comments) {
- this.comments = comments;
- }
-
- public Collection<PullRequestActivity> getActivities() {
- return activities;
- }
-
- public void setActivities(Collection<PullRequestActivity> activities) {
- this.activities = activities;
- }
-
- public Collection<Notification> getNotifications() {
- return notifications;
- }
-
- public void setNotifications(Collection<Notification> notifications) {
- this.notifications = notifications;
- }
-
- public Collection<PullRequestVisit> getVisits() {
- return visits;
- }
-
- public void setVisits(Collection<PullRequestVisit> visits) {
- this.visits = visits;
- }
-
- public Collection<PullRequestWatch> getWatches() {
- return watches;
- }
-
- public void setWatches(Collection<PullRequestWatch> watches) {
- this.watches = watches;
- }
-
- public Status getStatus() {
- if (closeInfo != null) {
- if (closeInfo.getCloseStatus() == CloseInfo.Status.INTEGRATED)
- return Status.INTEGRATED;
- else
- return Status.DISCARDED;
- } else if (getCheckResult() instanceof Pending || getCheckResult() instanceof Blocking)
- return Status.PENDING_APPROVAL;
- else if (getCheckResult() instanceof Failed)
- return Status.PENDING_UPDATE;
- else
- return Status.PENDING_INTEGRATE;
- }
-
- @Nullable
- public CloseInfo getCloseInfo() {
- return closeInfo;
- }
-
- public void setCloseInfo(CloseInfo closeInfo) {
- this.closeInfo = closeInfo;
- }
-
- public boolean isOpen() {
- return closeInfo == null;
- }
-
- public PullRequestUpdate getReferentialUpdate() {
- if (referentialUpdate != null)
- return referentialUpdate;
- else
- return getEffectiveUpdates().get(0);
- }
-
- public void setReferentialUpdate(PullRequestUpdate referentiralUpdate) {
- this.referentialUpdate = referentiralUpdate;
- }
-
- /**
- * Get gate keeper check result.
- *
- * @return
- * check result of this pull request has not been refreshed yet
- */
- public CheckResult getCheckResult() {
- if (checkResult == null)
- checkResult = getTargetRepo().getGateKeeper().checkRequest(this);
- return checkResult;
- }
-
- /**
- * Get last integration preview of this pull request. Note that this method may return an
- * out dated integration preview. Refer to {@link this#getIntegrationPreview()}
- * if you'd like to get an update-to-date integration preview
- *
- * @return
- * integration preview of this pull request, or <tt>null</tt> if integration
- * preview has not been calculated yet.
- */
- @Nullable
- public IntegrationPreview getLastIntegrationPreview() {
- return lastIntegrationPreview;
- }
-
- public void setLastIntegrationPreview(IntegrationPreview lastIntegrationPreview) {
- this.lastIntegrationPreview = lastIntegrationPreview;
- }
-
- /**
- * Get effective integration preview of this pull request.
- *
- * @return
- * update to date integration preview of this pull request, or <tt>null</tt> if
- * the integration preview has not been calculated or out dated. In both cases,
- * it will trigger a re-calculation, and client should call this method later
- * to get the calculated result
- */
- @JsonView(ExternalView.class)
- @Nullable
- public IntegrationPreview getIntegrationPreview() {
- return GitPlex.getInstance(PullRequestManager.class).previewIntegration(this);
- }
-
- /**
- * Get list of sorted updates.
- *
- * @return
- * list of sorted updates ordered by id
- */
- public List<PullRequestUpdate> getSortedUpdates() {
- if (sortedUpdates == null) {
- Preconditions.checkState(updates.size() >= 1);
- sortedUpdates = new ArrayList<PullRequestUpdate>(updates);
- Collections.sort(sortedUpdates);
- }
- return sortedUpdates;
- }
-
- /**
- * Get list of effective updates reversely sorted by id. Update is considered effective if it is
- * not ancestor of target branch head.
- *
- * @return
- * list of effective updates reversely sorted by id
- */
- public List<PullRequestUpdate> getEffectiveUpdates() {
- Preconditions.checkState(isOpen(), "Can only be called while request is open");
- if (effectiveUpdates == null) {
- effectiveUpdates = new ArrayList<PullRequestUpdate>();
-
- Git git = getTargetRepo().git();
- for (int i=getSortedUpdates().size()-1; i>=0; i--) {
- PullRequestUpdate update = getSortedUpdates().get(i);
- if (!git.isAncestor(update.getHeadCommitHash(), getTarget().getHead()))
- effectiveUpdates.add(update);
- else
- break;
- }
-
- Preconditions.checkState(!effectiveUpdates.isEmpty());
- }
- return effectiveUpdates;
- }
-
- public IntegrationStrategy getIntegrationStrategy() {
- return integrationStrategy;
- }
-
- public void setIntegrationStrategy(IntegrationStrategy integrationStrategy) {
- this.integrationStrategy = integrationStrategy;
- }
-
- @JsonView(ExternalView.class)
- public PullRequestUpdate getLatestUpdate() {
- return getSortedUpdates().get(getSortedUpdates().size()-1);
- }
-
- public Collection<String> findTouchedFiles() {
- Git git = getTargetRepo().git();
- return git.listChangedFiles(getTarget().getHead(), getLatestUpdate().getHeadCommitHash(), null);
- }
-
- @JsonView(ExternalView.class)
- public String getBaseRef() {
- Preconditions.checkNotNull(getId());
- return Repository.REFS_GITPLEX + "pulls/" + getId() + "/base";
- }
-
- @JsonView(ExternalView.class)
- public String getIntegrateRef() {
- Preconditions.checkNotNull(getId());
- return Repository.REFS_GITPLEX + "pulls/" + getId() + "/integrate";
- }
-
- /**
- * Delete refs of this pull request, without touching refs of its updates.
- */
- public void deleteRefs() {
- Git git = getTargetRepo().git();
- git.deleteRef(getBaseRef(), null, null);
- git.deleteRef(getIntegrateRef(), null, null);
- }
-
- public <T> T lockAndCall(Callable<T> callable) {
- Preconditions.checkNotNull(getId());
-
- return LockUtils.call("pull request: " + getId(), callable);
- }
-
- /**
- * Invite specified number of users in candidates to review this request.
- * <p>
- *
- * @param candidates
- * a collection of users to invite users from
- * @param count
- * number of users to invite
- */
- public void pickReviewers(Collection<User> candidates, int count) {
- List<User> pickList = new ArrayList<User>(candidates);
-
- /*
- * users already reviewed since base update should be excluded from
- * invitation list as their reviews are still valid
- */
- for (Review review: getReferentialUpdate().listReviewsOnwards())
- pickList.remove(review.getReviewer());
-
- final Map<User, Date> firstChoices = new HashMap<>();
- final Map<User, Date> secondChoices = new HashMap<>();
-
- for (ReviewInvitation invitation: getReviewInvitations()) {
- if (invitation.isPreferred())
- firstChoices.put(invitation.getReviewer(), invitation.getDate());
- else
- secondChoices.put(invitation.getReviewer(), invitation.getDate());
- }
-
- // submitter is not preferred
- if (getSubmitter() != null)
- secondChoices.put(getSubmitter(), new Date());
-
- /* Follow below rules to pick reviewers:
- * 1. If user is excluded previously, it will be considered last.
- * 2. If user is already a reviewer, it will be considered first.
- * 3. Otherwise pick user with least reviews.
- */
- Collections.sort(pickList, new Comparator<User>() {
-
- @Override
- public int compare(User user1, User user2) {
- if (firstChoices.containsKey(user1)) {
- if (firstChoices.containsKey(user2))
- return user1.getReviewEffort() - user2.getReviewEffort();
- else
- return -1;
- } else if (firstChoices.containsKey(user2)) {
- return 1;
- } else if (secondChoices.containsKey(user1)) {
- if (secondChoices.containsKey(user2))
- return secondChoices.get(user1).compareTo(secondChoices.get(user2));
- else
- return 1;
- } else if (secondChoices.containsKey(user2)) {
- return -1;
- } else {
- return user1.getReviewEffort() - user2.getReviewEffort();
- }
- }
-
- });
-
- List<User> picked;
- if (count <= pickList.size())
- picked = pickList.subList(0, count);
- else
- picked = pickList;
-
- for (User user: picked) {
- boolean found = false;
- for (ReviewInvitation invitation: getReviewInvitations()) {
- if (invitation.getReviewer().equals(user)) {
- invitation.setDate(new Date());
- invitation.setPerferred(true);
- found = true;
- }
- }
- if (!found) {
- ReviewInvitation invitation = new ReviewInvitation();
- invitation.setRequest(this);
- invitation.setReviewer(user);
- getReviewInvitations().add(invitation);
- }
- }
-
- }
-
- public static class CriterionHelper {
- public static Criterion ofOpen() {
- return Restrictions.isNull("closeInfo");
- }
-
- public static Criterion ofClosed() {
- return Restrictions.isNotNull("closeInfo");
- }
-
- public static Criterion ofTarget(RepoAndBranch target) {
- return Restrictions.and(
- Restrictions.eq("targetRepo", target.getRepository()),
- Restrictions.eq("targetBranch", target.getBranch()));
- }
-
- public static Criterion ofSource(RepoAndBranch source) {
- return Restrictions.and(
- Restrictions.eq("sourceRepo", source.getRepository()),
- Restrictions.eq("sourceBranch", source.getBranch()));
- }
-
- public static Criterion ofSubmitter(User submitter) {
- return Restrictions.eq("submitter", submitter);
- }
-
- }
-
- public Date getSubmitDate() {
- return submitDate;
- }
-
- public void setSubmitDate(Date submitDate) {
- this.submitDate = submitDate;
- }
-
- public Date getLastEventDate() {
- return lastEventDate;
- }
-
- public void setLastEventDate(Date lastEventDate) {
- this.lastEventDate = lastEventDate;
- }
-
- public Event getLastEvent() {
- return lastEvent;
- }
-
- public void setLastEvent(Event lastEvent) {
- this.lastEvent = lastEvent;
- }
-
- /**
- * Get commits pending integration.
- *
- * @return
- * commits pending integration
- */
- public Set<String> getPendingCommits() {
- if (pendingCommits == null) {
- pendingCommits = new HashSet<>();
- Repository repo = getTargetRepo();
- for (Commit commit: repo.git().log(getTarget().getHead(), getLatestUpdate().getHeadCommitHash(), null, 0, 0, false))
- pendingCommits.add(commit.getHash());
- }
- return pendingCommits;
- }
-
- public List<String> getCommentables() {
- List<String> commentables = new ArrayList<>();
- commentables.add(getBaseCommitHash());
- for (PullRequestUpdate update: getSortedUpdates()) {
- for (Commit commit: update.getCommits())
- commentables.add(commit.getHash());
- }
- return commentables;
- }
-
- /**
- * Merged commits represent commits already merged to target branch since base commit.
- *
- * @return
- * commits already merged to target branch since base commit
- */
- public Collection<Commit> getMergedCommits() {
- if (mergedCommits == null) {
- mergedCommits = new HashSet<>();
-
- Repository repo = getTargetRepo();
- for (Commit commit: repo.git().log(getBaseCommitHash(), getTarget().getHead(), null, 0, 0, false))
- mergedCommits.add(commit);
- }
- return mergedCommits;
- }
-
- private Collection<CommentReply> getCommentReplies() {
- if (commentReplies == null) {
- EntityCriteria<CommentReply> criteria = EntityCriteria.of(CommentReply.class);
- criteria.createCriteria("comment").add(Restrictions.eq("request", this));
- commentReplies = GitPlex.getInstance(Dao.class).query(criteria);
- }
- return commentReplies;
- }
-
- /**
- * This method is here for performance consideration. Often we need to load replies of
- * different comments in a pull request. And we optimize it to load all replies at once
- * for all comments in a pull request to reduce SQL queries.
- *
- * @param comment
- * @return
- */
- public Collection<CommentReply> getCommentReplies(Comment comment) {
- List<CommentReply> replies = new ArrayList<>();
- for (CommentReply reply: getCommentReplies()) {
- if (reply.getComment().equals(comment))
- replies.add(reply);
- }
- return replies;
- }
-
- public List<Review> getReviews() {
- if (reviews == null) {
- if (!isNew())
- reviews = GitPlex.getInstance(ReviewManager.class).findBy(this);
- else
- reviews = new ArrayList<>();
- }
- return reviews;
- }
-
- /**
- * This method is here for performance consideration. Often we need to load reviews of
- * different updates in a pull request. And we optimize it to load all reviews at once
- * for all updates in a pull request to reduce SQL queries.
- *
- * @param update
- * @return
- */
- public List<Review> getReviews(PullRequestUpdate update) {
- List<Review> reviews = new ArrayList<>();
- for (Review review: getReviews()) {
- if (review.getUpdate().equals(update))
- reviews.add(review);
- }
- return reviews;
- }
-
- public boolean isReviewEffective(User user) {
- for (Review review: getReviews()) {
- if (review.getUpdate().equals(getLatestUpdate()) && review.getReviewer().equals(user))
- return true;
- }
- return false;
- }
-
- /**
- * Calculate list of users can be added as reviewers of this pull request.
- *
- * @return
- * list of potential reviewers
- */
- public List<User> getPotentialReviewers() {
- List<User> reviewers = new ArrayList<>();
- Set<User> alreadyInvited = new HashSet<>();
- for (ReviewInvitation invitation: getReviewInvitations()) {
- if (invitation.isPreferred())
- alreadyInvited.add(invitation.getReviewer());
- }
- ObjectPermission readPerm = ObjectPermission.ofRepoPull(getTargetRepo());
- for (User user: GitPlex.getInstance(Dao.class).allOf(User.class)) {
- if (user.asSubject().isPermitted(readPerm) && !alreadyInvited.contains(user))
- reviewers.add(user);
- }
- return reviewers;
- }
-
- @Nullable
- public PullRequestWatch getWatch(User user) {
- for (PullRequestWatch watch: getWatches()) {
- if (watch.getUser().equals(user))
- return watch;
- }
- return null;
- }
-
- @Nullable
- public PullRequestVisit getVisit(User user) {
- for (PullRequestVisit visit: getVisits()) {
- if (visit.getUser().equals(user))
- return visit;
- }
- return null;
- }
-
- public String getUrl() {
- return GitPlex.getInstance().guessServerUrl() + "/" + getTargetRepo().getFQN()
- + "/pull_requests/" + getId() + "/overview";
- }
-
- @PrePersist
- public void prePersist() {
- idStr = getId().toString();
- }
-
- public String getIdStr() {
- return idStr;
- }
-
- public String getNoSpaceTitle() {
- return noSpaceTitle;
- }
-
- public long getVersion() {
- return version;
- }
-
-}
+package com.pmease.gitplex.core.model;
+
+import java.util.ArrayList;
+import java.util.Collection;
+import java.util.Collections;
+import java.util.Comparator;
+import java.util.Date;
+import java.util.HashMap;
+import java.util.HashSet;
+import java.util.List;
+import java.util.Map;
+import java.util.Set;
+import java.util.concurrent.Callable;
+
+import javax.annotation.Nullable;
+import javax.persistence.Column;
+import javax.persistence.Embedded;
+import javax.persistence.Entity;
+import javax.persistence.FetchType;
+import javax.persistence.JoinColumn;
+import javax.persistence.Lob;
+import javax.persistence.ManyToOne;
+import javax.persistence.OneToMany;
+import javax.persistence.PrePersist;
+import javax.persistence.Transient;
+import javax.persistence.Version;
+
+import org.apache.commons.lang3.StringUtils;
+import org.hibernate.annotations.DynamicUpdate;
+import org.hibernate.annotations.Index;
+import org.hibernate.annotations.OnDelete;
+import org.hibernate.annotations.OnDeleteAction;
+import org.hibernate.annotations.OptimisticLock;
+import org.hibernate.criterion.Criterion;
+import org.hibernate.criterion.Restrictions;
+
+import com.fasterxml.jackson.annotation.JsonView;
+import com.google.common.base.Preconditions;
+import com.pmease.commons.git.Commit;
+import com.pmease.commons.git.Git;
+import com.pmease.commons.git.GitUtils;
+import com.pmease.commons.hibernate.AbstractEntity;
+import com.pmease.commons.hibernate.dao.Dao;
+import com.pmease.commons.hibernate.dao.EntityCriteria;
+import com.pmease.commons.jackson.ExternalView;
+import com.pmease.commons.util.LockUtils;
+import com.pmease.gitplex.core.GitPlex;
+import com.pmease.gitplex.core.gatekeeper.checkresult.Blocking;
+import com.pmease.gitplex.core.gatekeeper.checkresult.CheckResult;
+import com.pmease.gitplex.core.gatekeeper.checkresult.Failed;
+import com.pmease.gitplex.core.gatekeeper.checkresult.Pending;
+import com.pmease.gitplex.core.manager.PullRequestManager;
+import com.pmease.gitplex.core.manager.ReviewManager;
+import com.pmease.gitplex.core.permission.ObjectPermission;
+
+/*
+ * @DynamicUpdate annotation here along with various @OptimisticLock annotations
+ * on certain fields tell Hibernate not to perform version check on those fields
+ * which can be updated from background thread.
+ */
+@SuppressWarnings("serial")
+@Entity
+@DynamicUpdate
+public class PullRequest extends AbstractEntity {
+
+ public enum Status {
+ PENDING_APPROVAL("Pending Approval"),
+ PENDING_UPDATE("Pending Update"), PENDING_INTEGRATE("Pending Integration"),
+ INTEGRATED("Integrated"), DISCARDED("Discarded");
+
+ private final String displayName;
+
+ Status(String displayName) {
+ this.displayName = displayName;
+ }
+
+ @Override
+ public String toString() {
+ return displayName;
+ }
+
+ }
+
+ public enum IntegrationStrategy {
+ MERGE_ALWAYS("Merge always",
+ "Always create merge commit when integrate into target branch"),
+ MERGE_IF_NECESSARY("Merge if necessary",
+ "Create merge commit only if target branch can not be fast-forwarded to the pull request"),
+ MERGE_WITH_SQUASH("Merge with squash",
+ "Squash all commits in the pull request and then merge with target branch"),
+ REBASE_SOURCE_ONTO_TARGET("Rebase source onto target",
+ "Rebase source branch onto target branch and then fast-forward target branch to source branch"),
+ REBASE_TARGET_ONTO_SOURCE("Rebase target onto source",
+ "Rebase target branch onto source branch");
+
+ private final String displayName;
+
+ private final String description;
+
+ IntegrationStrategy(String displayName, String description) {
+ this.displayName = displayName;
+ this.description = description;
+ }
+
+ public String getDisplayName() {
+ return displayName;
+ }
+
+ public String getDescription() {
+ return description;
+ }
+
+ @Override
+ public String toString() {
+ return displayName;
+ }
+
+ }
+
+ public enum Event {
+ OPENED("Newly opened"),
+ REVIEWED("New reviews in"),
+ VERIFIED("Build verification is finished for"),
+ UPDATED("New commits in"),
+ COMMENTED("New comments in"),
+ INTEGRATION_STRATEGY_CHANGED("Integration strategy is changed"),
+ INTEGRATED("Integration is done for"),
+ DISCARDED("Discarded"),
+ REOPENED("Reopened"),
+ INTEGRATION_PREVIEW_CALCULATED("Integration preview is calculated"),
+ ASSIGNED("Assigned"),
+ REVIEWER_CHANGED("Reviewer changed"),
+ REVIEW_REMOVED("Review removed"),
+ COMMENT_REPLIED("Comment is replied");
+
+ private final String displayName;
+
+ Event(String displayName) {
+ this.displayName = displayName;
+ }
+
+ public String toString() {
+ return displayName;
+ }
+
+ };
+
+ @Embedded
+ private CloseInfo closeInfo;
+
+ @Index(name="PR_TITLE")
+ @Column(nullable=false)
+ private String title;
+
+ @Lob
+ @Column(length=65535)
+ private String description;
+
+ @ManyToOne(fetch=FetchType.LAZY)
+ private User submitter;
+
+ @ManyToOne(fetch=FetchType.LAZY)
+ @JoinColumn(nullable=false)
+ private Repository targetRepo;
+
+ @Column(nullable=false)
+ private String targetBranch;
+
+ @ManyToOne(fetch=FetchType.LAZY)
+ private Repository sourceRepo;
+
+ @Column(nullable=false)
+ private String sourceBranch;
+
+ @Column(nullable=false)
+ private String baseCommitHash;
+
+ @ManyToOne(fetch=FetchType.LAZY)
+ private User assignee;
+
+ // used for id search in markdown editor
+ @Index(name="PR_ID_STR")
+ @Column(nullable=false)
+ private String idStr;
+
+ // used for title search in markdown editor
+ @Index(name="PR_NO_SP_TITLE")
+ @Column(nullable=false)
+ private String noSpaceTitle;
+
+ @Version
+ private long version;
+
+ @Transient
+ private Git sandbox;
+
+ @OptimisticLock(excluded=true)
+ @Embedded
+ private IntegrationPreview lastIntegrationPreview;
+
+ @Column(nullable=false)
+ private Date submitDate = new Date();
+
+ @OptimisticLock(excluded=true)
+ @Column(nullable=false)
+ private Date lastEventDate = new Date();
+
+ @OptimisticLock(excluded=true)
+ @Column(nullable=false)
+ private Event lastEvent = Event.OPENED;
+
+ @Column(nullable=false)
+ private IntegrationStrategy integrationStrategy;
+
+ @OneToMany(mappedBy="request")
+ @OnDelete(action=OnDeleteAction.CASCADE)
+ private Collection<PullRequestUpdate> updates = new ArrayList<>();
+
+ @OneToMany(mappedBy="request")
+ @OnDelete(action=OnDeleteAction.CASCADE)
+ private Collection<ReviewInvitation> reviewInvitations = new ArrayList<>();
+
+ @OneToMany(mappedBy="referenced")
+ @OnDelete(action=OnDeleteAction.CASCADE)
+ private Collection<PullRequestReference> referencedBy = new ArrayList<>();
+
+ @OneToMany(mappedBy="referencedBy")
+ @OnDelete(action=OnDeleteAction.CASCADE)
+ private Collection<PullRequestReference> referenced = new ArrayList<>();
+
+ @OneToMany(mappedBy="request")
+ @OnDelete(action=OnDeleteAction.CASCADE)
+ private Collection<Verification> verifications = new ArrayList<>();
+
+ @OneToMany(mappedBy="request")
+ @OnDelete(action=OnDeleteAction.CASCADE)
+ private Collection<Comment> comments = new ArrayList<>();
+
+ @OneToMany(mappedBy="request")
+ @OnDelete(action=OnDeleteAction.CASCADE)
+ private Collection<PullRequestActivity> activities = new ArrayList<>();
+
+ @OneToMany(mappedBy="request")
+ @OnDelete(action=OnDeleteAction.CASCADE)
+ private Collection<Notification> notifications = new ArrayList<>();
+
+ @OneToMany(mappedBy="request")
+ @OnDelete(action=OnDeleteAction.CASCADE)
+ private Collection<PullRequestVisit> visits = new ArrayList<>();
+
+ @OneToMany(mappedBy="request")
+ @OnDelete(action=OnDeleteAction.CASCADE)
+ private Collection<PullRequestWatch> watches = new ArrayList<>();
+
+ private transient CheckResult checkResult;
+
+ private transient List<PullRequestUpdate> sortedUpdates;
+
+ private transient List<PullRequestUpdate> effectiveUpdates;
+
+ private transient PullRequestUpdate referentialUpdate;
+
+ private transient Set<String> pendingCommits;
+
+ private transient Collection<Commit> mergedCommits;
+
+ private transient Collection<CommentReply> commentReplies;
+
+ private transient List<Review> reviews;
+
+ /**
+ * Get title of this merge request.
+ *
+ * @return user specified title of this merge request, <tt>null</tt> for
+ * auto-created merge request.
+ */
+ public @Nullable String getTitle() {
+ return title;
+ }
+
+ public void setTitle(String title) {
+ this.title = title;
+ noSpaceTitle = StringUtils.deleteWhitespace(title);
+ }
+
+ public String getDescription() {
+ return description;
+ }
+
+ public void setDescription(String description) {
+ this.description = description;
+ }
+
+ /**
+ * Get the user submitting the pull request.
+ *
+ * @return
+ * the user submitting the pull request, or <tt>null</tt> if unknown
+ */
+ @Nullable
+ public User getSubmitter() {
+ return submitter;
+ }
+
+ public void setSubmitter(@Nullable User submitter) {
+ this.submitter = submitter;
+ }
+
+ /**
+ * Get the user responsible for integration of the pull request.
+ *
+ * @return
+ * the user responsible for integration of this pull request, or <tt>null</tt> to have the
+ * system integrate the pull request automatically
+ */
+ @Nullable
+ public User getAssignee() {
+ return assignee;
+ }
+
+ public void setAssignee(User assignee) {
+ this.assignee = assignee;
+ }
+
+ public Repository getTargetRepo() {
+ return targetRepo;
+ }
+
+ public RepoAndBranch getTarget() {
+ return new RepoAndBranch(getTargetRepo(), getTargetBranch());
+ }
+
+ public void setTarget(RepoAndBranch target) {
+ setTargetRepo(target.getRepository());
+ setTargetBranch(target.getBranch());
+ }
+
+ public void setSource(RepoAndBranch source) {
+ setSourceRepo(source.getRepository());
+ setSourceBranch(source.getBranch());
+ }
+
+ public void setTargetRepo(Repository targetRepo) {
+ this.targetRepo = targetRepo;
+ }
+
+ public String getTargetBranch() {
+ return targetBranch;
+ }
+
+ public void setTargetBranch(String targetBranch) {
+ this.targetBranch = targetBranch;
+ }
+
+ @Nullable
+ public Repository getSourceRepo() {
+ return sourceRepo;
+ }
+
+ public void setSourceRepo(Repository sourceRepo) {
+ this.sourceRepo = sourceRepo;
+ }
+
+ public String getSourceBranch() {
+ return sourceBranch;
+ }
+
+ public void setSourceBranch(String sourceBranch) {
+ this.sourceBranch = sourceBranch;
+ }
+
+ public RepoAndBranch getSource() {
+ return new RepoAndBranch(getSourceRepo(), getSourceBranch());
+ }
+
+ public String getTargetRef() {
+ return GitUtils.branch2ref(getTargetBranch());
+ }
+
+ public String getSourceRef() {
+ return GitUtils.branch2ref(getSourceBranch());
+ }
+
+ public String getBaseCommitHash() {
+ return baseCommitHash;
+ }
+
+ public void setBaseCommitHash(String baseCommitHash) {
+ this.baseCommitHash = baseCommitHash;
+ }
+
+ public Commit getBaseCommit() {
+ return getTargetRepo().getCommit(getBaseCommitHash());
+ }
+
+ public Git git() {
+ if (sandbox == null)
+ return getTargetRepo().git();
+ else
+ return sandbox;
+ }
+
+ public Git getSandbox() {
+ return sandbox;
+ }
+
+ public void setSandbox(Git sandbox) {
+ this.sandbox = sandbox;
+ }
+
+ /**
+ * Get unmodifiable collection of updates of this pull request. To add update
+ * to the pull request, call {@link this#addUpdate(PullRequestUpdate)} instead.
+ *
+ * @return
+ * unmodifiable collection of updates
+ */
+ public Collection<PullRequestUpdate> getUpdates() {
+ return Collections.unmodifiableCollection(updates);
+ }
+
+ public void setUpdates(Collection<PullRequestUpdate> updates) {
+ this.updates = updates;
+ sortedUpdates = null;
+ effectiveUpdates = null;
+ }
+
+ public void addUpdate(PullRequestUpdate update) {
+ updates.add(update);
+ sortedUpdates = null;
+ effectiveUpdates = null;
+ }
+
+ public Collection<ReviewInvitation> getReviewInvitations() {
+ return reviewInvitations;
+ }
+
+ public void setReviewInvitations(Collection<ReviewInvitation> reviewInvitations) {
+ this.reviewInvitations = reviewInvitations;
+ }
+
+ public Collection<Verification> getVerifications() {
+ return verifications;
+ }
+
+ public void setVerifications(Collection<Verification> verifications) {
+ this.verifications = verifications;
+ }
+
+ public Collection<PullRequestReference> getReferencedBy() {
+ return referencedBy;
+ }
+
+ public void setReferencedBy(Collection<PullRequestReference> referencedBy) {
+ this.referencedBy = referencedBy;
+ }
+
+ public Collection<PullRequestReference> getReferenced() {
+ return referenced;
+ }
+
+ public void setReferenced(Collection<PullRequestReference> referenced) {
+ this.referenced = referenced;
+ }
+
+ public Collection<Comment> getComments() {
+ return comments;
+ }
+
+ public void setComments(Collection<Comment> comments) {
+ this.comments = comments;
+ }
+
+ public Collection<PullRequestActivity> getActivities() {
+ return activities;
+ }
+
+ public void setActivities(Collection<PullRequestActivity> activities) {
+ this.activities = activities;
+ }
+
+ public Collection<Notification> getNotifications() {
+ return notifications;
+ }
+
+ public void setNotifications(Collection<Notification> notifications) {
+ this.notifications = notifications;
+ }
+
+ public Collection<PullRequestVisit> getVisits() {
+ return visits;
+ }
+
+ public void setVisits(Collection<PullRequestVisit> visits) {
+ this.visits = visits;
+ }
+
+ public Collection<PullRequestWatch> getWatches() {
+ return watches;
+ }
+
+ public void setWatches(Collection<PullRequestWatch> watches) {
+ this.watches = watches;
+ }
+
+ public Status getStatus() {
+ if (closeInfo != null) {
+ if (closeInfo.getCloseStatus() == CloseInfo.Status.INTEGRATED)
+ return Status.INTEGRATED;
+ else
+ return Status.DISCARDED;
+ } else if (getCheckResult() instanceof Pending || getCheckResult() instanceof Blocking)
+ return Status.PENDING_APPROVAL;
+ else if (getCheckResult() instanceof Failed)
+ return Status.PENDING_UPDATE;
+ else
+ return Status.PENDING_INTEGRATE;
+ }
+
+ @Nullable
+ public CloseInfo getCloseInfo() {
+ return closeInfo;
+ }
+
+ public void setCloseInfo(CloseInfo closeInfo) {
+ this.closeInfo = closeInfo;
+ }
+
+ public boolean isOpen() {
+ return closeInfo == null;
+ }
+
+ public PullRequestUpdate getReferentialUpdate() {
+ if (referentialUpdate != null)
+ return referentialUpdate;
+ else
+ return getEffectiveUpdates().get(0);
+ }
+
+ public void setReferentialUpdate(PullRequestUpdate referentiralUpdate) {
+ this.referentialUpdate = referentiralUpdate;
+ }
+
+ /**
+ * Get gate keeper check result.
+ *
+ * @return
+ * check result of this pull request has not been refreshed yet
+ */
+ public CheckResult getCheckResult() {
+ if (checkResult == null)
+ checkResult = getTargetRepo().getGateKeeper().checkRequest(this);
+ return checkResult;
+ }
+
+ /**
+ * Get last integration preview of this pull request. Note that this method may return an
+ * out dated integration preview. Refer to {@link this#getIntegrationPreview()}
+ * if you'd like to get an update-to-date integration preview
+ *
+ * @return
+ * integration preview of this pull request, or <tt>null</tt> if integration
+ * preview has not been calculated yet.
+ */
+ @Nullable
+ public IntegrationPreview getLastIntegrationPreview() {
+ return lastIntegrationPreview;
+ }
+
+ public void setLastIntegrationPreview(IntegrationPreview lastIntegrationPreview) {
+ this.lastIntegrationPreview = lastIntegrationPreview;
+ }
+
+ /**
+ * Get effective integration preview of this pull request.
+ *
+ * @return
+ * update to date integration preview of this pull request, or <tt>null</tt> if
+ * the integration preview has not been calculated or out dated. In both cases,
+ * it will trigger a re-calculation, and client should call this method later
+ * to get the calculated result
+ */
+ @JsonView(ExternalView.class)
+ @Nullable
+ public IntegrationPreview getIntegrationPreview() {
+ return GitPlex.getInstance(PullRequestManager.class).previewIntegration(this);
+ }
+
+ /**
+ * Get list of sorted updates.
+ *
+ * @return
+ * list of sorted updates ordered by id
+ */
+ public List<PullRequestUpdate> getSortedUpdates() {
+ if (sortedUpdates == null) {
+ Preconditions.checkState(updates.size() >= 1);
+ sortedUpdates = new ArrayList<PullRequestUpdate>(updates);
+ Collections.sort(sortedUpdates);
+ }
+ return sortedUpdates;
+ }
+
+ /**
+ * Get list of effective updates reversely sorted by id. Update is considered effective if it is
+ * not ancestor of target branch head.
+ *
+ * @return
+ * list of effective updates reversely sorted by id
+ */
+ public List<PullRequestUpdate> getEffectiveUpdates() {
+ Preconditions.checkState(isOpen(), "Can only be called while request is open");
+ if (effectiveUpdates == null) {
+ effectiveUpdates = new ArrayList<PullRequestUpdate>();
+
+ for (int i=getSortedUpdates().size()-1; i>=0; i--) {
+ PullRequestUpdate update = getSortedUpdates().get(i);
+ if (!getTargetRepo().isAncestor(update.getHeadCommitHash(), getTarget().getHead()))
+ effectiveUpdates.add(update);
+ else
+ break;
+ }
+
+ Preconditions.checkState(!effectiveUpdates.isEmpty());
+ }
+ return effectiveUpdates;
+ }
+
+ public IntegrationStrategy getIntegrationStrategy() {
+ return integrationStrategy;
+ }
+
+ public void setIntegrationStrategy(IntegrationStrategy integrationStrategy) {
+ this.integrationStrategy = integrationStrategy;
+ }
+
+ @JsonView(ExternalView.class)
+ public PullRequestUpdate getLatestUpdate() {
+ return getSortedUpdates().get(getSortedUpdates().size()-1);
+ }
+
+ public Collection<String> findTouchedFiles() {
+ Git git = getTargetRepo().git();
+ return git.listChangedFiles(getTarget().getHead(), getLatestUpdate().getHeadCommitHash(), null);
+ }
+
+ @JsonView(ExternalView.class)
+ public String getBaseRef() {
+ Preconditions.checkNotNull(getId());
+ return Repository.REFS_GITPLEX + "pulls/" + getId() + "/base";
+ }
+
+ @JsonView(ExternalView.class)
+ public String getIntegrateRef() {
+ Preconditions.checkNotNull(getId());
+ return Repository.REFS_GITPLEX + "pulls/" + getId() + "/integrate";
+ }
+
+ /**
+ * Delete refs of this pull request, without touching refs of its updates.
+ */
+ public void deleteRefs() {
+ Git git = getTargetRepo().git();
+ git.deleteRef(getBaseRef(), null, null);
+ git.deleteRef(getIntegrateRef(), null, null);
+ }
+
+ public <T> T lockAndCall(Callable<T> callable) {
+ Preconditions.checkNotNull(getId());
+
+ return LockUtils.call("pull request: " + getId(), callable);
+ }
+
+ /**
+ * Invite specified number of users in candidates to review this request.
+ * <p>
+ *
+ * @param candidates
+ * a collection of users to invite users from
+ * @param count
+ * number of users to invite
+ */
+ public void pickReviewers(Collection<User> candidates, int count) {
+ List<User> pickList = new ArrayList<User>(candidates);
+
+ /*
+ * users already reviewed since base update should be excluded from
+ * invitation list as their reviews are still valid
+ */
+ for (Review review: getReferentialUpdate().listReviewsOnwards())
+ pickList.remove(review.getReviewer());
+
+ final Map<User, Date> firstChoices = new HashMap<>();
+ final Map<User, Date> secondChoices = new HashMap<>();
+
+ for (ReviewInvitation invitation: getReviewInvitations()) {
+ if (invitation.isPreferred())
+ firstChoices.put(invitation.getReviewer(), invitation.getDate());
+ else
+ secondChoices.put(invitation.getReviewer(), invitation.getDate());
+ }
+
+ // submitter is not preferred
+ if (getSubmitter() != null)
+ secondChoices.put(getSubmitter(), new Date());
+
+ /* Follow below rules to pick reviewers:
+ * 1. If user is excluded previously, it will be considered last.
+ * 2. If user is already a reviewer, it will be considered first.
+ * 3. Otherwise pick user with least reviews.
+ */
+ Collections.sort(pickList, new Comparator<User>() {
+
+ @Override
+ public int compare(User user1, User user2) {
+ if (firstChoices.containsKey(user1)) {
+ if (firstChoices.containsKey(user2))
+ return user1.getReviewEffort() - user2.getReviewEffort();
+ else
+ return -1;
+ } else if (firstChoices.containsKey(user2)) {
+ return 1;
+ } else if (secondChoices.containsKey(user1)) {
+ if (secondChoices.containsKey(user2))
+ return secondChoices.get(user1).compareTo(secondChoices.get(user2));
+ else
+ return 1;
+ } else if (secondChoices.containsKey(user2)) {
+ return -1;
+ } else {
+ return user1.getReviewEffort() - user2.getReviewEffort();
+ }
+ }
+
+ });
+
+ List<User> picked;
+ if (count <= pickList.size())
+ picked = pickList.subList(0, count);
+ else
+ picked = pickList;
+
+ for (User user: picked) {
+ boolean found = false;
+ for (ReviewInvitation invitation: getReviewInvitations()) {
+ if (invitation.getReviewer().equals(user)) {
+ invitation.setDate(new Date());
+ invitation.setPerferred(true);
+ found = true;
+ }
+ }
+ if (!found) {
+ ReviewInvitation invitation = new ReviewInvitation();
+ invitation.setRequest(this);
+ invitation.setReviewer(user);
+ getReviewInvitations().add(invitation);
+ }
+ }
+
+ }
+
+ public static class CriterionHelper {
+ public static Criterion ofOpen() {
+ return Restrictions.isNull("closeInfo");
+ }
+
+ public static Criterion ofClosed() {
+ return Restrictions.isNotNull("closeInfo");
+ }
+
+ public static Criterion ofTarget(RepoAndBranch target) {
+ return Restrictions.and(
+ Restrictions.eq("targetRepo", target.getRepository()),
+ Restrictions.eq("targetBranch", target.getBranch()));
+ }
+
+ public static Criterion ofSource(RepoAndBranch source) {
+ return Restrictions.and(
+ Restrictions.eq("sourceRepo", source.getRepository()),
+ Restrictions.eq("sourceBranch", source.getBranch()));
+ }
+
+ public static Criterion ofSubmitter(User submitter) {
+ return Restrictions.eq("submitter", submitter);
+ }
+
+ }
+
+ public Date getSubmitDate() {
+ return submitDate;
+ }
+
+ public void setSubmitDate(Date submitDate) {
+ this.submitDate = submitDate;
+ }
+
+ public Date getLastEventDate() {
+ return lastEventDate;
+ }
+
+ public void setLastEventDate(Date lastEventDate) {
+ this.lastEventDate = lastEventDate;
+ }
+
+ public Event getLastEvent() {
+ return lastEvent;
+ }
+
+ public void setLastEvent(Event lastEvent) {
+ this.lastEvent = lastEvent;
+ }
+
+ /**
+ * Get commits pending integration.
+ *
+ * @return
+ * commits pending integration
+ */
+ public Set<String> getPendingCommits() {
+ if (pendingCommits == null) {
+ pendingCommits = new HashSet<>();
+ Repository repo = getTargetRepo();
+ for (Commit commit: repo.git().log(getTarget().getHead(), getLatestUpdate().getHeadCommitHash(), null, 0, 0, false))
+ pendingCommits.add(commit.getHash());
+ }
+ return pendingCommits;
+ }
+
+ public List<String> getCommentables() {
+ List<String> commentables = new ArrayList<>();
+ commentables.add(getBaseCommitHash());
+ for (PullRequestUpdate update: getSortedUpdates()) {
+ for (Commit commit: update.getCommits())
+ commentables.add(commit.getHash());
+ }
+ return commentables;
+ }
+
+ /**
+ * Merged commits represent commits already merged to target branch since base commit.
+ *
+ * @return
+ * commits already merged to target branch since base commit
+ */
+ public Collection<Commit> getMergedCommits() {
+ if (mergedCommits == null) {
+ mergedCommits = new HashSet<>();
+
+ Repository repo = getTargetRepo();
+ for (Commit commit: repo.git().log(getBaseCommitHash(), getTarget().getHead(), null, 0, 0, false))
+ mergedCommits.add(commit);
+ }
+ return mergedCommits;
+ }
+
+ private Collection<CommentReply> getCommentReplies() {
+ if (commentReplies == null) {
+ EntityCriteria<CommentReply> criteria = EntityCriteria.of(CommentReply.class);
+ criteria.createCriteria("comment").add(Restrictions.eq("request", this));
+ commentReplies = GitPlex.getInstance(Dao.class).query(criteria);
+ }
+ return commentReplies;
+ }
+
+ /**
+ * This method is here for performance consideration. Often we need to load replies of
+ * different comments in a pull request. And we optimize it to load all replies at once
+ * for all comments in a pull request to reduce SQL queries.
+ *
+ * @param comment
+ * @return
+ */
+ public Collection<CommentReply> getCommentReplies(Comment comment) {
+ List<CommentReply> replies = new ArrayList<>();
+ for (CommentReply reply: getCommentReplies()) {
+ if (reply.getComment().equals(comment))
+ replies.add(reply);
+ }
+ return replies;
+ }
+
+ public List<Review> getReviews() {
+ if (reviews == null) {
+ if (!isNew())
+ reviews = GitPlex.getInstance(ReviewManager.class).findBy(this);
+ else
+ reviews = new ArrayList<>();
+ }
+ return reviews;
+ }
+
+ /**
+ * This method is here for performance consideration. Often we need to load reviews of
+ * different updates in a pull request. And we optimize it to load all reviews at once
+ * for all updates in a pull request to reduce SQL queries.
+ *
+ * @param update
+ * @return
+ */
+ public List<Review> getReviews(PullRequestUpdate update) {
+ List<Review> reviews = new ArrayList<>();
+ for (Review review: getReviews()) {
+ if (review.getUpdate().equals(update))
+ reviews.add(review);
+ }
+ return reviews;
+ }
+
+ public boolean isReviewEffective(User user) {
+ for (Review review: getReviews()) {
+ if (review.getUpdate().equals(getLatestUpdate()) && review.getReviewer().equals(user))
+ return true;
+ }
+ return false;
+ }
+
+ /**
+ * Calculate list of users can be added as reviewers of this pull request.
+ *
+ * @return
+ * list of potential reviewers
+ */
+ public List<User> getPotentialReviewers() {
+ List<User> reviewers = new ArrayList<>();
+ Set<User> alreadyInvited = new HashSet<>();
+ for (ReviewInvitation invitation: getReviewInvitations()) {
+ if (invitation.isPreferred())
+ alreadyInvited.add(invitation.getReviewer());
+ }
+ ObjectPermission readPerm = ObjectPermission.ofRepoPull(getTargetRepo());
+ for (User user: GitPlex.getInstance(Dao.class).allOf(User.class)) {
+ if (user.asSubject().isPermitted(readPerm) && !alreadyInvited.contains(user))
+ reviewers.add(user);
+ }
+ return reviewers;
+ }
+
+ @Nullable
+ public PullRequestWatch getWatch(User user) {
+ for (PullRequestWatch watch: getWatches()) {
+ if (watch.getUser().equals(user))
+ return watch;
+ }
+ return null;
+ }
+
+ @Nullable
+ public PullRequestVisit getVisit(User user) {
+ for (PullRequestVisit visit: getVisits()) {
+ if (visit.getUser().equals(user))
+ return visit;
+ }
+ return null;
+ }
+
+ public String getUrl() {
+ return GitPlex.getInstance().guessServerUrl() + "/" + getTargetRepo().getFQN()
+ + "/pull_requests/" + getId() + "/overview";
+ }
+
+ @PrePersist
+ public void prePersist() {
+ idStr = getId().toString();
+ }
+
+ public String getIdStr() {
+ return idStr;
+ }
+
+ public String getNoSpaceTitle() {
+ return noSpaceTitle;
+ }
+
+ public long getVersion() {
+ return version;
+ }
+
+}
diff --git a/gitplex.core/src/main/java/com/pmease/gitplex/core/model/PullRequestUpdate.java b/gitplex.core/src/main/java/com/pmease/gitplex/core/model/PullRequestUpdate.java
index 4abee24d71..d63c5d759c 100644
--- a/gitplex.core/src/main/java/com/pmease/gitplex/core/model/PullRequestUpdate.java
+++ b/gitplex.core/src/main/java/com/pmease/gitplex/core/model/PullRequestUpdate.java
@@ -1,358 +1,359 @@
-package com.pmease.gitplex.core.model;
-
-import java.io.File;
-import java.io.Serializable;
-import java.util.ArrayList;
-import java.util.Collection;
-import java.util.Collections;
-import java.util.Date;
-import java.util.HashMap;
-import java.util.LinkedHashMap;
-import java.util.List;
-import java.util.Map;
-import java.util.Stack;
-import java.util.concurrent.Callable;
-
-import javax.persistence.Column;
-import javax.persistence.Entity;
-import javax.persistence.FetchType;
-import javax.persistence.JoinColumn;
-import javax.persistence.ManyToOne;
-import javax.persistence.OneToMany;
-
-import org.hibernate.annotations.OnDelete;
-import org.hibernate.annotations.OnDeleteAction;
-
-import com.fasterxml.jackson.annotation.JsonProperty;
-import com.google.common.base.Preconditions;
-import com.google.common.base.Throwables;
-import com.google.common.collect.Lists;
-import com.pmease.commons.git.Commit;
-import com.pmease.commons.git.Git;
-import com.pmease.commons.hibernate.AbstractEntity;
-import com.pmease.commons.util.FileUtils;
-import com.pmease.gitplex.core.GitPlex;
-import com.pmease.gitplex.core.manager.StorageManager;
-
-@SuppressWarnings("serial")
-@Entity
-public class PullRequestUpdate extends AbstractEntity {
-
- @ManyToOne(fetch=FetchType.LAZY)
- @JoinColumn(nullable=false)
- private PullRequest request;
-
- @Column(nullable=false)
- private String headCommitHash;
-
- @Column(nullable=false)
- private Date date;
-
- @OneToMany(mappedBy="update")
- @OnDelete(action=OnDeleteAction.CASCADE)
- private Collection<Review> reviews = new ArrayList<Review>();
-
- private transient List<Commit> commits;
-
- private transient CachedInfo cachedInfo;
-
- public PullRequest getRequest() {
- return request;
- }
-
- public void setRequest(PullRequest request) {
- this.request = request;
- }
-
- public String getHeadCommitHash() {
- return headCommitHash;
- }
-
- public void setHeadCommitHash(String headCommitHash) {
- this.headCommitHash = headCommitHash;
- }
-
- public Date getDate() {
- return date;
- }
-
- public void setDate(Date date) {
- this.date = date;
- }
-
- public Collection<Review> getReviews() {
- return getRequest().getReviews(this);
- }
-
- @JsonProperty
- public String getHeadRef() {
- Preconditions.checkNotNull(getId());
- return Repository.REFS_GITPLEX + "updates/" + getId();
- }
-
- /**
- * List reviews against this update and all subsequent updates.
- * <p>
- * @return
- * list of found reviews, ordered by associated updates reversely
- */
- public List<Review> listReviewsOnwards() {
- List<Review> reviews = new ArrayList<Review>();
-
- for (PullRequestUpdate update: getRequest().getEffectiveUpdates()) {
- reviews.addAll(update.getReviews());
- if (update.equals(this))
- break;
- }
-
- return reviews;
- }
-
- public void deleteRefs() {
- Git git = getRequest().getTargetRepo().git();
- git.deleteRef(getHeadRef(), null, null);
- }
-
- public Collection<String> getChangedFiles() {
- return getCachedInfo().getChangedFiles();
- }
-
- public String getBaseCommitHash() {
- PullRequest request = getRequest();
-
- int index = request.getSortedUpdates().indexOf(this);
- if (index > 0)
- return request.getSortedUpdates().get(index-1).getHeadCommitHash();
- else
- return request.getBaseCommitHash();
- }
-
- /**
- * Base commit represents head commit of last update, or base commit of the request
- * for the first update. Base commit is used to calculate commits belonging to
- * current update.
- *
- * @return
- * base commit of this update
- */
- public Commit getBaseCommit() {
- PullRequest request = getRequest();
-
- int index = request.getSortedUpdates().indexOf(this);
- if (index > 0)
- return request.getSortedUpdates().get(index-1).getHeadCommit();
- else
- return request.getBaseCommit();
- }
-
- private CachedInfo getCachedInfo() {
- if (cachedInfo == null) {
- Callable<CachedInfo> callable = new Callable<CachedInfo>() {
-
- @Override
- public CachedInfo call() throws Exception {
- CachedInfo cachedInfo = new CachedInfo();
-
- Git git = getRequest().getTargetRepo().git();
- List<Commit> log = git.log(getBaseCommitHash(), getHeadCommitHash(), null, 0, 0, false);
- if (log.isEmpty())
- log = Lists.newArrayList(getRequest().getTargetRepo().getCommit(getHeadCommitHash()));
- cachedInfo.setLogCommits(log);
-
- String mergeBase = git.calcMergeBase(getHeadCommitHash(), getRequest().getTarget().getHead());
-
- if (git.isAncestor(getBaseCommitHash(), mergeBase)) {
- cachedInfo.setChangedFiles(git.listChangedFiles(mergeBase, getHeadCommitHash(), null));
- } else if (git.isAncestor(mergeBase, getBaseCommitHash())) {
- cachedInfo.setChangedFiles(git.listChangedFiles(getBaseCommitHash(), getHeadCommitHash(), null));
- } else {
- File tempDir = FileUtils.createTempDir();
- try {
- Git tempGit = new Git(tempDir);
-
- /*
- * Calculate changed files of this update since merged commit of:
- *
- * 1. merge base of update head and target branch head
- * 2. head of previous update
- *
- * This way changed files of this update will exclude merged changes
- * from target branch if there is any.
- */
- String branchName = getRequest().getTargetBranch();
- tempGit.clone(git.repoDir().getAbsolutePath(), false, true, true, branchName);
- tempGit.updateRef("HEAD", mergeBase, null, null);
- tempGit.reset(null, null);
- Preconditions.checkNotNull(tempGit.merge(getBaseCommitHash(), null, null, "ours", null));
-
- cachedInfo.setChangedFiles(tempGit.listChangedFiles(
- tempGit.parseRevision("HEAD", true), getHeadCommitHash(), null));
- } finally {
- FileUtils.deleteDir(tempDir);
- }
- }
-
- return cachedInfo;
- }
-
- };
- if (isNew()) {
- try {
- cachedInfo = callable.call();
- } catch (Exception e) {
- Throwables.propagate(e);
- }
- } else {
- StorageManager storageManager = GitPlex.getInstance(StorageManager.class);
- File cacheFile = new File(storageManager.getCacheDir(this), "cachedInfo");
- cachedInfo = FileUtils.readFile(cacheFile, callable);
- }
- }
- return cachedInfo;
- }
-
- /**
- * Get commits belonging to this update, ordered by commit id
- *
- * @return
- * commits belonging to this update ordered by commit id
- */
- public List<Commit> getCommits() {
- if (commits == null) {
- /*
- * This method calculates all commits belonging to this update. You might think that
- * the result is obvious, just take log output between last update and current head.
- * But that result may include noise commits, for instance, if you merges target
- * branch into source branch to resolve merge conflicts, all commits in target
- * branch will also appear in log output between last update and current update.
- * Now, you might suggest that let's just exclude from the log output those commits
- * being ancestor of target branch. But this still can cause issues as target branch
- * may merge some intermediate commits from our source branch, and these
- * intermediate commits will be ancestor of target branch. We certainly do not want
- * to exclude these intermediate commits as it originally belongs to our source
- * branch. To solve this contradiction, for those commits belong to both source
- * branch and target branch, we calculate affinity score of the commit to each
- * branch, and consider the commit to be belonging to a branch if the associated
- * affinity score is less.
- */
- commits = new ArrayList<>();
-
- Map<String, ScoreAwareCommit> allCommits = new LinkedHashMap<>();
- for (Commit commit: getCachedInfo().getLogCommits()) {
- ScoreAwareCommit scoreAwareCommit = new ScoreAwareCommit();
- scoreAwareCommit.setCommit(commit);
- allCommits.put(commit.getHash(), scoreAwareCommit);
- }
-
- ScoreAwareCommit headCommit = allCommits.get(getHeadCommitHash());
- if (headCommit != null) {
- headCommit.setScore(0);
- updateAffinityScores(allCommits, headCommit);
- }
-
- Map<String, ScoreAwareCommit> mergedCommits = new HashMap<>();
- for (Commit commit: getRequest().getMergedCommits()) {
- ScoreAwareCommit scoredCommit = new ScoreAwareCommit();
- scoredCommit.setCommit(commit);
- mergedCommits.put(commit.getHash(), scoredCommit);
- }
-
- headCommit = mergedCommits.get(getRequest().getTarget().getHead());
- if (headCommit != null) {
- headCommit.setScore(0);
- updateAffinityScores(mergedCommits, headCommit);
- }
-
- for (ScoreAwareCommit commit: allCommits.values()) {
- ScoreAwareCommit mergedCommit = mergedCommits.get(commit.getCommit().getHash());
- if (mergedCommit == null || mergedCommit.getScore() >= commit.getScore())
- commits.add(commit.getCommit());
- }
-
- getRequest().getTargetRepo().cacheCommits(commits);
-
- Collections.reverse(commits);
- }
- return commits;
- }
-
- public Commit getHeadCommit() {
- Commit headCommit = getCachedInfo().getLogCommits().get(0);
- Preconditions.checkState(headCommit.getHash().equals(getHeadCommitHash()));
- return headCommit;
- }
-
- /*
- * This method calculates affinity scores of a set of commits against specified head commit (or branch).
- * The affinity score reflects the distance between a commit and first-parent chain of the head commit.
- * For instance, if a commit can be reached recursively via first-parent of the head commit, its
- * affinity score will be 0.
- */
- private void updateAffinityScores(Map<String, ScoreAwareCommit> commits, ScoreAwareCommit headCommit) {
- Stack<ScoreAwareCommit> stack = new Stack<>();
- stack.push(headCommit);
- while (!stack.isEmpty()) {
- ScoreAwareCommit currentCommit = stack.pop();
- for (int i=0; i<currentCommit.getCommit().getParentHashes().size(); i++) {
- String parentCommitHash = currentCommit.getCommit().getParentHashes().get(i);
- ScoreAwareCommit parentCommit = commits.get(parentCommitHash);
- if (parentCommit != null && parentCommit.getScore() == Integer.MAX_VALUE) {
- /*
- * Parent hashes of a commit is ordered in parent number. For instance first-parent is at index 0.
- * So the parent score is calculated simply by adding current parent index to the head commit score.
- */
- parentCommit.setScore(i + currentCommit.getScore());
- stack.push(parentCommit);
- }
- }
- }
- }
-
- private static class ScoreAwareCommit {
-
- private Commit commit;
-
- private int score = Integer.MAX_VALUE;
-
- public Commit getCommit() {
- return commit;
- }
-
- public void setCommit(Commit commit) {
- this.commit = commit;
- }
-
- public int getScore() {
- return score;
- }
-
- public void setScore(int score) {
- this.score = score;
- }
-
- }
-
- private static class CachedInfo implements Serializable {
-
- private Collection<String> changedFiles;
-
- private List<Commit> logCommits;
-
- public Collection<String> getChangedFiles() {
- return changedFiles;
- }
-
- public void setChangedFiles(Collection<String> changedFiles) {
- this.changedFiles = changedFiles;
- }
-
- public List<Commit> getLogCommits() {
- return logCommits;
- }
-
- public void setLogCommits(List<Commit> logCommits) {
- this.logCommits = logCommits;
- }
-
- }
-}
+package com.pmease.gitplex.core.model;
+
+import java.io.File;
+import java.io.Serializable;
+import java.util.ArrayList;
+import java.util.Collection;
+import java.util.Collections;
+import java.util.Date;
+import java.util.HashMap;
+import java.util.LinkedHashMap;
+import java.util.List;
+import java.util.Map;
+import java.util.Stack;
+import java.util.concurrent.Callable;
+
+import javax.persistence.Column;
+import javax.persistence.Entity;
+import javax.persistence.FetchType;
+import javax.persistence.JoinColumn;
+import javax.persistence.ManyToOne;
+import javax.persistence.OneToMany;
+
+import org.hibernate.annotations.OnDelete;
+import org.hibernate.annotations.OnDeleteAction;
+
+import com.fasterxml.jackson.annotation.JsonProperty;
+import com.google.common.base.Preconditions;
+import com.google.common.base.Throwables;
+import com.google.common.collect.Lists;
+import com.pmease.commons.git.Commit;
+import com.pmease.commons.git.Git;
+import com.pmease.commons.hibernate.AbstractEntity;
+import com.pmease.commons.util.FileUtils;
+import com.pmease.gitplex.core.GitPlex;
+import com.pmease.gitplex.core.manager.StorageManager;
+
+@SuppressWarnings("serial")
+@Entity
+public class PullRequestUpdate extends AbstractEntity {
+
+ @ManyToOne(fetch=FetchType.LAZY)
+ @JoinColumn(nullable=false)
+ private PullRequest request;
+
+ @Column(nullable=false)
+ private String headCommitHash;
+
+ @Column(nullable=false)
+ private Date date;
+
+ @OneToMany(mappedBy="update")
+ @OnDelete(action=OnDeleteAction.CASCADE)
+ private Collection<Review> reviews = new ArrayList<Review>();
+
+ private transient List<Commit> commits;
+
+ private transient CachedInfo cachedInfo;
+
+ public PullRequest getRequest() {
+ return request;
+ }
+
+ public void setRequest(PullRequest request) {
+ this.request = request;
+ }
+
+ public String getHeadCommitHash() {
+ return headCommitHash;
+ }
+
+ public void setHeadCommitHash(String headCommitHash) {
+ this.headCommitHash = headCommitHash;
+ }
+
+ public Date getDate() {
+ return date;
+ }
+
+ public void setDate(Date date) {
+ this.date = date;
+ }
+
+ public Collection<Review> getReviews() {
+ return getRequest().getReviews(this);
+ }
+
+ @JsonProperty
+ public String getHeadRef() {
+ Preconditions.checkNotNull(getId());
+ return Repository.REFS_GITPLEX + "updates/" + getId();
+ }
+
+ /**
+ * List reviews against this update and all subsequent updates.
+ * <p>
+ * @return
+ * list of found reviews, ordered by associated updates reversely
+ */
+ public List<Review> listReviewsOnwards() {
+ List<Review> reviews = new ArrayList<Review>();
+
+ for (PullRequestUpdate update: getRequest().getEffectiveUpdates()) {
+ reviews.addAll(update.getReviews());
+ if (update.equals(this))
+ break;
+ }
+
+ return reviews;
+ }
+
+ public void deleteRefs() {
+ Git git = getRequest().getTargetRepo().git();
+ git.deleteRef(getHeadRef(), null, null);
+ }
+
+ public Collection<String> getChangedFiles() {
+ return getCachedInfo().getChangedFiles();
+ }
+
+ public String getBaseCommitHash() {
+ PullRequest request = getRequest();
+
+ int index = request.getSortedUpdates().indexOf(this);
+ if (index > 0)
+ return request.getSortedUpdates().get(index-1).getHeadCommitHash();
+ else
+ return request.getBaseCommitHash();
+ }
+
+ /**
+ * Base commit represents head commit of last update, or base commit of the request
+ * for the first update. Base commit is used to calculate commits belonging to
+ * current update.
+ *
+ * @return
+ * base commit of this update
+ */
+ public Commit getBaseCommit() {
+ PullRequest request = getRequest();
+
+ int index = request.getSortedUpdates().indexOf(this);
+ if (index > 0)
+ return request.getSortedUpdates().get(index-1).getHeadCommit();
+ else
+ return request.getBaseCommit();
+ }
+
+ private CachedInfo getCachedInfo() {
+ if (cachedInfo == null) {
+ Callable<CachedInfo> callable = new Callable<CachedInfo>() {
+
+ @Override
+ public CachedInfo call() throws Exception {
+ CachedInfo cachedInfo = new CachedInfo();
+
+ Repository targetRepo = getRequest().getTargetRepo();
+ Git git = targetRepo.git();
+ List<Commit> log = git.log(getBaseCommitHash(), getHeadCommitHash(), null, 0, 0, false);
+ if (log.isEmpty())
+ log = Lists.newArrayList(targetRepo.getCommit(getHeadCommitHash()));
+ cachedInfo.setLogCommits(log);
+
+ String mergeBase = git.calcMergeBase(getHeadCommitHash(), getRequest().getTarget().getHead());
+
+ if (targetRepo.isAncestor(getBaseCommitHash(), mergeBase)) {
+ cachedInfo.setChangedFiles(git.listChangedFiles(mergeBase, getHeadCommitHash(), null));
+ } else if (targetRepo.isAncestor(mergeBase, getBaseCommitHash())) {
+ cachedInfo.setChangedFiles(git.listChangedFiles(getBaseCommitHash(), getHeadCommitHash(), null));
+ } else {
+ File tempDir = FileUtils.createTempDir();
+ try {
+ Git tempGit = new Git(tempDir);
+
+ /*
+ * Calculate changed files of this update since merged commit of:
+ *
+ * 1. merge base of update head and target branch head
+ * 2. head of previous update
+ *
+ * This way changed files of this update will exclude merged changes
+ * from target branch if there is any.
+ */
+ String branchName = getRequest().getTargetBranch();
+ tempGit.clone(git.repoDir().getAbsolutePath(), false, true, true, branchName);
+ tempGit.updateRef("HEAD", mergeBase, null, null);
+ tempGit.reset(null, null);
+ Preconditions.checkNotNull(tempGit.merge(getBaseCommitHash(), null, null, "ours", null));
+
+ cachedInfo.setChangedFiles(tempGit.listChangedFiles(
+ tempGit.parseRevision("HEAD", true), getHeadCommitHash(), null));
+ } finally {
+ FileUtils.deleteDir(tempDir);
+ }
+ }
+
+ return cachedInfo;
+ }
+
+ };
+ if (isNew()) {
+ try {
+ cachedInfo = callable.call();
+ } catch (Exception e) {
+ Throwables.propagate(e);
+ }
+ } else {
+ StorageManager storageManager = GitPlex.getInstance(StorageManager.class);
+ File cacheFile = new File(storageManager.getCacheDir(this), "cachedInfo");
+ cachedInfo = FileUtils.readFile(cacheFile, callable);
+ }
+ }
+ return cachedInfo;
+ }
+
+ /**
+ * Get commits belonging to this update, ordered by commit id
+ *
+ * @return
+ * commits belonging to this update ordered by commit id
+ */
+ public List<Commit> getCommits() {
+ if (commits == null) {
+ /*
+ * This method calculates all commits belonging to this update. You might think that
+ * the result is obvious, just take log output between last update and current head.
+ * But that result may include noise commits, for instance, if you merges target
+ * branch into source branch to resolve merge conflicts, all commits in target
+ * branch will also appear in log output between last update and current update.
+ * Now, you might suggest that let's just exclude from the log output those commits
+ * being ancestor of target branch. But this still can cause issues as target branch
+ * may merge some intermediate commits from our source branch, and these
+ * intermediate commits will be ancestor of target branch. We certainly do not want
+ * to exclude these intermediate commits as it originally belongs to our source
+ * branch. To solve this contradiction, for those commits belong to both source
+ * branch and target branch, we calculate affinity score of the commit to each
+ * branch, and consider the commit to be belonging to a branch if the associated
+ * affinity score is less.
+ */
+ commits = new ArrayList<>();
+
+ Map<String, ScoreAwareCommit> allCommits = new LinkedHashMap<>();
+ for (Commit commit: getCachedInfo().getLogCommits()) {
+ ScoreAwareCommit scoreAwareCommit = new ScoreAwareCommit();
+ scoreAwareCommit.setCommit(commit);
+ allCommits.put(commit.getHash(), scoreAwareCommit);
+ }
+
+ ScoreAwareCommit headCommit = allCommits.get(getHeadCommitHash());
+ if (headCommit != null) {
+ headCommit.setScore(0);
+ updateAffinityScores(allCommits, headCommit);
+ }
+
+ Map<String, ScoreAwareCommit> mergedCommits = new HashMap<>();
+ for (Commit commit: getRequest().getMergedCommits()) {
+ ScoreAwareCommit scoredCommit = new ScoreAwareCommit();
+ scoredCommit.setCommit(commit);
+ mergedCommits.put(commit.getHash(), scoredCommit);
+ }
+
+ headCommit = mergedCommits.get(getRequest().getTarget().getHead());
+ if (headCommit != null) {
+ headCommit.setScore(0);
+ updateAffinityScores(mergedCommits, headCommit);
+ }
+
+ for (ScoreAwareCommit commit: allCommits.values()) {
+ ScoreAwareCommit mergedCommit = mergedCommits.get(commit.getCommit().getHash());
+ if (mergedCommit == null || mergedCommit.getScore() >= commit.getScore())
+ commits.add(commit.getCommit());
+ }
+
+ getRequest().getTargetRepo().cacheCommits(commits);
+
+ Collections.reverse(commits);
+ }
+ return commits;
+ }
+
+ public Commit getHeadCommit() {
+ Commit headCommit = getCachedInfo().getLogCommits().get(0);
+ Preconditions.checkState(headCommit.getHash().equals(getHeadCommitHash()));
+ return headCommit;
+ }
+
+ /*
+ * This method calculates affinity scores of a set of commits against specified head commit (or branch).
+ * The affinity score reflects the distance between a commit and first-parent chain of the head commit.
+ * For instance, if a commit can be reached recursively via first-parent of the head commit, its
+ * affinity score will be 0.
+ */
+ private void updateAffinityScores(Map<String, ScoreAwareCommit> commits, ScoreAwareCommit headCommit) {
+ Stack<ScoreAwareCommit> stack = new Stack<>();
+ stack.push(headCommit);
+ while (!stack.isEmpty()) {
+ ScoreAwareCommit currentCommit = stack.pop();
+ for (int i=0; i<currentCommit.getCommit().getParentHashes().size(); i++) {
+ String parentCommitHash = currentCommit.getCommit().getParentHashes().get(i);
+ ScoreAwareCommit parentCommit = commits.get(parentCommitHash);
+ if (parentCommit != null && parentCommit.getScore() == Integer.MAX_VALUE) {
+ /*
+ * Parent hashes of a commit is ordered in parent number. For instance first-parent is at index 0.
+ * So the parent score is calculated simply by adding current parent index to the head commit score.
+ */
+ parentCommit.setScore(i + currentCommit.getScore());
+ stack.push(parentCommit);
+ }
+ }
+ }
+ }
+
+ private static class ScoreAwareCommit {
+
+ private Commit commit;
+
+ private int score = Integer.MAX_VALUE;
+
+ public Commit getCommit() {
+ return commit;
+ }
+
+ public void setCommit(Commit commit) {
+ this.commit = commit;
+ }
+
+ public int getScore() {
+ return score;
+ }
+
+ public void setScore(int score) {
+ this.score = score;
+ }
+
+ }
+
+ private static class CachedInfo implements Serializable {
+
+ private Collection<String> changedFiles;
+
+ private List<Commit> logCommits;
+
+ public Collection<String> getChangedFiles() {
+ return changedFiles;
+ }
+
+ public void setChangedFiles(Collection<String> changedFiles) {
+ this.changedFiles = changedFiles;
+ }
+
+ public List<Commit> getLogCommits() {
+ return logCommits;
+ }
+
+ public void setLogCommits(List<Commit> logCommits) {
+ this.logCommits = logCommits;
+ }
+
+ }
+}
diff --git a/gitplex.core/src/main/java/com/pmease/gitplex/core/model/Repository.java b/gitplex.core/src/main/java/com/pmease/gitplex/core/model/Repository.java
index 13ddfd996e..858dc2e00b 100644
--- a/gitplex.core/src/main/java/com/pmease/gitplex/core/model/Repository.java
+++ b/gitplex.core/src/main/java/com/pmease/gitplex/core/model/Repository.java
@@ -1,834 +1,849 @@
-package com.pmease.gitplex.core.model;
-
-import java.io.File;
-import java.io.IOException;
-import java.io.InputStream;
-import java.io.Serializable;
-import java.util.ArrayList;
-import java.util.Collection;
-import java.util.Date;
-import java.util.HashMap;
-import java.util.HashSet;
-import java.util.List;
-import java.util.Map;
-import java.util.Set;
-import java.util.concurrent.ConcurrentHashMap;
-import java.util.concurrent.locks.ReadWriteLock;
-
-import javax.annotation.Nullable;
-import javax.persistence.Column;
-import javax.persistence.Entity;
-import javax.persistence.FetchType;
-import javax.persistence.JoinColumn;
-import javax.persistence.Lob;
-import javax.persistence.ManyToOne;
-import javax.persistence.OneToMany;
-import javax.persistence.Table;
-import javax.persistence.UniqueConstraint;
-import javax.validation.Valid;
-import javax.validation.constraints.NotNull;
-
-import org.apache.commons.lang3.SerializationUtils;
-import org.eclipse.jgit.diff.DiffEntry;
-import org.eclipse.jgit.diff.DiffFormatter;
-import org.eclipse.jgit.errors.RevisionSyntaxException;
-import org.eclipse.jgit.internal.storage.file.FileRepository;
-import org.eclipse.jgit.lib.AnyObjectId;
-import org.eclipse.jgit.lib.Constants;
-import org.eclipse.jgit.lib.FileMode;
-import org.eclipse.jgit.lib.ObjectId;
-import org.eclipse.jgit.lib.ObjectLoader;
-import org.eclipse.jgit.lib.Ref;
-import org.eclipse.jgit.lib.RepositoryCache;
-import org.eclipse.jgit.lib.RepositoryCache.FileKey;
-import org.eclipse.jgit.revwalk.LastCommitsOfChildren;
-import org.eclipse.jgit.revwalk.LastCommitsOfChildren.Value;
-import org.eclipse.jgit.revwalk.RevTree;
-import org.eclipse.jgit.revwalk.RevWalk;
-import org.eclipse.jgit.treewalk.TreeWalk;
-import org.eclipse.jgit.treewalk.filter.OrTreeFilter;
-import org.eclipse.jgit.treewalk.filter.PathFilter;
-import org.eclipse.jgit.treewalk.filter.TreeFilter;
-import org.eclipse.jgit.util.FS;
-import org.eclipse.jgit.util.io.NullOutputStream;
-import org.hibernate.annotations.Cache;
-import org.hibernate.annotations.CacheConcurrencyStrategy;
-import org.hibernate.annotations.OnDelete;
-import org.hibernate.annotations.OnDeleteAction;
-import org.hibernate.validator.constraints.NotEmpty;
-
-import com.google.common.base.Objects;
-import com.google.common.base.Optional;
-import com.google.common.base.Preconditions;
-import com.pmease.commons.git.Blob;
-import com.pmease.commons.git.BlobIdent;
-import com.pmease.commons.git.Commit;
-import com.pmease.commons.git.Git;
-import com.pmease.commons.git.GitUtils;
-import com.pmease.commons.git.Submodule;
-import com.pmease.commons.git.exception.NotFileException;
-import com.pmease.commons.git.exception.ObjectNotExistException;
-import com.pmease.commons.hibernate.AbstractEntity;
-import com.pmease.commons.loader.AppLoader;
-import com.pmease.commons.util.FileUtils;
-import com.pmease.commons.util.LockUtils;
-import com.pmease.commons.util.StringUtils;
-import com.pmease.commons.wicket.editable.annotation.Editable;
-import com.pmease.commons.wicket.editable.annotation.Markdown;
-import com.pmease.gitplex.core.GitPlex;
-import com.pmease.gitplex.core.gatekeeper.AndGateKeeper;
-import com.pmease.gitplex.core.gatekeeper.GateKeeper;
-import com.pmease.gitplex.core.listeners.RefListener;
-import com.pmease.gitplex.core.manager.StorageManager;
-import com.pmease.gitplex.core.permission.object.ProtectedObject;
-import com.pmease.gitplex.core.permission.object.UserBelonging;
-import com.pmease.gitplex.core.validation.RepositoryName;
-
-@Entity
-@Table(uniqueConstraints={@UniqueConstraint(columnNames={"owner", "name"})})
-@Cache(usage=CacheConcurrencyStrategy.READ_WRITE)
-@Editable
-@SuppressWarnings("serial")
-public class Repository extends AbstractEntity implements UserBelonging {
-
- private static final String FQN_SEPARATOR = "/";
-
- public static final String REFS_GITPLEX = "refs/gitplex/";
-
- private static final int LAST_COMMITS_CACHE_THRESHOLD = 1000;
-
- private static final int MAX_READ_BLOB_SIZE = 5*1024*1024;
-
- @ManyToOne(fetch=FetchType.LAZY)
- @JoinColumn(nullable=false)
- private User owner;
-
- @ManyToOne(fetch=FetchType.LAZY)
- @JoinColumn(nullable=true)
- private Repository forkedFrom;
-
- @Column(nullable=false)
- private String name;
-
- private String description;
-
- @Lob
- @Column(nullable=false, length=65535)
- private ArrayList<GateKeeper> gateKeepers = new ArrayList<>();
-
- @Lob
- @Column(nullable=false, length=65535)
- private ArrayList<IntegrationPolicy> integrationPolicies = new ArrayList<>();
-
- @Column(nullable=false)
- private Date createdAt = new Date();
-
- @OneToMany(mappedBy="targetRepo")
- @OnDelete(action=OnDeleteAction.CASCADE)
- private Collection<PullRequest> incomingRequests = new ArrayList<>();
-
- @OneToMany(mappedBy="sourceRepo")
- private Collection<PullRequest> outgoingRequests = new ArrayList<>();
-
- @OneToMany(mappedBy="repository")
- @OnDelete(action=OnDeleteAction.CASCADE)
- private Collection<Authorization> authorizations = new ArrayList<>();
-
- @OneToMany(mappedBy="forkedFrom")
- private Collection<Repository> forks = new ArrayList<>();
-
- private transient Map<BlobIdent, Blob> blobCache;
-
- private transient Map<DiffKey, List<DiffEntry>> diffCache;
-
- private transient Map<String, Commit> commitCache;
-
- private transient Map<String, Optional<ObjectId>> objectIdCache;
-
- private transient Map<String, Map<String, Ref>> refsCache;
-
- private transient Collection<String> branches;
-
- private transient Collection<String> tags;
-
- private transient String defaultBranch;
-
- public User getOwner() {
- return owner;
- }
-
- public void setOwner(User owner) {
- this.owner = owner;
- }
-
- @Editable(order=100, description=
- "Specify name of the repository. It will be used to identify the repository when accessing via Git.")
- @RepositoryName
- @NotEmpty
- public String getName() {
- return name;
- }
-
- public void setName(String name) {
- this.name = name;
- }
-
- @Editable(order=200, description="Specify description of the repository.")
- @Markdown
- public String getDescription() {
- return description;
- }
-
- public void setDescription(String description) {
- this.description = description;
- }
-
- @NotNull
- @Valid
- public List<GateKeeper> getGateKeepers() {
- return gateKeepers;
- }
-
- public void setGateKeepers(ArrayList<GateKeeper> gateKeepers) {
- this.gateKeepers = gateKeepers;
- }
-
- @Valid
- public List<IntegrationPolicy> getIntegrationPolicies() {
- return integrationPolicies;
- }
-
- public void setIntegrationPolicies(ArrayList<IntegrationPolicy> integrationPolicies) {
- this.integrationPolicies = integrationPolicies;
- }
-
- public Date getCreatedAt() {
- return createdAt;
- }
-
- public void setCreatedAt(Date createdAt) {
- this.createdAt = createdAt;
- }
-
- @Override
- public User getUser() {
- return getOwner();
- }
-
- public Collection<PullRequest> getIncomingRequests() {
- return incomingRequests;
- }
-
- public void setIncomingRequests(Collection<PullRequest> incomingRequests) {
- this.incomingRequests = incomingRequests;
- }
-
- public Collection<PullRequest> getOutgoingRequests() {
- return outgoingRequests;
- }
-
- public void setOutgoingRequests(Collection<PullRequest> outgoingRequests) {
- this.outgoingRequests = outgoingRequests;
- }
-
- public Collection<Authorization> getAuthorizations() {
- return authorizations;
- }
-
- public void setAuthorizations(Collection<Authorization> authorizations) {
- this.authorizations = authorizations;
- }
-
- public Repository getForkedFrom() {
- return forkedFrom;
- }
-
- public void setForkedFrom(Repository forkedFrom) {
- this.forkedFrom = forkedFrom;
- }
-
- public Collection<Repository> getForks() {
- return forks;
- }
-
- public void setForks(Collection<Repository> forks) {
- this.forks = forks;
- }
-
- public Collection<String> getBranches() {
- if (branches == null) {
- branches = new ArrayList<>();
- try (FileRepository jgitRepo = openAsJGitRepo()) {
- for (Ref ref: jgitRepo.getRefDatabase().getRefs(Git.REFS_HEADS).values())
- branches.add(GitUtils.ref2branch(ref.getName()));
- } catch (IOException e) {
- throw new RuntimeException(e);
- }
- }
- return branches;
- }
-
- public Collection<String> getTags() {
- if (tags == null) {
- tags = new ArrayList<>();
- try (FileRepository jgitRepo = openAsJGitRepo()) {
- for (Ref ref: jgitRepo.getRefDatabase().getRefs(Git.REFS_TAGS).values())
- tags.add(GitUtils.ref2tag(ref.getName()));
- } catch (IOException e) {
- throw new RuntimeException(e);
- }
- }
- return tags;
- }
-
- @Override
- public boolean has(ProtectedObject object) {
- if (object instanceof Repository) {
- Repository repository = (Repository) object;
- return repository.getId().equals(getId());
- } else {
- return false;
- }
- }
-
- public String getFQN() {
- return getOwner().getName() + FQN_SEPARATOR + getName();
- }
-
- public static String getNameByFQN(String repositoryFQN) {
- return StringUtils.substringAfterLast(repositoryFQN, FQN_SEPARATOR);
- }
-
- public static String getUserNameByFQN(String repositoryFQN) {
- return StringUtils.substringBeforeLast(repositoryFQN, FQN_SEPARATOR);
- }
-
- @Override
- public String toString() {
- return getFQN();
- }
-
- public Git git() {
- return new Git(AppLoader.getInstance(StorageManager.class).getRepoDir(this));
- }
-
- /**
- * Whether or not specified git represents a valid repository git. This can be used to tell
- * apart a GitPlex repository git from some other Git repositories.
- *
- * @return
- * <tt>true</tt> if valid; <tt>false</tt> otherwise
- */
- public boolean isValid() {
- return isUpdateHookValid() && isPostReceiveHookValid();
- }
-
- public boolean isUpdateHookValid() {
- File updateHook = new File(git().repoDir(), "hooks/update");
- if (!updateHook.exists())
- return false;
-
- try {
- String content = FileUtils.readFileToString(updateHook);
- if (!content.contains("GITPLEX_USER_ID"))
- return false;
- } catch (IOException e) {
- throw new RuntimeException(e);
- }
-
- if (!updateHook.canExecute())
- return false;
-
- return true;
- }
-
- public boolean isPostReceiveHookValid() {
- File postReceiveHook = new File(git().repoDir(), "hooks/post-receive");
- if (!postReceiveHook.exists())
- return false;
-
- try {
- String content = FileUtils.readFileToString(postReceiveHook);
- if (!content.contains("GITPLEX_USER_ID"))
- return false;
- } catch (IOException e) {
- throw new RuntimeException(e);
- }
-
- if (!postReceiveHook.canExecute())
- return false;
-
- return true;
- }
-
- public GateKeeper getGateKeeper() {
- AndGateKeeper andGateKeeper = new AndGateKeeper();
- for (GateKeeper each: getGateKeepers())
- andGateKeeper.getGateKeepers().add(each);
- return andGateKeeper;
- }
-
- /**
- * Find fork root of this repository.
- *
- * @return
- * fork root of this repository, or <tt>null</tt> if the repository is not
- * forked from any other repository
- */
- public @Nullable Repository findForkRoot() {
- if (forkedFrom != null) {
- Repository forkedRoot = forkedFrom.findForkRoot();
- if (forkedRoot != null)
- return forkedRoot;
- else
- return forkedFrom;
- } else {
- return null;
- }
- }
-
- /**
- * Find all descendant repositories forking from current repository.
- *
- * @return
- * all descendant repositories forking from current repository
- */
- public List<Repository> findForkDescendants() {
- List<Repository> descendants = new ArrayList<>();
- for (Repository fork: getForks()) {
- descendants.add(fork);
- descendants.addAll(fork.findForkDescendants());
- }
-
- return descendants;
- }
-
- /**
- * Find all comparable repositories of current repository. Comparable repositories can
- * be connected via forks, and can be compared/pulled.
- *
- * @return
- * comparable repositories of current repository, with current repository also
- * included in the collection
- */
- public List<Repository> findAffinals() {
- List<Repository> affinals = new ArrayList<Repository>();
- Repository forkRoot = findForkRoot();
- if (forkRoot != null) {
- affinals.add(forkRoot);
- affinals.addAll(forkRoot.findForkDescendants());
- } else {
- affinals.add(this);
- affinals.addAll(findForkDescendants());
- }
- return affinals;
- }
-
- public String getUrl() {
- return GitPlex.getInstance().guessServerUrl() + "/" + getFQN();
- }
-
- public String getDefaultBranch() {
- if (defaultBranch == null)
- defaultBranch = git().resolveDefaultBranch();
- return defaultBranch;
- }
-
- public String defaultBranchIfNull(@Nullable String revision) {
- if (revision != null)
- return revision;
- else
- return getDefaultBranch();
- }
-
- private Blob readBlob(ObjectLoader objectLoader, BlobIdent ident) {
- long blobSize = objectLoader.getSize();
- if (blobSize > MAX_READ_BLOB_SIZE) {
- try (InputStream is = objectLoader.openStream()) {
- byte[] bytes = new byte[MAX_READ_BLOB_SIZE];
- is.read(bytes);
- return new Blob(ident, bytes, blobSize);
- } catch (IOException e) {
- throw new RuntimeException(e);
- }
- } else {
- return new Blob(ident, objectLoader.getCachedBytes());
- }
- }
-
- private Map<BlobIdent, Blob> getBlobCache() {
- if (blobCache == null) {
- synchronized(this) {
- if (blobCache == null)
- blobCache = new ConcurrentHashMap<>();
- }
- }
- return blobCache;
- }
-
- /**
- * Read blob content and cache result in repository in case the same blob
- * content is requested again.
- *
- * We made this method thread-safe as we are using ForkJoinPool to calculate
- * diffs of multiple blob changes concurrently, and this method will be
- * accessed concurrently in that special case.
- *
- * @param blobIdent
- * ident of the blob
- * @return
- * blob of specified blob ident
- * @throws
- * ObjectNotExistException if blob of specified ident can not be found in repository
- *
- */
- public Blob getBlob(BlobIdent blobIdent) {
- Preconditions.checkArgument(blobIdent.revision!=null && blobIdent.path!=null && blobIdent.mode!=null,
- "Revision, path and mode of ident param should be specified");
-
- Blob blob = getBlobCache().get(blobIdent);
- if (blob == null) {
- if (blobIdent.id != null) {
- try (FileRepository jgitRepo = openAsJGitRepo()) {
- if (blobIdent.isGitLink()) {
- String url = getSubmodules(blobIdent.revision).get(blobIdent.path);
- if (url == null)
- throw new ObjectNotExistException("Unable to find submodule '" + blobIdent.path + "' in .gitmodules");
- blob = new Blob(blobIdent, new Submodule(url, blobIdent.id).toString().getBytes());
- } else if (blobIdent.isTree()) {
- throw new NotFileException("Path '" + blobIdent.path + "' is a tree");
- } else {
- ObjectLoader objectLoader = jgitRepo.open(ObjectId.fromString(blobIdent.id), Constants.OBJ_BLOB);
- blob = readBlob(objectLoader, blobIdent);
- }
- getBlobCache().put(blobIdent, blob);
- } catch (IOException e) {
- throw new RuntimeException(e);
- }
- } else {
- try (FileRepository jgitRepo = openAsJGitRepo(); RevWalk revWalk = new RevWalk(jgitRepo)) {
- ObjectId commitId = getObjectId(blobIdent.revision);
- RevTree revTree = revWalk.parseCommit(commitId).getTree();
- TreeWalk treeWalk = TreeWalk.forPath(jgitRepo, blobIdent.path, revTree);
- if (treeWalk != null) {
- if (blobIdent.isGitLink()) {
- String url = getSubmodules(blobIdent.revision).get(blobIdent.path);
- if (url == null)
- throw new ObjectNotExistException("Unable to find submodule '" + blobIdent.path + "' in .gitmodules");
- String hash = treeWalk.getObjectId(0).name();
- blob = new Blob(blobIdent, new Submodule(url, hash).toString().getBytes());
- } else if (blobIdent.isTree()) {
- throw new NotFileException("Path '" + blobIdent.path + "' is a tree");
- } else {
- ObjectLoader objectLoader = treeWalk.getObjectReader().open(treeWalk.getObjectId(0));
- blob = readBlob(objectLoader, blobIdent);
- }
- getBlobCache().put(blobIdent, blob);
- } else {
- throw new ObjectNotExistException("Unable to find blob path '" + blobIdent.path + "' in revision '" + blobIdent.revision + "'");
- }
- } catch (IOException e) {
- throw new RuntimeException(e);
- }
- }
- }
- return blob;
- }
-
- public InputStream getInputStream(BlobIdent ident) {
- try (FileRepository jgitRepo = openAsJGitRepo(); RevWalk revWalk = new RevWalk(jgitRepo)) {
- ObjectId commitId = getObjectId(ident.revision);
- RevTree revTree = revWalk.parseCommit(commitId).getTree();
- TreeWalk treeWalk = TreeWalk.forPath(jgitRepo, ident.path, revTree);
- if (treeWalk != null) {
- ObjectLoader objectLoader = treeWalk.getObjectReader().open(treeWalk.getObjectId(0));
- return objectLoader.openStream();
- } else {
- throw new ObjectNotExistException("Unable to find blob path '" + ident.path + "' in revision '" + ident.revision + "'");
- }
- } catch (IOException e) {
- throw new RuntimeException(e);
- }
- }
-
- /**
- * Get cached object id of specified revision.
- *
- * @param revision
- * revision to resolve object id for
- * @param mustExist
- * true to have the method throwing exception instead
- * of returning null if the revision does not exist
- * @return
- * object id of specified revision, or <tt>null</tt> if revision
- * does not exist and mustExist is specified as false
- */
- @Nullable
- public ObjectId getObjectId(String revision, boolean mustExist) {
- if (objectIdCache == null)
- objectIdCache = new HashMap<>();
-
- Optional<ObjectId> optional = objectIdCache.get(revision);
- if (optional == null) {
- ObjectId objectId;
- if (GitUtils.isHash(revision)) {
- objectId = ObjectId.fromString(revision);
- } else {
- try (FileRepository jgitRepo = openAsJGitRepo()) {
- objectId = jgitRepo.resolve(revision);
- } catch (RevisionSyntaxException | IOException e) {
- throw new RuntimeException(e);
- }
- }
- optional = Optional.fromNullable(objectId);
- objectIdCache.put(revision, optional);
- }
- if (mustExist && !optional.isPresent())
- throw new ObjectNotExistException("Unable to find revision '" + revision + "'");
- return optional.orNull();
- }
-
- public ObjectId getObjectId(String revision) {
- return getObjectId(revision, true);
- }
-
- public void cacheObjectId(String revision, @Nullable ObjectId objectId) {
- if (objectIdCache == null)
- objectIdCache = new HashMap<>();
-
- objectIdCache.put(revision, Optional.fromNullable(objectId));
- }
-
- public List<DiffEntry> getDiffs(String oldRev, String newRev, boolean detectRenames, String...paths) {
- if (diffCache == null)
- diffCache = new HashMap<>();
-
- DiffKey key = new DiffKey(oldRev, newRev, detectRenames, paths);
- List<DiffEntry> diffs = diffCache.get(key);
- if (diffs == null) {
- try ( FileRepository jgitRepo = openAsJGitRepo();
- DiffFormatter diffFormatter = new DiffFormatter(NullOutputStream.INSTANCE);) {
- diffFormatter.setRepository(jgitRepo);
- diffFormatter.setDetectRenames(detectRenames);
- AnyObjectId oldCommitId = getObjectId(oldRev);
- AnyObjectId newCommitId = getObjectId(newRev);
- if (paths.length >= 2) {
- List<TreeFilter> pathFilters = new ArrayList<>();
- for (String path: paths)
- pathFilters.add(PathFilter.create(path));
- diffFormatter.setPathFilter(OrTreeFilter.create(pathFilters));
- } else if (paths.length == 1) {
- diffFormatter.setPathFilter(PathFilter.create(paths[0]));
- }
- diffs = new ArrayList<>();
- for (DiffEntry entry: diffFormatter.scan(oldCommitId, newCommitId)) {
- if (!Objects.equal(entry.getOldPath(), entry.getNewPath())
- || !Objects.equal(entry.getOldMode(), entry.getNewMode())
- || entry.getOldId()==null || !entry.getOldId().isComplete()
- || entry.getNewId()== null || !entry.getNewId().isComplete()
- || !entry.getOldId().equals(entry.getNewId())) {
- diffs.add(entry);
- }
- }
- } catch (IOException e) {
- throw new RuntimeException(e);
- }
- diffCache.put(key, diffs);
- }
- return diffs;
- }
-
- public Commit getCommit(String commitHash) {
- if (commitCache == null)
- commitCache = new HashMap<>();
-
- Commit commit = commitCache.get(commitHash);
- if (commit == null) {
- commit = git().showRevision(commitHash);
- commitCache.put(commitHash, commit);
- }
- return commit;
- }
-
- public void cacheCommits(List<Commit> commits) {
- if (commitCache == null)
- commitCache = new HashMap<>();
-
- for (Commit commit: commits)
- commitCache.put(commit.getHash(), commit);
- }
-
- public FileRepository openAsJGitRepo() {
- try {
- return (FileRepository) RepositoryCache.open(FileKey.lenient(git().repoDir(), FS.DETECTED), true);
- } catch (IOException e) {
- throw new RuntimeException(e);
- }
- }
-
- public LastCommitsOfChildren getLastCommitsOfChildren(String revision, @Nullable String path) {
- if (path == null)
- path = "";
-
- final File cacheDir = new File(
- GitPlex.getInstance(StorageManager.class).getCacheDir(this),
- "last_commits/" + path + "/gitplex_last_commits");
-
- final ReadWriteLock lock;
- try {
- lock = LockUtils.getReadWriteLock(cacheDir.getCanonicalPath());
- } catch (IOException e) {
- throw new RuntimeException(e);
- }
-
- final Set<ObjectId> commitIds = new HashSet<>();
-
- lock.readLock().lock();
- try {
- if (cacheDir.exists()) {
- for (String each: cacheDir.list())
- commitIds.add(ObjectId.fromString(each));
- }
- } finally {
- lock.readLock().unlock();
- }
-
- org.eclipse.jgit.revwalk.LastCommitsOfChildren.Cache cache;
- if (!commitIds.isEmpty()) {
- cache = new org.eclipse.jgit.revwalk.LastCommitsOfChildren.Cache() {
-
- @SuppressWarnings("unchecked")
- @Override
- public Map<String, Value> getLastCommitsOfChildren(ObjectId commitId) {
- if (commitIds.contains(commitId)) {
- lock.readLock().lock();
- try {
- byte[] bytes = FileUtils.readFileToByteArray(new File(cacheDir, commitId.name()));
- return (Map<String, Value>) SerializationUtils.deserialize(bytes);
- } catch (IOException e) {
- throw new RuntimeException(e);
- } finally {
- lock.readLock().unlock();
- }
- } else {
- return null;
- }
- }
-
- };
- } else {
- cache = null;
- }
-
- final AnyObjectId commitId = getObjectId(revision);
-
- try (FileRepository jgitRepo = openAsJGitRepo()) {
- long time = System.currentTimeMillis();
- LastCommitsOfChildren lastCommits = new LastCommitsOfChildren(jgitRepo, commitId, path, cache);
- long elapsed = System.currentTimeMillis()-time;
- if (elapsed > LAST_COMMITS_CACHE_THRESHOLD) {
- lock.writeLock().lock();
- try {
- if (!cacheDir.exists())
- FileUtils.createDir(cacheDir);
- FileUtils.writeByteArrayToFile(
- new File(cacheDir, commitId.name()),
- SerializationUtils.serialize(lastCommits));
- } catch (IOException e) {
- throw new RuntimeException(e);
- } finally {
- lock.writeLock().unlock();
- }
- }
- return lastCommits;
- }
- }
-
- public Map<String, Ref> getRefs(String prefix) {
- if (refsCache == null)
- refsCache = new HashMap<>();
-
- Map<String, Ref> cached = refsCache.get(prefix);
- if (cached == null) {
- try (FileRepository jgitRepo = openAsJGitRepo()) {
- cached = jgitRepo.getRefDatabase().getRefs(prefix);
- refsCache.put(prefix, cached);
- } catch (IOException e) {
- throw new RuntimeException(e);
- }
- }
- return cached;
- }
-
- public Map<String, String> getSubmodules(String revision) {
- Map<String, String> submodules = new HashMap<>();
-
- Blob blob = getBlob(new BlobIdent(revision, ".gitmodules", FileMode.REGULAR_FILE.getBits()));
- String content = new String(blob.getBytes());
-
- String path = null;
- String url = null;
-
- for (String line: StringUtils.splitAndTrim(content, "\r\n")) {
- if (line.startsWith("[") && line.endsWith("]")) {
- if (path != null && url != null)
- submodules.put(path, url);
-
- path = url = null;
- } else if (line.startsWith("path")) {
- path = StringUtils.substringAfter(line, "=").trim();
- } else if (line.startsWith("url")) {
- url = StringUtils.substringAfter(line, "=").trim();
- }
- }
- if (path != null && url != null)
- submodules.put(path, url);
-
- return submodules;
- }
-
- public String getBranchFQN(String branch) {
- return getFQN() + ":" + branch;
- }
-
- public void deleteBranch(String branch) {
- git().deleteBranch(branch);
- for (RefListener listener: GitPlex.getExtensions(RefListener.class))
- listener.onRefUpdate(this, GitUtils.branch2ref(branch), null);
- }
-
- private static class DiffKey implements Serializable {
- String oldRev;
-
- String newRev;
-
- String[] paths;
-
- boolean detectRenames;
-
- DiffKey(String oldRev, String newRev, boolean detectRenames, String...paths) {
- this.oldRev = oldRev;
- this.newRev = newRev;
- this.detectRenames = detectRenames;
- this.paths = paths;
- }
-
- public boolean equals(Object other) {
- if (!(other instanceof DiffKey))
- return false;
- if (this == other)
- return true;
- DiffKey otherKey = (DiffKey) other;
- return Objects.equal(oldRev, otherKey.oldRev)
- && Objects.equal(newRev, otherKey.newRev)
- && Objects.equal(paths, otherKey.paths)
- && Objects.equal(detectRenames, otherKey.detectRenames);
- }
-
- public int hashCode() {
- return Objects.hashCode(oldRev, newRev, paths, detectRenames);
- }
-
- }
-
-}
+package com.pmease.gitplex.core.model;
+
+import java.io.File;
+import java.io.IOException;
+import java.io.InputStream;
+import java.io.Serializable;
+import java.util.ArrayList;
+import java.util.Collection;
+import java.util.Date;
+import java.util.HashMap;
+import java.util.HashSet;
+import java.util.List;
+import java.util.Map;
+import java.util.Set;
+import java.util.concurrent.ConcurrentHashMap;
+import java.util.concurrent.locks.ReadWriteLock;
+
+import javax.annotation.Nullable;
+import javax.persistence.Column;
+import javax.persistence.Entity;
+import javax.persistence.FetchType;
+import javax.persistence.JoinColumn;
+import javax.persistence.Lob;
+import javax.persistence.ManyToOne;
+import javax.persistence.OneToMany;
+import javax.persistence.Table;
+import javax.persistence.UniqueConstraint;
+import javax.validation.Valid;
+import javax.validation.constraints.NotNull;
+
+import org.apache.commons.lang3.SerializationUtils;
+import org.eclipse.jgit.diff.DiffEntry;
+import org.eclipse.jgit.diff.DiffFormatter;
+import org.eclipse.jgit.errors.RevisionSyntaxException;
+import org.eclipse.jgit.internal.storage.file.FileRepository;
+import org.eclipse.jgit.lib.AnyObjectId;
+import org.eclipse.jgit.lib.Constants;
+import org.eclipse.jgit.lib.FileMode;
+import org.eclipse.jgit.lib.ObjectId;
+import org.eclipse.jgit.lib.ObjectLoader;
+import org.eclipse.jgit.lib.Ref;
+import org.eclipse.jgit.lib.RepositoryCache;
+import org.eclipse.jgit.lib.RepositoryCache.FileKey;
+import org.eclipse.jgit.revwalk.LastCommitsOfChildren;
+import org.eclipse.jgit.revwalk.LastCommitsOfChildren.Value;
+import org.eclipse.jgit.revwalk.RevTree;
+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.OrTreeFilter;
+import org.eclipse.jgit.treewalk.filter.PathFilter;
+import org.eclipse.jgit.treewalk.filter.TreeFilter;
+import org.eclipse.jgit.util.FS;
+import org.eclipse.jgit.util.io.NullOutputStream;
+import org.hibernate.annotations.Cache;
+import org.hibernate.annotations.CacheConcurrencyStrategy;
+import org.hibernate.annotations.OnDelete;
+import org.hibernate.annotations.OnDeleteAction;
+import org.hibernate.validator.constraints.NotEmpty;
+
+import com.google.common.base.Objects;
+import com.google.common.base.Optional;
+import com.google.common.base.Preconditions;
+import com.pmease.commons.git.Blob;
+import com.pmease.commons.git.BlobIdent;
+import com.pmease.commons.git.Commit;
+import com.pmease.commons.git.Git;
+import com.pmease.commons.git.GitUtils;
+import com.pmease.commons.git.Submodule;
+import com.pmease.commons.git.exception.NotFileException;
+import com.pmease.commons.git.exception.ObjectNotExistException;
+import com.pmease.commons.hibernate.AbstractEntity;
+import com.pmease.commons.loader.AppLoader;
+import com.pmease.commons.util.FileUtils;
+import com.pmease.commons.util.LockUtils;
+import com.pmease.commons.util.StringUtils;
+import com.pmease.commons.wicket.editable.annotation.Editable;
+import com.pmease.commons.wicket.editable.annotation.Markdown;
+import com.pmease.gitplex.core.GitPlex;
+import com.pmease.gitplex.core.gatekeeper.AndGateKeeper;
+import com.pmease.gitplex.core.gatekeeper.GateKeeper;
+import com.pmease.gitplex.core.listeners.RefListener;
+import com.pmease.gitplex.core.manager.StorageManager;
+import com.pmease.gitplex.core.permission.object.ProtectedObject;
+import com.pmease.gitplex.core.permission.object.UserBelonging;
+import com.pmease.gitplex.core.validation.RepositoryName;
+
+@Entity
+@Table(uniqueConstraints={@UniqueConstraint(columnNames={"owner", "name"})})
+@Cache(usage=CacheConcurrencyStrategy.READ_WRITE)
+@Editable
+@SuppressWarnings("serial")
+public class Repository extends AbstractEntity implements UserBelonging {
+
+ private static final String FQN_SEPARATOR = "/";
+
+ public static final String REFS_GITPLEX = "refs/gitplex/";
+
+ private static final int LAST_COMMITS_CACHE_THRESHOLD = 1000;
+
+ private static final int MAX_READ_BLOB_SIZE = 5*1024*1024;
+
+ @ManyToOne(fetch=FetchType.LAZY)
+ @JoinColumn(nullable=false)
+ private User owner;
+
+ @ManyToOne(fetch=FetchType.LAZY)
+ @JoinColumn(nullable=true)
+ private Repository forkedFrom;
+
+ @Column(nullable=false)
+ private String name;
+
+ private String description;
+
+ @Lob
+ @Column(nullable=false, length=65535)
+ private ArrayList<GateKeeper> gateKeepers = new ArrayList<>();
+
+ @Lob
+ @Column(nullable=false, length=65535)
+ private ArrayList<IntegrationPolicy> integrationPolicies = new ArrayList<>();
+
+ @Column(nullable=false)
+ private Date createdAt = new Date();
+
+ @OneToMany(mappedBy="targetRepo")
+ @OnDelete(action=OnDeleteAction.CASCADE)
+ private Collection<PullRequest> incomingRequests = new ArrayList<>();
+
+ @OneToMany(mappedBy="sourceRepo")
+ private Collection<PullRequest> outgoingRequests = new ArrayList<>();
+
+ @OneToMany(mappedBy="repository")
+ @OnDelete(action=OnDeleteAction.CASCADE)
+ private Collection<Authorization> authorizations = new ArrayList<>();
+
+ @OneToMany(mappedBy="forkedFrom")
+ private Collection<Repository> forks = new ArrayList<>();
+
+ private transient Map<BlobIdent, Blob> blobCache;
+
+ private transient Map<DiffKey, List<DiffEntry>> diffCache;
+
+ private transient Map<String, Commit> commitCache;
+
+ private transient Map<String, Optional<ObjectId>> objectIdCache;
+
+ private transient Map<String, Map<String, Ref>> refsCache;
+
+ private transient Collection<String> branches;
+
+ private transient Collection<String> tags;
+
+ private transient String defaultBranch;
+
+ public User getOwner() {
+ return owner;
+ }
+
+ public void setOwner(User owner) {
+ this.owner = owner;
+ }
+
+ @Editable(order=100, description=
+ "Specify name of the repository. It will be used to identify the repository when accessing via Git.")
+ @RepositoryName
+ @NotEmpty
+ public String getName() {
+ return name;
+ }
+
+ public void setName(String name) {
+ this.name = name;
+ }
+
+ @Editable(order=200, description="Specify description of the repository.")
+ @Markdown
+ public String getDescription() {
+ return description;
+ }
+
+ public void setDescription(String description) {
+ this.description = description;
+ }
+
+ @NotNull
+ @Valid
+ public List<GateKeeper> getGateKeepers() {
+ return gateKeepers;
+ }
+
+ public void setGateKeepers(ArrayList<GateKeeper> gateKeepers) {
+ this.gateKeepers = gateKeepers;
+ }
+
+ @Valid
+ public List<IntegrationPolicy> getIntegrationPolicies() {
+ return integrationPolicies;
+ }
+
+ public void setIntegrationPolicies(ArrayList<IntegrationPolicy> integrationPolicies) {
+ this.integrationPolicies = integrationPolicies;
+ }
+
+ public Date getCreatedAt() {
+ return createdAt;
+ }
+
+ public void setCreatedAt(Date createdAt) {
+ this.createdAt = createdAt;
+ }
+
+ @Override
+ public User getUser() {
+ return getOwner();
+ }
+
+ public Collection<PullRequest> getIncomingRequests() {
+ return incomingRequests;
+ }
+
+ public void setIncomingRequests(Collection<PullRequest> incomingRequests) {
+ this.incomingRequests = incomingRequests;
+ }
+
+ public Collection<PullRequest> getOutgoingRequests() {
+ return outgoingRequests;
+ }
+
+ public void setOutgoingRequests(Collection<PullRequest> outgoingRequests) {
+ this.outgoingRequests = outgoingRequests;
+ }
+
+ public Collection<Authorization> getAuthorizations() {
+ return authorizations;
+ }
+
+ public void setAuthorizations(Collection<Authorization> authorizations) {
+ this.authorizations = authorizations;
+ }
+
+ public Repository getForkedFrom() {
+ return forkedFrom;
+ }
+
+ public void setForkedFrom(Repository forkedFrom) {
+ this.forkedFrom = forkedFrom;
+ }
+
+ public Collection<Repository> getForks() {
+ return forks;
+ }
+
+ public void setForks(Collection<Repository> forks) {
+ this.forks = forks;
+ }
+
+ public Collection<String> getBranches() {
+ if (branches == null) {
+ branches = new ArrayList<>();
+ try (FileRepository jgitRepo = openAsJGitRepo()) {
+ for (Ref ref: jgitRepo.getRefDatabase().getRefs(Git.REFS_HEADS).values())
+ branches.add(GitUtils.ref2branch(ref.getName()));
+ } catch (IOException e) {
+ throw new RuntimeException(e);
+ }
+ }
+ return branches;
+ }
+
+ public Collection<String> getTags() {
+ if (tags == null) {
+ tags = new ArrayList<>();
+ try (FileRepository jgitRepo = openAsJGitRepo()) {
+ for (Ref ref: jgitRepo.getRefDatabase().getRefs(Git.REFS_TAGS).values())
+ tags.add(GitUtils.ref2tag(ref.getName()));
+ } catch (IOException e) {
+ throw new RuntimeException(e);
+ }
+ }
+ return tags;
+ }
+
+ @Override
+ public boolean has(ProtectedObject object) {
+ if (object instanceof Repository) {
+ Repository repository = (Repository) object;
+ return repository.getId().equals(getId());
+ } else {
+ return false;
+ }
+ }
+
+ public String getFQN() {
+ return getOwner().getName() + FQN_SEPARATOR + getName();
+ }
+
+ public static String getNameByFQN(String repositoryFQN) {
+ return StringUtils.substringAfterLast(repositoryFQN, FQN_SEPARATOR);
+ }
+
+ public static String getUserNameByFQN(String repositoryFQN) {
+ return StringUtils.substringBeforeLast(repositoryFQN, FQN_SEPARATOR);
+ }
+
+ @Override
+ public String toString() {
+ return getFQN();
+ }
+
+ public Git git() {
+ return new Git(AppLoader.getInstance(StorageManager.class).getRepoDir(this));
+ }
+
+ /**
+ * Whether or not specified git represents a valid repository git. This can be used to tell
+ * apart a GitPlex repository git from some other Git repositories.
+ *
+ * @return
+ * <tt>true</tt> if valid; <tt>false</tt> otherwise
+ */
+ public boolean isValid() {
+ return isUpdateHookValid() && isPostReceiveHookValid();
+ }
+
+ public boolean isUpdateHookValid() {
+ File updateHook = new File(git().repoDir(), "hooks/update");
+ if (!updateHook.exists())
+ return false;
+
+ try {
+ String content = FileUtils.readFileToString(updateHook);
+ if (!content.contains("GITPLEX_USER_ID"))
+ return false;
+ } catch (IOException e) {
+ throw new RuntimeException(e);
+ }
+
+ if (!updateHook.canExecute())
+ return false;
+
+ return true;
+ }
+
+ public boolean isPostReceiveHookValid() {
+ File postReceiveHook = new File(git().repoDir(), "hooks/post-receive");
+ if (!postReceiveHook.exists())
+ return false;
+
+ try {
+ String content = FileUtils.readFileToString(postReceiveHook);
+ if (!content.contains("GITPLEX_USER_ID"))
+ return false;
+ } catch (IOException e) {
+ throw new RuntimeException(e);
+ }
+
+ if (!postReceiveHook.canExecute())
+ return false;
+
+ return true;
+ }
+
+ public GateKeeper getGateKeeper() {
+ AndGateKeeper andGateKeeper = new AndGateKeeper();
+ for (GateKeeper each: getGateKeepers())
+ andGateKeeper.getGateKeepers().add(each);
+ return andGateKeeper;
+ }
+
+ /**
+ * Find fork root of this repository.
+ *
+ * @return
+ * fork root of this repository, or <tt>null</tt> if the repository is not
+ * forked from any other repository
+ */
+ public @Nullable Repository findForkRoot() {
+ if (forkedFrom != null) {
+ Repository forkedRoot = forkedFrom.findForkRoot();
+ if (forkedRoot != null)
+ return forkedRoot;
+ else
+ return forkedFrom;
+ } else {
+ return null;
+ }
+ }
+
+ /**
+ * Find all descendant repositories forking from current repository.
+ *
+ * @return
+ * all descendant repositories forking from current repository
+ */
+ public List<Repository> findForkDescendants() {
+ List<Repository> descendants = new ArrayList<>();
+ for (Repository fork: getForks()) {
+ descendants.add(fork);
+ descendants.addAll(fork.findForkDescendants());
+ }
+
+ return descendants;
+ }
+
+ /**
+ * Find all comparable repositories of current repository. Comparable repositories can
+ * be connected via forks, and can be compared/pulled.
+ *
+ * @return
+ * comparable repositories of current repository, with current repository also
+ * included in the collection
+ */
+ public List<Repository> findAffinals() {
+ List<Repository> affinals = new ArrayList<Repository>();
+ Repository forkRoot = findForkRoot();
+ if (forkRoot != null) {
+ affinals.add(forkRoot);
+ affinals.addAll(forkRoot.findForkDescendants());
+ } else {
+ affinals.add(this);
+ affinals.addAll(findForkDescendants());
+ }
+ return affinals;
+ }
+
+ public boolean isAncestor(String ancestor, String descendant) {
+ try ( FileRepository jgitRepo = openAsJGitRepo();
+ RevWalk walk = new RevWalk(jgitRepo);) {
+ walk.setRevFilter(RevFilter.MERGE_BASE);
+ ObjectId ancestorId = getObjectId(ancestor);
+ walk.markStart(walk.lookupCommit(ancestorId));
+ ObjectId descendantId = getObjectId(descendant);
+ walk.markStart(walk.lookupCommit(descendantId));
+ return walk.next().name().equals(ancestorId.name());
+ } catch (IOException e) {
+ throw new RuntimeException(e);
+ }
+ }
+
+ public String getUrl() {
+ return GitPlex.getInstance().guessServerUrl() + "/" + getFQN();
+ }
+
+ public String getDefaultBranch() {
+ if (defaultBranch == null)
+ defaultBranch = git().resolveDefaultBranch();
+ return defaultBranch;
+ }
+
+ public String defaultBranchIfNull(@Nullable String revision) {
+ if (revision != null)
+ return revision;
+ else
+ return getDefaultBranch();
+ }
+
+ private Blob readBlob(ObjectLoader objectLoader, BlobIdent ident) {
+ long blobSize = objectLoader.getSize();
+ if (blobSize > MAX_READ_BLOB_SIZE) {
+ try (InputStream is = objectLoader.openStream()) {
+ byte[] bytes = new byte[MAX_READ_BLOB_SIZE];
+ is.read(bytes);
+ return new Blob(ident, bytes, blobSize);
+ } catch (IOException e) {
+ throw new RuntimeException(e);
+ }
+ } else {
+ return new Blob(ident, objectLoader.getCachedBytes());
+ }
+ }
+
+ private Map<BlobIdent, Blob> getBlobCache() {
+ if (blobCache == null) {
+ synchronized(this) {
+ if (blobCache == null)
+ blobCache = new ConcurrentHashMap<>();
+ }
+ }
+ return blobCache;
+ }
+
+ /**
+ * Read blob content and cache result in repository in case the same blob
+ * content is requested again.
+ *
+ * We made this method thread-safe as we are using ForkJoinPool to calculate
+ * diffs of multiple blob changes concurrently, and this method will be
+ * accessed concurrently in that special case.
+ *
+ * @param blobIdent
+ * ident of the blob
+ * @return
+ * blob of specified blob ident
+ * @throws
+ * ObjectNotExistException if blob of specified ident can not be found in repository
+ *
+ */
+ public Blob getBlob(BlobIdent blobIdent) {
+ Preconditions.checkArgument(blobIdent.revision!=null && blobIdent.path!=null && blobIdent.mode!=null,
+ "Revision, path and mode of ident param should be specified");
+
+ Blob blob = getBlobCache().get(blobIdent);
+ if (blob == null) {
+ if (blobIdent.id != null) {
+ try (FileRepository jgitRepo = openAsJGitRepo()) {
+ if (blobIdent.isGitLink()) {
+ String url = getSubmodules(blobIdent.revision).get(blobIdent.path);
+ if (url == null)
+ throw new ObjectNotExistException("Unable to find submodule '" + blobIdent.path + "' in .gitmodules");
+ blob = new Blob(blobIdent, new Submodule(url, blobIdent.id).toString().getBytes());
+ } else if (blobIdent.isTree()) {
+ throw new NotFileException("Path '" + blobIdent.path + "' is a tree");
+ } else {
+ ObjectLoader objectLoader = jgitRepo.open(ObjectId.fromString(blobIdent.id), Constants.OBJ_BLOB);
+ blob = readBlob(objectLoader, blobIdent);
+ }
+ getBlobCache().put(blobIdent, blob);
+ } catch (IOException e) {
+ throw new RuntimeException(e);
+ }
+ } else {
+ try (FileRepository jgitRepo = openAsJGitRepo(); RevWalk revWalk = new RevWalk(jgitRepo)) {
+ ObjectId commitId = getObjectId(blobIdent.revision);
+ RevTree revTree = revWalk.parseCommit(commitId).getTree();
+ TreeWalk treeWalk = TreeWalk.forPath(jgitRepo, blobIdent.path, revTree);
+ if (treeWalk != null) {
+ if (blobIdent.isGitLink()) {
+ String url = getSubmodules(blobIdent.revision).get(blobIdent.path);
+ if (url == null)
+ throw new ObjectNotExistException("Unable to find submodule '" + blobIdent.path + "' in .gitmodules");
+ String hash = treeWalk.getObjectId(0).name();
+ blob = new Blob(blobIdent, new Submodule(url, hash).toString().getBytes());
+ } else if (blobIdent.isTree()) {
+ throw new NotFileException("Path '" + blobIdent.path + "' is a tree");
+ } else {
+ ObjectLoader objectLoader = treeWalk.getObjectReader().open(treeWalk.getObjectId(0));
+ blob = readBlob(objectLoader, blobIdent);
+ }
+ getBlobCache().put(blobIdent, blob);
+ } else {
+ throw new ObjectNotExistException("Unable to find blob path '" + blobIdent.path + "' in revision '" + blobIdent.revision + "'");
+ }
+ } catch (IOException e) {
+ throw new RuntimeException(e);
+ }
+ }
+ }
+ return blob;
+ }
+
+ public InputStream getInputStream(BlobIdent ident) {
+ try (FileRepository jgitRepo = openAsJGitRepo(); RevWalk revWalk = new RevWalk(jgitRepo)) {
+ ObjectId commitId = getObjectId(ident.revision);
+ RevTree revTree = revWalk.parseCommit(commitId).getTree();
+ TreeWalk treeWalk = TreeWalk.forPath(jgitRepo, ident.path, revTree);
+ if (treeWalk != null) {
+ ObjectLoader objectLoader = treeWalk.getObjectReader().open(treeWalk.getObjectId(0));
+ return objectLoader.openStream();
+ } else {
+ throw new ObjectNotExistException("Unable to find blob path '" + ident.path + "' in revision '" + ident.revision + "'");
+ }
+ } catch (IOException e) {
+ throw new RuntimeException(e);
+ }
+ }
+
+ /**
+ * Get cached object id of specified revision.
+ *
+ * @param revision
+ * revision to resolve object id for
+ * @param mustExist
+ * true to have the method throwing exception instead
+ * of returning null if the revision does not exist
+ * @return
+ * object id of specified revision, or <tt>null</tt> if revision
+ * does not exist and mustExist is specified as false
+ */
+ @Nullable
+ public ObjectId getObjectId(String revision, boolean mustExist) {
+ if (objectIdCache == null)
+ objectIdCache = new HashMap<>();
+
+ Optional<ObjectId> optional = objectIdCache.get(revision);
+ if (optional == null) {
+ ObjectId objectId;
+ if (GitUtils.isHash(revision)) {
+ objectId = ObjectId.fromString(revision);
+ } else {
+ try (FileRepository jgitRepo = openAsJGitRepo()) {
+ objectId = jgitRepo.resolve(revision);
+ } catch (RevisionSyntaxException | IOException e) {
+ throw new RuntimeException(e);
+ }
+ }
+ optional = Optional.fromNullable(objectId);
+ objectIdCache.put(revision, optional);
+ }
+ if (mustExist && !optional.isPresent())
+ throw new ObjectNotExistException("Unable to find revision '" + revision + "'");
+ return optional.orNull();
+ }
+
+ public ObjectId getObjectId(String revision) {
+ return getObjectId(revision, true);
+ }
+
+ public void cacheObjectId(String revision, @Nullable ObjectId objectId) {
+ if (objectIdCache == null)
+ objectIdCache = new HashMap<>();
+
+ objectIdCache.put(revision, Optional.fromNullable(objectId));
+ }
+
+ public List<DiffEntry> getDiffs(String oldRev, String newRev, boolean detectRenames, String...paths) {
+ if (diffCache == null)
+ diffCache = new HashMap<>();
+
+ DiffKey key = new DiffKey(oldRev, newRev, detectRenames, paths);
+ List<DiffEntry> diffs = diffCache.get(key);
+ if (diffs == null) {
+ try ( FileRepository jgitRepo = openAsJGitRepo();
+ DiffFormatter diffFormatter = new DiffFormatter(NullOutputStream.INSTANCE);) {
+ diffFormatter.setRepository(jgitRepo);
+ diffFormatter.setDetectRenames(detectRenames);
+ AnyObjectId oldCommitId = getObjectId(oldRev);
+ AnyObjectId newCommitId = getObjectId(newRev);
+ if (paths.length >= 2) {
+ List<TreeFilter> pathFilters = new ArrayList<>();
+ for (String path: paths)
+ pathFilters.add(PathFilter.create(path));
+ diffFormatter.setPathFilter(OrTreeFilter.create(pathFilters));
+ } else if (paths.length == 1) {
+ diffFormatter.setPathFilter(PathFilter.create(paths[0]));
+ }
+ diffs = new ArrayList<>();
+ for (DiffEntry entry: diffFormatter.scan(oldCommitId, newCommitId)) {
+ if (!Objects.equal(entry.getOldPath(), entry.getNewPath())
+ || !Objects.equal(entry.getOldMode(), entry.getNewMode())
+ || entry.getOldId()==null || !entry.getOldId().isComplete()
+ || entry.getNewId()== null || !entry.getNewId().isComplete()
+ || !entry.getOldId().equals(entry.getNewId())) {
+ diffs.add(entry);
+ }
+ }
+ } catch (IOException e) {
+ throw new RuntimeException(e);
+ }
+ diffCache.put(key, diffs);
+ }
+ return diffs;
+ }
+
+ public Commit getCommit(String commitHash) {
+ if (commitCache == null)
+ commitCache = new HashMap<>();
+
+ Commit commit = commitCache.get(commitHash);
+ if (commit == null) {
+ commit = git().showRevision(commitHash);
+ commitCache.put(commitHash, commit);
+ }
+ return commit;
+ }
+
+ public void cacheCommits(List<Commit> commits) {
+ if (commitCache == null)
+ commitCache = new HashMap<>();
+
+ for (Commit commit: commits)
+ commitCache.put(commit.getHash(), commit);
+ }
+
+ public FileRepository openAsJGitRepo() {
+ try {
+ return (FileRepository) RepositoryCache.open(FileKey.lenient(git().repoDir(), FS.DETECTED), true);
+ } catch (IOException e) {
+ throw new RuntimeException(e);
+ }
+ }
+
+ public LastCommitsOfChildren getLastCommitsOfChildren(String revision, @Nullable String path) {
+ if (path == null)
+ path = "";
+
+ final File cacheDir = new File(
+ GitPlex.getInstance(StorageManager.class).getCacheDir(this),
+ "last_commits/" + path + "/gitplex_last_commits");
+
+ final ReadWriteLock lock;
+ try {
+ lock = LockUtils.getReadWriteLock(cacheDir.getCanonicalPath());
+ } catch (IOException e) {
+ throw new RuntimeException(e);
+ }
+
+ final Set<ObjectId> commitIds = new HashSet<>();
+
+ lock.readLock().lock();
+ try {
+ if (cacheDir.exists()) {
+ for (String each: cacheDir.list())
+ commitIds.add(ObjectId.fromString(each));
+ }
+ } finally {
+ lock.readLock().unlock();
+ }
+
+ org.eclipse.jgit.revwalk.LastCommitsOfChildren.Cache cache;
+ if (!commitIds.isEmpty()) {
+ cache = new org.eclipse.jgit.revwalk.LastCommitsOfChildren.Cache() {
+
+ @SuppressWarnings("unchecked")
+ @Override
+ public Map<String, Value> getLastCommitsOfChildren(ObjectId commitId) {
+ if (commitIds.contains(commitId)) {
+ lock.readLock().lock();
+ try {
+ byte[] bytes = FileUtils.readFileToByteArray(new File(cacheDir, commitId.name()));
+ return (Map<String, Value>) SerializationUtils.deserialize(bytes);
+ } catch (IOException e) {
+ throw new RuntimeException(e);
+ } finally {
+ lock.readLock().unlock();
+ }
+ } else {
+ return null;
+ }
+ }
+
+ };
+ } else {
+ cache = null;
+ }
+
+ final AnyObjectId commitId = getObjectId(revision);
+
+ try (FileRepository jgitRepo = openAsJGitRepo()) {
+ long time = System.currentTimeMillis();
+ LastCommitsOfChildren lastCommits = new LastCommitsOfChildren(jgitRepo, commitId, path, cache);
+ long elapsed = System.currentTimeMillis()-time;
+ if (elapsed > LAST_COMMITS_CACHE_THRESHOLD) {
+ lock.writeLock().lock();
+ try {
+ if (!cacheDir.exists())
+ FileUtils.createDir(cacheDir);
+ FileUtils.writeByteArrayToFile(
+ new File(cacheDir, commitId.name()),
+ SerializationUtils.serialize(lastCommits));
+ } catch (IOException e) {
+ throw new RuntimeException(e);
+ } finally {
+ lock.writeLock().unlock();
+ }
+ }
+ return lastCommits;
+ }
+ }
+
+ public Map<String, Ref> getRefs(String prefix) {
+ if (refsCache == null)
+ refsCache = new HashMap<>();
+
+ Map<String, Ref> cached = refsCache.get(prefix);
+ if (cached == null) {
+ try (FileRepository jgitRepo = openAsJGitRepo()) {
+ cached = jgitRepo.getRefDatabase().getRefs(prefix);
+ refsCache.put(prefix, cached);
+ } catch (IOException e) {
+ throw new RuntimeException(e);
+ }
+ }
+ return cached;
+ }
+
+ public Map<String, String> getSubmodules(String revision) {
+ Map<String, String> submodules = new HashMap<>();
+
+ Blob blob = getBlob(new BlobIdent(revision, ".gitmodules", FileMode.REGULAR_FILE.getBits()));
+ String content = new String(blob.getBytes());
+
+ String path = null;
+ String url = null;
+
+ for (String line: StringUtils.splitAndTrim(content, "\r\n")) {
+ if (line.startsWith("[") && line.endsWith("]")) {
+ if (path != null && url != null)
+ submodules.put(path, url);
+
+ path = url = null;
+ } else if (line.startsWith("path")) {
+ path = StringUtils.substringAfter(line, "=").trim();
+ } else if (line.startsWith("url")) {
+ url = StringUtils.substringAfter(line, "=").trim();
+ }
+ }
+ if (path != null && url != null)
+ submodules.put(path, url);
+
+ return submodules;
+ }
+
+ public String getBranchFQN(String branch) {
+ return getFQN() + ":" + branch;
+ }
+
+ public void deleteBranch(String branch) {
+ git().deleteBranch(branch);
+ for (RefListener listener: GitPlex.getExtensions(RefListener.class))
+ listener.onRefUpdate(this, GitUtils.branch2ref(branch), null);
+ }
+
+ private static class DiffKey implements Serializable {
+ String oldRev;
+
+ String newRev;
+
+ String[] paths;
+
+ boolean detectRenames;
+
+ DiffKey(String oldRev, String newRev, boolean detectRenames, String...paths) {
+ this.oldRev = oldRev;
+ this.newRev = newRev;
+ this.detectRenames = detectRenames;
+ this.paths = paths;
+ }
+
+ public boolean equals(Object other) {
+ if (!(other instanceof DiffKey))
+ return false;
+ if (this == other)
+ return true;
+ DiffKey otherKey = (DiffKey) other;
+ return Objects.equal(oldRev, otherKey.oldRev)
+ && Objects.equal(newRev, otherKey.newRev)
+ && Objects.equal(paths, otherKey.paths)
+ && Objects.equal(detectRenames, otherKey.detectRenames);
+ }
+
+ public int hashCode() {
+ return Objects.hashCode(oldRev, newRev, paths, detectRenames);
+ }
+
+ }
+
+}
diff --git a/gitplex.web/src/main/java/com/pmease/gitplex/web/Constants.java b/gitplex.web/src/main/java/com/pmease/gitplex/web/Constants.java
index a14e0c7331..9254f8ee18 100644
--- a/gitplex.web/src/main/java/com/pmease/gitplex/web/Constants.java
+++ b/gitplex.web/src/main/java/com/pmease/gitplex/web/Constants.java
@@ -1,27 +1,27 @@
-package com.pmease.gitplex.web;
-
-import org.joda.time.format.DateTimeFormat;
-import org.joda.time.format.DateTimeFormatter;
-
-public class Constants {
-
- public static final String DATETIME_FORMAT = "yyyy-MM-dd HH:mm";
- public static final DateTimeFormatter DATETIME_FORMATTER = DateTimeFormat.forPattern(DATETIME_FORMAT);
-
- public static final String DATE_FORMAT = "yyyy-MM-dd";
- public static final DateTimeFormatter DATE_FORMATTER = DateTimeFormat.forPattern(DATE_FORMAT);
-
- public static final int DEFAULT_PAGE_SIZE = 25;
-
- public static final int DEFAULT_SELECT2_PAGE_SIZE = 25;
-
- /* diff constants */
- public static final int DIFF_EXPAND_SIZE = 15;
- public static final int MAX_DIFF_FILES = 500;
- public static final int MAX_SINGLE_FILE_DIFF_LINES = 5000;
- public static final int MAX_DIFF_LINES = 20000;
-
- /* commit constants */
- public static final int MAX_DISPLAY_COMMITS = 500;
-
-}
+package com.pmease.gitplex.web;
+
+import org.joda.time.format.DateTimeFormat;
+import org.joda.time.format.DateTimeFormatter;
+
+public class Constants {
+
+ public static final String DATETIME_FORMAT = "yyyy-MM-dd HH:mm";
+ public static final DateTimeFormatter DATETIME_FORMATTER = DateTimeFormat.forPattern(DATETIME_FORMAT);
+
+ public static final String DATE_FORMAT = "yyyy-MM-dd";
+ public static final DateTimeFormatter DATE_FORMATTER = DateTimeFormat.forPattern(DATE_FORMAT);
+
+ public static final int DEFAULT_PAGE_SIZE = 25;
+
+ public static final int DEFAULT_SELECT2_PAGE_SIZE = 25;
+
+ /* diff constants */
+ public static final int DIFF_EXPAND_SIZE = 15;
+ public static final int MAX_DIFF_FILES = 200;
+ public static final int MAX_SINGLE_FILE_DIFF_LINES = 5000;
+ public static final int MAX_DIFF_LINES = 10000;
+
+ /* commit constants */
+ public static final int MAX_DISPLAY_COMMITS = 500;
+
+}
diff --git a/gitplex.web/src/main/java/com/pmease/gitplex/web/component/diff/revision/RevisionDiffPanel.java b/gitplex.web/src/main/java/com/pmease/gitplex/web/component/diff/revision/RevisionDiffPanel.java
index cb4892da41..1aaad77458 100644
--- a/gitplex.web/src/main/java/com/pmease/gitplex/web/component/diff/revision/RevisionDiffPanel.java
+++ b/gitplex.web/src/main/java/com/pmease/gitplex/web/component/diff/revision/RevisionDiffPanel.java
@@ -1,349 +1,349 @@
-package com.pmease.gitplex.web.component.diff.revision;
-
-import java.util.ArrayList;
-import java.util.Collection;
-import java.util.Iterator;
-import java.util.List;
-import java.util.concurrent.Callable;
-import java.util.concurrent.ExecutionException;
-import java.util.concurrent.ForkJoinPool;
-import java.util.concurrent.Future;
-
-import javax.annotation.Nullable;
-
-import org.apache.wicket.AttributeModifier;
-import org.apache.wicket.ajax.AjaxRequestTarget;
-import org.apache.wicket.ajax.attributes.AjaxRequestAttributes;
-import org.apache.wicket.ajax.markup.html.AjaxLink;
-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.WebMarkupContainer;
-import org.apache.wicket.markup.html.basic.Label;
-import org.apache.wicket.markup.html.list.ListItem;
-import org.apache.wicket.markup.html.list.ListView;
-import org.apache.wicket.markup.html.panel.Panel;
-import org.apache.wicket.model.AbstractReadOnlyModel;
-import org.apache.wicket.model.IModel;
-import org.apache.wicket.model.LoadableDetachableModel;
-import org.apache.wicket.request.resource.CssResourceReference;
-import org.apache.wicket.util.lang.Objects;
-import org.eclipse.jgit.diff.DiffEntry;
-import org.eclipse.jgit.diff.DiffEntry.ChangeType;
-
-import com.pmease.commons.git.Blob;
-import com.pmease.commons.git.BlobChange;
-import com.pmease.commons.git.BlobIdent;
-import com.pmease.commons.git.LineProcessor;
-import com.pmease.commons.lang.diff.DiffUtils;
-import com.pmease.commons.wicket.ajaxlistener.ConfirmLeaveListener;
-import com.pmease.commons.wicket.ajaxlistener.IndicateLoadingListener;
-import com.pmease.gitplex.core.GitPlex;
-import com.pmease.gitplex.core.model.Comment;
-import com.pmease.gitplex.core.model.PullRequest;
-import com.pmease.gitplex.core.model.Repository;
-import com.pmease.gitplex.web.Constants;
-import com.pmease.gitplex.web.component.diff.blob.BlobDiffPanel;
-import com.pmease.gitplex.web.component.diff.diffstat.DiffStatBar;
-
-@SuppressWarnings("serial")
-public abstract class RevisionDiffPanel extends Panel {
-
- private final IModel<Repository> repoModel;
-
- private final IModel<PullRequest> requestModel;
-
- private final IModel<Comment> commentModel;
-
- private final String oldRev;
-
- private final String newRev;
-
- private final String path;
-
- private final String comparePath;
-
- private final LineProcessor lineProcessor;
-
- private final DiffMode diffMode;
-
- private IModel<ChangesAndCount> changesAndCountModel = new LoadableDetachableModel<ChangesAndCount>() {
-
- @Override
- protected ChangesAndCount load() {
- String oldCommitHash = repoModel.getObject().getObjectId(oldRev).name();
- String newCommitHash = repoModel.getObject().getObjectId(newRev).name();
- List<String> paths = new ArrayList<>();
- if (path != null)
- paths.add(path);
- if (comparePath != null)
- paths.add(comparePath);
- List<DiffEntry> diffEntries = repoModel.getObject().getDiffs(oldCommitHash, newCommitHash,
- true, paths.toArray(new String[paths.size()]));
- List<BlobChange> diffableChanges = new ArrayList<>();
- for (DiffEntry entry: diffEntries) {
- if (diffableChanges.size() < Constants.MAX_DIFF_FILES) {
- diffableChanges.add(new BlobChange(oldRev, newRev, entry) {
-
- @Override
- public Blob getBlob(BlobIdent blobIdent) {
- return repoModel.getObject().getBlob(blobIdent);
- }
-
- @Override
- public LineProcessor getLineProcessor() {
- return lineProcessor;
- }
-
- });
- } else {
- break;
- }
- }
-
- // Diff calculation can be slow, so we pre-load diffs of each change
- // concurrently
- Collection<Callable<Void>> tasks = new ArrayList<>();
- for (final BlobChange change: diffableChanges) {
- tasks.add(new Callable<Void>() {
-
- @Override
- public Void call() throws Exception {
- change.getDiffBlocks();
- return null;
- }
-
- });
- }
- for (Future<Void> future: GitPlex.getInstance(ForkJoinPool.class).invokeAll(tasks)) {
- try {
- // call get in order to throw exception if there is any during task execution
- future.get();
- } catch (InterruptedException|ExecutionException e) {
- throw new RuntimeException(e);
- }
- }
-
- int totalChanges = diffEntries.size();
- if (diffableChanges.size() == totalChanges) {
- // some changes should be removed if content is the same after line processing
- for (Iterator<BlobChange> it = diffableChanges.iterator(); it.hasNext();) {
- BlobChange change = it.next();
- if (change.getType() == ChangeType.MODIFY
- && Objects.equal(change.getOldBlobIdent().mode, change.getNewBlobIdent().mode)
- && change.getAdditions() + change.getDeletions() == 0) {
- Blob.Text oldText = change.getOldText();
- Blob.Text newText = change.getNewText();
- if (oldText != null && newText != null
- && (oldText.getLines().size() + newText.getLines().size()) <= DiffUtils.MAX_DIFF_SIZE) {
- it.remove();
- }
- }
- }
- totalChanges = diffableChanges.size();
- }
-
- List<BlobChange> displayableChanges = new ArrayList<>();
- int totalChangedLines = 0;
- for (BlobChange change: diffableChanges) {
- int changedLines = change.getAdditions() + change.getDeletions();
-
- // we do not count large diff in a single file in order to
- // display smaller diffs from different files as many as
- // possible.
- if (changedLines <= Constants.MAX_SINGLE_FILE_DIFF_LINES) {
- totalChangedLines += changedLines;
- if (totalChangedLines <= Constants.MAX_DIFF_LINES)
- displayableChanges.add(change);
- else
- break;
- } else {
- // large diff in a single file will not be displayed, so
- // adding it to change list will do no harm, and can avoid
- // displaying "too many changes" when some big text file
- // is added/removed without touching too many files
- displayableChanges.add(change);
- }
- }
- return new ChangesAndCount(displayableChanges, totalChanges);
- }
- };
-
- public RevisionDiffPanel(String id, IModel<Repository> repoModel, IModel<PullRequest> requestModel,
- IModel<Comment> commentModel, String oldRev, String newRev, @Nullable String path,
- @Nullable String comparePath, LineProcessor lineProcessor, DiffMode diffMode) {
- super(id);
-
- this.repoModel = repoModel;
- this.requestModel = requestModel;
- this.commentModel = commentModel;
- this.oldRev = oldRev;
- this.newRev = newRev;
- this.path = path;
- this.comparePath = comparePath;
- this.lineProcessor = lineProcessor;
- this.diffMode = diffMode;
- }
-
- @Override
- protected void onInitialize() {
- super.onInitialize();
-
- add(new Label("totalChanged", new AbstractReadOnlyModel<Integer>() {
-
- @Override
- public Integer getObject() {
- return getChangesCount();
- }
-
- }));
- if (path != null) {
- add(new Label("filterPath", "filter by " + path));
- add(new AjaxLink<Void>("clearPath") {
-
- @Override
- protected void updateAjaxAttributes(AjaxRequestAttributes attributes) {
- super.updateAjaxAttributes(attributes);
- attributes.getAjaxCallListeners().add(new ConfirmLeaveListener(RevisionDiffPanel.this));
- attributes.getAjaxCallListeners().add(new IndicateLoadingListener());
- }
-
- @Override
- public void onClick(AjaxRequestTarget target) {
- onClearPath(target);
- }
-
- });
- } else {
- add(new WebMarkupContainer("filterPath").setVisible(false));
- add(new WebMarkupContainer("clearPath").setVisible(false));
- }
-
- add(new WebMarkupContainer("tooManyChanges") {
-
- @Override
- protected void onConfigure() {
- super.onConfigure();
- setVisible(getChanges().size() < getChangesCount());
- }
-
- });
-
- add(new ListView<BlobChange>("diffStats", new AbstractReadOnlyModel<List<BlobChange>>() {
-
- @Override
- public List<BlobChange> getObject() {
- return getChanges();
- }
-
- }) {
-
- @Override
- protected void populateItem(ListItem<BlobChange> item) {
- BlobChange change = item.getModelObject();
- String iconClass;
- if (change.getType() == ChangeType.ADD)
- iconClass = " fa-ext fa-diff-added";
- else if (change.getType() == ChangeType.DELETE)
- iconClass = " fa-ext fa-diff-removed";
- else if (change.getType() == ChangeType.MODIFY)
- iconClass = " fa-ext fa-diff-modified";
- else
- iconClass = " fa-ext fa-diff-renamed";
-
- item.add(new WebMarkupContainer("icon").add(AttributeAppender.append("class", iconClass)));
-
- WebMarkupContainer pathLink = new WebMarkupContainer("path");
- pathLink.add(AttributeModifier.replace("href", "#diff-" + change.getPath()));
- pathLink.add(new Label("path", change.getPath()));
-
- item.add(pathLink);
-
- item.add(new Label("additions", "+" + change.getAdditions()));
- item.add(new Label("deletions", "-" + change.getDeletions()));
-
- boolean barVisible;
- if (change.getType() == ChangeType.ADD) {
- Blob.Text text = change.getNewText();
- barVisible = (text != null && text.getLines().size() <= DiffUtils.MAX_DIFF_SIZE);
- } else if (change.getType() == ChangeType.DELETE) {
- Blob.Text text = change.getOldText();
- barVisible = (text != null && text.getLines().size() <= DiffUtils.MAX_DIFF_SIZE);
- } else {
- Blob.Text oldText = change.getOldText();
- Blob.Text newText = change.getNewText();
- barVisible = (oldText != null && newText != null
- && oldText.getLines().size()+newText.getLines().size() <= DiffUtils.MAX_DIFF_SIZE);
- }
- item.add(new DiffStatBar("bar", change.getAdditions(), change.getDeletions(), false).setVisible(barVisible));
- }
-
- });
-
- add(new ListView<BlobChange>("changes", new AbstractReadOnlyModel<List<BlobChange>>() {
-
- @Override
- public List<BlobChange> getObject() {
- return getChanges();
- }
-
- }) {
-
- @Override
- protected void populateItem(ListItem<BlobChange> item) {
- BlobChange change = item.getModelObject();
- item.setMarkupId("diff-" + change.getPath());
- item.setOutputMarkupId(true);
- item.add(new BlobDiffPanel("change", repoModel, requestModel, commentModel, change, diffMode));
- }
-
- });
- }
-
- private List<BlobChange> getChanges() {
- return changesAndCountModel.getObject().getChanges();
- }
-
- private int getChangesCount() {
- return changesAndCountModel.getObject().getCount();
- }
-
- @Override
- protected void onDetach() {
- changesAndCountModel.detach();
- repoModel.detach();
- requestModel.detach();
- commentModel.detach();
-
- super.onDetach();
- }
-
- @Override
- public void renderHead(IHeaderResponse response) {
- super.renderHead(response);
- response.render(CssHeaderItem.forReference(new CssResourceReference(RevisionDiffPanel.class, "revision-diff.css")));
- }
-
- protected abstract void onClearPath(AjaxRequestTarget target);
-
- private static class ChangesAndCount {
-
- private final List<BlobChange> changes;
-
- private final int count;
-
- public ChangesAndCount(List<BlobChange> changes, int count) {
- this.changes = changes;
- this.count = count;
- }
-
- public List<BlobChange> getChanges() {
- return changes;
- }
-
- public int getCount() {
- return count;
- }
-
- }
-}
+package com.pmease.gitplex.web.component.diff.revision;
+
+import java.util.ArrayList;
+import java.util.Collection;
+import java.util.Iterator;
+import java.util.List;
+import java.util.concurrent.Callable;
+import java.util.concurrent.ExecutionException;
+import java.util.concurrent.ForkJoinPool;
+import java.util.concurrent.Future;
+
+import javax.annotation.Nullable;
+
+import org.apache.wicket.AttributeModifier;
+import org.apache.wicket.ajax.AjaxRequestTarget;
+import org.apache.wicket.ajax.attributes.AjaxRequestAttributes;
+import org.apache.wicket.ajax.markup.html.AjaxLink;
+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.WebMarkupContainer;
+import org.apache.wicket.markup.html.basic.Label;
+import org.apache.wicket.markup.html.list.ListItem;
+import org.apache.wicket.markup.html.list.ListView;
+import org.apache.wicket.markup.html.panel.Panel;
+import org.apache.wicket.model.AbstractReadOnlyModel;
+import org.apache.wicket.model.IModel;
+import org.apache.wicket.model.LoadableDetachableModel;
+import org.apache.wicket.request.resource.CssResourceReference;
+import org.apache.wicket.util.lang.Objects;
+import org.eclipse.jgit.diff.DiffEntry;
+import org.eclipse.jgit.diff.DiffEntry.ChangeType;
+
+import com.pmease.commons.git.Blob;
+import com.pmease.commons.git.BlobChange;
+import com.pmease.commons.git.BlobIdent;
+import com.pmease.commons.git.LineProcessor;
+import com.pmease.commons.lang.diff.DiffUtils;
+import com.pmease.commons.wicket.ajaxlistener.ConfirmLeaveListener;
+import com.pmease.commons.wicket.ajaxlistener.IndicateLoadingListener;
+import com.pmease.gitplex.core.GitPlex;
+import com.pmease.gitplex.core.model.Comment;
+import com.pmease.gitplex.core.model.PullRequest;
+import com.pmease.gitplex.core.model.Repository;
+import com.pmease.gitplex.web.Constants;
+import com.pmease.gitplex.web.component.diff.blob.BlobDiffPanel;
+import com.pmease.gitplex.web.component.diff.diffstat.DiffStatBar;
+
+@SuppressWarnings("serial")
+public abstract class RevisionDiffPanel extends Panel {
+
+ private final IModel<Repository> repoModel;
+
+ private final IModel<PullRequest> requestModel;
+
+ private final IModel<Comment> commentModel;
+
+ private final String oldRev;
+
+ private final String newRev;
+
+ private final String path;
+
+ private final String comparePath;
+
+ private final LineProcessor lineProcessor;
+
+ private final DiffMode diffMode;
+
+ private IModel<ChangesAndCount> changesAndCountModel = new LoadableDetachableModel<ChangesAndCount>() {
+
+ @Override
+ protected ChangesAndCount load() {
+ String oldCommitHash = repoModel.getObject().getObjectId(oldRev).name();
+ String newCommitHash = repoModel.getObject().getObjectId(newRev).name();
+ List<String> paths = new ArrayList<>();
+ if (path != null)
+ paths.add(path);
+ if (comparePath != null)
+ paths.add(comparePath);
+ List<DiffEntry> diffEntries = repoModel.getObject().getDiffs(oldCommitHash, newCommitHash,
+ true, paths.toArray(new String[paths.size()]));
+ List<BlobChange> diffableChanges = new ArrayList<>();
+ for (DiffEntry entry: diffEntries) {
+ if (diffableChanges.size() < Constants.MAX_DIFF_FILES) {
+ diffableChanges.add(new BlobChange(oldRev, newRev, entry) {
+
+ @Override
+ public Blob getBlob(BlobIdent blobIdent) {
+ return repoModel.getObject().getBlob(blobIdent);
+ }
+
+ @Override
+ public LineProcessor getLineProcessor() {
+ return lineProcessor;
+ }
+
+ });
+ } else {
+ break;
+ }
+ }
+
+ // Diff calculation can be slow, so we pre-load diffs of each change
+ // concurrently
+ Collection<Callable<Void>> tasks = new ArrayList<>();
+ for (final BlobChange change: diffableChanges) {
+ tasks.add(new Callable<Void>() {
+
+ @Override
+ public Void call() throws Exception {
+ change.getDiffBlocks();
+ return null;
+ }
+
+ });
+ }
+ for (Future<Void> future: GitPlex.getInstance(ForkJoinPool.class).invokeAll(tasks)) {
+ try {
+ // call get in order to throw exception if there is any during task execution
+ future.get();
+ } catch (InterruptedException|ExecutionException e) {
+ throw new RuntimeException(e);
+ }
+ }
+
+ int totalChanges = diffEntries.size();
+ if (diffableChanges.size() == totalChanges) {
+ // some changes should be removed if content is the same after line processing
+ for (Iterator<BlobChange> it = diffableChanges.iterator(); it.hasNext();) {
+ BlobChange change = it.next();
+ if (change.getType() == ChangeType.MODIFY
+ && Objects.equal(change.getOldBlobIdent().mode, change.getNewBlobIdent().mode)
+ && change.getAdditions() + change.getDeletions() == 0) {
+ Blob.Text oldText = change.getOldText();
+ Blob.Text newText = change.getNewText();
+ if (oldText != null && newText != null
+ && (oldText.getLines().size() + newText.getLines().size()) <= DiffUtils.MAX_DIFF_SIZE) {
+ it.remove();
+ }
+ }
+ }
+ totalChanges = diffableChanges.size();
+ }
+
+ List<BlobChange> displayableChanges = new ArrayList<>();
+ int totalChangedLines = 0;
+ for (BlobChange change: diffableChanges) {
+ int changedLines = change.getAdditions() + change.getDeletions();
+
+ // we do not count large diff in a single file in order to
+ // display smaller diffs from different files as many as
+ // possible.
+ if (changedLines <= Constants.MAX_SINGLE_FILE_DIFF_LINES) {
+ totalChangedLines += changedLines;
+ if (totalChangedLines <= Constants.MAX_DIFF_LINES)
+ displayableChanges.add(change);
+ else
+ break;
+ } else {
+ // large diff in a single file will not be displayed, so
+ // adding it to change list will do no harm, and can avoid
+ // displaying "too many changes" when some big text file
+ // is added/removed without touching too many files
+ displayableChanges.add(change);
+ }
+ }
+ return new ChangesAndCount(displayableChanges, totalChanges);
+ }
+ };
+
+ public RevisionDiffPanel(String id, IModel<Repository> repoModel, IModel<PullRequest> requestModel,
+ IModel<Comment> commentModel, String oldRev, String newRev, @Nullable String path,
+ @Nullable String comparePath, LineProcessor lineProcessor, DiffMode diffMode) {
+ super(id);
+
+ this.repoModel = repoModel;
+ this.requestModel = requestModel;
+ this.commentModel = commentModel;
+ this.oldRev = oldRev;
+ this.newRev = newRev;
+ this.path = path;
+ this.comparePath = comparePath;
+ this.lineProcessor = lineProcessor;
+ this.diffMode = diffMode;
+ }
+
+ @Override
+ protected void onInitialize() {
+ super.onInitialize();
+
+ add(new Label("totalChanged", new AbstractReadOnlyModel<Integer>() {
+
+ @Override
+ public Integer getObject() {
+ return getChangesCount();
+ }
+
+ }));
+ if (path != null) {
+ add(new Label("filterPath", "filter by " + path));
+ add(new AjaxLink<Void>("clearPath") {
+
+ @Override
+ protected void updateAjaxAttributes(AjaxRequestAttributes attributes) {
+ super.updateAjaxAttributes(attributes);
+ attributes.getAjaxCallListeners().add(new ConfirmLeaveListener(RevisionDiffPanel.this));
+ attributes.getAjaxCallListeners().add(new IndicateLoadingListener());
+ }
+
+ @Override
+ public void onClick(AjaxRequestTarget target) {
+ onClearPath(target);
+ }
+
+ });
+ } else {
+ add(new WebMarkupContainer("filterPath").setVisible(false));
+ add(new WebMarkupContainer("clearPath").setVisible(false));
+ }
+
+ add(new WebMarkupContainer("tooManyChanges") {
+
+ @Override
+ protected void onConfigure() {
+ super.onConfigure();
+ setVisible(getChanges().size() < getChangesCount());
+ }
+
+ });
+
+ add(new ListView<BlobChange>("diffStats", new AbstractReadOnlyModel<List<BlobChange>>() {
+
+ @Override
+ public List<BlobChange> getObject() {
+ return getChanges();
+ }
+
+ }) {
+
+ @Override
+ protected void populateItem(ListItem<BlobChange> item) {
+ BlobChange change = item.getModelObject();
+ String iconClass;
+ if (change.getType() == ChangeType.ADD)
+ iconClass = " fa-ext fa-diff-added";
+ else if (change.getType() == ChangeType.DELETE)
+ iconClass = " fa-ext fa-diff-removed";
+ else if (change.getType() == ChangeType.MODIFY)
+ iconClass = " fa-ext fa-diff-modified";
+ else
+ iconClass = " fa-ext fa-diff-renamed";
+
+ item.add(new WebMarkupContainer("icon").add(AttributeAppender.append("class", iconClass)));
+
+ WebMarkupContainer pathLink = new WebMarkupContainer("path");
+ pathLink.add(AttributeModifier.replace("href", "#diff-" + change.getPath()));
+ pathLink.add(new Label("path", change.getPath()));
+
+ item.add(pathLink);
+
+ item.add(new Label("additions", "+" + change.getAdditions()));
+ item.add(new Label("deletions", "-" + change.getDeletions()));
+
+ boolean barVisible;
+ if (change.getType() == ChangeType.ADD) {
+ Blob.Text text = change.getNewText();
+ barVisible = (text != null && text.getLines().size() <= DiffUtils.MAX_DIFF_SIZE);
+ } else if (change.getType() == ChangeType.DELETE) {
+ Blob.Text text = change.getOldText();
+ barVisible = (text != null && text.getLines().size() <= DiffUtils.MAX_DIFF_SIZE);
+ } else {
+ Blob.Text oldText = change.getOldText();
+ Blob.Text newText = change.getNewText();
+ barVisible = (oldText != null && newText != null
+ && oldText.getLines().size()+newText.getLines().size() <= DiffUtils.MAX_DIFF_SIZE);
+ }
+ item.add(new DiffStatBar("bar", change.getAdditions(), change.getDeletions(), false).setVisible(barVisible));
+ }
+
+ });
+
+ add(new ListView<BlobChange>("changes", new AbstractReadOnlyModel<List<BlobChange>>() {
+
+ @Override
+ public List<BlobChange> getObject() {
+ return getChanges();
+ }
+
+ }) {
+
+ @Override
+ protected void populateItem(ListItem<BlobChange> item) {
+ BlobChange change = item.getModelObject();
+ item.setMarkupId("diff-" + change.getPath());
+ item.setOutputMarkupId(true);
+ item.add(new BlobDiffPanel("change", repoModel, requestModel, commentModel, change, diffMode));
+ }
+
+ });
+ }
+
+ private List<BlobChange> getChanges() {
+ return changesAndCountModel.getObject().getChanges();
+ }
+
+ private int getChangesCount() {
+ return changesAndCountModel.getObject().getCount();
+ }
+
+ @Override
+ protected void onDetach() {
+ changesAndCountModel.detach();
+ repoModel.detach();
+ requestModel.detach();
+ commentModel.detach();
+
+ super.onDetach();
+ }
+
+ @Override
+ public void renderHead(IHeaderResponse response) {
+ super.renderHead(response);
+ response.render(CssHeaderItem.forReference(new CssResourceReference(RevisionDiffPanel.class, "revision-diff.css")));
+ }
+
+ protected abstract void onClearPath(AjaxRequestTarget target);
+
+ private static class ChangesAndCount {
+
+ private final List<BlobChange> changes;
+
+ private final int count;
+
+ public ChangesAndCount(List<BlobChange> changes, int count) {
+ this.changes = changes;
+ this.count = count;
+ }
+
+ public List<BlobChange> getChanges() {
+ return changes;
+ }
+
+ public int getCount() {
+ return count;
+ }
+
+ }
+}
diff --git a/gitplex.web/src/main/java/com/pmease/gitplex/web/page/repository/RepositoryPage.java b/gitplex.web/src/main/java/com/pmease/gitplex/web/page/repository/RepositoryPage.java
index 64f9edae2d..2b06b76e25 100644
--- a/gitplex.web/src/main/java/com/pmease/gitplex/web/page/repository/RepositoryPage.java
+++ b/gitplex.web/src/main/java/com/pmease/gitplex/web/page/repository/RepositoryPage.java
@@ -1,195 +1,196 @@
-package com.pmease.gitplex.web.page.repository;
-
-import java.util.ArrayList;
-import java.util.List;
-
-import javax.persistence.EntityNotFoundException;
-import javax.servlet.http.Cookie;
-
-import org.apache.wicket.Component;
-import org.apache.wicket.RestartResponseException;
-import org.apache.wicket.ajax.AjaxRequestTarget;
-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.head.JavaScriptHeaderItem;
-import org.apache.wicket.markup.html.WebMarkupContainer;
-import org.apache.wicket.markup.html.basic.Label;
-import org.apache.wicket.markup.html.form.TextField;
-import org.apache.wicket.markup.html.link.BookmarkablePageLink;
-import org.apache.wicket.markup.html.link.Link;
-import org.apache.wicket.markup.html.panel.Fragment;
-import org.apache.wicket.model.IModel;
-import org.apache.wicket.model.Model;
-import org.apache.wicket.request.cycle.RequestCycle;
-import org.apache.wicket.request.http.WebRequest;
-import org.apache.wicket.request.mapper.parameter.PageParameters;
-import org.apache.wicket.request.resource.CssResourceReference;
-import org.apache.wicket.request.resource.JavaScriptResourceReference;
-import org.eclipse.jgit.lib.Constants;
-
-import com.google.common.base.Preconditions;
-import com.pmease.commons.wicket.assets.cookies.CookiesResourceReference;
-import com.pmease.commons.wicket.component.DropdownLink;
-import com.pmease.commons.wicket.component.floating.FloatingPanel;
-import com.pmease.commons.wicket.component.tabbable.PageTab;
-import com.pmease.commons.wicket.component.tabbable.Tabbable;
-import com.pmease.gitplex.core.GitPlex;
-import com.pmease.gitplex.core.manager.RepositoryManager;
-import com.pmease.gitplex.core.manager.UrlManager;
-import com.pmease.gitplex.core.model.Repository;
-import com.pmease.gitplex.core.permission.ObjectPermission;
-import com.pmease.gitplex.core.security.SecurityUtils;
-import com.pmease.gitplex.web.component.reposelector.RepositorySelector;
-import com.pmease.gitplex.web.model.RepositoryModel;
-import com.pmease.gitplex.web.page.account.AccountPage;
-import com.pmease.gitplex.web.page.account.repositories.AccountReposPage;
-import com.pmease.gitplex.web.page.repository.branches.RepoBranchesPage;
-import com.pmease.gitplex.web.page.repository.branches.compare.BranchComparePage;
-import com.pmease.gitplex.web.page.repository.commit.RepoCommitsPage;
-import com.pmease.gitplex.web.page.repository.file.RepoFilePage;
-import com.pmease.gitplex.web.page.repository.pullrequest.PullRequestPage;
-import com.pmease.gitplex.web.page.repository.pullrequest.requestlist.RequestListPage;
-import com.pmease.gitplex.web.page.repository.setting.RepoSettingPage;
-import com.pmease.gitplex.web.page.repository.setting.general.GeneralSettingPage;
-import com.pmease.gitplex.web.page.repository.tags.RepoTagsPage;
-
-@SuppressWarnings("serial")
-public abstract class RepositoryPage extends AccountPage {
-
- private static final String PARAM_REPO = "repo";
-
- protected final IModel<Repository> repoModel;
-
- public static PageParameters paramsOf(Repository repository) {
- PageParameters params = paramsOf(repository.getUser());
- params.set(PARAM_REPO, repository.getName());
- return params;
- }
-
- public RepositoryPage(PageParameters params) {
- super(params);
-
- String repoName = params.get(PARAM_REPO).toString();
- Preconditions.checkNotNull(repoName);
-
- if (repoName.endsWith(Constants.DOT_GIT_EXT))
- repoName = repoName.substring(0, repoName.length() - Constants.DOT_GIT_EXT.length());
-
- Repository repository = GitPlex.getInstance(RepositoryManager.class).findBy(getAccount(), repoName);
-
- if (repository == null)
- throw new EntityNotFoundException("Unable to find repository " + getAccount() + "/" + repoName);
-
- repoModel = new RepositoryModel(repository);
-
- if (!(this instanceof NoCommitsPage)
- && !(this instanceof RepoSettingPage)
- && !getRepository().git().hasCommits()) {
- throw new RestartResponseException(NoCommitsPage.class, paramsOf(getRepository()));
- }
- }
-
- @Override
- protected void onInitialize() {
- super.onInitialize();
-
- List<PageTab> tabs = new ArrayList<>();
- tabs.add(new RepoTab(Model.of("Files"), "fa fa-fw fa-file-text-o", RepoFilePage.class));
- tabs.add(new RepoTab(Model.of("Commits"), "fa fa-fw fa-ext fa-commit", RepoCommitsPage.class));
- tabs.add(new RepoTab(Model.of("Branches"), "fa fa-fw fa-ext fa-branch",
- RepoBranchesPage.class, BranchComparePage.class));
- tabs.add(new RepoTab(Model.of("Tags"), "fa fa-fw fa-tag", RepoTagsPage.class));
- tabs.add(new RepoTab(Model.of("Pull Requests"), "fa fa-fw fa-ext fa-branch-compare",
- RequestListPage.class, PullRequestPage.class));
-
- if (SecurityUtils.canManage(getRepository()))
- tabs.add(new RepoTab(Model.of("Setting"), "fa fa-fw fa-cog", GeneralSettingPage.class, RepoSettingPage.class));
-
- WebMarkupContainer sidebar = new WebMarkupContainer("sidebar");
- add(sidebar);
-
- /*
- * Add mini class here instead of repository.js as we want the sidebar to
- * be minimized initially even if the page takes some time to load
- */
- WebRequest request = (WebRequest) RequestCycle.get().getRequest();
- Cookie cookie = request.getCookie("repository.miniSidebar");
- if (cookie != null && "yes".equals(cookie.getValue()))
- sidebar.add(AttributeAppender.append("class", " mini"));
-
- sidebar.add(new Tabbable("repoTabs", tabs));
- }
-
- @Override
- public void renderHead(IHeaderResponse response) {
- super.renderHead(response);
-
- response.render(JavaScriptHeaderItem.forReference(CookiesResourceReference.INSTANCE));
- response.render(JavaScriptHeaderItem.forReference(
- new JavaScriptResourceReference(RepositoryPage.class, "repository.js")));
- response.render(CssHeaderItem.forReference(
- new CssResourceReference(RepositoryPage.class, "repository.css")));
- }
-
- @Override
- protected boolean isPermitted() {
- return SecurityUtils.getSubject().isPermitted(ObjectPermission.ofRepoPull(repoModel.getObject()));
- }
-
- public Repository getRepository() {
- return repoModel.getObject();
- }
-
- @Override
- protected void onDetach() {
- repoModel.detach();
-
- super.onDetach();
- }
-
- protected abstract void onSelect(AjaxRequestTarget target, Repository repository);
-
- @Override
- protected Component newContextHead(String componentId) {
- Fragment fragment = new Fragment(componentId, "contextHeadFrag", this);
- WebMarkupContainer accountAndRepo = new WebMarkupContainer("accountAndRepo");
- fragment.add(accountAndRepo);
- Link<Void> accountLink = new BookmarkablePageLink<>("accountLink", AccountReposPage.class, paramsOf(getAccount()));
- accountLink.add(new Label("accountName", getAccount().getName()));
- accountAndRepo.add(accountLink);
-
- Link<Void> repoLink = new BookmarkablePageLink<>("repoLink", RepoFilePage.class, paramsOf(getRepository()));
- repoLink.add(new Label("repoName", getRepository().getName()));
- accountAndRepo.add(repoLink);
-
- fragment.add(new DropdownLink("repoChoiceTrigger") {
-
- @Override
- protected void onInitialize(FloatingPanel dropdown) {
- super.onInitialize(dropdown);
- dropdown.add(AttributeAppender.append("class", " repo-choice"));
- }
-
- @Override
- protected Component newContent(String id) {
- return new RepositorySelector(id, null, repoModel) {
-
- @Override
- protected void onSelect(AjaxRequestTarget target, Repository repository) {
- RepositoryPage.this.onSelect(target, repository);
- }
-
- };
- }
-
- });
-
- UrlManager urlManager = GitPlex.getInstance(UrlManager.class);
- Model<String> cloneUrlModel = Model.of(urlManager.urlFor(getRepository()));
- fragment.add(new TextField<String>("cloneUrl", cloneUrlModel));
-
- return fragment;
- }
-
-}
+package com.pmease.gitplex.web.page.repository;
+
+import java.util.ArrayList;
+import java.util.List;
+
+import javax.persistence.EntityNotFoundException;
+import javax.servlet.http.Cookie;
+
+import org.apache.wicket.Component;
+import org.apache.wicket.RestartResponseException;
+import org.apache.wicket.ajax.AjaxRequestTarget;
+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.head.JavaScriptHeaderItem;
+import org.apache.wicket.markup.html.WebMarkupContainer;
+import org.apache.wicket.markup.html.basic.Label;
+import org.apache.wicket.markup.html.form.TextField;
+import org.apache.wicket.markup.html.link.BookmarkablePageLink;
+import org.apache.wicket.markup.html.link.Link;
+import org.apache.wicket.markup.html.panel.Fragment;
+import org.apache.wicket.model.IModel;
+import org.apache.wicket.model.Model;
+import org.apache.wicket.request.cycle.RequestCycle;
+import org.apache.wicket.request.http.WebRequest;
+import org.apache.wicket.request.mapper.parameter.PageParameters;
+import org.apache.wicket.request.resource.CssResourceReference;
+import org.apache.wicket.request.resource.JavaScriptResourceReference;
+import org.eclipse.jgit.lib.Constants;
+
+import com.google.common.base.Preconditions;
+import com.pmease.commons.wicket.assets.cookies.CookiesResourceReference;
+import com.pmease.commons.wicket.component.DropdownLink;
+import com.pmease.commons.wicket.component.floating.FloatingPanel;
+import com.pmease.commons.wicket.component.tabbable.PageTab;
+import com.pmease.commons.wicket.component.tabbable.Tabbable;
+import com.pmease.gitplex.core.GitPlex;
+import com.pmease.gitplex.core.manager.RepositoryManager;
+import com.pmease.gitplex.core.manager.UrlManager;
+import com.pmease.gitplex.core.model.Repository;
+import com.pmease.gitplex.core.permission.ObjectPermission;
+import com.pmease.gitplex.core.security.SecurityUtils;
+import com.pmease.gitplex.web.component.reposelector.RepositorySelector;
+import com.pmease.gitplex.web.model.RepositoryModel;
+import com.pmease.gitplex.web.page.account.AccountPage;
+import com.pmease.gitplex.web.page.account.repositories.AccountReposPage;
+import com.pmease.gitplex.web.page.repository.branches.RepoBranchesPage;
+import com.pmease.gitplex.web.page.repository.branches.compare.BranchComparePage;
+import com.pmease.gitplex.web.page.repository.commit.RepoCommitPage;
+import com.pmease.gitplex.web.page.repository.commit.RepoCommitsPage;
+import com.pmease.gitplex.web.page.repository.file.RepoFilePage;
+import com.pmease.gitplex.web.page.repository.pullrequest.PullRequestPage;
+import com.pmease.gitplex.web.page.repository.pullrequest.requestlist.RequestListPage;
+import com.pmease.gitplex.web.page.repository.setting.RepoSettingPage;
+import com.pmease.gitplex.web.page.repository.setting.general.GeneralSettingPage;
+import com.pmease.gitplex.web.page.repository.tags.RepoTagsPage;
+
+@SuppressWarnings("serial")
+public abstract class RepositoryPage extends AccountPage {
+
+ private static final String PARAM_REPO = "repo";
+
+ protected final IModel<Repository> repoModel;
+
+ public static PageParameters paramsOf(Repository repository) {
+ PageParameters params = paramsOf(repository.getUser());
+ params.set(PARAM_REPO, repository.getName());
+ return params;
+ }
+
+ public RepositoryPage(PageParameters params) {
+ super(params);
+
+ String repoName = params.get(PARAM_REPO).toString();
+ Preconditions.checkNotNull(repoName);
+
+ if (repoName.endsWith(Constants.DOT_GIT_EXT))
+ repoName = repoName.substring(0, repoName.length() - Constants.DOT_GIT_EXT.length());
+
+ Repository repository = GitPlex.getInstance(RepositoryManager.class).findBy(getAccount(), repoName);
+
+ if (repository == null)
+ throw new EntityNotFoundException("Unable to find repository " + getAccount() + "/" + repoName);
+
+ repoModel = new RepositoryModel(repository);
+
+ if (!(this instanceof NoCommitsPage)
+ && !(this instanceof RepoSettingPage)
+ && !getRepository().git().hasCommits()) {
+ throw new RestartResponseException(NoCommitsPage.class, paramsOf(getRepository()));
+ }
+ }
+
+ @Override
+ protected void onInitialize() {
+ super.onInitialize();
+
+ List<PageTab> tabs = new ArrayList<>();
+ tabs.add(new RepoTab(Model.of("Files"), "fa fa-fw fa-file-text-o", RepoFilePage.class));
+ tabs.add(new RepoTab(Model.of("Commits"), "fa fa-fw fa-ext fa-commit", RepoCommitsPage.class, RepoCommitPage.class));
+ tabs.add(new RepoTab(Model.of("Branches"), "fa fa-fw fa-ext fa-branch",
+ RepoBranchesPage.class, BranchComparePage.class));
+ tabs.add(new RepoTab(Model.of("Tags"), "fa fa-fw fa-tag", RepoTagsPage.class));
+ tabs.add(new RepoTab(Model.of("Pull Requests"), "fa fa-fw fa-ext fa-branch-compare",
+ RequestListPage.class, PullRequestPage.class));
+
+ if (SecurityUtils.canManage(getRepository()))
+ tabs.add(new RepoTab(Model.of("Setting"), "fa fa-fw fa-cog", GeneralSettingPage.class, RepoSettingPage.class));
+
+ WebMarkupContainer sidebar = new WebMarkupContainer("sidebar");
+ add(sidebar);
+
+ /*
+ * Add mini class here instead of repository.js as we want the sidebar to
+ * be minimized initially even if the page takes some time to load
+ */
+ WebRequest request = (WebRequest) RequestCycle.get().getRequest();
+ Cookie cookie = request.getCookie("repository.miniSidebar");
+ if (cookie != null && "yes".equals(cookie.getValue()))
+ sidebar.add(AttributeAppender.append("class", " mini"));
+
+ sidebar.add(new Tabbable("repoTabs", tabs));
+ }
+
+ @Override
+ public void renderHead(IHeaderResponse response) {
+ super.renderHead(response);
+
+ response.render(JavaScriptHeaderItem.forReference(CookiesResourceReference.INSTANCE));
+ response.render(JavaScriptHeaderItem.forReference(
+ new JavaScriptResourceReference(RepositoryPage.class, "repository.js")));
+ response.render(CssHeaderItem.forReference(
+ new CssResourceReference(RepositoryPage.class, "repository.css")));
+ }
+
+ @Override
+ protected boolean isPermitted() {
+ return SecurityUtils.getSubject().isPermitted(ObjectPermission.ofRepoPull(repoModel.getObject()));
+ }
+
+ public Repository getRepository() {
+ return repoModel.getObject();
+ }
+
+ @Override
+ protected void onDetach() {
+ repoModel.detach();
+
+ super.onDetach();
+ }
+
+ protected abstract void onSelect(AjaxRequestTarget target, Repository repository);
+
+ @Override
+ protected Component newContextHead(String componentId) {
+ Fragment fragment = new Fragment(componentId, "contextHeadFrag", this);
+ WebMarkupContainer accountAndRepo = new WebMarkupContainer("accountAndRepo");
+ fragment.add(accountAndRepo);
+ Link<Void> accountLink = new BookmarkablePageLink<>("accountLink", AccountReposPage.class, paramsOf(getAccount()));
+ accountLink.add(new Label("accountName", getAccount().getName()));
+ accountAndRepo.add(accountLink);
+
+ Link<Void> repoLink = new BookmarkablePageLink<>("repoLink", RepoFilePage.class, paramsOf(getRepository()));
+ repoLink.add(new Label("repoName", getRepository().getName()));
+ accountAndRepo.add(repoLink);
+
+ fragment.add(new DropdownLink("repoChoiceTrigger") {
+
+ @Override
+ protected void onInitialize(FloatingPanel dropdown) {
+ super.onInitialize(dropdown);
+ dropdown.add(AttributeAppender.append("class", " repo-choice"));
+ }
+
+ @Override
+ protected Component newContent(String id) {
+ return new RepositorySelector(id, null, repoModel) {
+
+ @Override
+ protected void onSelect(AjaxRequestTarget target, Repository repository) {
+ RepositoryPage.this.onSelect(target, repository);
+ }
+
+ };
+ }
+
+ });
+
+ UrlManager urlManager = GitPlex.getInstance(UrlManager.class);
+ Model<String> cloneUrlModel = Model.of(urlManager.urlFor(getRepository()));
+ fragment.add(new TextField<String>("cloneUrl", cloneUrlModel));
+
+ return fragment;
+ }
+
+}
diff --git a/gitplex.web/src/main/java/com/pmease/gitplex/web/page/repository/commit/RepoCommitPage.java b/gitplex.web/src/main/java/com/pmease/gitplex/web/page/repository/commit/RepoCommitPage.java
index 48e7eec3dd..90fb6ffe96 100644
--- a/gitplex.web/src/main/java/com/pmease/gitplex/web/page/repository/commit/RepoCommitPage.java
+++ b/gitplex.web/src/main/java/com/pmease/gitplex/web/page/repository/commit/RepoCommitPage.java
@@ -1,359 +1,359 @@
-package com.pmease.gitplex.web.page.repository.commit;
-
-import java.io.IOException;
-import java.io.Serializable;
-import java.util.ArrayList;
-import java.util.List;
-
-import javax.annotation.Nullable;
-
-import org.apache.wicket.ajax.AjaxRequestTarget;
-import org.apache.wicket.ajax.attributes.AjaxRequestAttributes;
-import org.apache.wicket.ajax.form.OnChangeAjaxBehavior;
-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.WebMarkupContainer;
-import org.apache.wicket.markup.html.basic.Label;
-import org.apache.wicket.markup.html.form.DropDownChoice;
-import org.apache.wicket.markup.html.form.IChoiceRenderer;
-import org.apache.wicket.markup.html.link.BookmarkablePageLink;
-import org.apache.wicket.markup.html.link.Link;
-import org.apache.wicket.markup.html.list.ListItem;
-import org.apache.wicket.markup.html.list.ListView;
-import org.apache.wicket.model.IModel;
-import org.apache.wicket.model.LoadableDetachableModel;
-import org.apache.wicket.model.Model;
-import org.apache.wicket.request.cycle.RequestCycle;
-import org.apache.wicket.request.mapper.parameter.PageParameters;
-import org.apache.wicket.request.resource.CssResourceReference;
-import org.eclipse.jgit.errors.RevisionSyntaxException;
-import org.eclipse.jgit.internal.storage.file.FileRepository;
-import org.eclipse.jgit.lib.ObjectId;
-import org.eclipse.jgit.revwalk.RevCommit;
-import org.eclipse.jgit.revwalk.RevWalk;
-
-import com.google.common.base.Preconditions;
-import com.pmease.commons.git.GitUtils;
-import com.pmease.commons.wicket.ajaxlistener.IndicateLoadingListener;
-import com.pmease.gitplex.core.model.Comment;
-import com.pmease.gitplex.core.model.PullRequest;
-import com.pmease.gitplex.core.model.Repository;
-import com.pmease.gitplex.web.component.commithash.CommitHashPanel;
-import com.pmease.gitplex.web.component.diff.revision.RevisionDiffPanel;
-import com.pmease.gitplex.web.component.diff.revision.option.DiffOptionPanel;
-import com.pmease.gitplex.web.component.personlink.PersonLink;
-import com.pmease.gitplex.web.page.repository.RepositoryPage;
-import com.pmease.gitplex.web.page.repository.file.RepoFilePage;
-import com.pmease.gitplex.web.page.repository.file.RepoFileState;
-import com.pmease.gitplex.web.utils.DateUtils;
-
-@SuppressWarnings("serial")
-public class RepoCommitPage extends RepositoryPage {
-
- private static final String PARAM_REVISION = "revision";
-
- private static final String PARAM_COMPARE_WITH = "compareWith";
-
- private static final String PARAM_PATH = "path";
-
- protected String revision;
-
- private HistoryState state = new HistoryState();
-
- private IModel<RevCommit> commitModel = new LoadableDetachableModel<RevCommit>() {
-
- @Override
- protected RevCommit load() {
- try( FileRepository jgitRepo = getRepository().openAsJGitRepo();
- RevWalk revWalk = new RevWalk(jgitRepo);) {
- ObjectId objectId;
- if (GitUtils.isHash(revision))
- objectId = ObjectId.fromString(revision);
- else
- objectId = jgitRepo.resolve(revision);
- return revWalk.parseCommit(objectId);
- } catch (RevisionSyntaxException | IOException e) {
- throw new RuntimeException(e);
- }
- }
-
- };
-
- private DiffOptionPanel diffOption;
-
- private RevisionDiffPanel compareResult;
-
- public RepoCommitPage(PageParameters params) {
- super(params);
-
- revision = GitUtils.normalizePath(params.get(PARAM_REVISION).toString());
- state = new HistoryState(params);
- }
-
- private RevCommit getCommit() {
- return commitModel.getObject();
- }
-
- private List<String> getParents() {
- List<String> parents = new ArrayList<>();
- for (RevCommit parent: getCommit().getParents())
- parents.add(parent.name());
- return parents;
- }
-
- @Override
- protected void onInitialize() {
- super.onInitialize();
-
- add(new Label("title", GitUtils.getShortMessage(getCommit())));
- add(new CommitHashPanel("hash", Model.of(getCommit().name())));
-
- RepoFileState state = new RepoFileState();
- state.blobIdent.revision = getCommit().name();
- add(new BookmarkablePageLink<Void>("code", RepoFilePage.class,
- RepoFilePage.paramsOf(repoModel.getObject(), state)));
-
- String detailMessage = GitUtils.getDetailMessage(getCommit());
- if (detailMessage != null)
- add(new Label("detail", detailMessage));
- else
- add(new WebMarkupContainer("detail").setVisible(false));
-
- add(new ListView<String>("refs", new LoadableDetachableModel<List<String>>() {
-
- @Override
- protected List<String> load() {
- return new ArrayList<>();
- }
-
- }) {
-
- @Override
- protected void populateItem(ListItem<String> item) {
- String ref = item.getModelObject();
- String branch = GitUtils.ref2branch(ref);
- if (branch != null) {
- RepoFileState state = new RepoFileState();
- state.blobIdent.revision = branch;
- Link<Void> link = new BookmarkablePageLink<Void>("link", RepoFilePage.class,
- RepoFilePage.paramsOf(repoModel.getObject(), state));
- link.add(new Label("label", branch));
- link.add(AttributeAppender.append("class", "branch"));
- item.add(link);
- } else {
- String tag = Preconditions.checkNotNull(GitUtils.ref2tag(ref));
- RepoFileState state = new RepoFileState();
- state.blobIdent.revision = tag;
- Link<Void> link = new BookmarkablePageLink<Void>("link", RepoFilePage.class,
- RepoFilePage.paramsOf(repoModel.getObject(), state));
- link.add(new Label("label", tag));
- link.add(AttributeAppender.append("class", "tag"));
- item.add(link);
- }
- }
-
- });
- add(new PersonLink("author", Model.of(getCommit().getAuthorIdent())));
- add(new Label("age", DateUtils.formatAge(getCommit().getAuthorIdent().getWhen())));
-
- add(new ListView<String>("parents", new LoadableDetachableModel<List<String>>() {
-
- @Override
- protected List<String> load() {
- return getParents();
- }
-
- }) {
-
- @Override
- protected void populateItem(ListItem<String> item) {
- String parent = item.getModelObject();
- Link<Void> link = new BookmarkablePageLink<Void>("link", RepoCommitPage.class,
- paramsOf(repoModel.getObject(), parent));
- link.add(new Label("label", GitUtils.abbreviateSHA(parent)));
- item.add(link);
- }
-
- });
-
- add(new DropDownChoice<String>("compareWith", new IModel<String>() {
-
- @Override
- public void detach() {
- }
-
- @Override
- public String getObject() {
- return getCompareWith();
- }
-
- @Override
- public void setObject(String object) {
- RepoCommitPage.this.state.compareWith = object;
- }
-
- }, new LoadableDetachableModel<List<String>>() {
-
- @Override
- protected List<String> load() {
- return getParents();
- }
-
- }, new IChoiceRenderer<String>() {
-
- @Override
- public Object getDisplayValue(String object) {
- return GitUtils.abbreviateSHA(object);
- }
-
- @Override
- public String getIdValue(String object, int index) {
- return object;
- }
-
- }) {
-
- @Override
- protected void onConfigure() {
- super.onConfigure();
- setVisible(getCommit().getParentCount()>1);
- }
-
- }.add(new OnChangeAjaxBehavior() {
-
- @Override
- protected void updateAjaxAttributes(AjaxRequestAttributes attributes) {
- super.updateAjaxAttributes(attributes);
- attributes.getAjaxCallListeners().add(new IndicateLoadingListener());
- }
-
- @Override
- protected void onUpdate(AjaxRequestTarget target) {
- newCompareResult(target);
- pushState(target);
- }
-
- }));
-
- if (getCommit().getParentCount() != 0) {
- add(diffOption = new DiffOptionPanel("diffOption", repoModel, getCommit().name()) {
-
- @Override
- protected void onSelectPath(AjaxRequestTarget target, String path) {
- RepoCommitPage.this.state.path = path;
- newCompareResult(target);
- pushState(target);
- }
-
- @Override
- protected void onLineProcessorChange(AjaxRequestTarget target) {
- newCompareResult(target);
- }
-
- @Override
- protected void onDiffModeChange(AjaxRequestTarget target) {
- newCompareResult(target);
- }
-
- });
- newCompareResult(null);
- } else {
- add(new WebMarkupContainer("diffOption").setVisible(false));
- add(new WebMarkupContainer("compareResult").setVisible(false));
- }
- }
-
- private void newCompareResult(@Nullable AjaxRequestTarget target) {
- compareResult = new RevisionDiffPanel("compareResult", repoModel,
- Model.of((PullRequest)null), Model.of((Comment)null), getCompareWith(),
- getCommit().name(), state.path, state.path, diffOption.getLineProcessor(),
- diffOption.getDiffMode()) {
-
- @Override
- protected void onClearPath(AjaxRequestTarget target) {
- state.path = null;
- newCompareResult(target);
- pushState(target);
- }
-
- };
- compareResult.setOutputMarkupId(true);
- if (target != null) {
- replace(compareResult);
- target.add(compareResult);
- } else {
- add(compareResult);
- }
- }
-
- @Override
- public void renderHead(IHeaderResponse response) {
- super.renderHead(response);
- response.render(CssHeaderItem.forReference(new CssResourceReference(
- RepoCommitPage.class, "repo-commit.css")));
- }
-
- public static PageParameters paramsOf(Repository repository, String revision) {
- return paramsOf(repository, revision, new HistoryState());
- }
-
- public static PageParameters paramsOf(Repository repository, String revision, HistoryState state) {
- PageParameters params = paramsOf(repository);
- params.set(PARAM_REVISION, revision);
- if (state.compareWith != null)
- params.set(PARAM_COMPARE_WITH, state.compareWith);
- if (state.path != null)
- params.set(PARAM_PATH, state.path);
- return params;
- }
-
- @Override
- protected void onSelect(AjaxRequestTarget target, Repository repository) {
- setResponsePage(RepoCommitsPage.class, paramsOf(repository));
- }
-
- private String getCompareWith() {
- if (state.compareWith == null)
- state.compareWith = getCommit().getParents()[0].name();
- return state.compareWith;
- }
-
- @Override
- protected void onDetach() {
- commitModel.detach();
-
- super.onDetach();
- }
-
- private void pushState(AjaxRequestTarget target) {
- PageParameters params = paramsOf(getRepository(), getCommit().name(), state);
- CharSequence url = RequestCycle.get().urlFor(RepoCommitsPage.class, params);
- pushState(target, url.toString(), state);
- }
-
- @Override
- protected void onPopState(AjaxRequestTarget target, Serializable data) {
- super.onPopState(target, data);
-
- state = (HistoryState) data;
- newCompareResult(target);
- }
-
- public static class HistoryState implements Serializable {
-
- private static final long serialVersionUID = 1L;
-
- public String compareWith;
-
- public String path;
-
- public HistoryState() {
- }
-
- public HistoryState(PageParameters params) {
- compareWith = params.get(PARAM_COMPARE_WITH).toString();
- path = params.get(PARAM_PATH).toString();
- }
- }
-}
+package com.pmease.gitplex.web.page.repository.commit;
+
+import java.io.IOException;
+import java.io.Serializable;
+import java.util.ArrayList;
+import java.util.List;
+
+import javax.annotation.Nullable;
+
+import org.apache.wicket.ajax.AjaxRequestTarget;
+import org.apache.wicket.ajax.attributes.AjaxRequestAttributes;
+import org.apache.wicket.ajax.form.OnChangeAjaxBehavior;
+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.WebMarkupContainer;
+import org.apache.wicket.markup.html.basic.Label;
+import org.apache.wicket.markup.html.form.DropDownChoice;
+import org.apache.wicket.markup.html.form.IChoiceRenderer;
+import org.apache.wicket.markup.html.link.BookmarkablePageLink;
+import org.apache.wicket.markup.html.link.Link;
+import org.apache.wicket.markup.html.list.ListItem;
+import org.apache.wicket.markup.html.list.ListView;
+import org.apache.wicket.model.IModel;
+import org.apache.wicket.model.LoadableDetachableModel;
+import org.apache.wicket.model.Model;
+import org.apache.wicket.request.cycle.RequestCycle;
+import org.apache.wicket.request.mapper.parameter.PageParameters;
+import org.apache.wicket.request.resource.CssResourceReference;
+import org.eclipse.jgit.errors.RevisionSyntaxException;
+import org.eclipse.jgit.internal.storage.file.FileRepository;
+import org.eclipse.jgit.lib.ObjectId;
+import org.eclipse.jgit.revwalk.RevCommit;
+import org.eclipse.jgit.revwalk.RevWalk;
+
+import com.google.common.base.Preconditions;
+import com.pmease.commons.git.GitUtils;
+import com.pmease.commons.wicket.ajaxlistener.IndicateLoadingListener;
+import com.pmease.gitplex.core.model.Comment;
+import com.pmease.gitplex.core.model.PullRequest;
+import com.pmease.gitplex.core.model.Repository;
+import com.pmease.gitplex.web.component.commithash.CommitHashPanel;
+import com.pmease.gitplex.web.component.diff.revision.RevisionDiffPanel;
+import com.pmease.gitplex.web.component.diff.revision.option.DiffOptionPanel;
+import com.pmease.gitplex.web.component.personlink.PersonLink;
+import com.pmease.gitplex.web.page.repository.RepositoryPage;
+import com.pmease.gitplex.web.page.repository.file.RepoFilePage;
+import com.pmease.gitplex.web.page.repository.file.RepoFileState;
+import com.pmease.gitplex.web.utils.DateUtils;
+
+@SuppressWarnings("serial")
+public class RepoCommitPage extends RepositoryPage {
+
+ private static final String PARAM_REVISION = "revision";
+
+ private static final String PARAM_COMPARE_WITH = "compareWith";
+
+ private static final String PARAM_PATH = "path";
+
+ protected String revision;
+
+ private HistoryState state = new HistoryState();
+
+ private IModel<RevCommit> commitModel = new LoadableDetachableModel<RevCommit>() {
+
+ @Override
+ protected RevCommit load() {
+ try( FileRepository jgitRepo = getRepository().openAsJGitRepo();
+ RevWalk revWalk = new RevWalk(jgitRepo);) {
+ ObjectId objectId;
+ if (GitUtils.isHash(revision))
+ objectId = ObjectId.fromString(revision);
+ else
+ objectId = jgitRepo.resolve(revision);
+ return revWalk.parseCommit(objectId);
+ } catch (RevisionSyntaxException | IOException e) {
+ throw new RuntimeException(e);
+ }
+ }
+
+ };
+
+ private DiffOptionPanel diffOption;
+
+ private RevisionDiffPanel compareResult;
+
+ public RepoCommitPage(PageParameters params) {
+ super(params);
+
+ revision = GitUtils.normalizePath(params.get(PARAM_REVISION).toString());
+ state = new HistoryState(params);
+ }
+
+ private RevCommit getCommit() {
+ return commitModel.getObject();
+ }
+
+ private List<String> getParents() {
+ List<String> parents = new ArrayList<>();
+ for (RevCommit parent: getCommit().getParents())
+ parents.add(parent.name());
+ return parents;
+ }
+
+ @Override
+ protected void onInitialize() {
+ super.onInitialize();
+
+ add(new Label("title", GitUtils.getShortMessage(getCommit())));
+ add(new CommitHashPanel("hash", Model.of(getCommit().name())));
+
+ RepoFileState state = new RepoFileState();
+ state.blobIdent.revision = getCommit().name();
+ add(new BookmarkablePageLink<Void>("code", RepoFilePage.class,
+ RepoFilePage.paramsOf(repoModel.getObject(), state)));
+
+ String detailMessage = GitUtils.getDetailMessage(getCommit());
+ if (detailMessage != null)
+ add(new Label("detail", detailMessage));
+ else
+ add(new WebMarkupContainer("detail").setVisible(false));
+
+ add(new ListView<String>("refs", new LoadableDetachableModel<List<String>>() {
+
+ @Override
+ protected List<String> load() {
+ return new ArrayList<>();
+ }
+
+ }) {
+
+ @Override
+ protected void populateItem(ListItem<String> item) {
+ String ref = item.getModelObject();
+ String branch = GitUtils.ref2branch(ref);
+ if (branch != null) {
+ RepoFileState state = new RepoFileState();
+ state.blobIdent.revision = branch;
+ Link<Void> link = new BookmarkablePageLink<Void>("link", RepoFilePage.class,
+ RepoFilePage.paramsOf(repoModel.getObject(), state));
+ link.add(new Label("label", branch));
+ link.add(AttributeAppender.append("class", "branch"));
+ item.add(link);
+ } else {
+ String tag = Preconditions.checkNotNull(GitUtils.ref2tag(ref));
+ RepoFileState state = new RepoFileState();
+ state.blobIdent.revision = tag;
+ Link<Void> link = new BookmarkablePageLink<Void>("link", RepoFilePage.class,
+ RepoFilePage.paramsOf(repoModel.getObject(), state));
+ link.add(new Label("label", tag));
+ link.add(AttributeAppender.append("class", "tag"));
+ item.add(link);
+ }
+ }
+
+ });
+ add(new PersonLink("author", Model.of(getCommit().getAuthorIdent())));
+ add(new Label("age", DateUtils.formatAge(getCommit().getAuthorIdent().getWhen())));
+
+ add(new ListView<String>("parents", new LoadableDetachableModel<List<String>>() {
+
+ @Override
+ protected List<String> load() {
+ return getParents();
+ }
+
+ }) {
+
+ @Override
+ protected void populateItem(ListItem<String> item) {
+ String parent = item.getModelObject();
+ Link<Void> link = new BookmarkablePageLink<Void>("link", RepoCommitPage.class,
+ paramsOf(repoModel.getObject(), parent));
+ link.add(new Label("label", GitUtils.abbreviateSHA(parent)));
+ item.add(link);
+ }
+
+ });
+
+ add(new DropDownChoice<String>("compareWith", new IModel<String>() {
+
+ @Override
+ public void detach() {
+ }
+
+ @Override
+ public String getObject() {
+ return getCompareWith();
+ }
+
+ @Override
+ public void setObject(String object) {
+ RepoCommitPage.this.state.compareWith = object;
+ }
+
+ }, new LoadableDetachableModel<List<String>>() {
+
+ @Override
+ protected List<String> load() {
+ return getParents();
+ }
+
+ }, new IChoiceRenderer<String>() {
+
+ @Override
+ public Object getDisplayValue(String object) {
+ return GitUtils.abbreviateSHA(object);
+ }
+
+ @Override
+ public String getIdValue(String object, int index) {
+ return object;
+ }
+
+ }) {
+
+ @Override
+ protected void onConfigure() {
+ super.onConfigure();
+ setVisible(getCommit().getParentCount()>1);
+ }
+
+ }.add(new OnChangeAjaxBehavior() {
+
+ @Override
+ protected void updateAjaxAttributes(AjaxRequestAttributes attributes) {
+ super.updateAjaxAttributes(attributes);
+ attributes.getAjaxCallListeners().add(new IndicateLoadingListener());
+ }
+
+ @Override
+ protected void onUpdate(AjaxRequestTarget target) {
+ newCompareResult(target);
+ pushState(target);
+ }
+
+ }));
+
+ if (getCommit().getParentCount() != 0) {
+ add(diffOption = new DiffOptionPanel("diffOption", repoModel, getCommit().name()) {
+
+ @Override
+ protected void onSelectPath(AjaxRequestTarget target, String path) {
+ RepoCommitPage.this.state.path = path;
+ newCompareResult(target);
+ pushState(target);
+ }
+
+ @Override
+ protected void onLineProcessorChange(AjaxRequestTarget target) {
+ newCompareResult(target);
+ }
+
+ @Override
+ protected void onDiffModeChange(AjaxRequestTarget target) {
+ newCompareResult(target);
+ }
+
+ });
+ newCompareResult(null);
+ } else {
+ add(new WebMarkupContainer("diffOption").setVisible(false));
+ add(new WebMarkupContainer("compareResult").setVisible(false));
+ }
+ }
+
+ private void newCompareResult(@Nullable AjaxRequestTarget target) {
+ compareResult = new RevisionDiffPanel("compareResult", repoModel,
+ Model.of((PullRequest)null), Model.of((Comment)null), getCompareWith(),
+ getCommit().name(), state.path, state.path, diffOption.getLineProcessor(),
+ diffOption.getDiffMode()) {
+
+ @Override
+ protected void onClearPath(AjaxRequestTarget target) {
+ state.path = null;
+ newCompareResult(target);
+ pushState(target);
+ }
+
+ };
+ compareResult.setOutputMarkupId(true);
+ if (target != null) {
+ replace(compareResult);
+ target.add(compareResult);
+ } else {
+ add(compareResult);
+ }
+ }
+
+ @Override
+ public void renderHead(IHeaderResponse response) {
+ super.renderHead(response);
+ response.render(CssHeaderItem.forReference(new CssResourceReference(
+ RepoCommitPage.class, "repo-commit.css")));
+ }
+
+ public static PageParameters paramsOf(Repository repository, String revision) {
+ return paramsOf(repository, revision, new HistoryState());
+ }
+
+ public static PageParameters paramsOf(Repository repository, String revision, HistoryState state) {
+ PageParameters params = paramsOf(repository);
+ params.set(PARAM_REVISION, revision);
+ if (state.compareWith != null)
+ params.set(PARAM_COMPARE_WITH, state.compareWith);
+ if (state.path != null)
+ params.set(PARAM_PATH, state.path);
+ return params;
+ }
+
+ @Override
+ protected void onSelect(AjaxRequestTarget target, Repository repository) {
+ setResponsePage(RepoCommitsPage.class, paramsOf(repository));
+ }
+
+ private String getCompareWith() {
+ if (state.compareWith == null)
+ state.compareWith = getCommit().getParents()[0].name();
+ return state.compareWith;
+ }
+
+ @Override
+ protected void onDetach() {
+ commitModel.detach();
+
+ super.onDetach();
+ }
+
+ private void pushState(AjaxRequestTarget target) {
+ PageParameters params = paramsOf(getRepository(), getCommit().name(), state);
+ CharSequence url = RequestCycle.get().urlFor(RepoCommitPage.class, params);
+ pushState(target, url.toString(), state);
+ }
+
+ @Override
+ protected void onPopState(AjaxRequestTarget target, Serializable data) {
+ super.onPopState(target, data);
+
+ state = (HistoryState) data;
+ newCompareResult(target);
+ }
+
+ public static class HistoryState implements Serializable {
+
+ private static final long serialVersionUID = 1L;
+
+ public String compareWith;
+
+ public String path;
+
+ public HistoryState() {
+ }
+
+ public HistoryState(PageParameters params) {
+ compareWith = params.get(PARAM_COMPARE_WITH).toString();
+ path = params.get(PARAM_PATH).toString();
+ }
+ }
+}
diff --git a/gitplex.web/src/main/java/com/pmease/gitplex/web/page/repository/pullrequest/newrequest/NewRequestPage.java b/gitplex.web/src/main/java/com/pmease/gitplex/web/page/repository/pullrequest/newrequest/NewRequestPage.java
index 71835a725b..875096a372 100644
--- a/gitplex.web/src/main/java/com/pmease/gitplex/web/page/repository/pullrequest/newrequest/NewRequestPage.java
+++ b/gitplex.web/src/main/java/com/pmease/gitplex/web/page/repository/pullrequest/newrequest/NewRequestPage.java
@@ -1,667 +1,667 @@
-package com.pmease.gitplex.web.page.repository.pullrequest.newrequest;
-
-import static com.pmease.gitplex.core.model.PullRequest.Status.INTEGRATED;
-import static com.pmease.gitplex.core.model.PullRequest.Status.PENDING_UPDATE;
-
-import java.util.ArrayList;
-import java.util.Collections;
-import java.util.Date;
-import java.util.List;
-
-import org.apache.wicket.Component;
-import org.apache.wicket.RestartResponseAtInterceptPageException;
-import org.apache.wicket.RestartResponseException;
-import org.apache.wicket.ajax.AjaxRequestTarget;
-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.WebMarkupContainer;
-import org.apache.wicket.markup.html.basic.Label;
-import org.apache.wicket.markup.html.form.Button;
-import org.apache.wicket.markup.html.form.Form;
-import org.apache.wicket.markup.html.form.TextField;
-import org.apache.wicket.markup.html.link.Link;
-import org.apache.wicket.markup.html.list.ListItem;
-import org.apache.wicket.markup.html.list.ListView;
-import org.apache.wicket.markup.html.panel.Fragment;
-import org.apache.wicket.model.AbstractReadOnlyModel;
-import org.apache.wicket.model.IModel;
-import org.apache.wicket.model.LoadableDetachableModel;
-import org.apache.wicket.model.Model;
-import org.apache.wicket.model.PropertyModel;
-import org.apache.wicket.request.mapper.parameter.PageParameters;
-import org.apache.wicket.request.resource.CssResourceReference;
-
-import com.google.common.base.Preconditions;
-import com.pmease.commons.git.Commit;
-import com.pmease.commons.git.Git;
-import com.pmease.commons.hibernate.dao.Dao;
-import com.pmease.commons.util.FileUtils;
-import com.pmease.commons.wicket.behavior.StickyBehavior;
-import com.pmease.commons.wicket.component.backtotop.BackToTop;
-import com.pmease.commons.wicket.component.tabbable.AjaxActionTab;
-import com.pmease.commons.wicket.component.tabbable.Tab;
-import com.pmease.commons.wicket.component.tabbable.Tabbable;
-import com.pmease.commons.wicket.websocket.WebSocketRenderBehavior.PageId;
-import com.pmease.gitplex.core.GitPlex;
-import com.pmease.gitplex.core.manager.PullRequestManager;
-import com.pmease.gitplex.core.model.CloseInfo;
-import com.pmease.gitplex.core.model.Comment;
-import com.pmease.gitplex.core.model.PullRequest;
-import com.pmease.gitplex.core.model.PullRequest.IntegrationStrategy;
-import com.pmease.gitplex.core.model.PullRequest.Status;
-import com.pmease.gitplex.core.model.PullRequestUpdate;
-import com.pmease.gitplex.core.model.RepoAndBranch;
-import com.pmease.gitplex.core.model.Repository;
-import com.pmease.gitplex.core.model.ReviewInvitation;
-import com.pmease.gitplex.core.model.User;
-import com.pmease.gitplex.core.permission.ObjectPermission;
-import com.pmease.gitplex.web.component.BranchLink;
-import com.pmease.gitplex.web.component.branchchoice.affinalchoice.AffinalBranchSingleChoice;
-import com.pmease.gitplex.web.component.comment.CommentInput;
-import com.pmease.gitplex.web.component.commitlist.CommitListPanel;
-import com.pmease.gitplex.web.component.diff.revision.RevisionDiffPanel;
-import com.pmease.gitplex.web.component.diff.revision.option.DiffOptionPanel;
-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.model.ReviewersModel;
-import com.pmease.gitplex.web.page.repository.NoCommitsPage;
-import com.pmease.gitplex.web.page.repository.RepositoryPage;
-import com.pmease.gitplex.web.page.repository.pullrequest.PullRequestPage;
-import com.pmease.gitplex.web.page.repository.pullrequest.requestdetail.RequestDetailPage;
-import com.pmease.gitplex.web.page.repository.pullrequest.requestdetail.overview.RequestOverviewPage;
-import com.pmease.gitplex.web.page.repository.pullrequest.requestlist.RequestListPage;
-import com.pmease.gitplex.web.page.security.LoginPage;
-
-import de.agilecoders.wicket.core.markup.html.bootstrap.common.NotificationPanel;
-
-@SuppressWarnings("serial")
-public class NewRequestPage extends PullRequestPage {
-
- private static final String TAB_PANEL_ID = "tabPanel";
-
- private AffinalBranchSingleChoice targetChoice, sourceChoice;
-
- private IModel<List<Commit>> commitsModel;
-
- private IModel<PullRequest> requestModel;
-
- private DiffOptionPanel diffOption;
-
- private String path;
-
- public static PageParameters paramsOf(Repository repository, RepoAndBranch source, RepoAndBranch target) {
- PageParameters params = paramsOf(repository);
- params.set("source", source.getId());
- params.set("target", target.getId());
- return params;
- }
-
- public NewRequestPage(PageParameters params) {
- super(params);
-
- if (!getRepository().git().hasCommits())
- throw new RestartResponseException(NoCommitsPage.class, paramsOf(getRepository()));
-
- RepoAndBranch target, source = null;
- if (params.get("target").toString() != null) {
- target = new RepoAndBranch(params.get("target").toString());
- } else {
- if (getRepository().getForkedFrom() != null) {
- target = new RepoAndBranch(getRepository().getForkedFrom(),
- getRepository().getForkedFrom().getDefaultBranch());
- } else {
- target = new RepoAndBranch(getRepository(), getRepository().getDefaultBranch());
- }
- }
- if (params.get("source").toString() != null) {
- source = new RepoAndBranch(params.get("source").toString());
- } else {
- if (getRepository().getForkedFrom() != null) {
- source = new RepoAndBranch(getRepository(), getRepository().getDefaultBranch());
- } else {
- for (String each: getRepository().getBranches()) {
- if (!each.equals(target.getBranch())) {
- source = new RepoAndBranch(getRepository(), each);
- break;
- }
- }
- if (source == null)
- source = target;
- }
- }
-
- User currentUser = getCurrentUser();
- if (currentUser == null)
- throw new RestartResponseAtInterceptPageException(LoginPage.class);
-
- PullRequest pullRequest = GitPlex.getInstance(PullRequestManager.class).findOpen(target, source);
-
- if (pullRequest == null) {
- pullRequest = new PullRequest();
- pullRequest.setTarget(target);
- pullRequest.setSource(source);
- pullRequest.setSubmitter(currentUser);
-
- PullRequestUpdate update = new PullRequestUpdate();
- pullRequest.addUpdate(update);
- update.setRequest(pullRequest);
- update.setHeadCommitHash(source.getHead());
- pullRequest.setLastEventDate(new Date());
-
- PullRequestManager pullRequestManager = GitPlex.getInstance(PullRequestManager.class);
- List<IntegrationStrategy> strategies = pullRequestManager.getApplicableIntegrationStrategies(pullRequest);
- Preconditions.checkState(!strategies.isEmpty());
- pullRequest.setIntegrationStrategy(strategies.get(0));
-
- ObjectPermission writePermission = ObjectPermission.ofRepoPush(getRepository());
- if (currentUser.asSubject().isPermitted(writePermission))
- pullRequest.setAssignee(currentUser);
- else
- pullRequest.setAssignee(getRepository().getOwner());
-
- if (target.getRepository().equals(source.getRepository())) {
- pullRequest.setBaseCommitHash(pullRequest.git().calcMergeBase(
- target.getHead(), source.getHead()));
- if (target.getRepository().git().isAncestor(source.getHead(), target.getHead())) {
- CloseInfo closeInfo = new CloseInfo();
- closeInfo.setCloseDate(new Date());
- closeInfo.setCloseStatus(CloseInfo.Status.INTEGRATED);
- pullRequest.setCloseInfo(closeInfo);
- }
- } else {
- Git sandbox = new Git(FileUtils.createTempDir());
- pullRequest.setSandbox(sandbox);
- sandbox.clone(target.getRepository().git(), false, true, true, pullRequest.getTarget().getBranch());
- sandbox.reset(null, null);
-
- sandbox.fetch(source.getRepository().git(), source.getBranch());
-
- pullRequest.setBaseCommitHash(pullRequest.git().calcMergeBase(target.getHead(), source.getHead()));
-
- if (sandbox.isAncestor(source.getHead(), target.getHead())) {
- CloseInfo closeInfo = new CloseInfo();
- closeInfo.setCloseDate(new Date());
- closeInfo.setCloseStatus(CloseInfo.Status.INTEGRATED);
- pullRequest.setCloseInfo(closeInfo);
- }
- }
- requestModel = Model.of(pullRequest);
- } else {
- final Long requestId = pullRequest.getId();
- requestModel = new LoadableDetachableModel<PullRequest>() {
-
- @Override
- protected PullRequest load() {
- return GitPlex.getInstance(Dao.class).load(PullRequest.class, requestId);
- }
-
- };
- requestModel.setObject(pullRequest);
- }
-
- commitsModel = new LoadableDetachableModel<List<Commit>>() {
-
- @Override
- protected List<Commit> load() {
- PullRequest request = getPullRequest();
- List<Commit> commits = request.git().log(request.getBaseCommitHash(),
- request.getLatestUpdate().getHeadCommitHash(), null, 0, 0, false);
- Collections.reverse(commits);
- return commits;
- }
-
- };
-
- }
-
- private PullRequest getPullRequest() {
- return requestModel.getObject();
- }
-
- @Override
- protected void onInitialize() {
- super.onInitialize();
-
- setOutputMarkupId(true);
-
- IModel<Repository> currentRepositoryModel = new LoadableDetachableModel<Repository>() {
-
- @Override
- protected Repository load() {
- RepositoryPage page = (RepositoryPage) getPage();
- return page.getRepository();
- }
-
- };
-
- targetChoice = new AffinalBranchSingleChoice("target", currentRepositoryModel,
- Model.of(getPullRequest().getTarget().getId()), false) {
-
- @Override
- protected void onChange(AjaxRequestTarget target) {
- super.onChange(target);
-
- PageParameters params = paramsOf(getRepository(),
- new RepoAndBranch(sourceChoice.getModelObject()),
- new RepoAndBranch(targetChoice.getModelObject()));
- setResponsePage(NewRequestPage.class, params);
- }
-
- };
- targetChoice.setRequired(true);
- add(targetChoice);
-
- sourceChoice = new AffinalBranchSingleChoice("source", currentRepositoryModel,
- Model.of(getPullRequest().getSource().getId()), false) {
-
- @Override
- protected void onChange(AjaxRequestTarget target) {
- super.onChange(target);
-
- PageParameters params = paramsOf(getRepository(),
- new RepoAndBranch(sourceChoice.getModelObject()),
- new RepoAndBranch(targetChoice.getModelObject()));
- setResponsePage(NewRequestPage.class, params);
- }
-
- };
- sourceChoice.setRequired(true);
- add(sourceChoice);
-
- add(new Link<Void>("swap") {
-
- @Override
- public void onClick() {
- setResponsePage(
- NewRequestPage.class,
- paramsOf(getRepository(), getPullRequest().getTarget(), getPullRequest().getSource()));
- }
-
- });
-
- Fragment fragment;
- if (getPullRequest().getId() != null) {
- fragment = newOpenedFrag();
- } else if (getPullRequest().getSource().equals(getPullRequest().getTarget())) {
- fragment = newSameBranchFrag();
- } else if (getPullRequest().getStatus() == INTEGRATED) {
- fragment = newIntegratedFrag();
- } else if (getPullRequest().getStatus() == PENDING_UPDATE) {
- fragment = newRejectedFrag();
- } else {
- fragment = newCanSendFrag();
- }
- add(fragment);
-
- List<Tab> tabs = new ArrayList<>();
-
- tabs.add(new AjaxActionTab(Model.of("Commits")) {
-
- @Override
- protected void onSelect(AjaxRequestTarget target, Component tabLink) {
- Component panel = newCommitsPanel();
- getPage().replace(panel);
- target.add(panel);
- }
-
- });
-
- tabs.add(new AjaxActionTab(Model.of("Files Changed")) {
-
- @Override
- protected void onSelect(AjaxRequestTarget target, Component tabLink) {
- Component panel = newComparePanel();
- getPage().replace(panel);
- target.add(panel);
- }
-
- });
-
- add(new Tabbable("tabs", tabs) {
-
- @Override
- protected void onConfigure() {
- super.onConfigure();
-
- setVisible(getPullRequest().getStatus() != INTEGRATED);
- }
-
- });
-
- add(newCommitsPanel());
-
- add(new BackToTop("backToTop"));
- }
-
- private Component newCommitsPanel() {
- return new CommitListPanel(TAB_PANEL_ID, repoModel, commitsModel).setOutputMarkupId(true);
- }
-
- private Component newComparePanel() {
- final Fragment fragment = new Fragment(TAB_PANEL_ID, "compareFrag", this);
-
- diffOption = new DiffOptionPanel("diffOption", repoModel, getPullRequest().getLatestUpdate().getHeadCommitHash()) {
-
- @Override
- protected void onSelectPath(AjaxRequestTarget target, String path) {
- NewRequestPage.this.path = path;
- RevisionDiffPanel diffPanel = newRevDiffPanel();
- fragment.replace(diffPanel);
- target.add(diffPanel);
- }
-
- @Override
- protected void onLineProcessorChange(AjaxRequestTarget target) {
- RevisionDiffPanel diffPanel = newRevDiffPanel();
- fragment.replace(diffPanel);
- target.add(diffPanel);
- }
-
- @Override
- protected void onDiffModeChange(AjaxRequestTarget target) {
- RevisionDiffPanel diffPanel = newRevDiffPanel();
- fragment.replace(diffPanel);
- target.add(diffPanel);
- }
-
- };
- diffOption.add(new StickyBehavior());
- fragment.add(diffOption);
- fragment.add(newRevDiffPanel());
-
- return fragment;
- }
-
- protected RevisionDiffPanel newRevDiffPanel() {
- PullRequest request = getPullRequest();
- String oldRev = request.getBaseCommitHash();
- String newRev = request.getLatestUpdate().getHeadCommitHash();
-
- RevisionDiffPanel diffPanel = new RevisionDiffPanel("revisionDiff", repoModel, new Model<PullRequest>(null),
- new Model<Comment>(null), oldRev, newRev, path, null, diffOption.getLineProcessor(),
- diffOption.getDiffMode()) {
-
- @Override
- protected void onClearPath(AjaxRequestTarget target) {
- path = null;
- RevisionDiffPanel diffPanel = newRevDiffPanel();
- replaceWith(diffPanel);
- target.add(diffPanel);
- }
-
- };
- diffPanel.setOutputMarkupId(true);
- return diffPanel;
- }
-
- private Fragment newOpenedFrag() {
- Fragment fragment = new Fragment("status", "openedFrag", this);
- fragment.add(new Link<Void>("view") {
-
- @Override
- protected void onInitialize() {
- super.onInitialize();
- add(new Label("no", new AbstractReadOnlyModel<String>() {
-
- @Override
- public String getObject() {
- return getPullRequest().getId().toString();
- }
- }));
- }
-
- @Override
- public void onClick() {
- PageParameters params = RequestDetailPage.paramsOf(getPullRequest());
- setResponsePage(RequestOverviewPage.class, params);
- }
-
- });
-
- fragment.add(new Label("title", new AbstractReadOnlyModel<String>() {
-
- @Override
- public String getObject() {
- return getPullRequest().getTitle();
- }
- }));
-
- return fragment;
- }
-
- private Fragment newSameBranchFrag() {
- return new Fragment("status", "sameBranchFrag", this);
- }
-
- private Fragment newIntegratedFrag() {
- Fragment fragment = new Fragment("status", "integratedFrag", this);
- fragment.add(new BranchLink("sourceBranch", getPullRequest().getSource()));
- fragment.add(new BranchLink("targetBranch", getPullRequest().getTarget()));
- fragment.add(new Link<Void>("swapBranches") {
-
- @Override
- public void onClick() {
- setResponsePage(
- NewRequestPage.class,
- paramsOf(getRepository(), getPullRequest().getTarget(), getPullRequest().getSource()));
- }
-
- });
- return fragment;
- }
-
- private Fragment newRejectedFrag() {
- Fragment fragment = new Fragment("status", "rejectedFrag", this);
- fragment.add(new ListView<String>("reasons", new LoadableDetachableModel<List<String>>() {
-
- @Override
- protected List<String> load() {
- return getPullRequest().getCheckResult().getReasons();
- }
-
- }) {
-
- @Override
- protected void populateItem(ListItem<String> item) {
- item.add(new Label("reason", item.getModelObject()));
- }
-
- });
-
- return fragment;
- }
-
- private Fragment newCanSendFrag() {
- Fragment fragment = new Fragment("status", "canSendFrag", this);
- final Form<?> form = new Form<Void>("form");
- fragment.add(form);
-
- form.add(new Button("send") {
-
- @Override
- public void onSubmit() {
- super.onSubmit();
-
- Dao dao = GitPlex.getInstance(Dao.class);
- RepoAndBranch target = getPullRequest().getTarget();
- RepoAndBranch source = getPullRequest().getSource();
- if (!target.getHead().equals(getPullRequest().getTarget().getHead())
- || !source.getHead().equals(getPullRequest().getSource().getHead())) {
- getSession().warn("Either target branch or source branch has new commits just now, please re-check.");
- setResponsePage(NewRequestPage.class, paramsOf(getRepository(), source, target));
- } else {
- getPullRequest().setSource(source);
- getPullRequest().setTarget(target);
- for (ReviewInvitation invitation: getPullRequest().getReviewInvitations())
- invitation.setReviewer(dao.load(User.class, invitation.getReviewer().getId()));
-
- getPullRequest().setAssignee(dao.load(User.class, getPullRequest().getAssignee().getId()));
-
- GitPlex.getInstance(PullRequestManager.class).open(getPullRequest(), new PageId(getPageId()));
-
- setResponsePage(RequestOverviewPage.class, RequestOverviewPage.paramsOf(getPullRequest()));
- }
- }
-
- });
-
- WebMarkupContainer titleContainer = new WebMarkupContainer("title");
- form.add(titleContainer);
- final TextField<String> titleInput = new TextField<String>("title", new IModel<String>() {
-
- @Override
- public void detach() {
- }
-
- @Override
- public String getObject() {
- if (getPullRequest().getTitle() == null) {
- List<Commit> commits = commitsModel.getObject();
- Preconditions.checkState(!commits.isEmpty());
- if (commits.size() == 1)
- getPullRequest().setTitle(commits.get(0).getSubject());
- else
- getPullRequest().setTitle(getPullRequest().getSource().getBranch());
- }
- return getPullRequest().getTitle();
- }
-
- @Override
- public void setObject(String object) {
- getPullRequest().setTitle(object);
- }
-
- });
- titleInput.setRequired(true);
- titleContainer.add(titleInput);
-
- titleContainer.add(new NotificationPanel("feedback", titleInput));
-
- titleContainer.add(AttributeAppender.append("class", new AbstractReadOnlyModel<String>() {
-
- @Override
- public String getObject() {
- return !titleInput.isValid()?" has-error":"";
- }
-
- }));
-
- form.add(new CommentInput("comment", requestModel, new IModel<String>() {
-
- @Override
- public void detach() {
- }
-
- @Override
- public String getObject() {
- return getPullRequest().getDescription();
- }
-
- @Override
- public void setObject(String object) {
- getPullRequest().setDescription(object);
- }
-
- }));
-
- WebMarkupContainer assigneeContainer = new WebMarkupContainer("assignee");
- form.add(assigneeContainer);
- IModel<User> assigneeModel = new PropertyModel<>(getPullRequest(), "assignee");
- final AssigneeChoice assigneeChoice = new AssigneeChoice("assignee", repoModel, assigneeModel);
- assigneeChoice.setRequired(true);
- assigneeContainer.add(assigneeChoice);
-
- assigneeContainer.add(new NotificationPanel("feedback", assigneeChoice));
-
- assigneeContainer.add(AttributeAppender.append("class", new AbstractReadOnlyModel<String>() {
-
- @Override
- public String getObject() {
- return !assigneeChoice.isValid()?" has-error":"";
- }
-
- }));
-
- final WebMarkupContainer reviewersContainer = new WebMarkupContainer("reviewers") {
-
- @Override
- protected void onBeforeRender() {
- super.onBeforeRender();
- }
-
- };
- reviewersContainer.setOutputMarkupId(true);
- form.add(reviewersContainer);
- reviewersContainer.add(new ListView<ReviewInvitation>("reviewers", new ReviewersModel(requestModel)) {
-
- @Override
- protected void populateItem(ListItem<ReviewInvitation> item) {
- ReviewInvitation invitation = item.getModelObject();
-
- item.add(new ReviewerAvatar("avatar", invitation) {
-
- @Override
- protected void onAvatarRemove(AjaxRequestTarget target) {
- super.onAvatarRemove(target);
-
- target.add(reviewersContainer);
- }
-
- });
- }
-
- });
-
- reviewersContainer.add(new ReviewerChoice("addReviewer", requestModel) {
-
- @Override
- protected void onSelect(AjaxRequestTarget target, User user) {
- super.onSelect(target, user);
-
- target.add(reviewersContainer);
- }
-
- });
-
- reviewersContainer.add(new WebMarkupContainer("prePopulateHint") {
-
- @Override
- protected void onConfigure() {
- super.onConfigure();
- setVisible(getPullRequest().getStatus() == Status.PENDING_APPROVAL);
- }
-
- });
-
- return fragment;
- }
-
- @Override
- public void renderHead(IHeaderResponse response) {
- super.renderHead(response);
- response.render(CssHeaderItem.forReference(
- new CssResourceReference(NewRequestPage.class, "new-request.css")));
- }
-
- @Override
- protected void onDetach() {
- commitsModel.detach();
-
- if (getPullRequest() != null && getPullRequest().getSandbox() != null) {
- FileUtils.deleteDir(getPullRequest().getSandbox().repoDir());
- getPullRequest().setSandbox(null);
- }
-
- requestModel.detach();
-
- super.onDetach();
- }
-
- @Override
- protected void onSelect(AjaxRequestTarget target, Repository repository) {
- setResponsePage(RequestListPage.class, paramsOf(repository));
- }
-
-}
+package com.pmease.gitplex.web.page.repository.pullrequest.newrequest;
+
+import static com.pmease.gitplex.core.model.PullRequest.Status.INTEGRATED;
+import static com.pmease.gitplex.core.model.PullRequest.Status.PENDING_UPDATE;
+
+import java.util.ArrayList;
+import java.util.Collections;
+import java.util.Date;
+import java.util.List;
+
+import org.apache.wicket.Component;
+import org.apache.wicket.RestartResponseAtInterceptPageException;
+import org.apache.wicket.RestartResponseException;
+import org.apache.wicket.ajax.AjaxRequestTarget;
+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.WebMarkupContainer;
+import org.apache.wicket.markup.html.basic.Label;
+import org.apache.wicket.markup.html.form.Button;
+import org.apache.wicket.markup.html.form.Form;
+import org.apache.wicket.markup.html.form.TextField;
+import org.apache.wicket.markup.html.link.Link;
+import org.apache.wicket.markup.html.list.ListItem;
+import org.apache.wicket.markup.html.list.ListView;
+import org.apache.wicket.markup.html.panel.Fragment;
+import org.apache.wicket.model.AbstractReadOnlyModel;
+import org.apache.wicket.model.IModel;
+import org.apache.wicket.model.LoadableDetachableModel;
+import org.apache.wicket.model.Model;
+import org.apache.wicket.model.PropertyModel;
+import org.apache.wicket.request.mapper.parameter.PageParameters;
+import org.apache.wicket.request.resource.CssResourceReference;
+
+import com.google.common.base.Preconditions;
+import com.pmease.commons.git.Commit;
+import com.pmease.commons.git.Git;
+import com.pmease.commons.hibernate.dao.Dao;
+import com.pmease.commons.util.FileUtils;
+import com.pmease.commons.wicket.behavior.StickyBehavior;
+import com.pmease.commons.wicket.component.backtotop.BackToTop;
+import com.pmease.commons.wicket.component.tabbable.AjaxActionTab;
+import com.pmease.commons.wicket.component.tabbable.Tab;
+import com.pmease.commons.wicket.component.tabbable.Tabbable;
+import com.pmease.commons.wicket.websocket.WebSocketRenderBehavior.PageId;
+import com.pmease.gitplex.core.GitPlex;
+import com.pmease.gitplex.core.manager.PullRequestManager;
+import com.pmease.gitplex.core.model.CloseInfo;
+import com.pmease.gitplex.core.model.Comment;
+import com.pmease.gitplex.core.model.PullRequest;
+import com.pmease.gitplex.core.model.PullRequest.IntegrationStrategy;
+import com.pmease.gitplex.core.model.PullRequest.Status;
+import com.pmease.gitplex.core.model.PullRequestUpdate;
+import com.pmease.gitplex.core.model.RepoAndBranch;
+import com.pmease.gitplex.core.model.Repository;
+import com.pmease.gitplex.core.model.ReviewInvitation;
+import com.pmease.gitplex.core.model.User;
+import com.pmease.gitplex.core.permission.ObjectPermission;
+import com.pmease.gitplex.web.component.BranchLink;
+import com.pmease.gitplex.web.component.branchchoice.affinalchoice.AffinalBranchSingleChoice;
+import com.pmease.gitplex.web.component.comment.CommentInput;
+import com.pmease.gitplex.web.component.commitlist.CommitListPanel;
+import com.pmease.gitplex.web.component.diff.revision.RevisionDiffPanel;
+import com.pmease.gitplex.web.component.diff.revision.option.DiffOptionPanel;
+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.model.ReviewersModel;
+import com.pmease.gitplex.web.page.repository.NoCommitsPage;
+import com.pmease.gitplex.web.page.repository.RepositoryPage;
+import com.pmease.gitplex.web.page.repository.pullrequest.PullRequestPage;
+import com.pmease.gitplex.web.page.repository.pullrequest.requestdetail.RequestDetailPage;
+import com.pmease.gitplex.web.page.repository.pullrequest.requestdetail.overview.RequestOverviewPage;
+import com.pmease.gitplex.web.page.repository.pullrequest.requestlist.RequestListPage;
+import com.pmease.gitplex.web.page.security.LoginPage;
+
+import de.agilecoders.wicket.core.markup.html.bootstrap.common.NotificationPanel;
+
+@SuppressWarnings("serial")
+public class NewRequestPage extends PullRequestPage {
+
+ private static final String TAB_PANEL_ID = "tabPanel";
+
+ private AffinalBranchSingleChoice targetChoice, sourceChoice;
+
+ private IModel<List<Commit>> commitsModel;
+
+ private IModel<PullRequest> requestModel;
+
+ private DiffOptionPanel diffOption;
+
+ private String path;
+
+ public static PageParameters paramsOf(Repository repository, RepoAndBranch source, RepoAndBranch target) {
+ PageParameters params = paramsOf(repository);
+ params.set("source", source.getId());
+ params.set("target", target.getId());
+ return params;
+ }
+
+ public NewRequestPage(PageParameters params) {
+ super(params);
+
+ if (!getRepository().git().hasCommits())
+ throw new RestartResponseException(NoCommitsPage.class, paramsOf(getRepository()));
+
+ RepoAndBranch target, source = null;
+ if (params.get("target").toString() != null) {
+ target = new RepoAndBranch(params.get("target").toString());
+ } else {
+ if (getRepository().getForkedFrom() != null) {
+ target = new RepoAndBranch(getRepository().getForkedFrom(),
+ getRepository().getForkedFrom().getDefaultBranch());
+ } else {
+ target = new RepoAndBranch(getRepository(), getRepository().getDefaultBranch());
+ }
+ }
+ if (params.get("source").toString() != null) {
+ source = new RepoAndBranch(params.get("source").toString());
+ } else {
+ if (getRepository().getForkedFrom() != null) {
+ source = new RepoAndBranch(getRepository(), getRepository().getDefaultBranch());
+ } else {
+ for (String each: getRepository().getBranches()) {
+ if (!each.equals(target.getBranch())) {
+ source = new RepoAndBranch(getRepository(), each);
+ break;
+ }
+ }
+ if (source == null)
+ source = target;
+ }
+ }
+
+ User currentUser = getCurrentUser();
+ if (currentUser == null)
+ throw new RestartResponseAtInterceptPageException(LoginPage.class);
+
+ PullRequest pullRequest = GitPlex.getInstance(PullRequestManager.class).findOpen(target, source);
+
+ if (pullRequest == null) {
+ pullRequest = new PullRequest();
+ pullRequest.setTarget(target);
+ pullRequest.setSource(source);
+ pullRequest.setSubmitter(currentUser);
+
+ PullRequestUpdate update = new PullRequestUpdate();
+ pullRequest.addUpdate(update);
+ update.setRequest(pullRequest);
+ update.setHeadCommitHash(source.getHead());
+ pullRequest.setLastEventDate(new Date());
+
+ PullRequestManager pullRequestManager = GitPlex.getInstance(PullRequestManager.class);
+ List<IntegrationStrategy> strategies = pullRequestManager.getApplicableIntegrationStrategies(pullRequest);
+ Preconditions.checkState(!strategies.isEmpty());
+ pullRequest.setIntegrationStrategy(strategies.get(0));
+
+ ObjectPermission writePermission = ObjectPermission.ofRepoPush(getRepository());
+ if (currentUser.asSubject().isPermitted(writePermission))
+ pullRequest.setAssignee(currentUser);
+ else
+ pullRequest.setAssignee(getRepository().getOwner());
+
+ if (target.getRepository().equals(source.getRepository())) {
+ pullRequest.setBaseCommitHash(pullRequest.git().calcMergeBase(
+ target.getHead(), source.getHead()));
+ if (target.getRepository().isAncestor(source.getHead(), target.getHead())) {
+ CloseInfo closeInfo = new CloseInfo();
+ closeInfo.setCloseDate(new Date());
+ closeInfo.setCloseStatus(CloseInfo.Status.INTEGRATED);
+ pullRequest.setCloseInfo(closeInfo);
+ }
+ } else {
+ Git sandbox = new Git(FileUtils.createTempDir());
+ pullRequest.setSandbox(sandbox);
+ sandbox.clone(target.getRepository().git(), false, true, true, pullRequest.getTarget().getBranch());
+ sandbox.reset(null, null);
+
+ sandbox.fetch(source.getRepository().git(), source.getBranch());
+
+ pullRequest.setBaseCommitHash(pullRequest.git().calcMergeBase(target.getHead(), source.getHead()));
+
+ if (sandbox.isAncestor(source.getHead(), target.getHead())) {
+ CloseInfo closeInfo = new CloseInfo();
+ closeInfo.setCloseDate(new Date());
+ closeInfo.setCloseStatus(CloseInfo.Status.INTEGRATED);
+ pullRequest.setCloseInfo(closeInfo);
+ }
+ }
+ requestModel = Model.of(pullRequest);
+ } else {
+ final Long requestId = pullRequest.getId();
+ requestModel = new LoadableDetachableModel<PullRequest>() {
+
+ @Override
+ protected PullRequest load() {
+ return GitPlex.getInstance(Dao.class).load(PullRequest.class, requestId);
+ }
+
+ };
+ requestModel.setObject(pullRequest);
+ }
+
+ commitsModel = new LoadableDetachableModel<List<Commit>>() {
+
+ @Override
+ protected List<Commit> load() {
+ PullRequest request = getPullRequest();
+ List<Commit> commits = request.git().log(request.getBaseCommitHash(),
+ request.getLatestUpdate().getHeadCommitHash(), null, 0, 0, false);
+ Collections.reverse(commits);
+ return commits;
+ }
+
+ };
+
+ }
+
+ private PullRequest getPullRequest() {
+ return requestModel.getObject();
+ }
+
+ @Override
+ protected void onInitialize() {
+ super.onInitialize();
+
+ setOutputMarkupId(true);
+
+ IModel<Repository> currentRepositoryModel = new LoadableDetachableModel<Repository>() {
+
+ @Override
+ protected Repository load() {
+ RepositoryPage page = (RepositoryPage) getPage();
+ return page.getRepository();
+ }
+
+ };
+
+ targetChoice = new AffinalBranchSingleChoice("target", currentRepositoryModel,
+ Model.of(getPullRequest().getTarget().getId()), false) {
+
+ @Override
+ protected void onChange(AjaxRequestTarget target) {
+ super.onChange(target);
+
+ PageParameters params = paramsOf(getRepository(),
+ new RepoAndBranch(sourceChoice.getModelObject()),
+ new RepoAndBranch(targetChoice.getModelObject()));
+ setResponsePage(NewRequestPage.class, params);
+ }
+
+ };
+ targetChoice.setRequired(true);
+ add(targetChoice);
+
+ sourceChoice = new AffinalBranchSingleChoice("source", currentRepositoryModel,
+ Model.of(getPullRequest().getSource().getId()), false) {
+
+ @Override
+ protected void onChange(AjaxRequestTarget target) {
+ super.onChange(target);
+
+ PageParameters params = paramsOf(getRepository(),
+ new RepoAndBranch(sourceChoice.getModelObject()),
+ new RepoAndBranch(targetChoice.getModelObject()));
+ setResponsePage(NewRequestPage.class, params);
+ }
+
+ };
+ sourceChoice.setRequired(true);
+ add(sourceChoice);
+
+ add(new Link<Void>("swap") {
+
+ @Override
+ public void onClick() {
+ setResponsePage(
+ NewRequestPage.class,
+ paramsOf(getRepository(), getPullRequest().getTarget(), getPullRequest().getSource()));
+ }
+
+ });
+
+ Fragment fragment;
+ if (getPullRequest().getId() != null) {
+ fragment = newOpenedFrag();
+ } else if (getPullRequest().getSource().equals(getPullRequest().getTarget())) {
+ fragment = newSameBranchFrag();
+ } else if (getPullRequest().getStatus() == INTEGRATED) {
+ fragment = newIntegratedFrag();
+ } else if (getPullRequest().getStatus() == PENDING_UPDATE) {
+ fragment = newRejectedFrag();
+ } else {
+ fragment = newCanSendFrag();
+ }
+ add(fragment);
+
+ List<Tab> tabs = new ArrayList<>();
+
+ tabs.add(new AjaxActionTab(Model.of("Commits")) {
+
+ @Override
+ protected void onSelect(AjaxRequestTarget target, Component tabLink) {
+ Component panel = newCommitsPanel();
+ getPage().replace(panel);
+ target.add(panel);
+ }
+
+ });
+
+ tabs.add(new AjaxActionTab(Model.of("Files Changed")) {
+
+ @Override
+ protected void onSelect(AjaxRequestTarget target, Component tabLink) {
+ Component panel = newComparePanel();
+ getPage().replace(panel);
+ target.add(panel);
+ }
+
+ });
+
+ add(new Tabbable("tabs", tabs) {
+
+ @Override
+ protected void onConfigure() {
+ super.onConfigure();
+
+ setVisible(getPullRequest().getStatus() != INTEGRATED);
+ }
+
+ });
+
+ add(newCommitsPanel());
+
+ add(new BackToTop("backToTop"));
+ }
+
+ private Component newCommitsPanel() {
+ return new CommitListPanel(TAB_PANEL_ID, repoModel, commitsModel).setOutputMarkupId(true);
+ }
+
+ private Component newComparePanel() {
+ final Fragment fragment = new Fragment(TAB_PANEL_ID, "compareFrag", this);
+
+ diffOption = new DiffOptionPanel("diffOption", repoModel, getPullRequest().getLatestUpdate().getHeadCommitHash()) {
+
+ @Override
+ protected void onSelectPath(AjaxRequestTarget target, String path) {
+ NewRequestPage.this.path = path;
+ RevisionDiffPanel diffPanel = newRevDiffPanel();
+ fragment.replace(diffPanel);
+ target.add(diffPanel);
+ }
+
+ @Override
+ protected void onLineProcessorChange(AjaxRequestTarget target) {
+ RevisionDiffPanel diffPanel = newRevDiffPanel();
+ fragment.replace(diffPanel);
+ target.add(diffPanel);
+ }
+
+ @Override
+ protected void onDiffModeChange(AjaxRequestTarget target) {
+ RevisionDiffPanel diffPanel = newRevDiffPanel();
+ fragment.replace(diffPanel);
+ target.add(diffPanel);
+ }
+
+ };
+ diffOption.add(new StickyBehavior());
+ fragment.add(diffOption);
+ fragment.add(newRevDiffPanel());
+
+ return fragment;
+ }
+
+ protected RevisionDiffPanel newRevDiffPanel() {
+ PullRequest request = getPullRequest();
+ String oldRev = request.getBaseCommitHash();
+ String newRev = request.getLatestUpdate().getHeadCommitHash();
+
+ RevisionDiffPanel diffPanel = new RevisionDiffPanel("revisionDiff", repoModel, new Model<PullRequest>(null),
+ new Model<Comment>(null), oldRev, newRev, path, null, diffOption.getLineProcessor(),
+ diffOption.getDiffMode()) {
+
+ @Override
+ protected void onClearPath(AjaxRequestTarget target) {
+ path = null;
+ RevisionDiffPanel diffPanel = newRevDiffPanel();
+ replaceWith(diffPanel);
+ target.add(diffPanel);
+ }
+
+ };
+ diffPanel.setOutputMarkupId(true);
+ return diffPanel;
+ }
+
+ private Fragment newOpenedFrag() {
+ Fragment fragment = new Fragment("status", "openedFrag", this);
+ fragment.add(new Link<Void>("view") {
+
+ @Override
+ protected void onInitialize() {
+ super.onInitialize();
+ add(new Label("no", new AbstractReadOnlyModel<String>() {
+
+ @Override
+ public String getObject() {
+ return getPullRequest().getId().toString();
+ }
+ }));
+ }
+
+ @Override
+ public void onClick() {
+ PageParameters params = RequestDetailPage.paramsOf(getPullRequest());
+ setResponsePage(RequestOverviewPage.class, params);
+ }
+
+ });
+
+ fragment.add(new Label("title", new AbstractReadOnlyModel<String>() {
+
+ @Override
+ public String getObject() {
+ return getPullRequest().getTitle();
+ }
+ }));
+
+ return fragment;
+ }
+
+ private Fragment newSameBranchFrag() {
+ return new Fragment("status", "sameBranchFrag", this);
+ }
+
+ private Fragment newIntegratedFrag() {
+ Fragment fragment = new Fragment("status", "integratedFrag", this);
+ fragment.add(new BranchLink("sourceBranch", getPullRequest().getSource()));
+ fragment.add(new BranchLink("targetBranch", getPullRequest().getTarget()));
+ fragment.add(new Link<Void>("swapBranches") {
+
+ @Override
+ public void onClick() {
+ setResponsePage(
+ NewRequestPage.class,
+ paramsOf(getRepository(), getPullRequest().getTarget(), getPullRequest().getSource()));
+ }
+
+ });
+ return fragment;
+ }
+
+ private Fragment newRejectedFrag() {
+ Fragment fragment = new Fragment("status", "rejectedFrag", this);
+ fragment.add(new ListView<String>("reasons", new LoadableDetachableModel<List<String>>() {
+
+ @Override
+ protected List<String> load() {
+ return getPullRequest().getCheckResult().getReasons();
+ }
+
+ }) {
+
+ @Override
+ protected void populateItem(ListItem<String> item) {
+ item.add(new Label("reason", item.getModelObject()));
+ }
+
+ });
+
+ return fragment;
+ }
+
+ private Fragment newCanSendFrag() {
+ Fragment fragment = new Fragment("status", "canSendFrag", this);
+ final Form<?> form = new Form<Void>("form");
+ fragment.add(form);
+
+ form.add(new Button("send") {
+
+ @Override
+ public void onSubmit() {
+ super.onSubmit();
+
+ Dao dao = GitPlex.getInstance(Dao.class);
+ RepoAndBranch target = getPullRequest().getTarget();
+ RepoAndBranch source = getPullRequest().getSource();
+ if (!target.getHead().equals(getPullRequest().getTarget().getHead())
+ || !source.getHead().equals(getPullRequest().getSource().getHead())) {
+ getSession().warn("Either target branch or source branch has new commits just now, please re-check.");
+ setResponsePage(NewRequestPage.class, paramsOf(getRepository(), source, target));
+ } else {
+ getPullRequest().setSource(source);
+ getPullRequest().setTarget(target);
+ for (ReviewInvitation invitation: getPullRequest().getReviewInvitations())
+ invitation.setReviewer(dao.load(User.class, invitation.getReviewer().getId()));
+
+ getPullRequest().setAssignee(dao.load(User.class, getPullRequest().getAssignee().getId()));
+
+ GitPlex.getInstance(PullRequestManager.class).open(getPullRequest(), new PageId(getPageId()));
+
+ setResponsePage(RequestOverviewPage.class, RequestOverviewPage.paramsOf(getPullRequest()));
+ }
+ }
+
+ });
+
+ WebMarkupContainer titleContainer = new WebMarkupContainer("title");
+ form.add(titleContainer);
+ final TextField<String> titleInput = new TextField<String>("title", new IModel<String>() {
+
+ @Override
+ public void detach() {
+ }
+
+ @Override
+ public String getObject() {
+ if (getPullRequest().getTitle() == null) {
+ List<Commit> commits = commitsModel.getObject();
+ Preconditions.checkState(!commits.isEmpty());
+ if (commits.size() == 1)
+ getPullRequest().setTitle(commits.get(0).getSubject());
+ else
+ getPullRequest().setTitle(getPullRequest().getSource().getBranch());
+ }
+ return getPullRequest().getTitle();
+ }
+
+ @Override
+ public void setObject(String object) {
+ getPullRequest().setTitle(object);
+ }
+
+ });
+ titleInput.setRequired(true);
+ titleContainer.add(titleInput);
+
+ titleContainer.add(new NotificationPanel("feedback", titleInput));
+
+ titleContainer.add(AttributeAppender.append("class", new AbstractReadOnlyModel<String>() {
+
+ @Override
+ public String getObject() {
+ return !titleInput.isValid()?" has-error":"";
+ }
+
+ }));
+
+ form.add(new CommentInput("comment", requestModel, new IModel<String>() {
+
+ @Override
+ public void detach() {
+ }
+
+ @Override
+ public String getObject() {
+ return getPullRequest().getDescription();
+ }
+
+ @Override
+ public void setObject(String object) {
+ getPullRequest().setDescription(object);
+ }
+
+ }));
+
+ WebMarkupContainer assigneeContainer = new WebMarkupContainer("assignee");
+ form.add(assigneeContainer);
+ IModel<User> assigneeModel = new PropertyModel<>(getPullRequest(), "assignee");
+ final AssigneeChoice assigneeChoice = new AssigneeChoice("assignee", repoModel, assigneeModel);
+ assigneeChoice.setRequired(true);
+ assigneeContainer.add(assigneeChoice);
+
+ assigneeContainer.add(new NotificationPanel("feedback", assigneeChoice));
+
+ assigneeContainer.add(AttributeAppender.append("class", new AbstractReadOnlyModel<String>() {
+
+ @Override
+ public String getObject() {
+ return !assigneeChoice.isValid()?" has-error":"";
+ }
+
+ }));
+
+ final WebMarkupContainer reviewersContainer = new WebMarkupContainer("reviewers") {
+
+ @Override
+ protected void onBeforeRender() {
+ super.onBeforeRender();
+ }
+
+ };
+ reviewersContainer.setOutputMarkupId(true);
+ form.add(reviewersContainer);
+ reviewersContainer.add(new ListView<ReviewInvitation>("reviewers", new ReviewersModel(requestModel)) {
+
+ @Override
+ protected void populateItem(ListItem<ReviewInvitation> item) {
+ ReviewInvitation invitation = item.getModelObject();
+
+ item.add(new ReviewerAvatar("avatar", invitation) {
+
+ @Override
+ protected void onAvatarRemove(AjaxRequestTarget target) {
+ super.onAvatarRemove(target);
+
+ target.add(reviewersContainer);
+ }
+
+ });
+ }
+
+ });
+
+ reviewersContainer.add(new ReviewerChoice("addReviewer", requestModel) {
+
+ @Override
+ protected void onSelect(AjaxRequestTarget target, User user) {
+ super.onSelect(target, user);
+
+ target.add(reviewersContainer);
+ }
+
+ });
+
+ reviewersContainer.add(new WebMarkupContainer("prePopulateHint") {
+
+ @Override
+ protected void onConfigure() {
+ super.onConfigure();
+ setVisible(getPullRequest().getStatus() == Status.PENDING_APPROVAL);
+ }
+
+ });
+
+ return fragment;
+ }
+
+ @Override
+ public void renderHead(IHeaderResponse response) {
+ super.renderHead(response);
+ response.render(CssHeaderItem.forReference(
+ new CssResourceReference(NewRequestPage.class, "new-request.css")));
+ }
+
+ @Override
+ protected void onDetach() {
+ commitsModel.detach();
+
+ if (getPullRequest() != null && getPullRequest().getSandbox() != null) {
+ FileUtils.deleteDir(getPullRequest().getSandbox().repoDir());
+ getPullRequest().setSandbox(null);
+ }
+
+ requestModel.detach();
+
+ super.onDetach();
+ }
+
+ @Override
+ protected void onSelect(AjaxRequestTarget target, Repository repository) {
+ setResponsePage(RequestListPage.class, paramsOf(repository));
+ }
+
+}
diff --git a/gitplex.web/src/main/java/com/pmease/gitplex/web/page/repository/pullrequest/requestdetail/PullRequestOperation.java b/gitplex.web/src/main/java/com/pmease/gitplex/web/page/repository/pullrequest/requestdetail/PullRequestOperation.java
index 96bad1b31f..805914c92a 100644
--- a/gitplex.web/src/main/java/com/pmease/gitplex/web/page/repository/pullrequest/requestdetail/PullRequestOperation.java
+++ b/gitplex.web/src/main/java/com/pmease/gitplex/web/page/repository/pullrequest/requestdetail/PullRequestOperation.java
@@ -1,172 +1,172 @@
-package com.pmease.gitplex.web.page.repository.pullrequest.requestdetail;
-
-import javax.annotation.Nullable;
-
-import com.pmease.commons.git.Git;
-import com.pmease.gitplex.core.GitPlex;
-import com.pmease.gitplex.core.manager.PullRequestManager;
-import com.pmease.gitplex.core.manager.ReviewManager;
-import com.pmease.gitplex.core.manager.UserManager;
-import com.pmease.gitplex.core.model.IntegrationPreview;
-import com.pmease.gitplex.core.model.PullRequest;
-import com.pmease.gitplex.core.model.PullRequest.Status;
-import com.pmease.gitplex.core.model.Review;
-import com.pmease.gitplex.core.model.ReviewInvitation;
-import com.pmease.gitplex.core.model.User;
-import com.pmease.gitplex.core.permission.ObjectPermission;
-import com.pmease.gitplex.core.security.SecurityUtils;
-
-public enum PullRequestOperation {
- INTEGRATE {
-
- @Override
- public boolean canOperate(PullRequest request) {
- if (!SecurityUtils.getSubject().isPermitted(
- ObjectPermission.ofRepoPush(request.getTargetRepo()))) {
- return false;
- } else {
- return GitPlex.getInstance(PullRequestManager.class).canIntegrate(request);
- }
- }
-
- @Override
- public void operate(PullRequest request, String comment) {
- GitPlex.getInstance(PullRequestManager.class).integrate(request, comment);
- }
-
- },
- DISCARD {
-
- @Override
- public boolean canOperate(PullRequest request) {
- if (!SecurityUtils.canModify(request))
- return false;
- else
- return request.isOpen();
- }
-
- @Override
- public void operate(PullRequest request, String comment) {
- GitPlex.getInstance(PullRequestManager.class).discard(request, comment);
- }
-
- },
- APPROVE {
-
- @Override
- public boolean canOperate(PullRequest request) {
- return canReview(request);
- }
-
- @Override
- public void operate(PullRequest request, String comment) {
- User user = GitPlex.getInstance(UserManager.class).getCurrent();
- GitPlex.getInstance(ReviewManager.class).review(
- request, user, Review.Result.APPROVE, comment);
- }
-
- },
- DISAPPROVE {
-
- @Override
- public boolean canOperate(PullRequest request) {
- return canReview(request);
- }
-
- @Override
- public void operate(PullRequest request, String comment) {
- User user = GitPlex.getInstance(UserManager.class).getCurrent();
- GitPlex.getInstance(ReviewManager.class).review(
- request, user, Review.Result.DISAPPROVE, comment);
- }
-
- },
- REOPEN {
-
- @Override
- public boolean canOperate(PullRequest request) {
- PullRequestManager pullRequestManager = GitPlex.getInstance(PullRequestManager.class);
- if (request.isOpen()
- || !SecurityUtils.canModify(request)
- || request.getTarget().getHead(false) == null
- || request.getSourceRepo() == null
- || request.getSource().getHead(false) == null
- || pullRequestManager.findOpen(request.getTarget(), request.getSource()) != null) {
- return false;
- }
-
- // now check if source branch is integrated into target branch
- Git git = request.getTargetRepo().git();
- String sourceHead = request.getSource().getHead();
- return git.parseRevision(sourceHead, false) == null
- || !git.isAncestor(sourceHead, request.getTarget().getHead());
- }
-
- @Override
- public void operate(PullRequest request, String comment) {
- GitPlex.getInstance(PullRequestManager.class).reopen(request, comment);
- }
-
- },
- DELETE_SOURCE_BRANCH {
-
- @Override
- public void operate(PullRequest request, String comment) {
- GitPlex.getInstance(PullRequestManager.class).deleteSourceBranch(request);
- }
-
- @Override
- public boolean canOperate(PullRequest request) {
- IntegrationPreview preview = request.getLastIntegrationPreview();
- PullRequestManager pullRequestManager = GitPlex.getInstance(PullRequestManager.class);
- return request.getStatus() == Status.INTEGRATED
- && request.getSourceRepo() != null
- && request.getSource().getHead(false) != null
- && !request.getSource().isDefault()
- && preview != null
- && (request.getSource().getHead().equals(preview.getRequestHead())
- || request.getSource().getHead().equals(preview.getIntegrated()))
- && SecurityUtils.canModify(request)
- && SecurityUtils.canModify(request.getSource())
- && pullRequestManager.queryOpenTo(request.getSource(), null).isEmpty();
- }
-
- },
- RESTORE_SOURCE_BRANCH {
-
- @Override
- public void operate(PullRequest request, String comment) {
- GitPlex.getInstance(PullRequestManager.class).restoreSourceBranch(request);
- }
-
- @Override
- public boolean canOperate(PullRequest request) {
- return request.getSourceRepo() != null && request.getSource().getHead(false) == null
- && SecurityUtils.canModify(request) && SecurityUtils.canCreate(request.getSource());
- }
-
- };
-
- private static boolean canReview(PullRequest request) {
- User user = GitPlex.getInstance(UserManager.class).getCurrent();
-
- // call request.getStatus() in order to trigger generation of review
- // integrations which will be used in else condition
- if (user == null
- || request.getStatus() == PullRequest.Status.INTEGRATED
- || request.getStatus() == PullRequest.Status.DISCARDED
- || request.isReviewEffective(user)) {
- return false;
- } else {
- for (ReviewInvitation invitation: request.getReviewInvitations()) {
- if (invitation.isPreferred() && invitation.getReviewer().equals(user))
- return true;
- }
- return false;
- }
- }
-
- public abstract void operate(PullRequest request, @Nullable String comment);
-
- public abstract boolean canOperate(PullRequest request);
-}
+package com.pmease.gitplex.web.page.repository.pullrequest.requestdetail;
+
+import javax.annotation.Nullable;
+
+import com.pmease.commons.git.Git;
+import com.pmease.gitplex.core.GitPlex;
+import com.pmease.gitplex.core.manager.PullRequestManager;
+import com.pmease.gitplex.core.manager.ReviewManager;
+import com.pmease.gitplex.core.manager.UserManager;
+import com.pmease.gitplex.core.model.IntegrationPreview;
+import com.pmease.gitplex.core.model.PullRequest;
+import com.pmease.gitplex.core.model.PullRequest.Status;
+import com.pmease.gitplex.core.model.Review;
+import com.pmease.gitplex.core.model.ReviewInvitation;
+import com.pmease.gitplex.core.model.User;
+import com.pmease.gitplex.core.permission.ObjectPermission;
+import com.pmease.gitplex.core.security.SecurityUtils;
+
+public enum PullRequestOperation {
+ INTEGRATE {
+
+ @Override
+ public boolean canOperate(PullRequest request) {
+ if (!SecurityUtils.getSubject().isPermitted(
+ ObjectPermission.ofRepoPush(request.getTargetRepo()))) {
+ return false;
+ } else {
+ return GitPlex.getInstance(PullRequestManager.class).canIntegrate(request);
+ }
+ }
+
+ @Override
+ public void operate(PullRequest request, String comment) {
+ GitPlex.getInstance(PullRequestManager.class).integrate(request, comment);
+ }
+
+ },
+ DISCARD {
+
+ @Override
+ public boolean canOperate(PullRequest request) {
+ if (!SecurityUtils.canModify(request))
+ return false;
+ else
+ return request.isOpen();
+ }
+
+ @Override
+ public void operate(PullRequest request, String comment) {
+ GitPlex.getInstance(PullRequestManager.class).discard(request, comment);
+ }
+
+ },
+ APPROVE {
+
+ @Override
+ public boolean canOperate(PullRequest request) {
+ return canReview(request);
+ }
+
+ @Override
+ public void operate(PullRequest request, String comment) {
+ User user = GitPlex.getInstance(UserManager.class).getCurrent();
+ GitPlex.getInstance(ReviewManager.class).review(
+ request, user, Review.Result.APPROVE, comment);
+ }
+
+ },
+ DISAPPROVE {
+
+ @Override
+ public boolean canOperate(PullRequest request) {
+ return canReview(request);
+ }
+
+ @Override
+ public void operate(PullRequest request, String comment) {
+ User user = GitPlex.getInstance(UserManager.class).getCurrent();
+ GitPlex.getInstance(ReviewManager.class).review(
+ request, user, Review.Result.DISAPPROVE, comment);
+ }
+
+ },
+ REOPEN {
+
+ @Override
+ public boolean canOperate(PullRequest request) {
+ PullRequestManager pullRequestManager = GitPlex.getInstance(PullRequestManager.class);
+ if (request.isOpen()
+ || !SecurityUtils.canModify(request)
+ || request.getTarget().getHead(false) == null
+ || request.getSourceRepo() == null
+ || request.getSource().getHead(false) == null
+ || pullRequestManager.findOpen(request.getTarget(), request.getSource()) != null) {
+ return false;
+ }
+
+ // now check if source branch is integrated into target branch
+ Git git = request.getTargetRepo().git();
+ String sourceHead = request.getSource().getHead();
+ return git.parseRevision(sourceHead, false) == null
+ || !request.getTargetRepo().isAncestor(sourceHead, request.getTarget().getHead());
+ }
+
+ @Override
+ public void operate(PullRequest request, String comment) {
+ GitPlex.getInstance(PullRequestManager.class).reopen(request, comment);
+ }
+
+ },
+ DELETE_SOURCE_BRANCH {
+
+ @Override
+ public void operate(PullRequest request, String comment) {
+ GitPlex.getInstance(PullRequestManager.class).deleteSourceBranch(request);
+ }
+
+ @Override
+ public boolean canOperate(PullRequest request) {
+ IntegrationPreview preview = request.getLastIntegrationPreview();
+ PullRequestManager pullRequestManager = GitPlex.getInstance(PullRequestManager.class);
+ return request.getStatus() == Status.INTEGRATED
+ && request.getSourceRepo() != null
+ && request.getSource().getHead(false) != null
+ && !request.getSource().isDefault()
+ && preview != null
+ && (request.getSource().getHead().equals(preview.getRequestHead())
+ || request.getSource().getHead().equals(preview.getIntegrated()))
+ && SecurityUtils.canModify(request)
+ && SecurityUtils.canModify(request.getSource())
+ && pullRequestManager.queryOpenTo(request.getSource(), null).isEmpty();
+ }
+
+ },
+ RESTORE_SOURCE_BRANCH {
+
+ @Override
+ public void operate(PullRequest request, String comment) {
+ GitPlex.getInstance(PullRequestManager.class).restoreSourceBranch(request);
+ }
+
+ @Override
+ public boolean canOperate(PullRequest request) {
+ return request.getSourceRepo() != null && request.getSource().getHead(false) == null
+ && SecurityUtils.canModify(request) && SecurityUtils.canCreate(request.getSource());
+ }
+
+ };
+
+ private static boolean canReview(PullRequest request) {
+ User user = GitPlex.getInstance(UserManager.class).getCurrent();
+
+ // call request.getStatus() in order to trigger generation of review
+ // integrations which will be used in else condition
+ if (user == null
+ || request.getStatus() == PullRequest.Status.INTEGRATED
+ || request.getStatus() == PullRequest.Status.DISCARDED
+ || request.isReviewEffective(user)) {
+ return false;
+ } else {
+ for (ReviewInvitation invitation: request.getReviewInvitations()) {
+ if (invitation.isPreferred() && invitation.getReviewer().equals(user))
+ return true;
+ }
+ return false;
+ }
+ }
+
+ public abstract void operate(PullRequest request, @Nullable String comment);
+
+ public abstract boolean canOperate(PullRequest request);
+}
diff --git a/gitplex.web/src/main/java/com/pmease/gitplex/web/page/test/TestPage.java b/gitplex.web/src/main/java/com/pmease/gitplex/web/page/test/TestPage.java
index 6d77a4bbe8..61685ea2a9 100644
--- a/gitplex.web/src/main/java/com/pmease/gitplex/web/page/test/TestPage.java
+++ b/gitplex.web/src/main/java/com/pmease/gitplex/web/page/test/TestPage.java
@@ -1,40 +1,23 @@
-package com.pmease.gitplex.web.page.test;
-
-import org.apache.wicket.markup.html.link.Link;
-
-import com.pmease.commons.util.concurrent.PrioritizedRunnable;
-import com.pmease.gitplex.core.GitPlex;
-import com.pmease.gitplex.core.manager.WorkManager;
-import com.pmease.gitplex.web.page.base.BasePage;
-
-@SuppressWarnings("serial")
-public class TestPage extends BasePage {
-
- @Override
- protected void onInitialize() {
- super.onInitialize();
-
- add(new Link<Void>("test") {
-
- @Override
- public void onClick() {
- GitPlex.getInstance(WorkManager.class).execute(new PrioritizedRunnable(0) {
-
- @Override
- public void run() {
- try {
- System.out.println("begin");
- Thread.sleep(30000);
- System.out.println("end");
- } catch (InterruptedException e) {
- // TODO Auto-generated catch block
- e.printStackTrace();
- }
- }
- });
- }
-
- });
- }
-
-}
+package com.pmease.gitplex.web.page.test;
+
+import org.apache.wicket.markup.html.link.Link;
+
+import com.pmease.gitplex.web.page.base.BasePage;
+
+@SuppressWarnings("serial")
+public class TestPage extends BasePage {
+
+ @Override
+ protected void onInitialize() {
+ super.onInitialize();
+
+ add(new Link<Void>("test") {
+
+ @Override
+ public void onClick() {
+ }
+
+ });
+ }
+
+}