The Unified and Autonomous Development Platform
Merge logic for pull request.
robin shined8e1a25386c2
diff --git a/commons.git/src/main/java/com/pmease/commons/git/BriefCommit.java b/commons.git/src/main/java/com/pmease/commons/git/BriefCommit.javaindex 71456a46a4..98f348ffe7 100644--- a/commons.git/src/main/java/com/pmease/commons/git/BriefCommit.java+++ b/commons.git/src/main/java/com/pmease/commons/git/BriefCommit.java@@ -1,36 +1,21 @@package com.pmease.commons.git;-import java.util.Date;-import com.google.common.base.Objects;public class BriefCommit {private final String hash;- private final String committer;-- private final String committerEmail;-- private final Date committerDate;-- private final String author;+ private final UserInfo committer;- private final String authorEmail;-- private final Date authorDate;+ private final UserInfo author;private final String summary;- public BriefCommit(String hash, String committer, String committerEmail, Date committerDate,- String author, String authorEmail, Date authorDate, String summary) {+ public BriefCommit(String hash, UserInfo committer, UserInfo author, String summary) {this.hash = hash;this.committer = committer;- this.committerEmail = committerEmail;- this.committerDate = committerDate;this.author = author;- this.authorEmail = authorEmail;- this.authorDate = authorDate;this.summary = summary;}@@ -38,30 +23,14 @@ public class BriefCommit {return hash;}- public String getCommitter() {+ public UserInfo getCommitter() {return committer;}- public String getCommitterEmail() {- return committerEmail;- }-- public Date getCommitterDate() {- return committerDate;- }-- public String getAuthor() {+ public UserInfo getAuthor() {return author;}- public String getAuthorEmail() {- return authorEmail;- }-- public Date getAuthorDate() {- return authorDate;- }-public String getSummary() {return summary;}@@ -70,8 +39,8 @@ public class BriefCommit {public String toString() {return Objects.toStringHelper(this).add("hash", hash)- .add("committer", committer)- .add("date", committerDate)+ .add("committer", committer.getName())+ .add("date", committer.getDate()).add("summary", summary).toString();}diff --git a/commons.git/src/main/java/com/pmease/commons/git/Commit.java b/commons.git/src/main/java/com/pmease/commons/git/Commit.javaindex 059dfb4206..b8b43212d8 100644--- a/commons.git/src/main/java/com/pmease/commons/git/Commit.java+++ b/commons.git/src/main/java/com/pmease/commons/git/Commit.java@@ -2,7 +2,6 @@ package com.pmease.commons.git;import java.util.ArrayList;import java.util.Collections;-import java.util.Date;import java.util.List;import javax.annotation.Nullable;@@ -19,13 +18,11 @@ public class Commit extends BriefCommit {private final List<FileChange> fileChanges;- public Commit(String hash, String committer, String committerEmail,- Date committerDate, String author, String authorEmail,- Date authorDate, String summary, @Nullable String message,+ public Commit(String hash, UserInfo committer, UserInfo author,+ String summary, @Nullable String message,@Nullable String note, List<String> parentHashes,List<FileChange> fileChanges) {- super(hash, committer, committerEmail, committerDate, author,- authorEmail, authorDate, summary);+ super(hash, committer, author, summary);this.message = message;this.note = note;diff --git a/commons.git/src/main/java/com/pmease/commons/git/Git.java b/commons.git/src/main/java/com/pmease/commons/git/Git.javaindex 78ba9f3430..f6af8ee961 100644--- a/commons.git/src/main/java/com/pmease/commons/git/Git.java+++ b/commons.git/src/main/java/com/pmease/commons/git/Git.java@@ -14,7 +14,6 @@ import com.pmease.commons.git.command.AddNoteCommand;import com.pmease.commons.git.command.AddSubModuleCommand;import com.pmease.commons.git.command.BlameCommand;import com.pmease.commons.git.command.CalcMergeBaseCommand;-import com.pmease.commons.git.command.CheckAncestorCommand;import com.pmease.commons.git.command.CheckoutCommand;import com.pmease.commons.git.command.CloneCommand;import com.pmease.commons.git.command.CommitCommand;@@ -22,6 +21,7 @@ import com.pmease.commons.git.command.DeleteRefCommand;import com.pmease.commons.git.command.DiffCommand;import com.pmease.commons.git.command.FetchCommand;import com.pmease.commons.git.command.InitCommand;+import com.pmease.commons.git.command.IsAncestorCommand;import com.pmease.commons.git.command.IsBinaryCommand;import com.pmease.commons.git.command.ListBranchesCommand;import com.pmease.commons.git.command.ListChangedFilesCommand;@@ -33,6 +33,7 @@ import com.pmease.commons.git.command.MergeCommand;import com.pmease.commons.git.command.RemoveCommand;import com.pmease.commons.git.command.ResetCommand;import com.pmease.commons.git.command.ShowCommand;+import com.pmease.commons.git.command.ShowRefCommand;import com.pmease.commons.git.command.UpdateRefCommand;import com.pmease.commons.util.FileUtils;import com.pmease.commons.util.GeneralException;@@ -81,7 +82,7 @@ public class Git implements Serializable {return this;}- public Commit resolveCommit(String revision) {+ public Commit resolveRevision(String revision) {List<Commit> commits = new LogCommand(repoDir).toRev(revision).maxCommits(1).call();Preconditions.checkState(commits.size() == 1);return commits.get(0);@@ -120,7 +121,7 @@ public class Git implements Serializable {return this;}- public Git commit(String message, boolean amend) {+ public Git commit(String message, boolean add, boolean amend) {new CommitCommand(repoDir).message(message).amend(amend).call();return this;}@@ -146,22 +147,56 @@ public class Git implements Serializable {return this;}- public Git merge(String revision, @Nullable String message) {- new MergeCommand(repoDir).revision(revision).message(message).call();- return this;+ public boolean merge(String revision, @Nullable String strategy,+ @Nullable String strategyOption, @Nullable String message) {+ return new MergeCommand(repoDir).revision(revision).message(message).call();}public Git fetch(String from, String refspec) {new FetchCommand(repoDir).from(from).refspec(refspec).call();return this;}++ public List<RefInfo> showRefs(String pattern) {+ return new ShowRefCommand(repoDir).pattern(pattern).call();+ }++ /**+ * Resolve commit hash of specified ref name.+ *+ * @param refName+ * ref name to be resolved+ * @param shouldExist+ * indicate whether or not the ref should already exist+ * @return+ * commit hash of specified ref name, or <tt>null</tt> if ref name+ * does not exist, and <tt>shouldExist</tt> is specified as+ * <tt>false</tt>+ * @throws+ * IllegalStateException if multiple refs matching specified ref+ * name, or specified ref does not exist while <tt>shouldExist<tt>+ * is specified as <tt>true</tt>+ */+ public @Nullable String resolveRef(String refName, boolean shouldExist) {+ List<RefInfo> refs = showRefs(refName);+ if (refs.isEmpty()) {+ if (shouldExist)+ throw new IllegalStateException();+ else+ return null;+ } else if (refs.size() == 1) {+ return refs.get(0).getCommitHash();+ } else {+ throw new IllegalStateException();+ }+ }public String calcMergeBase(String rev1, String rev2) {return new CalcMergeBaseCommand(repoDir).rev1(rev1).rev2(rev2).call();}- public boolean checkAncestor(String ancestor, String descendant) {- return new CheckAncestorCommand(repoDir).ancestor(ancestor).descendant(descendant).call();+ public boolean isAncestor(String ancestor, String descendant) {+ return new IsAncestorCommand(repoDir).ancestor(ancestor).descendant(descendant).call();}public Collection<String> listBranches() {diff --git a/commons.git/src/main/java/com/pmease/commons/git/RefInfo.java b/commons.git/src/main/java/com/pmease/commons/git/RefInfo.javanew file mode 100644index 0000000000..fda0760a0f--- /dev/null+++ b/commons.git/src/main/java/com/pmease/commons/git/RefInfo.java@@ -0,0 +1,22 @@+package com.pmease.commons.git;++public class RefInfo {++ private final String name;++ private final String commitHash;++ public RefInfo(final String name, final String commitHash) {+ this.name = name;+ this.commitHash = commitHash;+ }++ public String getName() {+ return name;+ }++ public String getCommitHash() {+ return commitHash;+ }++}diff --git a/commons.git/src/main/java/com/pmease/commons/git/UserInfo.java b/commons.git/src/main/java/com/pmease/commons/git/UserInfo.javanew file mode 100644index 0000000000..f8b17df82d--- /dev/null+++ b/commons.git/src/main/java/com/pmease/commons/git/UserInfo.java@@ -0,0 +1,31 @@+package com.pmease.commons.git;++import java.util.Date;++public class UserInfo {++ private final String name;++ private final String email;++ private final Date date;++ public UserInfo(String name, String email, Date date) {+ this.name = name;+ this.email = email;+ this.date = date;+ }++ public String getName() {+ return name;+ }++ public String getEmail() {+ return email;+ }++ public Date getDate() {+ return date;+ }++}diff --git a/commons.git/src/main/java/com/pmease/commons/git/command/BlameCommand.java b/commons.git/src/main/java/com/pmease/commons/git/command/BlameCommand.javaindex a281197a5f..42edfa0b18 100644--- a/commons.git/src/main/java/com/pmease/commons/git/command/BlameCommand.java+++ b/commons.git/src/main/java/com/pmease/commons/git/command/BlameCommand.java@@ -12,6 +12,7 @@ import org.apache.commons.lang3.StringUtils;import com.google.common.base.Preconditions;import com.pmease.commons.git.Blame;import com.pmease.commons.git.BriefCommit;+import com.pmease.commons.git.UserInfo;import com.pmease.commons.util.execution.Commandline;import com.pmease.commons.util.execution.LineConsumer;@@ -122,8 +123,11 @@ public class BlameCommand extends GitCommand<List<Blame>> {private String summary;private BriefCommit build() {- return new BriefCommit(hash, committer, committerEmail, committerDate,- author, authorEmail, authorDate, summary.trim());+ return new BriefCommit(+ hash,+ new UserInfo(committer, committerEmail, committerDate),+ new UserInfo(author, authorEmail, authorDate),+ summary.trim());}}}diff --git a/commons.git/src/main/java/com/pmease/commons/git/command/CalcMergeBaseCommand.java b/commons.git/src/main/java/com/pmease/commons/git/command/CalcMergeBaseCommand.javaindex 176b31c902..baf6d1351f 100644--- a/commons.git/src/main/java/com/pmease/commons/git/command/CalcMergeBaseCommand.java+++ b/commons.git/src/main/java/com/pmease/commons/git/command/CalcMergeBaseCommand.java@@ -6,7 +6,6 @@ import javax.annotation.Nullable;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 CalcMergeBaseCommand extends GitCommand<String> {@@ -40,8 +39,7 @@ public class CalcMergeBaseCommand extends GitCommand<String> {cmd.addArgs("merge-base", rev1, rev2);- final boolean[] revExists = new boolean[]{true};- ExecuteResult result = cmd.execute(new LineConsumer() {+ cmd.execute(new LineConsumer() {@Overridepublic void consume(String line) {@@ -53,18 +51,10 @@ public class CalcMergeBaseCommand extends GitCommand<String> {@Overridepublic void consume(String line) {- if (line.contains("Not a valid object name"))- revExists[0] = false;- else- LineConsumer.logger.error(line);+ LineConsumer.logger.error(line);}- });-- if (!revExists[0])- return null;- else- result.checkReturnCode();+ }).checkReturnCode();return commonAncestor[0];}diff --git a/commons.git/src/main/java/com/pmease/commons/git/command/CommitCommand.java b/commons.git/src/main/java/com/pmease/commons/git/command/CommitCommand.javaindex 65e6b907ee..bc9624d491 100644--- a/commons.git/src/main/java/com/pmease/commons/git/command/CommitCommand.java+++ b/commons.git/src/main/java/com/pmease/commons/git/command/CommitCommand.java@@ -11,6 +11,8 @@ public class CommitCommand extends GitCommand<Void> {private boolean amend;+ private boolean add;+public CommitCommand(final File repoDir) {super(repoDir);}@@ -24,6 +26,11 @@ public class CommitCommand extends GitCommand<Void> {this.amend = amend;return this;}++ public CommitCommand add(final boolean add) {+ this.add = add;+ return this;+ }@Overridepublic Void call() {@@ -32,6 +39,8 @@ public class CommitCommand extends GitCommand<Void> {Commandline cmd = cmd().addArgs("commit");cmd.addArgs("-m", message);+ if (add)+ cmd.addArgs("-a");if (amend)cmd.addArgs("--amend");diff --git a/commons.git/src/main/java/com/pmease/commons/git/command/CheckAncestorCommand.java b/commons.git/src/main/java/com/pmease/commons/git/command/IsAncestorCommand.javasimilarity index 78%rename from commons.git/src/main/java/com/pmease/commons/git/command/CheckAncestorCommand.javarename to commons.git/src/main/java/com/pmease/commons/git/command/IsAncestorCommand.javaindex 3462569c86..cdc81ae314 100644--- a/commons.git/src/main/java/com/pmease/commons/git/command/CheckAncestorCommand.java+++ b/commons.git/src/main/java/com/pmease/commons/git/command/IsAncestorCommand.java@@ -6,22 +6,22 @@ import com.google.common.base.Preconditions;import com.pmease.commons.util.execution.Commandline;import com.pmease.commons.util.execution.ExecuteResult;-public class CheckAncestorCommand extends GitCommand<Boolean> {+public class IsAncestorCommand extends GitCommand<Boolean> {private String ancestor;private String descendant;- public CheckAncestorCommand(final File repoDir) {+ public IsAncestorCommand(final File repoDir) {super(repoDir);}- public CheckAncestorCommand ancestor(final String ancestor) {+ public IsAncestorCommand ancestor(final String ancestor) {this.ancestor = ancestor;return this;}- public CheckAncestorCommand descendant(final String descendant) {+ public IsAncestorCommand descendant(final String descendant) {this.descendant = descendant;return this;}diff --git a/commons.git/src/main/java/com/pmease/commons/git/command/LogCommand.java b/commons.git/src/main/java/com/pmease/commons/git/command/LogCommand.javaindex d782d0f49b..b0b18d4448 100644--- a/commons.git/src/main/java/com/pmease/commons/git/command/LogCommand.java+++ b/commons.git/src/main/java/com/pmease/commons/git/command/LogCommand.java@@ -11,6 +11,7 @@ import org.joda.time.format.DateTimeFormatter;import com.pmease.commons.git.Commit;import com.pmease.commons.git.FileChange;+import com.pmease.commons.git.UserInfo;import com.pmease.commons.util.execution.Commandline;import com.pmease.commons.util.execution.LineConsumer;@@ -71,8 +72,9 @@ public class LogCommand extends GitCommand<List<Commit>> {if (maxCommits != 0)cmd.addArgs("-" + maxCommits);+ cmd.addArgs("--");if (path != null)- cmd.addArgs("--", path);+ cmd.addArgs(path);final List<Commit> commits = new ArrayList<>();@@ -187,8 +189,11 @@ public class LogCommand extends GitCommand<List<Commit>> {private List<FileChange> fileChanges = new ArrayList<>();private Commit build() {- return new Commit(hash, committer, committerEmail, committerDate,- author, authorEmail, authorDate, summary.trim(),+ return new Commit(+ hash,+ new UserInfo(committer, committerEmail, committerDate),+ new UserInfo(author, authorEmail, authorDate),+ summary.trim(),StringUtils.isNotBlank(message)?message.trim():null,StringUtils.isNotBlank(note)?note.trim():null,parentHashes, fileChanges);diff --git a/commons.git/src/main/java/com/pmease/commons/git/command/MergeCommand.java b/commons.git/src/main/java/com/pmease/commons/git/command/MergeCommand.javaindex 71738b139f..9e1b40e583 100644--- a/commons.git/src/main/java/com/pmease/commons/git/command/MergeCommand.java+++ b/commons.git/src/main/java/com/pmease/commons/git/command/MergeCommand.java@@ -4,11 +4,17 @@ import java.io.File;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 MergeCommand extends GitCommand<Void> {+public class MergeCommand extends GitCommand<Boolean> {private String revision;+ private String strategy;++ private String strategyOption;+private String message;public MergeCommand(final File repoDir) {@@ -20,25 +26,55 @@ public class MergeCommand extends GitCommand<Void> {return this;}+ public MergeCommand strategy(String strategy) {+ this.strategy = strategy;+ return this;+ }++ public MergeCommand strategyOption(String strategyOption) {+ this.strategyOption = strategyOption;+ return this;+ }+public MergeCommand message(String message) {this.message = message;return this;}@Override- public Void call() {+ public Boolean call() {Preconditions.checkNotNull(revision, "revision has to be specified.");Commandline cmd = cmd().addArgs("merge");+ if (strategy != null)+ cmd.addArgs("-s", strategy);+ if (strategyOption != null)+ cmd.addArgs("-X", strategyOption);+cmd.addArgs("--no-edit", "--log", "--quiet");if (message != null)cmd.addArgs("-m", message);cmd.addArgs(revision);++ final boolean conflict[] = new boolean[]{false};++ ExecuteResult result = cmd.execute(new LineConsumer() {++ @Override+ public void consume(String line) {+ if (line.startsWith("CONFLICT"))+ conflict[0] = true;+ }++ }, errorLogger());++ if (conflict[0])+ return false;- cmd.execute(debugLogger(), errorLogger()).checkReturnCode();+ result.checkReturnCode();- return null;+ return true;}}diff --git a/commons.git/src/main/java/com/pmease/commons/git/command/ShowRefCommand.java b/commons.git/src/main/java/com/pmease/commons/git/command/ShowRefCommand.javanew file mode 100644index 0000000000..fcca8d4615--- /dev/null+++ b/commons.git/src/main/java/com/pmease/commons/git/command/ShowRefCommand.java@@ -0,0 +1,48 @@+package com.pmease.commons.git.command;++import java.io.File;+import java.util.ArrayList;+import java.util.List;++import org.apache.commons.lang3.StringUtils;++import com.google.common.base.Preconditions;+import com.pmease.commons.git.RefInfo;+import com.pmease.commons.util.execution.Commandline;+import com.pmease.commons.util.execution.LineConsumer;++public class ShowRefCommand extends GitCommand<List<RefInfo>> {++ private String pattern;++ public ShowRefCommand(File repoDir) {+ super(repoDir);+ }++ public ShowRefCommand pattern(String pattern) {+ this.pattern = pattern;+ return this;+ }++ @Override+ public List<RefInfo> call() {+ Preconditions.checkNotNull(pattern, "pattern has to be specified.");++ Commandline cmd = cmd().addArgs("show-ref", pattern);++ final List<RefInfo> refs = new ArrayList<RefInfo>();+ cmd.execute(new LineConsumer() {++ @Override+ public void consume(String line) {+ String commitHash = StringUtils.substringBefore(line, " ");+ String refName = StringUtils.substringAfter(line, " ");+ refs.add(new RefInfo(refName, commitHash));+ }++ }, errorLogger()).checkReturnCode();++ return refs;+ }++}diff --git a/commons.git/src/test/java/com/pmease/commons/git/command/BlameCommandTest.java b/commons.git/src/test/java/com/pmease/commons/git/command/BlameCommandTest.javaindex d7b189db0e..719b9acc39 100644--- a/commons.git/src/test/java/com/pmease/commons/git/command/BlameCommandTest.java+++ b/commons.git/src/test/java/com/pmease/commons/git/command/BlameCommandTest.java@@ -35,7 +35,7 @@ public class BlameCommandTest {+ "7th line\n"+ "8th line\n"+ "9th line\n");- workGit.add("file").commit("initial commit", false);+ workGit.add("file").commit("initial commit", false, false);List<Blame> blames = workGit.blame("file", "master");assertEquals(1, blames.size());@@ -50,7 +50,7 @@ public class BlameCommandTest {+ "7th line\n"+ "8th line\n"+ "nineth line\n");- workGit.add("file").commit("second commit", false);+ workGit.add("file").commit("second commit", false, false);blames = workGit.blame("file", "master");assertEquals(3, blames.size());@@ -62,7 +62,7 @@ public class BlameCommandTest {FileUtils.writeFile(file,"first line\n"+ "nineth line\n");- workGit.add("file").commit("third commit", false);+ workGit.add("file").commit("third commit", false, false);Git bareGit = new Git(new File(tempDir, "bare"));bareGit.clone(workGit.repoDir().getAbsolutePath(), true);diff --git a/commons.git/src/test/java/com/pmease/commons/git/command/DiffCommandTest.java b/commons.git/src/test/java/com/pmease/commons/git/command/DiffCommandTest.javaindex 86e6690ef0..74e59b3eb0 100644--- a/commons.git/src/test/java/com/pmease/commons/git/command/DiffCommandTest.java+++ b/commons.git/src/test/java/com/pmease/commons/git/command/DiffCommandTest.java@@ -46,7 +46,7 @@ public class DiffCommandTest {File file2 = new File(dir, "file2");FileUtils.writeFile(file2, "file2");- workGit.add("dir").commit("add readme, dir/file1 and dir/file2", false);+ workGit.add("dir").commit("add readme, dir/file1 and dir/file2", false, false);workGit.checkout("dev", true);@@ -75,7 +75,7 @@ public class DiffCommandTest {workGit.add("dir/file3");- workGit.commit("modify readme, modify dir/file1, remove dir/file2, and add dir/file3", false);+ workGit.commit("modify readme, modify dir/file1, remove dir/file2, and add dir/file3", false, false);Git bareGit = new Git(new File(tempDir, "bare"));bareGit.clone(workGit.repoDir().getAbsolutePath(), true);diff --git a/commons.git/src/test/java/com/pmease/commons/git/command/IsBinaryCommandTest.java b/commons.git/src/test/java/com/pmease/commons/git/command/IsBinaryCommandTest.javaindex 945920fab3..b25b949e78 100644--- a/commons.git/src/test/java/com/pmease/commons/git/command/IsBinaryCommandTest.java+++ b/commons.git/src/test/java/com/pmease/commons/git/command/IsBinaryCommandTest.java@@ -25,14 +25,14 @@ public class IsBinaryCommandTest {git.init(false);File file = new File(git.repoDir(), "file");FileUtils.writeFile(file, "hello world");- git.add("file").commit("initial commit", false);+ git.add("file").commit("initial commit", false, false);byte[] bytes = new byte[]{0, 1, 2, 3, 4, 5, 6, 7, 8, 9};OutputStream os = new FileOutputStream(file);os.write(bytes);os.close();- git.add("file").commit("second commit", false);+ git.add("file").commit("second commit", false, false);assertFalse(git.isBinary("file", "master~1"));assertTrue(git.isBinary("file", "master"));diff --git a/commons.git/src/test/java/com/pmease/commons/git/command/ListChangedFilesCommandTest.java b/commons.git/src/test/java/com/pmease/commons/git/command/ListChangedFilesCommandTest.javaindex 6522f0a2f2..db95618e94 100644--- a/commons.git/src/test/java/com/pmease/commons/git/command/ListChangedFilesCommandTest.java+++ b/commons.git/src/test/java/com/pmease/commons/git/command/ListChangedFilesCommandTest.java@@ -22,23 +22,23 @@ public class ListChangedFilesCommandTest {try {FileUtils.touchFile(new File(git.repoDir(), "a"));git.add("a");- git.commit("commit", false);+ git.commit("commit", false, false);FileUtils.touchFile(new File(git.repoDir(), "b"));git.add("b");- git.commit("commit", false);+ git.commit("commit", false, false);FileUtils.touchFile(new File(git.repoDir(), "c"));git.add("c");- git.commit("commit", false);+ git.commit("commit", false, false);FileUtils.touchFile(new File(git.repoDir(), "d"));git.add("d");- git.commit("commit", false);+ git.commit("commit", false, false);FileUtils.writeFile(new File(git.repoDir(), "a"), "a");git.add("a");- git.commit("commit", false);+ git.commit("commit", false, false);Collection<String> changedFiles = git.listChangedFiles("HEAD~4", "HEAD");diff --git a/commons.git/src/test/java/com/pmease/commons/git/command/ListSubModulesCommandTest.java b/commons.git/src/test/java/com/pmease/commons/git/command/ListSubModulesCommandTest.javaindex c47586d9dc..2046cc4aa9 100644--- a/commons.git/src/test/java/com/pmease/commons/git/command/ListSubModulesCommandTest.java+++ b/commons.git/src/test/java/com/pmease/commons/git/command/ListSubModulesCommandTest.java@@ -28,14 +28,14 @@ public class ListSubModulesCommandTest {module2.init(false);FileUtils.writeFile(new File(work.repoDir(), "readme"), "readme");- work.add("readme").commit("initial commit", false);+ work.add("readme").commit("initial commit", false, false);FileUtils.writeFile(new File(module1.repoDir(), "readme"), "readme");- module1.add("readme").commit("initial commit", false);+ module1.add("readme").commit("initial commit", false, false);FileUtils.writeFile(new File(module2.repoDir(), "readme"), "readme");- module2.add("readme").commit("initial commit", false);+ module2.add("readme").commit("initial commit", false, false);work.addSubModule(module1.repoDir().getAbsolutePath(), "module1");- work.commit("add submodule1", false);+ work.commit("add submodule1", false, false);Map<String, String> subModules = work.listSubModules("master");assertEquals(module1.repoDir().getCanonicalPath(),@@ -45,7 +45,7 @@ public class ListSubModulesCommandTest {FileUtils.createDir(dir);work.addSubModule(module2.repoDir().getAbsolutePath(), "dir/module2");- work.commit("add submodule2", false);+ work.commit("add submodule2", false, false);subModules = work.listSubModules("master");assertEquals(module1.repoDir().getCanonicalPath(),new File(subModules.get("module1")).getCanonicalPath());diff --git a/commons.git/src/test/java/com/pmease/commons/git/command/ListTreeCommandTest.java b/commons.git/src/test/java/com/pmease/commons/git/command/ListTreeCommandTest.javaindex 77034210ed..d2ef1ee5ab 100644--- a/commons.git/src/test/java/com/pmease/commons/git/command/ListTreeCommandTest.java+++ b/commons.git/src/test/java/com/pmease/commons/git/command/ListTreeCommandTest.java@@ -26,40 +26,40 @@ public class ListTreeCommandTest {FileUtils.touchFile(new File(workGit.repoDir(), "a"));workGit.add("a");- workGit.commit("commit", false);+ workGit.commit("commit", false, false);FileUtils.touchFile(new File(workGit.repoDir(), "b"));workGit.add("b");- workGit.commit("commit", false);+ workGit.commit("commit", false, false);FileUtils.touchFile(new File(workGit.repoDir(), "c"));workGit.add("c");- workGit.commit("commit", false);+ workGit.commit("commit", false, false);FileUtils.touchFile(new File(workGit.repoDir(), "d"));workGit.add("d");- workGit.commit("commit", false);+ workGit.commit("commit", false, false);FileUtils.writeFile(new File(workGit.repoDir(), "a"), "a");workGit.add("a");- workGit.commit("commit", false);+ workGit.commit("commit", false, false);FileUtils.createDir(new File(workGit.repoDir(), "dir"));FileUtils.writeFile(new File(workGit.repoDir(), "dir/file"), "hello world");workGit.add("dir/file");- workGit.commit("commit", false);+ workGit.commit("commit", false, false);Git moduleGit = new Git(new File(tempDir, "module"));moduleGit.init(false);FileUtils.writeFile(new File(moduleGit.repoDir(), "readme"), "readme");- moduleGit.add("readme").commit("commit", false);+ moduleGit.add("readme").commit("commit", false, false);workGit.addSubModule(moduleGit.repoDir().getAbsolutePath(), "module");- workGit.commit("commit", false);+ workGit.commit("commit", false, false);workGit.checkout("dev", true);workGit.remove("dir/file");- workGit.commit("commit", false);+ workGit.commit("commit", false, false);Git bareGit = new Git(new File(tempDir, "bare"));bareGit.clone(workGit.repoDir().getAbsolutePath(), true);diff --git a/commons.git/src/test/java/com/pmease/commons/git/command/LogCommandTest.java b/commons.git/src/test/java/com/pmease/commons/git/command/LogCommandTest.javaindex 2cc9dfd7f1..b8f4cedee5 100644--- a/commons.git/src/test/java/com/pmease/commons/git/command/LogCommandTest.java+++ b/commons.git/src/test/java/com/pmease/commons/git/command/LogCommandTest.java@@ -25,34 +25,34 @@ public class LogCommandTest {FileUtils.touchFile(new File(workGit.repoDir(), "a"));workGit.add("a");- workGit.commit("add a", false);+ workGit.commit("add a", false, false);FileUtils.touchFile(new File(workGit.repoDir(), "b"));workGit.add("b");- workGit.commit("add b", false);+ workGit.commit("add b", false, false);FileUtils.touchFile(new File(workGit.repoDir(), "c"));workGit.add("c");- workGit.commit("add c", false);+ workGit.commit("add c", false, false);FileUtils.touchFile(new File(workGit.repoDir(), "d"));workGit.add("d");- workGit.commit("add d", false);+ workGit.commit("add d", false, false);FileUtils.writeFile(new File(workGit.repoDir(), "a"), "a");workGit.add("a");- workGit.commit("modify a", false);+ workGit.commit("modify a", false, false);FileUtils.createDir(new File(workGit.repoDir(), "dir"));FileUtils.writeFile(new File(workGit.repoDir(), "dir/file"), "hello world");FileUtils.writeFile(new File(workGit.repoDir(), "dir/file2"), "hello world");workGit.add("dir/file");workGit.add("dir/file2");- workGit.commit("add dir/file\nadd dir/file to test files under a directory", false);+ workGit.commit("add dir/file\nadd dir/file to test files under a directory", false, false);workGit.checkout("dev", true);workGit.remove("dir/file");- workGit.commit("remove dir/file", false);+ workGit.commit("remove dir/file", false, false);Git bareGit = new Git(new File(tempDir, "bare"));bareGit.clone(workGit.repoDir().getAbsolutePath(), true);@@ -72,10 +72,10 @@ public class LogCommandTest {assertEquals(null, commits.get(1).getNote());- workGit.checkout("master", false).remove("a").commit("remove a", false);+ workGit.checkout("master", false).remove("a").commit("remove a", false, false);FileUtils.writeFile(new File(workGit.repoDir(), "dir/file2"), "file2");- workGit.add("dir/file2").commit("add dir/file2", false);- workGit.merge("dev", null);+ workGit.add("dir/file2").commit("add dir/file2", false, false);+ workGit.merge("dev", null, null, null);commits = workGit.log(null, "master", null, 0);@@ -87,8 +87,8 @@ public class LogCommandTest {commits = workGit.log("dev", "master", "dir", 0);assertEquals(commits.size(), 2);- assertEquals(workGit.resolveCommit(commits.get(0).getHash()).getHash(), commits.get(0).getHash());- assertEquals(workGit.resolveCommit(commits.get(1).getHash()).getHash(), commits.get(1).getHash());+ assertEquals(workGit.resolveRevision(commits.get(0).getHash()).getHash(), commits.get(0).getHash());+ assertEquals(workGit.resolveRevision(commits.get(1).getHash()).getHash(), commits.get(1).getHash());} finally {FileUtils.deleteDir(tempDir);}diff --git a/commons.wicket/src/main/java/com/pmease/commons/wicket/behavior/dropdown/DropdownAlignment.java b/commons.wicket/src/main/java/com/pmease/commons/wicket/behavior/dropdown/DropdownAlignment.javaindex 722630484c..46b4cee232 100644--- a/commons.wicket/src/main/java/com/pmease/commons/wicket/behavior/dropdown/DropdownAlignment.java+++ b/commons.wicket/src/main/java/com/pmease/commons/wicket/behavior/dropdown/DropdownAlignment.java@@ -8,7 +8,7 @@ public class DropdownAlignment implements Serializable {private static final long serialVersionUID = 1L;- public enum INDICATOR_MODE {SHOW, HIDE, AUTO}+ public enum IndicatorMode {SHOW, HIDE, AUTO}private Component target;@@ -16,7 +16,7 @@ public class DropdownAlignment implements Serializable {private int gap = -1;- private INDICATOR_MODE indicatorMode = INDICATOR_MODE.AUTO;+ private IndicatorMode indicatorMode = IndicatorMode.AUTO;public DropdownAlignment() {}@@ -89,11 +89,11 @@ public class DropdownAlignment implements Serializable {return dropdownY;}- public INDICATOR_MODE getIndicatorMode() {+ public IndicatorMode getIndicatorMode() {return indicatorMode;}- public DropdownAlignment setIndicatorMode(INDICATOR_MODE indicatorMode) {+ public DropdownAlignment setIndicatorMode(IndicatorMode indicatorMode) {this.indicatorMode = indicatorMode;return this;}diff --git a/commons.wicket/src/main/java/com/pmease/commons/wicket/behavior/popover/PopoverBehavior.java b/commons.wicket/src/main/java/com/pmease/commons/wicket/behavior/popover/PopoverBehavior.javaindex b7c28bfd08..90780fe010 100644--- a/commons.wicket/src/main/java/com/pmease/commons/wicket/behavior/popover/PopoverBehavior.java+++ b/commons.wicket/src/main/java/com/pmease/commons/wicket/behavior/popover/PopoverBehavior.java@@ -7,7 +7,7 @@ import org.apache.wicket.request.resource.CssResourceReference;import com.pmease.commons.wicket.behavior.dropdown.DropdownAlignment;import com.pmease.commons.wicket.behavior.dropdown.DropdownBehavior;-import com.pmease.commons.wicket.behavior.dropdown.DropdownAlignment.INDICATOR_MODE;+import com.pmease.commons.wicket.behavior.dropdown.DropdownAlignment.IndicatorMode;@SuppressWarnings("serial")public class PopoverBehavior extends DropdownBehavior {@@ -15,7 +15,7 @@ public class PopoverBehavior extends DropdownBehavior {public PopoverBehavior(PopoverPanel popoverPanel) {super(popoverPanel);- setAlignment(new DropdownAlignment(100, 50, 0, 50).setIndicatorMode(INDICATOR_MODE.SHOW));+ setAlignment(new DropdownAlignment(100, 50, 0, 50).setIndicatorMode(IndicatorMode.SHOW));}@Overridediff --git a/commons.wicket/src/main/java/com/pmease/commons/wicket/behavior/tooltip/TooltipBehavior.java b/commons.wicket/src/main/java/com/pmease/commons/wicket/behavior/tooltip/TooltipBehavior.javaindex 3796e15fea..731ac8ff3d 100644--- a/commons.wicket/src/main/java/com/pmease/commons/wicket/behavior/tooltip/TooltipBehavior.java+++ b/commons.wicket/src/main/java/com/pmease/commons/wicket/behavior/tooltip/TooltipBehavior.java@@ -13,7 +13,7 @@ import org.apache.wicket.request.resource.CssResourceReference;import com.pmease.commons.wicket.behavior.dropdown.DropdownAlignment;import com.pmease.commons.wicket.behavior.dropdown.DropdownResourceReference;-import com.pmease.commons.wicket.behavior.dropdown.DropdownAlignment.INDICATOR_MODE;+import com.pmease.commons.wicket.behavior.dropdown.DropdownAlignment.IndicatorMode;public class TooltipBehavior extends Behavior {@@ -21,7 +21,7 @@ public class TooltipBehavior extends Behavior {private final IModel<String> contentModel;- private DropdownAlignment alignment = new DropdownAlignment(50, 0, 50, 100).setIndicatorMode(INDICATOR_MODE.SHOW);+ private DropdownAlignment alignment = new DropdownAlignment(50, 0, 50, 100).setIndicatorMode(IndicatorMode.SHOW);public TooltipBehavior(IModel<String> contentModel) {this.contentModel = contentModel;diff --git a/gitop.core/src/main/java/com/pmease/gitop/core/gatekeeper/BuildAwareGateKeeper.java b/gitop.core/src/main/java/com/pmease/gitop/core/gatekeeper/BuildAwareGateKeeper.javanew file mode 100644index 0000000000..3283f3a8a8--- /dev/null+++ b/gitop.core/src/main/java/com/pmease/gitop/core/gatekeeper/BuildAwareGateKeeper.java@@ -0,0 +1,6 @@+package com.pmease.gitop.core.gatekeeper;++@SuppressWarnings("serial")+public abstract class BuildAwareGateKeeper implements GateKeeper {++}diff --git a/gitop.core/src/main/java/com/pmease/gitop/core/gatekeeper/IsFastForward.java b/gitop.core/src/main/java/com/pmease/gitop/core/gatekeeper/IsFastForward.javadeleted file mode 100644index 73f217d96e..0000000000--- a/gitop.core/src/main/java/com/pmease/gitop/core/gatekeeper/IsFastForward.java+++ /dev/null@@ -1,19 +0,0 @@-package com.pmease.gitop.core.gatekeeper;--import com.pmease.commons.editable.annotation.Editable;-import com.pmease.gitop.core.gatekeeper.checkresult.CheckResult;-import com.pmease.gitop.core.model.PullRequest;--@SuppressWarnings("serial")-@Editable-public class IsFastForward extends AbstractGateKeeper {-- @Override- public CheckResult check(PullRequest request) {- if (request.isFastForward())- return accepted("Is fast-forward.");- else- return rejected("None fast-forward.");- }--}diff --git a/gitop.core/src/main/java/com/pmease/gitop/core/gatekeeper/TouchSpecifiedFiles.java b/gitop.core/src/main/java/com/pmease/gitop/core/gatekeeper/TouchSpecifiedFiles.javaindex bff7e4fb96..932c116fe0 100644--- a/gitop.core/src/main/java/com/pmease/gitop/core/gatekeeper/TouchSpecifiedFiles.java+++ b/gitop.core/src/main/java/com/pmease/gitop/core/gatekeeper/TouchSpecifiedFiles.java@@ -1,14 +1,12 @@package com.pmease.gitop.core.gatekeeper;import java.io.File;-import java.util.ArrayList;import java.util.Collection;import org.hibernate.validator.constraints.NotEmpty;import com.pmease.commons.editable.annotation.Editable;import com.pmease.commons.git.Git;-import com.pmease.commons.git.TreeNode;import com.pmease.commons.loader.AppLoader;import com.pmease.commons.util.pattern.WildcardUtils;import com.pmease.gitop.core.gatekeeper.checkresult.CheckResult;@@ -39,22 +37,8 @@ public class TouchSpecifiedFiles extends AbstractGateKeeper {for (int i=0; i<request.getEffectiveUpdates().size(); i++) {PullRequestUpdate update = request.getEffectiveUpdates().get(i);- Collection<String> touchedFiles;- if (i == request.getEffectiveUpdates().size()-1) {- if (request.getMergeBase() == null) {- touchedFiles = new ArrayList<>();- for (TreeNode each: new Git(repoDir).listTree(update.getRefName(), null, true)) {- if (each.getType() == TreeNode.Type.FILE)- touchedFiles.add(each.getPath());- }- } else {- touchedFiles = new Git(repoDir).listChangedFiles(request.getMergeBase(), update.getRefName());- }- } else {- touchedFiles = new Git(repoDir).listChangedFiles(- request.getEffectiveUpdates().get(i+1).getRefName(),- update.getRefName());- }+ Collection<String> touchedFiles = new Git(repoDir).listChangedFiles(+ update.getBaseCommit(), update.getHeadCommit());for (String file: touchedFiles) {if (WildcardUtils.matchPath(getFilePaths(), file)) {diff --git a/gitop.core/src/main/java/com/pmease/gitop/core/hookcallback/PostReceiveServlet.java b/gitop.core/src/main/java/com/pmease/gitop/core/hookcallback/PostReceiveServlet.javaindex 197dc3eada..a2f3dc12e0 100644--- a/gitop.core/src/main/java/com/pmease/gitop/core/hookcallback/PostReceiveServlet.java+++ b/gitop.core/src/main/java/com/pmease/gitop/core/hookcallback/PostReceiveServlet.java@@ -9,6 +9,7 @@ import org.slf4j.Logger;import org.slf4j.LoggerFactory;import com.google.common.base.Preconditions;+import com.pmease.commons.git.Commit;import com.pmease.commons.util.StringUtils;import com.pmease.gitop.core.manager.BranchManager;import com.pmease.gitop.core.manager.PullRequestManager;@@ -44,19 +45,29 @@ public class PostReceiveServlet extends CallbackServlet {protected void callback(Project project, String callbackData, Output output) {List<String> splitted = StringUtils.splitAndTrim(callbackData, " ");- // String oldCommitHash = splitted.get(0);+ String oldCommitHash = splitted.get(0);String branchName = splitted.get(2);++ // User with write permission can create new branch+ if (oldCommitHash.equals(Commit.ZERO_HASH)) {+ Branch branch = new Branch();+ branch.setProject(project);+ branch.setName(branchName);+ branchManager.save(branch);+ return;+ }+if (branchName.startsWith("refs/heads/"))branchName = branchName.substring("refs/heads/".length());logger.info("Executing post-receive hook against branch {}...", branchName);- Branch branch = branchManager.find(project, branchName);+ Branch branch = branchManager.find(project, branchName, true);User user = User.getCurrent();Preconditions.checkNotNull(user, "User pushing commits is unknown.");- PullRequest request = pullRequestManager.findOpened(branch, null, user);+ PullRequest request = pullRequestManager.findOpen(branch, null, user);if (request != null) {boolean voted = false;for (PullRequestUpdate update: request.getUpdates()) {@@ -64,7 +75,7 @@ public class PostReceiveServlet extends CallbackServlet {voted = true;}if (voted) {- request.setStatus(PullRequest.Status.MERGED);+// request.setStatus(PullRequest.Status.MERGED);pullRequestManager.save(request);} else {// Delete merged request without votes to reduce number of merge requestsdiff --git a/gitop.core/src/main/java/com/pmease/gitop/core/hookcallback/PreReceiveServlet.java b/gitop.core/src/main/java/com/pmease/gitop/core/hookcallback/PreReceiveServlet.javaindex f0a03255cc..3da0a27fc8 100644--- a/gitop.core/src/main/java/com/pmease/gitop/core/hookcallback/PreReceiveServlet.java+++ b/gitop.core/src/main/java/com/pmease/gitop/core/hookcallback/PreReceiveServlet.java@@ -18,14 +18,14 @@ import com.pmease.gitop.core.gatekeeper.checkresult.CheckResult;import com.pmease.gitop.core.gatekeeper.checkresult.Pending;import com.pmease.gitop.core.gatekeeper.checkresult.Rejected;import com.pmease.gitop.core.manager.BranchManager;+import com.pmease.gitop.core.manager.ProjectManager;import com.pmease.gitop.core.manager.PullRequestManager;import com.pmease.gitop.core.manager.PullRequestUpdateManager;-import com.pmease.gitop.core.manager.ProjectManager;import com.pmease.gitop.core.manager.StorageManager;import com.pmease.gitop.core.model.Branch;+import com.pmease.gitop.core.model.Project;import com.pmease.gitop.core.model.PullRequest;import com.pmease.gitop.core.model.PullRequestUpdate;-import com.pmease.gitop.core.model.Project;import com.pmease.gitop.core.model.User;@SuppressWarnings("serial")@@ -62,7 +62,12 @@ public class PreReceiveServlet extends CallbackServlet {protected void callback(Project project, String callbackData, Output output) {List<String> splitted = StringUtils.splitAndTrim(callbackData, " ");-// String oldCommitHash = splitted.get(0);+ String oldCommitHash = splitted.get(0);++ // User with write permission can create new branch+ if (oldCommitHash.equals(Commit.ZERO_HASH))+ return;+String newCommitHash = splitted.get(1);String branchName = splitted.get(2);@@ -76,7 +81,7 @@ public class PreReceiveServlet extends CallbackServlet {User user = User.getCurrent();Preconditions.checkNotNull(user, "User pushing commits is unknown.");- PullRequest request = pullRequestManager.findOpened(branch, null, user);+ PullRequest request = pullRequestManager.findOpen(branch, null, user);if (request == null) {request = new PullRequest();request.setAutoCreated(true);@@ -87,24 +92,21 @@ public class PreReceiveServlet extends CallbackServlet {pullRequestManager.save(request);}- if (request.getLatestUpdate() == null- || !request.getLatestUpdate().getCommitHash().equals(newCommitHash)) {+ if (!request.getLatestUpdate().getHeadCommit().equals(newCommitHash)) {Git git = new Git(storageManager.getStorage(project).ofCode());PullRequestUpdate update = new PullRequestUpdate();- update.setCommitHash(newCommitHash);update.setRequest(request);- Commit commit = git.resolveCommit(newCommitHash);+ Commit commit = git.resolveRevision(newCommitHash);update.setSubject(commit.getSummary());request.getUpdates().add(update);- request.updatesChanged();-pullRequestUpdateManager.save(update);}-- CheckResult checkResult = request.check();++ request.refresh();+ CheckResult checkResult = request.getCheckResult();if (checkResult instanceof Rejected) {output.markError();diff --git a/gitop.core/src/main/java/com/pmease/gitop/core/manager/PullRequestManager.java b/gitop.core/src/main/java/com/pmease/gitop/core/manager/PullRequestManager.javaindex 6a7dcaa63b..049d8dfd66 100644--- a/gitop.core/src/main/java/com/pmease/gitop/core/manager/PullRequestManager.java+++ b/gitop.core/src/main/java/com/pmease/gitop/core/manager/PullRequestManager.java@@ -12,6 +12,6 @@ import com.pmease.gitop.core.model.User;@ImplementedBy(DefaultPullRequestManager.class)public interface PullRequestManager extends GenericDao<PullRequest> {- @Nullable PullRequest findOpened(Branch target, @Nullable Branch source, User user);+ @Nullable PullRequest findOpen(Branch target, @Nullable Branch source, User user);}diff --git a/gitop.core/src/main/java/com/pmease/gitop/core/manager/PullRequestUpdateManager.java b/gitop.core/src/main/java/com/pmease/gitop/core/manager/PullRequestUpdateManager.javaindex cb361f2f7a..bf8391da60 100644--- a/gitop.core/src/main/java/com/pmease/gitop/core/manager/PullRequestUpdateManager.java+++ b/gitop.core/src/main/java/com/pmease/gitop/core/manager/PullRequestUpdateManager.java@@ -7,4 +7,5 @@ import com.pmease.gitop.core.model.PullRequestUpdate;@ImplementedBy(DefaultPullRequestUpdateManager.class)public interface PullRequestUpdateManager extends GenericDao<PullRequestUpdate> {+}diff --git a/gitop.core/src/main/java/com/pmease/gitop/core/manager/impl/DefaultPullRequestManager.java b/gitop.core/src/main/java/com/pmease/gitop/core/manager/impl/DefaultPullRequestManager.javaindex 2fb05213bb..3c594986db 100644--- a/gitop.core/src/main/java/com/pmease/gitop/core/manager/impl/DefaultPullRequestManager.java+++ b/gitop.core/src/main/java/com/pmease/gitop/core/manager/impl/DefaultPullRequestManager.java@@ -32,13 +32,12 @@ public class DefaultPullRequestManager extends AbstractGenericDao<PullRequest> i@Sessional@Override- public PullRequest findOpened(Branch target, Branch source, User submitter) {+ public PullRequest findOpen(Branch target, Branch source, User submitter) {Criterion statusCriterion =- Restrictions.or(- Restrictions.eq("status", PullRequest.Status.PENDING_CHECK),- Restrictions.eq("status", PullRequest.Status.PENDING_APPROVAL),- Restrictions.eq("status", PullRequest.Status.PENDING_UPDATE),- Restrictions.eq("status", PullRequest.Status.PENDING_MERGE));+ Restrictions.and(+ Restrictions.not(Restrictions.eq("status", PullRequest.Status.MERGED)),+ Restrictions.not(Restrictions.eq("status", PullRequest.Status.DECLINED))+ );return find(Restrictions.eq("target", target), Restrictions.eqOrIsNull("source", source),Restrictions.eq("submitter", submitter), statusCriterion);diff --git a/gitop.core/src/main/java/com/pmease/gitop/core/manager/impl/DefaultPullRequestUpdateManager.java b/gitop.core/src/main/java/com/pmease/gitop/core/manager/impl/DefaultPullRequestUpdateManager.javaindex 762c45864f..5ee6b31b46 100644--- a/gitop.core/src/main/java/com/pmease/gitop/core/manager/impl/DefaultPullRequestUpdateManager.java+++ b/gitop.core/src/main/java/com/pmease/gitop/core/manager/impl/DefaultPullRequestUpdateManager.java@@ -3,8 +3,6 @@ package com.pmease.gitop.core.manager.impl;import javax.inject.Inject;import javax.inject.Singleton;-import com.pmease.commons.git.Git;-import com.pmease.commons.hibernate.Transactional;import com.pmease.commons.hibernate.dao.AbstractGenericDao;import com.pmease.commons.hibernate.dao.GeneralDao;import com.pmease.gitop.core.manager.PullRequestUpdateManager;@@ -19,22 +17,4 @@ public class DefaultPullRequestUpdateManager extends AbstractGenericDao<PullRequsuper(generalDao);}- @Transactional- @Override- public void save(PullRequestUpdate update) {- super.save(update);-- Git git = update.getRequest().getTarget().getProject().getCodeRepo();- git.updateRef(update.getRefName(), update.getCommitHash(), null, null);- }-- @Transactional- @Override- public void delete(PullRequestUpdate update) {- super.delete(update);-- Git git = update.getRequest().getTarget().getProject().getCodeRepo();- git.deleteRef(update.getRefName());- }-}diff --git a/gitop.core/src/main/java/com/pmease/gitop/core/model/Branch.java b/gitop.core/src/main/java/com/pmease/gitop/core/model/Branch.javaindex ab44123793..9395d93f1a 100644--- a/gitop.core/src/main/java/com/pmease/gitop/core/model/Branch.java+++ b/gitop.core/src/main/java/com/pmease/gitop/core/model/Branch.java@@ -13,6 +13,7 @@ import javax.persistence.Table;import javax.persistence.UniqueConstraint;import com.google.common.base.Objects;+import com.pmease.commons.git.Git;import com.pmease.commons.hibernate.AbstractEntity;@SuppressWarnings("serial")@@ -40,6 +41,8 @@ public class Branch extends AbstractEntity {@OneToMany(mappedBy="source", cascade=CascadeType.REMOVE)private Collection<PullRequest> outgoingRequests = new ArrayList<PullRequest>();++ private transient String headCommit;public Project getProject() {return project;@@ -88,6 +91,18 @@ public class Branch extends AbstractEntity {public void setOutgoingRequests(Collection<PullRequest> outgoingRequests) {this.outgoingRequests = outgoingRequests;}++ public String getHeadCommit() {+ if (headCommit == null) {+ Git git = getProject().getCodeRepo();+ headCommit = git.resolveRef(getHeadRef(), true);+ }+ return headCommit;+ }++ public String getHeadRef() {+ return "refs/heads/" + name;+ }@Overridepublic String toString() {diff --git a/gitop.core/src/main/java/com/pmease/gitop/core/model/PullRequest.java b/gitop.core/src/main/java/com/pmease/gitop/core/model/PullRequest.javaindex 3d1b0650f3..52b54c6b8d 100644--- a/gitop.core/src/main/java/com/pmease/gitop/core/model/PullRequest.java+++ b/gitop.core/src/main/java/com/pmease/gitop/core/model/PullRequest.java@@ -1,5 +1,7 @@package com.pmease.gitop.core.model;+import java.io.File;+import java.io.Serializable;import java.util.ArrayList;import java.util.Collection;import java.util.Collections;@@ -17,13 +19,12 @@ import javax.persistence.Lob;import javax.persistence.ManyToOne;import javax.persistence.OneToMany;-import com.google.common.base.Optional;import com.google.common.base.Preconditions;import com.pmease.commons.git.Git;import com.pmease.commons.hibernate.AbstractEntity;+import com.pmease.commons.util.FileUtils;import com.pmease.gitop.core.Gitop;import com.pmease.gitop.core.gatekeeper.GateKeeper;-import com.pmease.gitop.core.gatekeeper.checkresult.Accepted;import com.pmease.gitop.core.gatekeeper.checkresult.Blocked;import com.pmease.gitop.core.gatekeeper.checkresult.CheckResult;import com.pmease.gitop.core.gatekeeper.checkresult.Pending;@@ -36,21 +37,8 @@ import com.pmease.gitop.core.manager.VoteInvitationManager;public class PullRequest extends AbstractEntity {public enum Status {- PENDING_CHECK("Pending Check"), PENDING_APPROVAL("Pending Approval"),- PENDING_UPDATE("Pending Update"), PENDING_MERGE("Pending Merge"),- MERGED("Merged"), CLOSED("Closed");-- private final String displayName;-- Status(String displayName) {- this.displayName = displayName;- }-- @Override- public String toString() {- return displayName;- }-+ PENDING_CHECK, PENDING_APPROVAL, PENDING_UPDATE,+ PENDING_MERGE, MERGED, DECLINED;}private String title;@@ -68,24 +56,24 @@ public class PullRequest extends AbstractEntity {private Branch target;@ManyToOne+ @JoinColumn(nullable = false)private Branch source;@Lob- private CheckResult lastCheckResult;+ private CheckResult checkResult;@Column(nullable = false)private Status status = Status.PENDING_CHECK;-- private transient Boolean merged;-- private transient Optional<String> mergeBase;++ @Lob+ private MergeResult mergeResult;private transient List<PullRequestUpdate> sortedUpdates;private transient List<PullRequestUpdate> effectiveUpdates;private transient PullRequestUpdate baseUpdate;-+@OneToMany(mappedBy = "request", cascade = CascadeType.REMOVE)private Collection<PullRequestUpdate> updates = new ArrayList<PullRequestUpdate>();@@ -161,10 +149,6 @@ public class PullRequest extends AbstractEntity {this.source = source;}- public void setLastCheckResult(CheckResult lastCheckResult) {- this.lastCheckResult = lastCheckResult;- }-public Collection<PullRequestUpdate> getUpdates() {return updates;}@@ -185,10 +169,10 @@ public class PullRequest extends AbstractEntity {return status;}- public void setStatus(Status status) {- this.status = status;+ public boolean isOpen() {+ return status != Status.MERGED && status != Status.DECLINED;}-+public PullRequestUpdate getBaseUpdate() {if (baseUpdate != null) {return baseUpdate;@@ -201,12 +185,12 @@ public class PullRequest extends AbstractEntity {this.baseUpdate = baseUpdate;}- public CheckResult getLastCheckResult() {- return lastCheckResult;+ public CheckResult getCheckResult() {+ return checkResult;}-- public String getMergeRefName() {- return "refs/gitop/pulls/" + getId();++ public MergeResult getMergeResult() {+ return mergeResult;}/**@@ -217,6 +201,7 @@ public class PullRequest extends AbstractEntity {*/public List<PullRequestUpdate> getSortedUpdates() {if (sortedUpdates == null) {+ Preconditions.checkState(!getUpdates().isEmpty());sortedUpdates = new ArrayList<PullRequestUpdate>(getUpdates());Collections.sort(sortedUpdates);@@ -227,8 +212,7 @@ public class PullRequest extends AbstractEntity {/*** Get list of effective updates in reverse order. Update is considered- * effective if it is descendant of merge base of latest update and target- * branch head.+ * effective if it is not ancestor of target branch head.** @return list of effective updates in reverse order.*/@@ -236,67 +220,27 @@ public class PullRequest extends AbstractEntity {if (effectiveUpdates == null) {effectiveUpdates = new ArrayList<PullRequestUpdate>();- if (getMergeBase() != null) {- Git git = getTarget().getProject().getCodeRepo();- for (PullRequestUpdate update : getSortedUpdates()) {- if (git.checkAncestor(getMergeBase(), update.getRefName())) {- effectiveUpdates.add(update);- } else {- break;- }+ Git git = getTarget().getProject().getCodeRepo();+ for (PullRequestUpdate update : getSortedUpdates()) {+ if (!git.isAncestor(update.getHeadCommit(), getTarget().getHeadCommit())) {+ effectiveUpdates.add(update);+ } else {+ break;}- } else {- effectiveUpdates = getSortedUpdates();}++ Preconditions.checkState(!effectiveUpdates.isEmpty());}return effectiveUpdates;}- public @Nullable PullRequestUpdate getLatestUpdate() {- if (getSortedUpdates().isEmpty())- return null;- else- return getSortedUpdates().iterator().next();+ public PullRequestUpdate getLatestUpdate() {+ return getSortedUpdates().iterator().next();}- public void updatesChanged() {- merged = null;- mergeBase = null;- sortedUpdates = null;- effectiveUpdates = null;- baseUpdate = null;- }-- public boolean isFastForward() {- Git git = getTarget().getProject().getCodeRepo();- return git.checkAncestor(getTarget().getName(), getLatestUpdate().getRefName());- }-public Collection<String> findTouchedFiles() {Git git = getTarget().getProject().getCodeRepo();- PullRequestUpdate update = getLatestUpdate();- if (update != null) {- return git.listChangedFiles(getTarget().getName(), update.getRefName());- } else {- return new ArrayList<>();- }- }-- public boolean isMerged() {- if (merged == null) {- Git git = getTarget().getProject().getCodeRepo();- merged = git.checkAncestor(getLatestUpdate().getRefName(), getTarget().getName());- }- return merged;- }-- public @Nullable- String getMergeBase() {- if (mergeBase == null) {- mergeBase = Optional.fromNullable(getTarget().getProject().getCodeRepo()- .calcMergeBase(getLatestUpdate().getRefName(), getTarget().getName()));- }- return mergeBase.orNull();+ return git.listChangedFiles(getTarget().getHeadCommit(), getLatestUpdate().getHeadCommit());}/**@@ -348,53 +292,147 @@ public class PullRequest extends AbstractEntity {}}-- public CheckResult check() {- GateKeeper gateKeeper = getTarget().getProject().getGateKeeper();- lastCheckResult = gateKeeper.check(this);-- VoteInvitationManager voteInvitationManager =- Gitop.getInstance(VoteInvitationManager.class);- for (VoteInvitation invitation : getVoteInvitations()) {- if (!lastCheckResult.canVote(invitation.getVoter(), this))- voteInvitationManager.delete(invitation);- }-- if (lastCheckResult instanceof Pending || lastCheckResult instanceof Blocked) {- setStatus(Status.PENDING_APPROVAL);- } else if (lastCheckResult instanceof Rejected) {- setStatus(Status.PENDING_UPDATE);++ private String getMergeRef() {+ return "refs/gitop/pulls/" + getId() + "/merge";+ }++ /**+ * Refresh internal state of this pull request. Pull request should be refreshed when:+ * <li> It is updated+ * <li> Head of target branch changes+ * <li> Some one vote against it+ * <li> CI system reports completion of build against relevant commits+ */+ public void refresh() {+ Git git = getTarget().getProject().getCodeRepo();+ String branchHead = getTarget().getHeadCommit();+ String requestHead = getLatestUpdate().getHeadCommit();++ if (git.isAncestor(requestHead, branchHead)) {+ status = Status.MERGED;} else {- setStatus(Status.PENDING_MERGE);+ if (git.isAncestor(branchHead, requestHead)) {+ mergeResult = new MergeResult(branchHead, requestHead, requestHead);+ git.updateRef(getMergeRef(), requestHead, null, null);+ } else {+ if (mergeResult != null+ && (!mergeResult.getBranchHead().equals(branchHead)+ || !mergeResult.getRequestHead().equals(requestHead))) {+ // Commits for merging have been changed since last merge, we have to+ // re-merge+ mergeResult = null;+ }+ if (mergeResult != null && mergeResult.getMerged() != null+ && !mergeResult.getMerged().equals(git.resolveRef(getMergeRef(), false))) {+ // Commits for merging have not been changed since last merge, but recorded+ // merge is incorrect in repository, so we have to re-merge+ mergeResult = null;+ }+ if (mergeResult == null) {+ File tempDir = FileUtils.createTempDir();+ try {+ Git tempGit = new Git(tempDir);++ // Branch name here is not significant, we just use an existing branch+ // in cloned repository to hold mergeBase, so that we can merge with+ // previousUpdate+ String branchName = getTarget().getName();+ tempGit.clone(git.repoDir().getAbsolutePath(), false, true, true, branchName);+ tempGit.updateRef("HEAD", requestHead, null, null);+ tempGit.reset(null, null);+ if (tempGit.merge(branchHead, null, null, null)) {+ git.fetch(tempGit.repoDir().getAbsolutePath(), "+HEAD:" + getMergeRef());+ mergeResult = new MergeResult(branchHead, requestHead, git.resolveRef(getMergeRef(), true));+ } else {+ mergeResult = new MergeResult(branchHead, requestHead, null);+ }+ } finally {+ FileUtils.deleteDir(tempDir);+ }+ }+ }++ GateKeeper gateKeeper = getTarget().getProject().getGateKeeper();+ checkResult = gateKeeper.check(this);++ VoteInvitationManager voteInvitationManager =+ Gitop.getInstance(VoteInvitationManager.class);+ for (VoteInvitation invitation : getVoteInvitations()) {+ if (!checkResult.canVote(invitation.getVoter(), this))+ voteInvitationManager.delete(invitation);+ }++ Preconditions.checkNotNull(mergeResult);++ if (checkResult instanceof Pending || checkResult instanceof Blocked) {+ status = Status.PENDING_APPROVAL;+ } else if (checkResult instanceof Rejected) {+ status = Status.PENDING_UPDATE;+ } else if (mergeResult.getMerged() == null) {+ status = Status.PENDING_UPDATE;+ } else {+ status = Status.PENDING_MERGE;+ }}Gitop.getInstance(PullRequestManager.class).save(this);-- return lastCheckResult;}- public void close() {- setStatus(Status.CLOSED);+ public void decline() {+ status = Status.DECLINED;Gitop.getInstance(PullRequestManager.class).save(this);}++ public boolean merge() {+ refresh();- public void merge() {- Preconditions.checkState(getLastCheckResult() instanceof Accepted,- "Can only merge when gate keeper check is passed.");+ if (status == Status.PENDING_MERGE) {+ Git git = getTarget().getProject().getCodeRepo();+ git.updateRef(getTarget().getHeadRef(), mergeResult.getMerged(),+ getTarget().getHeadCommit(), "merge pull request");+ status = Status.MERGED;+ Gitop.getInstance(PullRequestManager.class).save(this);+ return true;+ } else {+ return false;+ }+ }- // TODO: implement this+ public static class MergeResult implements Serializable {++ private final String branchHead;++ private final String requestHead;++ private final String merged;- Git git = getTarget().getProject().getCodeRepo();- git.updateRef("refs/heads/" + getTarget().getName(),- getLatestUpdate().getCommitHash(), null, null);+ public MergeResult(final String branchHead, final String requestHead, final String merged) {+ this.branchHead = branchHead;+ this.requestHead = requestHead;+ this.merged = merged;+ }- setStatus(Status.MERGED);- Gitop.getInstance(PullRequestManager.class).save(this);- }+ public String getBranchHead() {+ return branchHead;+ }- public boolean canMergeWithoutConflicts() {- // TODO: implement this- return true;- }+ public String getRequestHead() {+ return requestHead;+ }++ public String getMerged() {+ return merged;+ }++ public boolean isConflict() {+ return merged == null;+ }++ public boolean isFastForward() {+ return requestHead.equals(merged);+ }++ };}diff --git a/gitop.core/src/main/java/com/pmease/gitop/core/model/PullRequestUpdate.java b/gitop.core/src/main/java/com/pmease/gitop/core/model/PullRequestUpdate.javaindex 7d23b1f2e5..e7b2b8cebd 100644--- a/gitop.core/src/main/java/com/pmease/gitop/core/model/PullRequestUpdate.java+++ b/gitop.core/src/main/java/com/pmease/gitop/core/model/PullRequestUpdate.java@@ -1,5 +1,6 @@package com.pmease.gitop.core.model;+import java.io.File;import java.util.ArrayList;import java.util.Collection;import java.util.Date;@@ -13,7 +14,11 @@ import javax.persistence.JoinColumn;import javax.persistence.ManyToOne;import javax.persistence.OneToMany;+import com.google.common.base.Preconditions;+import com.pmease.commons.git.Commit;+import com.pmease.commons.git.Git;import com.pmease.commons.hibernate.AbstractEntity;+import com.pmease.commons.util.FileUtils;@SuppressWarnings("serial")@Entity@@ -28,12 +33,13 @@ public class PullRequestUpdate extends AbstractEntity {private Date date = new Date();- @Column(nullable=false)- private String commitHash;-@OneToMany(mappedBy="update", cascade=CascadeType.REMOVE)private Collection<Vote> votes = new ArrayList<Vote>();+ private transient String headCommit;++ private transient String baseCommit;+public PullRequest getRequest() {return request;}@@ -58,14 +64,6 @@ public class PullRequestUpdate extends AbstractEntity {this.date = date;}- public String getCommitHash() {- return commitHash;- }-- public void setCommitHash(String commitHash) {- this.commitHash = commitHash;- }-public Collection<Vote> getVotes() {return votes;}@@ -74,8 +72,81 @@ public class PullRequestUpdate extends AbstractEntity {this.votes = votes;}- public String getRefName() {- return "refs/gitop/updates/" + getId();+ public String getHeadRef() {+ return "refs/gitop/updates/" + getId() + "/head";+ }++ public String getHeadCommit() {+ if (headCommit == null)+ headCommit = getRequest().getTarget().getProject().getCodeRepo().resolveRef(getHeadRef(), true);+ return headCommit;+ }++ /**+ * Calculate base commit for change calculation of this update. Base commit is merged+ * commit of:+ * <li> merge base of head ref and target branch head+ * <li> head ref of previous update+ * Changed files of this update will be calculated between change base and head ref+ * and this effectively represents changes made since previous update with merged+ * changes from target branch excluded if there is any.+ *+ * @return+ * base commit used for change calculation of current update+ */+ public String getBaseCommit() {+ if (baseCommit == null) {+ Git git = getRequest().getTarget().getProject().getCodeRepo();+ String mergeBase = git.calcMergeBase(getHeadCommit(), getRequest().getTarget().getHeadCommit());+ int index = getRequest().getSortedUpdates().indexOf(this);+ Preconditions.checkState(index != -1);++ String previousUpdate;+ if (index == 0) {+ previousUpdate = mergeBase;+ } else {+ previousUpdate = getRequest().getSortedUpdates().get(index-1).getHeadCommit();+ }++ if (git.isAncestor(previousUpdate, mergeBase)) {+ baseCommit = mergeBase;+ } else if (git.isAncestor(mergeBase, previousUpdate)) {+ baseCommit = previousUpdate;+ } else {+ String baseRef = "refs/gitop/updates/" + getId() + "/base";+ baseCommit = git.resolveRef(baseRef, false);++ if (baseCommit != null) {+ Commit commit = git.resolveRevision(baseCommit);+ if (!commit.getParentHashes().contains(mergeBase) || !commit.getParentHashes().contains(previousUpdate))+ baseCommit = null;+ }++ if (baseCommit == null) {+ File tempDir = FileUtils.createTempDir();+ try {+ Git tempGit = new Git(tempDir);++ /*+ * Branch name here is not significant, we just use an existing branch+ * in cloned repository to hold mergeBase, so that we can merge with+ * previousUpdate+ */+ String branchName = getRequest().getTarget().getName();+ tempGit.clone(git.repoDir().getAbsolutePath(), false, true, true, branchName);+ tempGit.updateRef("HEAD", mergeBase, null, null);+ tempGit.reset(null, null);+ Preconditions.checkState(tempGit.merge(previousUpdate, null, "ours", null));+ git.fetch(tempGit.repoDir().getAbsolutePath(), "+HEAD:" + baseRef);+ baseCommit = git.resolveRef(baseRef, true);+ } finally {+ FileUtils.deleteDir(tempDir);+ }+ }+ }+ }++ return baseCommit;}/**diff --git a/gitop.core/src/test/java/com/pmease/gitop/core/model/PullRequestTest.java b/gitop.core/src/test/java/com/pmease/gitop/core/model/PullRequestTest.javaindex c3385db7f2..fd8f518414 100644--- a/gitop.core/src/test/java/com/pmease/gitop/core/model/PullRequestTest.java+++ b/gitop.core/src/test/java/com/pmease/gitop/core/model/PullRequestTest.java@@ -42,19 +42,19 @@ public class PullRequestTest extends AppLoaderMocker {public void shouldReturnAllUpdatesAsEffectiveIfTheyAreFastForward() {FileUtils.touchFile(new File(git.repoDir(), "a"));git.add("a");- git.commit("commit", false);+ git.commit("commit", false, false);git.checkout("dev", true);FileUtils.touchFile(new File(git.repoDir(), "b"));git.add("b");- git.commit("commit", false);+ git.commit("commit", false, false);git.updateRef("refs/updates/1", "HEAD", null, null);FileUtils.touchFile(new File(git.repoDir(), "c"));git.add("c");- git.commit("commit", false);+ git.commit("commit", false, false);git.updateRef("refs/updates/2", "HEAD", null, null);@@ -86,25 +86,25 @@ public class PullRequestTest extends AppLoaderMocker {public void shouldReturnLatestUpdateAsEffectiveIfAllOthersHaveBeenMerged() {FileUtils.touchFile(new File(git.repoDir(), "a"));git.add("a");- git.commit("commit", false);+ git.commit("commit", false, false);git.checkout("dev", true);FileUtils.touchFile(new File(git.repoDir(), "b"));git.add("b");- git.commit("commit", false);+ git.commit("commit", false, false);git.updateRef("refs/updates/1", "HEAD", null, null);FileUtils.touchFile(new File(git.repoDir(), "c"));git.add("c");- git.commit("commit", false);+ git.commit("commit", false, false);git.updateRef("refs/updates/2", "HEAD", null, null);FileUtils.touchFile(new File(git.repoDir(), "d"));git.add("d");- git.commit("commit", false);+ git.commit("commit", false, false);git.updateRef("refs/updates/3", "HEAD", null, null);@@ -112,9 +112,9 @@ public class PullRequestTest extends AppLoaderMocker {FileUtils.touchFile(new File(git.repoDir(), "e"));git.add("e");- git.commit("commit", false);+ git.commit("commit", false, false);- git.merge("refs/updates/2", null);+ git.merge("refs/updates/2", null, null, null);Mockito.when(AppLoader.getInstance(StorageManager.class)).thenReturn(storageManager);diff --git a/gitop.web/src/main/java/com/pmease/gitop/web/page/test/PullRequestsPage.java b/gitop.web/src/main/java/com/pmease/gitop/web/page/test/PullRequestsPage.javaindex 85b1d05880..6a3d2f17a8 100644--- a/gitop.web/src/main/java/com/pmease/gitop/web/page/test/PullRequestsPage.java+++ b/gitop.web/src/main/java/com/pmease/gitop/web/page/test/PullRequestsPage.java@@ -41,7 +41,7 @@ public class PullRequestsPage extends AbstractLayoutPage {List<PullRequest> pullRequests = new ArrayList<PullRequest>();for (Branch branch: Gitop.getInstance(BranchManager.class).query()) {for (PullRequest request: branch.getIngoingRequests()) {- if (request.getStatus() != PullRequest.Status.CLOSED && request.getLastCheckResult() != null)+ if (request.getStatus() != PullRequest.Status.DECLINED && request.getCheckResult() != null)pullRequests.add(request);}}@@ -58,7 +58,7 @@ public class PullRequestsPage extends AbstractLayoutPage {requestItem.add(new Label("status", request.getStatus().toString()));- requestItem.add(new ListView<String>("reasons", request.getLastCheckResult().getReasons()) {+ requestItem.add(new ListView<String>("reasons", request.getCheckResult().getReasons()) {@Overrideprotected void populateItem(ListItem<String> item) {@@ -87,7 +87,7 @@ public class PullRequestsPage extends AbstractLayoutPage {@Overridepublic void onClick() {PullRequest request = requestItem.getModelObject();- request.close();+ request.decline();}});@@ -106,7 +106,7 @@ public class PullRequestsPage extends AbstractLayoutPage {PullRequestUpdate update = updateItem.getModelObject();updateItem.add(new Label("title", update.getSubject()));- updateItem.add(new Label("commitHash", update.getCommitHash()));+ updateItem.add(new Label("commitHash", update.getHeadCommit()));Collection<String> approvedUsers = new ArrayList<>();Collection<String> rejectedUsers = new ArrayList<>();@@ -131,7 +131,7 @@ public class PullRequestsPage extends AbstractLayoutPage {List<User> usersCanVote = new ArrayList<>();PullRequest request = requestItem.getModelObject();for (User user: Gitop.getInstance(UserManager.class).query()) {- if (request.getLastCheckResult().canVote(user, request))+ if (request.getCheckResult().canVote(user, request))usersCanVote.add(user);}@@ -157,7 +157,7 @@ public class PullRequestsPage extends AbstractLayoutPage {vote.getVoter().getVotes().add(vote);Gitop.getInstance(VoteManager.class).save(vote);- requestItem.getModelObject().check();+ requestItem.getModelObject().refresh();}});@@ -173,7 +173,7 @@ public class PullRequestsPage extends AbstractLayoutPage {vote.getVoter().getVotes().add(vote);Gitop.getInstance(VoteManager.class).save(vote);- requestItem.getModelObject().check();+ requestItem.getModelObject().refresh();}});