Skip to content

The Unified and Autonomous Development Platform

Some bug fixes.

robin shineae926fc7a53c
diff --git a/commons.git/src/main/java/com/pmease/commons/git/BlobChange.java b/commons.git/src/main/java/com/pmease/commons/git/BlobChange.java
index 2b2f2359b9..e8ed2261c1 100644
--- a/commons.git/src/main/java/com/pmease/commons/git/BlobChange.java
+++ b/commons.git/src/main/java/com/pmease/commons/git/BlobChange.java
@@ -98,8 +98,6 @@ public abstract class BlobChange implements Serializable {
} else {
diffBlocks = new ArrayList<>();
}
- } else if (oldBlobIdent.id != null && oldBlobIdent.id.equals(newBlobIdent.id)) {
- diffBlocks = new ArrayList<>();
} else {
if (getOldText() != null && getNewText() != null) {
List<String> oldLines = getOldText().getLines();
diff --git a/commons.git/src/main/java/com/pmease/commons/git/BlobIdent.java b/commons.git/src/main/java/com/pmease/commons/git/BlobIdent.java
index 4cf2bb27e1..22fe63a8ed 100644
--- a/commons.git/src/main/java/com/pmease/commons/git/BlobIdent.java
+++ b/commons.git/src/main/java/com/pmease/commons/git/BlobIdent.java
@@ -23,9 +23,6 @@ public class BlobIdent implements Serializable, Comparable<BlobIdent> {
@Nullable
public Integer mode;
- @Nullable
- public String id;
-
public BlobIdent() {
}
@@ -33,7 +30,6 @@ public class BlobIdent implements Serializable, Comparable<BlobIdent> {
revision = blobIdent.revision;
path = blobIdent.path;
mode = blobIdent.mode;
- id = blobIdent.id;
}
public BlobIdent(@Nullable String revision, @Nullable String path, @Nullable Integer mode) {
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 575c04aba7..e67e5296ed 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,234 +1,229 @@
-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.Constants;
-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 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 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(Constants.R_HEADS))
- return refName.substring(Constants.R_HEADS.length());
- else
- return null;
- }
-
- public static String branch2ref(String branch) {
- return Constants.R_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(Constants.R_TAGS))
- return refName.substring(Constants.R_TAGS.length());
- else
- return null;
- }
-
- public static String tag2ref(String tag) {
- return Constants.R_TAGS + 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.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.Constants;
+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 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 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(Constants.R_HEADS))
+ return refName.substring(Constants.R_HEADS.length());
+ else
+ return null;
+ }
+
+ public static String branch2ref(String branch) {
+ return Constants.R_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(Constants.R_TAGS))
+ return refName.substring(Constants.R_TAGS.length());
+ else
+ return null;
+ }
+
+ public static String tag2ref(String tag) {
+ return Constants.R_TAGS + 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());
+ } 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());
+ } else {
+ blobIdent = new BlobIdent(newRev, null, null);
+ }
+ return blobIdent;
+ }
+
+}
diff --git a/commons.lang/src/main/java/com/pmease/commons/lang/diff/WhitespaceOption.java b/commons.lang/src/main/java/com/pmease/commons/lang/diff/WhitespaceOption.java
index 819c760814..76364419e9 100644
--- a/commons.lang/src/main/java/com/pmease/commons/lang/diff/WhitespaceOption.java
+++ b/commons.lang/src/main/java/com/pmease/commons/lang/diff/WhitespaceOption.java
@@ -12,14 +12,14 @@ public enum WhitespaceOption {
@Override
public String process(String line) {
- return line;
+ return StringUtils.stripEnd(line, " \t\r\n");
}
@Override
public String getDescription() {
- return "Do not ignore white spaces";
+ return "Ignore trailing white spaces";
}
-
+
},
IGNORE_LEADING() {
@@ -34,45 +34,45 @@ public enum WhitespaceOption {
}
},
- IGNORE_TRAILING() {
+ IGNORE_CHANGE() {
@Override
public String process(String line) {
- return StringUtils.stripEnd(line, " \t\r\n");
+ return WHITESPACE_PATTERN.matcher(line.trim()).replaceAll(" ");
}
@Override
public String getDescription() {
- return "Ignore trailing white spaces";
+ return "Ignore white space changes";
}
},
- IGNORE_CHANGE() {
+ IGNORE_ALL() {
@Override
public String process(String line) {
- return WHITESPACE_PATTERN.matcher(line.trim()).replaceAll(" ");
+ return WHITESPACE_PATTERN.matcher(line.trim()).replaceAll("");
}
@Override
public String getDescription() {
- return "Ignore white space changes";
+ return "Ignore all white spaces";
}
},
- IGNORE_ALL() {
+ DO_NOT_IGNORE() {
@Override
public String process(String line) {
- return WHITESPACE_PATTERN.matcher(line.trim()).replaceAll("");
+ return line;
}
@Override
public String getDescription() {
- return "Ignore all white spaces";
+ return "Do not ignore white spaces";
}
-
- };
+
+ };
private static final Pattern WHITESPACE_PATTERN = Pattern.compile("\\s+");
diff --git a/commons.wicket/src/main/java/com/pmease/commons/wicket/behavior/inputassist/input-assist.js b/commons.wicket/src/main/java/com/pmease/commons/wicket/behavior/inputassist/input-assist.js
index 4f6f72a9be..62e9abc307 100644
--- a/commons.wicket/src/main/java/com/pmease/commons/wicket/behavior/inputassist/input-assist.js
+++ b/commons.wicket/src/main/java/com/pmease/commons/wicket/behavior/inputassist/input-assist.js
@@ -1,187 +1,187 @@
-pmease.commons.inputassist = {
- init: function(inputId, callback) {
- var $input = $("#" + inputId);
-
- $input.data("prevValue", $input.val());
- $input.data("prevCaret", -1);
- $input.on("input click keyup", function(e) {
- var value = $input.val();
- var caret;
- if ($input.is(":focus"))
- caret = $input.caret();
- else
- caret = -1;
- if (value != $input.data("prevValue") || caret != $input.data("prevCaret")) {
- $input.data("prevValue", value);
- $input.data("prevCaret", caret);
- if ($input.is(":focus") && e.keyCode != 27 && e.keyCode != 13) // ignore esc, enter
- callback(value, caret, 1);
- }
- if (value.trim().length == 0)
- pmease.commons.inputassist.markErrors(inputId, []);
- });
- function onFocus() {
- var value = $input.val();
- if (value.length == 0 && $input.closest(".has-error").length == 0) {
- var caret = $input.caret();
- $input.data("prevValue", value);
- $input.data("prevCaret", caret);
- callback(value, caret, 1);
- }
- $input.off("focus", onFocus);
- }
- $input.on("focus", onFocus);
-
- $input.on("blur", function(e) {
- $input.data("prevCaret", -1);
- });
-
- $input.data("update", function($item) {
- var value = $item.data("content");
- $input.val(value);
- var caret = $item.data("caret");
- if (caret != undefined)
- $input.caret(caret);
- $input.focus();
- $input.trigger("input");
- });
-
- $input.bind("keydown", "up", function() {
- var $dropdown = $input.data("dropdown");
- if ($dropdown) {
- var $active = $dropdown.find("tr.active");
- if ($active.length != 0) {
- var $prev = $active.prev();
- if ($prev.length != 0) {
- $prev.addClass("active");
- $active.removeClass("active");
- }
- } else {
- $dropdown.find("tr").last().addClass("active");
- }
- $dropdown.find(".suggestions").scrollIntoView("tr.active");
- pmease.commons.inputassist.updateHelp($dropdown);
- $dropdown.align($dropdown.data("alignment"));
- return false;
- }
- });
-
- $input.bind("keydown", "down", function() {
- var $dropdown = $input.data("dropdown");
- if ($dropdown) {
- var $active = $dropdown.find("tr.active");
- if ($active.length != 0) {
- var $next = $active.next();
- if ($next.length != 0) {
- $next.addClass("active");
- $active.removeClass("active");
- }
- } else {
- $dropdown.find("tr").first().addClass("active");
- }
- $dropdown.find(".suggestions").scrollIntoView("tr.active");
- pmease.commons.inputassist.updateHelp($dropdown);
- $dropdown.align($dropdown.data("alignment"));
- return false;
- }
- });
-
- $input.bind("keydown", "return", function() {
- var $dropdown = $input.data("dropdown");
- if ($dropdown) {
- var $active = $dropdown.find("tr.active");
- if ($active.length != 0) {
- $input.data("update")($active);
- return false;
- } else {
- pmease.commons.floating.close($dropdown, true);
- }
- }
- });
-
- $input.bind("keydown", "tab", function() {
- var $dropdown = $input.data("dropdown");
- if ($dropdown) {
- var $active = $dropdown.find("tr.active");
- if ($active.length != 0)
- $input.data("update")($active);
- else
- $input.data("update")($dropdown.find("tr").first());
- return false;
- }
- });
-
- callback($input.val());
- },
-
- markErrors: function(inputId, errors) {
- var $input = $("#" + inputId);
- $input.data("errors", errors);
- var $parent = $input.closest("form");
- $parent.css("position", "relative");
- $parent.find(">.input-error-mark").remove();
- if ($input.val().length != 0) {
- for (var i in errors) {
- var error = errors[i];
- var fromCoord = getCaretCoordinates($input[0], error.from);
- var toCoord = getCaretCoordinates($input[0], error.to+1);
- var $error = $("<div class='input-error-mark'></div>");
- $error.appendTo($parent);
- var inputCoord = $input.offset();
- var parentCoord = $parent.offset();
- var textHeight = 16;
- var errorHeight = 5;
- var errorOffset = 9;
- var minWidth = 5;
- var left = fromCoord.left + inputCoord.left - parentCoord.left;
- var top = fromCoord.top + inputCoord.top - parentCoord.top + textHeight;
- $error.css({left: left, top: top});
- $error.outerWidth(Math.max(toCoord.left-fromCoord.left, minWidth));
- $error.outerHeight(errorHeight);
- }
- }
- },
-
- assistOpened: function(inputId, dropdownId) {
- var $input = $("#" + inputId);
- var $dropdown = $("#" + dropdownId);
- $dropdown.data("trigger", $input);
- $input.data("dropdown", $dropdown);
- $dropdown.on("close", function() {
- $input.data("dropdown", null);
- });
- pmease.commons.inputassist.assistUpdated(inputId, dropdownId);
- },
-
- assistUpdated: function(inputId, dropdownId) {
- var $input = $("#" + inputId);
- var $dropdown = $("#" + dropdownId);
- $dropdown.click(function() {
- $input.focus();
- });
- var $item = $dropdown.find("tr");
- $item.click(function() {
- var $this = $(this);
- $input.data("update")($this);
- });
- pmease.commons.inputassist.updateHelp($dropdown);
- },
-
- initInfiniteScroll: function(assistId, callback) {
- $("#" + assistId + " .suggestions").scroll(function() {
- if($(this).scrollTop() + $(this).innerHeight() >= $(this)[0].scrollHeight) {
- callback();
- }
- });
- },
-
- updateHelp: function($dropdown) {
- if ($dropdown.find(".help>li").length > 1)
- $dropdown.find(".help").addClass("multiple");
- if ($dropdown.find("tr.active").length != 0) {
- $dropdown.find(".help>.completion").empty().append("Press 'enter' to complete selected item");
- } else {
- $dropdown.find(".help>.completion").empty().append("Press 'tab' to complete first item");
- }
- }
+pmease.commons.inputassist = {
+ init: function(inputId, callback) {
+ var $input = $("#" + inputId);
+
+ $input.data("prevValue", $input.val());
+ $input.data("prevCaret", -1);
+ $input.on("input click keyup", function(e) {
+ var value = $input.val();
+ var caret;
+ if ($input.is(":focus"))
+ caret = $input.caret();
+ else
+ caret = -1;
+ if (value != $input.data("prevValue") || caret != $input.data("prevCaret") || !$input.data("dropdown")) {
+ $input.data("prevValue", value);
+ $input.data("prevCaret", caret);
+ if ($input.is(":focus") && e.keyCode != 27 && e.keyCode != 13) // ignore esc, enter
+ callback(value, caret, 1);
+ }
+ if (value.trim().length == 0)
+ pmease.commons.inputassist.markErrors(inputId, []);
+ });
+ function onFocus() {
+ var value = $input.val();
+ if (value.length == 0 && $input.closest(".has-error").length == 0) {
+ var caret = $input.caret();
+ $input.data("prevValue", value);
+ $input.data("prevCaret", caret);
+ callback(value, caret, 1);
+ }
+ $input.off("focus", onFocus);
+ }
+ $input.on("focus", onFocus);
+
+ $input.on("blur", function(e) {
+ $input.data("prevCaret", -1);
+ });
+
+ $input.data("update", function($item) {
+ var value = $item.data("content");
+ $input.val(value);
+ var caret = $item.data("caret");
+ if (caret != undefined)
+ $input.caret(caret);
+ $input.focus();
+ $input.trigger("input");
+ });
+
+ $input.bind("keydown", "up", function() {
+ var $dropdown = $input.data("dropdown");
+ if ($dropdown) {
+ var $active = $dropdown.find("tr.active");
+ if ($active.length != 0) {
+ var $prev = $active.prev();
+ if ($prev.length != 0) {
+ $prev.addClass("active");
+ $active.removeClass("active");
+ }
+ } else {
+ $dropdown.find("tr").last().addClass("active");
+ }
+ $dropdown.find(".suggestions").scrollIntoView("tr.active");
+ pmease.commons.inputassist.updateHelp($dropdown);
+ $dropdown.align($dropdown.data("alignment"));
+ return false;
+ }
+ });
+
+ $input.bind("keydown", "down", function() {
+ var $dropdown = $input.data("dropdown");
+ if ($dropdown) {
+ var $active = $dropdown.find("tr.active");
+ if ($active.length != 0) {
+ var $next = $active.next();
+ if ($next.length != 0) {
+ $next.addClass("active");
+ $active.removeClass("active");
+ }
+ } else {
+ $dropdown.find("tr").first().addClass("active");
+ }
+ $dropdown.find(".suggestions").scrollIntoView("tr.active");
+ pmease.commons.inputassist.updateHelp($dropdown);
+ $dropdown.align($dropdown.data("alignment"));
+ return false;
+ }
+ });
+
+ $input.bind("keydown", "return", function() {
+ var $dropdown = $input.data("dropdown");
+ if ($dropdown) {
+ var $active = $dropdown.find("tr.active");
+ if ($active.length != 0) {
+ $input.data("update")($active);
+ return false;
+ } else {
+ pmease.commons.floating.close($dropdown, true);
+ }
+ }
+ });
+
+ $input.bind("keydown", "tab", function() {
+ var $dropdown = $input.data("dropdown");
+ if ($dropdown) {
+ var $active = $dropdown.find("tr.active");
+ if ($active.length != 0)
+ $input.data("update")($active);
+ else
+ $input.data("update")($dropdown.find("tr").first());
+ return false;
+ }
+ });
+
+ callback($input.val());
+ },
+
+ markErrors: function(inputId, errors) {
+ var $input = $("#" + inputId);
+ $input.data("errors", errors);
+ var $parent = $input.closest("form");
+ $parent.css("position", "relative");
+ $parent.find(">.input-error-mark").remove();
+ if ($input.val().length != 0) {
+ for (var i in errors) {
+ var error = errors[i];
+ var fromCoord = getCaretCoordinates($input[0], error.from);
+ var toCoord = getCaretCoordinates($input[0], error.to+1);
+ var $error = $("<div class='input-error-mark'></div>");
+ $error.appendTo($parent);
+ var inputCoord = $input.offset();
+ var parentCoord = $parent.offset();
+ var textHeight = 16;
+ var errorHeight = 5;
+ var errorOffset = 9;
+ var minWidth = 5;
+ var left = fromCoord.left + inputCoord.left - parentCoord.left;
+ var top = fromCoord.top + inputCoord.top - parentCoord.top + textHeight;
+ $error.css({left: left, top: top});
+ $error.outerWidth(Math.max(toCoord.left-fromCoord.left, minWidth));
+ $error.outerHeight(errorHeight);
+ }
+ }
+ },
+
+ assistOpened: function(inputId, dropdownId) {
+ var $input = $("#" + inputId);
+ var $dropdown = $("#" + dropdownId);
+ $dropdown.data("trigger", $input);
+ $input.data("dropdown", $dropdown);
+ $dropdown.on("close", function() {
+ $input.data("dropdown", null);
+ });
+ pmease.commons.inputassist.assistUpdated(inputId, dropdownId);
+ },
+
+ assistUpdated: function(inputId, dropdownId) {
+ var $input = $("#" + inputId);
+ var $dropdown = $("#" + dropdownId);
+ $dropdown.click(function() {
+ $input.focus();
+ });
+ var $item = $dropdown.find("tr");
+ $item.click(function() {
+ var $this = $(this);
+ $input.data("update")($this);
+ });
+ pmease.commons.inputassist.updateHelp($dropdown);
+ },
+
+ initInfiniteScroll: function(assistId, callback) {
+ $("#" + assistId + " .suggestions").scroll(function() {
+ if($(this).scrollTop() + $(this).innerHeight() >= $(this)[0].scrollHeight) {
+ callback();
+ }
+ });
+ },
+
+ updateHelp: function($dropdown) {
+ if ($dropdown.find(".help>li").length > 1)
+ $dropdown.find(".help").addClass("multiple");
+ if ($dropdown.find("tr.active").length != 0) {
+ $dropdown.find(".help>.completion").empty().append("Press 'enter' to complete selected item");
+ } else {
+ $dropdown.find(".help>.completion").empty().append("Press 'tab' to complete first item");
+ }
+ }
}
\ No newline at end of file
diff --git a/gitplex.core/src/main/java/com/pmease/gitplex/core/entity/Depot.java b/gitplex.core/src/main/java/com/pmease/gitplex/core/entity/Depot.java
index 2712f2f5cb..2a6af56268 100644
--- a/gitplex.core/src/main/java/com/pmease/gitplex/core/entity/Depot.java
+++ b/gitplex.core/src/main/java/com/pmease/gitplex/core/entity/Depot.java
@@ -1,1033 +1,1014 @@
-package com.pmease.gitplex.core.entity;
-
-import java.io.File;
-import java.io.IOException;
-import java.io.InputStream;
-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.persistence.Version;
-import javax.validation.Valid;
-import javax.validation.constraints.NotNull;
-
-import org.apache.commons.lang3.SerializationUtils;
-import org.eclipse.jgit.api.CreateBranchCommand;
-import org.eclipse.jgit.api.TagCommand;
-import org.eclipse.jgit.api.errors.GitAPIException;
-import org.eclipse.jgit.diff.DiffEntry;
-import org.eclipse.jgit.diff.DiffFormatter;
-import org.eclipse.jgit.diff.MyersDiff;
-import org.eclipse.jgit.diff.RawTextComparator;
-import org.eclipse.jgit.errors.MissingObjectException;
-import org.eclipse.jgit.errors.RevisionSyntaxException;
-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.PersonIdent;
-import org.eclipse.jgit.lib.Ref;
-import org.eclipse.jgit.lib.Repository;
-import org.eclipse.jgit.revwalk.LastCommitsOfChildren;
-import org.eclipse.jgit.revwalk.LastCommitsOfChildren.Value;
-import org.eclipse.jgit.revwalk.RevCommit;
-import org.eclipse.jgit.revwalk.RevObject;
-import org.eclipse.jgit.revwalk.RevTag;
-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.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.entity.component.IntegrationPolicy;
-import com.pmease.gitplex.core.gatekeeper.AndGateKeeper;
-import com.pmease.gitplex.core.gatekeeper.GateKeeper;
-import com.pmease.gitplex.core.listener.RefListener;
-import com.pmease.gitplex.core.manager.ConfigManager;
-import com.pmease.gitplex.core.manager.DepotManager;
-import com.pmease.gitplex.core.manager.StorageManager;
-import com.pmease.gitplex.core.security.protectedobject.AccountBelonging;
-import com.pmease.gitplex.core.security.protectedobject.ProtectedObject;
-import com.pmease.gitplex.core.util.validation.DepotName;
-
-@Entity
-@Table(uniqueConstraints={@UniqueConstraint(columnNames={"g_account_id", "name"})})
-@Cache(usage=CacheConcurrencyStrategy.READ_WRITE)
-@Editable
-public class Depot extends AbstractEntity implements AccountBelonging {
-
- private static final long serialVersionUID = 1L;
-
- public static final String FQN_SEPARATOR = "/";
-
- public static final String REF_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 Account account;
-
- @ManyToOne(fetch=FetchType.LAZY)
- @JoinColumn(nullable=true)
- private Depot forkedFrom;
-
- @Column(nullable=false)
- private String name;
-
- private String description;
-
- private boolean publicRead;
-
- /*
- * Optimistic lock is necessary to ensure database integrity when update
- * gate keepers and integration policies upon depot renaming/deletion
- */
- @Version
- private long version;
-
- @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="targetDepot")
- @OnDelete(action=OnDeleteAction.CASCADE)
- private Collection<PullRequest> incomingRequests = new ArrayList<>();
-
- @OneToMany(mappedBy="sourceDepot")
- private Collection<PullRequest> outgoingRequests = new ArrayList<>();
-
- @OneToMany(mappedBy="forkedFrom")
- private Collection<Depot> forks = new ArrayList<>();
-
- @OneToMany(mappedBy="depot")
- @OnDelete(action=OnDeleteAction.CASCADE)
- private Collection<TeamAuthorization> authorizedTeams = new ArrayList<>();
-
- @OneToMany(mappedBy="depot")
- @OnDelete(action=OnDeleteAction.CASCADE)
- private Collection<UserAuthorization> authorizedUsers = new ArrayList<>();
-
- private transient Repository repository;
-
- private transient Map<BlobIdent, Blob> blobCache;
-
- private transient Map<String, Commit> commitCache;
-
- private transient Map<String, Optional<ObjectId>> objectIdCache;
-
- private transient Map<String, Map<String, Ref>> prefixRefsCache;
-
- private transient Map<AnyObjectId, Optional<RevObject>> revObjectCache;
-
- private transient Map<RevObject, Optional<RevCommit>> revCommitCache;
-
- private transient Map<String, Optional<Ref>> refCache;
-
- private transient String defaultBranch;
-
- @Override
- public Account getAccount() {
- return account;
- }
-
- public void setAccount(Account account) {
- this.account = account;
- }
-
- @Editable(order=100)
- @DepotName
- @NotEmpty
- public String getName() {
- return name;
- }
-
- public void setName(String name) {
- this.name = name;
- }
-
- @Editable(order=200, description="Optionally describe the repository")
- @Markdown
- public String getDescription() {
- return description;
- }
-
- public void setDescription(String description) {
- this.description = description;
- }
-
- @Editable(order=300, name="Public", description="Whether or not this repository can be read by everyone")
- public boolean isPublicRead() {
- return publicRead;
- }
-
- public void setPublicRead(boolean publicRead) {
- this.publicRead = publicRead;
- }
-
- @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;
- }
-
- 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 Depot getForkedFrom() {
- return forkedFrom;
- }
-
- public void setForkedFrom(Depot forkedFrom) {
- this.forkedFrom = forkedFrom;
- }
-
- public Collection<Depot> getForks() {
- return forks;
- }
-
- public void setForks(Collection<Depot> forks) {
- this.forks = forks;
- }
-
- public List<Ref> getBranchRefs() {
- List<Ref> refs = new ArrayList<Ref>(getRefs(Constants.R_HEADS).values());
- refs.sort((o1, o2) -> {
- if (o1.getObjectId().equals(o2.getObjectId())) {
- return o1.getName().compareTo(o2.getName());
- } else {
- RevCommit commit1 = getRevCommit(o1.getObjectId());
- RevCommit commit2 = getRevCommit(o2.getObjectId());
- return commit2.getCommitTime() - commit1.getCommitTime();
- }
- });
- return refs;
- }
-
- public List<Ref> getTagRefs() {
- List<Ref> refs = new ArrayList<>();
- for (Ref ref: getRefs(Constants.R_TAGS).values()) {
- if (getRevCommit(ref.getObjectId(), false) != null)
- refs.add(ref);
- }
- refs.sort((o1, o2) -> {
- RevObject obj1 = getRevObject(o1.getObjectId());
- RevObject obj2 = getRevObject(o2.getObjectId());
- if (obj1 instanceof RevTag && obj2 instanceof RevTag) {
- RevTag tag1 = (RevTag) obj1;
- RevTag tag2 = (RevTag) obj2;
- if (tag1.getTaggerIdent() != null && tag2.getTaggerIdent() != null)
- return tag2.getTaggerIdent().getWhen().compareTo(tag1.getTaggerIdent().getWhen());
- }
- RevCommit commit1 = getRevCommit(o1.getObjectId());
- RevCommit commit2 = getRevCommit(o2.getObjectId());
- if (commit1.getId().equals(commit2.getId()))
- return o1.getName().compareTo(o2.getName());
- else
- return commit2.getCommitTime() - commit1.getCommitTime();
- });
- return refs;
- }
-
- @Override
- public boolean has(ProtectedObject object) {
- if (object instanceof Depot) {
- Depot depot = (Depot) object;
- return depot.getId().equals(getId());
- } else {
- return false;
- }
- }
-
- public String getFQN() {
- return getAccount().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).getDepotDir(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().depotDir(), "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().depotDir(), "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 Depot findForkRoot() {
- if (forkedFrom != null) {
- Depot 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<Depot> findForkDescendants() {
- List<Depot> descendants = new ArrayList<>();
- for (Depot 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<Depot> findAffinals() {
- List<Depot> affinals = new ArrayList<Depot>();
- Depot forkRoot = findForkRoot();
- if (forkRoot != null) {
- affinals.add(forkRoot);
- affinals.addAll(forkRoot.findForkDescendants());
- } else {
- affinals.add(this);
- affinals.addAll(findForkDescendants());
- }
- affinals.sort((repo1, repo2) -> {
- if (repo1.getAccount().equals(repo2.getAccount()))
- return repo1.getName().compareTo(repo2.getName());
- else
- return repo1.getAccount().getName().compareTo(repo2.getAccount().getName());
- });
- return affinals;
- }
-
- public Repository getRepository() {
- if (repository == null) {
- repository = GitPlex.getInstance(DepotManager.class).getRepository(this);
- }
- return repository;
- }
-
- public RevCommit getMergeBase(String ancestor, String descendant) {
- try (RevWalk revWalk = new RevWalk(getRepository())) {
- ObjectId ancestorId = getObjectId(ancestor);
- ObjectId descendantId = getObjectId(descendant);
- revWalk.setRevFilter(RevFilter.MERGE_BASE);
- RevCommit ancestorCommit = getRevCommit(ancestorId);
- RevCommit descendantCommit = getRevCommit(descendantId);
-
- // we should look up commit again as markStart requires that the commit
- // should be resolved in the same revWalk. Also we should not look up
- // against ancestorId directly as it might be id of an annotated tag
- revWalk.markStart(revWalk.lookupCommit(ancestorCommit.getId()));
- revWalk.markStart(revWalk.lookupCommit(descendantCommit.getId()));
- return Preconditions.checkNotNull(revWalk.next());
- } catch (IOException e) {
- throw new RuntimeException(e);
- }
- }
-
- public boolean isAncestor(String ancestor, String descendant) {
- try (RevWalk revWalk = new RevWalk(getRepository())) {
- ObjectId ancestorId = getObjectId(ancestor);
- ObjectId descendantId = getObjectId(descendant);
- revWalk.setRevFilter(RevFilter.MERGE_BASE);
- RevCommit ancestorCommit = getRevCommit(ancestorId);
- RevCommit descendantCommit = getRevCommit(descendantId);
-
- // we should look up commit again as markStart requires that the commit
- // should be resolved in the same revWalk. Also we should not look up
- // against ancestorId directly as it might be id of an annotated tag
- revWalk.markStart(revWalk.lookupCommit(ancestorCommit.getId()));
- revWalk.markStart(revWalk.lookupCommit(descendantCommit.getId()));
- return ancestorId.equals(Preconditions.checkNotNull(revWalk.next().getId()));
- } catch (IOException e) {
- throw new RuntimeException(e);
- }
- }
-
- public String getUrl() {
- return GitPlex.getInstance(ConfigManager.class).getSystemSetting().getServerUrl() + "/" + 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 {
- 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 = getRepository().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 (RevWalk revWalk = new RevWalk(getRepository())) {
- ObjectId commitId = getObjectId(blobIdent.revision);
- RevTree revTree = revWalk.parseCommit(commitId).getTree();
- TreeWalk treeWalk = TreeWalk.forPath(getRepository(), 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 (RevWalk revWalk = new RevWalk(getRepository())) {
- ObjectId commitId = getObjectId(ident.revision);
- RevTree revTree = revWalk.parseCommit(commitId).getTree();
- TreeWalk treeWalk = TreeWalk.forPath(getRepository(), 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;
- try {
- objectId = getRepository().resolve(revision);
- } catch (RevisionSyntaxException | IOException e) {
- if (!mustExist) {
- objectId = null;
- } else {
- 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) {
- List<DiffEntry> diffs = new ArrayList<>();
- try (DiffFormatter diffFormatter = new DiffFormatter(NullOutputStream.INSTANCE);) {
- diffFormatter.setRepository(getRepository());
- diffFormatter.setDetectRenames(true);
- diffFormatter.setDiffAlgorithm(MyersDiff.INSTANCE);
- diffFormatter.setDiffComparator(RawTextComparator.DEFAULT);
- AnyObjectId oldCommitId = getObjectId(oldRev);
- AnyObjectId newCommitId = getObjectId(newRev);
- for (DiffEntry entry: diffFormatter.scan(oldCommitId, newCommitId)) {
- 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);
- }
- 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 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);
-
- long time = System.currentTimeMillis();
- LastCommitsOfChildren lastCommits = new LastCommitsOfChildren(getRepository(), 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;
- }
-
- @Nullable
- public Ref getRef(String revision) {
- if (refCache == null)
- refCache = new HashMap<>();
- Optional<Ref> optional = refCache.get(revision);
- if (optional == null) {
- try {
- optional = Optional.fromNullable(getRepository().findRef(revision));
- } catch (IOException e) {
- throw new RuntimeException(e);
- }
- refCache.put(revision, optional);
- }
- return optional.orNull();
- }
-
- public RevObject getRevObject(AnyObjectId revId) {
- return getRevObject(revId, true);
- }
-
- @Nullable
- public RevObject getRevObject(AnyObjectId revId, boolean mustExist) {
- if (revId == null && !mustExist)
- return null;
-
- if (revObjectCache == null)
- revObjectCache = new HashMap<>();
- Optional<RevObject> optional = revObjectCache.get(revId);
- if (optional == null) {
- try (RevWalk revWalk = new RevWalk(getRepository());) {
- optional = Optional.of(revWalk.parseAny(revId));
- } catch (MissingObjectException e) {
- if (!mustExist)
- optional = Optional.absent();
- } catch (IOException e) {
- throw new RuntimeException(e);
- }
- revObjectCache.put(revId, optional);
- }
- if (mustExist)
- return optional.get();
- else
- return optional.orNull();
- }
-
- public RevCommit getRevCommit(RevObject revObject) {
- return getRevCommit(revObject, true);
- }
-
- @Nullable
- public RevCommit getRevCommit(RevObject revObject, boolean mustExist) {
- if (revObject == null && !mustExist)
- return null;
-
- if (revCommitCache == null)
- revCommitCache = new HashMap<>();
- Optional<RevCommit> optional = revCommitCache.get(revObject);
- if (optional == null) {
- try (RevWalk revWalk = new RevWalk(getRepository())) {
- RevObject peeled = revWalk.peel(revObject);
- if (peeled instanceof RevCommit)
- optional = Optional.of((RevCommit) peeled);
- else
- optional = Optional.absent();
- } catch (IOException e) {
- throw new RuntimeException(e);
- }
- revCommitCache.put(revObject, optional);
- }
- if (mustExist)
- return optional.get();
- else
- return optional.orNull();
- }
-
- @Nullable
- public RevCommit getRevCommit(AnyObjectId revId, boolean mustExist) {
- return getRevCommit(getRevObject(revId, mustExist), mustExist);
- }
-
- @Nullable
- public RevCommit getRevCommit(String revision, boolean mustExist) {
- return getRevCommit(getObjectId(revision, mustExist), mustExist);
- }
-
- public RevCommit getRevCommit(String revision) {
- return getRevCommit(revision, true);
- }
-
- public RevCommit getRevCommit(AnyObjectId revId) {
- return getRevCommit(getRevObject(revId), true);
- }
-
- public Map<String, Ref> getRefs(String prefix) {
- if (prefixRefsCache == null)
- prefixRefsCache = new HashMap<>();
-
- Map<String, Ref> cached = prefixRefsCache.get(prefix);
- if (cached == null) {
- try {
- cached = getRepository().getRefDatabase().getRefs(prefix);
- prefixRefsCache.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 void deleteBranch(String branch) {
- String refName = GitUtils.branch2ref(branch);
- ObjectId commitId = getRevCommit(refName).getId();
- git().deleteRef(refName);
- for (RefListener listener: GitPlex.getExtensions(RefListener.class))
- listener.onRefUpdate(this, refName, commitId, ObjectId.zeroId());
- }
-
- public void createBranch(String branchName, String branchRevision) {
- try {
- CreateBranchCommand command = org.eclipse.jgit.api.Git.wrap(getRepository()).branchCreate();
- command.setName(branchName);
- command.setStartPoint(getRevCommit(branchRevision));
- command.call();
- } catch (GitAPIException e) {
- throw new RuntimeException(e);
- }
- }
-
- public void tag(String tagName, String tagRevision, PersonIdent taggerIdent, @Nullable String tagMessage) {
- try {
- TagCommand tag = org.eclipse.jgit.api.Git.wrap(getRepository()).tag();
- tag.setName(tagName);
- if (tagMessage != null)
- tag.setMessage(tagMessage);
- tag.setTagger(taggerIdent);
- tag.setObjectId(getRevCommit(tagRevision));
- tag.call();
- } catch (GitAPIException e) {
- throw new RuntimeException(e);
- }
- }
-
- public void deleteTag(String tag) {
- String refName = GitUtils.tag2ref(tag);
- ObjectId commitId = getRevCommit(refName).getId();
- git().deleteRef(refName);
- for (RefListener listener: GitPlex.getExtensions(RefListener.class))
- listener.onRefUpdate(this, refName, commitId, ObjectId.zeroId());
- }
-
- public Collection<TeamAuthorization> getAuthorizedTeams() {
- return authorizedTeams;
- }
-
- public void setAuthorizedTeams(Collection<TeamAuthorization> authorizedTeams) {
- this.authorizedTeams = authorizedTeams;
- }
-
- public Collection<UserAuthorization> getAuthorizedUsers() {
- return authorizedUsers;
- }
-
- public void setAuthorizedUsers(Collection<UserAuthorization> authorizedUsers) {
- this.authorizedUsers = authorizedUsers;
- }
-
- public long getVersion() {
- return version;
- }
-
- public boolean matches(@Nullable String searchTerm) {
- if (searchTerm == null)
- searchTerm = "";
- else
- searchTerm = searchTerm.toLowerCase().trim();
-
- return getName().toLowerCase().contains(searchTerm);
- }
-
- public boolean matchesFQN(@Nullable String searchTerm) {
- if (searchTerm == null)
- searchTerm = "";
- else
- searchTerm = searchTerm.toLowerCase().trim();
-
- return getFQN().toLowerCase().contains(searchTerm);
- }
-
- @Override
- public int compareTo(AbstractEntity entity) {
- Depot depot = (Depot) entity;
- if (getAccount().equals(depot.getAccount())) {
- return getName().compareTo(depot.getName());
- } else {
- return getAccount().compareTo(depot.getAccount());
- }
- }
-
-}
+package com.pmease.gitplex.core.entity;
+
+import java.io.File;
+import java.io.IOException;
+import java.io.InputStream;
+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.persistence.Version;
+import javax.validation.Valid;
+import javax.validation.constraints.NotNull;
+
+import org.apache.commons.lang3.SerializationUtils;
+import org.eclipse.jgit.api.CreateBranchCommand;
+import org.eclipse.jgit.api.TagCommand;
+import org.eclipse.jgit.api.errors.GitAPIException;
+import org.eclipse.jgit.diff.DiffEntry;
+import org.eclipse.jgit.diff.DiffFormatter;
+import org.eclipse.jgit.diff.MyersDiff;
+import org.eclipse.jgit.diff.RawTextComparator;
+import org.eclipse.jgit.errors.MissingObjectException;
+import org.eclipse.jgit.errors.RevisionSyntaxException;
+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.PersonIdent;
+import org.eclipse.jgit.lib.Ref;
+import org.eclipse.jgit.lib.Repository;
+import org.eclipse.jgit.revwalk.LastCommitsOfChildren;
+import org.eclipse.jgit.revwalk.LastCommitsOfChildren.Value;
+import org.eclipse.jgit.revwalk.RevCommit;
+import org.eclipse.jgit.revwalk.RevObject;
+import org.eclipse.jgit.revwalk.RevTag;
+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.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.entity.component.IntegrationPolicy;
+import com.pmease.gitplex.core.gatekeeper.AndGateKeeper;
+import com.pmease.gitplex.core.gatekeeper.GateKeeper;
+import com.pmease.gitplex.core.listener.RefListener;
+import com.pmease.gitplex.core.manager.ConfigManager;
+import com.pmease.gitplex.core.manager.DepotManager;
+import com.pmease.gitplex.core.manager.StorageManager;
+import com.pmease.gitplex.core.security.protectedobject.AccountBelonging;
+import com.pmease.gitplex.core.security.protectedobject.ProtectedObject;
+import com.pmease.gitplex.core.util.validation.DepotName;
+
+@Entity
+@Table(uniqueConstraints={@UniqueConstraint(columnNames={"g_account_id", "name"})})
+@Cache(usage=CacheConcurrencyStrategy.READ_WRITE)
+@Editable
+public class Depot extends AbstractEntity implements AccountBelonging {
+
+ private static final long serialVersionUID = 1L;
+
+ public static final String FQN_SEPARATOR = "/";
+
+ public static final String REF_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 Account account;
+
+ @ManyToOne(fetch=FetchType.LAZY)
+ @JoinColumn(nullable=true)
+ private Depot forkedFrom;
+
+ @Column(nullable=false)
+ private String name;
+
+ private String description;
+
+ private boolean publicRead;
+
+ /*
+ * Optimistic lock is necessary to ensure database integrity when update
+ * gate keepers and integration policies upon depot renaming/deletion
+ */
+ @Version
+ private long version;
+
+ @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="targetDepot")
+ @OnDelete(action=OnDeleteAction.CASCADE)
+ private Collection<PullRequest> incomingRequests = new ArrayList<>();
+
+ @OneToMany(mappedBy="sourceDepot")
+ private Collection<PullRequest> outgoingRequests = new ArrayList<>();
+
+ @OneToMany(mappedBy="forkedFrom")
+ private Collection<Depot> forks = new ArrayList<>();
+
+ @OneToMany(mappedBy="depot")
+ @OnDelete(action=OnDeleteAction.CASCADE)
+ private Collection<TeamAuthorization> authorizedTeams = new ArrayList<>();
+
+ @OneToMany(mappedBy="depot")
+ @OnDelete(action=OnDeleteAction.CASCADE)
+ private Collection<UserAuthorization> authorizedUsers = new ArrayList<>();
+
+ private transient Repository repository;
+
+ private transient Map<BlobIdent, Blob> blobCache;
+
+ private transient Map<String, Commit> commitCache;
+
+ private transient Map<String, Optional<ObjectId>> objectIdCache;
+
+ private transient Map<String, Map<String, Ref>> prefixRefsCache;
+
+ private transient Map<AnyObjectId, Optional<RevObject>> revObjectCache;
+
+ private transient Map<RevObject, Optional<RevCommit>> revCommitCache;
+
+ private transient Map<String, Optional<Ref>> refCache;
+
+ private transient String defaultBranch;
+
+ @Override
+ public Account getAccount() {
+ return account;
+ }
+
+ public void setAccount(Account account) {
+ this.account = account;
+ }
+
+ @Editable(order=100)
+ @DepotName
+ @NotEmpty
+ public String getName() {
+ return name;
+ }
+
+ public void setName(String name) {
+ this.name = name;
+ }
+
+ @Editable(order=200, description="Optionally describe the repository")
+ @Markdown
+ public String getDescription() {
+ return description;
+ }
+
+ public void setDescription(String description) {
+ this.description = description;
+ }
+
+ @Editable(order=300, name="Public", description="Whether or not this repository can be read by everyone")
+ public boolean isPublicRead() {
+ return publicRead;
+ }
+
+ public void setPublicRead(boolean publicRead) {
+ this.publicRead = publicRead;
+ }
+
+ @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;
+ }
+
+ 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 Depot getForkedFrom() {
+ return forkedFrom;
+ }
+
+ public void setForkedFrom(Depot forkedFrom) {
+ this.forkedFrom = forkedFrom;
+ }
+
+ public Collection<Depot> getForks() {
+ return forks;
+ }
+
+ public void setForks(Collection<Depot> forks) {
+ this.forks = forks;
+ }
+
+ public List<Ref> getBranchRefs() {
+ List<Ref> refs = new ArrayList<Ref>(getRefs(Constants.R_HEADS).values());
+ refs.sort((o1, o2) -> {
+ if (o1.getObjectId().equals(o2.getObjectId())) {
+ return o1.getName().compareTo(o2.getName());
+ } else {
+ RevCommit commit1 = getRevCommit(o1.getObjectId());
+ RevCommit commit2 = getRevCommit(o2.getObjectId());
+ return commit2.getCommitTime() - commit1.getCommitTime();
+ }
+ });
+ return refs;
+ }
+
+ public List<Ref> getTagRefs() {
+ List<Ref> refs = new ArrayList<>();
+ for (Ref ref: getRefs(Constants.R_TAGS).values()) {
+ if (getRevCommit(ref.getObjectId(), false) != null)
+ refs.add(ref);
+ }
+ refs.sort((o1, o2) -> {
+ RevObject obj1 = getRevObject(o1.getObjectId());
+ RevObject obj2 = getRevObject(o2.getObjectId());
+ if (obj1 instanceof RevTag && obj2 instanceof RevTag) {
+ RevTag tag1 = (RevTag) obj1;
+ RevTag tag2 = (RevTag) obj2;
+ if (tag1.getTaggerIdent() != null && tag2.getTaggerIdent() != null)
+ return tag2.getTaggerIdent().getWhen().compareTo(tag1.getTaggerIdent().getWhen());
+ }
+ RevCommit commit1 = getRevCommit(o1.getObjectId());
+ RevCommit commit2 = getRevCommit(o2.getObjectId());
+ if (commit1.getId().equals(commit2.getId()))
+ return o1.getName().compareTo(o2.getName());
+ else
+ return commit2.getCommitTime() - commit1.getCommitTime();
+ });
+ return refs;
+ }
+
+ @Override
+ public boolean has(ProtectedObject object) {
+ if (object instanceof Depot) {
+ Depot depot = (Depot) object;
+ return depot.getId().equals(getId());
+ } else {
+ return false;
+ }
+ }
+
+ public String getFQN() {
+ return getAccount().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).getDepotDir(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().depotDir(), "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().depotDir(), "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 Depot findForkRoot() {
+ if (forkedFrom != null) {
+ Depot 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<Depot> findForkDescendants() {
+ List<Depot> descendants = new ArrayList<>();
+ for (Depot 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<Depot> findAffinals() {
+ List<Depot> affinals = new ArrayList<Depot>();
+ Depot forkRoot = findForkRoot();
+ if (forkRoot != null) {
+ affinals.add(forkRoot);
+ affinals.addAll(forkRoot.findForkDescendants());
+ } else {
+ affinals.add(this);
+ affinals.addAll(findForkDescendants());
+ }
+ affinals.sort((repo1, repo2) -> {
+ if (repo1.getAccount().equals(repo2.getAccount()))
+ return repo1.getName().compareTo(repo2.getName());
+ else
+ return repo1.getAccount().getName().compareTo(repo2.getAccount().getName());
+ });
+ return affinals;
+ }
+
+ public Repository getRepository() {
+ if (repository == null) {
+ repository = GitPlex.getInstance(DepotManager.class).getRepository(this);
+ }
+ return repository;
+ }
+
+ public RevCommit getMergeBase(String ancestor, String descendant) {
+ try (RevWalk revWalk = new RevWalk(getRepository())) {
+ ObjectId ancestorId = getObjectId(ancestor);
+ ObjectId descendantId = getObjectId(descendant);
+ revWalk.setRevFilter(RevFilter.MERGE_BASE);
+ RevCommit ancestorCommit = getRevCommit(ancestorId);
+ RevCommit descendantCommit = getRevCommit(descendantId);
+
+ // we should look up commit again as markStart requires that the commit
+ // should be resolved in the same revWalk. Also we should not look up
+ // against ancestorId directly as it might be id of an annotated tag
+ revWalk.markStart(revWalk.lookupCommit(ancestorCommit.getId()));
+ revWalk.markStart(revWalk.lookupCommit(descendantCommit.getId()));
+ return Preconditions.checkNotNull(revWalk.next());
+ } catch (IOException e) {
+ throw new RuntimeException(e);
+ }
+ }
+
+ public boolean isAncestor(String ancestor, String descendant) {
+ try (RevWalk revWalk = new RevWalk(getRepository())) {
+ ObjectId ancestorId = getObjectId(ancestor);
+ ObjectId descendantId = getObjectId(descendant);
+ revWalk.setRevFilter(RevFilter.MERGE_BASE);
+ RevCommit ancestorCommit = getRevCommit(ancestorId);
+ RevCommit descendantCommit = getRevCommit(descendantId);
+
+ // we should look up commit again as markStart requires that the commit
+ // should be resolved in the same revWalk. Also we should not look up
+ // against ancestorId directly as it might be id of an annotated tag
+ revWalk.markStart(revWalk.lookupCommit(ancestorCommit.getId()));
+ revWalk.markStart(revWalk.lookupCommit(descendantCommit.getId()));
+ return ancestorId.equals(Preconditions.checkNotNull(revWalk.next().getId()));
+ } catch (IOException e) {
+ throw new RuntimeException(e);
+ }
+ }
+
+ public String getUrl() {
+ return GitPlex.getInstance(ConfigManager.class).getSystemSetting().getServerUrl() + "/" + 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) {
+ try (RevWalk revWalk = new RevWalk(getRepository())) {
+ ObjectId commitId = getObjectId(blobIdent.revision);
+ RevTree revTree = revWalk.parseCommit(commitId).getTree();
+ TreeWalk treeWalk = TreeWalk.forPath(getRepository(), 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 (RevWalk revWalk = new RevWalk(getRepository())) {
+ ObjectId commitId = getObjectId(ident.revision);
+ RevTree revTree = revWalk.parseCommit(commitId).getTree();
+ TreeWalk treeWalk = TreeWalk.forPath(getRepository(), 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;
+ try {
+ objectId = getRepository().resolve(revision);
+ } catch (RevisionSyntaxException | IOException e) {
+ if (!mustExist) {
+ objectId = null;
+ } else {
+ 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) {
+ List<DiffEntry> diffs = new ArrayList<>();
+ try (DiffFormatter diffFormatter = new DiffFormatter(NullOutputStream.INSTANCE);) {
+ diffFormatter.setRepository(getRepository());
+ diffFormatter.setDetectRenames(true);
+ diffFormatter.setDiffAlgorithm(MyersDiff.INSTANCE);
+ diffFormatter.setDiffComparator(RawTextComparator.DEFAULT);
+ AnyObjectId oldCommitId = getObjectId(oldRev);
+ AnyObjectId newCommitId = getObjectId(newRev);
+ for (DiffEntry entry: diffFormatter.scan(oldCommitId, newCommitId)) {
+ 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);
+ }
+ 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 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);
+
+ long time = System.currentTimeMillis();
+ LastCommitsOfChildren lastCommits = new LastCommitsOfChildren(getRepository(), 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;
+ }
+
+ @Nullable
+ public Ref getRef(String revision) {
+ if (refCache == null)
+ refCache = new HashMap<>();
+ Optional<Ref> optional = refCache.get(revision);
+ if (optional == null) {
+ try {
+ optional = Optional.fromNullable(getRepository().findRef(revision));
+ } catch (IOException e) {
+ throw new RuntimeException(e);
+ }
+ refCache.put(revision, optional);
+ }
+ return optional.orNull();
+ }
+
+ public RevObject getRevObject(AnyObjectId revId) {
+ return getRevObject(revId, true);
+ }
+
+ @Nullable
+ public RevObject getRevObject(AnyObjectId revId, boolean mustExist) {
+ if (revId == null && !mustExist)
+ return null;
+
+ if (revObjectCache == null)
+ revObjectCache = new HashMap<>();
+ Optional<RevObject> optional = revObjectCache.get(revId);
+ if (optional == null) {
+ try (RevWalk revWalk = new RevWalk(getRepository());) {
+ optional = Optional.of(revWalk.parseAny(revId));
+ } catch (MissingObjectException e) {
+ if (!mustExist)
+ optional = Optional.absent();
+ } catch (IOException e) {
+ throw new RuntimeException(e);
+ }
+ revObjectCache.put(revId, optional);
+ }
+ if (mustExist)
+ return optional.get();
+ else
+ return optional.orNull();
+ }
+
+ public RevCommit getRevCommit(RevObject revObject) {
+ return getRevCommit(revObject, true);
+ }
+
+ @Nullable
+ public RevCommit getRevCommit(RevObject revObject, boolean mustExist) {
+ if (revObject == null && !mustExist)
+ return null;
+
+ if (revCommitCache == null)
+ revCommitCache = new HashMap<>();
+ Optional<RevCommit> optional = revCommitCache.get(revObject);
+ if (optional == null) {
+ try (RevWalk revWalk = new RevWalk(getRepository())) {
+ RevObject peeled = revWalk.peel(revObject);
+ if (peeled instanceof RevCommit)
+ optional = Optional.of((RevCommit) peeled);
+ else
+ optional = Optional.absent();
+ } catch (IOException e) {
+ throw new RuntimeException(e);
+ }
+ revCommitCache.put(revObject, optional);
+ }
+ if (mustExist)
+ return optional.get();
+ else
+ return optional.orNull();
+ }
+
+ @Nullable
+ public RevCommit getRevCommit(AnyObjectId revId, boolean mustExist) {
+ return getRevCommit(getRevObject(revId, mustExist), mustExist);
+ }
+
+ @Nullable
+ public RevCommit getRevCommit(String revision, boolean mustExist) {
+ return getRevCommit(getObjectId(revision, mustExist), mustExist);
+ }
+
+ public RevCommit getRevCommit(String revision) {
+ return getRevCommit(revision, true);
+ }
+
+ public RevCommit getRevCommit(AnyObjectId revId) {
+ return getRevCommit(getRevObject(revId), true);
+ }
+
+ public Map<String, Ref> getRefs(String prefix) {
+ if (prefixRefsCache == null)
+ prefixRefsCache = new HashMap<>();
+
+ Map<String, Ref> cached = prefixRefsCache.get(prefix);
+ if (cached == null) {
+ try {
+ cached = getRepository().getRefDatabase().getRefs(prefix);
+ prefixRefsCache.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 void deleteBranch(String branch) {
+ String refName = GitUtils.branch2ref(branch);
+ ObjectId commitId = getRevCommit(refName).getId();
+ git().deleteRef(refName);
+ for (RefListener listener: GitPlex.getExtensions(RefListener.class))
+ listener.onRefUpdate(this, refName, commitId, ObjectId.zeroId());
+ }
+
+ public void createBranch(String branchName, String branchRevision) {
+ try {
+ CreateBranchCommand command = org.eclipse.jgit.api.Git.wrap(getRepository()).branchCreate();
+ command.setName(branchName);
+ command.setStartPoint(getRevCommit(branchRevision));
+ command.call();
+ } catch (GitAPIException e) {
+ throw new RuntimeException(e);
+ }
+ }
+
+ public void tag(String tagName, String tagRevision, PersonIdent taggerIdent, @Nullable String tagMessage) {
+ try {
+ TagCommand tag = org.eclipse.jgit.api.Git.wrap(getRepository()).tag();
+ tag.setName(tagName);
+ if (tagMessage != null)
+ tag.setMessage(tagMessage);
+ tag.setTagger(taggerIdent);
+ tag.setObjectId(getRevCommit(tagRevision));
+ tag.call();
+ } catch (GitAPIException e) {
+ throw new RuntimeException(e);
+ }
+ }
+
+ public void deleteTag(String tag) {
+ String refName = GitUtils.tag2ref(tag);
+ ObjectId commitId = getRevCommit(refName).getId();
+ git().deleteRef(refName);
+ for (RefListener listener: GitPlex.getExtensions(RefListener.class))
+ listener.onRefUpdate(this, refName, commitId, ObjectId.zeroId());
+ }
+
+ public Collection<TeamAuthorization> getAuthorizedTeams() {
+ return authorizedTeams;
+ }
+
+ public void setAuthorizedTeams(Collection<TeamAuthorization> authorizedTeams) {
+ this.authorizedTeams = authorizedTeams;
+ }
+
+ public Collection<UserAuthorization> getAuthorizedUsers() {
+ return authorizedUsers;
+ }
+
+ public void setAuthorizedUsers(Collection<UserAuthorization> authorizedUsers) {
+ this.authorizedUsers = authorizedUsers;
+ }
+
+ public long getVersion() {
+ return version;
+ }
+
+ public boolean matches(@Nullable String searchTerm) {
+ if (searchTerm == null)
+ searchTerm = "";
+ else
+ searchTerm = searchTerm.toLowerCase().trim();
+
+ return getName().toLowerCase().contains(searchTerm);
+ }
+
+ public boolean matchesFQN(@Nullable String searchTerm) {
+ if (searchTerm == null)
+ searchTerm = "";
+ else
+ searchTerm = searchTerm.toLowerCase().trim();
+
+ return getFQN().toLowerCase().contains(searchTerm);
+ }
+
+ @Override
+ public int compareTo(AbstractEntity entity) {
+ Depot depot = (Depot) entity;
+ if (getAccount().equals(depot.getAccount())) {
+ return getName().compareTo(depot.getName());
+ } else {
+ return getAccount().compareTo(depot.getAccount());
+ }
+ }
+
+}
diff --git a/gitplex.web/src/main/java/com/pmease/gitplex/web/component/depotfile/blobview/source/SourceViewPanel.java b/gitplex.web/src/main/java/com/pmease/gitplex/web/component/depotfile/blobview/source/SourceViewPanel.java
index cfa99d1afd..3e711fe940 100644
--- a/gitplex.web/src/main/java/com/pmease/gitplex/web/component/depotfile/blobview/source/SourceViewPanel.java
+++ b/gitplex.web/src/main/java/com/pmease/gitplex/web/component/depotfile/blobview/source/SourceViewPanel.java
@@ -566,7 +566,7 @@ public class SourceViewPanel extends BlobViewPanel {
@Override
protected void onSelect(AjaxRequestTarget target, QueryHit hit) {
BlobIdent blobIdent = new BlobIdent(
- getRevision(), hit.getBlobPath(), FileMode.REGULAR_FILE.getBits());
+ getCommitId().name(), hit.getBlobPath(), FileMode.REGULAR_FILE.getBits());
context.onSelect(target, blobIdent, hit.getTokenPos());
}
diff --git a/gitplex.web/src/main/java/com/pmease/gitplex/web/component/diff/blob/text/TextDiffPanel.java b/gitplex.web/src/main/java/com/pmease/gitplex/web/component/diff/blob/text/TextDiffPanel.java
index 58e6ada77f..b5f2d19aac 100644
--- a/gitplex.web/src/main/java/com/pmease/gitplex/web/component/diff/blob/text/TextDiffPanel.java
+++ b/gitplex.web/src/main/java/com/pmease/gitplex/web/component/diff/blob/text/TextDiffPanel.java
@@ -207,7 +207,7 @@ public class TextDiffPanel extends Panel {
@Override
protected String getBlobPath() {
- if (getRevision().equals(change.getNewBlobIdent().revision))
+ if (getCommitId().name().equals(change.getNewBlobIdent().revision))
return change.getNewBlobIdent().path;
else
return change.getOldBlobIdent().path;
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 917be3260c..fcf6f8a66a 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
@@ -43,7 +43,6 @@ import org.eclipse.jgit.diff.DiffEntry;
import org.eclipse.jgit.diff.DiffEntry.ChangeType;
import com.google.common.base.Objects;
-import com.google.common.base.Preconditions;
import com.google.common.collect.Lists;
import com.pmease.commons.antlr.codeassist.InputCompletion;
import com.pmease.commons.antlr.codeassist.InputStatus;
@@ -353,7 +352,10 @@ public abstract class RevisionDiffPanel extends Panel {
@Override
public void setObject(String object) {
- pathFilter = object;
+ if (object != null)
+ pathFilter = object;
+ else
+ pathFilter = ""; // use empty string to make files tab being selected upon refresh
}
}));
@@ -427,7 +429,6 @@ public abstract class RevisionDiffPanel extends Panel {
@Override
protected void onSubmit(AjaxRequestTarget target, Form<?> form) {
super.onSubmit(target, form);
- Preconditions.checkNotNull(target);
target.add(body);
onPathFilterChange(target, pathFilter);
}
@@ -600,9 +601,6 @@ public abstract class RevisionDiffPanel extends Panel {
new JavaScriptResourceReference(RevisionDiffPanel.class, "revision-diff.js")));
response.render(CssHeaderItem.forReference(
new CssResourceReference(RevisionDiffPanel.class, "revision-diff.css")));
-
- if (RequestCycle.get().find(AjaxRequestTarget.class) == null)
- response.render(OnDomReadyHeaderItem.forScript("gitplex.revisionDiff.scroll();"));
}
protected abstract void onPathFilterChange(AjaxRequestTarget target, String pathFilter);
diff --git a/gitplex.web/src/main/java/com/pmease/gitplex/web/component/symboltooltip/SymbolTooltipPanel.java b/gitplex.web/src/main/java/com/pmease/gitplex/web/component/symboltooltip/SymbolTooltipPanel.java
index f42e2e2a59..e226e355ed 100644
--- a/gitplex.web/src/main/java/com/pmease/gitplex/web/component/symboltooltip/SymbolTooltipPanel.java
+++ b/gitplex.web/src/main/java/com/pmease/gitplex/web/component/symboltooltip/SymbolTooltipPanel.java
@@ -57,7 +57,7 @@ public abstract class SymbolTooltipPanel extends Panel {
private final IModel<PullRequest> requestModel;
- private String revision = "";
+ private ObjectId commitId = ObjectId.zeroId();
private String symbol = "";
@@ -157,8 +157,7 @@ public abstract class SymbolTooltipPanel extends Panel {
null, null, SearchResultPanel.MAX_QUERY_ENTRIES);
try {
SearchManager searchManager = GitPlex.getInstance(SearchManager.class);
- ObjectId commit = depotModel.getObject().getRevCommit(revision);
- List<QueryHit> hits = searchManager.search(depotModel.getObject(), commit, query);
+ List<QueryHit> hits = searchManager.search(depotModel.getObject(), commitId, query);
onOccurrencesQueried(target, hits);
} catch (InterruptedException e) {
throw new RuntimeException(e);
@@ -190,18 +189,17 @@ public abstract class SymbolTooltipPanel extends Panel {
@Override
protected void respond(AjaxRequestTarget target) {
IRequestParameters params = RequestCycle.get().getRequest().getQueryParameters();
- revision = params.getParameterValue("revision").toString();
+ commitId = ObjectId.fromString(params.getParameterValue("commit").toString());
symbol = params.getParameterValue("symbol").toString();
if (symbol.startsWith("@"))
symbol = symbol.substring(1);
try {
SymbolQuery query = new SymbolQuery(symbol, true, true, null, null, QUERY_ENTRIES);
SearchManager searchManager = GitPlex.getInstance(SearchManager.class);
- ObjectId commit = depotModel.getObject().getRevCommit(revision);
- symbolHits = searchManager.search(depotModel.getObject(), commit, query);
+ symbolHits = searchManager.search(depotModel.getObject(), commitId, query);
if (symbolHits.size() < QUERY_ENTRIES) {
query = new SymbolQuery(symbol, false, true, null, null, QUERY_ENTRIES - symbolHits.size());
- symbolHits.addAll(searchManager.search(depotModel.getObject(), commit, query));
+ symbolHits.addAll(searchManager.search(depotModel.getObject(), commitId, query));
}
} catch (InterruptedException e) {
throw new RuntimeException(e);
@@ -224,7 +222,7 @@ public abstract class SymbolTooltipPanel extends Panel {
ResourceReference ajaxIndicator = new PackageResourceReference(
SymbolTooltipPanel.class, "ajax-indicator.gif");
String script = String.format("gitplex.symboltooltip.init('%s', %s, '%s');",
- getMarkupId(), getCallbackFunction(explicit("revision"), explicit("symbol")),
+ getMarkupId(), getCallbackFunction(explicit("commit"), explicit("symbol")),
RequestCycle.get().urlFor(ajaxIndicator, new PageParameters()));
response.render(OnDomReadyHeaderItem.forScript(script));
}
@@ -238,7 +236,7 @@ public abstract class SymbolTooltipPanel extends Panel {
public PageParameters getQueryHitParams(QueryHit hit) {
HistoryState state = new HistoryState();
- state.blobIdent.revision = revision;
+ state.blobIdent.revision = commitId.name();
state.blobIdent.path = hit.getBlobPath();
state.mark = Mark.of(hit.getTokenPos());
state.requestId = PullRequest.idOf(requestModel.getObject());
@@ -247,7 +245,7 @@ public abstract class SymbolTooltipPanel extends Panel {
public PageParameters getFindOccurrencesParams() {
HistoryState state = new HistoryState();
- state.blobIdent.revision = revision;
+ state.blobIdent.revision = commitId.name();
state.blobIdent.path = getBlobPath();
state.requestId = PullRequest.idOf(requestModel.getObject());
state.query = symbol;
@@ -258,8 +256,8 @@ public abstract class SymbolTooltipPanel extends Panel {
return symbol;
}
- public String getRevision() {
- return revision;
+ public ObjectId getCommitId() {
+ return commitId;
}
@Override
diff --git a/gitplex.web/src/main/java/com/pmease/gitplex/web/component/symboltooltip/symbol-tooltip.js b/gitplex.web/src/main/java/com/pmease/gitplex/web/component/symboltooltip/symbol-tooltip.js
index 2221fe3abd..2c3af50928 100644
--- a/gitplex.web/src/main/java/com/pmease/gitplex/web/component/symboltooltip/symbol-tooltip.js
+++ b/gitplex.web/src/main/java/com/pmease/gitplex/web/component/symboltooltip/symbol-tooltip.js
@@ -28,7 +28,7 @@ gitplex.symboltooltip = {
}
};
- container.onMouseOverSymbol = function(revision, symbolEl) {
+ container.onMouseOverSymbol = function(commit, symbolEl) {
var $symbol = $(symbolEl);
if (gitplex.mouseState.pressed || !gitplex.mouseState.moved || $symbol.text() == "@")
return;
@@ -73,7 +73,7 @@ gitplex.symboltooltip = {
$tooltip.data("alignment", {placement: {x: 0, y:0, offset:2, targetX: 0, targetY: 100}, target: {element: symbolEl}});
$tooltip.align($tooltip.data("alignment"));
- queryCallback(revision, $symbol.text());
+ queryCallback(commit, $symbol.text());
showTimer = null;
}, 500);
diff --git a/gitplex.web/src/main/java/com/pmease/gitplex/web/page/depot/file/DepotFilePage.java b/gitplex.web/src/main/java/com/pmease/gitplex/web/page/depot/file/DepotFilePage.java
index b395b08cad..516b9cf7f2 100644
--- a/gitplex.web/src/main/java/com/pmease/gitplex/web/page/depot/file/DepotFilePage.java
+++ b/gitplex.web/src/main/java/com/pmease/gitplex/web/page/depot/file/DepotFilePage.java
@@ -796,22 +796,6 @@ public class DepotFilePage extends DepotPage implements BlobViewContext {
super.onDetach();
}
- public static class IndexedListener implements IndexListener {
-
- @Override
- public void commitIndexed(Depot depot, ObjectId commit) {
- CommitIndexed trait = new CommitIndexed();
- trait.depotId = depot.getId();
- trait.commitId = commit;
- WebSocketRenderBehavior.requestToRender(trait);
- }
-
- @Override
- public void indexRemoving(Depot depot) {
- }
-
- }
-
@Override
public BlobIdent getBlobIdent() {
return blobIdent;
@@ -961,6 +945,22 @@ public class DepotFilePage extends DepotPage implements BlobViewContext {
return new ArrayList<>();
}
+ public static class IndexedListener implements IndexListener {
+
+ @Override
+ public void commitIndexed(Depot depot, ObjectId commit) {
+ CommitIndexed trait = new CommitIndexed();
+ trait.depotId = depot.getId();
+ trait.commitId = commit;
+ WebSocketRenderBehavior.requestToRender(trait);
+ }
+
+ @Override
+ public void indexRemoving(Depot depot) {
+ }
+
+ }
+
public static class HistoryState implements Serializable {
private static final long serialVersionUID = 1L;