Skip to content

The Unified and Autonomous Development Platform

Refactor pull request checking

robin shine65050f20db4b
diff --git a/commons.git/pom.xml b/commons.git/pom.xml
index 8eabcb4f6d..69cbf6f97e 100644
--- a/commons.git/pom.xml
+++ b/commons.git/pom.xml
@@ -1,100 +1,100 @@
-<?xml version="1.0" encoding="UTF-8"?>
-
-<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
- xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
- <modelVersion>4.0.0</modelVersion>
- <artifactId>commons.git</artifactId>
- <version>1.0.0</version>
- <parent>
- <groupId>com.pmease</groupId>
- <artifactId>parent.general</artifactId>
- <version>1.0.31</version>
- </parent>
- <build>
- <plugins>
- <plugin>
- <groupId>com.pmease</groupId>
- <artifactId>plugin.maven</artifactId>
- </plugin>
- <!-- Uncomment below if you'd like to publish an archetype based on your
- plugin -->
- <!--plugin> <artifactId>maven-archetype-plugin</artifactId> </plugin -->
- <plugin>
- <artifactId>maven-jar-plugin</artifactId>
- <executions>
- <execution>
- <goals>
- <goal>test-jar</goal>
- </goals>
- </execution>
- </executions>
- </plugin>
- <plugin>
- <artifactId>maven-source-plugin</artifactId>
- </plugin>
- <plugin>
- <artifactId>maven-javadoc-plugin</artifactId>
- </plugin>
- </plugins>
- </build>
- <dependencies>
- <dependency>
- <groupId>com.pmease</groupId>
- <artifactId>commons.loader</artifactId>
- <version>1.0.31</version>
- </dependency>
- <dependency>
- <groupId>org.eclipse.jgit</groupId>
- <artifactId>org.eclipse.jgit.http.server</artifactId>
- <version>${jgitVersion}</version>
- </dependency>
- <dependency>
- <groupId>org.eclipse.jgit</groupId>
- <artifactId>org.eclipse.jgit.archive</artifactId>
- <version>${jgitVersion}</version>
- </dependency>
- <dependency>
- <groupId>com.pmease</groupId>
- <artifactId>commons.util</artifactId>
- <version>1.0.31</version>
- </dependency>
- <dependency>
- <groupId>com.pmease</groupId>
- <artifactId>commons.loader</artifactId>
- <version>1.0.31</version>
- <type>test-jar</type>
- <scope>test</scope>
- </dependency>
- <dependency>
- <groupId>com.pmease</groupId>
- <artifactId>commons.wicket</artifactId>
- <version>1.0.29</version>
- </dependency>
- <dependency>
- <groupId>com.pmease</groupId>
- <artifactId>commons.lang</artifactId>
- <version>1.0.0</version>
- </dependency>
- </dependencies>
- <repositories>
- <repository>
- <id>pmeaseRepo</id>
- <name>PMEase Repository</name>
- <releases>
- <enabled>true</enabled>
- <updatePolicy>never</updatePolicy>
- <checksumPolicy>fail</checksumPolicy>
- </releases>
- <snapshots>
- <enabled>true</enabled>
- <updatePolicy>always</updatePolicy>
- <checksumPolicy>fail</checksumPolicy>
- </snapshots>
- <url>http://artifact.pmease.com/</url>
- </repository>
- </repositories>
- <properties>
- <jgitVersion>4.3.0.201604071810-r</jgitVersion>
- <moduleClass>com.pmease.commons.git.GitModule</moduleClass>
- </properties>
-</project>
+<?xml version="1.0" encoding="UTF-8"?>
+
+<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
+ xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
+ <modelVersion>4.0.0</modelVersion>
+ <artifactId>commons.git</artifactId>
+ <version>1.0.0</version>
+ <parent>
+ <groupId>com.pmease</groupId>
+ <artifactId>parent.general</artifactId>
+ <version>1.0.31</version>
+ </parent>
+ <build>
+ <plugins>
+ <plugin>
+ <groupId>com.pmease</groupId>
+ <artifactId>plugin.maven</artifactId>
+ </plugin>
+ <!-- Uncomment below if you'd like to publish an archetype based on your
+ plugin -->
+ <!--plugin> <artifactId>maven-archetype-plugin</artifactId> </plugin -->
+ <plugin>
+ <artifactId>maven-jar-plugin</artifactId>
+ <executions>
+ <execution>
+ <goals>
+ <goal>test-jar</goal>
+ </goals>
+ </execution>
+ </executions>
+ </plugin>
+ <plugin>
+ <artifactId>maven-source-plugin</artifactId>
+ </plugin>
+ <plugin>
+ <artifactId>maven-javadoc-plugin</artifactId>
+ </plugin>
+ </plugins>
+ </build>
+ <dependencies>
+ <dependency>
+ <groupId>com.pmease</groupId>
+ <artifactId>commons.loader</artifactId>
+ <version>1.0.31</version>
+ </dependency>
+ <dependency>
+ <groupId>org.eclipse.jgit</groupId>
+ <artifactId>org.eclipse.jgit.http.server</artifactId>
+ <version>${jgitVersion}</version>
+ </dependency>
+ <dependency>
+ <groupId>org.eclipse.jgit</groupId>
+ <artifactId>org.eclipse.jgit.archive</artifactId>
+ <version>${jgitVersion}</version>
+ </dependency>
+ <dependency>
+ <groupId>com.pmease</groupId>
+ <artifactId>commons.util</artifactId>
+ <version>1.0.31</version>
+ </dependency>
+ <dependency>
+ <groupId>com.pmease</groupId>
+ <artifactId>commons.loader</artifactId>
+ <version>1.0.31</version>
+ <type>test-jar</type>
+ <scope>test</scope>
+ </dependency>
+ <dependency>
+ <groupId>com.pmease</groupId>
+ <artifactId>commons.wicket</artifactId>
+ <version>1.0.29</version>
+ </dependency>
+ <dependency>
+ <groupId>com.pmease</groupId>
+ <artifactId>commons.lang</artifactId>
+ <version>1.0.0</version>
+ </dependency>
+ </dependencies>
+ <repositories>
+ <repository>
+ <id>pmeaseRepo</id>
+ <name>PMEase Repository</name>
+ <releases>
+ <enabled>true</enabled>
+ <updatePolicy>never</updatePolicy>
+ <checksumPolicy>fail</checksumPolicy>
+ </releases>
+ <snapshots>
+ <enabled>true</enabled>
+ <updatePolicy>always</updatePolicy>
+ <checksumPolicy>fail</checksumPolicy>
+ </snapshots>
+ <url>http://artifact.pmease.com/</url>
+ </repository>
+ </repositories>
+ <properties>
+ <jgitVersion>4.4.1.201607150455-r</jgitVersion>
+ <moduleClass>com.pmease.commons.git.GitModule</moduleClass>
+ </properties>
+</project>
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 0d79baa4c5..dbfa869fde 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
@@ -340,7 +340,7 @@ public class GitUtils {
}
}
inserter.flush();
- return headCommit;
+ return headCommit.copy();
} catch (IOException e) {
throw new RuntimeException(e);
}
diff --git a/commons.git/src/main/java/org/eclipse/jgit/revwalk/RevCommit.java b/commons.git/src/main/java/org/eclipse/jgit/revwalk/RevCommit.java
index c23e4e3288..e67ada6022 100644
--- a/commons.git/src/main/java/org/eclipse/jgit/revwalk/RevCommit.java
+++ b/commons.git/src/main/java/org/eclipse/jgit/revwalk/RevCommit.java
@@ -44,12 +44,17 @@
package org.eclipse.jgit.revwalk;
+import static java.nio.charset.StandardCharsets.UTF_8;
+
import java.io.IOException;
import java.nio.charset.Charset;
+import java.nio.charset.IllegalCharsetNameException;
+import java.nio.charset.UnsupportedCharsetException;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
+import org.eclipse.jgit.annotations.Nullable;
import org.eclipse.jgit.errors.IncorrectObjectTypeException;
import org.eclipse.jgit.errors.MissingObjectException;
import org.eclipse.jgit.lib.AnyObjectId;
@@ -441,12 +446,12 @@ public class RevCommit extends RevObject {
* @return decoded commit message as a string. Never null.
*/
public final String getFullMessage() {
- final byte[] raw = buffer;
- final int msgB = RawParseUtils.commitMessage(raw, 0);
- if (msgB < 0)
+ byte[] raw = buffer;
+ int msgB = RawParseUtils.commitMessage(raw, 0);
+ if (msgB < 0) {
return ""; //$NON-NLS-1$
- final Charset enc = RawParseUtils.parseEncoding(raw);
- return RawParseUtils.decode(enc, raw, msgB, raw.length);
+ }
+ return RawParseUtils.decode(guessEncoding(), raw, msgB, raw.length);
}
/**
@@ -465,16 +470,17 @@ public class RevCommit extends RevObject {
* spanned multiple lines. Embedded LFs are converted to spaces.
*/
public final String getShortMessage() {
- final byte[] raw = buffer;
- final int msgB = RawParseUtils.commitMessage(raw, 0);
- if (msgB < 0)
+ byte[] raw = buffer;
+ int msgB = RawParseUtils.commitMessage(raw, 0);
+ if (msgB < 0) {
return ""; //$NON-NLS-1$
+ }
- final Charset enc = RawParseUtils.parseEncoding(raw);
- final int msgE = RawParseUtils.endOfParagraph(raw, msgB);
- String str = RawParseUtils.decode(enc, raw, msgB, msgE);
- if (hasLF(raw, msgB, msgE))
+ int msgE = RawParseUtils.endOfParagraph(raw, msgB);
+ String str = RawParseUtils.decode(guessEncoding(), raw, msgB, msgE);
+ if (hasLF(raw, msgB, msgE)) {
str = StringUtils.replaceLineBreaksWithSpace(str);
+ }
return str;
}
@@ -485,6 +491,23 @@ public class RevCommit extends RevObject {
return false;
}
+ /**
+ * Determine the encoding of the commit message buffer.
+ * <p>
+ * Locates the "encoding" header (if present) and returns its value. Due to
+ * corruption in the wild this may be an invalid encoding name that is not
+ * recognized by any character encoding library.
+ * <p>
+ * If no encoding header is present, null.
+ *
+ * @return the preferred encoding of {@link #getRawBuffer()}; or null.
+ * @since 4.2
+ */
+ @Nullable
+ public final String getEncodingName() {
+ return RawParseUtils.parseEncodingName(buffer);
+ }
+
/**
* Determine the encoding of the commit message buffer.
* <p>
@@ -492,14 +515,28 @@ public class RevCommit extends RevObject {
* character set to apply to this buffer to evaluate its contents as
* character data.
* <p>
- * If no encoding header is present, {@link Constants#CHARSET} is assumed.
+ * If no encoding header is present {@code UTF-8} is assumed.
*
* @return the preferred encoding of {@link #getRawBuffer()}.
+ * @throws IllegalCharsetNameException
+ * if the character set requested by the encoding header is
+ * malformed and unsupportable.
+ * @throws UnsupportedCharsetException
+ * if the JRE does not support the character set requested by
+ * the encoding header.
*/
public final Charset getEncoding() {
return RawParseUtils.parseEncoding(buffer);
}
+ private Charset guessEncoding() {
+ try {
+ return getEncoding();
+ } catch (IllegalCharsetNameException | UnsupportedCharsetException e) {
+ return UTF_8;
+ }
+ }
+
/**
* Parse the footer lines (e.g. "Signed-off-by") for machine processing.
* <p>
@@ -529,7 +566,7 @@ public class RevCommit extends RevObject {
final int msgB = RawParseUtils.commitMessage(raw, 0);
final ArrayList<FooterLine> r = new ArrayList<FooterLine>(4);
- final Charset enc = getEncoding();
+ final Charset enc = guessEncoding();
for (;;) {
ptr = RawParseUtils.prevLF(raw, ptr);
if (ptr <= msgB)
diff --git a/commons.git/src/main/java/org/eclipse/jgit/revwalk/RevTag.java b/commons.git/src/main/java/org/eclipse/jgit/revwalk/RevTag.java
index bf2785e0d7..81a54bf7ea 100644
--- a/commons.git/src/main/java/org/eclipse/jgit/revwalk/RevTag.java
+++ b/commons.git/src/main/java/org/eclipse/jgit/revwalk/RevTag.java
@@ -45,8 +45,12 @@
package org.eclipse.jgit.revwalk;
+import static java.nio.charset.StandardCharsets.UTF_8;
+
import java.io.IOException;
import java.nio.charset.Charset;
+import java.nio.charset.IllegalCharsetNameException;
+import java.nio.charset.UnsupportedCharsetException;
import org.eclipse.jgit.errors.CorruptObjectException;
import org.eclipse.jgit.errors.IncorrectObjectTypeException;
@@ -162,7 +166,7 @@ public class RevTag extends RevObject {
int p = pos.value += 4; // "tag "
final int nameEnd = RawParseUtils.nextLF(rawTag, p) - 1;
- tagName = RawParseUtils.decode(Constants.CHARSET, rawTag, p, nameEnd);
+ tagName = RawParseUtils.decode(UTF_8, rawTag, p, nameEnd);
if (walk.isRetainBody())
buffer = rawTag;
@@ -207,12 +211,12 @@ public class RevTag extends RevObject {
* @return decoded tag message as a string. Never null.
*/
public final String getFullMessage() {
- final byte[] raw = buffer;
- final int msgB = RawParseUtils.tagMessage(raw, 0);
- if (msgB < 0)
+ byte[] raw = buffer;
+ int msgB = RawParseUtils.tagMessage(raw, 0);
+ if (msgB < 0) {
return ""; //$NON-NLS-1$
- final Charset enc = RawParseUtils.parseEncoding(raw);
- return RawParseUtils.decode(enc, raw, msgB, raw.length);
+ }
+ return RawParseUtils.decode(guessEncoding(), raw, msgB, raw.length);
}
/**
@@ -231,19 +235,28 @@ public class RevTag extends RevObject {
* multiple lines. Embedded LFs are converted to spaces.
*/
public final String getShortMessage() {
- final byte[] raw = buffer;
- final int msgB = RawParseUtils.tagMessage(raw, 0);
- if (msgB < 0)
+ byte[] raw = buffer;
+ int msgB = RawParseUtils.tagMessage(raw, 0);
+ if (msgB < 0) {
return ""; //$NON-NLS-1$
+ }
- final Charset enc = RawParseUtils.parseEncoding(raw);
- final int msgE = RawParseUtils.endOfParagraph(raw, msgB);
- String str = RawParseUtils.decode(enc, raw, msgB, msgE);
- if (RevCommit.hasLF(raw, msgB, msgE))
+ int msgE = RawParseUtils.endOfParagraph(raw, msgB);
+ String str = RawParseUtils.decode(guessEncoding(), raw, msgB, msgE);
+ if (RevCommit.hasLF(raw, msgB, msgE)) {
str = StringUtils.replaceLineBreaksWithSpace(str);
+ }
return str;
}
+ private Charset guessEncoding() {
+ try {
+ return RawParseUtils.parseEncoding(buffer);
+ } catch (IllegalCharsetNameException | UnsupportedCharsetException e) {
+ return UTF_8;
+ }
+ }
+
/**
* Get a reference to the object this tag was placed on.
* <p>
diff --git a/commons.git/src/main/java/org/eclipse/jgit/revwalk/RevWalk.java b/commons.git/src/main/java/org/eclipse/jgit/revwalk/RevWalk.java
index 1176d958b0..c8504937a7 100644
--- a/commons.git/src/main/java/org/eclipse/jgit/revwalk/RevWalk.java
+++ b/commons.git/src/main/java/org/eclipse/jgit/revwalk/RevWalk.java
@@ -1295,7 +1295,6 @@ public class RevWalk implements Iterable<RevCommit>, AutoCloseable {
retainOnReset = 0;
carryFlags = UNINTERESTING;
objects.clear();
- reader.close();
roots.clear();
queue = new DateRevQueue();
pending = new StartGenerator(this);
diff --git a/commons.git/src/main/java/org/eclipse/jgit/revwalk/filter/AndRevFilter.java b/commons.git/src/main/java/org/eclipse/jgit/revwalk/filter/AndRevFilter.java
new file mode 100644
index 0000000000..4a91493dc0
--- /dev/null
+++ b/commons.git/src/main/java/org/eclipse/jgit/revwalk/filter/AndRevFilter.java
@@ -0,0 +1,208 @@
+/*
+ * Copyright (C) 2007, Robin Rosenberg <[email protected]>
+ * Copyright (C) 2008, Shawn O. Pearce <[email protected]>
+ * and other copyright owners as documented in the project's IP log.
+ *
+ * This program and the accompanying materials are made available
+ * under the terms of the Eclipse Distribution License v1.0 which
+ * accompanies this distribution, is reproduced below, and is
+ * available at http://www.eclipse.org/org/documents/edl-v10.php
+ *
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or
+ * without modification, are permitted provided that the following
+ * conditions are met:
+ *
+ * - Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ *
+ * - Redistributions in binary form must reproduce the above
+ * copyright notice, this list of conditions and the following
+ * disclaimer in the documentation and/or other materials provided
+ * with the distribution.
+ *
+ * - Neither the name of the Eclipse Foundation, Inc. nor the
+ * names of its contributors may be used to endorse or promote
+ * products derived from this software without specific prior
+ * written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND
+ * CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES,
+ * INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
+ * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+ * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
+ * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
+ * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
+ * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
+ * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
+ * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
+ * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
+ * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
+ * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+ */
+
+package org.eclipse.jgit.revwalk.filter;
+
+import java.io.IOException;
+import java.util.Collection;
+
+import org.eclipse.jgit.errors.IncorrectObjectTypeException;
+import org.eclipse.jgit.errors.MissingObjectException;
+import org.eclipse.jgit.internal.JGitText;
+import org.eclipse.jgit.revwalk.RevCommit;
+import org.eclipse.jgit.revwalk.RevWalk;
+
+/**
+ * Includes a commit only if all subfilters include the same commit.
+ * <p>
+ * Classic shortcut behavior is used, so evaluation of the
+ * {@link RevFilter#include(RevWalk, RevCommit)} method stops as soon as a false
+ * result is obtained. Applications can improve filtering performance by placing
+ * faster filters that are more likely to reject a result earlier in the list.
+ */
+public abstract class AndRevFilter extends RevFilter {
+ /**
+ * Create a filter with two filters, both of which must match.
+ *
+ * @param a
+ * first filter to test.
+ * @param b
+ * second filter to test.
+ * @return a filter that must match both input filters.
+ */
+ public static RevFilter create(final RevFilter a, final RevFilter b) {
+ if (a == ALL)
+ return b;
+ if (b == ALL)
+ return a;
+ return new Binary(a, b);
+ }
+
+ /**
+ * Create a filter around many filters, all of which must match.
+ *
+ * @param list
+ * list of filters to match against. Must contain at least 2
+ * filters.
+ * @return a filter that must match all input filters.
+ */
+ public static RevFilter create(final RevFilter[] list) {
+ if (list.length == 2)
+ return create(list[0], list[1]);
+ if (list.length < 2)
+ throw new IllegalArgumentException(JGitText.get().atLeastTwoFiltersNeeded);
+ final RevFilter[] subfilters = new RevFilter[list.length];
+ System.arraycopy(list, 0, subfilters, 0, list.length);
+ return new List(subfilters);
+ }
+
+ /**
+ * Create a filter around many filters, all of which must match.
+ *
+ * @param list
+ * list of filters to match against. Must contain at least 2
+ * filters.
+ * @return a filter that must match all input filters.
+ */
+ public static RevFilter create(final Collection<RevFilter> list) {
+ if (list.size() < 2)
+ throw new IllegalArgumentException(JGitText.get().atLeastTwoFiltersNeeded);
+ final RevFilter[] subfilters = new RevFilter[list.size()];
+ list.toArray(subfilters);
+ if (subfilters.length == 2)
+ return create(subfilters[0], subfilters[1]);
+ return new List(subfilters);
+ }
+
+ private static class Binary extends AndRevFilter {
+ private final RevFilter a;
+
+ private final RevFilter b;
+
+ private final boolean requiresCommitBody;
+
+ Binary(final RevFilter one, final RevFilter two) {
+ a = one;
+ b = two;
+ requiresCommitBody = a.requiresCommitBody()
+ || b.requiresCommitBody();
+ }
+
+ @Override
+ public boolean include(final RevWalk walker, final RevCommit c)
+ throws MissingObjectException, IncorrectObjectTypeException,
+ IOException {
+ return a.include(walker, c) && b.include(walker, c);
+ }
+
+ @Override
+ public boolean requiresCommitBody() {
+ return requiresCommitBody;
+ }
+
+ @Override
+ public RevFilter clone() {
+ return new Binary(a.clone(), b.clone());
+ }
+
+ @SuppressWarnings("nls")
+ @Override
+ public String toString() {
+ return "(" + a.toString() + " AND " + b.toString() + ")"; //$NON-NLS-1$
+ }
+ }
+
+ private static class List extends AndRevFilter {
+ private final RevFilter[] subfilters;
+
+ private final boolean requiresCommitBody;
+
+ List(final RevFilter[] list) {
+ subfilters = list;
+
+ boolean rcb = false;
+ for (RevFilter filter : subfilters)
+ rcb |= filter.requiresCommitBody();
+ requiresCommitBody = rcb;
+ }
+
+ @Override
+ public boolean include(final RevWalk walker, final RevCommit c)
+ throws MissingObjectException, IncorrectObjectTypeException,
+ IOException {
+ for (final RevFilter f : subfilters) {
+ if (!f.include(walker, c))
+ return false;
+ }
+ return true;
+ }
+
+ @Override
+ public boolean requiresCommitBody() {
+ return requiresCommitBody;
+ }
+
+ @Override
+ public RevFilter clone() {
+ final RevFilter[] s = new RevFilter[subfilters.length];
+ for (int i = 0; i < s.length; i++)
+ s[i] = subfilters[i].clone();
+ return new List(s);
+ }
+
+ @SuppressWarnings("nls")
+ @Override
+ public String toString() {
+ final StringBuilder r = new StringBuilder();
+ r.append("(");
+ for (int i = 0; i < subfilters.length; i++) {
+ if (i > 0)
+ r.append(" AND ");
+ r.append(subfilters[i].toString());
+ }
+ r.append(")");
+ return r.toString();
+ }
+ }
+}
diff --git a/commons.git/src/main/java/org/eclipse/jgit/revwalk/filter/AuthorRevFilter.java b/commons.git/src/main/java/org/eclipse/jgit/revwalk/filter/AuthorRevFilter.java
new file mode 100644
index 0000000000..ef0064b238
--- /dev/null
+++ b/commons.git/src/main/java/org/eclipse/jgit/revwalk/filter/AuthorRevFilter.java
@@ -0,0 +1,117 @@
+/*
+ * Copyright (C) 2008, Shawn O. Pearce <[email protected]>
+ * and other copyright owners as documented in the project's IP log.
+ *
+ * This program and the accompanying materials are made available
+ * under the terms of the Eclipse Distribution License v1.0 which
+ * accompanies this distribution, is reproduced below, and is
+ * available at http://www.eclipse.org/org/documents/edl-v10.php
+ *
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or
+ * without modification, are permitted provided that the following
+ * conditions are met:
+ *
+ * - Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ *
+ * - Redistributions in binary form must reproduce the above
+ * copyright notice, this list of conditions and the following
+ * disclaimer in the documentation and/or other materials provided
+ * with the distribution.
+ *
+ * - Neither the name of the Eclipse Foundation, Inc. nor the
+ * names of its contributors may be used to endorse or promote
+ * products derived from this software without specific prior
+ * written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND
+ * CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES,
+ * INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
+ * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+ * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
+ * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
+ * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
+ * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
+ * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
+ * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
+ * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
+ * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
+ * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+ */
+
+package org.eclipse.jgit.revwalk.filter;
+
+import java.util.regex.Pattern;
+
+import org.eclipse.jgit.internal.JGitText;
+import org.eclipse.jgit.revwalk.RevCommit;
+import org.eclipse.jgit.util.RawCharSequence;
+import org.eclipse.jgit.util.RawParseUtils;
+
+/** Matches only commits whose author name matches the pattern. */
+public class AuthorRevFilter {
+ /**
+ * Create a new author filter.
+ * <p>
+ * An optimized substring search may be automatically selected if the
+ * pattern does not contain any regular expression meta-characters.
+ * <p>
+ * The search is performed using a case-insensitive comparison. The
+ * character encoding of the commit message itself is not respected. The
+ * filter matches on raw UTF-8 byte sequences.
+ *
+ * @param pattern
+ * regular expression pattern to match.
+ * @return a new filter that matches the given expression against the author
+ * name and address of a commit.
+ */
+ public static RevFilter create(String pattern) {
+ if (pattern.length() == 0)
+ throw new IllegalArgumentException(JGitText.get().cannotMatchOnEmptyString);
+ if (SubStringRevFilter.safe(pattern))
+ return new SubStringSearch(pattern);
+ return new PatternSearch(pattern);
+ }
+
+ private AuthorRevFilter() {
+ // Don't permit us to be created.
+ }
+
+ static RawCharSequence textFor(final RevCommit cmit) {
+ final byte[] raw = cmit.getRawBuffer();
+ final int b = RawParseUtils.author(raw, 0);
+ if (b < 0)
+ return RawCharSequence.EMPTY;
+ final int e = RawParseUtils.nextLF(raw, b, '>');
+ return new RawCharSequence(raw, b, e);
+ }
+
+ private static class PatternSearch extends PatternMatchRevFilter {
+ PatternSearch(final String patternText) {
+ super(patternText, true, true, Pattern.CASE_INSENSITIVE);
+ }
+
+ @Override
+ protected CharSequence text(final RevCommit cmit) {
+ return textFor(cmit);
+ }
+
+ @Override
+ public RevFilter clone() {
+ return new PatternSearch(pattern());
+ }
+ }
+
+ private static class SubStringSearch extends SubStringRevFilter {
+ SubStringSearch(final String patternText) {
+ super(patternText);
+ }
+
+ @Override
+ protected RawCharSequence text(final RevCommit cmit) {
+ return textFor(cmit);
+ }
+ }
+}
diff --git a/commons.git/src/main/java/org/eclipse/jgit/revwalk/filter/CommitTimeRevFilter.java b/commons.git/src/main/java/org/eclipse/jgit/revwalk/filter/CommitTimeRevFilter.java
new file mode 100644
index 0000000000..5bf9366ded
--- /dev/null
+++ b/commons.git/src/main/java/org/eclipse/jgit/revwalk/filter/CommitTimeRevFilter.java
@@ -0,0 +1,210 @@
+/*
+ * Copyright (C) 2009, Mark Struberg <[email protected]>
+ * Copyright (C) 2008, Shawn O. Pearce <[email protected]>
+ * and other copyright owners as documented in the project's IP log.
+ *
+ * This program and the accompanying materials are made available
+ * under the terms of the Eclipse Distribution License v1.0 which
+ * accompanies this distribution, is reproduced below, and is
+ * available at http://www.eclipse.org/org/documents/edl-v10.php
+ *
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or
+ * without modification, are permitted provided that the following
+ * conditions are met:
+ *
+ * - Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ *
+ * - Redistributions in binary form must reproduce the above
+ * copyright notice, this list of conditions and the following
+ * disclaimer in the documentation and/or other materials provided
+ * with the distribution.
+ *
+ * - Neither the name of the Eclipse Foundation, Inc. nor the
+ * names of its contributors may be used to endorse or promote
+ * products derived from this software without specific prior
+ * written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND
+ * CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES,
+ * INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
+ * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+ * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
+ * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
+ * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
+ * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
+ * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
+ * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
+ * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
+ * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
+ * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+ */
+
+package org.eclipse.jgit.revwalk.filter;
+
+import java.io.IOException;
+import java.util.Date;
+
+import org.eclipse.jgit.errors.IncorrectObjectTypeException;
+import org.eclipse.jgit.errors.MissingObjectException;
+import org.eclipse.jgit.errors.StopWalkException;
+import org.eclipse.jgit.revwalk.RevCommit;
+import org.eclipse.jgit.revwalk.RevWalk;
+
+/** Selects commits based upon the commit time field. */
+public abstract class CommitTimeRevFilter extends RevFilter {
+ /**
+ * Create a new filter to select commits before a given date/time.
+ *
+ * @param ts
+ * the point in time to cut on.
+ * @return a new filter to select commits on or before <code>ts</code>.
+ */
+ public static final RevFilter before(final Date ts) {
+ return before(ts.getTime());
+ }
+
+ /**
+ * Create a new filter to select commits before a given date/time.
+ *
+ * @param ts
+ * the point in time to cut on, in milliseconds
+ * @return a new filter to select commits on or before <code>ts</code>.
+ */
+ public static final RevFilter before(final long ts) {
+ return new Before(ts);
+ }
+
+ /**
+ * Create a new filter to select commits after a given date/time.
+ *
+ * @param ts
+ * the point in time to cut on.
+ * @return a new filter to select commits on or after <code>ts</code>.
+ */
+ public static final RevFilter after(final Date ts) {
+ return after(ts.getTime());
+ }
+
+ /**
+ * Create a new filter to select commits after a given date/time.
+ *
+ * @param ts
+ * the point in time to cut on, in milliseconds.
+ * @return a new filter to select commits on or after <code>ts</code>.
+ */
+ public static final RevFilter after(final long ts) {
+ return new After(ts);
+ }
+
+ /**
+ * Create a new filter to select commits after or equal a given date/time <code>since</code>
+ * and before or equal a given date/time <code>until</code>.
+ *
+ * @param since the point in time to cut on.
+ * @param until the point in time to cut off.
+ * @return a new filter to select commits between the given date/times.
+ */
+ public static final RevFilter between(final Date since, final Date until) {
+ return between(since.getTime(), until.getTime());
+ }
+
+ /**
+ * Create a new filter to select commits after or equal a given date/time <code>since</code>
+ * and before or equal a given date/time <code>until</code>.
+ *
+ * @param since the point in time to cut on, in milliseconds.
+ * @param until the point in time to cut off, in millisconds.
+ * @return a new filter to select commits between the given date/times.
+ */
+ public static final RevFilter between(final long since, final long until) {
+ return new Between(since, until);
+ }
+
+ final int when;
+
+ CommitTimeRevFilter(final long ts) {
+ when = (int) (ts / 1000);
+ }
+
+ @Override
+ public RevFilter clone() {
+ return this;
+ }
+
+ @Override
+ public boolean requiresCommitBody() {
+ return false;
+ }
+
+ private static class Before extends CommitTimeRevFilter {
+ Before(final long ts) {
+ super(ts);
+ }
+
+ @Override
+ public boolean include(final RevWalk walker, final RevCommit cmit)
+ throws StopWalkException, MissingObjectException,
+ IncorrectObjectTypeException, IOException {
+ return cmit.getCommitTime() <= when;
+ }
+
+ @SuppressWarnings("nls")
+ @Override
+ public String toString() {
+ return super.toString() + "(" + new Date(when * 1000L) + ")";
+ }
+ }
+
+ private static class After extends CommitTimeRevFilter {
+ After(final long ts) {
+ super(ts);
+ }
+
+ @Override
+ public boolean include(final RevWalk walker, final RevCommit cmit)
+ throws StopWalkException, MissingObjectException,
+ IncorrectObjectTypeException, IOException {
+ // Since the walker sorts commits by commit time we can be
+ // reasonably certain there is nothing remaining worth our
+ // scanning if this commit is before the point in question.
+ //
+ if (cmit.getCommitTime() < when)
+ throw StopWalkException.INSTANCE;
+ return true;
+ }
+
+ @SuppressWarnings("nls")
+ @Override
+ public String toString() {
+ return super.toString() + "(" + new Date(when * 1000L) + ")";
+ }
+ }
+
+ private static class Between extends CommitTimeRevFilter {
+ private final int until;
+
+ Between(final long since, final long until) {
+ super(since);
+ this.until = (int) (until / 1000);
+ }
+
+ @Override
+ public boolean include(final RevWalk walker, final RevCommit cmit)
+ throws StopWalkException, MissingObjectException,
+ IncorrectObjectTypeException, IOException {
+ return cmit.getCommitTime() <= until && cmit.getCommitTime() >= when;
+ }
+
+ @SuppressWarnings("nls")
+ @Override
+ public String toString() {
+ return super.toString() + "(" + new Date(when * 1000L) + " - "
+ + new Date(until * 1000L) + ")";
+ }
+
+ }
+
+}
diff --git a/commons.git/src/main/java/org/eclipse/jgit/revwalk/filter/CommitterRevFilter.java b/commons.git/src/main/java/org/eclipse/jgit/revwalk/filter/CommitterRevFilter.java
new file mode 100644
index 0000000000..eedfef215c
--- /dev/null
+++ b/commons.git/src/main/java/org/eclipse/jgit/revwalk/filter/CommitterRevFilter.java
@@ -0,0 +1,117 @@
+/*
+ * Copyright (C) 2008, Shawn O. Pearce <[email protected]>
+ * and other copyright owners as documented in the project's IP log.
+ *
+ * This program and the accompanying materials are made available
+ * under the terms of the Eclipse Distribution License v1.0 which
+ * accompanies this distribution, is reproduced below, and is
+ * available at http://www.eclipse.org/org/documents/edl-v10.php
+ *
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or
+ * without modification, are permitted provided that the following
+ * conditions are met:
+ *
+ * - Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ *
+ * - Redistributions in binary form must reproduce the above
+ * copyright notice, this list of conditions and the following
+ * disclaimer in the documentation and/or other materials provided
+ * with the distribution.
+ *
+ * - Neither the name of the Eclipse Foundation, Inc. nor the
+ * names of its contributors may be used to endorse or promote
+ * products derived from this software without specific prior
+ * written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND
+ * CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES,
+ * INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
+ * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+ * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
+ * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
+ * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
+ * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
+ * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
+ * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
+ * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
+ * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
+ * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+ */
+
+package org.eclipse.jgit.revwalk.filter;
+
+import java.util.regex.Pattern;
+
+import org.eclipse.jgit.internal.JGitText;
+import org.eclipse.jgit.revwalk.RevCommit;
+import org.eclipse.jgit.util.RawCharSequence;
+import org.eclipse.jgit.util.RawParseUtils;
+
+/** Matches only commits whose committer name matches the pattern. */
+public class CommitterRevFilter {
+ /**
+ * Create a new committer filter.
+ * <p>
+ * An optimized substring search may be automatically selected if the
+ * pattern does not contain any regular expression meta-characters.
+ * <p>
+ * The search is performed using a case-insensitive comparison. The
+ * character encoding of the commit message itself is not respected. The
+ * filter matches on raw UTF-8 byte sequences.
+ *
+ * @param pattern
+ * regular expression pattern to match.
+ * @return a new filter that matches the given expression against the author
+ * name and address of a commit.
+ */
+ public static RevFilter create(String pattern) {
+ if (pattern.length() == 0)
+ throw new IllegalArgumentException(JGitText.get().cannotMatchOnEmptyString);
+ if (SubStringRevFilter.safe(pattern))
+ return new SubStringSearch(pattern);
+ return new PatternSearch(pattern);
+ }
+
+ private CommitterRevFilter() {
+ // Don't permit us to be created.
+ }
+
+ static RawCharSequence textFor(final RevCommit cmit) {
+ final byte[] raw = cmit.getRawBuffer();
+ final int b = RawParseUtils.committer(raw, 0);
+ if (b < 0)
+ return RawCharSequence.EMPTY;
+ final int e = RawParseUtils.nextLF(raw, b, '>');
+ return new RawCharSequence(raw, b, e);
+ }
+
+ private static class PatternSearch extends PatternMatchRevFilter {
+ PatternSearch(final String patternText) {
+ super(patternText, true, true, Pattern.CASE_INSENSITIVE);
+ }
+
+ @Override
+ protected CharSequence text(final RevCommit cmit) {
+ return textFor(cmit);
+ }
+
+ @Override
+ public RevFilter clone() {
+ return new PatternSearch(pattern());
+ }
+ }
+
+ private static class SubStringSearch extends SubStringRevFilter {
+ SubStringSearch(final String patternText) {
+ super(patternText);
+ }
+
+ @Override
+ protected RawCharSequence text(final RevCommit cmit) {
+ return textFor(cmit);
+ }
+ }
+}
diff --git a/commons.git/src/main/java/org/eclipse/jgit/revwalk/filter/MaxCountRevFilter.java b/commons.git/src/main/java/org/eclipse/jgit/revwalk/filter/MaxCountRevFilter.java
new file mode 100644
index 0000000000..38b0da5286
--- /dev/null
+++ b/commons.git/src/main/java/org/eclipse/jgit/revwalk/filter/MaxCountRevFilter.java
@@ -0,0 +1,96 @@
+/*
+ * Copyright (C) 2011, Tomasz Zarna <[email protected]>
+ * and other copyright owners as documented in the project's IP log.
+ *
+ * This program and the accompanying materials are made available
+ * under the terms of the Eclipse Distribution License v1.0 which
+ * accompanies this distribution, is reproduced below, and is
+ * available at http://www.eclipse.org/org/documents/edl-v10.php
+ *
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or
+ * without modification, are permitted provided that the following
+ * conditions are met:
+ *
+ * - Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ *
+ * - Redistributions in binary form must reproduce the above
+ * copyright notice, this list of conditions and the following
+ * disclaimer in the documentation and/or other materials provided
+ * with the distribution.
+ *
+ * - Neither the name of the Eclipse Foundation, Inc. nor the
+ * names of its contributors may be used to endorse or promote
+ * products derived from this software without specific prior
+ * written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND
+ * CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES,
+ * INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
+ * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+ * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
+ * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
+ * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
+ * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
+ * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
+ * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
+ * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
+ * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
+ * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+ */
+package org.eclipse.jgit.revwalk.filter;
+
+import java.io.IOException;
+
+import org.eclipse.jgit.errors.IncorrectObjectTypeException;
+import org.eclipse.jgit.errors.MissingObjectException;
+import org.eclipse.jgit.errors.StopWalkException;
+import org.eclipse.jgit.internal.JGitText;
+import org.eclipse.jgit.revwalk.RevCommit;
+import org.eclipse.jgit.revwalk.RevWalk;
+
+/**
+ * Limits the number of commits output.
+ */
+public class MaxCountRevFilter extends RevFilter {
+
+ private int maxCount;
+
+ private int count;
+
+ /**
+ * Create a new max count filter.
+ *
+ * @param maxCount
+ * the limit
+ * @return a new filter
+ */
+ public static RevFilter create(int maxCount) {
+ if (maxCount < 0)
+ throw new IllegalArgumentException(
+ JGitText.get().maxCountMustBeNonNegative);
+ return new MaxCountRevFilter(maxCount);
+ }
+
+ private MaxCountRevFilter(int maxCount) {
+ this.count = 0;
+ this.maxCount = maxCount;
+ }
+
+ @Override
+ public boolean include(RevWalk walker, RevCommit cmit)
+ throws StopWalkException, MissingObjectException,
+ IncorrectObjectTypeException, IOException {
+ count++;
+ if (count > maxCount)
+ throw StopWalkException.INSTANCE;
+ return true;
+ }
+
+ @Override
+ public RevFilter clone() {
+ return new MaxCountRevFilter(maxCount);
+ }
+}
diff --git a/commons.git/src/main/java/org/eclipse/jgit/revwalk/filter/MessageRevFilter.java b/commons.git/src/main/java/org/eclipse/jgit/revwalk/filter/MessageRevFilter.java
new file mode 100644
index 0000000000..a7cc5bdc10
--- /dev/null
+++ b/commons.git/src/main/java/org/eclipse/jgit/revwalk/filter/MessageRevFilter.java
@@ -0,0 +1,117 @@
+/*
+ * Copyright (C) 2008, Shawn O. Pearce <[email protected]>
+ * and other copyright owners as documented in the project's IP log.
+ *
+ * This program and the accompanying materials are made available
+ * under the terms of the Eclipse Distribution License v1.0 which
+ * accompanies this distribution, is reproduced below, and is
+ * available at http://www.eclipse.org/org/documents/edl-v10.php
+ *
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or
+ * without modification, are permitted provided that the following
+ * conditions are met:
+ *
+ * - Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ *
+ * - Redistributions in binary form must reproduce the above
+ * copyright notice, this list of conditions and the following
+ * disclaimer in the documentation and/or other materials provided
+ * with the distribution.
+ *
+ * - Neither the name of the Eclipse Foundation, Inc. nor the
+ * names of its contributors may be used to endorse or promote
+ * products derived from this software without specific prior
+ * written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND
+ * CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES,
+ * INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
+ * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+ * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
+ * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
+ * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
+ * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
+ * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
+ * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
+ * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
+ * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
+ * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+ */
+
+package org.eclipse.jgit.revwalk.filter;
+
+import java.util.regex.Pattern;
+
+import org.eclipse.jgit.internal.JGitText;
+import org.eclipse.jgit.revwalk.RevCommit;
+import org.eclipse.jgit.util.RawCharSequence;
+import org.eclipse.jgit.util.RawParseUtils;
+
+/** Matches only commits whose message matches the pattern. */
+public class MessageRevFilter {
+ /**
+ * Create a message filter.
+ * <p>
+ * An optimized substring search may be automatically selected if the
+ * pattern does not contain any regular expression meta-characters.
+ * <p>
+ * The search is performed using a case-insensitive comparison. The
+ * character encoding of the commit message itself is not respected. The
+ * filter matches on raw UTF-8 byte sequences.
+ *
+ * @param pattern
+ * regular expression pattern to match.
+ * @return a new filter that matches the given expression against the
+ * message body of the commit.
+ */
+ public static RevFilter create(String pattern) {
+ if (pattern.length() == 0)
+ throw new IllegalArgumentException(JGitText.get().cannotMatchOnEmptyString);
+ if (SubStringRevFilter.safe(pattern))
+ return new SubStringSearch(pattern);
+ return new PatternSearch(pattern);
+ }
+
+ private MessageRevFilter() {
+ // Don't permit us to be created.
+ }
+
+ static RawCharSequence textFor(final RevCommit cmit) {
+ final byte[] raw = cmit.getRawBuffer();
+ final int b = RawParseUtils.commitMessage(raw, 0);
+ if (b < 0)
+ return RawCharSequence.EMPTY;
+ return new RawCharSequence(raw, b, raw.length);
+ }
+
+ private static class PatternSearch extends PatternMatchRevFilter {
+ PatternSearch(final String patternText) {
+ super(patternText, true, true, Pattern.CASE_INSENSITIVE
+ | Pattern.DOTALL);
+ }
+
+ @Override
+ protected CharSequence text(final RevCommit cmit) {
+ return textFor(cmit);
+ }
+
+ @Override
+ public RevFilter clone() {
+ return new PatternSearch(pattern());
+ }
+ }
+
+ private static class SubStringSearch extends SubStringRevFilter {
+ SubStringSearch(final String patternText) {
+ super(patternText);
+ }
+
+ @Override
+ protected RawCharSequence text(final RevCommit cmit) {
+ return textFor(cmit);
+ }
+ }
+}
diff --git a/commons.git/src/main/java/org/eclipse/jgit/revwalk/filter/NotRevFilter.java b/commons.git/src/main/java/org/eclipse/jgit/revwalk/filter/NotRevFilter.java
new file mode 100644
index 0000000000..d3388021ba
--- /dev/null
+++ b/commons.git/src/main/java/org/eclipse/jgit/revwalk/filter/NotRevFilter.java
@@ -0,0 +1,98 @@
+/*
+ * Copyright (C) 2008, Shawn O. Pearce <[email protected]>
+ * and other copyright owners as documented in the project's IP log.
+ *
+ * This program and the accompanying materials are made available
+ * under the terms of the Eclipse Distribution License v1.0 which
+ * accompanies this distribution, is reproduced below, and is
+ * available at http://www.eclipse.org/org/documents/edl-v10.php
+ *
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or
+ * without modification, are permitted provided that the following
+ * conditions are met:
+ *
+ * - Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ *
+ * - Redistributions in binary form must reproduce the above
+ * copyright notice, this list of conditions and the following
+ * disclaimer in the documentation and/or other materials provided
+ * with the distribution.
+ *
+ * - Neither the name of the Eclipse Foundation, Inc. nor the
+ * names of its contributors may be used to endorse or promote
+ * products derived from this software without specific prior
+ * written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND
+ * CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES,
+ * INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
+ * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+ * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
+ * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
+ * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
+ * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
+ * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
+ * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
+ * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
+ * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
+ * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+ */
+
+package org.eclipse.jgit.revwalk.filter;
+
+import java.io.IOException;
+
+import org.eclipse.jgit.errors.IncorrectObjectTypeException;
+import org.eclipse.jgit.errors.MissingObjectException;
+import org.eclipse.jgit.revwalk.RevCommit;
+import org.eclipse.jgit.revwalk.RevWalk;
+
+/** Includes a commit only if the subfilter does not include the commit. */
+public class NotRevFilter extends RevFilter {
+ /**
+ * Create a filter that negates the result of another filter.
+ *
+ * @param a
+ * filter to negate.
+ * @return a filter that does the reverse of <code>a</code>.
+ */
+ public static RevFilter create(final RevFilter a) {
+ return new NotRevFilter(a);
+ }
+
+ private final RevFilter a;
+
+ private NotRevFilter(final RevFilter one) {
+ a = one;
+ }
+
+ @Override
+ public RevFilter negate() {
+ return a;
+ }
+
+ @Override
+ public boolean include(final RevWalk walker, final RevCommit c)
+ throws MissingObjectException, IncorrectObjectTypeException,
+ IOException {
+ return !a.include(walker, c);
+ }
+
+ @Override
+ public boolean requiresCommitBody() {
+ return a.requiresCommitBody();
+ }
+
+ @Override
+ public RevFilter clone() {
+ return new NotRevFilter(a.clone());
+ }
+
+ @Override
+ public String toString() {
+ return "NOT " + a.toString(); //$NON-NLS-1$
+ }
+}
diff --git a/commons.git/src/main/java/org/eclipse/jgit/revwalk/filter/ObjectFilter.java b/commons.git/src/main/java/org/eclipse/jgit/revwalk/filter/ObjectFilter.java
new file mode 100644
index 0000000000..2ad273d9ec
--- /dev/null
+++ b/commons.git/src/main/java/org/eclipse/jgit/revwalk/filter/ObjectFilter.java
@@ -0,0 +1,93 @@
+/**
+ * Copyright (C) 2015, Google Inc.
+ * and other copyright owners as documented in the project's IP log.
+ *
+ * This program and the accompanying materials are made available
+ * under the terms of the Eclipse Distribution License v1.0 which
+ * accompanies this distribution, is reproduced below, and is
+ * available at http://www.eclipse.org/org/documents/edl-v10.php
+ *
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or
+ * without modification, are permitted provided that the following
+ * conditions are met:
+ *
+ * - Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ *
+ * - Redistributions in binary form must reproduce the above
+ * copyright notice, this list of conditions and the following
+ * disclaimer in the documentation and/or other materials provided
+ * with the distribution.
+ *
+ * - Neither the name of the Eclipse Foundation, Inc. nor the
+ * names of its contributors may be used to endorse or promote
+ * products derived from this software without specific prior
+ * written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND
+ * CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES,
+ * INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
+ * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+ * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
+ * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
+ * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
+ * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
+ * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
+ * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
+ * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
+ * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
+ * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+ */
+
+package org.eclipse.jgit.revwalk.filter;
+
+import java.io.IOException;
+
+import org.eclipse.jgit.errors.IncorrectObjectTypeException;
+import org.eclipse.jgit.errors.MissingObjectException;
+import org.eclipse.jgit.lib.AnyObjectId;
+import org.eclipse.jgit.revwalk.ObjectWalk;
+
+/**
+ * Selects interesting objects when walking.
+ * <p>
+ * Applications should install the filter on an ObjectWalk by
+ * {@link ObjectWalk#setObjectFilter(ObjectFilter)} prior to starting traversal.
+ *
+ * @since 4.0
+ */
+public abstract class ObjectFilter {
+ /** Default filter that always returns true. */
+ public static final ObjectFilter ALL = new AllFilter();
+
+ private static final class AllFilter extends ObjectFilter {
+ @Override
+ public boolean include(ObjectWalk walker, AnyObjectId o) {
+ return true;
+ }
+ }
+
+ /**
+ * Determine if the named object should be included in the walk.
+ *
+ * @param walker
+ * the active walker this filter is being invoked from within.
+ * @param objid
+ * the object currently being tested.
+ * @return {@code true} if the named object should be included in the walk.
+ * @throws MissingObjectException
+ * an object the filter needed to consult to determine its
+ * answer was missing
+ * @throws IncorrectObjectTypeException
+ * an object the filter needed to consult to determine its
+ * answer was of the wrong type
+ * @throws IOException
+ * an object the filter needed to consult to determine its
+ * answer could not be read.
+ */
+ public abstract boolean include(ObjectWalk walker, AnyObjectId objid)
+ throws MissingObjectException, IncorrectObjectTypeException,
+ IOException;
+}
diff --git a/commons.git/src/main/java/org/eclipse/jgit/revwalk/filter/OrRevFilter.java b/commons.git/src/main/java/org/eclipse/jgit/revwalk/filter/OrRevFilter.java
new file mode 100644
index 0000000000..4c7b3bf47e
--- /dev/null
+++ b/commons.git/src/main/java/org/eclipse/jgit/revwalk/filter/OrRevFilter.java
@@ -0,0 +1,205 @@
+/*
+ * Copyright (C) 2007, Robin Rosenberg <[email protected]>
+ * Copyright (C) 2008, Shawn O. Pearce <[email protected]>
+ * and other copyright owners as documented in the project's IP log.
+ *
+ * This program and the accompanying materials are made available
+ * under the terms of the Eclipse Distribution License v1.0 which
+ * accompanies this distribution, is reproduced below, and is
+ * available at http://www.eclipse.org/org/documents/edl-v10.php
+ *
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or
+ * without modification, are permitted provided that the following
+ * conditions are met:
+ *
+ * - Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ *
+ * - Redistributions in binary form must reproduce the above
+ * copyright notice, this list of conditions and the following
+ * disclaimer in the documentation and/or other materials provided
+ * with the distribution.
+ *
+ * - Neither the name of the Eclipse Foundation, Inc. nor the
+ * names of its contributors may be used to endorse or promote
+ * products derived from this software without specific prior
+ * written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND
+ * CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES,
+ * INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
+ * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+ * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
+ * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
+ * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
+ * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
+ * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
+ * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
+ * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
+ * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
+ * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+ */
+
+package org.eclipse.jgit.revwalk.filter;
+
+import java.io.IOException;
+import java.util.Collection;
+
+import org.eclipse.jgit.errors.IncorrectObjectTypeException;
+import org.eclipse.jgit.errors.MissingObjectException;
+import org.eclipse.jgit.internal.JGitText;
+import org.eclipse.jgit.revwalk.RevCommit;
+import org.eclipse.jgit.revwalk.RevWalk;
+
+/**
+ * Includes a commit if any subfilters include the same commit.
+ * <p>
+ * Classic shortcut behavior is used, so evaluation of the
+ * {@link RevFilter#include(RevWalk, RevCommit)} method stops as soon as a true
+ * result is obtained. Applications can improve filtering performance by placing
+ * faster filters that are more likely to accept a result earlier in the list.
+ */
+public abstract class OrRevFilter extends RevFilter {
+ /**
+ * Create a filter with two filters, one of which must match.
+ *
+ * @param a
+ * first filter to test.
+ * @param b
+ * second filter to test.
+ * @return a filter that must match at least one input filter.
+ */
+ public static RevFilter create(final RevFilter a, final RevFilter b) {
+ if (a == ALL || b == ALL)
+ return ALL;
+ return new Binary(a, b);
+ }
+
+ /**
+ * Create a filter around many filters, one of which must match.
+ *
+ * @param list
+ * list of filters to match against. Must contain at least 2
+ * filters.
+ * @return a filter that must match at least one input filter.
+ */
+ public static RevFilter create(final RevFilter[] list) {
+ if (list.length == 2)
+ return create(list[0], list[1]);
+ if (list.length < 2)
+ throw new IllegalArgumentException(JGitText.get().atLeastTwoFiltersNeeded);
+ final RevFilter[] subfilters = new RevFilter[list.length];
+ System.arraycopy(list, 0, subfilters, 0, list.length);
+ return new List(subfilters);
+ }
+
+ /**
+ * Create a filter around many filters, one of which must match.
+ *
+ * @param list
+ * list of filters to match against. Must contain at least 2
+ * filters.
+ * @return a filter that must match at least one input filter.
+ */
+ public static RevFilter create(final Collection<RevFilter> list) {
+ if (list.size() < 2)
+ throw new IllegalArgumentException(JGitText.get().atLeastTwoFiltersNeeded);
+ final RevFilter[] subfilters = new RevFilter[list.size()];
+ list.toArray(subfilters);
+ if (subfilters.length == 2)
+ return create(subfilters[0], subfilters[1]);
+ return new List(subfilters);
+ }
+
+ private static class Binary extends OrRevFilter {
+ private final RevFilter a;
+
+ private final RevFilter b;
+
+ private final boolean requiresCommitBody;
+
+ Binary(final RevFilter one, final RevFilter two) {
+ a = one;
+ b = two;
+ requiresCommitBody = a.requiresCommitBody()
+ || b.requiresCommitBody();
+ }
+
+ @Override
+ public boolean include(final RevWalk walker, final RevCommit c)
+ throws MissingObjectException, IncorrectObjectTypeException,
+ IOException {
+ return a.include(walker, c) || b.include(walker, c);
+ }
+
+ @Override
+ public boolean requiresCommitBody() {
+ return requiresCommitBody;
+ }
+
+ @Override
+ public RevFilter clone() {
+ return new Binary(a.clone(), b.clone());
+ }
+
+ @SuppressWarnings("nls")
+ @Override
+ public String toString() {
+ return "(" + a.toString() + " OR " + b.toString() + ")";
+ }
+ }
+
+ private static class List extends OrRevFilter {
+ private final RevFilter[] subfilters;
+
+ private final boolean requiresCommitBody;
+
+ List(final RevFilter[] list) {
+ subfilters = list;
+
+ boolean rcb = false;
+ for (RevFilter filter : subfilters)
+ rcb |= filter.requiresCommitBody();
+ requiresCommitBody = rcb;
+ }
+
+ @Override
+ public boolean include(final RevWalk walker, final RevCommit c)
+ throws MissingObjectException, IncorrectObjectTypeException,
+ IOException {
+ for (final RevFilter f : subfilters) {
+ if (f.include(walker, c))
+ return true;
+ }
+ return false;
+ }
+
+ @Override
+ public boolean requiresCommitBody() {
+ return requiresCommitBody;
+ }
+
+ @Override
+ public RevFilter clone() {
+ final RevFilter[] s = new RevFilter[subfilters.length];
+ for (int i = 0; i < s.length; i++)
+ s[i] = subfilters[i].clone();
+ return new List(s);
+ }
+
+ @Override
+ public String toString() {
+ final StringBuilder r = new StringBuilder();
+ r.append("("); //$NON-NLS-1$
+ for (int i = 0; i < subfilters.length; i++) {
+ if (i > 0)
+ r.append(" OR "); //$NON-NLS-1$
+ r.append(subfilters[i].toString());
+ }
+ r.append(")"); //$NON-NLS-1$
+ return r.toString();
+ }
+ }
+}
diff --git a/commons.git/src/main/java/org/eclipse/jgit/revwalk/filter/PatternMatchRevFilter.java b/commons.git/src/main/java/org/eclipse/jgit/revwalk/filter/PatternMatchRevFilter.java
new file mode 100644
index 0000000000..1dd4555e5a
--- /dev/null
+++ b/commons.git/src/main/java/org/eclipse/jgit/revwalk/filter/PatternMatchRevFilter.java
@@ -0,0 +1,153 @@
+/*
+ * Copyright (C) 2009, Google Inc.
+ * Copyright (C) 2008, Shawn O. Pearce <[email protected]>
+ * and other copyright owners as documented in the project's IP log.
+ *
+ * This program and the accompanying materials are made available
+ * under the terms of the Eclipse Distribution License v1.0 which
+ * accompanies this distribution, is reproduced below, and is
+ * available at http://www.eclipse.org/org/documents/edl-v10.php
+ *
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or
+ * without modification, are permitted provided that the following
+ * conditions are met:
+ *
+ * - Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ *
+ * - Redistributions in binary form must reproduce the above
+ * copyright notice, this list of conditions and the following
+ * disclaimer in the documentation and/or other materials provided
+ * with the distribution.
+ *
+ * - Neither the name of the Eclipse Foundation, Inc. nor the
+ * names of its contributors may be used to endorse or promote
+ * products derived from this software without specific prior
+ * written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND
+ * CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES,
+ * INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
+ * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+ * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
+ * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
+ * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
+ * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
+ * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
+ * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
+ * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
+ * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
+ * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+ */
+
+package org.eclipse.jgit.revwalk.filter;
+
+import java.io.IOException;
+import java.util.regex.Matcher;
+import java.util.regex.Pattern;
+
+import org.eclipse.jgit.errors.IncorrectObjectTypeException;
+import org.eclipse.jgit.errors.MissingObjectException;
+import org.eclipse.jgit.internal.JGitText;
+import org.eclipse.jgit.lib.Constants;
+import org.eclipse.jgit.revwalk.RevCommit;
+import org.eclipse.jgit.revwalk.RevWalk;
+import org.eclipse.jgit.util.RawCharSequence;
+
+/** Abstract filter that searches text using extended regular expressions. */
+public abstract class PatternMatchRevFilter extends RevFilter {
+ /**
+ * Encode a string pattern for faster matching on byte arrays.
+ * <p>
+ * Force the characters to our funny UTF-8 only convention that we use on
+ * raw buffers. This avoids needing to perform character set decodes on the
+ * individual commit buffers.
+ *
+ * @param patternText
+ * original pattern string supplied by the user or the
+ * application.
+ * @return same pattern, but re-encoded to match our funny raw UTF-8
+ * character sequence {@link RawCharSequence}.
+ */
+ protected static final String forceToRaw(final String patternText) {
+ final byte[] b = Constants.encode(patternText);
+ final StringBuilder needle = new StringBuilder(b.length);
+ for (int i = 0; i < b.length; i++)
+ needle.append((char) (b[i] & 0xff));
+ return needle.toString();
+ }
+
+ private final String patternText;
+
+ private final Matcher compiledPattern;
+
+ /**
+ * Construct a new pattern matching filter.
+ *
+ * @param pattern
+ * text of the pattern. Callers may want to surround their
+ * pattern with ".*" on either end to allow matching in the
+ * middle of the string.
+ * @param innerString
+ * should .* be wrapped around the pattern of ^ and $ are
+ * missing? Most users will want this set.
+ * @param rawEncoding
+ * should {@link #forceToRaw(String)} be applied to the pattern
+ * before compiling it?
+ * @param flags
+ * flags from {@link Pattern} to control how matching performs.
+ */
+ protected PatternMatchRevFilter(String pattern, final boolean innerString,
+ final boolean rawEncoding, final int flags) {
+ if (pattern.length() == 0)
+ throw new IllegalArgumentException(JGitText.get().cannotMatchOnEmptyString);
+ patternText = pattern;
+
+ if (innerString) {
+ if (!pattern.startsWith("^") && !pattern.startsWith(".*")) //$NON-NLS-1$ //$NON-NLS-2$
+ pattern = ".*" + pattern; //$NON-NLS-1$
+ if (!pattern.endsWith("$") && !pattern.endsWith(".*")) //$NON-NLS-1$ //$NON-NLS-2$
+ pattern = pattern + ".*"; //$NON-NLS-1$
+ }
+ final String p = rawEncoding ? forceToRaw(pattern) : pattern;
+ compiledPattern = Pattern.compile(p, flags).matcher(""); //$NON-NLS-1$
+ }
+
+ /**
+ * Get the pattern this filter uses.
+ *
+ * @return the pattern this filter is applying to candidate strings.
+ */
+ public String pattern() {
+ return patternText;
+ }
+
+ @Override
+ public boolean include(final RevWalk walker, final RevCommit cmit)
+ throws MissingObjectException, IncorrectObjectTypeException,
+ IOException {
+ return compiledPattern.reset(text(cmit)).matches();
+ }
+
+ @Override
+ public boolean requiresCommitBody() {
+ return true;
+ }
+
+ /**
+ * Obtain the raw text to match against.
+ *
+ * @param cmit
+ * current commit being evaluated.
+ * @return sequence for the commit's content that we need to match on.
+ */
+ protected abstract CharSequence text(RevCommit cmit);
+
+ @SuppressWarnings("nls")
+ @Override
+ public String toString() {
+ return super.toString() + "(\"" + patternText + "\")";
+ }
+}
diff --git a/commons.git/src/main/java/org/eclipse/jgit/revwalk/filter/RevFilter.java b/commons.git/src/main/java/org/eclipse/jgit/revwalk/filter/RevFilter.java
new file mode 100644
index 0000000000..14a98a10bf
--- /dev/null
+++ b/commons.git/src/main/java/org/eclipse/jgit/revwalk/filter/RevFilter.java
@@ -0,0 +1,300 @@
+/*
+ * Copyright (C) 2008, Shawn O. Pearce <[email protected]>
+ * and other copyright owners as documented in the project's IP log.
+ *
+ * This program and the accompanying materials are made available
+ * under the terms of the Eclipse Distribution License v1.0 which
+ * accompanies this distribution, is reproduced below, and is
+ * available at http://www.eclipse.org/org/documents/edl-v10.php
+ *
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or
+ * without modification, are permitted provided that the following
+ * conditions are met:
+ *
+ * - Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ *
+ * - Redistributions in binary form must reproduce the above
+ * copyright notice, this list of conditions and the following
+ * disclaimer in the documentation and/or other materials provided
+ * with the distribution.
+ *
+ * - Neither the name of the Eclipse Foundation, Inc. nor the
+ * names of its contributors may be used to endorse or promote
+ * products derived from this software without specific prior
+ * written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND
+ * CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES,
+ * INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
+ * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+ * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
+ * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
+ * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
+ * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
+ * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
+ * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
+ * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
+ * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
+ * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+ */
+
+package org.eclipse.jgit.revwalk.filter;
+
+import java.io.IOException;
+
+import org.eclipse.jgit.errors.IncorrectObjectTypeException;
+import org.eclipse.jgit.errors.MissingObjectException;
+import org.eclipse.jgit.errors.StopWalkException;
+import org.eclipse.jgit.internal.JGitText;
+import org.eclipse.jgit.revwalk.RevCommit;
+import org.eclipse.jgit.revwalk.RevWalk;
+
+/**
+ * Selects interesting revisions during walking.
+ * <p>
+ * This is an abstract interface. Applications may implement a subclass, or use
+ * one of the predefined implementations already available within this package.
+ * Filters may be chained together using <code>AndRevFilter</code> and
+ * <code>OrRevFilter</code> to create complex boolean expressions.
+ * <p>
+ * Applications should install the filter on a RevWalk by
+ * {@link RevWalk#setRevFilter(RevFilter)} prior to starting traversal.
+ * <p>
+ * Unless specifically noted otherwise a RevFilter implementation is not thread
+ * safe and may not be shared by different RevWalk instances at the same time.
+ * This restriction allows RevFilter implementations to cache state within their
+ * instances during {@link #include(RevWalk, RevCommit)} if it is beneficial to
+ * their implementation. Deep clones created by {@link #clone()} may be used to
+ * construct a thread-safe copy of an existing filter.
+ *
+ * <p>
+ * <b>Message filters:</b>
+ * <ul>
+ * <li>Author name/email: {@link AuthorRevFilter}</li>
+ * <li>Committer name/email: {@link CommitterRevFilter}</li>
+ * <li>Message body: {@link MessageRevFilter}</li>
+ * </ul>
+ *
+ * <p>
+ * <b>Merge filters:</b>
+ * <ul>
+ * <li>Skip all merges: {@link #NO_MERGES}.</li>
+ * <li>Skip all non-merges: {@link #ONLY_MERGES}</li>
+ * </ul>
+ *
+ * <p>
+ * <b>Boolean modifiers:</b>
+ * <ul>
+ * <li>AND: {@link AndRevFilter}</li>
+ * <li>OR: {@link OrRevFilter}</li>
+ * <li>NOT: {@link NotRevFilter}</li>
+ * </ul>
+ */
+public abstract class RevFilter {
+ /** Default filter that always returns true (thread safe). */
+ public static final RevFilter ALL = new AllFilter();
+
+ private static final class AllFilter extends RevFilter {
+ @Override
+ public boolean include(final RevWalk walker, final RevCommit c) {
+ return true;
+ }
+
+ @Override
+ public RevFilter clone() {
+ return this;
+ }
+
+ @Override
+ public boolean requiresCommitBody() {
+ return false;
+ }
+
+ @Override
+ public String toString() {
+ return "ALL"; //$NON-NLS-1$
+ }
+ }
+
+ /** Default filter that always returns false (thread safe). */
+ public static final RevFilter NONE = new NoneFilter();
+
+ private static final class NoneFilter extends RevFilter {
+ @Override
+ public boolean include(final RevWalk walker, final RevCommit c) {
+ return false;
+ }
+
+ @Override
+ public RevFilter clone() {
+ return this;
+ }
+
+ @Override
+ public boolean requiresCommitBody() {
+ return false;
+ }
+
+ @Override
+ public String toString() {
+ return "NONE"; //$NON-NLS-1$
+ }
+ }
+
+ /**
+ * Filter including only merge commits, excluding all commits with less than
+ * two parents (thread safe).
+ *
+ * @since 4.4
+ */
+ public static final RevFilter ONLY_MERGES = new OnlyMergesFilter();
+
+ private static final class OnlyMergesFilter extends RevFilter {
+
+ @Override
+ public boolean include(RevWalk walker, RevCommit c) {
+ return c.getParentCount() >= 2;
+ }
+
+ @Override
+ public RevFilter clone() {
+ return this;
+ }
+
+ @Override
+ public boolean requiresCommitBody() {
+ return false;
+ }
+
+ @Override
+ public String toString() {
+ return "ONLY_MERGES"; //$NON-NLS-1$
+ }
+ }
+
+ /** Excludes commits with more than one parent (thread safe). */
+ public static final RevFilter NO_MERGES = new NoMergesFilter();
+
+ private static final class NoMergesFilter extends RevFilter {
+ @Override
+ public boolean include(final RevWalk walker, final RevCommit c) {
+ return c.getParentCount() < 2;
+ }
+
+ @Override
+ public RevFilter clone() {
+ return this;
+ }
+
+ @Override
+ public boolean requiresCommitBody() {
+ return false;
+ }
+
+ @Override
+ public String toString() {
+ return "NO_MERGES"; //$NON-NLS-1$
+ }
+ }
+
+ /**
+ * Selects only merge bases of the starting points (thread safe).
+ * <p>
+ * This is a special case filter that cannot be combined with any other
+ * filter. Its include method always throws an exception as context
+ * information beyond the arguments is necessary to determine if the
+ * supplied commit is a merge base.
+ */
+ public static final RevFilter MERGE_BASE = new MergeBaseFilter();
+
+ private static final class MergeBaseFilter extends RevFilter {
+ @Override
+ public boolean include(final RevWalk walker, final RevCommit c) {
+ throw new UnsupportedOperationException(JGitText.get().cannotBeCombined);
+ }
+
+ @Override
+ public RevFilter clone() {
+ return this;
+ }
+
+ @Override
+ public boolean requiresCommitBody() {
+ return false;
+ }
+
+ @Override
+ public String toString() {
+ return "MERGE_BASE"; //$NON-NLS-1$
+ }
+ }
+
+ /**
+ * Create a new filter that does the opposite of this filter.
+ *
+ * @return a new filter that includes commits this filter rejects.
+ */
+ public RevFilter negate() {
+ return NotRevFilter.create(this);
+ }
+
+ /** @return true if the filter needs the commit body to be parsed. */
+ public boolean requiresCommitBody() {
+ // Assume true to be backward compatible with prior behavior.
+ return true;
+ }
+
+ /**
+ * Determine if the supplied commit should be included in results.
+ *
+ * @param walker
+ * the active walker this filter is being invoked from within.
+ * @param cmit
+ * the commit currently being tested. The commit has been parsed
+ * and its body is available for inspection only if the filter
+ * returns true from {@link #requiresCommitBody()}.
+ * @return true to include this commit in the results; false to have this
+ * commit be omitted entirely from the results.
+ * @throws StopWalkException
+ * the filter knows for certain that no additional commits can
+ * ever match, and the current commit doesn't match either. The
+ * walk is halted and no more results are provided.
+ * @throws MissingObjectException
+ * an object the filter needs to consult to determine its answer
+ * does not exist in the Git repository the walker is operating
+ * on. Filtering this commit is impossible without the object.
+ * @throws IncorrectObjectTypeException
+ * an object the filter needed to consult was not of the
+ * expected object type. This usually indicates a corrupt
+ * repository, as an object link is referencing the wrong type.
+ * @throws IOException
+ * a loose object or pack file could not be read to obtain data
+ * necessary for the filter to make its decision.
+ */
+ public abstract boolean include(RevWalk walker, RevCommit cmit)
+ throws StopWalkException, MissingObjectException,
+ IncorrectObjectTypeException, IOException;
+
+ /**
+ * Clone this revision filter, including its parameters.
+ * <p>
+ * This is a deep clone. If this filter embeds objects or other filters it
+ * must also clone those, to ensure the instances do not share mutable data.
+ *
+ * @return another copy of this filter, suitable for another thread.
+ */
+ public abstract RevFilter clone();
+
+ @Override
+ public String toString() {
+ String n = getClass().getName();
+ int lastDot = n.lastIndexOf('.');
+ if (lastDot >= 0) {
+ n = n.substring(lastDot + 1);
+ }
+ return n.replace('$', '.');
+ }
+}
diff --git a/commons.git/src/main/java/org/eclipse/jgit/revwalk/filter/RevFlagFilter.java b/commons.git/src/main/java/org/eclipse/jgit/revwalk/filter/RevFlagFilter.java
new file mode 100644
index 0000000000..1fbf74617e
--- /dev/null
+++ b/commons.git/src/main/java/org/eclipse/jgit/revwalk/filter/RevFlagFilter.java
@@ -0,0 +1,171 @@
+/*
+ * Copyright (C) 2008, Shawn O. Pearce <[email protected]>
+ * and other copyright owners as documented in the project's IP log.
+ *
+ * This program and the accompanying materials are made available
+ * under the terms of the Eclipse Distribution License v1.0 which
+ * accompanies this distribution, is reproduced below, and is
+ * available at http://www.eclipse.org/org/documents/edl-v10.php
+ *
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or
+ * without modification, are permitted provided that the following
+ * conditions are met:
+ *
+ * - Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ *
+ * - Redistributions in binary form must reproduce the above
+ * copyright notice, this list of conditions and the following
+ * disclaimer in the documentation and/or other materials provided
+ * with the distribution.
+ *
+ * - Neither the name of the Eclipse Foundation, Inc. nor the
+ * names of its contributors may be used to endorse or promote
+ * products derived from this software without specific prior
+ * written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND
+ * CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES,
+ * INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
+ * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+ * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
+ * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
+ * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
+ * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
+ * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
+ * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
+ * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
+ * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
+ * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+ */
+
+package org.eclipse.jgit.revwalk.filter;
+
+import java.io.IOException;
+
+import org.eclipse.jgit.errors.IncorrectObjectTypeException;
+import org.eclipse.jgit.errors.MissingObjectException;
+import org.eclipse.jgit.revwalk.RevCommit;
+import org.eclipse.jgit.revwalk.RevFlag;
+import org.eclipse.jgit.revwalk.RevFlagSet;
+import org.eclipse.jgit.revwalk.RevWalk;
+
+/** Matches only commits with some/all RevFlags already set. */
+public abstract class RevFlagFilter extends RevFilter {
+ /**
+ * Create a new filter that tests for a single flag.
+ *
+ * @param a
+ * the flag to test.
+ * @return filter that selects only commits with flag <code>a</code>.
+ */
+ public static RevFilter has(final RevFlag a) {
+ final RevFlagSet s = new RevFlagSet();
+ s.add(a);
+ return new HasAll(s);
+ }
+
+ /**
+ * Create a new filter that tests all flags in a set.
+ *
+ * @param a
+ * set of flags to test.
+ * @return filter that selects only commits with all flags in <code>a</code>.
+ */
+ public static RevFilter hasAll(final RevFlag... a) {
+ final RevFlagSet set = new RevFlagSet();
+ for (final RevFlag flag : a)
+ set.add(flag);
+ return new HasAll(set);
+ }
+
+ /**
+ * Create a new filter that tests all flags in a set.
+ *
+ * @param a
+ * set of flags to test.
+ * @return filter that selects only commits with all flags in <code>a</code>.
+ */
+ public static RevFilter hasAll(final RevFlagSet a) {
+ return new HasAll(new RevFlagSet(a));
+ }
+
+ /**
+ * Create a new filter that tests for any flag in a set.
+ *
+ * @param a
+ * set of flags to test.
+ * @return filter that selects only commits with any flag in <code>a</code>.
+ */
+ public static RevFilter hasAny(final RevFlag... a) {
+ final RevFlagSet set = new RevFlagSet();
+ for (final RevFlag flag : a)
+ set.add(flag);
+ return new HasAny(set);
+ }
+
+ /**
+ * Create a new filter that tests for any flag in a set.
+ *
+ * @param a
+ * set of flags to test.
+ * @return filter that selects only commits with any flag in <code>a</code>.
+ */
+ public static RevFilter hasAny(final RevFlagSet a) {
+ return new HasAny(new RevFlagSet(a));
+ }
+
+ final RevFlagSet flags;
+
+ RevFlagFilter(final RevFlagSet m) {
+ flags = m;
+ }
+
+ @Override
+ public RevFilter clone() {
+ return this;
+ }
+
+ @Override
+ public String toString() {
+ return super.toString() + flags;
+ }
+
+ private static class HasAll extends RevFlagFilter {
+ HasAll(final RevFlagSet m) {
+ super(m);
+ }
+
+ @Override
+ public boolean include(final RevWalk walker, final RevCommit c)
+ throws MissingObjectException, IncorrectObjectTypeException,
+ IOException {
+ return c.hasAll(flags);
+ }
+
+ @Override
+ public boolean requiresCommitBody() {
+ return false;
+ }
+ }
+
+ private static class HasAny extends RevFlagFilter {
+ HasAny(final RevFlagSet m) {
+ super(m);
+ }
+
+ @Override
+ public boolean include(final RevWalk walker, final RevCommit c)
+ throws MissingObjectException, IncorrectObjectTypeException,
+ IOException {
+ return c.hasAny(flags);
+ }
+
+ @Override
+ public boolean requiresCommitBody() {
+ return false;
+ }
+ }
+}
diff --git a/commons.git/src/main/java/org/eclipse/jgit/revwalk/filter/SkipRevFilter.java b/commons.git/src/main/java/org/eclipse/jgit/revwalk/filter/SkipRevFilter.java
new file mode 100644
index 0000000000..e230c9b6b1
--- /dev/null
+++ b/commons.git/src/main/java/org/eclipse/jgit/revwalk/filter/SkipRevFilter.java
@@ -0,0 +1,94 @@
+/*
+ * Copyright (C) 2011, Tomasz Zarna <[email protected]>
+ * and other copyright owners as documented in the project's IP log.
+ *
+ * This program and the accompanying materials are made available
+ * under the terms of the Eclipse Distribution License v1.0 which
+ * accompanies this distribution, is reproduced below, and is
+ * available at http://www.eclipse.org/org/documents/edl-v10.php
+ *
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or
+ * without modification, are permitted provided that the following
+ * conditions are met:
+ *
+ * - Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ *
+ * - Redistributions in binary form must reproduce the above
+ * copyright notice, this list of conditions and the following
+ * disclaimer in the documentation and/or other materials provided
+ * with the distribution.
+ *
+ * - Neither the name of the Eclipse Foundation, Inc. nor the
+ * names of its contributors may be used to endorse or promote
+ * products derived from this software without specific prior
+ * written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND
+ * CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES,
+ * INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
+ * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+ * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
+ * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
+ * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
+ * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
+ * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
+ * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
+ * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
+ * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
+ * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+ */
+package org.eclipse.jgit.revwalk.filter;
+
+import java.io.IOException;
+
+import org.eclipse.jgit.errors.IncorrectObjectTypeException;
+import org.eclipse.jgit.errors.MissingObjectException;
+import org.eclipse.jgit.errors.StopWalkException;
+import org.eclipse.jgit.internal.JGitText;
+import org.eclipse.jgit.revwalk.RevCommit;
+import org.eclipse.jgit.revwalk.RevWalk;
+
+/**
+ * Filter that includes commits after a configured number are skipped.
+ */
+public class SkipRevFilter extends RevFilter {
+
+ private final int skip;
+
+ private int count;
+
+ /**
+ * Create a new skip filter.
+ *
+ * @param skip
+ * the number of commits to skip
+ * @return a new filter
+ */
+ public static RevFilter create(int skip) {
+ if (skip < 0)
+ throw new IllegalArgumentException(
+ JGitText.get().skipMustBeNonNegative);
+ return new SkipRevFilter(skip);
+ }
+
+ private SkipRevFilter(int skip) {
+ this.skip = skip;
+ }
+
+ @Override
+ public boolean include(RevWalk walker, RevCommit cmit)
+ throws StopWalkException, MissingObjectException,
+ IncorrectObjectTypeException, IOException {
+ if (skip > count++)
+ return false;
+ return true;
+ }
+
+ @Override
+ public RevFilter clone() {
+ return new SkipRevFilter(skip);
+ }
+}
\ No newline at end of file
diff --git a/commons.git/src/main/java/org/eclipse/jgit/revwalk/filter/SubStringRevFilter.java b/commons.git/src/main/java/org/eclipse/jgit/revwalk/filter/SubStringRevFilter.java
new file mode 100644
index 0000000000..ce3a022293
--- /dev/null
+++ b/commons.git/src/main/java/org/eclipse/jgit/revwalk/filter/SubStringRevFilter.java
@@ -0,0 +1,131 @@
+/*
+ * Copyright (C) 2008, Shawn O. Pearce <[email protected]>
+ * and other copyright owners as documented in the project's IP log.
+ *
+ * This program and the accompanying materials are made available
+ * under the terms of the Eclipse Distribution License v1.0 which
+ * accompanies this distribution, is reproduced below, and is
+ * available at http://www.eclipse.org/org/documents/edl-v10.php
+ *
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or
+ * without modification, are permitted provided that the following
+ * conditions are met:
+ *
+ * - Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ *
+ * - Redistributions in binary form must reproduce the above
+ * copyright notice, this list of conditions and the following
+ * disclaimer in the documentation and/or other materials provided
+ * with the distribution.
+ *
+ * - Neither the name of the Eclipse Foundation, Inc. nor the
+ * names of its contributors may be used to endorse or promote
+ * products derived from this software without specific prior
+ * written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND
+ * CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES,
+ * INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
+ * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+ * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
+ * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
+ * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
+ * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
+ * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
+ * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
+ * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
+ * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
+ * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+ */
+
+package org.eclipse.jgit.revwalk.filter;
+
+import java.io.IOException;
+
+import org.eclipse.jgit.errors.IncorrectObjectTypeException;
+import org.eclipse.jgit.errors.MissingObjectException;
+import org.eclipse.jgit.revwalk.RevCommit;
+import org.eclipse.jgit.revwalk.RevWalk;
+import org.eclipse.jgit.util.RawCharSequence;
+import org.eclipse.jgit.util.RawSubStringPattern;
+
+/** Abstract filter that searches text using only substring search. */
+public abstract class SubStringRevFilter extends RevFilter {
+ /**
+ * Can this string be safely handled by a substring filter?
+ *
+ * @param pattern
+ * the pattern text proposed by the user.
+ * @return true if a substring filter can perform this pattern match; false
+ * if {@link PatternMatchRevFilter} must be used instead.
+ */
+ public static boolean safe(final String pattern) {
+ for (int i = 0; i < pattern.length(); i++) {
+ final char c = pattern.charAt(i);
+ switch (c) {
+ case '.':
+ case '?':
+ case '*':
+ case '+':
+ case '{':
+ case '}':
+ case '(':
+ case ')':
+ case '[':
+ case ']':
+ case '\\':
+ return false;
+ }
+ }
+ return true;
+ }
+
+ private final RawSubStringPattern pattern;
+
+ /**
+ * Construct a new matching filter.
+ *
+ * @param patternText
+ * text to locate. This should be a safe string as described by
+ * the {@link #safe(String)} as regular expression meta
+ * characters are treated as literals.
+ */
+ protected SubStringRevFilter(final String patternText) {
+ pattern = new RawSubStringPattern(patternText);
+ }
+
+ @Override
+ public boolean include(final RevWalk walker, final RevCommit cmit)
+ throws MissingObjectException, IncorrectObjectTypeException,
+ IOException {
+ return pattern.match(text(cmit)) >= 0;
+ }
+
+ @Override
+ public boolean requiresCommitBody() {
+ return true;
+ }
+
+ /**
+ * Obtain the raw text to match against.
+ *
+ * @param cmit
+ * current commit being evaluated.
+ * @return sequence for the commit's content that we need to match on.
+ */
+ protected abstract RawCharSequence text(RevCommit cmit);
+
+ @Override
+ public RevFilter clone() {
+ return this; // Typically we are actually thread-safe.
+ }
+
+ @SuppressWarnings("nls")
+ @Override
+ public String toString() {
+ return super.toString() + "(\"" + pattern.pattern() + "\")";
+ }
+}
diff --git a/commons.git/src/main/java/org/eclipse/jgit/revwalk/filter/package-info.java b/commons.git/src/main/java/org/eclipse/jgit/revwalk/filter/package-info.java
new file mode 100644
index 0000000000..135850cba5
--- /dev/null
+++ b/commons.git/src/main/java/org/eclipse/jgit/revwalk/filter/package-info.java
@@ -0,0 +1,4 @@
+/**
+ * Filters for use in revision walking.
+ */
+package org.eclipse.jgit.revwalk.filter;
diff --git a/commons.hibernate/src/main/java/com/pmease/commons/hibernate/dao/AbstractEntityManager.java b/commons.hibernate/src/main/java/com/pmease/commons/hibernate/dao/AbstractEntityManager.java
index 9707890faf..b04fa5211c 100644
--- a/commons.hibernate/src/main/java/com/pmease/commons/hibernate/dao/AbstractEntityManager.java
+++ b/commons.hibernate/src/main/java/com/pmease/commons/hibernate/dao/AbstractEntityManager.java
@@ -79,8 +79,8 @@ public abstract class AbstractEntityManager<T extends AbstractEntity> implements
dao.doAfterCommit(runnable);
}
- protected void doUnitOfWorkAfterCommitAsync(Runnable runnable) {
- dao.doUnitOfWorkAfterCommitAsync(runnable);
+ protected void doUnitOfWorkAsyncAfterCommit(Runnable runnable) {
+ dao.doUnitOfWorkAsyncAfterCommit(runnable);
}
protected Session getSession() {
diff --git a/commons.hibernate/src/main/java/com/pmease/commons/hibernate/dao/Dao.java b/commons.hibernate/src/main/java/com/pmease/commons/hibernate/dao/Dao.java
index 71a613db89..3b8b57b269 100644
--- a/commons.hibernate/src/main/java/com/pmease/commons/hibernate/dao/Dao.java
+++ b/commons.hibernate/src/main/java/com/pmease/commons/hibernate/dao/Dao.java
@@ -96,9 +96,9 @@ public interface Dao {
void doAfterCommit(Runnable runnable);
- void doAfterCommitAsync(Runnable runnable);
+ void doAsyncAfterCommit(Runnable runnable);
- void doUnitOfWorkAfterCommitAsync(Runnable runnable);
+ void doUnitOfWorkAsyncAfterCommit(Runnable runnable);
Session getSession();
diff --git a/commons.hibernate/src/main/java/com/pmease/commons/hibernate/dao/DefaultDao.java b/commons.hibernate/src/main/java/com/pmease/commons/hibernate/dao/DefaultDao.java
index 34a1af5310..1f63baa8d4 100644
--- a/commons.hibernate/src/main/java/com/pmease/commons/hibernate/dao/DefaultDao.java
+++ b/commons.hibernate/src/main/java/com/pmease/commons/hibernate/dao/DefaultDao.java
@@ -1,175 +1,175 @@
-package com.pmease.commons.hibernate.dao;
-
-import java.io.ObjectStreamException;
-import java.io.Serializable;
-import java.util.List;
-import java.util.concurrent.ExecutorService;
-
-import javax.inject.Inject;
-import javax.inject.Provider;
-import javax.inject.Singleton;
-import javax.transaction.Status;
-import javax.transaction.Synchronization;
-
-import org.hibernate.Criteria;
-import org.hibernate.Session;
-import org.hibernate.criterion.Projections;
-
-import com.pmease.commons.hibernate.AbstractEntity;
-import com.pmease.commons.hibernate.Sessional;
-import com.pmease.commons.hibernate.Transactional;
-import com.pmease.commons.hibernate.UnitOfWork;
-import com.pmease.commons.loader.ListenerRegistry;
-import com.pmease.commons.loader.ManagedSerializedForm;
-
-@Singleton
-@SuppressWarnings("unchecked")
-public class DefaultDao implements Dao, Serializable {
-
- private final Provider<Session> sessionProvider;
-
- private final ListenerRegistry listenerRegistry;
-
- private final ExecutorService executorService;
-
- private final UnitOfWork unitOfWork;
-
- @Inject
- public DefaultDao(Provider<Session> sessionProvider, UnitOfWork unitOfWork,
- ListenerRegistry listenerRegistry, ExecutorService executorService) {
- this.sessionProvider = sessionProvider;
- this.unitOfWork = unitOfWork;
- this.listenerRegistry = listenerRegistry;
- this.executorService = executorService;
- }
-
- @Sessional
- @Override
- public <T extends AbstractEntity> T get(Class<T> entityClass, Long entityId) {
- return (T) getSession().get(unproxy(getSession(), entityClass), entityId);
- }
-
- @Sessional
- @Override
- public <T extends AbstractEntity> T load(Class<T> entityClass, Long entityId) {
- return (T) getSession().load(unproxy(getSession(), entityClass), entityId);
- }
-
- @Transactional
- @Override
- public void persist(AbstractEntity entity) {
- boolean isNew = entity.isNew();
- getSession().saveOrUpdate(entity);
- listenerRegistry.post(new EntityPersisted(entity, isNew));
- }
-
- @Transactional
- @Override
- public void remove(AbstractEntity entity) {
- getSession().delete(entity);
- listenerRegistry.post(new EntityRemoved(entity));
- }
-
- @Override
- public Session getSession() {
- return sessionProvider.get();
- }
-
- protected <T extends AbstractEntity> Class<T> unproxy(Session session, Class<T> entityClass) {
- //class meta data will be null if entityClass is not registered with Hibernate or when
- //it is a Hibernate proxy class (e.x. test.googlecode.genericdao.model.Person_$$_javassist_5).
- //So if a class is not recognized, we will look at superclasses to see if
- //it is a proxy.
- while (session.getSessionFactory().getClassMetadata(entityClass) == null) {
- entityClass = (Class<T>) entityClass.getSuperclass();
- if (Object.class.equals(entityClass))
- return null;
- }
-
- return entityClass;
- }
-
- @Sessional
- @Override
- public <T extends AbstractEntity> List<T> findRange(EntityCriteria<T> entityCriteria, int firstResult, int maxResults) {
- Criteria criteria = entityCriteria.getExecutableCriteria(getSession());
- if (firstResult != 0)
- criteria.setFirstResult(firstResult);
- if (maxResults != 0)
- criteria.setMaxResults(maxResults);
- return criteria.list();
- }
-
- @Sessional
- @Override
- public <T extends AbstractEntity> List<T> findAll(EntityCriteria<T> entityCriteria) {
- return findRange(entityCriteria, 0, 0);
- }
-
- @Sessional
- @Override
- public <T extends AbstractEntity> T find(EntityCriteria<T> entityCriteria) {
- Criteria criteria = entityCriteria.getExecutableCriteria(getSession());
- criteria.setFirstResult(0);
- criteria.setMaxResults(1);
- return (T) criteria.uniqueResult();
- }
-
- @Override
- public <T extends AbstractEntity> int count(EntityCriteria<T> entityCriteria) {
- Criteria criteria = entityCriteria.getExecutableCriteria(getSession());
- criteria.setProjection(Projections.rowCount());
- return ((Long) criteria.uniqueResult()).intValue();
- }
-
- public Object writeReplace() throws ObjectStreamException {
- return new ManagedSerializedForm(Dao.class);
- }
-
- @Sessional
- @Override
- public <T extends AbstractEntity> List<T> findAll(Class<T> entityClass) {
- return findRange(EntityCriteria.of(entityClass), 0, 0);
- }
-
- @Override
- public void doAfterCommit(Runnable runnable) {
- getSession().getTransaction().registerSynchronization(new Synchronization() {
-
- @Override
- public void beforeCompletion() {
- }
-
- @Override
- public void afterCompletion(int status) {
- if (status == Status.STATUS_COMMITTED)
- runnable.run();
- }
- });
- }
-
- @Override
- public void doAfterCommitAsync(Runnable runnable) {
- doAfterCommit(new Runnable() {
-
- @Override
- public void run() {
- executorService.submit(runnable);
- }
-
- });
- }
-
- @Override
- public void doUnitOfWorkAfterCommitAsync(Runnable runnable) {
- doAfterCommit(new Runnable() {
-
- @Override
- public void run() {
- unitOfWork.doAsync(runnable);
- }
-
- });
- }
-
-}
+package com.pmease.commons.hibernate.dao;
+
+import java.io.ObjectStreamException;
+import java.io.Serializable;
+import java.util.List;
+import java.util.concurrent.ExecutorService;
+
+import javax.inject.Inject;
+import javax.inject.Provider;
+import javax.inject.Singleton;
+import javax.transaction.Status;
+import javax.transaction.Synchronization;
+
+import org.hibernate.Criteria;
+import org.hibernate.Session;
+import org.hibernate.criterion.Projections;
+
+import com.pmease.commons.hibernate.AbstractEntity;
+import com.pmease.commons.hibernate.Sessional;
+import com.pmease.commons.hibernate.Transactional;
+import com.pmease.commons.hibernate.UnitOfWork;
+import com.pmease.commons.loader.ListenerRegistry;
+import com.pmease.commons.loader.ManagedSerializedForm;
+
+@Singleton
+@SuppressWarnings("unchecked")
+public class DefaultDao implements Dao, Serializable {
+
+ private final Provider<Session> sessionProvider;
+
+ private final ListenerRegistry listenerRegistry;
+
+ private final ExecutorService executorService;
+
+ private final UnitOfWork unitOfWork;
+
+ @Inject
+ public DefaultDao(Provider<Session> sessionProvider, UnitOfWork unitOfWork,
+ ListenerRegistry listenerRegistry, ExecutorService executorService) {
+ this.sessionProvider = sessionProvider;
+ this.unitOfWork = unitOfWork;
+ this.listenerRegistry = listenerRegistry;
+ this.executorService = executorService;
+ }
+
+ @Sessional
+ @Override
+ public <T extends AbstractEntity> T get(Class<T> entityClass, Long entityId) {
+ return (T) getSession().get(unproxy(getSession(), entityClass), entityId);
+ }
+
+ @Sessional
+ @Override
+ public <T extends AbstractEntity> T load(Class<T> entityClass, Long entityId) {
+ return (T) getSession().load(unproxy(getSession(), entityClass), entityId);
+ }
+
+ @Transactional
+ @Override
+ public void persist(AbstractEntity entity) {
+ boolean isNew = entity.isNew();
+ getSession().saveOrUpdate(entity);
+ listenerRegistry.post(new EntityPersisted(entity, isNew));
+ }
+
+ @Transactional
+ @Override
+ public void remove(AbstractEntity entity) {
+ getSession().delete(entity);
+ listenerRegistry.post(new EntityRemoved(entity));
+ }
+
+ @Override
+ public Session getSession() {
+ return sessionProvider.get();
+ }
+
+ protected <T extends AbstractEntity> Class<T> unproxy(Session session, Class<T> entityClass) {
+ //class meta data will be null if entityClass is not registered with Hibernate or when
+ //it is a Hibernate proxy class (e.x. test.googlecode.genericdao.model.Person_$$_javassist_5).
+ //So if a class is not recognized, we will look at superclasses to see if
+ //it is a proxy.
+ while (session.getSessionFactory().getClassMetadata(entityClass) == null) {
+ entityClass = (Class<T>) entityClass.getSuperclass();
+ if (Object.class.equals(entityClass))
+ return null;
+ }
+
+ return entityClass;
+ }
+
+ @Sessional
+ @Override
+ public <T extends AbstractEntity> List<T> findRange(EntityCriteria<T> entityCriteria, int firstResult, int maxResults) {
+ Criteria criteria = entityCriteria.getExecutableCriteria(getSession());
+ if (firstResult != 0)
+ criteria.setFirstResult(firstResult);
+ if (maxResults != 0)
+ criteria.setMaxResults(maxResults);
+ return criteria.list();
+ }
+
+ @Sessional
+ @Override
+ public <T extends AbstractEntity> List<T> findAll(EntityCriteria<T> entityCriteria) {
+ return findRange(entityCriteria, 0, 0);
+ }
+
+ @Sessional
+ @Override
+ public <T extends AbstractEntity> T find(EntityCriteria<T> entityCriteria) {
+ Criteria criteria = entityCriteria.getExecutableCriteria(getSession());
+ criteria.setFirstResult(0);
+ criteria.setMaxResults(1);
+ return (T) criteria.uniqueResult();
+ }
+
+ @Override
+ public <T extends AbstractEntity> int count(EntityCriteria<T> entityCriteria) {
+ Criteria criteria = entityCriteria.getExecutableCriteria(getSession());
+ criteria.setProjection(Projections.rowCount());
+ return ((Long) criteria.uniqueResult()).intValue();
+ }
+
+ public Object writeReplace() throws ObjectStreamException {
+ return new ManagedSerializedForm(Dao.class);
+ }
+
+ @Sessional
+ @Override
+ public <T extends AbstractEntity> List<T> findAll(Class<T> entityClass) {
+ return findRange(EntityCriteria.of(entityClass), 0, 0);
+ }
+
+ @Override
+ public void doAfterCommit(Runnable runnable) {
+ getSession().getTransaction().registerSynchronization(new Synchronization() {
+
+ @Override
+ public void beforeCompletion() {
+ }
+
+ @Override
+ public void afterCompletion(int status) {
+ if (status == Status.STATUS_COMMITTED)
+ runnable.run();
+ }
+ });
+ }
+
+ @Override
+ public void doAsyncAfterCommit(Runnable runnable) {
+ doAfterCommit(new Runnable() {
+
+ @Override
+ public void run() {
+ executorService.submit(runnable);
+ }
+
+ });
+ }
+
+ @Override
+ public void doUnitOfWorkAsyncAfterCommit(Runnable runnable) {
+ doAfterCommit(new Runnable() {
+
+ @Override
+ public void run() {
+ unitOfWork.doAsync(runnable);
+ }
+
+ });
+ }
+
+}
diff --git a/commons.wicket/src/main/java/com/pmease/commons/wicket/component/markdown/MarkdownPanel.java b/commons.wicket/src/main/java/com/pmease/commons/wicket/component/markdown/MarkdownPanel.java
index ffe814c6a3..2a6a5c03a9 100644
--- a/commons.wicket/src/main/java/com/pmease/commons/wicket/component/markdown/MarkdownPanel.java
+++ b/commons.wicket/src/main/java/com/pmease/commons/wicket/component/markdown/MarkdownPanel.java
@@ -1,109 +1,109 @@
-package com.pmease.commons.wicket.component.markdown;
-
-import static org.apache.wicket.ajax.attributes.CallbackParameter.explicit;
-
-import javax.annotation.Nullable;
-
-import org.apache.wicket.Component;
-import org.apache.wicket.ajax.AbstractDefaultAjaxBehavior;
-import org.apache.wicket.ajax.AjaxRequestTarget;
-import org.apache.wicket.markup.head.IHeaderResponse;
-import org.apache.wicket.markup.head.JavaScriptHeaderItem;
-import org.apache.wicket.markup.head.OnDomReadyHeaderItem;
-import org.apache.wicket.markup.html.basic.Label;
-import org.apache.wicket.markup.html.panel.GenericPanel;
-import org.apache.wicket.model.IModel;
-import org.apache.wicket.model.LoadableDetachableModel;
-import org.apache.wicket.request.IRequestParameters;
-import org.apache.wicket.request.cycle.RequestCycle;
-import org.hibernate.StaleObjectStateException;
-
-import com.pmease.commons.loader.AppLoader;
-import com.pmease.commons.markdown.MarkdownManager;
-import com.pmease.commons.util.StringUtils;
-
-import de.agilecoders.wicket.core.markup.html.bootstrap.common.NotificationPanel;
-
-@SuppressWarnings("serial")
-public class MarkdownPanel extends GenericPanel<String> {
-
- private final MarkdownEditSupport editSupport;
-
- private long lastVersion;
-
- public MarkdownPanel(String id, IModel<String> model, @Nullable MarkdownEditSupport editSupport) {
- super(id, model);
-
- this.editSupport = editSupport;
- if (editSupport != null)
- lastVersion = editSupport.getVersion();
- }
-
- @Override
- protected void onInitialize() {
- super.onInitialize();
-
- NotificationPanel feedback = new NotificationPanel("feedback", this);
- feedback.setOutputMarkupPlaceholderTag(true);
- add(feedback);
-
- add(new Label("content", new LoadableDetachableModel<String>() {
-
- @Override
- protected String load() {
- String markdown = MarkdownPanel.this.getModelObject();
- if (markdown != null) {
- return AppLoader.getInstance(MarkdownManager.class).parseAndProcess(markdown);
- } else {
- return null;
- }
- }
- }).setEscapeModelStrings(false));
-
- add(new AbstractDefaultAjaxBehavior() {
-
- @Override
- protected void respond(AjaxRequestTarget target) {
- IRequestParameters params = RequestCycle.get().getRequest().getQueryParameters();
- int taskStartIndex = params.getParameterValue("taskStartIndex").toInt();
- boolean taskChecked = params.getParameterValue("taskChecked").toBoolean();
- String markdown = getModelObject();
- String beforeTask = markdown.substring(0, taskStartIndex);
- String beforeBracket = StringUtils.substringBeforeLast(beforeTask, "[");
- String afterBracket = StringUtils.substringAfterLast(beforeTask, "]");
- String taskStatus = taskChecked?"x":" ";
- String newMarkdown = beforeBracket + "[" + taskStatus + "]"
- + afterBracket + markdown.substring(taskStartIndex);
-
- try {
- if (editSupport.getVersion() != lastVersion)
- throw new StaleObjectStateException("unknown", "unknown");
- editSupport.setContent(newMarkdown);
- target.add(feedback); // clear the feedback
- } catch (StaleObjectStateException e) {
- warn("Some one changed the content you are editing. The content has now been "
- + "reloaded, please try again.");
- target.add(MarkdownPanel.this);
- }
- lastVersion = editSupport.getVersion();
- }
-
- @Override
- public void renderHead(Component component, IHeaderResponse response) {
- super.renderHead(component, response);
-
- response.render(JavaScriptHeaderItem.forReference(MarkdownResourceReference.INSTANCE));
-
- CharSequence callbackFunc = getCallbackFunction(
- explicit("taskStartIndex"), explicit("taskChecked"));
- String script = String.format("pmease.commons.initMarkdownViewer($('#%s>.md-preview'), %s);",
- getMarkupId(true), editSupport!=null?callbackFunc:"undefined");
- response.render(OnDomReadyHeaderItem.forScript(script));
- }
-
- });
-
- setOutputMarkupId(true);
- }
-
-}
+package com.pmease.commons.wicket.component.markdown;
+
+import static org.apache.wicket.ajax.attributes.CallbackParameter.explicit;
+
+import javax.annotation.Nullable;
+
+import org.apache.wicket.Component;
+import org.apache.wicket.ajax.AbstractDefaultAjaxBehavior;
+import org.apache.wicket.ajax.AjaxRequestTarget;
+import org.apache.wicket.markup.head.IHeaderResponse;
+import org.apache.wicket.markup.head.JavaScriptHeaderItem;
+import org.apache.wicket.markup.head.OnDomReadyHeaderItem;
+import org.apache.wicket.markup.html.basic.Label;
+import org.apache.wicket.markup.html.panel.GenericPanel;
+import org.apache.wicket.model.IModel;
+import org.apache.wicket.model.LoadableDetachableModel;
+import org.apache.wicket.request.IRequestParameters;
+import org.apache.wicket.request.cycle.RequestCycle;
+import org.hibernate.StaleStateException;
+
+import com.pmease.commons.loader.AppLoader;
+import com.pmease.commons.markdown.MarkdownManager;
+import com.pmease.commons.util.StringUtils;
+
+import de.agilecoders.wicket.core.markup.html.bootstrap.common.NotificationPanel;
+
+@SuppressWarnings("serial")
+public class MarkdownPanel extends GenericPanel<String> {
+
+ private final MarkdownEditSupport editSupport;
+
+ private long lastVersion;
+
+ public MarkdownPanel(String id, IModel<String> model, @Nullable MarkdownEditSupport editSupport) {
+ super(id, model);
+
+ this.editSupport = editSupport;
+ if (editSupport != null)
+ lastVersion = editSupport.getVersion();
+ }
+
+ @Override
+ protected void onInitialize() {
+ super.onInitialize();
+
+ NotificationPanel feedback = new NotificationPanel("feedback", this);
+ feedback.setOutputMarkupPlaceholderTag(true);
+ add(feedback);
+
+ add(new Label("content", new LoadableDetachableModel<String>() {
+
+ @Override
+ protected String load() {
+ String markdown = MarkdownPanel.this.getModelObject();
+ if (markdown != null) {
+ return AppLoader.getInstance(MarkdownManager.class).parseAndProcess(markdown);
+ } else {
+ return null;
+ }
+ }
+ }).setEscapeModelStrings(false));
+
+ add(new AbstractDefaultAjaxBehavior() {
+
+ @Override
+ protected void respond(AjaxRequestTarget target) {
+ IRequestParameters params = RequestCycle.get().getRequest().getQueryParameters();
+ int taskStartIndex = params.getParameterValue("taskStartIndex").toInt();
+ boolean taskChecked = params.getParameterValue("taskChecked").toBoolean();
+ String markdown = getModelObject();
+ String beforeTask = markdown.substring(0, taskStartIndex);
+ String beforeBracket = StringUtils.substringBeforeLast(beforeTask, "[");
+ String afterBracket = StringUtils.substringAfterLast(beforeTask, "]");
+ String taskStatus = taskChecked?"x":" ";
+ String newMarkdown = beforeBracket + "[" + taskStatus + "]"
+ + afterBracket + markdown.substring(taskStartIndex);
+
+ try {
+ if (editSupport.getVersion() != lastVersion)
+ throw new StaleStateException("");
+ editSupport.setContent(newMarkdown);
+ target.add(feedback); // clear the feedback
+ } catch (StaleStateException e) {
+ warn("Some one changed the content you are editing. The content has now been "
+ + "reloaded, please try again.");
+ target.add(MarkdownPanel.this);
+ }
+ lastVersion = editSupport.getVersion();
+ }
+
+ @Override
+ public void renderHead(Component component, IHeaderResponse response) {
+ super.renderHead(component, response);
+
+ response.render(JavaScriptHeaderItem.forReference(MarkdownResourceReference.INSTANCE));
+
+ CharSequence callbackFunc = getCallbackFunction(
+ explicit("taskStartIndex"), explicit("taskChecked"));
+ String script = String.format("pmease.commons.initMarkdownViewer($('#%s>.md-preview'), %s);",
+ getMarkupId(true), editSupport!=null?callbackFunc:"undefined");
+ response.render(OnDomReadyHeaderItem.forScript(script));
+ }
+
+ });
+
+ setOutputMarkupId(true);
+ }
+
+}
diff --git a/commons.wicket/src/main/java/com/pmease/commons/wicket/websocket/DefaultWebSocketManager.java b/commons.wicket/src/main/java/com/pmease/commons/wicket/websocket/DefaultWebSocketManager.java
index 7c96586478..fe97a5469e 100644
--- a/commons.wicket/src/main/java/com/pmease/commons/wicket/websocket/DefaultWebSocketManager.java
+++ b/commons.wicket/src/main/java/com/pmease/commons/wicket/websocket/DefaultWebSocketManager.java
@@ -19,9 +19,12 @@ import org.apache.wicket.protocol.ws.api.IWebSocketConnection;
import org.apache.wicket.protocol.ws.api.registry.IWebSocketConnectionRegistry;
import org.apache.wicket.protocol.ws.api.registry.SimpleWebSocketConnectionRegistry;
import org.eclipse.jetty.websocket.api.WebSocketPolicy;
+import org.hibernate.resource.transaction.spi.TransactionStatus;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
+import com.pmease.commons.hibernate.Sessional;
+import com.pmease.commons.hibernate.dao.Dao;
import com.pmease.commons.wicket.CommonPage;
@Singleton
@@ -31,6 +34,8 @@ public class DefaultWebSocketManager implements WebSocketManager {
private final Application application;
+ private final Dao dao;
+
private final ExecutorService executorService;
private final ScheduledExecutorService scheduledExecutorService = Executors.newScheduledThreadPool(1);
@@ -42,9 +47,10 @@ public class DefaultWebSocketManager implements WebSocketManager {
private final IWebSocketConnectionRegistry connectionRegistry = new SimpleWebSocketConnectionRegistry();
@Inject
- public DefaultWebSocketManager(Application application,
+ public DefaultWebSocketManager(Application application, Dao dao,
ExecutorService executorService, WebSocketPolicy webSocketPolicy) {
this.application = application;
+ this.dao = dao;
this.executorService = executorService;
this.webSocketPolicy = webSocketPolicy;
}
@@ -62,16 +68,28 @@ public class DefaultWebSocketManager implements WebSocketManager {
}
}
+ @Sessional
@Override
public void renderAsync(WebSocketRegion region, @Nullable PageKey sourcePageKey) {
- executorService.execute(new Runnable() {
+ if (dao.getSession().getTransaction().getStatus() == TransactionStatus.ACTIVE) {
+ dao.doAsyncAfterCommit(new Runnable() {
- @Override
- public void run() {
- render(region, sourcePageKey);
- }
-
- });
+ @Override
+ public void run() {
+ render(region, sourcePageKey);
+ }
+
+ });
+ } else {
+ executorService.execute(new Runnable() {
+
+ @Override
+ public void run() {
+ render(region, sourcePageKey);
+ }
+
+ });
+ }
}
@Override
@@ -107,6 +125,16 @@ public class DefaultWebSocketManager implements WebSocketManager {
@Override
public void onConnect(WebSocketConnection connection) {
+ /*
+ * re-render interesting parts upon websocket connecting after a page is opened,
+ * this is necessary in case some web socket render request is sent between the
+ * gap of opening a page and a websocket connection is established. For instance
+ * when someone creates a pull request, the server will re-render integration
+ * preview section of the page after preview is calculated and this may happen
+ * before the web socket connection is established. Requiring the page to
+ * re-render the integration preview section after connecting will make it
+ * displaying correctly
+ */
synchronized (connection) {
try {
connection.sendMessage(INITIAL_RENDER_CALLBACK);
diff --git a/gitplex.core/src/main/java/com/pmease/gitplex/core/entity/PullRequest.java b/gitplex.core/src/main/java/com/pmease/gitplex/core/entity/PullRequest.java
index e2da3fe620..d75908b35b 100644
--- a/gitplex.core/src/main/java/com/pmease/gitplex/core/entity/PullRequest.java
+++ b/gitplex.core/src/main/java/com/pmease/gitplex/core/entity/PullRequest.java
@@ -56,8 +56,8 @@ import com.pmease.gitplex.core.event.pullrequest.PullRequestCodeCommentResolved;
import com.pmease.gitplex.core.event.pullrequest.PullRequestCodeCommentUnresolved;
import com.pmease.gitplex.core.event.pullrequest.PullRequestCodeCommented;
import com.pmease.gitplex.core.gatekeeper.checkresult.Blocking;
-import com.pmease.gitplex.core.gatekeeper.checkresult.GateCheckResult;
import com.pmease.gitplex.core.gatekeeper.checkresult.Failed;
+import com.pmease.gitplex.core.gatekeeper.checkresult.GateCheckResult;
import com.pmease.gitplex.core.gatekeeper.checkresult.Pending;
import com.pmease.gitplex.core.manager.CodeCommentRelationManager;
import com.pmease.gitplex.core.manager.PullRequestManager;
@@ -163,7 +163,7 @@ public class PullRequest extends AbstractEntity {
@Column(nullable=false)
private String baseCommitHash;
-
+
@ManyToOne(fetch=FetchType.LAZY)
private Account assignee;
@@ -229,7 +229,9 @@ public class PullRequest extends AbstractEntity {
@OneToMany(mappedBy="request", cascade=CascadeType.REMOVE)
private Collection<PullRequestWatch> watches = new ArrayList<>();
- private transient GateCheckResult gateCheckResult;
+ private transient GateCheckResult gateResult;
+
+ private transient Boolean merged;
private transient List<PullRequestUpdate> sortedUpdates;
@@ -368,10 +370,18 @@ public class PullRequest extends AbstractEntity {
this.baseCommitHash = baseCommitHash;
}
+ public String getHeadCommitHash() {
+ return getLatestUpdate().getHeadCommitHash();
+ }
+
public RevCommit getBaseCommit() {
return getTargetDepot().getRevCommit(ObjectId.fromString(getBaseCommitHash()));
}
+ public RevCommit getHeadCommit() {
+ return getTargetDepot().getRevCommit(ObjectId.fromString(getHeadCommitHash()));
+ }
+
/**
* Get unmodifiable collection of updates of this pull request. To add update
* to the pull request, call {@link this#addUpdate(PullRequestUpdate)} instead.
@@ -469,16 +479,28 @@ public class PullRequest extends AbstractEntity {
public Status getStatus() {
if (closeInfo != null) {
- if (closeInfo.getCloseStatus() == CloseInfo.Status.INTEGRATED)
+ if (closeInfo.getCloseStatus() == CloseInfo.Status.INTEGRATED) {
return Status.INTEGRATED;
- else
+ } else {
return Status.DISCARDED;
- } else if (checkGates(false) instanceof Pending || checkGates(false) instanceof Blocking)
- return Status.PENDING_APPROVAL;
- else if (checkGates(false) instanceof Failed)
- return Status.PENDING_UPDATE;
- else
- return Status.PENDING_INTEGRATE;
+ }
+ } else {
+ GateCheckResult result = checkGates(false);
+ if (result instanceof Pending || result instanceof Blocking) {
+ return Status.PENDING_APPROVAL;
+ } else if (result instanceof Failed) {
+ return Status.PENDING_INTEGRATE;
+ } else {
+ return Status.PENDING_INTEGRATE;
+ }
+ }
+ }
+
+ public GateCheckResult checkGates(boolean recheck) {
+ if (recheck || gateResult == null) {
+ gateResult = getTargetDepot().getGateKeeper().checkRequest(this);
+ }
+ return gateResult;
}
@Nullable
@@ -505,18 +527,6 @@ public class PullRequest extends AbstractEntity {
this.referentialUpdate = referentiralUpdate;
}
- /**
- * Check against gate keeper.
- *
- * @return
- * gate check result
- */
- public GateCheckResult checkGates(boolean recheck) {
- if (gateCheckResult == null || recheck)
- gateCheckResult = getTargetDepot().getGateKeeper().checkRequest(this);
- return gateCheckResult;
- }
-
/**
* Get last integration preview of this pull request. Note that this method may return an
* out dated integration preview. Refer to {@link this#getIntegrationPreview()}
@@ -759,7 +769,7 @@ public class PullRequest extends AbstractEntity {
pendingCommits = new HashSet<>();
Depot depot = getTargetDepot();
try (RevWalk revWalk = new RevWalk(depot.getRepository())) {
- revWalk.markStart(revWalk.parseCommit(ObjectId.fromString(getLatestUpdate().getHeadCommitHash())));
+ revWalk.markStart(revWalk.parseCommit(ObjectId.fromString(getHeadCommitHash())));
revWalk.markUninteresting(revWalk.parseCommit(ObjectId.fromString(getTarget().getObjectName())));
revWalk.forEach(c->pendingCommits.add(c));
} catch (IOException e) {
@@ -886,7 +896,7 @@ public class PullRequest extends AbstractEntity {
public List<CodeComment> getCodeComments() {
if (codeComments == null) {
- codeComments = GitPlex.getInstance(CodeCommentRelationManager.class).findAllCodeComments(this);
+ codeComments = GitPlex.getInstance(CodeCommentRelationManager.class).findCodeComments(this);
}
return codeComments;
}
@@ -972,9 +982,9 @@ public class PullRequest extends AbstractEntity {
}
public boolean isMerged() {
- return getTargetDepot().isMergedInto(
- getLatestUpdate().getHeadCommitHash(),
- getTarget().getObjectName());
+ if (merged == null)
+ merged = getTargetDepot().isMergedInto(getHeadCommitHash(), getTarget().getObjectName());
+ return merged;
}
public void setLastEvent(PullRequestChangeEvent event) {
diff --git a/gitplex.core/src/main/java/com/pmease/gitplex/core/entity/PullRequestUpdate.java b/gitplex.core/src/main/java/com/pmease/gitplex/core/entity/PullRequestUpdate.java
index 468d609d4a..185eabe6a6 100644
--- a/gitplex.core/src/main/java/com/pmease/gitplex/core/entity/PullRequestUpdate.java
+++ b/gitplex.core/src/main/java/com/pmease/gitplex/core/entity/PullRequestUpdate.java
@@ -1,288 +1,286 @@
-package com.pmease.gitplex.core.entity;
-
-import java.io.IOException;
-import java.util.ArrayList;
-import java.util.Collection;
-import java.util.Collections;
-import java.util.Date;
-import java.util.HashSet;
-import java.util.List;
-import java.util.Set;
-import java.util.UUID;
-
-import javax.persistence.CascadeType;
-import javax.persistence.Column;
-import javax.persistence.Entity;
-import javax.persistence.FetchType;
-import javax.persistence.Index;
-import javax.persistence.JoinColumn;
-import javax.persistence.ManyToOne;
-import javax.persistence.OneToMany;
-import javax.persistence.Table;
-
-import org.eclipse.jgit.errors.IncorrectObjectTypeException;
-import org.eclipse.jgit.errors.MissingObjectException;
-import org.eclipse.jgit.lib.ObjectId;
-import org.eclipse.jgit.lib.Repository;
-import org.eclipse.jgit.revwalk.RevCommit;
-import org.eclipse.jgit.revwalk.RevWalk;
-import org.eclipse.jgit.revwalk.filter.RevFilter;
-import org.eclipse.jgit.treewalk.TreeWalk;
-import org.eclipse.jgit.treewalk.filter.TreeFilter;
-
-import com.fasterxml.jackson.annotation.JsonProperty;
-import com.google.common.base.Preconditions;
-import com.pmease.commons.git.GitUtils;
-import com.pmease.commons.hibernate.AbstractEntity;
-import com.pmease.gitplex.core.manager.impl.DefaultCodeCommentRelationManager;
-
-@Entity
-@Table(indexes={@Index(columnList="uuid"), @Index(columnList="date")})
-public class PullRequestUpdate extends AbstractEntity {
-
- private static final long serialVersionUID = 1L;
-
- @ManyToOne(fetch=FetchType.LAZY)
- @JoinColumn(nullable=false)
- private PullRequest request;
-
- @Column(nullable=false)
- private String headCommitHash;
-
- @Column(nullable=false)
- private String mergeCommitHash;
-
- @Column(nullable=false)
- private Date date = new Date();
-
- @OneToMany(mappedBy="update", cascade=CascadeType.REMOVE)
- private Collection<PullRequestReview> reviews = new ArrayList<PullRequestReview>();
-
- @Column(nullable=false)
- private String uuid = UUID.randomUUID().toString();
-
- private transient List<RevCommit> commits;
-
- private transient Collection<String> changedFiles;
-
- public PullRequest getRequest() {
- return request;
- }
-
- public void setRequest(PullRequest request) {
- this.request = request;
- }
-
- public String getHeadCommitHash() {
- return headCommitHash;
- }
-
- public void setHeadCommitHash(String headCommitHash) {
- this.headCommitHash = headCommitHash;
- }
-
- public String getMergeCommitHash() {
- return mergeCommitHash;
- }
-
- public void setMergeCommitHash(String mergeCommitHash) {
- this.mergeCommitHash = mergeCommitHash;
- }
-
- public Date getDate() {
- return date;
- }
-
- public void setDate(Date date) {
- this.date = date;
- }
-
- public Collection<PullRequestReview> getReviews() {
- return getRequest().getReviews(this);
- }
-
- @JsonProperty
- public String getHeadRef() {
- Preconditions.checkNotNull(getId());
- return Depot.REFS_GITPLEX + "updates/" + getId();
- }
-
- /**
- * List reviews against this update and all subsequent updates.
- * <p>
- * @return
- * list of found reviews, ordered by associated updates reversely
- */
- public List<PullRequestReview> listReviewsOnwards() {
- List<PullRequestReview> reviews = new ArrayList<PullRequestReview>();
- Set<Account> excludedReviewers = new HashSet<>();
- for (PullRequestReviewInvitation invitation: getRequest().getReviewInvitations()) {
- if (invitation.getStatus() == PullRequestReviewInvitation.Status.EXCLUDED)
- excludedReviewers.add(invitation.getUser());
- }
- for (PullRequestUpdate update: getRequest().getEffectiveUpdates()) {
- for (PullRequestReview review: update.getReviews()) {
- if (!excludedReviewers.contains(review.getUser()))
- reviews.add(review);
- }
- if (update.equals(this))
- break;
- }
-
- return reviews;
- }
-
- public void deleteRefs() {
- GitUtils.deleteRef(getRequest().getTargetDepot().updateRef(getHeadRef()));
- }
-
- /**
- * Get changed files of this update since previous update. This calculation
- * excludes changes introduced by commits from target branch (this will
- * happen if some commits were merged from target branch to source branch)
- */
- public Collection<String> getChangedFiles() {
- if (changedFiles == null) {
- changedFiles = new HashSet<>();
- Repository repository = getRequest().getTargetDepot().getRepository();
- try ( RevWalk revWalk = new RevWalk(repository);
- TreeWalk treeWalk = new TreeWalk(repository)) {
- RevCommit mergeCommit = revWalk.parseCommit(ObjectId.fromString(getMergeCommitHash()));
- RevCommit baseCommit = revWalk.parseCommit(ObjectId.fromString(getBaseCommitHash()));
- RevCommit headCommit = revWalk.parseCommit(ObjectId.fromString(getHeadCommitHash()));
- revWalk.markStart(mergeCommit);
- revWalk.markStart(baseCommit);
- revWalk.setRevFilter(RevFilter.MERGE_BASE);
- RevCommit mergeBase = Preconditions.checkNotNull(revWalk.next());
- treeWalk.setRecursive(true);
- if (mergeBase.equals(baseCommit)) {
- treeWalk.addTree(mergeCommit.getTree());
- treeWalk.addTree(headCommit.getTree());
- treeWalk.setFilter(TreeFilter.ANY_DIFF);
- while (treeWalk.next())
- changedFiles.add(treeWalk.getPathString());
- } else if (mergeBase.equals(mergeCommit)) {
- treeWalk.addTree(baseCommit.getTree());
- treeWalk.addTree(headCommit.getTree());
- treeWalk.setFilter(TreeFilter.ANY_DIFF);
- while (treeWalk.next())
- changedFiles.add(treeWalk.getPathString());
- } else {
- treeWalk.addTree(headCommit.getTree());
- treeWalk.addTree(baseCommit.getTree());
- treeWalk.addTree(mergeCommit.getTree());
- treeWalk.setFilter(new TreeFilter() {
-
- @Override
- public boolean include(TreeWalk walker)
- throws MissingObjectException, IncorrectObjectTypeException, IOException {
- int m0 = walker.getRawMode(0);
-
- // only include the path if the file is modified in head commit
- // compared to base commit and that modification is not introduced
- // by commit from target branch
- return (walker.getRawMode(1) != m0 || !walker.idEqual(1, 0))
- && (walker.getRawMode(2) != m0 || !walker.idEqual(2, 0));
- }
-
- @Override
- public boolean shouldBeRecursive() {
- return false;
- }
-
- @Override
- public TreeFilter clone() {
- return this;
- }
-
- });
- while (treeWalk.next()) {
- changedFiles.add(treeWalk.getPathString());
- }
- }
- } catch (IOException e) {
- throw new RuntimeException(e);
- }
- }
- return changedFiles;
- }
-
- public String getBaseCommitHash() {
- PullRequest request = getRequest();
-
- int index = request.getSortedUpdates().indexOf(this);
- if (index > 0)
- return request.getSortedUpdates().get(index-1).getHeadCommitHash();
- else
- return request.getBaseCommitHash();
- }
-
- /**
- * Base commit represents head commit of last update, or base commit of the request
- * for the first update. Base commit is used to calculate commits belonging to
- * current update.
- *
- * @return
- * base commit of this update
- */
- public RevCommit getBaseCommit() {
- PullRequest request = getRequest();
-
- int index = request.getSortedUpdates().indexOf(this);
- if (index > 0)
- return request.getSortedUpdates().get(index-1).getHeadCommit();
- else
- return request.getBaseCommit();
- }
-
- public String getUUID() {
- return uuid;
- }
-
- public void setUUID(String uuid) {
- this.uuid = uuid;
- }
-
- /**
- * Get commits belonging to this update, reversely ordered by commit traversing. The list of commit will remain
- * unchanged even if tip of target branch changes. This assumption is key to our caching of code comment to
- * to pull request relations. Check {@link DefaultCodeCommentRelationManager#findAllCodeComments(PullRequest)} for
- * details
- *
- * @return
- * commits belonging to this update ordered by commit id
- */
- public List<RevCommit> getCommits() {
- if (commits == null) {
- commits = new ArrayList<>();
-
- try (RevWalk revWalk = new RevWalk(getRequest().getTargetDepot().getRepository())) {
- RevCommit headCommit = revWalk.parseCommit(ObjectId.fromString(getHeadCommitHash()));
- revWalk.markStart(headCommit);
- revWalk.markUninteresting(revWalk.parseCommit(ObjectId.fromString(getBaseCommitHash())));
-
- /*
- * Instead of excluding commits reachable from target branch, we exclude commits reachable
- * from the merge commit to achieve two purposes:
- * 1. commits merged back into target branch after this update can still be included in this
- * update
- * 2. commits of this update will remain unchanged even if tip of the target branch changes
- */
- revWalk.markUninteresting(revWalk.parseCommit(ObjectId.fromString(getMergeCommitHash())));
-
- revWalk.forEach(c->commits.add(c));
- if (commits.isEmpty())
- commits.add(headCommit);
- } catch (IOException e) {
- throw new RuntimeException(e);
- }
- Collections.reverse(commits);
- }
- return commits;
- }
-
- public RevCommit getHeadCommit() {
- return request.getTargetDepot().getRevCommit(ObjectId.fromString(getHeadCommitHash()));
- }
-
-}
+package com.pmease.gitplex.core.entity;
+
+import java.io.IOException;
+import java.util.ArrayList;
+import java.util.Collection;
+import java.util.Collections;
+import java.util.Date;
+import java.util.HashSet;
+import java.util.List;
+import java.util.Set;
+import java.util.UUID;
+
+import javax.persistence.CascadeType;
+import javax.persistence.Column;
+import javax.persistence.Entity;
+import javax.persistence.FetchType;
+import javax.persistence.Index;
+import javax.persistence.JoinColumn;
+import javax.persistence.ManyToOne;
+import javax.persistence.OneToMany;
+import javax.persistence.Table;
+
+import org.eclipse.jgit.errors.IncorrectObjectTypeException;
+import org.eclipse.jgit.errors.MissingObjectException;
+import org.eclipse.jgit.lib.ObjectId;
+import org.eclipse.jgit.lib.Repository;
+import org.eclipse.jgit.revwalk.RevCommit;
+import org.eclipse.jgit.revwalk.RevWalk;
+import org.eclipse.jgit.revwalk.filter.RevFilter;
+import org.eclipse.jgit.treewalk.TreeWalk;
+import org.eclipse.jgit.treewalk.filter.TreeFilter;
+
+import com.fasterxml.jackson.annotation.JsonProperty;
+import com.google.common.base.Preconditions;
+import com.pmease.commons.git.GitUtils;
+import com.pmease.commons.hibernate.AbstractEntity;
+import com.pmease.gitplex.core.manager.impl.DefaultCodeCommentRelationManager;
+
+@Entity
+@Table(indexes={@Index(columnList="uuid"), @Index(columnList="date")})
+public class PullRequestUpdate extends AbstractEntity {
+
+ private static final long serialVersionUID = 1L;
+
+ @ManyToOne(fetch=FetchType.LAZY)
+ @JoinColumn(nullable=false)
+ private PullRequest request;
+
+ @Column(nullable=false)
+ private String headCommitHash;
+
+ @Column(nullable=false)
+ private String mergeCommitHash;
+
+ @Column(nullable=false)
+ private Date date = new Date();
+
+ @OneToMany(mappedBy="update", cascade=CascadeType.REMOVE)
+ private Collection<PullRequestReview> reviews = new ArrayList<PullRequestReview>();
+
+ @Column(nullable=false)
+ private String uuid = UUID.randomUUID().toString();
+
+ private transient List<RevCommit> commits;
+
+ private transient Collection<String> changedFiles;
+
+ public PullRequest getRequest() {
+ return request;
+ }
+
+ public void setRequest(PullRequest request) {
+ this.request = request;
+ }
+
+ public String getHeadCommitHash() {
+ return headCommitHash;
+ }
+
+ public void setHeadCommitHash(String headCommitHash) {
+ this.headCommitHash = headCommitHash;
+ }
+
+ public String getMergeCommitHash() {
+ return mergeCommitHash;
+ }
+
+ public void setMergeCommitHash(String mergeCommitHash) {
+ this.mergeCommitHash = mergeCommitHash;
+ }
+
+ public Date getDate() {
+ return date;
+ }
+
+ public void setDate(Date date) {
+ this.date = date;
+ }
+
+ public Collection<PullRequestReview> getReviews() {
+ return getRequest().getReviews(this);
+ }
+
+ @JsonProperty
+ public String getHeadRef() {
+ Preconditions.checkNotNull(getId());
+ return Depot.REFS_GITPLEX + "updates/" + getId();
+ }
+
+ /**
+ * List reviews against this update and all subsequent updates.
+ * <p>
+ * @return
+ * list of found reviews, ordered by associated updates reversely
+ */
+ public List<PullRequestReview> listReviewsOnwards() {
+ List<PullRequestReview> reviews = new ArrayList<PullRequestReview>();
+ Set<Account> excludedReviewers = new HashSet<>();
+ for (PullRequestReviewInvitation invitation: getRequest().getReviewInvitations()) {
+ if (invitation.getStatus() == PullRequestReviewInvitation.Status.EXCLUDED)
+ excludedReviewers.add(invitation.getUser());
+ }
+ for (PullRequestUpdate update: getRequest().getEffectiveUpdates()) {
+ for (PullRequestReview review: update.getReviews()) {
+ if (!excludedReviewers.contains(review.getUser()))
+ reviews.add(review);
+ }
+ if (update.equals(this))
+ break;
+ }
+
+ return reviews;
+ }
+
+ public void deleteRefs() {
+ GitUtils.deleteRef(getRequest().getTargetDepot().updateRef(getHeadRef()));
+ }
+
+ /**
+ * Get changed files of this update since previous update. This calculation
+ * excludes changes introduced by commits from target branch (this will
+ * happen if some commits were merged from target branch to source branch)
+ */
+ public Collection<String> getChangedFiles() {
+ if (changedFiles == null) {
+ changedFiles = new HashSet<>();
+ Repository repository = getRequest().getTargetDepot().getRepository();
+ try ( RevWalk revWalk = new RevWalk(repository);
+ TreeWalk treeWalk = new TreeWalk(repository)) {
+ RevCommit mergeCommit = revWalk.parseCommit(ObjectId.fromString(getMergeCommitHash()));
+ RevCommit baseCommit = revWalk.parseCommit(ObjectId.fromString(getBaseCommitHash()));
+ RevCommit headCommit = revWalk.parseCommit(ObjectId.fromString(getHeadCommitHash()));
+ revWalk.markStart(mergeCommit);
+ revWalk.markStart(baseCommit);
+ revWalk.setRevFilter(RevFilter.MERGE_BASE);
+ RevCommit mergeBase = Preconditions.checkNotNull(revWalk.next());
+ treeWalk.setRecursive(true);
+ if (mergeBase.equals(baseCommit)) {
+ treeWalk.addTree(mergeCommit.getTree());
+ treeWalk.addTree(headCommit.getTree());
+ treeWalk.setFilter(TreeFilter.ANY_DIFF);
+ while (treeWalk.next())
+ changedFiles.add(treeWalk.getPathString());
+ } else if (mergeBase.equals(mergeCommit)) {
+ treeWalk.addTree(baseCommit.getTree());
+ treeWalk.addTree(headCommit.getTree());
+ treeWalk.setFilter(TreeFilter.ANY_DIFF);
+ while (treeWalk.next())
+ changedFiles.add(treeWalk.getPathString());
+ } else {
+ treeWalk.addTree(headCommit.getTree());
+ treeWalk.addTree(baseCommit.getTree());
+ treeWalk.addTree(mergeCommit.getTree());
+ treeWalk.setFilter(new TreeFilter() {
+
+ @Override
+ public boolean include(TreeWalk walker)
+ throws MissingObjectException, IncorrectObjectTypeException, IOException {
+ int m0 = walker.getRawMode(0);
+
+ // only include the path if the file is modified in head commit
+ // compared to base commit and that modification is not introduced
+ // by commit from target branch
+ return (walker.getRawMode(1) != m0 || !walker.idEqual(1, 0))
+ && (walker.getRawMode(2) != m0 || !walker.idEqual(2, 0));
+ }
+
+ @Override
+ public boolean shouldBeRecursive() {
+ return false;
+ }
+
+ @Override
+ public TreeFilter clone() {
+ return this;
+ }
+
+ });
+ while (treeWalk.next()) {
+ changedFiles.add(treeWalk.getPathString());
+ }
+ }
+ } catch (IOException e) {
+ throw new RuntimeException(e);
+ }
+ }
+ return changedFiles;
+ }
+
+ public String getBaseCommitHash() {
+ PullRequest request = getRequest();
+
+ int index = request.getSortedUpdates().indexOf(this);
+ if (index > 0)
+ return request.getSortedUpdates().get(index-1).getHeadCommitHash();
+ else
+ return request.getBaseCommitHash();
+ }
+
+ /**
+ * Base commit represents head commit of last update, or base commit of the request
+ * for the first update. Base commit is used to calculate commits belonging to
+ * current update.
+ *
+ * @return
+ * base commit of this update
+ */
+ public RevCommit getBaseCommit() {
+ PullRequest request = getRequest();
+
+ int index = request.getSortedUpdates().indexOf(this);
+ if (index > 0)
+ return request.getSortedUpdates().get(index-1).getHeadCommit();
+ else
+ return request.getBaseCommit();
+ }
+
+ public String getUUID() {
+ return uuid;
+ }
+
+ public void setUUID(String uuid) {
+ this.uuid = uuid;
+ }
+
+ /**
+ * Get commits belonging to this update, reversely ordered by commit traversing. The list of commit will remain
+ * unchanged even if tip of target branch changes. This assumption is key to our caching of code comment to
+ * to pull request relations. Check {@link DefaultCodeCommentRelationManager#findCodeComments(PullRequest)} for
+ * details
+ *
+ * @return
+ * commits belonging to this update ordered by commit id
+ */
+ public List<RevCommit> getCommits() {
+ if (commits == null) {
+ commits = new ArrayList<>();
+
+ try (RevWalk revWalk = new RevWalk(getRequest().getTargetDepot().getRepository())) {
+ RevCommit headCommit = revWalk.parseCommit(ObjectId.fromString(getHeadCommitHash()));
+ revWalk.markStart(headCommit);
+ revWalk.markUninteresting(revWalk.parseCommit(ObjectId.fromString(getBaseCommitHash())));
+
+ /*
+ * Instead of excluding commits reachable from target branch, we exclude commits reachable
+ * from the merge commit to achieve two purposes:
+ * 1. commits merged back into target branch after this update can still be included in this
+ * update
+ * 2. commits of this update will remain unchanged even if tip of the target branch changes
+ */
+ revWalk.markUninteresting(revWalk.parseCommit(ObjectId.fromString(getMergeCommitHash())));
+
+ revWalk.forEach(c->commits.add(c));
+ } catch (IOException e) {
+ throw new RuntimeException(e);
+ }
+ Collections.reverse(commits);
+ }
+ return commits;
+ }
+
+ public RevCommit getHeadCommit() {
+ return request.getTargetDepot().getRevCommit(ObjectId.fromString(getHeadCommitHash()));
+ }
+
+}
diff --git a/gitplex.core/src/main/java/com/pmease/gitplex/core/entity/support/IntegrationPreview.java b/gitplex.core/src/main/java/com/pmease/gitplex/core/entity/support/IntegrationPreview.java
index 8e33bdea9b..d02301636d 100644
--- a/gitplex.core/src/main/java/com/pmease/gitplex/core/entity/support/IntegrationPreview.java
+++ b/gitplex.core/src/main/java/com/pmease/gitplex/core/entity/support/IntegrationPreview.java
@@ -79,7 +79,7 @@ public class IntegrationPreview implements Serializable {
}
public boolean isObsolete(PullRequest request) {
- if (getRequestHead().equals(request.getLatestUpdate().getHeadCommitHash())
+ if (getRequestHead().equals(request.getHeadCommitHash())
&& getTargetHead().equals(request.getTarget().getObjectName())
&& getIntegrationStrategy() == request.getIntegrationStrategy()
&& (getIntegrated() == null || ObjectId.fromString(getIntegrated()).equals((request.getTargetDepot().getObjectId(request.getIntegrateRef(), false))))) {
diff --git a/gitplex.core/src/main/java/com/pmease/gitplex/core/gatekeeper/IfSubmitWithGerritStylePatch.java b/gitplex.core/src/main/java/com/pmease/gitplex/core/gatekeeper/IfSubmitWithGerritStylePatch.java
index 1e8c726680..fc70d4dd60 100644
--- a/gitplex.core/src/main/java/com/pmease/gitplex/core/gatekeeper/IfSubmitWithGerritStylePatch.java
+++ b/gitplex.core/src/main/java/com/pmease/gitplex/core/gatekeeper/IfSubmitWithGerritStylePatch.java
@@ -24,7 +24,7 @@ public class IfSubmitWithGerritStylePatch extends AbstractGateKeeper {
@Override
protected GateCheckResult doCheckRequest(PullRequest request) {
String branchHead = request.getBaseCommitHash();
- String requestHead = request.getLatestUpdate().getHeadCommitHash();
+ String requestHead = request.getHeadCommitHash();
Depot depot = request.getTargetDepot();
try (RevWalk revWalk = new RevWalk(depot.getRepository())) {
RevCommit requestHeadCommit = revWalk.parseCommit(depot.getObjectId(requestHead));
diff --git a/gitplex.core/src/main/java/com/pmease/gitplex/core/gatekeeper/IfTouchSpecifiedFiles.java b/gitplex.core/src/main/java/com/pmease/gitplex/core/gatekeeper/IfTouchSpecifiedFiles.java
index 30b62b7dba..0f5fa8ab6d 100644
--- a/gitplex.core/src/main/java/com/pmease/gitplex/core/gatekeeper/IfTouchSpecifiedFiles.java
+++ b/gitplex.core/src/main/java/com/pmease/gitplex/core/gatekeeper/IfTouchSpecifiedFiles.java
@@ -76,8 +76,8 @@ public class IfTouchSpecifiedFiles extends AbstractGateKeeper {
protected GateCheckResult doCheckPush(Account user, Depot depot, String refName, ObjectId oldCommit, ObjectId newCommit) {
if (!oldCommit.equals(ObjectId.zeroId()) && !newCommit.equals(ObjectId.zeroId())) {
try (TreeWalk treeWalk = new TreeWalk(depot.getRepository())) {
- treeWalk.addTree(depot.getRevCommit(oldCommit));
- treeWalk.addTree(depot.getRevCommit(newCommit));
+ treeWalk.addTree(depot.getRevCommit(oldCommit).getTree());
+ treeWalk.addTree(depot.getRevCommit(newCommit).getTree());
while (treeWalk.next()) {
if (matches(treeWalk.getPathString()))
return passed(Lists.newArrayList("Touched files match '" + pathMatch + "'"));
diff --git a/gitplex.core/src/main/java/com/pmease/gitplex/core/gatekeeper/IfVerifiedByBuilds.java b/gitplex.core/src/main/java/com/pmease/gitplex/core/gatekeeper/IfVerifiedByBuilds.java
index cc723987e9..5978359134 100644
--- a/gitplex.core/src/main/java/com/pmease/gitplex/core/gatekeeper/IfVerifiedByBuilds.java
+++ b/gitplex.core/src/main/java/com/pmease/gitplex/core/gatekeeper/IfVerifiedByBuilds.java
@@ -85,7 +85,7 @@ public class IfVerifiedByBuilds extends AbstractGateKeeper {
if (commit == null)
return failed(Lists.newArrayList("Can not build against integration result due to conflicts"));
} else {
- commit = request.getLatestUpdate().getHeadCommitHash();
+ commit = request.getHeadCommitHash();
}
PullRequestVerificationManager verificationManager = GitPlex.getInstance(PullRequestVerificationManager.class);
diff --git a/gitplex.core/src/main/java/com/pmease/gitplex/core/manager/CodeCommentRelationManager.java b/gitplex.core/src/main/java/com/pmease/gitplex/core/manager/CodeCommentRelationManager.java
index 0993e23bf7..bce6a46d43 100644
--- a/gitplex.core/src/main/java/com/pmease/gitplex/core/manager/CodeCommentRelationManager.java
+++ b/gitplex.core/src/main/java/com/pmease/gitplex/core/manager/CodeCommentRelationManager.java
@@ -1,17 +1,17 @@
-package com.pmease.gitplex.core.manager;
-
-import java.util.List;
-
-import com.pmease.commons.hibernate.dao.EntityManager;
-import com.pmease.gitplex.core.entity.CodeComment;
-import com.pmease.gitplex.core.entity.CodeCommentRelation;
-import com.pmease.gitplex.core.entity.PullRequest;
-
-public interface CodeCommentRelationManager extends EntityManager<CodeCommentRelation> {
-
- /**
- * Get code comments related to specified pull request, ordered by id descendantly
- */
- List<CodeComment> findAllCodeComments(PullRequest request);
-
-}
+package com.pmease.gitplex.core.manager;
+
+import java.util.List;
+
+import com.pmease.commons.hibernate.dao.EntityManager;
+import com.pmease.gitplex.core.entity.CodeComment;
+import com.pmease.gitplex.core.entity.CodeCommentRelation;
+import com.pmease.gitplex.core.entity.PullRequest;
+
+public interface CodeCommentRelationManager extends EntityManager<CodeCommentRelation> {
+
+ /**
+ * Get code comments related to specified pull request, ordered by id descendantly
+ */
+ List<CodeComment> findCodeComments(PullRequest request);
+
+}
diff --git a/gitplex.core/src/main/java/com/pmease/gitplex/core/manager/PullRequestManager.java b/gitplex.core/src/main/java/com/pmease/gitplex/core/manager/PullRequestManager.java
index 9bc66d4dff..42f6e3e3b0 100644
--- a/gitplex.core/src/main/java/com/pmease/gitplex/core/manager/PullRequestManager.java
+++ b/gitplex.core/src/main/java/com/pmease/gitplex/core/manager/PullRequestManager.java
@@ -1,83 +1,79 @@
-package com.pmease.gitplex.core.manager;
-
-import java.util.Collection;
-import java.util.List;
-
-import javax.annotation.Nullable;
-
-import com.pmease.commons.hibernate.dao.EntityManager;
-import com.pmease.gitplex.core.entity.Depot;
-import com.pmease.gitplex.core.entity.PullRequest;
-import com.pmease.gitplex.core.entity.PullRequest.IntegrationStrategy;
-import com.pmease.gitplex.core.entity.support.DepotAndBranch;
-import com.pmease.gitplex.core.entity.support.IntegrationPreview;
-
-public interface PullRequestManager extends EntityManager<PullRequest> {
-
- @Nullable
- PullRequest findOpen(DepotAndBranch target, DepotAndBranch source);
-
- Collection<PullRequest> findAllOpenTo(DepotAndBranch target, @Nullable Depot sourceDepot);
-
- Collection<PullRequest> findAllOpenFrom(DepotAndBranch source, @Nullable Depot targetDepot);
-
- Collection<PullRequest> findAllOpen(DepotAndBranch sourceOrTarget);
-
- @Nullable
- PullRequest find(Depot target, long number);
-
- @Nullable
- PullRequest find(String uuid);
-
- boolean canIntegrate(PullRequest request);
-
- /**
- * Integrate specified pull request.
- *
- * @param request
- * pull request to be integrated
- * @param note
- * comment for the integration
- */
- void integrate(PullRequest request, @Nullable String note);
-
- void discard(PullRequest request, @Nullable String note);
-
- void reopen(PullRequest request, @Nullable String note);
-
- void changeAssignee(PullRequest request);
-
- void check(PullRequest request);
-
- /**
- * Preview integration of this pull request.
- *
- * @param request
- * pull request to preview integration of
- * @return
- * integration preview, or <tt>null</tt> if preview is being calculating
- */
- IntegrationPreview previewIntegration(PullRequest request);
-
- /**
- * Delete git refs of this pull request and all its updates.
- *
- * @param request
- * pull request whose git refs and update refs to be deleted
- */
- void deleteRefs(PullRequest request);
-
- void open(PullRequest request);
-
- void delete(PullRequest request);
-
- List<IntegrationStrategy> getApplicableIntegrationStrategies(PullRequest request);
-
- void deleteSourceBranch(PullRequest request, @Nullable String note);
-
- void restoreSourceBranch(PullRequest request, @Nullable String note);
-
- void checkSanity();
-
- int countOpen(Depot depot);
-}
+package com.pmease.gitplex.core.manager;
+
+import java.util.Collection;
+import java.util.List;
+
+import javax.annotation.Nullable;
+
+import com.pmease.commons.hibernate.dao.EntityManager;
+import com.pmease.gitplex.core.entity.Depot;
+import com.pmease.gitplex.core.entity.PullRequest;
+import com.pmease.gitplex.core.entity.PullRequest.IntegrationStrategy;
+import com.pmease.gitplex.core.entity.support.DepotAndBranch;
+import com.pmease.gitplex.core.entity.support.IntegrationPreview;
+
+public interface PullRequestManager extends EntityManager<PullRequest> {
+
+ @Nullable
+ PullRequest findOpen(DepotAndBranch target, DepotAndBranch source);
+
+ Collection<PullRequest> findAllOpenTo(DepotAndBranch target, @Nullable Depot sourceDepot);
+
+ Collection<PullRequest> findAllOpenFrom(DepotAndBranch source, @Nullable Depot targetDepot);
+
+ Collection<PullRequest> findAllOpen(DepotAndBranch sourceOrTarget);
+
+ @Nullable
+ PullRequest find(Depot target, long number);
+
+ @Nullable
+ PullRequest find(String uuid);
+
+ /**
+ * Integrate specified pull request.
+ *
+ * @param request
+ * pull request to be integrated
+ * @param note
+ * comment for the integration
+ */
+ void integrate(PullRequest request, @Nullable String note);
+
+ void discard(PullRequest request, @Nullable String note);
+
+ void reopen(PullRequest request, @Nullable String note);
+
+ void changeAssignee(PullRequest request);
+
+ void check(PullRequest request);
+
+ /**
+ * Preview integration of this pull request.
+ *
+ * @param request
+ * pull request to preview integration of
+ * @return
+ * integration preview, or <tt>null</tt> if preview is being calculating
+ */
+ IntegrationPreview previewIntegration(PullRequest request);
+
+ /**
+ * Delete git refs of this pull request and all its updates.
+ *
+ * @param request
+ * pull request whose git refs and update refs to be deleted
+ */
+ void deleteRefs(PullRequest request);
+
+ void open(PullRequest request);
+
+ void delete(PullRequest request);
+
+ List<IntegrationStrategy> getApplicableIntegrationStrategies(PullRequest request);
+
+ void deleteSourceBranch(PullRequest request, @Nullable String note);
+
+ void restoreSourceBranch(PullRequest request, @Nullable String note);
+
+ int countOpen(Depot depot);
+}
diff --git a/gitplex.core/src/main/java/com/pmease/gitplex/core/manager/PullRequestUpdateManager.java b/gitplex.core/src/main/java/com/pmease/gitplex/core/manager/PullRequestUpdateManager.java
index 7b004670c7..230d15ca40 100644
--- a/gitplex.core/src/main/java/com/pmease/gitplex/core/manager/PullRequestUpdateManager.java
+++ b/gitplex.core/src/main/java/com/pmease/gitplex/core/manager/PullRequestUpdateManager.java
@@ -10,7 +10,14 @@ import com.pmease.gitplex.core.entity.PullRequestUpdate;
public interface PullRequestUpdateManager extends EntityManager<PullRequestUpdate> {
- void save(PullRequestUpdate update, boolean callListeners);
+ /**
+ * @param update
+ * update to be saved
+ * @param independent
+ * whether or not this update is an independent update. An independent update is
+ * not created as result of other actions such as open and integrate
+ */
+ void save(PullRequestUpdate update, boolean independent);
@Nullable
PullRequestUpdate find(String uuid);
diff --git a/gitplex.core/src/main/java/com/pmease/gitplex/core/manager/impl/DefaultCodeCommentRelationManager.java b/gitplex.core/src/main/java/com/pmease/gitplex/core/manager/impl/DefaultCodeCommentRelationManager.java
index 74c97708cf..2fee494054 100644
--- a/gitplex.core/src/main/java/com/pmease/gitplex/core/manager/impl/DefaultCodeCommentRelationManager.java
+++ b/gitplex.core/src/main/java/com/pmease/gitplex/core/manager/impl/DefaultCodeCommentRelationManager.java
@@ -1,12 +1,12 @@
package com.pmease.gitplex.core.manager.impl;
-import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
+import java.util.stream.Collectors;
import javax.inject.Inject;
import javax.inject.Singleton;
@@ -74,7 +74,7 @@ public class DefaultCodeCommentRelationManager extends AbstractEntityManager<Cod
*/
@Transactional
@Override
- public List<CodeComment> findAllCodeComments(PullRequest request) {
+ public List<CodeComment> findCodeComments(PullRequest request) {
if (request.getCodeCommentRelations().size() < PullRequest.MAX_CODE_COMMENTS) {
Collection<String> relatedComments = new HashSet<>();
for (CodeCommentRelation relation: request.getCodeCommentRelations()) {
@@ -117,19 +117,16 @@ public class DefaultCodeCommentRelationManager extends AbstractEntityManager<Cod
}
}
}
-
- }
-
- List<CodeComment> comments = new ArrayList<>();
- for (CodeCommentRelation relation: request.getCodeCommentRelations()) {
- comments.add(relation.getComment());
}
- comments.sort(CodeComment::compareTo);
- Collections.reverse(comments);
-
+ List<CodeComment> comments = request.getCodeCommentRelations()
+ .stream()
+ .map(CodeCommentRelation::getComment)
+ .sorted(CodeComment::compareTo)
+ .collect(Collectors.toList());
+ Collections.reverse(comments);
return comments;
}
-
+
@Transactional
@Override
public void save(CodeCommentRelation entity) {
diff --git a/gitplex.core/src/main/java/com/pmease/gitplex/core/manager/impl/DefaultDepotManager.java b/gitplex.core/src/main/java/com/pmease/gitplex/core/manager/impl/DefaultDepotManager.java
index a4342eef77..1fd5f3b12a 100644
--- a/gitplex.core/src/main/java/com/pmease/gitplex/core/manager/impl/DefaultDepotManager.java
+++ b/gitplex.core/src/main/java/com/pmease/gitplex/core/manager/impl/DefaultDepotManager.java
@@ -1,460 +1,453 @@
-package com.pmease.gitplex.core.manager.impl;
-
-import java.io.File;
-import java.io.IOException;
-import java.io.InputStream;
-import java.util.Collection;
-import java.util.HashSet;
-import java.util.Iterator;
-import java.util.Map;
-import java.util.Set;
-import java.util.concurrent.ConcurrentHashMap;
-import java.util.concurrent.locks.ReadWriteLock;
-import java.util.concurrent.locks.ReentrantReadWriteLock;
-import java.util.stream.Collectors;
-
-import javax.inject.Inject;
-import javax.inject.Singleton;
-
-import org.apache.commons.io.IOUtils;
-import org.eclipse.jgit.api.Git;
-import org.eclipse.jgit.internal.storage.file.FileRepository;
-import org.eclipse.jgit.lib.ObjectId;
-import org.eclipse.jgit.lib.Repository;
-import org.hibernate.Query;
-import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
-
-import com.google.common.base.Preconditions;
-import com.google.common.base.Throwables;
-import com.google.common.collect.BiMap;
-import com.google.common.collect.HashBiMap;
-import com.pmease.commons.git.GitUtils;
-import com.pmease.commons.git.command.CloneCommand;
-import com.pmease.commons.hibernate.Sessional;
-import com.pmease.commons.hibernate.Transactional;
-import com.pmease.commons.hibernate.dao.AbstractEntityManager;
-import com.pmease.commons.hibernate.dao.Dao;
-import com.pmease.commons.loader.Listen;
-import com.pmease.commons.loader.ListenerRegistry;
-import com.pmease.commons.util.FileUtils;
-import com.pmease.commons.util.Pair;
-import com.pmease.commons.util.StringUtils;
-import com.pmease.gitplex.core.GitPlex;
-import com.pmease.gitplex.core.entity.Account;
-import com.pmease.gitplex.core.entity.Depot;
-import com.pmease.gitplex.core.entity.Team;
-import com.pmease.gitplex.core.entity.TeamAuthorization;
-import com.pmease.gitplex.core.entity.support.IntegrationPolicy;
-import com.pmease.gitplex.core.event.RefUpdated;
-import com.pmease.gitplex.core.event.depot.DepotDeleted;
-import com.pmease.gitplex.core.event.depot.DepotRenamed;
-import com.pmease.gitplex.core.event.depot.DepotTransferred;
-import com.pmease.gitplex.core.event.lifecycle.SystemStarted;
-import com.pmease.gitplex.core.event.lifecycle.SystemStarting;
-import com.pmease.gitplex.core.event.lifecycle.SystemStopping;
-import com.pmease.gitplex.core.gatekeeper.GateKeeper;
-import com.pmease.gitplex.core.manager.AccountManager;
-import com.pmease.gitplex.core.manager.CodeCommentInfoManager;
-import com.pmease.gitplex.core.manager.CommitInfoManager;
-import com.pmease.gitplex.core.manager.DepotManager;
-import com.pmease.gitplex.core.manager.PullRequestInfoManager;
-import com.pmease.gitplex.core.manager.PullRequestManager;
-import com.pmease.gitplex.core.manager.StorageManager;
-import com.pmease.gitplex.core.manager.TeamAuthorizationManager;
-import com.pmease.gitplex.core.security.privilege.DepotPrivilege;
-
-@Singleton
-public class DefaultDepotManager extends AbstractEntityManager<Depot> implements DepotManager {
-
- private static final Logger logger = LoggerFactory.getLogger(DefaultDepotManager.class);
-
- private final ListenerRegistry listenerRegistry;
-
- private final StorageManager storageManager;
-
- private final AccountManager userManager;
-
- private final CommitInfoManager commitInfoManager;
-
- private final PullRequestInfoManager pullRequestInfoManager;
-
- private final CodeCommentInfoManager codeCommentInfoManager;
-
- private final PullRequestManager pullRequestManager;
-
- private final TeamAuthorizationManager teamAuthorizationManager;
-
- private final String gitReceiveHook;
-
- private final BiMap<Pair<Long, String>, Long> nameToId = HashBiMap.create();
-
- private final ReadWriteLock idLock = new ReentrantReadWriteLock();
-
- private final Map<Long, Repository> repositoryCache = new ConcurrentHashMap<>();
-
- @Inject
- public DefaultDepotManager(Dao dao, AccountManager userManager, CodeCommentInfoManager codeCommentInfoManager,
- TeamAuthorizationManager teamAuthorizationManager, PullRequestInfoManager pullRequestInfoManager,
- StorageManager storageManager, CommitInfoManager commitInfoManager,
- PullRequestManager pullRequestManager, ListenerRegistry listenerRegistry) {
- super(dao);
-
- this.storageManager = storageManager;
- this.userManager = userManager;
- this.pullRequestInfoManager = pullRequestInfoManager;
- this.teamAuthorizationManager = teamAuthorizationManager;
- this.commitInfoManager = commitInfoManager;
- this.codeCommentInfoManager = codeCommentInfoManager;
- this.pullRequestManager = pullRequestManager;
- this.listenerRegistry = listenerRegistry;
-
- try (InputStream is = getClass().getClassLoader().getResourceAsStream("git-receive-hook")) {
- Preconditions.checkNotNull(is);
- gitReceiveHook = StringUtils.join(IOUtils.readLines(is), "\n");
- } catch (IOException e) {
- throw new RuntimeException(e);
- }
-
- }
-
- @Override
- public Repository getRepository(Depot depot) {
- Repository repository = repositoryCache.get(depot.getId());
- if (repository == null) {
- synchronized (repositoryCache) {
- repository = repositoryCache.get(depot.getId());
- if (repository == null) {
- try {
- repository = new FileRepository(depot.getDirectory());
- } catch (IOException e) {
- throw new RuntimeException(e);
- }
- repositoryCache.put(depot.getId(), repository);
- }
- }
- }
- return repository;
- }
-
- @Transactional
- @Override
- public void save(Depot depot, Long oldAccountId, String oldName) {
- Preconditions.checkArgument(oldAccountId==null || oldName==null,
- "Can not rename and transfer depot in the same time");
-
- boolean isNew = depot.isNew();
-
- dao.persist(depot);
-
- if (oldAccountId != null && !depot.getAccount().getId().equals(oldAccountId)) {
- Account oldAccount = userManager.load(oldAccountId);
- listenerRegistry.post(new DepotTransferred(depot, oldAccount));
-
- for (Depot each: findAll()) {
- for (IntegrationPolicy policy: each.getIntegrationPolicies()) {
- policy.onDepotTransfer(depot, oldAccount);
- }
- for (Iterator<GateKeeper> it = each.getGateKeepers().iterator(); it.hasNext();) {
- if (it.next().onDepotTransfer(each, depot, oldAccount))
- it.remove();
- }
- }
- }
- if (oldName != null && !depot.getName().equals(oldName)) {
- listenerRegistry.post(new DepotRenamed(depot, oldName));
-
- for (Depot each: findAll()) {
- for (IntegrationPolicy integrationPolicy: each.getIntegrationPolicies()) {
- integrationPolicy.onDepotRename(depot.getAccount(), oldName, depot.getName());
- }
- for (GateKeeper gateKeeper: each.getGateKeepers()) {
- gateKeeper.onDepotRename(depot, oldName);
- }
- }
- }
-
- doAfterCommit(new Runnable() {
-
- @Override
- public void run() {
- idLock.writeLock().lock();
- try {
- nameToId.inverse().put(depot.getId(), new Pair<>(depot.getAccount().getId(), depot.getName()));
- } finally {
- idLock.writeLock().unlock();
- }
- if (isNew) {
- checkSanity(depot);
- commitInfoManager.collect(depot);
- }
- }
-
- });
- }
-
- @Transactional
- @Override
- public void delete(Depot depot) {
- Query query = getSession().createQuery("update Depot set forkedFrom=null where forkedFrom=:forkedFrom");
- query.setParameter("forkedFrom", depot);
- query.executeUpdate();
-
- dao.remove(depot);
-
- for (Depot each: findAll()) {
- for (Iterator<IntegrationPolicy> it = each.getIntegrationPolicies().iterator(); it.hasNext();) {
- if (it.next().onDepotDelete(depot))
- it.remove();
- }
- for (Iterator<GateKeeper> it = each.getGateKeepers().iterator(); it.hasNext();) {
- if (it.next().onDepotDelete(depot))
- it.remove();
- }
- }
-
- doAfterCommit(new Runnable() {
-
- @Override
- public void run() {
- idLock.writeLock().lock();
- try {
- nameToId.inverse().remove(depot.getId());
- } finally {
- idLock.writeLock().unlock();
- }
- getRepository(depot).close();
- repositoryCache.remove(depot.getId());
-
- FileUtils.deleteDir(storageManager.getGitDir(depot));
- }
-
- });
-
- listenerRegistry.post(new DepotDeleted(depot));
- }
-
- @Sessional
- @Override
- public Depot find(String accountName, String depotName) {
- Account user = userManager.find(accountName);
- if (user != null)
- return find(user, depotName);
- else
- return null;
- }
-
- @Sessional
- @Override
- public Depot find(Account account, String depotName) {
- idLock.readLock().lock();
- try {
- Long id = nameToId.get(new Pair<>(account.getId(), depotName));
- if (id != null)
- return load(id);
- else
- return null;
- } finally {
- idLock.readLock().unlock();
- }
- }
-
- @Sessional
- @Override
- public Depot find(String depotFQN) {
- String userName = StringUtils.substringBefore(depotFQN, Depot.FQN_SEPARATOR);
- Account user = userManager.find(userName);
- if (user != null)
- return find(user, StringUtils.substringAfter(depotFQN, Depot.FQN_SEPARATOR));
- else
- return null;
- }
-
- @Transactional
- @Override
- public Depot fork(Depot depot, Account user) {
- if (depot.getAccount().equals(user))
- return depot;
-
- Depot forked = null;
- for (Depot each: user.getDepots()) {
- if (depot.equals(each.getForkedFrom())) {
- forked = each;
- break;
- }
- }
- if (forked == null) {
- Set<String> existingNames = new HashSet<>();
- for (Depot each: user.getDepots())
- existingNames.add(each.getName());
-
- forked = new Depot();
- forked.setAccount(user);
- forked.setForkedFrom(depot);
- if (existingNames.contains(depot.getName())) {
- int suffix = 1;
- while (existingNames.contains(depot.getName() + "_" + suffix))
- suffix++;
- forked.setName(depot.getName() + "_" + suffix);
- } else {
- forked.setName(depot.getName());
- }
-
- dao.persist(forked);
-
- FileUtils.cleanDir(forked.getDirectory());
- new CloneCommand(forked.getDirectory()).bare(true).from(depot.getDirectory().getAbsolutePath()).call();
- }
-
- return forked;
- }
-
- private void checkSanity(Depot depot) {
- logger.info("Checking sanity of repository '{}'...", depot);
-
- File gitDir = depot.getDirectory();
- if (depot.getDirectory().exists() && !GitUtils.isValid(gitDir)) {
- logger.warn("Directory '" + gitDir + "' is not a valid git repository, removing...");
- FileUtils.deleteDir(gitDir);
- }
-
- if (!gitDir.exists()) {
- logger.warn("Initializing git repository in '" + gitDir + "'...");
- FileUtils.createDir(gitDir);
- try {
- Git.init().setDirectory(gitDir).setBare(true).call();
- } catch (Exception e) {
- Throwables.propagate(e);
- }
- }
-
- if (!depot.isValid()) {
- File hooksDir = new File(gitDir, "hooks");
-
- File gitPreReceiveHookFile = new File(hooksDir, "pre-receive");
- FileUtils.writeFile(gitPreReceiveHookFile, String.format(gitReceiveHook, "git-prereceive-callback"));
- gitPreReceiveHookFile.setExecutable(true);
-
- File gitPostReceiveHookFile = new File(hooksDir, "post-receive");
- FileUtils.writeFile(gitPostReceiveHookFile, String.format(gitReceiveHook, "git-postreceive-callback"));
- gitPostReceiveHookFile.setExecutable(true);
- }
- }
-
- @Sessional
- @Listen
- public void on(SystemStarting event) {
- for (Depot depot: findAll())
- nameToId.inverse().put(depot.getId(), new Pair<>(depot.getAccount().getId(), depot.getName()));
- }
-
- @Transactional
- @Listen
- public void on(SystemStarted event) {
- for (Depot depot: findAll()) {
- checkSanity(depot);
- commitInfoManager.collect(depot);
- pullRequestInfoManager.collect(depot);
- codeCommentInfoManager.collect(depot);
- }
-
- pullRequestManager.checkSanity();
- }
-
- @Listen
- public void on(SystemStopping event) {
- synchronized(repositoryCache) {
- for (Repository repository: repositoryCache.values()) {
- repository.close();
- }
- }
- }
-
- @Transactional
- @Listen
- public void on(RefUpdated event) {
- if (event.getNewCommit().equals(ObjectId.zeroId())) {
- String branch = GitUtils.ref2branch(event.getRefName());
- for (Depot each: findAll()) {
- if (branch != null) {
- for (Iterator<IntegrationPolicy> it = each.getIntegrationPolicies().iterator(); it.hasNext();) {
- if (it.next().onBranchDelete(each, event.getDepot(), branch))
- it.remove();
- }
- }
- for (Iterator<GateKeeper> it = each.getGateKeepers().iterator(); it.hasNext();) {
- if (it.next().onRefDelete(event.getRefName()))
- it.remove();
- }
- }
- }
- }
-
- @Sessional
- @Override
- public Collection<Depot> findAllAccessible(Account account, Account user) {
- Collection<Depot> depots;
- if (account == null)
- depots = GitPlex.getInstance(DepotManager.class).findAll();
- else
- depots = account.getDepots();
-
- if (user == null) {
- return depots.stream().filter((depot)->depot.isPublicRead()).collect(Collectors.toSet());
- } else if (user.isAdministrator() || user.equals(account)) {
- return depots;
- } else {
- Collection<Account> adminOrganizations = user.getOrganizations()
- .stream()
- .filter((membership)->membership.isAdmin())
- .map((membership)->membership.getOrganization())
- .collect(Collectors.toSet());
-
- // return fast in special cases
- if (adminOrganizations.contains(account)) {
- return depots;
- }
-
- Collection<Account> memberOrganizations = user.getOrganizations()
- .stream()
- .filter((membership)->!membership.isAdmin())
- .map((membership)->membership.getOrganization())
- .collect(Collectors.toSet());
-
- // return fast in special cases
- if (memberOrganizations.contains(account) && account.getDefaultPrivilege() != DepotPrivilege.NONE) {
- return depots;
- }
-
- Collection<Depot> authorizedDepots = user.getAuthorizedDepots()
- .stream()
- .map((authorization)->authorization.getDepot())
- .collect(Collectors.toSet());
- Collection<Team> joinedTeams = user.getJoinedTeams()
- .stream()
- .map((membership)->membership.getTeam())
- .collect(Collectors.toSet());
-
- Collection<TeamAuthorization> authorizations;
- if (account != null)
- authorizations = account.getAllTeamAuthorizationsInOrganization();
- else
- authorizations = teamAuthorizationManager.findAll();
-
- for (TeamAuthorization authorization: authorizations) {
- if (joinedTeams.contains(authorization.getTeam()))
- authorizedDepots.add(authorization.getDepot());
- }
-
- return depots.stream()
- .filter((depot->depot.isPublicRead()
- || depot.getAccount().equals(user)
- || authorizedDepots.contains(depot)
- || adminOrganizations.contains(depot.getAccount())
- || memberOrganizations.contains(depot.getAccount())
- && depot.getAccount().getDefaultPrivilege() != DepotPrivilege.NONE))
- .collect(Collectors.toSet());
- }
- }
-
-}
+package com.pmease.gitplex.core.manager.impl;
+
+import java.io.File;
+import java.io.IOException;
+import java.io.InputStream;
+import java.util.Collection;
+import java.util.HashSet;
+import java.util.Iterator;
+import java.util.Map;
+import java.util.Set;
+import java.util.concurrent.ConcurrentHashMap;
+import java.util.concurrent.locks.ReadWriteLock;
+import java.util.concurrent.locks.ReentrantReadWriteLock;
+import java.util.stream.Collectors;
+
+import javax.inject.Inject;
+import javax.inject.Singleton;
+
+import org.apache.commons.io.IOUtils;
+import org.eclipse.jgit.api.Git;
+import org.eclipse.jgit.internal.storage.file.FileRepository;
+import org.eclipse.jgit.lib.ObjectId;
+import org.eclipse.jgit.lib.Repository;
+import org.hibernate.Query;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+import com.google.common.base.Preconditions;
+import com.google.common.base.Throwables;
+import com.google.common.collect.BiMap;
+import com.google.common.collect.HashBiMap;
+import com.pmease.commons.git.GitUtils;
+import com.pmease.commons.git.command.CloneCommand;
+import com.pmease.commons.hibernate.Sessional;
+import com.pmease.commons.hibernate.Transactional;
+import com.pmease.commons.hibernate.dao.AbstractEntityManager;
+import com.pmease.commons.hibernate.dao.Dao;
+import com.pmease.commons.loader.Listen;
+import com.pmease.commons.loader.ListenerRegistry;
+import com.pmease.commons.util.FileUtils;
+import com.pmease.commons.util.Pair;
+import com.pmease.commons.util.StringUtils;
+import com.pmease.gitplex.core.GitPlex;
+import com.pmease.gitplex.core.entity.Account;
+import com.pmease.gitplex.core.entity.Depot;
+import com.pmease.gitplex.core.entity.Team;
+import com.pmease.gitplex.core.entity.TeamAuthorization;
+import com.pmease.gitplex.core.entity.support.IntegrationPolicy;
+import com.pmease.gitplex.core.event.RefUpdated;
+import com.pmease.gitplex.core.event.depot.DepotDeleted;
+import com.pmease.gitplex.core.event.depot.DepotRenamed;
+import com.pmease.gitplex.core.event.depot.DepotTransferred;
+import com.pmease.gitplex.core.event.lifecycle.SystemStarted;
+import com.pmease.gitplex.core.event.lifecycle.SystemStarting;
+import com.pmease.gitplex.core.event.lifecycle.SystemStopping;
+import com.pmease.gitplex.core.gatekeeper.GateKeeper;
+import com.pmease.gitplex.core.manager.AccountManager;
+import com.pmease.gitplex.core.manager.CodeCommentInfoManager;
+import com.pmease.gitplex.core.manager.CommitInfoManager;
+import com.pmease.gitplex.core.manager.DepotManager;
+import com.pmease.gitplex.core.manager.PullRequestInfoManager;
+import com.pmease.gitplex.core.manager.StorageManager;
+import com.pmease.gitplex.core.manager.TeamAuthorizationManager;
+import com.pmease.gitplex.core.security.privilege.DepotPrivilege;
+
+@Singleton
+public class DefaultDepotManager extends AbstractEntityManager<Depot> implements DepotManager {
+
+ private static final Logger logger = LoggerFactory.getLogger(DefaultDepotManager.class);
+
+ private final ListenerRegistry listenerRegistry;
+
+ private final StorageManager storageManager;
+
+ private final AccountManager userManager;
+
+ private final CommitInfoManager commitInfoManager;
+
+ private final PullRequestInfoManager pullRequestInfoManager;
+
+ private final CodeCommentInfoManager codeCommentInfoManager;
+
+ private final TeamAuthorizationManager teamAuthorizationManager;
+
+ private final String gitReceiveHook;
+
+ private final BiMap<Pair<Long, String>, Long> nameToId = HashBiMap.create();
+
+ private final ReadWriteLock idLock = new ReentrantReadWriteLock();
+
+ private final Map<Long, Repository> repositoryCache = new ConcurrentHashMap<>();
+
+ @Inject
+ public DefaultDepotManager(Dao dao, AccountManager userManager, CodeCommentInfoManager codeCommentInfoManager,
+ TeamAuthorizationManager teamAuthorizationManager, PullRequestInfoManager pullRequestInfoManager,
+ StorageManager storageManager, CommitInfoManager commitInfoManager, ListenerRegistry listenerRegistry) {
+ super(dao);
+
+ this.storageManager = storageManager;
+ this.userManager = userManager;
+ this.pullRequestInfoManager = pullRequestInfoManager;
+ this.teamAuthorizationManager = teamAuthorizationManager;
+ this.commitInfoManager = commitInfoManager;
+ this.codeCommentInfoManager = codeCommentInfoManager;
+ this.listenerRegistry = listenerRegistry;
+
+ try (InputStream is = getClass().getClassLoader().getResourceAsStream("git-receive-hook")) {
+ Preconditions.checkNotNull(is);
+ gitReceiveHook = StringUtils.join(IOUtils.readLines(is), "\n");
+ } catch (IOException e) {
+ throw new RuntimeException(e);
+ }
+
+ }
+
+ @Override
+ public Repository getRepository(Depot depot) {
+ Repository repository = repositoryCache.get(depot.getId());
+ if (repository == null) {
+ synchronized (repositoryCache) {
+ repository = repositoryCache.get(depot.getId());
+ if (repository == null) {
+ try {
+ repository = new FileRepository(depot.getDirectory());
+ } catch (IOException e) {
+ throw new RuntimeException(e);
+ }
+ repositoryCache.put(depot.getId(), repository);
+ }
+ }
+ }
+ return repository;
+ }
+
+ @Transactional
+ @Override
+ public void save(Depot depot, Long oldAccountId, String oldName) {
+ Preconditions.checkArgument(oldAccountId==null || oldName==null,
+ "Can not rename and transfer depot in the same time");
+
+ boolean isNew = depot.isNew();
+
+ dao.persist(depot);
+
+ if (oldAccountId != null && !depot.getAccount().getId().equals(oldAccountId)) {
+ Account oldAccount = userManager.load(oldAccountId);
+ listenerRegistry.post(new DepotTransferred(depot, oldAccount));
+
+ for (Depot each: findAll()) {
+ for (IntegrationPolicy policy: each.getIntegrationPolicies()) {
+ policy.onDepotTransfer(depot, oldAccount);
+ }
+ for (Iterator<GateKeeper> it = each.getGateKeepers().iterator(); it.hasNext();) {
+ if (it.next().onDepotTransfer(each, depot, oldAccount))
+ it.remove();
+ }
+ }
+ }
+ if (oldName != null && !depot.getName().equals(oldName)) {
+ listenerRegistry.post(new DepotRenamed(depot, oldName));
+
+ for (Depot each: findAll()) {
+ for (IntegrationPolicy integrationPolicy: each.getIntegrationPolicies()) {
+ integrationPolicy.onDepotRename(depot.getAccount(), oldName, depot.getName());
+ }
+ for (GateKeeper gateKeeper: each.getGateKeepers()) {
+ gateKeeper.onDepotRename(depot, oldName);
+ }
+ }
+ }
+
+ doAfterCommit(new Runnable() {
+
+ @Override
+ public void run() {
+ idLock.writeLock().lock();
+ try {
+ nameToId.inverse().put(depot.getId(), new Pair<>(depot.getAccount().getId(), depot.getName()));
+ } finally {
+ idLock.writeLock().unlock();
+ }
+ if (isNew) {
+ checkSanity(depot);
+ commitInfoManager.collect(depot);
+ }
+ }
+
+ });
+ }
+
+ @Transactional
+ @Override
+ public void delete(Depot depot) {
+ Query query = getSession().createQuery("update Depot set forkedFrom=null where forkedFrom=:forkedFrom");
+ query.setParameter("forkedFrom", depot);
+ query.executeUpdate();
+
+ dao.remove(depot);
+
+ for (Depot each: findAll()) {
+ for (Iterator<IntegrationPolicy> it = each.getIntegrationPolicies().iterator(); it.hasNext();) {
+ if (it.next().onDepotDelete(depot))
+ it.remove();
+ }
+ for (Iterator<GateKeeper> it = each.getGateKeepers().iterator(); it.hasNext();) {
+ if (it.next().onDepotDelete(depot))
+ it.remove();
+ }
+ }
+
+ doAfterCommit(new Runnable() {
+
+ @Override
+ public void run() {
+ idLock.writeLock().lock();
+ try {
+ nameToId.inverse().remove(depot.getId());
+ } finally {
+ idLock.writeLock().unlock();
+ }
+ getRepository(depot).close();
+ repositoryCache.remove(depot.getId());
+
+ FileUtils.deleteDir(storageManager.getGitDir(depot));
+ }
+
+ });
+
+ listenerRegistry.post(new DepotDeleted(depot));
+ }
+
+ @Sessional
+ @Override
+ public Depot find(String accountName, String depotName) {
+ Account user = userManager.find(accountName);
+ if (user != null)
+ return find(user, depotName);
+ else
+ return null;
+ }
+
+ @Sessional
+ @Override
+ public Depot find(Account account, String depotName) {
+ idLock.readLock().lock();
+ try {
+ Long id = nameToId.get(new Pair<>(account.getId(), depotName));
+ if (id != null)
+ return load(id);
+ else
+ return null;
+ } finally {
+ idLock.readLock().unlock();
+ }
+ }
+
+ @Sessional
+ @Override
+ public Depot find(String depotFQN) {
+ String userName = StringUtils.substringBefore(depotFQN, Depot.FQN_SEPARATOR);
+ Account user = userManager.find(userName);
+ if (user != null)
+ return find(user, StringUtils.substringAfter(depotFQN, Depot.FQN_SEPARATOR));
+ else
+ return null;
+ }
+
+ @Transactional
+ @Override
+ public Depot fork(Depot depot, Account user) {
+ if (depot.getAccount().equals(user))
+ return depot;
+
+ Depot forked = null;
+ for (Depot each: user.getDepots()) {
+ if (depot.equals(each.getForkedFrom())) {
+ forked = each;
+ break;
+ }
+ }
+ if (forked == null) {
+ Set<String> existingNames = new HashSet<>();
+ for (Depot each: user.getDepots())
+ existingNames.add(each.getName());
+
+ forked = new Depot();
+ forked.setAccount(user);
+ forked.setForkedFrom(depot);
+ if (existingNames.contains(depot.getName())) {
+ int suffix = 1;
+ while (existingNames.contains(depot.getName() + "_" + suffix))
+ suffix++;
+ forked.setName(depot.getName() + "_" + suffix);
+ } else {
+ forked.setName(depot.getName());
+ }
+
+ dao.persist(forked);
+
+ FileUtils.cleanDir(forked.getDirectory());
+ new CloneCommand(forked.getDirectory()).bare(true).from(depot.getDirectory().getAbsolutePath()).call();
+ }
+
+ return forked;
+ }
+
+ private void checkSanity(Depot depot) {
+ logger.info("Checking sanity of repository '{}'...", depot);
+
+ File gitDir = depot.getDirectory();
+ if (depot.getDirectory().exists() && !GitUtils.isValid(gitDir)) {
+ logger.warn("Directory '" + gitDir + "' is not a valid git repository, removing...");
+ FileUtils.deleteDir(gitDir);
+ }
+
+ if (!gitDir.exists()) {
+ logger.warn("Initializing git repository in '" + gitDir + "'...");
+ FileUtils.createDir(gitDir);
+ try {
+ Git.init().setDirectory(gitDir).setBare(true).call();
+ } catch (Exception e) {
+ Throwables.propagate(e);
+ }
+ }
+
+ if (!depot.isValid()) {
+ File hooksDir = new File(gitDir, "hooks");
+
+ File gitPreReceiveHookFile = new File(hooksDir, "pre-receive");
+ FileUtils.writeFile(gitPreReceiveHookFile, String.format(gitReceiveHook, "git-prereceive-callback"));
+ gitPreReceiveHookFile.setExecutable(true);
+
+ File gitPostReceiveHookFile = new File(hooksDir, "post-receive");
+ FileUtils.writeFile(gitPostReceiveHookFile, String.format(gitReceiveHook, "git-postreceive-callback"));
+ gitPostReceiveHookFile.setExecutable(true);
+ }
+ }
+
+ @Sessional
+ @Listen
+ public void on(SystemStarting event) {
+ for (Depot depot: findAll())
+ nameToId.inverse().put(depot.getId(), new Pair<>(depot.getAccount().getId(), depot.getName()));
+ }
+
+ @Transactional
+ @Listen
+ public void on(SystemStarted event) {
+ for (Depot depot: findAll()) {
+ checkSanity(depot);
+ commitInfoManager.collect(depot);
+ pullRequestInfoManager.collect(depot);
+ codeCommentInfoManager.collect(depot);
+ }
+ }
+
+ @Listen
+ public void on(SystemStopping event) {
+ synchronized(repositoryCache) {
+ for (Repository repository: repositoryCache.values()) {
+ repository.close();
+ }
+ }
+ }
+
+ @Transactional
+ @Listen
+ public void on(RefUpdated event) {
+ if (event.getNewCommit().equals(ObjectId.zeroId())) {
+ String branch = GitUtils.ref2branch(event.getRefName());
+ for (Depot each: findAll()) {
+ if (branch != null) {
+ for (Iterator<IntegrationPolicy> it = each.getIntegrationPolicies().iterator(); it.hasNext();) {
+ if (it.next().onBranchDelete(each, event.getDepot(), branch))
+ it.remove();
+ }
+ }
+ for (Iterator<GateKeeper> it = each.getGateKeepers().iterator(); it.hasNext();) {
+ if (it.next().onRefDelete(event.getRefName()))
+ it.remove();
+ }
+ }
+ }
+ }
+
+ @Sessional
+ @Override
+ public Collection<Depot> findAllAccessible(Account account, Account user) {
+ Collection<Depot> depots;
+ if (account == null)
+ depots = GitPlex.getInstance(DepotManager.class).findAll();
+ else
+ depots = account.getDepots();
+
+ if (user == null) {
+ return depots.stream().filter((depot)->depot.isPublicRead()).collect(Collectors.toSet());
+ } else if (user.isAdministrator() || user.equals(account)) {
+ return depots;
+ } else {
+ Collection<Account> adminOrganizations = user.getOrganizations()
+ .stream()
+ .filter((membership)->membership.isAdmin())
+ .map((membership)->membership.getOrganization())
+ .collect(Collectors.toSet());
+
+ // return fast in special cases
+ if (adminOrganizations.contains(account)) {
+ return depots;
+ }
+
+ Collection<Account> memberOrganizations = user.getOrganizations()
+ .stream()
+ .filter((membership)->!membership.isAdmin())
+ .map((membership)->membership.getOrganization())
+ .collect(Collectors.toSet());
+
+ // return fast in special cases
+ if (memberOrganizations.contains(account) && account.getDefaultPrivilege() != DepotPrivilege.NONE) {
+ return depots;
+ }
+
+ Collection<Depot> authorizedDepots = user.getAuthorizedDepots()
+ .stream()
+ .map((authorization)->authorization.getDepot())
+ .collect(Collectors.toSet());
+ Collection<Team> joinedTeams = user.getJoinedTeams()
+ .stream()
+ .map((membership)->membership.getTeam())
+ .collect(Collectors.toSet());
+
+ Collection<TeamAuthorization> authorizations;
+ if (account != null)
+ authorizations = account.getAllTeamAuthorizationsInOrganization();
+ else
+ authorizations = teamAuthorizationManager.findAll();
+
+ for (TeamAuthorization authorization: authorizations) {
+ if (joinedTeams.contains(authorization.getTeam()))
+ authorizedDepots.add(authorization.getDepot());
+ }
+
+ return depots.stream()
+ .filter((depot->depot.isPublicRead()
+ || depot.getAccount().equals(user)
+ || authorizedDepots.contains(depot)
+ || adminOrganizations.contains(depot.getAccount())
+ || memberOrganizations.contains(depot.getAccount())
+ && depot.getAccount().getDefaultPrivilege() != DepotPrivilege.NONE))
+ .collect(Collectors.toSet());
+ }
+ }
+
+}
diff --git a/gitplex.core/src/main/java/com/pmease/gitplex/core/manager/impl/DefaultMailManager.java b/gitplex.core/src/main/java/com/pmease/gitplex/core/manager/impl/DefaultMailManager.java
index 35d42ec903..88ec812439 100644
--- a/gitplex.core/src/main/java/com/pmease/gitplex/core/manager/impl/DefaultMailManager.java
+++ b/gitplex.core/src/main/java/com/pmease/gitplex/core/manager/impl/DefaultMailManager.java
@@ -12,11 +12,14 @@ import javax.inject.Singleton;
import org.apache.commons.codec.CharEncoding;
import org.apache.commons.mail.EmailException;
import org.apache.commons.mail.HtmlEmail;
+import org.hibernate.resource.transaction.spi.TransactionStatus;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.google.common.collect.Sets;
import com.pmease.commons.bootstrap.Bootstrap;
+import com.pmease.commons.hibernate.Sessional;
+import com.pmease.commons.hibernate.dao.Dao;
import com.pmease.commons.loader.Listen;
import com.pmease.commons.markdown.MarkdownManager;
import com.pmease.gitplex.core.entity.Account;
@@ -42,18 +45,30 @@ public class DefaultMailManager implements MailManager {
private final UrlManager urlManager;
+ private final Dao dao;
+
@Inject
- public DefaultMailManager(ConfigManager configManager, ExecutorService executorService,
+ public DefaultMailManager(Dao dao, ConfigManager configManager, ExecutorService executorService,
MarkdownManager markdownManager, UrlManager urlManager) {
+ this.dao = dao;
this.configManager = configManager;
this.executorService = executorService;
this.markdownManager = markdownManager;
this.urlManager = urlManager;
}
-
+
+ @Sessional
@Override
public void sendMailAsync(Collection<Account> toList, String subject, String body) {
- executorService.execute(new Runnable() {
+ if (dao.getSession().getTransaction().getStatus() == TransactionStatus.ACTIVE) {
+ dao.doAsyncAfterCommit(newSendMailRunnable(toList, subject, body));
+ } else {
+ executorService.execute(newSendMailRunnable(toList, subject, body));
+ }
+ }
+
+ private Runnable newSendMailRunnable(Collection<Account> toList, String subject, String body) {
+ return new Runnable() {
@Override
public void run() {
@@ -64,7 +79,7 @@ public class DefaultMailManager implements MailManager {
}
}
- });
+ };
}
@Override
@@ -172,5 +187,5 @@ public class DefaultMailManager implements MailManager {
+ "-- Sent by GitPlex",
user.getDisplayName(), body);
}
-
+
}
diff --git a/gitplex.core/src/main/java/com/pmease/gitplex/core/manager/impl/DefaultPullRequestManager.java b/gitplex.core/src/main/java/com/pmease/gitplex/core/manager/impl/DefaultPullRequestManager.java
index a28282ac44..8a97a1a377 100644
--- a/gitplex.core/src/main/java/com/pmease/gitplex/core/manager/impl/DefaultPullRequestManager.java
+++ b/gitplex.core/src/main/java/com/pmease/gitplex/core/manager/impl/DefaultPullRequestManager.java
@@ -8,9 +8,6 @@ import static com.pmease.gitplex.core.entity.PullRequest.IntegrationStrategy.MER
import static com.pmease.gitplex.core.entity.PullRequest.IntegrationStrategy.MERGE_WITH_SQUASH;
import static com.pmease.gitplex.core.entity.PullRequest.IntegrationStrategy.REBASE_SOURCE_ONTO_TARGET;
import static com.pmease.gitplex.core.entity.PullRequest.IntegrationStrategy.REBASE_TARGET_ONTO_SOURCE;
-import static com.pmease.gitplex.core.entity.PullRequest.Status.PENDING_APPROVAL;
-import static com.pmease.gitplex.core.entity.PullRequest.Status.PENDING_INTEGRATE;
-import static com.pmease.gitplex.core.entity.PullRequest.Status.PENDING_UPDATE;
import java.util.Collection;
import java.util.Date;
@@ -18,7 +15,6 @@ import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.Callable;
-import java.util.concurrent.ExecutorService;
import java.util.concurrent.atomic.AtomicLong;
import javax.annotation.Nullable;
@@ -86,6 +82,10 @@ import com.pmease.gitplex.core.event.pullrequest.PullRequestVerificationFailed;
import com.pmease.gitplex.core.event.pullrequest.PullRequestVerificationSucceeded;
import com.pmease.gitplex.core.event.pullrequest.SourceBranchDeleted;
import com.pmease.gitplex.core.event.pullrequest.SourceBranchRestored;
+import com.pmease.gitplex.core.gatekeeper.checkresult.Blocking;
+import com.pmease.gitplex.core.gatekeeper.checkresult.Failed;
+import com.pmease.gitplex.core.gatekeeper.checkresult.GateCheckResult;
+import com.pmease.gitplex.core.gatekeeper.checkresult.Pending;
import com.pmease.gitplex.core.manager.AccountManager;
import com.pmease.gitplex.core.manager.BatchWorkManager;
import com.pmease.gitplex.core.manager.PullRequestManager;
@@ -121,16 +121,14 @@ public class DefaultPullRequestManager extends AbstractEntityManager<PullRequest
private final BatchWorkManager batchWorkManager;
- private final ExecutorService executorService;
-
private final Map<String, AtomicLong> nextNumbers = new HashMap<>();
-
+
@Inject
public DefaultPullRequestManager(Dao dao, PullRequestUpdateManager pullRequestUpdateManager,
PullRequestReviewInvitationManager reviewInvitationManager, AccountManager accountManager,
PullRequestNotificationManager notificationManager, MarkdownManager markdownManager,
BatchWorkManager batchWorkManager, ListenerRegistry listenerRegistry,
- ExecutorService executorService, UnitOfWork unitOfWork) {
+ UnitOfWork unitOfWork) {
super(dao);
this.pullRequestUpdateManager = pullRequestUpdateManager;
@@ -138,7 +136,6 @@ public class DefaultPullRequestManager extends AbstractEntityManager<PullRequest
this.accountManager = accountManager;
this.batchWorkManager = batchWorkManager;
this.unitOfWork = unitOfWork;
- this.executorService = executorService;
this.listenerRegistry = listenerRegistry;
}
@@ -163,7 +160,7 @@ public class DefaultPullRequestManager extends AbstractEntityManager<PullRequest
public void restoreSourceBranch(PullRequest request, String note) {
Preconditions.checkState(!request.isOpen() && request.getSourceDepot() != null);
if (request.getSource().getObjectName(false) == null) {
- RevCommit latestCommit = request.getLatestUpdate().getHeadCommit();
+ RevCommit latestCommit = request.getHeadCommit();
try {
request.getSourceDepot().git().branchCreate().setName(request.getSourceBranch()).setStartPoint(latestCommit).call();
} catch (Exception e) {
@@ -194,19 +191,13 @@ public class DefaultPullRequestManager extends AbstractEntityManager<PullRequest
@Transactional
@Override
public void reopen(PullRequest request, String note) {
- Preconditions.checkState(!request.isOpen(), "Pull request is alreay opened");
- updateIfNecessary(request, false);
Account user = accountManager.getCurrent();
- if (request.isMerged()) {
- closeAsIntegrated(request, true, null);
- } else {
- request.setCloseInfo(null);
- PullRequestReopened event = new PullRequestReopened(request, user, note);
- listenerRegistry.post(event);
- request.setLastEvent(event);
- save(request);
- checkAsync(request);
- }
+ request.setCloseInfo(null);
+ PullRequestReopened event = new PullRequestReopened(request, user, note);
+ listenerRegistry.post(event);
+ request.setLastEvent(event);
+ save(request);
+ checkAsync(request);
}
@Transactional
@@ -229,9 +220,6 @@ public class DefaultPullRequestManager extends AbstractEntityManager<PullRequest
@Transactional
@Override
public void integrate(PullRequest request, String note) {
- if (request.getStatus() != PENDING_INTEGRATE)
- throw new IllegalStateException("Gate keeper disallows integration right now.");
-
IntegrationPreview preview = request.getIntegrationPreview();
if (preview == null)
throw new IllegalStateException("Integration preview has not been calculated yet.");
@@ -277,13 +265,13 @@ public class DefaultPullRequestManager extends AbstractEntityManager<PullRequest
refUpdate.setExpectedOldObjectId(requestHeadId);
refUpdate.setRefLogMessage("Pull request #" + request.getNumber(), true);
GitUtils.updateRef(refUpdate);
-
- updateIfNecessary(request, false);
+
+ checkUpdate(request, false);
Long requestId = request.getId();
Subject subject = SecurityUtils.getSubject();
ObjectId newCommitId = integratedCommitId;
- doUnitOfWorkAfterCommitAsync(new Runnable() {
+ doUnitOfWorkAsyncAfterCommit(new Runnable() {
@Override
public void run() {
@@ -313,7 +301,7 @@ public class DefaultPullRequestManager extends AbstractEntityManager<PullRequest
Long requestId = request.getId();
Subject subject = SecurityUtils.getSubject();
ObjectId newCommitId = integratedCommitId;
- doUnitOfWorkAfterCommitAsync(new Runnable() {
+ doUnitOfWorkAsyncAfterCommit(new Runnable() {
@Override
public void run() {
@@ -373,7 +361,7 @@ public class DefaultPullRequestManager extends AbstractEntityManager<PullRequest
GitUtils.updateRef(refUpdate);
for (PullRequestUpdate update: request.getUpdates()) {
- pullRequestUpdateManager.save(update, false);
+ pullRequestUpdateManager.save(update);
}
for (PullRequestReviewInvitation invitation: request.getReviewInvitations())
@@ -410,18 +398,6 @@ public class DefaultPullRequestManager extends AbstractEntityManager<PullRequest
}
save(request);
}
-
- private void onTargetBranchUpdate(PullRequest request) {
- String targetHead = request.getTarget().getObjectName();
- if (request.getLastIntegrationPreview() == null || !request.getLastIntegrationPreview().getTargetHead().equals(targetHead)) {
- if (request.isMerged()) {
- closeAsIntegrated(request, true, null);
- }
- if (request.isOpen()) {
- batchWorkManager.submit(getIntegrationPreviewer(request), new Prioritized(BACKEND_PREVIEW_PRIORITY));
- }
- }
- }
private void closeAsIntegrated(PullRequest request, boolean dueToMerged, String note) {
Account user = accountManager.getCurrent();
@@ -443,69 +419,73 @@ public class DefaultPullRequestManager extends AbstractEntityManager<PullRequest
save(request);
}
- private void updateIfNecessary(PullRequest request, boolean notifyListeners) {
- if (!request.getLatestUpdate().getHeadCommitHash().equals(request.getSource().getObjectName())) {
+ private void checkUpdate(PullRequest request, boolean independent) {
+ if (!request.getHeadCommitHash().equals(request.getSource().getObjectName())) {
PullRequestUpdate update = new PullRequestUpdate();
update.setRequest(request);
update.setHeadCommitHash(request.getSource().getObjectName());
update.setMergeCommitHash(GitUtils.getMergeBase(request.getTargetDepot().getRepository(),
request.getTarget().getObjectId(), ObjectId.fromString(update.getHeadCommitHash())).name());
request.addUpdate(update);
- pullRequestUpdateManager.save(update, notifyListeners);
+ pullRequestUpdateManager.save(update, independent);
}
}
- /**
- * This method might take some time and is not key to pull request logic (even if we
- * did not call it, we can always call it later), so normally should be called in an
- * executor
- */
- @Sessional
+ @Transactional
@Override
public void check(PullRequest request) {
if (request.isOpen()) {
- if (request.isMerged()) {
- closeAsIntegrated(request, true, null);
+ if (request.getSourceDepot() == null) {
+ discard(request, "Source repository no longer exists");
+ } else if (request.getSource().getObjectId(false) == null) {
+ discard(request, "Source branch no longer exists");
+ } else if (request.getTarget().getObjectId(false) == null) {
+ discard(request, "Target branch no longer exists");
} else {
- Date timeBeforeCheck = new Date();
- if (request.getStatus() == PENDING_UPDATE) {
- listenerRegistry.post(new PullRequestPendingUpdate(request));
- } else if (request.getStatus() == PENDING_INTEGRATE) {
+ checkUpdate(request, true);
+ if (request.isMerged()) {
+ closeAsIntegrated(request, true, null);
+ } else {
IntegrationPreview integrationPreview = request.getIntegrationPreview();
- if (integrationPreview != null
- && integrationPreview.getIntegrated() != null
- && request.getAssignee() == null) {
- integrate(request, "Integrated automatically by system");
+ Date timeBeforeCheck = new Date();
+ GateCheckResult result = request.checkGates(false);
+ if (result instanceof Pending || result instanceof Blocking) {
+ for (PullRequestReviewInvitation invitation: request.getReviewInvitations()) {
+ if (invitation.getDate().getTime()>=timeBeforeCheck.getTime())
+ reviewInvitationManager.save(invitation);
+ }
+ listenerRegistry.post(new PullRequestPendingApproval(request));
+ } else if (result instanceof Failed) {
+ listenerRegistry.post(new PullRequestPendingUpdate(request));
+ } else if (integrationPreview != null
+ && integrationPreview.getIntegrated() != null
+ && request.getAssignee() == null) {
+ integrate(request, "Integrated automatically by GitPlex");
} else {
listenerRegistry.post(new PullRequestPendingIntegration(request));
}
- } else if (request.getStatus() == PENDING_APPROVAL) {
- for (PullRequestReviewInvitation invitation: request.getReviewInvitations()) {
- if (invitation.getDate().getTime()>=timeBeforeCheck.getTime())
- reviewInvitationManager.save(invitation);
- }
- listenerRegistry.post(new PullRequestPendingApproval(request));
}
}
}
}
- @Override
- public boolean canIntegrate(PullRequest request) {
- if (request.getStatus() != PENDING_INTEGRATE) {
- return false;
- } else {
- IntegrationPreview integrationPreview = request.getIntegrationPreview();
- return integrationPreview != null && integrationPreview.getIntegrated() != null;
- }
- }
-
@Override
public IntegrationPreview previewIntegration(PullRequest request) {
IntegrationPreview preview = request.getLastIntegrationPreview();
- if (request.isOpen() && (preview == null || preview.isObsolete(request))) {
+ if (request.isOpen() && !request.isMerged() && (preview == null || preview.isObsolete(request))) {
int priority = RequestCycle.get() != null?UI_PREVIEW_PRIORITY:BACKEND_PREVIEW_PRIORITY;
- batchWorkManager.submit(getIntegrationPreviewer(request), new Prioritized(priority));
+ if (dao.getSession().getTransaction().getStatus() == TransactionStatus.ACTIVE) {
+ doAfterCommit(new Runnable() {
+
+ @Override
+ public void run() {
+ batchWorkManager.submit(getIntegrationPreviewer(request), new Prioritized(priority));
+ }
+
+ });
+ } else {
+ batchWorkManager.submit(getIntegrationPreviewer(request), new Prioritized(priority));
+ }
return null;
} else {
return preview;
@@ -526,10 +506,10 @@ public class DefaultPullRequestManager extends AbstractEntityManager<PullRequest
PullRequest request = load(requestId);
try {
IntegrationPreview preview = request.getLastIntegrationPreview();
- if (request.isOpen() && (preview == null || preview.isObsolete(request))) {
+ if (request.isOpen() && !request.isMerged() && (preview == null || preview.isObsolete(request))) {
logger.info("Calculating integration preview of pull request #{} in repository '{}'...",
request.getNumber(), request.getTargetDepot());
- String requestHead = request.getLatestUpdate().getHeadCommitHash();
+ String requestHead = request.getHeadCommitHash();
String targetHead = request.getTarget().getObjectName();
Depot targetDepot = request.getTargetDepot();
preview = new IntegrationPreview(targetHead, requestHead, request.getIntegrationStrategy(), null);
@@ -568,13 +548,7 @@ public class DefaultPullRequestManager extends AbstractEntityManager<PullRequest
}
}
dao.persist(request);
-
- if (request.getStatus() == PENDING_INTEGRATE
- && preview.getIntegrated() != null
- && request.getAssignee() == null) {
- integrate(request, "Integrated automatically by GitPlex");
- }
-
+
listenerRegistry.post(new IntegrationPreviewCalculated(request));
logger.info("Integration preview of pull request #{} in repository '{}' is calculated.",
request.getNumber(), request.getTargetDepot());
@@ -611,39 +585,11 @@ public class DefaultPullRequestManager extends AbstractEntityManager<PullRequest
String branch = GitUtils.ref2branch(event.getRefName());
if (branch != null) {
DepotAndBranch depotAndBranch = new DepotAndBranch(event.getDepot(), branch);
- if (!event.getNewCommit().equals(ObjectId.zeroId())) {
- Criterion criterion = Restrictions.and(ofOpen(), ofSource(depotAndBranch));
- for (PullRequest request: findAll(EntityCriteria.of(PullRequest.class).add(criterion))) {
- if (event.getDepot().getObjectId(request.getBaseCommitHash(), false) != null) {
- updateIfNecessary(request, true);
- if (request.isMerged()) {
- closeAsIntegrated(request, true, null);
- } else {
- checkAsync(request);
- }
- } else {
- logger.error("Unable to update pull request #{} due to unexpected source repository.", request.getNumber());
- }
- }
-
- depotAndBranch = new DepotAndBranch(event.getDepot(), branch);
- criterion = Restrictions.and(ofOpen(), ofTarget(depotAndBranch));
- for (PullRequest request: findAll(EntityCriteria.of(PullRequest.class).add(criterion))) {
- if (request.getSourceDepot().getObjectId(request.getBaseCommitHash(), false) != null)
- onTargetBranchUpdate(request);
- else
- logger.error("Unable to update pull request #{} due to unexpected target repository.", request.getNumber());
- }
- } else {
- Criterion criterion = Restrictions.and(
- ofOpen(),
- Restrictions.or(ofSource(depotAndBranch), ofTarget(depotAndBranch)));
- for (PullRequest request: findAll(EntityCriteria.of(PullRequest.class).add(criterion))) {
- if (request.getTargetDepot().equals(event.getDepot()) && request.getTargetBranch().equals(branch))
- discard(request, "Target branch is deleted.");
- else
- discard(request, "Source branch is deleted.");
- }
+ Criterion criterion = Restrictions.and(
+ ofOpen(),
+ Restrictions.or(ofSource(depotAndBranch), ofTarget(depotAndBranch)));
+ for (PullRequest request: findAll(EntityCriteria.of(PullRequest.class).add(criterion))) {
+ check(request);
}
}
}
@@ -688,62 +634,6 @@ public class DefaultPullRequestManager extends AbstractEntityManager<PullRequest
return findAll(criteria);
}
- @Sessional
- @Override
- public void checkSanity() {
- logger.info("Checking sanity of pull requests...");
-
- EntityCriteria<PullRequest> criteria = EntityCriteria.of(PullRequest.class);
- criteria.add(ofOpen());
- for (PullRequest request: findAll(criteria)) {
- Depot sourceDepot = request.getSourceDepot();
- if (sourceDepot == null) {
- discard(request, "Source repository is deleted.");
- } else if (sourceDepot.isValid()) {
- String baseCommitHash = request.getBaseCommitHash();
-
- // only modifies pull request status if source repository is the repository we
- // previously worked with. This avoids disaster of closing all pull requests
- // if repository storage points to a different location by mistake
- if (sourceDepot.getObjectId(baseCommitHash, false) != null) {
- String sourceHead = request.getSource().getObjectName(false);
- if (sourceHead == null) {
- discard(request, "Source branch is deleted.");
- } else {
- updateIfNecessary(request, false);
- if (request.isMerged()) {
- closeAsIntegrated(request, true, null);
- } else {
- checkAsync(request);
- }
- }
- } else {
- logger.error("Unable to update pull request #{} due to unexpected source repository", request.getNumber());
- }
- }
-
- if (request.isOpen()) {
- Depot targetDepot = request.getTargetDepot();
- if (targetDepot.isValid()) {
- String baseCommitHash = request.getBaseCommitHash();
-
- // only modifies pull request status if target repository is the repository we
- // previously worked with. This avoids disaster of closing all pull requests
- // if repository storage points to a different location by mistake
- if (targetDepot.getObjectId(baseCommitHash, false) != null) {
- String targetHead = request.getTarget().getObjectName(false);
- if (targetHead == null)
- discard(request, "Target branch is deleted.");
- else
- onTargetBranchUpdate(request);
- } else {
- logger.error("Unable to update pull request #{} due to unexpected target repository", request.getNumber());
- }
- }
- }
- }
- }
-
@Sessional
@Override
public int countOpen(Depot depot) {
@@ -780,6 +670,11 @@ public class DefaultPullRequestManager extends AbstractEntityManager<PullRequest
checkAsync(event.getRequest());
}
+ @Listen
+ public void on(IntegrationPreviewCalculated event) {
+ checkAsync(event.getRequest());
+ }
+
@Transactional
@Listen
public void on(PullRequestApproved event) {
@@ -804,39 +699,33 @@ public class DefaultPullRequestManager extends AbstractEntityManager<PullRequest
checkAsync(event.getRequest());
}
+ private Runnable newCheckRunnable(Long requestId, Subject subject) {
+ return new Runnable() {
+
+ @Override
+ public void run() {
+ try {
+ ThreadContext.bind(subject);
+ check(load(requestId));
+ } catch (Exception e) {
+ logger.error("Error checking pull request", e);
+ } finally {
+ ThreadContext.unbindSubject();
+ }
+ }
+
+ };
+ }
+
@Sessional
- private void checkAsync(PullRequest request) {
+ protected void checkAsync(PullRequest request) {
Long requestId = request.getId();
Subject subject = SecurityUtils.getSubject();
if (dao.getSession().getTransaction().getStatus() == TransactionStatus.ACTIVE) {
- doUnitOfWorkAfterCommitAsync(new Runnable() {
-
- @Override
- public void run() {
- try {
- ThreadContext.bind(subject);
- check(load(requestId));
- } finally {
- ThreadContext.unbindSubject();
- }
- }
-
- });
+ doUnitOfWorkAsyncAfterCommit(newCheckRunnable(requestId, subject));
} else {
- executorService.execute(new Runnable() {
-
- @Override
- public void run() {
- try {
- ThreadContext.bind(subject);
- check(load(requestId));
- } finally {
- ThreadContext.unbindSubject();
- }
- }
-
- });
+ unitOfWork.doAsync(newCheckRunnable(requestId, subject));
}
}
-
+
}
diff --git a/gitplex.core/src/main/java/com/pmease/gitplex/core/manager/impl/DefaultPullRequestUpdateManager.java b/gitplex.core/src/main/java/com/pmease/gitplex/core/manager/impl/DefaultPullRequestUpdateManager.java
index 59c8a88b16..a40484181c 100644
--- a/gitplex.core/src/main/java/com/pmease/gitplex/core/manager/impl/DefaultPullRequestUpdateManager.java
+++ b/gitplex.core/src/main/java/com/pmease/gitplex/core/manager/impl/DefaultPullRequestUpdateManager.java
@@ -52,7 +52,7 @@ public class DefaultPullRequestUpdateManager extends AbstractEntityManager<PullR
@Transactional
@Override
- public void save(PullRequestUpdate update, boolean callListeners) {
+ public void save(PullRequestUpdate update, boolean independent) {
PullRequest request = update.getRequest();
String sourceHead = request.getSource().getObjectName();
@@ -74,7 +74,7 @@ public class DefaultPullRequestUpdateManager extends AbstractEntityManager<PullR
GitUtils.updateRef(refUpdate);
}
- if (callListeners) {
+ if (independent) {
PullRequestUpdated event = new PullRequestUpdated(update);
listenerRegistry.post(event);
request.setLastEvent(event);
diff --git a/gitplex.core/src/main/java/com/pmease/gitplex/core/manager/impl/DefaultPullRequestWatchManager.java b/gitplex.core/src/main/java/com/pmease/gitplex/core/manager/impl/DefaultPullRequestWatchManager.java
index 318cf4d47e..50a49f1e29 100644
--- a/gitplex.core/src/main/java/com/pmease/gitplex/core/manager/impl/DefaultPullRequestWatchManager.java
+++ b/gitplex.core/src/main/java/com/pmease/gitplex/core/manager/impl/DefaultPullRequestWatchManager.java
@@ -192,7 +192,6 @@ public class DefaultPullRequestWatchManager extends AbstractEntityManager<PullRe
user.getDisplayName(), body);
}
- @Transactional
private void makeContributorsWatching(PullRequestUpdate update) {
// we use a name-email pair to filter off duplicate person as equals method of PersonIdent also takes
// "when" field into account
diff --git a/gitplex.web/src/main/java/com/pmease/gitplex/web/component/comment/CodeCommentPanel.java b/gitplex.web/src/main/java/com/pmease/gitplex/web/component/comment/CodeCommentPanel.java
index 89585c8c8f..c879a9f29e 100644
--- a/gitplex.web/src/main/java/com/pmease/gitplex/web/component/comment/CodeCommentPanel.java
+++ b/gitplex.web/src/main/java/com/pmease/gitplex/web/component/comment/CodeCommentPanel.java
@@ -1,803 +1,803 @@
-package com.pmease.gitplex.web.component.comment;
-
-import java.io.Serializable;
-import java.util.ArrayList;
-import java.util.Date;
-import java.util.List;
-
-import javax.annotation.Nullable;
-
-import org.apache.commons.lang3.StringUtils;
-import org.apache.wicket.Component;
-import org.apache.wicket.ajax.AjaxRequestTarget;
-import org.apache.wicket.ajax.attributes.AjaxRequestAttributes;
-import org.apache.wicket.ajax.markup.html.AjaxLink;
-import org.apache.wicket.ajax.markup.html.form.AjaxButton;
-import org.apache.wicket.behavior.AttributeAppender;
-import org.apache.wicket.markup.head.CssHeaderItem;
-import org.apache.wicket.markup.head.IHeaderResponse;
-import org.apache.wicket.markup.html.WebMarkupContainer;
-import org.apache.wicket.markup.html.basic.Label;
-import org.apache.wicket.markup.html.form.Form;
-import org.apache.wicket.markup.html.form.TextField;
-import org.apache.wicket.markup.html.link.Link;
-import org.apache.wicket.markup.html.panel.Fragment;
-import org.apache.wicket.markup.html.panel.Panel;
-import org.apache.wicket.markup.repeater.RepeatingView;
-import org.apache.wicket.model.AbstractReadOnlyModel;
-import org.apache.wicket.model.LoadableDetachableModel;
-import org.apache.wicket.model.Model;
-import org.apache.wicket.protocol.ws.api.WebSocketRequestHandler;
-import org.apache.wicket.request.mapper.parameter.PageParameters;
-import org.apache.wicket.request.resource.CssResourceReference;
-import org.hibernate.StaleObjectStateException;
-
-import com.pmease.commons.hibernate.dao.Dao;
-import com.pmease.commons.wicket.ajaxlistener.ConfirmLeaveListener;
-import com.pmease.commons.wicket.ajaxlistener.ConfirmListener;
-import com.pmease.commons.wicket.behavior.markdown.AttachmentSupport;
-import com.pmease.commons.wicket.component.markdown.MarkdownEditSupport;
-import com.pmease.commons.wicket.component.markdown.MarkdownPanel;
-import com.pmease.commons.wicket.websocket.WebSocketRenderBehavior;
-import com.pmease.gitplex.core.GitPlex;
-import com.pmease.gitplex.core.entity.Account;
-import com.pmease.gitplex.core.entity.CodeComment;
-import com.pmease.gitplex.core.entity.CodeCommentReply;
-import com.pmease.gitplex.core.entity.CodeCommentStatusChange;
-import com.pmease.gitplex.core.entity.Depot;
-import com.pmease.gitplex.core.entity.PullRequest;
-import com.pmease.gitplex.core.entity.support.CodeCommentActivity;
-import com.pmease.gitplex.core.entity.support.CompareContext;
-import com.pmease.gitplex.core.entity.support.DepotAndRevision;
-import com.pmease.gitplex.core.manager.CodeCommentManager;
-import com.pmease.gitplex.core.manager.CodeCommentReplyManager;
-import com.pmease.gitplex.core.manager.CodeCommentStatusChangeManager;
-import com.pmease.gitplex.core.manager.VisitInfoManager;
-import com.pmease.gitplex.core.security.SecurityUtils;
-import com.pmease.gitplex.web.component.AccountLink;
-import com.pmease.gitplex.web.component.avatar.AvatarLink;
-import com.pmease.gitplex.web.page.depot.compare.RevisionComparePage;
-import com.pmease.gitplex.web.page.depot.pullrequest.requestdetail.changes.RequestChangesPage;
-import com.pmease.gitplex.web.util.DateUtils;
-
-import de.agilecoders.wicket.core.markup.html.bootstrap.common.NotificationPanel;
-
-@SuppressWarnings("serial")
-public abstract class CodeCommentPanel extends Panel {
-
- private final Long commentId;
-
- private RepeatingView activitiesView;
-
- /**
- * We pass comment id instead of comment model as we want to make sure that
- * comment is always loaded upon usage as this panel is involved in websocket
- * update and websocket update does not detach models at end of request which
- * may result in Hibernate lazy load exception when the comment is used again
- * in next request
- *
- * @param id
- * @param commentId
- */
- public CodeCommentPanel(String id, Long commentId) {
- super(id);
- this.commentId = commentId;
- }
-
- protected CodeComment getComment() {
- return GitPlex.getInstance(CodeCommentManager.class).load(commentId);
- }
-
- private WebMarkupContainer newCommentContainer() {
- WebMarkupContainer commentContainer = new Fragment("comment", "viewFrag", this);
- commentContainer.setOutputMarkupId(true);
-
- commentContainer.add(AttributeAppender.append("class", new LoadableDetachableModel<String>() {
-
- @Override
- protected String load() {
- return getComment().isVisitedAfter(getComment().getDate())?"": "new";
- }
-
- }));
-
- commentContainer.add(new AvatarLink("userAvatar", getComment().getUser()));
- commentContainer.add(new AccountLink("userName", getComment().getUser()));
- commentContainer.add(new Label("activityDescription", "commented"));
- commentContainer.add(new Label("activityDate", DateUtils.formatAge(getComment().getDate())));
- commentContainer.add(new Link<Void>("compareContext") {
-
- @Override
- protected void onConfigure() {
- super.onConfigure();
- setVisible(!getCompareContext(getComment()).equals(getComment().getCompareContext()));
- }
-
- @Override
- public void onClick() {
- CodeComment comment = getComment();
- CompareContext compareContext = comment.getCompareContext();
- PullRequest request = getPullRequest();
- if (request != null) {
- RequestChangesPage.State state = new RequestChangesPage.State();
- state.commentId = comment.getId();
- if (compareContext.isLeftSide()) {
- state.oldCommit = compareContext.getCompareCommit();
- state.newCommit = comment.getCommentPos().getCommit();
- } else {
- state.oldCommit = comment.getCommentPos().getCommit();
- state.newCommit = compareContext.getCompareCommit();
- }
- state.mark = comment.getCommentPos();
- state.pathFilter = compareContext.getPathFilter();
- state.whitespaceOption = compareContext.getWhitespaceOption();
- PageParameters params = RequestChangesPage.paramsOf(request, state);
- setResponsePage(RequestChangesPage.class, params);
- } else {
- RevisionComparePage.State state = new RevisionComparePage.State();
- state.commentId = comment.getId();
- state.compareWithMergeBase = false;
- if (compareContext.isLeftSide()) {
- state.leftSide = new DepotAndRevision(comment.getDepot(), compareContext.getCompareCommit());
- state.rightSide = new DepotAndRevision(comment.getDepot(), comment.getCommentPos().getCommit());
- } else {
- state.leftSide = new DepotAndRevision(comment.getDepot(), comment.getCommentPos().getCommit());
- state.rightSide = new DepotAndRevision(comment.getDepot(), compareContext.getCompareCommit());
- }
- state.mark = comment.getCommentPos();
- state.pathFilter = compareContext.getPathFilter();
- state.tabPanel = RevisionComparePage.TabPanel.CHANGES;
- state.whitespaceOption = compareContext.getWhitespaceOption();
- PageParameters params = RevisionComparePage.paramsOf(comment.getDepot(), state);
- setResponsePage(RevisionComparePage.class, params);
- }
- }
-
- }.add(AttributeAppender.append("title", "This comment is added in a different compare context, click to show")));
-
- MarkdownEditSupport editSupport;
- if (SecurityUtils.canModify(getComment())) {
- editSupport = new MarkdownEditSupport() {
-
- @Override
- public void setContent(String content) {
- CodeComment comment = getComment();
- comment.setContent(content);
- GitPlex.getInstance(CodeCommentManager.class).save(comment);
- }
-
- @Override
- public long getVersion() {
- return getComment().getVersion();
- }
-
- };
- } else {
- editSupport = null;
- }
- commentContainer.add(new MarkdownPanel("content", new AbstractReadOnlyModel<String>() {
-
- @Override
- public String getObject() {
- return getComment().getContent();
- }
-
- }, editSupport));
-
- WebMarkupContainer foot = new WebMarkupContainer("foot");
- foot.setVisible(SecurityUtils.canModify(getComment()));
- foot.add(new AjaxLink<Void>("edit") {
-
- @Override
- public void onClick(AjaxRequestTarget target) {
- Fragment fragment = new Fragment(commentContainer.getId(), "commentEditFrag", CodeCommentPanel.this);
- Form<?> form = new Form<Void>("form");
- form.setOutputMarkupId(true);
-
- TextField<String> titleInput = new TextField<String>("title", Model.of(getComment().getTitle()));
- titleInput.setRequired(true);
- form.add(titleInput);
- CommentInput contentInput = new CommentInput("content", Model.of(getComment().getContent())) {
-
- @Override
- protected AttachmentSupport getAttachmentSupport() {
- return new DepotAttachmentSupport(getComment().getDepot(), getComment().getUUID());
- }
-
- @Override
- protected Depot getDepot() {
- return getComment().getDepot();
- }
-
- };
- form.add(contentInput);
- contentInput.setRequired(true);
-
- NotificationPanel feedback = new NotificationPanel("feedback", form);
- feedback.setOutputMarkupPlaceholderTag(true);
- form.add(feedback);
-
- form.add(new AjaxLink<Void>("cancel") {
-
- @Override
- protected void updateAjaxAttributes(AjaxRequestAttributes attributes) {
- super.updateAjaxAttributes(attributes);
- attributes.getAjaxCallListeners().add(new ConfirmLeaveListener(form));
- }
-
- @Override
- public void onClick(AjaxRequestTarget target) {
- WebMarkupContainer commentContainer = newCommentContainer();
- fragment.replaceWith(commentContainer);
- target.add(commentContainer);
- }
-
- });
-
- long lastVersion = getComment().getVersion();
- form.add(new AjaxButton("save") {
-
- @Override
- protected void onError(AjaxRequestTarget target, Form<?> form) {
- super.onError(target, form);
- target.add(feedback);
- }
-
- @Override
- protected void onSubmit(AjaxRequestTarget target, Form<?> form) {
- super.onSubmit(target, form);
-
- try {
- CodeComment comment = getComment();
- if (comment.getVersion() != lastVersion)
- throw new StaleObjectStateException(CodeComment.class.getName(), comment.getId());
- comment.setTitle(titleInput.getModelObject());
- comment.setContent(contentInput.getModelObject());
- GitPlex.getInstance(CodeCommentManager.class).save(comment);
- WebMarkupContainer commentContainer = newCommentContainer();
- fragment.replaceWith(commentContainer);
- target.add(commentContainer);
- onSaveComment(target, comment);
- } catch (StaleObjectStateException e) {
- error("Some one changed the content you are editing. Reload the page and try again.");
- target.add(feedback);
- }
- }
-
- });
-
- fragment.add(form);
- fragment.setOutputMarkupId(true);
- commentContainer.replaceWith(fragment);
- target.add(fragment);
- }
-
- });
-
- foot.add(new AjaxLink<Void>("delete") {
-
- @Override
- protected void updateAjaxAttributes(AjaxRequestAttributes attributes) {
- super.updateAjaxAttributes(attributes);
- String confirmMessage;
- if (getComment().getReplies().isEmpty()) {
- confirmMessage = "Do you really want to delete this comment?";
- } else {
- confirmMessage = "Deleting this comment will also delete all replies, do you really "
- + "want to continue?";
- }
- attributes.getAjaxCallListeners().add(new ConfirmListener(confirmMessage));
- }
-
- @Override
- public void onClick(AjaxRequestTarget target) {
- onDeleteComment(target, getComment());
- GitPlex.getInstance(CodeCommentManager.class).delete(getComment());
- }
-
- });
-
- commentContainer.add(foot);
- return commentContainer;
- }
-
- private WebMarkupContainer newActivityContainer(String componentId, CodeCommentActivity activity) {
- ActivityIdentity identity = new ActivityIdentity(activity);
- Fragment activityContainer = new Fragment(componentId, "viewFrag", this, Model.of(identity));
- activityContainer.setOutputMarkupId(true);
-
- activityContainer.add(new AvatarLink("userAvatar", activity.getUser()));
- activityContainer.add(new AccountLink("userName", activity.getUser()));
- String activityDescription;
- if (activity instanceof CodeCommentStatusChange) {
- CodeCommentStatusChange statusChange = (CodeCommentStatusChange) activity;
- if (statusChange.isResolved())
- activityDescription = "resolved";
- else
- activityDescription = "unresolved";
- } else {
- activityDescription = "replied";
- }
- activityContainer.add(new Label("activityDescription", activityDescription));
- activityContainer.add(new Label("activityDate", DateUtils.formatAge(activity.getDate())));
- activityContainer.add(new Link<Void>("compareContext") {
-
- @Override
- protected void onConfigure() {
- super.onConfigure();
- setVisible(!getCompareContext(getComment()).equals(identity.getActivity().getCompareContext()));
- }
-
- @Override
- public void onClick() {
- CodeCommentActivity activity = identity.getActivity();
- CompareContext compareContext = activity.getCompareContext();
- PullRequest request = getPullRequest();
- if (request != null) {
- RequestChangesPage.State state = new RequestChangesPage.State();
- state.commentId = activity.getComment().getId();
- if (compareContext.isLeftSide()) {
- state.oldCommit = compareContext.getCompareCommit();
- state.newCommit = activity.getComment().getCommentPos().getCommit();
- } else {
- state.oldCommit = activity.getComment().getCommentPos().getCommit();
- state.newCommit = compareContext.getCompareCommit();
- }
- state.mark = activity.getComment().getCommentPos();
- state.pathFilter = compareContext.getPathFilter();
- state.whitespaceOption = compareContext.getWhitespaceOption();
- PageParameters params = RequestChangesPage.paramsOf(request, state);
- setResponsePage(RequestChangesPage.class, params);
- } else {
- RevisionComparePage.State state = new RevisionComparePage.State();
- CodeComment comment = activity.getComment();
- state.commentId = comment.getId();
- state.compareWithMergeBase = false;
- if (compareContext.isLeftSide()) {
- state.leftSide = new DepotAndRevision(comment.getDepot(), compareContext.getCompareCommit());
- state.rightSide = new DepotAndRevision(comment.getDepot(), comment.getCommentPos().getCommit());
- } else {
- state.leftSide = new DepotAndRevision(comment.getDepot(), comment.getCommentPos().getCommit());
- state.rightSide = new DepotAndRevision(comment.getDepot(), compareContext.getCompareCommit());
- }
- state.mark = comment.getCommentPos();
- state.pathFilter = compareContext.getPathFilter();
- state.tabPanel = RevisionComparePage.TabPanel.CHANGES;
- state.whitespaceOption = compareContext.getWhitespaceOption();
- PageParameters params = RevisionComparePage.paramsOf(comment.getDepot(), state);
- setResponsePage(RevisionComparePage.class, params);
- }
- }
-
- }.add(AttributeAppender.append("title", "This reply is added in a different compare context, click to show")));
-
- if (StringUtils.isNotBlank(activity.getNote())) {
- MarkdownEditSupport editSupport;
- if (SecurityUtils.canModify(getComment())) {
- editSupport = new MarkdownEditSupport() {
-
- @Override
- public void setContent(String content) {
- if (identity.clazz == CodeCommentReply.class) {
- CodeCommentReply reply = (CodeCommentReply) activity;
- reply.setContent(content);
- GitPlex.getInstance(CodeCommentReplyManager.class).save(reply);
- } else {
- CodeCommentStatusChange statusChange = (CodeCommentStatusChange) activity;
- statusChange.setNote(content);
- GitPlex.getInstance(CodeCommentStatusChangeManager.class).save(statusChange);
- }
- }
-
- @Override
- public long getVersion() {
- return identity.getActivity().getVersion();
- }
-
- };
- } else {
- editSupport = null;
- }
- activityContainer.add(new MarkdownPanel("content", new LoadableDetachableModel<String>() {
-
- @Override
- protected String load() {
- return identity.getActivity().getNote();
- }
-
- }, editSupport));
-
- } else {
- activityContainer.add(new Label("content", "<div class='no-note'>No note</div>").setEscapeModelStrings(false));
- }
-
- WebMarkupContainer foot = new WebMarkupContainer("foot");
- foot.setVisible(SecurityUtils.canModify(activity));
-
- foot.add(new AjaxLink<Void>("edit") {
-
- @Override
- public void onClick(AjaxRequestTarget target) {
- Fragment fragment = new Fragment(activityContainer.getId(), "activityEditFrag",
- CodeCommentPanel.this, Model.of(identity.id));
- Form<?> form = new Form<Void>("form");
- CommentInput contentInput = new CommentInput("content", Model.of(identity.getActivity().getNote())) {
-
- @Override
- protected AttachmentSupport getAttachmentSupport() {
- return new DepotAttachmentSupport(getComment().getDepot(), getComment().getUUID());
- }
-
- @Override
- protected Depot getDepot() {
- return getComment().getDepot();
- }
-
- };
- contentInput.setRequired(identity.clazz == CodeCommentReply.class);
- form.add(contentInput);
-
- NotificationPanel feedback = new NotificationPanel("feedback", form);
- feedback.setOutputMarkupPlaceholderTag(true);
- form.add(feedback);
-
- form.add(new AjaxLink<Void>("cancel") {
-
- @Override
- protected void updateAjaxAttributes(AjaxRequestAttributes attributes) {
- super.updateAjaxAttributes(attributes);
- attributes.getAjaxCallListeners().add(new ConfirmLeaveListener(form));
- }
-
- @Override
- public void onClick(AjaxRequestTarget target) {
- WebMarkupContainer replyContainer = newActivityContainer(componentId, identity.getActivity());
- fragment.replaceWith(replyContainer);
- target.add(replyContainer);
- }
-
- });
-
- long lastVersion = identity.getActivity().getVersion();
- form.add(new AjaxButton("save") {
-
- @Override
- protected void onError(AjaxRequestTarget target, Form<?> form) {
- super.onError(target, form);
- target.add(feedback);
- }
-
- @Override
- protected void onSubmit(AjaxRequestTarget target, Form<?> form) {
- super.onSubmit(target, form);
-
- try {
- CodeCommentActivity activity = identity.getActivity();
- if (activity.getVersion() != lastVersion)
- throw new StaleObjectStateException("", "");
-
- if (identity.clazz == CodeCommentReply.class) {
- CodeCommentReply reply = (CodeCommentReply) activity;
- reply.setContent(contentInput.getModelObject());
- GitPlex.getInstance(CodeCommentReplyManager.class).save(reply);
- } else {
- CodeCommentStatusChange statusChange = (CodeCommentStatusChange) activity;
- statusChange.setNote(contentInput.getModelObject());
- GitPlex.getInstance(CodeCommentStatusChangeManager.class).save(statusChange);
- }
- WebMarkupContainer activityContainer = newActivityContainer(componentId, identity.getActivity());
- fragment.replaceWith(activityContainer);
- target.add(activityContainer);
- } catch (StaleObjectStateException e) {
- error("Some one changed the content you are editing. Reload the page and try again.");
- target.add(feedback);
- }
- }
-
- }.add(new Label("label", "Save")));
-
- fragment.add(form);
- fragment.setOutputMarkupId(true);
- activityContainer.replaceWith(fragment);
- target.add(fragment);
- }
-
- });
- foot.add(new AjaxLink<Void>("delete") {
-
- @Override
- protected void updateAjaxAttributes(AjaxRequestAttributes attributes) {
- super.updateAjaxAttributes(attributes);
- attributes.getAjaxCallListeners().add(new ConfirmListener("Do you really want to delete this reply?"));
- }
-
- @Override
- public void onClick(AjaxRequestTarget target) {
- activityContainer.remove();
- GitPlex.getInstance(CodeCommentReplyManager.class).delete((CodeCommentReply) identity.getActivity());
- String script = String.format("$('#%s').remove();", activityContainer.getMarkupId());
- target.appendJavaScript(script);
- }
-
- }.setVisible(activity instanceof CodeCommentReply));
-
- activityContainer.add(foot);
- return activityContainer;
- }
-
- private WebMarkupContainer newAddReplyContainer() {
- WebMarkupContainer addReplyContainer = new Fragment("addReply", "addReplyFrag", this) {
-
- @Override
- protected void onConfigure() {
- super.onConfigure();
- setVisible(SecurityUtils.getAccount() != null);
- }
-
- };
- addReplyContainer.setOutputMarkupId(true);
- addReplyContainer.add(new AjaxLink<Void>("reply") {
-
- @Override
- public void onClick(AjaxRequestTarget target) {
- onAddReply(target, false);
- }
-
- });
- return addReplyContainer;
- }
-
- @Override
- protected void onInitialize() {
- super.onInitialize();
-
- add(newCommentContainer());
-
- activitiesView = new RepeatingView("activities");
- PullRequest request = getPullRequest();
-
- List<CodeCommentActivity> activities = new ArrayList<>();
- for (CodeCommentReply reply: getComment().getReplies()) {
- if (request == null || request.getRequestComparingInfo(reply.getComparingInfo()) != null) {
- activities.add(reply);
- }
- }
- for (CodeCommentStatusChange statusChange: getComment().getStatusChanges()) {
- if (request == null || request.getRequestComparingInfo(statusChange.getComparingInfo()) != null) {
- activities.add(statusChange);
- }
- }
-
- activities.sort((o1, o2)->o1.getDate().compareTo(o2.getDate()));
-
- for (CodeCommentActivity activity: activities) {
- Component activityContainer = newActivityContainer(activitiesView.newChildId(), activity);
- if (!getComment().isVisitedAfter(activity.getDate()))
- activityContainer.add(AttributeAppender.append("class", "new"));
- activitiesView.add(activityContainer);
- }
- add(activitiesView);
- add(newAddReplyContainer());
-
- setOutputMarkupId(true);
-
- add(new WebSocketRenderBehavior() {
-
- @Override
- protected void onRender(WebSocketRequestHandler handler) {
- Date lastActivityDate;
- String prevActivityMarkupId;
- if (activitiesView.size() != 0) {
- @SuppressWarnings("deprecation")
- Component lastActivityContainer = activitiesView.get(activitiesView.size()-1);
-
- CodeCommentActivity lastActivity = ((ActivityIdentity) lastActivityContainer.getDefaultModelObject()).getActivity();
- lastActivityDate = lastActivity.getDate();
- prevActivityMarkupId = lastActivityContainer.getMarkupId();
- } else {
- lastActivityDate = getComment().getDate();
- prevActivityMarkupId = get("comment").getMarkupId();
- }
-
- PullRequest request = getPullRequest();
- List<CodeCommentActivity> activities = new ArrayList<>();
- for (CodeCommentReply reply: getComment().getReplies()) {
- if (reply.getDate().getTime()>lastActivityDate.getTime()
- && (request == null || request.getRequestComparingInfo(reply.getComparingInfo()) != null)) {
- activities.add(reply);
- }
- }
- for (CodeCommentStatusChange statusChange: getComment().getStatusChanges()) {
- if (statusChange.getDate().getTime()>lastActivityDate.getTime()
- && (request == null || request.getRequestComparingInfo(statusChange.getComparingInfo()) != null)) {
- activities.add(statusChange);
- }
- }
- activities.sort((o1, o2)->o1.getDate().compareTo(o2.getDate()));
-
- for (CodeCommentActivity activity: activities) {
- Component newActivityContainer = newActivityContainer(activitiesView.newChildId(), activity);
- newActivityContainer.add(AttributeAppender.append("class", "new"));
- activitiesView.add(newActivityContainer);
-
- String script = String.format("$(\"<tr id='%s'></tr>\").insertAfter('#%s');",
- newActivityContainer.getMarkupId(), prevActivityMarkupId);
- handler.prependJavaScript(script);
- handler.add(newActivityContainer);
- prevActivityMarkupId = newActivityContainer.getMarkupId();
- }
- }
-
- @Override
- protected void onInitialRenderDetach() {
- Account user = SecurityUtils.getAccount();
- if (user != null)
- GitPlex.getInstance(VisitInfoManager.class).visit(user, getComment());
- super.onInitialRenderDetach();
- }
-
- });
- }
-
- @Override
- public void renderHead(IHeaderResponse response) {
- super.renderHead(response);
- response.render(CssHeaderItem.forReference(new CssResourceReference(
- CodeCommentPanel.class, "code-comment.css")));
- }
-
- private void onAddReply(AjaxRequestTarget target, boolean changeStatus) {
- Fragment fragment = new Fragment("addReply", "activityEditFrag", CodeCommentPanel.this);
- Form<?> form = new Form<Void>("form");
- CommentInput contentInput = new CommentInput("content", Model.of("")) {
-
- @Override
- protected AttachmentSupport getAttachmentSupport() {
- return new DepotAttachmentSupport(getComment().getDepot(), getComment().getUUID());
- }
-
- @Override
- protected Depot getDepot() {
- return getComment().getDepot();
- }
-
- };
- contentInput.setRequired(!changeStatus);
- form.add(contentInput);
-
- NotificationPanel feedback = new NotificationPanel("feedback", form);
- feedback.setOutputMarkupPlaceholderTag(true);
- form.add(feedback);
-
- form.add(new AjaxLink<Void>("cancel") {
-
- @Override
- protected void updateAjaxAttributes(AjaxRequestAttributes attributes) {
- super.updateAjaxAttributes(attributes);
- attributes.getAjaxCallListeners().add(new ConfirmLeaveListener(form));
- }
-
- @Override
- public void onClick(AjaxRequestTarget target) {
- WebMarkupContainer addReplyContainer = newAddReplyContainer();
- fragment.replaceWith(addReplyContainer);
- target.add(addReplyContainer);
- }
-
- });
-
- AjaxButton saveButton = new AjaxButton("save") {
-
- @Override
- protected void onError(AjaxRequestTarget target, Form<?> form) {
- super.onError(target, form);
- target.add(feedback);
- }
-
- @Override
- protected void onSubmit(AjaxRequestTarget target, Form<?> form) {
- super.onSubmit(target, form);
-
- Account user = SecurityUtils.getAccount();
- CodeComment comment = getComment();
- Date date = new Date();
- CompareContext compareContext = getCompareContext(comment);
- if (changeStatus) {
- CodeCommentStatusChange statusChange = new CodeCommentStatusChange();
- statusChange.setComment(getComment());
- statusChange.setUser(user);
- statusChange.setCompareContext(compareContext);
- statusChange.setResolved(!comment.isResolved());
- statusChange.setDate(date);
- statusChange.setNote(contentInput.getModelObject());
-
- GitPlex.getInstance(CodeCommentManager.class).changeStatus(statusChange);
- onStatusChanged(target, fragment, statusChange);
- onSaveComment(target, getComment());
- } else {
- CodeCommentReply reply = new CodeCommentReply();
- reply.setComment(comment);
- reply.setDate(date);
- reply.setUser(user);
- reply.setContent(contentInput.getModelObject());
- reply.setCompareContext(compareContext);
- GitPlex.getInstance(CodeCommentReplyManager.class).save(reply);
- onReplyAdded(target, fragment, reply);
- }
- }
-
- };
- if (changeStatus) {
- saveButton.add(new Label("label", getComment().isResolved()?"Confirm unresolve":"Confirm resolve"));
- } else {
- saveButton.add(new Label("label", "Save"));
- saveButton.add(AttributeAppender.append("class", "dirty-aware"));
- }
- form.add(saveButton);
-
- fragment.add(form);
- fragment.setOutputMarkupId(true);
- get("addReply").replaceWith(fragment);
- target.add(fragment);
- }
-
- public void onChangeStatus(AjaxRequestTarget target) {
- onAddReply(target, true);
- }
-
- private void onStatusChanged(AjaxRequestTarget target, Fragment fragment, CodeCommentStatusChange statusChange) {
- WebMarkupContainer activityContainer = newActivityContainer(activitiesView.newChildId(), statusChange);
- activitiesView.add(activityContainer);
-
- String script = String.format("$('#%s .add-reply').before('<div id=\"%s\"></div>');",
- CodeCommentPanel.this.getMarkupId(), activityContainer.getMarkupId());
- target.prependJavaScript(script);
- target.add(activityContainer);
-
- WebMarkupContainer addReplyContainer = newAddReplyContainer();
- fragment.replaceWith(addReplyContainer);
- target.add(addReplyContainer);
- }
-
- private void onReplyAdded(AjaxRequestTarget target, Fragment fragment, @Nullable CodeCommentReply reply) {
- if (reply != null) {
- WebMarkupContainer activityContainer = newActivityContainer(activitiesView.newChildId(), reply);
- activitiesView.add(activityContainer);
-
- String script = String.format("$('#%s .add-reply').before('<div id=\"%s\"></div>');",
- CodeCommentPanel.this.getMarkupId(), activityContainer.getMarkupId());
- target.prependJavaScript(script);
- target.add(activityContainer);
- }
-
- WebMarkupContainer addReplyContainer = newAddReplyContainer();
- fragment.replaceWith(addReplyContainer);
- target.add(addReplyContainer);
- }
-
- protected abstract void onDeleteComment(AjaxRequestTarget target, CodeComment comment);
-
- protected abstract void onSaveComment(AjaxRequestTarget target, CodeComment comment);
-
- protected abstract CompareContext getCompareContext(CodeComment comment);
-
- @Nullable
- protected abstract PullRequest getPullRequest();
-
- private static class ActivityIdentity implements Serializable {
-
- final Class<? extends CodeCommentActivity> clazz;
-
- final Long id;
-
- ActivityIdentity(CodeCommentActivity activity) {
- this.clazz = activity.getClass();
- this.id = activity.getId();
- }
-
- CodeCommentActivity getActivity() {
- return GitPlex.getInstance(Dao.class).load(clazz, id);
- }
-
- }
-}
+package com.pmease.gitplex.web.component.comment;
+
+import java.io.Serializable;
+import java.util.ArrayList;
+import java.util.Date;
+import java.util.List;
+
+import javax.annotation.Nullable;
+
+import org.apache.commons.lang3.StringUtils;
+import org.apache.wicket.Component;
+import org.apache.wicket.ajax.AjaxRequestTarget;
+import org.apache.wicket.ajax.attributes.AjaxRequestAttributes;
+import org.apache.wicket.ajax.markup.html.AjaxLink;
+import org.apache.wicket.ajax.markup.html.form.AjaxButton;
+import org.apache.wicket.behavior.AttributeAppender;
+import org.apache.wicket.markup.head.CssHeaderItem;
+import org.apache.wicket.markup.head.IHeaderResponse;
+import org.apache.wicket.markup.html.WebMarkupContainer;
+import org.apache.wicket.markup.html.basic.Label;
+import org.apache.wicket.markup.html.form.Form;
+import org.apache.wicket.markup.html.form.TextField;
+import org.apache.wicket.markup.html.link.Link;
+import org.apache.wicket.markup.html.panel.Fragment;
+import org.apache.wicket.markup.html.panel.Panel;
+import org.apache.wicket.markup.repeater.RepeatingView;
+import org.apache.wicket.model.AbstractReadOnlyModel;
+import org.apache.wicket.model.LoadableDetachableModel;
+import org.apache.wicket.model.Model;
+import org.apache.wicket.protocol.ws.api.WebSocketRequestHandler;
+import org.apache.wicket.request.mapper.parameter.PageParameters;
+import org.apache.wicket.request.resource.CssResourceReference;
+import org.hibernate.StaleStateException;
+
+import com.pmease.commons.hibernate.dao.Dao;
+import com.pmease.commons.wicket.ajaxlistener.ConfirmLeaveListener;
+import com.pmease.commons.wicket.ajaxlistener.ConfirmListener;
+import com.pmease.commons.wicket.behavior.markdown.AttachmentSupport;
+import com.pmease.commons.wicket.component.markdown.MarkdownEditSupport;
+import com.pmease.commons.wicket.component.markdown.MarkdownPanel;
+import com.pmease.commons.wicket.websocket.WebSocketRenderBehavior;
+import com.pmease.gitplex.core.GitPlex;
+import com.pmease.gitplex.core.entity.Account;
+import com.pmease.gitplex.core.entity.CodeComment;
+import com.pmease.gitplex.core.entity.CodeCommentReply;
+import com.pmease.gitplex.core.entity.CodeCommentStatusChange;
+import com.pmease.gitplex.core.entity.Depot;
+import com.pmease.gitplex.core.entity.PullRequest;
+import com.pmease.gitplex.core.entity.support.CodeCommentActivity;
+import com.pmease.gitplex.core.entity.support.CompareContext;
+import com.pmease.gitplex.core.entity.support.DepotAndRevision;
+import com.pmease.gitplex.core.manager.CodeCommentManager;
+import com.pmease.gitplex.core.manager.CodeCommentReplyManager;
+import com.pmease.gitplex.core.manager.CodeCommentStatusChangeManager;
+import com.pmease.gitplex.core.manager.VisitInfoManager;
+import com.pmease.gitplex.core.security.SecurityUtils;
+import com.pmease.gitplex.web.component.AccountLink;
+import com.pmease.gitplex.web.component.avatar.AvatarLink;
+import com.pmease.gitplex.web.page.depot.compare.RevisionComparePage;
+import com.pmease.gitplex.web.page.depot.pullrequest.requestdetail.changes.RequestChangesPage;
+import com.pmease.gitplex.web.util.DateUtils;
+
+import de.agilecoders.wicket.core.markup.html.bootstrap.common.NotificationPanel;
+
+@SuppressWarnings("serial")
+public abstract class CodeCommentPanel extends Panel {
+
+ private final Long commentId;
+
+ private RepeatingView activitiesView;
+
+ /**
+ * We pass comment id instead of comment model as we want to make sure that
+ * comment is always loaded upon usage as this panel is involved in websocket
+ * update and websocket update does not detach models at end of request which
+ * may result in Hibernate lazy load exception when the comment is used again
+ * in next request
+ *
+ * @param id
+ * @param commentId
+ */
+ public CodeCommentPanel(String id, Long commentId) {
+ super(id);
+ this.commentId = commentId;
+ }
+
+ protected CodeComment getComment() {
+ return GitPlex.getInstance(CodeCommentManager.class).load(commentId);
+ }
+
+ private WebMarkupContainer newCommentContainer() {
+ WebMarkupContainer commentContainer = new Fragment("comment", "viewFrag", this);
+ commentContainer.setOutputMarkupId(true);
+
+ commentContainer.add(AttributeAppender.append("class", new LoadableDetachableModel<String>() {
+
+ @Override
+ protected String load() {
+ return getComment().isVisitedAfter(getComment().getDate())?"": "new";
+ }
+
+ }));
+
+ commentContainer.add(new AvatarLink("userAvatar", getComment().getUser()));
+ commentContainer.add(new AccountLink("userName", getComment().getUser()));
+ commentContainer.add(new Label("activityDescription", "commented"));
+ commentContainer.add(new Label("activityDate", DateUtils.formatAge(getComment().getDate())));
+ commentContainer.add(new Link<Void>("compareContext") {
+
+ @Override
+ protected void onConfigure() {
+ super.onConfigure();
+ setVisible(!getCompareContext(getComment()).equals(getComment().getCompareContext()));
+ }
+
+ @Override
+ public void onClick() {
+ CodeComment comment = getComment();
+ CompareContext compareContext = comment.getCompareContext();
+ PullRequest request = getPullRequest();
+ if (request != null) {
+ RequestChangesPage.State state = new RequestChangesPage.State();
+ state.commentId = comment.getId();
+ if (compareContext.isLeftSide()) {
+ state.oldCommit = compareContext.getCompareCommit();
+ state.newCommit = comment.getCommentPos().getCommit();
+ } else {
+ state.oldCommit = comment.getCommentPos().getCommit();
+ state.newCommit = compareContext.getCompareCommit();
+ }
+ state.mark = comment.getCommentPos();
+ state.pathFilter = compareContext.getPathFilter();
+ state.whitespaceOption = compareContext.getWhitespaceOption();
+ PageParameters params = RequestChangesPage.paramsOf(request, state);
+ setResponsePage(RequestChangesPage.class, params);
+ } else {
+ RevisionComparePage.State state = new RevisionComparePage.State();
+ state.commentId = comment.getId();
+ state.compareWithMergeBase = false;
+ if (compareContext.isLeftSide()) {
+ state.leftSide = new DepotAndRevision(comment.getDepot(), compareContext.getCompareCommit());
+ state.rightSide = new DepotAndRevision(comment.getDepot(), comment.getCommentPos().getCommit());
+ } else {
+ state.leftSide = new DepotAndRevision(comment.getDepot(), comment.getCommentPos().getCommit());
+ state.rightSide = new DepotAndRevision(comment.getDepot(), compareContext.getCompareCommit());
+ }
+ state.mark = comment.getCommentPos();
+ state.pathFilter = compareContext.getPathFilter();
+ state.tabPanel = RevisionComparePage.TabPanel.CHANGES;
+ state.whitespaceOption = compareContext.getWhitespaceOption();
+ PageParameters params = RevisionComparePage.paramsOf(comment.getDepot(), state);
+ setResponsePage(RevisionComparePage.class, params);
+ }
+ }
+
+ }.add(AttributeAppender.append("title", "This comment is added in a different compare context, click to show")));
+
+ MarkdownEditSupport editSupport;
+ if (SecurityUtils.canModify(getComment())) {
+ editSupport = new MarkdownEditSupport() {
+
+ @Override
+ public void setContent(String content) {
+ CodeComment comment = getComment();
+ comment.setContent(content);
+ GitPlex.getInstance(CodeCommentManager.class).save(comment);
+ }
+
+ @Override
+ public long getVersion() {
+ return getComment().getVersion();
+ }
+
+ };
+ } else {
+ editSupport = null;
+ }
+ commentContainer.add(new MarkdownPanel("content", new AbstractReadOnlyModel<String>() {
+
+ @Override
+ public String getObject() {
+ return getComment().getContent();
+ }
+
+ }, editSupport));
+
+ WebMarkupContainer foot = new WebMarkupContainer("foot");
+ foot.setVisible(SecurityUtils.canModify(getComment()));
+ foot.add(new AjaxLink<Void>("edit") {
+
+ @Override
+ public void onClick(AjaxRequestTarget target) {
+ Fragment fragment = new Fragment(commentContainer.getId(), "commentEditFrag", CodeCommentPanel.this);
+ Form<?> form = new Form<Void>("form");
+ form.setOutputMarkupId(true);
+
+ TextField<String> titleInput = new TextField<String>("title", Model.of(getComment().getTitle()));
+ titleInput.setRequired(true);
+ form.add(titleInput);
+ CommentInput contentInput = new CommentInput("content", Model.of(getComment().getContent())) {
+
+ @Override
+ protected AttachmentSupport getAttachmentSupport() {
+ return new DepotAttachmentSupport(getComment().getDepot(), getComment().getUUID());
+ }
+
+ @Override
+ protected Depot getDepot() {
+ return getComment().getDepot();
+ }
+
+ };
+ form.add(contentInput);
+ contentInput.setRequired(true);
+
+ NotificationPanel feedback = new NotificationPanel("feedback", form);
+ feedback.setOutputMarkupPlaceholderTag(true);
+ form.add(feedback);
+
+ form.add(new AjaxLink<Void>("cancel") {
+
+ @Override
+ protected void updateAjaxAttributes(AjaxRequestAttributes attributes) {
+ super.updateAjaxAttributes(attributes);
+ attributes.getAjaxCallListeners().add(new ConfirmLeaveListener(form));
+ }
+
+ @Override
+ public void onClick(AjaxRequestTarget target) {
+ WebMarkupContainer commentContainer = newCommentContainer();
+ fragment.replaceWith(commentContainer);
+ target.add(commentContainer);
+ }
+
+ });
+
+ long lastVersion = getComment().getVersion();
+ form.add(new AjaxButton("save") {
+
+ @Override
+ protected void onError(AjaxRequestTarget target, Form<?> form) {
+ super.onError(target, form);
+ target.add(feedback);
+ }
+
+ @Override
+ protected void onSubmit(AjaxRequestTarget target, Form<?> form) {
+ super.onSubmit(target, form);
+
+ try {
+ CodeComment comment = getComment();
+ if (comment.getVersion() != lastVersion)
+ throw new StaleStateException("");
+ comment.setTitle(titleInput.getModelObject());
+ comment.setContent(contentInput.getModelObject());
+ GitPlex.getInstance(CodeCommentManager.class).save(comment);
+ WebMarkupContainer commentContainer = newCommentContainer();
+ fragment.replaceWith(commentContainer);
+ target.add(commentContainer);
+ onSaveComment(target, comment);
+ } catch (StaleStateException e) {
+ error("Some one changed the content you are editing. Reload the page and try again.");
+ target.add(feedback);
+ }
+ }
+
+ });
+
+ fragment.add(form);
+ fragment.setOutputMarkupId(true);
+ commentContainer.replaceWith(fragment);
+ target.add(fragment);
+ }
+
+ });
+
+ foot.add(new AjaxLink<Void>("delete") {
+
+ @Override
+ protected void updateAjaxAttributes(AjaxRequestAttributes attributes) {
+ super.updateAjaxAttributes(attributes);
+ String confirmMessage;
+ if (getComment().getReplies().isEmpty()) {
+ confirmMessage = "Do you really want to delete this comment?";
+ } else {
+ confirmMessage = "Deleting this comment will also delete all replies, do you really "
+ + "want to continue?";
+ }
+ attributes.getAjaxCallListeners().add(new ConfirmListener(confirmMessage));
+ }
+
+ @Override
+ public void onClick(AjaxRequestTarget target) {
+ onDeleteComment(target, getComment());
+ GitPlex.getInstance(CodeCommentManager.class).delete(getComment());
+ }
+
+ });
+
+ commentContainer.add(foot);
+ return commentContainer;
+ }
+
+ private WebMarkupContainer newActivityContainer(String componentId, CodeCommentActivity activity) {
+ ActivityIdentity identity = new ActivityIdentity(activity);
+ Fragment activityContainer = new Fragment(componentId, "viewFrag", this, Model.of(identity));
+ activityContainer.setOutputMarkupId(true);
+
+ activityContainer.add(new AvatarLink("userAvatar", activity.getUser()));
+ activityContainer.add(new AccountLink("userName", activity.getUser()));
+ String activityDescription;
+ if (activity instanceof CodeCommentStatusChange) {
+ CodeCommentStatusChange statusChange = (CodeCommentStatusChange) activity;
+ if (statusChange.isResolved())
+ activityDescription = "resolved";
+ else
+ activityDescription = "unresolved";
+ } else {
+ activityDescription = "replied";
+ }
+ activityContainer.add(new Label("activityDescription", activityDescription));
+ activityContainer.add(new Label("activityDate", DateUtils.formatAge(activity.getDate())));
+ activityContainer.add(new Link<Void>("compareContext") {
+
+ @Override
+ protected void onConfigure() {
+ super.onConfigure();
+ setVisible(!getCompareContext(getComment()).equals(identity.getActivity().getCompareContext()));
+ }
+
+ @Override
+ public void onClick() {
+ CodeCommentActivity activity = identity.getActivity();
+ CompareContext compareContext = activity.getCompareContext();
+ PullRequest request = getPullRequest();
+ if (request != null) {
+ RequestChangesPage.State state = new RequestChangesPage.State();
+ state.commentId = activity.getComment().getId();
+ if (compareContext.isLeftSide()) {
+ state.oldCommit = compareContext.getCompareCommit();
+ state.newCommit = activity.getComment().getCommentPos().getCommit();
+ } else {
+ state.oldCommit = activity.getComment().getCommentPos().getCommit();
+ state.newCommit = compareContext.getCompareCommit();
+ }
+ state.mark = activity.getComment().getCommentPos();
+ state.pathFilter = compareContext.getPathFilter();
+ state.whitespaceOption = compareContext.getWhitespaceOption();
+ PageParameters params = RequestChangesPage.paramsOf(request, state);
+ setResponsePage(RequestChangesPage.class, params);
+ } else {
+ RevisionComparePage.State state = new RevisionComparePage.State();
+ CodeComment comment = activity.getComment();
+ state.commentId = comment.getId();
+ state.compareWithMergeBase = false;
+ if (compareContext.isLeftSide()) {
+ state.leftSide = new DepotAndRevision(comment.getDepot(), compareContext.getCompareCommit());
+ state.rightSide = new DepotAndRevision(comment.getDepot(), comment.getCommentPos().getCommit());
+ } else {
+ state.leftSide = new DepotAndRevision(comment.getDepot(), comment.getCommentPos().getCommit());
+ state.rightSide = new DepotAndRevision(comment.getDepot(), compareContext.getCompareCommit());
+ }
+ state.mark = comment.getCommentPos();
+ state.pathFilter = compareContext.getPathFilter();
+ state.tabPanel = RevisionComparePage.TabPanel.CHANGES;
+ state.whitespaceOption = compareContext.getWhitespaceOption();
+ PageParameters params = RevisionComparePage.paramsOf(comment.getDepot(), state);
+ setResponsePage(RevisionComparePage.class, params);
+ }
+ }
+
+ }.add(AttributeAppender.append("title", "This reply is added in a different compare context, click to show")));
+
+ if (StringUtils.isNotBlank(activity.getNote())) {
+ MarkdownEditSupport editSupport;
+ if (SecurityUtils.canModify(getComment())) {
+ editSupport = new MarkdownEditSupport() {
+
+ @Override
+ public void setContent(String content) {
+ if (identity.clazz == CodeCommentReply.class) {
+ CodeCommentReply reply = (CodeCommentReply) activity;
+ reply.setContent(content);
+ GitPlex.getInstance(CodeCommentReplyManager.class).save(reply);
+ } else {
+ CodeCommentStatusChange statusChange = (CodeCommentStatusChange) activity;
+ statusChange.setNote(content);
+ GitPlex.getInstance(CodeCommentStatusChangeManager.class).save(statusChange);
+ }
+ }
+
+ @Override
+ public long getVersion() {
+ return identity.getActivity().getVersion();
+ }
+
+ };
+ } else {
+ editSupport = null;
+ }
+ activityContainer.add(new MarkdownPanel("content", new LoadableDetachableModel<String>() {
+
+ @Override
+ protected String load() {
+ return identity.getActivity().getNote();
+ }
+
+ }, editSupport));
+
+ } else {
+ activityContainer.add(new Label("content", "<div class='no-note'>No note</div>").setEscapeModelStrings(false));
+ }
+
+ WebMarkupContainer foot = new WebMarkupContainer("foot");
+ foot.setVisible(SecurityUtils.canModify(activity));
+
+ foot.add(new AjaxLink<Void>("edit") {
+
+ @Override
+ public void onClick(AjaxRequestTarget target) {
+ Fragment fragment = new Fragment(activityContainer.getId(), "activityEditFrag",
+ CodeCommentPanel.this, Model.of(identity.id));
+ Form<?> form = new Form<Void>("form");
+ CommentInput contentInput = new CommentInput("content", Model.of(identity.getActivity().getNote())) {
+
+ @Override
+ protected AttachmentSupport getAttachmentSupport() {
+ return new DepotAttachmentSupport(getComment().getDepot(), getComment().getUUID());
+ }
+
+ @Override
+ protected Depot getDepot() {
+ return getComment().getDepot();
+ }
+
+ };
+ contentInput.setRequired(identity.clazz == CodeCommentReply.class);
+ form.add(contentInput);
+
+ NotificationPanel feedback = new NotificationPanel("feedback", form);
+ feedback.setOutputMarkupPlaceholderTag(true);
+ form.add(feedback);
+
+ form.add(new AjaxLink<Void>("cancel") {
+
+ @Override
+ protected void updateAjaxAttributes(AjaxRequestAttributes attributes) {
+ super.updateAjaxAttributes(attributes);
+ attributes.getAjaxCallListeners().add(new ConfirmLeaveListener(form));
+ }
+
+ @Override
+ public void onClick(AjaxRequestTarget target) {
+ WebMarkupContainer replyContainer = newActivityContainer(componentId, identity.getActivity());
+ fragment.replaceWith(replyContainer);
+ target.add(replyContainer);
+ }
+
+ });
+
+ long lastVersion = identity.getActivity().getVersion();
+ form.add(new AjaxButton("save") {
+
+ @Override
+ protected void onError(AjaxRequestTarget target, Form<?> form) {
+ super.onError(target, form);
+ target.add(feedback);
+ }
+
+ @Override
+ protected void onSubmit(AjaxRequestTarget target, Form<?> form) {
+ super.onSubmit(target, form);
+
+ try {
+ CodeCommentActivity activity = identity.getActivity();
+ if (activity.getVersion() != lastVersion)
+ throw new StaleStateException("");
+
+ if (identity.clazz == CodeCommentReply.class) {
+ CodeCommentReply reply = (CodeCommentReply) activity;
+ reply.setContent(contentInput.getModelObject());
+ GitPlex.getInstance(CodeCommentReplyManager.class).save(reply);
+ } else {
+ CodeCommentStatusChange statusChange = (CodeCommentStatusChange) activity;
+ statusChange.setNote(contentInput.getModelObject());
+ GitPlex.getInstance(CodeCommentStatusChangeManager.class).save(statusChange);
+ }
+ WebMarkupContainer activityContainer = newActivityContainer(componentId, identity.getActivity());
+ fragment.replaceWith(activityContainer);
+ target.add(activityContainer);
+ } catch (StaleStateException e) {
+ error("Some one changed the content you are editing. Reload the page and try again.");
+ target.add(feedback);
+ }
+ }
+
+ }.add(new Label("label", "Save")));
+
+ fragment.add(form);
+ fragment.setOutputMarkupId(true);
+ activityContainer.replaceWith(fragment);
+ target.add(fragment);
+ }
+
+ });
+ foot.add(new AjaxLink<Void>("delete") {
+
+ @Override
+ protected void updateAjaxAttributes(AjaxRequestAttributes attributes) {
+ super.updateAjaxAttributes(attributes);
+ attributes.getAjaxCallListeners().add(new ConfirmListener("Do you really want to delete this reply?"));
+ }
+
+ @Override
+ public void onClick(AjaxRequestTarget target) {
+ activityContainer.remove();
+ GitPlex.getInstance(CodeCommentReplyManager.class).delete((CodeCommentReply) identity.getActivity());
+ String script = String.format("$('#%s').remove();", activityContainer.getMarkupId());
+ target.appendJavaScript(script);
+ }
+
+ }.setVisible(activity instanceof CodeCommentReply));
+
+ activityContainer.add(foot);
+ return activityContainer;
+ }
+
+ private WebMarkupContainer newAddReplyContainer() {
+ WebMarkupContainer addReplyContainer = new Fragment("addReply", "addReplyFrag", this) {
+
+ @Override
+ protected void onConfigure() {
+ super.onConfigure();
+ setVisible(SecurityUtils.getAccount() != null);
+ }
+
+ };
+ addReplyContainer.setOutputMarkupId(true);
+ addReplyContainer.add(new AjaxLink<Void>("reply") {
+
+ @Override
+ public void onClick(AjaxRequestTarget target) {
+ onAddReply(target, false);
+ }
+
+ });
+ return addReplyContainer;
+ }
+
+ @Override
+ protected void onInitialize() {
+ super.onInitialize();
+
+ add(newCommentContainer());
+
+ activitiesView = new RepeatingView("activities");
+ PullRequest request = getPullRequest();
+
+ List<CodeCommentActivity> activities = new ArrayList<>();
+ for (CodeCommentReply reply: getComment().getReplies()) {
+ if (request == null || request.getRequestComparingInfo(reply.getComparingInfo()) != null) {
+ activities.add(reply);
+ }
+ }
+ for (CodeCommentStatusChange statusChange: getComment().getStatusChanges()) {
+ if (request == null || request.getRequestComparingInfo(statusChange.getComparingInfo()) != null) {
+ activities.add(statusChange);
+ }
+ }
+
+ activities.sort((o1, o2)->o1.getDate().compareTo(o2.getDate()));
+
+ for (CodeCommentActivity activity: activities) {
+ Component activityContainer = newActivityContainer(activitiesView.newChildId(), activity);
+ if (!getComment().isVisitedAfter(activity.getDate()))
+ activityContainer.add(AttributeAppender.append("class", "new"));
+ activitiesView.add(activityContainer);
+ }
+ add(activitiesView);
+ add(newAddReplyContainer());
+
+ setOutputMarkupId(true);
+
+ add(new WebSocketRenderBehavior() {
+
+ @Override
+ protected void onRender(WebSocketRequestHandler handler) {
+ Date lastActivityDate;
+ String prevActivityMarkupId;
+ if (activitiesView.size() != 0) {
+ @SuppressWarnings("deprecation")
+ Component lastActivityContainer = activitiesView.get(activitiesView.size()-1);
+
+ CodeCommentActivity lastActivity = ((ActivityIdentity) lastActivityContainer.getDefaultModelObject()).getActivity();
+ lastActivityDate = lastActivity.getDate();
+ prevActivityMarkupId = lastActivityContainer.getMarkupId();
+ } else {
+ lastActivityDate = getComment().getDate();
+ prevActivityMarkupId = get("comment").getMarkupId();
+ }
+
+ PullRequest request = getPullRequest();
+ List<CodeCommentActivity> activities = new ArrayList<>();
+ for (CodeCommentReply reply: getComment().getReplies()) {
+ if (reply.getDate().getTime()>lastActivityDate.getTime()
+ && (request == null || request.getRequestComparingInfo(reply.getComparingInfo()) != null)) {
+ activities.add(reply);
+ }
+ }
+ for (CodeCommentStatusChange statusChange: getComment().getStatusChanges()) {
+ if (statusChange.getDate().getTime()>lastActivityDate.getTime()
+ && (request == null || request.getRequestComparingInfo(statusChange.getComparingInfo()) != null)) {
+ activities.add(statusChange);
+ }
+ }
+ activities.sort((o1, o2)->o1.getDate().compareTo(o2.getDate()));
+
+ for (CodeCommentActivity activity: activities) {
+ Component newActivityContainer = newActivityContainer(activitiesView.newChildId(), activity);
+ newActivityContainer.add(AttributeAppender.append("class", "new"));
+ activitiesView.add(newActivityContainer);
+
+ String script = String.format("$(\"<tr id='%s'></tr>\").insertAfter('#%s');",
+ newActivityContainer.getMarkupId(), prevActivityMarkupId);
+ handler.prependJavaScript(script);
+ handler.add(newActivityContainer);
+ prevActivityMarkupId = newActivityContainer.getMarkupId();
+ }
+ }
+
+ @Override
+ protected void onInitialRenderDetach() {
+ Account user = SecurityUtils.getAccount();
+ if (user != null)
+ GitPlex.getInstance(VisitInfoManager.class).visit(user, getComment());
+ super.onInitialRenderDetach();
+ }
+
+ });
+ }
+
+ @Override
+ public void renderHead(IHeaderResponse response) {
+ super.renderHead(response);
+ response.render(CssHeaderItem.forReference(new CssResourceReference(
+ CodeCommentPanel.class, "code-comment.css")));
+ }
+
+ private void onAddReply(AjaxRequestTarget target, boolean changeStatus) {
+ Fragment fragment = new Fragment("addReply", "activityEditFrag", CodeCommentPanel.this);
+ Form<?> form = new Form<Void>("form");
+ CommentInput contentInput = new CommentInput("content", Model.of("")) {
+
+ @Override
+ protected AttachmentSupport getAttachmentSupport() {
+ return new DepotAttachmentSupport(getComment().getDepot(), getComment().getUUID());
+ }
+
+ @Override
+ protected Depot getDepot() {
+ return getComment().getDepot();
+ }
+
+ };
+ contentInput.setRequired(!changeStatus);
+ form.add(contentInput);
+
+ NotificationPanel feedback = new NotificationPanel("feedback", form);
+ feedback.setOutputMarkupPlaceholderTag(true);
+ form.add(feedback);
+
+ form.add(new AjaxLink<Void>("cancel") {
+
+ @Override
+ protected void updateAjaxAttributes(AjaxRequestAttributes attributes) {
+ super.updateAjaxAttributes(attributes);
+ attributes.getAjaxCallListeners().add(new ConfirmLeaveListener(form));
+ }
+
+ @Override
+ public void onClick(AjaxRequestTarget target) {
+ WebMarkupContainer addReplyContainer = newAddReplyContainer();
+ fragment.replaceWith(addReplyContainer);
+ target.add(addReplyContainer);
+ }
+
+ });
+
+ AjaxButton saveButton = new AjaxButton("save") {
+
+ @Override
+ protected void onError(AjaxRequestTarget target, Form<?> form) {
+ super.onError(target, form);
+ target.add(feedback);
+ }
+
+ @Override
+ protected void onSubmit(AjaxRequestTarget target, Form<?> form) {
+ super.onSubmit(target, form);
+
+ Account user = SecurityUtils.getAccount();
+ CodeComment comment = getComment();
+ Date date = new Date();
+ CompareContext compareContext = getCompareContext(comment);
+ if (changeStatus) {
+ CodeCommentStatusChange statusChange = new CodeCommentStatusChange();
+ statusChange.setComment(getComment());
+ statusChange.setUser(user);
+ statusChange.setCompareContext(compareContext);
+ statusChange.setResolved(!comment.isResolved());
+ statusChange.setDate(date);
+ statusChange.setNote(contentInput.getModelObject());
+
+ GitPlex.getInstance(CodeCommentManager.class).changeStatus(statusChange);
+ onStatusChanged(target, fragment, statusChange);
+ onSaveComment(target, getComment());
+ } else {
+ CodeCommentReply reply = new CodeCommentReply();
+ reply.setComment(comment);
+ reply.setDate(date);
+ reply.setUser(user);
+ reply.setContent(contentInput.getModelObject());
+ reply.setCompareContext(compareContext);
+ GitPlex.getInstance(CodeCommentReplyManager.class).save(reply);
+ onReplyAdded(target, fragment, reply);
+ }
+ }
+
+ };
+ if (changeStatus) {
+ saveButton.add(new Label("label", getComment().isResolved()?"Confirm unresolve":"Confirm resolve"));
+ } else {
+ saveButton.add(new Label("label", "Save"));
+ saveButton.add(AttributeAppender.append("class", "dirty-aware"));
+ }
+ form.add(saveButton);
+
+ fragment.add(form);
+ fragment.setOutputMarkupId(true);
+ get("addReply").replaceWith(fragment);
+ target.add(fragment);
+ }
+
+ public void onChangeStatus(AjaxRequestTarget target) {
+ onAddReply(target, true);
+ }
+
+ private void onStatusChanged(AjaxRequestTarget target, Fragment fragment, CodeCommentStatusChange statusChange) {
+ WebMarkupContainer activityContainer = newActivityContainer(activitiesView.newChildId(), statusChange);
+ activitiesView.add(activityContainer);
+
+ String script = String.format("$('#%s .add-reply').before('<div id=\"%s\"></div>');",
+ CodeCommentPanel.this.getMarkupId(), activityContainer.getMarkupId());
+ target.prependJavaScript(script);
+ target.add(activityContainer);
+
+ WebMarkupContainer addReplyContainer = newAddReplyContainer();
+ fragment.replaceWith(addReplyContainer);
+ target.add(addReplyContainer);
+ }
+
+ private void onReplyAdded(AjaxRequestTarget target, Fragment fragment, @Nullable CodeCommentReply reply) {
+ if (reply != null) {
+ WebMarkupContainer activityContainer = newActivityContainer(activitiesView.newChildId(), reply);
+ activitiesView.add(activityContainer);
+
+ String script = String.format("$('#%s .add-reply').before('<div id=\"%s\"></div>');",
+ CodeCommentPanel.this.getMarkupId(), activityContainer.getMarkupId());
+ target.prependJavaScript(script);
+ target.add(activityContainer);
+ }
+
+ WebMarkupContainer addReplyContainer = newAddReplyContainer();
+ fragment.replaceWith(addReplyContainer);
+ target.add(addReplyContainer);
+ }
+
+ protected abstract void onDeleteComment(AjaxRequestTarget target, CodeComment comment);
+
+ protected abstract void onSaveComment(AjaxRequestTarget target, CodeComment comment);
+
+ protected abstract CompareContext getCompareContext(CodeComment comment);
+
+ @Nullable
+ protected abstract PullRequest getPullRequest();
+
+ private static class ActivityIdentity implements Serializable {
+
+ final Class<? extends CodeCommentActivity> clazz;
+
+ final Long id;
+
+ ActivityIdentity(CodeCommentActivity activity) {
+ this.clazz = activity.getClass();
+ this.id = activity.getId();
+ }
+
+ CodeCommentActivity getActivity() {
+ return GitPlex.getInstance(Dao.class).load(clazz, id);
+ }
+
+ }
+}
diff --git a/gitplex.web/src/main/java/com/pmease/gitplex/web/page/depot/compare/RevisionComparePage.java b/gitplex.web/src/main/java/com/pmease/gitplex/web/page/depot/compare/RevisionComparePage.java
index 9e4c68b070..493d6c0ab1 100644
--- a/gitplex.web/src/main/java/com/pmease/gitplex/web/page/depot/compare/RevisionComparePage.java
+++ b/gitplex.web/src/main/java/com/pmease/gitplex/web/page/depot/compare/RevisionComparePage.java
@@ -1,755 +1,754 @@
-package com.pmease.gitplex.web.page.depot.compare;
-
-import java.io.File;
-import java.io.IOException;
-import java.io.Serializable;
-import java.util.ArrayList;
-import java.util.Collection;
-import java.util.List;
-
-import javax.annotation.Nullable;
-
-import org.apache.wicket.Component;
-import org.apache.wicket.RestartResponseException;
-import org.apache.wicket.ajax.AjaxRequestTarget;
-import org.apache.wicket.ajax.form.OnChangeAjaxBehavior;
-import org.apache.wicket.behavior.AttributeAppender;
-import org.apache.wicket.markup.head.CssHeaderItem;
-import org.apache.wicket.markup.head.IHeaderResponse;
-import org.apache.wicket.markup.html.WebMarkupContainer;
-import org.apache.wicket.markup.html.basic.Label;
-import org.apache.wicket.markup.html.form.CheckBox;
-import org.apache.wicket.markup.html.link.BookmarkablePageLink;
-import org.apache.wicket.markup.html.link.Link;
-import org.apache.wicket.model.AbstractReadOnlyModel;
-import org.apache.wicket.model.IModel;
-import org.apache.wicket.model.LoadableDetachableModel;
-import org.apache.wicket.model.Model;
-import org.apache.wicket.request.cycle.RequestCycle;
-import org.apache.wicket.request.mapper.parameter.PageParameters;
-import org.apache.wicket.request.resource.CssResourceReference;
-import org.eclipse.jgit.lib.ObjectId;
-import org.eclipse.jgit.revwalk.RevCommit;
-import org.eclipse.jgit.revwalk.RevWalk;
-
-import com.pmease.commons.git.command.CalcMergeBaseCommand;
-import com.pmease.commons.git.command.CloneCommand;
-import com.pmease.commons.git.command.FetchCommand;
-import com.pmease.commons.lang.diff.WhitespaceOption;
-import com.pmease.commons.util.FileUtils;
-import com.pmease.commons.wicket.behavior.TooltipBehavior;
-import com.pmease.commons.wicket.component.backtotop.BackToTop;
-import com.pmease.commons.wicket.component.tabbable.AjaxActionTab;
-import com.pmease.commons.wicket.component.tabbable.Tab;
-import com.pmease.commons.wicket.component.tabbable.Tabbable;
-import com.pmease.commons.wicket.websocket.WebSocketManager;
-import com.pmease.commons.wicket.websocket.WebSocketRegion;
-import com.pmease.gitplex.core.GitPlex;
-import com.pmease.gitplex.core.entity.CodeComment;
-import com.pmease.gitplex.core.entity.Depot;
-import com.pmease.gitplex.core.entity.PullRequest;
-import com.pmease.gitplex.core.entity.support.CommentPos;
-import com.pmease.gitplex.core.entity.support.CompareContext;
-import com.pmease.gitplex.core.entity.support.DepotAndBranch;
-import com.pmease.gitplex.core.entity.support.DepotAndRevision;
-import com.pmease.gitplex.core.manager.CodeCommentManager;
-import com.pmease.gitplex.core.manager.PullRequestManager;
-import com.pmease.gitplex.web.component.commitlist.CommitListPanel;
-import com.pmease.gitplex.web.component.diff.revision.CommentSupport;
-import com.pmease.gitplex.web.component.diff.revision.RevisionDiffPanel;
-import com.pmease.gitplex.web.component.revisionpicker.AffinalRevisionPicker;
-import com.pmease.gitplex.web.page.depot.DepotPage;
-import com.pmease.gitplex.web.page.depot.NoBranchesPage;
-import com.pmease.gitplex.web.page.depot.commit.CommitDetailPage;
-import com.pmease.gitplex.web.page.depot.pullrequest.newrequest.NewRequestPage;
-import com.pmease.gitplex.web.page.depot.pullrequest.requestdetail.RequestDetailPage;
-import com.pmease.gitplex.web.page.depot.pullrequest.requestdetail.overview.RequestOverviewPage;
-import com.pmease.gitplex.web.websocket.CodeCommentChangedRegion;
-
-@SuppressWarnings("serial")
-public class RevisionComparePage extends DepotPage implements CommentSupport {
-
- public enum TabPanel {
- COMMITS,
- CHANGES;
-
- public static TabPanel of(@Nullable String name) {
- if (name != null) {
- return valueOf(name.toUpperCase());
- } else {
- return COMMITS;
- }
- }
-
- };
-
- private static final String PARAM_LEFT = "left";
-
- private static final String PARAM_RIGHT = "right";
-
- private static final String PARAM_COMPARE_WITH_MERGE_BASE = "compare-with-merge-base";
-
- private static final String PARAM_WHITESPACE_OPTION = "whitespace-option";
-
- private static final String PARAM_COMMENT = "comment";
-
- private static final String PARAM_MARK = "mark";
-
- private static final String PARAM_PATH_FILTER = "path-filter";
-
- private static final String PARAM_BLAME_FILE = "blame-file";
-
- private static final String PARAM_TAB = "tab-panel";
-
- private static final String TAB_PANEL_ID = "tabPanel";
-
- private IModel<List<RevCommit>> commitsModel;
-
- private IModel<PullRequest> requestModel;
-
- private IModel<ObjectId> mergeBaseModel;
-
- private State state = new State();
-
- private ObjectId leftCommitId;
-
- private ObjectId rightCommitId;
-
- private Tabbable tabbable;
-
- public static PageParameters paramsOf(Depot depot, CodeComment comment) {
- RevisionComparePage.State state = new RevisionComparePage.State();
- state.commentId = comment.getId();
- state.mark = comment.getCommentPos();
- state.compareWithMergeBase = false;
- CompareContext compareContext = comment.getLastCompareContext();
- if (compareContext.isLeftSide()) {
- state.leftSide = new DepotAndRevision(depot, compareContext.getCompareCommit());
- state.rightSide = new DepotAndRevision(depot, comment.getCommentPos().getCommit());
- } else {
- state.leftSide = new DepotAndRevision(depot, comment.getCommentPos().getCommit());
- state.rightSide = new DepotAndRevision(depot, compareContext.getCompareCommit());
- }
- state.tabPanel = RevisionComparePage.TabPanel.CHANGES;
- state.whitespaceOption = compareContext.getWhitespaceOption();
- state.pathFilter = compareContext.getPathFilter();
- return paramsOf(depot, state);
- }
-
- public static PageParameters paramsOf(Depot depot, State state) {
- PageParameters params = paramsOf(depot);
- params.set(PARAM_LEFT, state.leftSide.toString());
- params.set(PARAM_RIGHT, state.rightSide.toString());
- params.set(PARAM_COMPARE_WITH_MERGE_BASE, state.compareWithMergeBase);
- if (state.whitespaceOption != WhitespaceOption.DEFAULT)
- params.set(PARAM_WHITESPACE_OPTION, state.whitespaceOption.name());
- if (state.pathFilter != null)
- params.set(PARAM_PATH_FILTER, state.pathFilter);
- if (state.blameFile != null)
- params.set(PARAM_BLAME_FILE, state.blameFile);
- if (state.commentId != null)
- params.set(PARAM_COMMENT, state.commentId);
- if (state.mark != null)
- params.set(PARAM_MARK, state.mark.toString());
- if (state.tabPanel != null)
- params.set(PARAM_TAB, state.tabPanel.name());
- return params;
- }
-
- public RevisionComparePage(final PageParameters params) {
- super(params);
-
- if (getDepot().getDefaultBranch() == null)
- throw new RestartResponseException(NoBranchesPage.class, paramsOf(getDepot()));
-
- String str = params.get(PARAM_LEFT).toString();
- if (str != null) {
- state.leftSide = new DepotAndRevision(str);
- } else {
- state.leftSide = new DepotAndRevision(getDepot(), getDepot().getDefaultBranch());
- }
- leftCommitId = state.leftSide.getCommit().copy();
-
- str = params.get(PARAM_RIGHT).toString();
- if (str != null) {
- state.rightSide = new DepotAndRevision(str);
- } else {
- state.rightSide = new DepotAndRevision(getDepot(), getDepot().getDefaultBranch());
- }
- rightCommitId = state.rightSide.getCommit().copy();
-
- state.compareWithMergeBase = params.get(PARAM_COMPARE_WITH_MERGE_BASE).toBoolean(true);
-
- /*
- * When compare across different repositories, left revision and right revision might not
- * exist in same repository and this cause many difficulties such as calculating changes,
- * recording comment revisions, or get permanent mark urls. So we add below constraint as
- * merge base commit and right side revision are guaranteed to be both in right side
- * repository
- */
- if (!state.compareWithMergeBase && !state.leftSide.getDepot().equals(state.rightSide.getDepot())) {
- throw new IllegalArgumentException("Can only compare with merge base when compare across repositories");
- }
-
- state.pathFilter = params.get(PARAM_PATH_FILTER).toString();
- state.blameFile = params.get(PARAM_BLAME_FILE).toString();
- state.whitespaceOption = WhitespaceOption.of(params.get(PARAM_WHITESPACE_OPTION).toString());
-
- state.commentId = params.get(PARAM_COMMENT).toOptionalLong();
- state.mark = CommentPos.of(params.get(PARAM_MARK).toString());
-
- state.tabPanel = TabPanel.of(params.get(PARAM_TAB).toString());
-
- requestModel = new LoadableDetachableModel<PullRequest>() {
-
- @Override
- protected PullRequest load() {
- DepotAndBranch left = new DepotAndBranch(state.leftSide.toString());
- DepotAndBranch right = new DepotAndBranch(state.rightSide.toString());
- return GitPlex.getInstance(PullRequestManager.class).findOpen(left, right);
- }
-
- };
-
- mergeBaseModel = new LoadableDetachableModel<ObjectId>() {
-
- @Override
- protected ObjectId load() {
- Depot leftDepot = state.leftSide.getDepot();
- Depot rightDepot = state.rightSide.getDepot();
- if (!leftDepot.equals(rightDepot)) {
- File tempDir = FileUtils.createTempDir();
- try {
- new CloneCommand(tempDir).from(leftDepot.getDirectory().getAbsolutePath()).bare(true).shared(true).call();
- new FetchCommand(tempDir).from(rightDepot.getDirectory().getAbsolutePath()).refspec(state.rightSide.getRevision()).call();
- return ObjectId.fromString(new CalcMergeBaseCommand(tempDir).rev1(leftCommitId.name()).rev2(rightCommitId.name()).call());
- } finally {
- FileUtils.deleteDir(tempDir);
- }
- } else {
- return leftDepot.getMergeBase(state.leftSide.getRevision(), state.rightSide.getRevision());
- }
- }
-
- };
-
- commitsModel = new LoadableDetachableModel<List<RevCommit>>() {
-
- @Override
- protected List<RevCommit> load() {
- List<RevCommit> commits = new ArrayList<>();
- Depot rightDepot = state.rightSide.getDepot();
-
- try (RevWalk revWalk = new RevWalk(getDepot().getRepository())) {
- ObjectId mergeBase = mergeBaseModel.getObject();
- if (rightDepot.equals(state.leftSide.getDepot())
- && !state.compareWithMergeBase
- && !mergeBase.equals(leftCommitId)) {
- revWalk.markStart(revWalk.parseCommit(rightCommitId));
- revWalk.markStart(revWalk.parseCommit(leftCommitId));
- revWalk.markUninteresting(revWalk.parseCommit(mergeBase));
- revWalk.forEach(c->commits.add(c));
- /*
- * Add the merge base commit to make the revision graph understandable,
- * note that we can not get merge commit object by calling parseCommit
- * in current revWalk as it has been marked as uninteresting and this
- * will make the commit object incomplete
- */
- commits.add(getDepot().getRevCommit(mergeBase));
- } else {
- revWalk.markStart(revWalk.parseCommit(rightCommitId));
- revWalk.markUninteresting(revWalk.parseCommit(leftCommitId));
- revWalk.forEach(c->commits.add(c));
- }
- } catch (IOException e) {
- throw new RuntimeException(e);
- }
-
- return commits;
- }
-
- };
-
- }
-
- @Override
- protected void onInitialize() {
- super.onInitialize();
-
- setOutputMarkupId(true);
-
- add(new AffinalRevisionPicker("leftRevSelector", state.leftSide.getDepotId(), state.leftSide.getRevision()) {
-
- @Override
- protected void onSelect(AjaxRequestTarget target, Depot depot, String revision) {
- State newState = new State();
- newState.leftSide = new DepotAndRevision(depot, revision);
- newState.rightSide = state.rightSide;
- newState.pathFilter = state.pathFilter;
- newState.tabPanel = state.tabPanel;
- newState.whitespaceOption = state.whitespaceOption;
- newState.compareWithMergeBase = state.compareWithMergeBase;
- newState.mark = state.mark;
- newState.commentId = state.commentId;
- newState.tabPanel = state.tabPanel;
-
- PageParameters params = paramsOf(depot, newState);
- setResponsePage(RevisionComparePage.class, params);
- }
-
- });
-
- CheckBox checkBox = new CheckBox("compareWithMergeBase", Model.of(state.compareWithMergeBase)) {
-
- @Override
- protected void onConfigure() {
- super.onConfigure();
- setVisible(!mergeBaseModel.equals(leftCommitId));
- }
-
- };
- checkBox.add(new OnChangeAjaxBehavior() {
-
- @Override
- protected void onUpdate(AjaxRequestTarget target) {
- State newState = new State();
- newState.leftSide = state.leftSide;
- newState.rightSide = state.rightSide;
- newState.whitespaceOption = state.whitespaceOption;
- newState.compareWithMergeBase = !state.compareWithMergeBase;
- newState.commentId = state.commentId;
- newState.mark = state.mark;
- newState.tabPanel = state.tabPanel;
-
- PageParameters params = RevisionComparePage.paramsOf(depotModel.getObject(), newState);
- setResponsePage(RevisionComparePage.class, params);
- }
-
- });
- add(checkBox);
-
- String tooltip;
- if (!state.leftSide.getDepot().equals(state.rightSide.getDepot())) {
- checkBox.add(AttributeAppender.append("disabled", "disabled"));
- tooltip = "Can only compare with common ancestor when compare across different repositories";
- } else {
- tooltip = "Check this to compare \"right side\" with common ancestor of left and right";
- }
-
- add(new WebMarkupContainer("mergeBaseTooltip").add(new TooltipBehavior(Model.of(tooltip))));
-
- PageParameters params = CommitDetailPage.paramsOf(state.leftSide.getDepot(), state.leftSide.getCommit().name());
- Link<Void> leftCommitLink = new BookmarkablePageLink<Void>("leftCommitLink", CommitDetailPage.class, params);
- leftCommitLink.add(new Label("message", state.leftSide.getCommit().getShortMessage()));
- add(leftCommitLink);
-
- params = CommitDetailPage.paramsOf(state.rightSide.getDepot(), state.rightSide.getCommit().name());
- Link<Void> rightCommitLink = new BookmarkablePageLink<Void>("rightCommitLink", CommitDetailPage.class, params);
- rightCommitLink.add(new Label("message", state.rightSide.getCommit().getShortMessage()));
- add(rightCommitLink);
-
- add(new AffinalRevisionPicker("rightRevSelector",
- state.rightSide.getDepotId(), state.rightSide.getRevision()) {
-
- @Override
- protected void onSelect(AjaxRequestTarget target, Depot depot, String revision) {
- State newState = new State();
- newState.leftSide = state.leftSide;
- newState.rightSide = new DepotAndRevision(depot, revision);
- newState.pathFilter = state.pathFilter;
- newState.tabPanel = state.tabPanel;
- newState.whitespaceOption = state.whitespaceOption;
- newState.compareWithMergeBase = state.compareWithMergeBase;
- newState.commentId = state.commentId;
- newState.mark = state.mark;
- newState.tabPanel = state.tabPanel;
-
- PageParameters params = paramsOf(getDepot(), newState);
- setResponsePage(RevisionComparePage.class, params);
- }
-
- });
-
- add(new Link<Void>("swap") {
-
- @Override
- public void onClick() {
- State newState = new State();
- newState.leftSide = state.rightSide;
- newState.rightSide = state.leftSide;
- newState.pathFilter = state.pathFilter;
- newState.tabPanel = state.tabPanel;
- newState.whitespaceOption = state.whitespaceOption;
- newState.compareWithMergeBase = state.compareWithMergeBase;
- newState.mark = state.mark;
- newState.commentId = state.commentId;
-
- setResponsePage(RevisionComparePage.class,paramsOf(getDepot(), newState));
- }
-
- });
-
- add(new Link<Void>("createRequest") {
-
- @Override
- public void onClick() {
- DepotAndBranch left = new DepotAndBranch(state.leftSide.toString());
- DepotAndBranch right = new DepotAndBranch(state.rightSide.toString());
- setResponsePage(NewRequestPage.class, NewRequestPage.paramsOf(left.getDepot(), left, right));
- }
-
- @Override
- protected void onConfigure() {
- super.onConfigure();
-
- if (state.leftSide.getBranch()!=null && state.rightSide.getBranch()!=null) {
- PullRequest request = requestModel.getObject();
- setVisible(request == null && !mergeBaseModel.getObject().equals(rightCommitId));
- } else {
- setVisible(false);
- }
- }
-
- });
-
- add(new WebMarkupContainer("openedRequest") {
-
- @Override
- protected void onConfigure() {
- super.onConfigure();
-
- setVisible(requestModel.getObject() != null);
- }
-
- @Override
- protected void onInitialize() {
- super.onInitialize();
-
- add(new Label("no", new AbstractReadOnlyModel<String>() {
-
- @Override
- public String getObject() {
- return String.valueOf(requestModel.getObject().getNumber());
- }
-
- }));
- add(new Link<Void>("link") {
-
- @Override
- protected void onInitialize() {
- super.onInitialize();
- add(new Label("label", new AbstractReadOnlyModel<String>() {
-
- @Override
- public String getObject() {
- return requestModel.getObject().getTitle();
- }
- }));
- }
-
- @Override
- public void onClick() {
- PageParameters params = RequestDetailPage.paramsOf(requestModel.getObject());
- setResponsePage(RequestOverviewPage.class, params);
- }
-
- });
-
- }
-
- });
-
- List<Tab> tabs = new ArrayList<>();
-
- tabs.add(new AjaxActionTab(Model.of("Commits")) {
-
- @Override
- public boolean isSelected() {
- return state.tabPanel == null || state.tabPanel == TabPanel.COMMITS;
- }
-
- @Override
- protected void onSelect(AjaxRequestTarget target, Component tabLink) {
- state.tabPanel = TabPanel.COMMITS;
- newTabPanel(target);
- pushState(target);
- }
-
- });
-
- tabs.add(new AjaxActionTab(Model.of("Changes")) {
-
- @Override
- public boolean isSelected() {
- return state.tabPanel == TabPanel.CHANGES;
- }
-
- @Override
- protected void onSelect(AjaxRequestTarget target, Component tabLink) {
- state.tabPanel = TabPanel.CHANGES;
- newTabPanel(target);
- pushState(target);
- }
-
- });
-
- add(tabbable = new Tabbable("tabs", tabs));
-
- newTabPanel(null);
-
- add(new BackToTop("backToTop"));
- }
-
- @Override
- public void renderHead(IHeaderResponse response) {
- super.renderHead(response);
- response.render(CssHeaderItem.forReference(
- new CssResourceReference(RevisionComparePage.class, "revision-compare.css")));
- }
-
- private void newTabPanel(@Nullable AjaxRequestTarget target) {
- IModel<Depot> depotModel = new LoadableDetachableModel<Depot>() {
-
- @Override
- protected Depot load() {
- Depot depot = state.rightSide.getDepot();
- if (state.leftSide.getDepot().equals(state.rightSide.getDepot()))
- depot.cacheObjectId(state.leftSide.getRevision(), leftCommitId);
- depot.cacheObjectId(state.rightSide.getRevision(), rightCommitId);
- return depot;
- }
-
- };
- WebMarkupContainer tabPanel;
- switch (state.tabPanel) {
- case CHANGES:
- IModel<String> blameModel = new IModel<String>() {
-
- @Override
- public void detach() {
- }
-
- @Override
- public String getObject() {
- return state.blameFile;
- }
-
- @Override
- public void setObject(String object) {
- state.blameFile = object;
- pushState(RequestCycle.get().find(AjaxRequestTarget.class));
- }
-
- };
-
- IModel<String> pathFilterModel = new IModel<String>() {
-
- @Override
- public void detach() {
- }
-
- @Override
- public String getObject() {
- return state.pathFilter;
- }
-
- @Override
- public void setObject(String object) {
- state.pathFilter = object;
- pushState(RequestCycle.get().find(AjaxRequestTarget.class));
- }
-
- };
- IModel<WhitespaceOption> whitespaceOptionModel = new IModel<WhitespaceOption>() {
-
- @Override
- public void detach() {
- }
-
- @Override
- public WhitespaceOption getObject() {
- return state.whitespaceOption;
- }
-
- @Override
- public void setObject(WhitespaceOption object) {
- state.whitespaceOption = object;
- pushState(RequestCycle.get().find(AjaxRequestTarget.class));
- }
-
- };
-
- tabPanel = new RevisionDiffPanel(TAB_PANEL_ID, depotModel,
- new Model<PullRequest>(null),
- state.compareWithMergeBase?mergeBaseModel.getObject().name():state.leftSide.getRevision(),
- state.rightSide.getRevision(), pathFilterModel, whitespaceOptionModel, blameModel, this);
- break;
- default:
- tabPanel = new CommitListPanel(TAB_PANEL_ID, depotModel, commitsModel);
-
- if (!mergeBaseModel.equals(leftCommitId) && !state.compareWithMergeBase) {
- tabPanel.add(AttributeAppender.append("class", "with-merge-base"));
- }
- break;
- }
- tabPanel.setOutputMarkupId(true);
- if (target != null) {
- replace(tabPanel);
- target.add(tabPanel);
- } else {
- add(tabPanel);
- }
- }
-
- private void pushState(AjaxRequestTarget target) {
- PageParameters params = paramsOf(getDepot(), state);
- CharSequence url = RequestCycle.get().urlFor(RevisionComparePage.class, params);
- pushState(target, url.toString(), state);
- }
-
- @Override
- protected void onPopState(AjaxRequestTarget target, Serializable data) {
- super.onPopState(target, data);
-
- state = (State) data;
- GitPlex.getInstance(WebSocketManager.class).onRegionChange(this);
-
- newTabPanel(target);
- target.add(tabbable);
- }
-
- @Override
- protected void onDetach() {
- requestModel.detach();
- mergeBaseModel.detach();
- commitsModel.detach();
-
- super.onDetach();
- }
-
- @Override
- protected void onSelect(AjaxRequestTarget target, Depot depot) {
- setResponsePage(RevisionComparePage.class, paramsOf(depot));
- }
-
- public static class State implements Serializable {
-
- private static final long serialVersionUID = 1L;
-
- public DepotAndRevision leftSide;
-
- public DepotAndRevision rightSide;
-
- public boolean compareWithMergeBase = true;
-
- public WhitespaceOption whitespaceOption = WhitespaceOption.DEFAULT;
-
- @Nullable
- public TabPanel tabPanel;
-
- @Nullable
- public String pathFilter;
-
- @Nullable
- public String blameFile;
-
- @Nullable
- public Long commentId;
-
- @Nullable
- public CommentPos mark;
-
- public State() {
- }
-
- public State(State state) {
- leftSide = state.leftSide;
- rightSide = state.rightSide;
- compareWithMergeBase = state.compareWithMergeBase;
- whitespaceOption = state.whitespaceOption;
- pathFilter = state.pathFilter;
- blameFile = state.blameFile;
- commentId = state.commentId;
- mark = state.mark;
- tabPanel = state.tabPanel;
- }
-
- }
-
- @Override
- public CommentPos getMark() {
- return state.mark;
- }
-
- @Override
- public String getMarkUrl(CommentPos mark) {
- State markState = new State();
- markState.leftSide = new DepotAndRevision(state.rightSide.getDepot(),
- state.compareWithMergeBase?mergeBaseModel.getObject().name():leftCommitId.name());
- markState.rightSide = new DepotAndRevision(state.rightSide.getDepot(), rightCommitId.name());
- markState.mark = mark;
- markState.pathFilter = state.pathFilter;
- markState.tabPanel = TabPanel.CHANGES;
- markState.whitespaceOption = state.whitespaceOption;
- markState.compareWithMergeBase = false;
- return urlFor(RevisionComparePage.class, paramsOf(markState.rightSide.getDepot(), markState)).toString();
- }
-
- @Override
- public String getCommentUrl(CodeComment comment) {
- State commentState = new State();
- commentState.leftSide = new DepotAndRevision(state.rightSide.getDepot(),
- state.compareWithMergeBase?mergeBaseModel.getObject().name():leftCommitId.name());
- commentState.rightSide = new DepotAndRevision(state.rightSide.getDepot(), rightCommitId.name());
- commentState.mark = comment.getCommentPos();
- commentState.commentId = comment.getId();
- commentState.tabPanel = TabPanel.CHANGES;
- commentState.pathFilter = state.pathFilter;
- commentState.whitespaceOption = state.whitespaceOption;
- commentState.compareWithMergeBase = false;
- return urlFor(RevisionComparePage.class, paramsOf(commentState.rightSide.getDepot(), commentState)).toString();
- }
-
- @Override
- public CodeComment getOpenComment() {
- if (state.commentId != null)
- return GitPlex.getInstance(CodeCommentManager.class).load(state.commentId);
- else
- return null;
- }
-
- @Override
- public void onCommentOpened(AjaxRequestTarget target, CodeComment comment) {
- if (comment != null) {
- state.mark = comment.getCommentPos();
- state.commentId = comment.getId();
- } else {
- state.commentId = null;
- }
- pushState(target);
- GitPlex.getInstance(WebSocketManager.class).onRegionChange(this);
- }
-
- @Override
- public void onMark(AjaxRequestTarget target, CommentPos mark) {
- state.mark = mark;
- pushState(target);
- }
-
- @Override
- public void onAddComment(AjaxRequestTarget target, CommentPos mark) {
- state.commentId = null;
- state.mark = mark;
- pushState(target);
- GitPlex.getInstance(WebSocketManager.class).onRegionChange(this);
- }
-
- @Override
- public Collection<WebSocketRegion> getWebSocketRegions() {
- Collection<WebSocketRegion> regions = new ArrayList<>();
- if (state.commentId != null)
- regions.add(new CodeCommentChangedRegion(state.commentId));
- return regions;
- }
-
-}
+package com.pmease.gitplex.web.page.depot.compare;
+
+import java.io.File;
+import java.io.IOException;
+import java.io.Serializable;
+import java.util.ArrayList;
+import java.util.Collection;
+import java.util.List;
+
+import javax.annotation.Nullable;
+
+import org.apache.wicket.Component;
+import org.apache.wicket.RestartResponseException;
+import org.apache.wicket.ajax.AjaxRequestTarget;
+import org.apache.wicket.ajax.form.OnChangeAjaxBehavior;
+import org.apache.wicket.behavior.AttributeAppender;
+import org.apache.wicket.markup.head.CssHeaderItem;
+import org.apache.wicket.markup.head.IHeaderResponse;
+import org.apache.wicket.markup.html.WebMarkupContainer;
+import org.apache.wicket.markup.html.basic.Label;
+import org.apache.wicket.markup.html.form.CheckBox;
+import org.apache.wicket.markup.html.link.BookmarkablePageLink;
+import org.apache.wicket.markup.html.link.Link;
+import org.apache.wicket.model.AbstractReadOnlyModel;
+import org.apache.wicket.model.IModel;
+import org.apache.wicket.model.LoadableDetachableModel;
+import org.apache.wicket.model.Model;
+import org.apache.wicket.request.cycle.RequestCycle;
+import org.apache.wicket.request.mapper.parameter.PageParameters;
+import org.apache.wicket.request.resource.CssResourceReference;
+import org.eclipse.jgit.lib.ObjectId;
+import org.eclipse.jgit.revwalk.RevCommit;
+import org.eclipse.jgit.revwalk.RevWalk;
+
+import com.pmease.commons.git.command.CalcMergeBaseCommand;
+import com.pmease.commons.git.command.CloneCommand;
+import com.pmease.commons.git.command.FetchCommand;
+import com.pmease.commons.lang.diff.WhitespaceOption;
+import com.pmease.commons.util.FileUtils;
+import com.pmease.commons.wicket.behavior.TooltipBehavior;
+import com.pmease.commons.wicket.component.backtotop.BackToTop;
+import com.pmease.commons.wicket.component.tabbable.AjaxActionTab;
+import com.pmease.commons.wicket.component.tabbable.Tab;
+import com.pmease.commons.wicket.component.tabbable.Tabbable;
+import com.pmease.commons.wicket.websocket.WebSocketManager;
+import com.pmease.commons.wicket.websocket.WebSocketRegion;
+import com.pmease.gitplex.core.GitPlex;
+import com.pmease.gitplex.core.entity.CodeComment;
+import com.pmease.gitplex.core.entity.Depot;
+import com.pmease.gitplex.core.entity.PullRequest;
+import com.pmease.gitplex.core.entity.support.CommentPos;
+import com.pmease.gitplex.core.entity.support.CompareContext;
+import com.pmease.gitplex.core.entity.support.DepotAndBranch;
+import com.pmease.gitplex.core.entity.support.DepotAndRevision;
+import com.pmease.gitplex.core.manager.CodeCommentManager;
+import com.pmease.gitplex.core.manager.PullRequestManager;
+import com.pmease.gitplex.web.component.commitlist.CommitListPanel;
+import com.pmease.gitplex.web.component.diff.revision.CommentSupport;
+import com.pmease.gitplex.web.component.diff.revision.RevisionDiffPanel;
+import com.pmease.gitplex.web.component.revisionpicker.AffinalRevisionPicker;
+import com.pmease.gitplex.web.page.depot.DepotPage;
+import com.pmease.gitplex.web.page.depot.NoBranchesPage;
+import com.pmease.gitplex.web.page.depot.commit.CommitDetailPage;
+import com.pmease.gitplex.web.page.depot.pullrequest.newrequest.NewRequestPage;
+import com.pmease.gitplex.web.page.depot.pullrequest.requestdetail.RequestDetailPage;
+import com.pmease.gitplex.web.page.depot.pullrequest.requestdetail.overview.RequestOverviewPage;
+import com.pmease.gitplex.web.websocket.CodeCommentChangedRegion;
+
+@SuppressWarnings("serial")
+public class RevisionComparePage extends DepotPage implements CommentSupport {
+
+ public enum TabPanel {
+ COMMITS,
+ CHANGES;
+
+ public static TabPanel of(@Nullable String name) {
+ if (name != null) {
+ return valueOf(name.toUpperCase());
+ } else {
+ return COMMITS;
+ }
+ }
+
+ };
+
+ private static final String PARAM_LEFT = "left";
+
+ private static final String PARAM_RIGHT = "right";
+
+ private static final String PARAM_COMPARE_WITH_MERGE_BASE = "compare-with-merge-base";
+
+ private static final String PARAM_WHITESPACE_OPTION = "whitespace-option";
+
+ private static final String PARAM_COMMENT = "comment";
+
+ private static final String PARAM_MARK = "mark";
+
+ private static final String PARAM_PATH_FILTER = "path-filter";
+
+ private static final String PARAM_BLAME_FILE = "blame-file";
+
+ private static final String PARAM_TAB = "tab-panel";
+
+ private static final String TAB_PANEL_ID = "tabPanel";
+
+ private IModel<List<RevCommit>> commitsModel;
+
+ private IModel<PullRequest> requestModel;
+
+ private IModel<ObjectId> mergeBaseModel;
+
+ private State state = new State();
+
+ private ObjectId leftCommitId;
+
+ private ObjectId rightCommitId;
+
+ private Tabbable tabbable;
+
+ public static PageParameters paramsOf(Depot depot, CodeComment comment) {
+ RevisionComparePage.State state = new RevisionComparePage.State();
+ state.commentId = comment.getId();
+ state.mark = comment.getCommentPos();
+ state.compareWithMergeBase = false;
+ CompareContext compareContext = comment.getLastCompareContext();
+ if (compareContext.isLeftSide()) {
+ state.leftSide = new DepotAndRevision(depot, compareContext.getCompareCommit());
+ state.rightSide = new DepotAndRevision(depot, comment.getCommentPos().getCommit());
+ } else {
+ state.leftSide = new DepotAndRevision(depot, comment.getCommentPos().getCommit());
+ state.rightSide = new DepotAndRevision(depot, compareContext.getCompareCommit());
+ }
+ state.tabPanel = RevisionComparePage.TabPanel.CHANGES;
+ state.whitespaceOption = compareContext.getWhitespaceOption();
+ state.pathFilter = compareContext.getPathFilter();
+ return paramsOf(depot, state);
+ }
+
+ public static PageParameters paramsOf(Depot depot, State state) {
+ PageParameters params = paramsOf(depot);
+ params.set(PARAM_LEFT, state.leftSide.toString());
+ params.set(PARAM_RIGHT, state.rightSide.toString());
+ params.set(PARAM_COMPARE_WITH_MERGE_BASE, state.compareWithMergeBase);
+ if (state.whitespaceOption != WhitespaceOption.DEFAULT)
+ params.set(PARAM_WHITESPACE_OPTION, state.whitespaceOption.name());
+ if (state.pathFilter != null)
+ params.set(PARAM_PATH_FILTER, state.pathFilter);
+ if (state.blameFile != null)
+ params.set(PARAM_BLAME_FILE, state.blameFile);
+ if (state.commentId != null)
+ params.set(PARAM_COMMENT, state.commentId);
+ if (state.mark != null)
+ params.set(PARAM_MARK, state.mark.toString());
+ if (state.tabPanel != null)
+ params.set(PARAM_TAB, state.tabPanel.name());
+ return params;
+ }
+
+ public RevisionComparePage(final PageParameters params) {
+ super(params);
+
+ if (getDepot().getDefaultBranch() == null)
+ throw new RestartResponseException(NoBranchesPage.class, paramsOf(getDepot()));
+
+ String str = params.get(PARAM_LEFT).toString();
+ if (str != null) {
+ state.leftSide = new DepotAndRevision(str);
+ } else {
+ state.leftSide = new DepotAndRevision(getDepot(), getDepot().getDefaultBranch());
+ }
+ leftCommitId = state.leftSide.getCommit().copy();
+
+ str = params.get(PARAM_RIGHT).toString();
+ if (str != null) {
+ state.rightSide = new DepotAndRevision(str);
+ } else {
+ state.rightSide = new DepotAndRevision(getDepot(), getDepot().getDefaultBranch());
+ }
+ rightCommitId = state.rightSide.getCommit().copy();
+
+ state.compareWithMergeBase = params.get(PARAM_COMPARE_WITH_MERGE_BASE).toBoolean(true);
+
+ /*
+ * When compare across different repositories, left revision and right revision might not
+ * exist in same repository and this cause many difficulties such as calculating changes,
+ * recording comment revisions, or get permanent mark urls. So we add below constraint as
+ * merge base commit and right side revision are guaranteed to be both in right side
+ * repository
+ */
+ if (!state.compareWithMergeBase && !state.leftSide.getDepot().equals(state.rightSide.getDepot())) {
+ throw new IllegalArgumentException("Can only compare with merge base when compare across repositories");
+ }
+
+ state.pathFilter = params.get(PARAM_PATH_FILTER).toString();
+ state.blameFile = params.get(PARAM_BLAME_FILE).toString();
+ state.whitespaceOption = WhitespaceOption.of(params.get(PARAM_WHITESPACE_OPTION).toString());
+
+ state.commentId = params.get(PARAM_COMMENT).toOptionalLong();
+ state.mark = CommentPos.of(params.get(PARAM_MARK).toString());
+
+ state.tabPanel = TabPanel.of(params.get(PARAM_TAB).toString());
+
+ requestModel = new LoadableDetachableModel<PullRequest>() {
+
+ @Override
+ protected PullRequest load() {
+ DepotAndBranch left = new DepotAndBranch(state.leftSide.toString());
+ DepotAndBranch right = new DepotAndBranch(state.rightSide.toString());
+ return GitPlex.getInstance(PullRequestManager.class).findOpen(left, right);
+ }
+
+ };
+
+ mergeBaseModel = new LoadableDetachableModel<ObjectId>() {
+
+ @Override
+ protected ObjectId load() {
+ Depot leftDepot = state.leftSide.getDepot();
+ Depot rightDepot = state.rightSide.getDepot();
+ if (!leftDepot.equals(rightDepot)) {
+ File tempDir = FileUtils.createTempDir();
+ try {
+ new CloneCommand(tempDir).from(leftDepot.getDirectory().getAbsolutePath()).bare(true).shared(true).call();
+ new FetchCommand(tempDir).from(rightDepot.getDirectory().getAbsolutePath()).refspec(state.rightSide.getRevision()).call();
+ return ObjectId.fromString(new CalcMergeBaseCommand(tempDir).rev1(leftCommitId.name()).rev2(rightCommitId.name()).call());
+ } finally {
+ FileUtils.deleteDir(tempDir);
+ }
+ } else {
+ return leftDepot.getMergeBase(state.leftSide.getRevision(), state.rightSide.getRevision());
+ }
+ }
+
+ };
+
+ commitsModel = new LoadableDetachableModel<List<RevCommit>>() {
+
+ @Override
+ protected List<RevCommit> load() {
+ List<RevCommit> commits = new ArrayList<>();
+ Depot rightDepot = state.rightSide.getDepot();
+
+ try (RevWalk revWalk = new RevWalk(getDepot().getRepository())) {
+ ObjectId mergeBase = mergeBaseModel.getObject();
+ if (rightDepot.equals(state.leftSide.getDepot())
+ && !state.compareWithMergeBase
+ && !mergeBase.equals(leftCommitId)) {
+ revWalk.markStart(revWalk.parseCommit(rightCommitId));
+ revWalk.markStart(revWalk.parseCommit(leftCommitId));
+ revWalk.markUninteresting(revWalk.parseCommit(mergeBase));
+ revWalk.forEach(c->commits.add(c));
+ /*
+ * Add the merge base commit to make the revision graph understandable,
+ * note that we can not get merge commit object in current revWalk as
+ * it has been marked and this will make the commit object incomplete
+ */
+ commits.add(getDepot().getRevCommit(mergeBase));
+ } else {
+ revWalk.markStart(revWalk.parseCommit(rightCommitId));
+ revWalk.markUninteresting(revWalk.parseCommit(leftCommitId));
+ revWalk.forEach(c->commits.add(c));
+ }
+ } catch (IOException e) {
+ throw new RuntimeException(e);
+ }
+
+ return commits;
+ }
+
+ };
+
+ }
+
+ @Override
+ protected void onInitialize() {
+ super.onInitialize();
+
+ setOutputMarkupId(true);
+
+ add(new AffinalRevisionPicker("leftRevSelector", state.leftSide.getDepotId(), state.leftSide.getRevision()) {
+
+ @Override
+ protected void onSelect(AjaxRequestTarget target, Depot depot, String revision) {
+ State newState = new State();
+ newState.leftSide = new DepotAndRevision(depot, revision);
+ newState.rightSide = state.rightSide;
+ newState.pathFilter = state.pathFilter;
+ newState.tabPanel = state.tabPanel;
+ newState.whitespaceOption = state.whitespaceOption;
+ newState.compareWithMergeBase = state.compareWithMergeBase;
+ newState.mark = state.mark;
+ newState.commentId = state.commentId;
+ newState.tabPanel = state.tabPanel;
+
+ PageParameters params = paramsOf(depot, newState);
+ setResponsePage(RevisionComparePage.class, params);
+ }
+
+ });
+
+ CheckBox checkBox = new CheckBox("compareWithMergeBase", Model.of(state.compareWithMergeBase)) {
+
+ @Override
+ protected void onConfigure() {
+ super.onConfigure();
+ setVisible(!mergeBaseModel.equals(leftCommitId));
+ }
+
+ };
+ checkBox.add(new OnChangeAjaxBehavior() {
+
+ @Override
+ protected void onUpdate(AjaxRequestTarget target) {
+ State newState = new State();
+ newState.leftSide = state.leftSide;
+ newState.rightSide = state.rightSide;
+ newState.whitespaceOption = state.whitespaceOption;
+ newState.compareWithMergeBase = !state.compareWithMergeBase;
+ newState.commentId = state.commentId;
+ newState.mark = state.mark;
+ newState.tabPanel = state.tabPanel;
+
+ PageParameters params = RevisionComparePage.paramsOf(depotModel.getObject(), newState);
+ setResponsePage(RevisionComparePage.class, params);
+ }
+
+ });
+ add(checkBox);
+
+ String tooltip;
+ if (!state.leftSide.getDepot().equals(state.rightSide.getDepot())) {
+ checkBox.add(AttributeAppender.append("disabled", "disabled"));
+ tooltip = "Can only compare with common ancestor when compare across different repositories";
+ } else {
+ tooltip = "Check this to compare \"right side\" with common ancestor of left and right";
+ }
+
+ add(new WebMarkupContainer("mergeBaseTooltip").add(new TooltipBehavior(Model.of(tooltip))));
+
+ PageParameters params = CommitDetailPage.paramsOf(state.leftSide.getDepot(), state.leftSide.getCommit().name());
+ Link<Void> leftCommitLink = new BookmarkablePageLink<Void>("leftCommitLink", CommitDetailPage.class, params);
+ leftCommitLink.add(new Label("message", state.leftSide.getCommit().getShortMessage()));
+ add(leftCommitLink);
+
+ params = CommitDetailPage.paramsOf(state.rightSide.getDepot(), state.rightSide.getCommit().name());
+ Link<Void> rightCommitLink = new BookmarkablePageLink<Void>("rightCommitLink", CommitDetailPage.class, params);
+ rightCommitLink.add(new Label("message", state.rightSide.getCommit().getShortMessage()));
+ add(rightCommitLink);
+
+ add(new AffinalRevisionPicker("rightRevSelector",
+ state.rightSide.getDepotId(), state.rightSide.getRevision()) {
+
+ @Override
+ protected void onSelect(AjaxRequestTarget target, Depot depot, String revision) {
+ State newState = new State();
+ newState.leftSide = state.leftSide;
+ newState.rightSide = new DepotAndRevision(depot, revision);
+ newState.pathFilter = state.pathFilter;
+ newState.tabPanel = state.tabPanel;
+ newState.whitespaceOption = state.whitespaceOption;
+ newState.compareWithMergeBase = state.compareWithMergeBase;
+ newState.commentId = state.commentId;
+ newState.mark = state.mark;
+ newState.tabPanel = state.tabPanel;
+
+ PageParameters params = paramsOf(getDepot(), newState);
+ setResponsePage(RevisionComparePage.class, params);
+ }
+
+ });
+
+ add(new Link<Void>("swap") {
+
+ @Override
+ public void onClick() {
+ State newState = new State();
+ newState.leftSide = state.rightSide;
+ newState.rightSide = state.leftSide;
+ newState.pathFilter = state.pathFilter;
+ newState.tabPanel = state.tabPanel;
+ newState.whitespaceOption = state.whitespaceOption;
+ newState.compareWithMergeBase = state.compareWithMergeBase;
+ newState.mark = state.mark;
+ newState.commentId = state.commentId;
+
+ setResponsePage(RevisionComparePage.class,paramsOf(getDepot(), newState));
+ }
+
+ });
+
+ add(new Link<Void>("createRequest") {
+
+ @Override
+ public void onClick() {
+ DepotAndBranch left = new DepotAndBranch(state.leftSide.toString());
+ DepotAndBranch right = new DepotAndBranch(state.rightSide.toString());
+ setResponsePage(NewRequestPage.class, NewRequestPage.paramsOf(left.getDepot(), left, right));
+ }
+
+ @Override
+ protected void onConfigure() {
+ super.onConfigure();
+
+ if (state.leftSide.getBranch()!=null && state.rightSide.getBranch()!=null) {
+ PullRequest request = requestModel.getObject();
+ setVisible(request == null && !mergeBaseModel.getObject().equals(rightCommitId));
+ } else {
+ setVisible(false);
+ }
+ }
+
+ });
+
+ add(new WebMarkupContainer("openedRequest") {
+
+ @Override
+ protected void onConfigure() {
+ super.onConfigure();
+
+ setVisible(requestModel.getObject() != null);
+ }
+
+ @Override
+ protected void onInitialize() {
+ super.onInitialize();
+
+ add(new Label("no", new AbstractReadOnlyModel<String>() {
+
+ @Override
+ public String getObject() {
+ return String.valueOf(requestModel.getObject().getNumber());
+ }
+
+ }));
+ add(new Link<Void>("link") {
+
+ @Override
+ protected void onInitialize() {
+ super.onInitialize();
+ add(new Label("label", new AbstractReadOnlyModel<String>() {
+
+ @Override
+ public String getObject() {
+ return requestModel.getObject().getTitle();
+ }
+ }));
+ }
+
+ @Override
+ public void onClick() {
+ PageParameters params = RequestDetailPage.paramsOf(requestModel.getObject());
+ setResponsePage(RequestOverviewPage.class, params);
+ }
+
+ });
+
+ }
+
+ });
+
+ List<Tab> tabs = new ArrayList<>();
+
+ tabs.add(new AjaxActionTab(Model.of("Commits")) {
+
+ @Override
+ public boolean isSelected() {
+ return state.tabPanel == null || state.tabPanel == TabPanel.COMMITS;
+ }
+
+ @Override
+ protected void onSelect(AjaxRequestTarget target, Component tabLink) {
+ state.tabPanel = TabPanel.COMMITS;
+ newTabPanel(target);
+ pushState(target);
+ }
+
+ });
+
+ tabs.add(new AjaxActionTab(Model.of("Changes")) {
+
+ @Override
+ public boolean isSelected() {
+ return state.tabPanel == TabPanel.CHANGES;
+ }
+
+ @Override
+ protected void onSelect(AjaxRequestTarget target, Component tabLink) {
+ state.tabPanel = TabPanel.CHANGES;
+ newTabPanel(target);
+ pushState(target);
+ }
+
+ });
+
+ add(tabbable = new Tabbable("tabs", tabs));
+
+ newTabPanel(null);
+
+ add(new BackToTop("backToTop"));
+ }
+
+ @Override
+ public void renderHead(IHeaderResponse response) {
+ super.renderHead(response);
+ response.render(CssHeaderItem.forReference(
+ new CssResourceReference(RevisionComparePage.class, "revision-compare.css")));
+ }
+
+ private void newTabPanel(@Nullable AjaxRequestTarget target) {
+ IModel<Depot> depotModel = new LoadableDetachableModel<Depot>() {
+
+ @Override
+ protected Depot load() {
+ Depot depot = state.rightSide.getDepot();
+ if (state.leftSide.getDepot().equals(state.rightSide.getDepot()))
+ depot.cacheObjectId(state.leftSide.getRevision(), leftCommitId);
+ depot.cacheObjectId(state.rightSide.getRevision(), rightCommitId);
+ return depot;
+ }
+
+ };
+ WebMarkupContainer tabPanel;
+ switch (state.tabPanel) {
+ case CHANGES:
+ IModel<String> blameModel = new IModel<String>() {
+
+ @Override
+ public void detach() {
+ }
+
+ @Override
+ public String getObject() {
+ return state.blameFile;
+ }
+
+ @Override
+ public void setObject(String object) {
+ state.blameFile = object;
+ pushState(RequestCycle.get().find(AjaxRequestTarget.class));
+ }
+
+ };
+
+ IModel<String> pathFilterModel = new IModel<String>() {
+
+ @Override
+ public void detach() {
+ }
+
+ @Override
+ public String getObject() {
+ return state.pathFilter;
+ }
+
+ @Override
+ public void setObject(String object) {
+ state.pathFilter = object;
+ pushState(RequestCycle.get().find(AjaxRequestTarget.class));
+ }
+
+ };
+ IModel<WhitespaceOption> whitespaceOptionModel = new IModel<WhitespaceOption>() {
+
+ @Override
+ public void detach() {
+ }
+
+ @Override
+ public WhitespaceOption getObject() {
+ return state.whitespaceOption;
+ }
+
+ @Override
+ public void setObject(WhitespaceOption object) {
+ state.whitespaceOption = object;
+ pushState(RequestCycle.get().find(AjaxRequestTarget.class));
+ }
+
+ };
+
+ tabPanel = new RevisionDiffPanel(TAB_PANEL_ID, depotModel,
+ new Model<PullRequest>(null),
+ state.compareWithMergeBase?mergeBaseModel.getObject().name():state.leftSide.getRevision(),
+ state.rightSide.getRevision(), pathFilterModel, whitespaceOptionModel, blameModel, this);
+ break;
+ default:
+ tabPanel = new CommitListPanel(TAB_PANEL_ID, depotModel, commitsModel);
+
+ if (!mergeBaseModel.equals(leftCommitId) && !state.compareWithMergeBase) {
+ tabPanel.add(AttributeAppender.append("class", "with-merge-base"));
+ }
+ break;
+ }
+ tabPanel.setOutputMarkupId(true);
+ if (target != null) {
+ replace(tabPanel);
+ target.add(tabPanel);
+ } else {
+ add(tabPanel);
+ }
+ }
+
+ private void pushState(AjaxRequestTarget target) {
+ PageParameters params = paramsOf(getDepot(), state);
+ CharSequence url = RequestCycle.get().urlFor(RevisionComparePage.class, params);
+ pushState(target, url.toString(), state);
+ }
+
+ @Override
+ protected void onPopState(AjaxRequestTarget target, Serializable data) {
+ super.onPopState(target, data);
+
+ state = (State) data;
+ GitPlex.getInstance(WebSocketManager.class).onRegionChange(this);
+
+ newTabPanel(target);
+ target.add(tabbable);
+ }
+
+ @Override
+ protected void onDetach() {
+ requestModel.detach();
+ mergeBaseModel.detach();
+ commitsModel.detach();
+
+ super.onDetach();
+ }
+
+ @Override
+ protected void onSelect(AjaxRequestTarget target, Depot depot) {
+ setResponsePage(RevisionComparePage.class, paramsOf(depot));
+ }
+
+ public static class State implements Serializable {
+
+ private static final long serialVersionUID = 1L;
+
+ public DepotAndRevision leftSide;
+
+ public DepotAndRevision rightSide;
+
+ public boolean compareWithMergeBase = true;
+
+ public WhitespaceOption whitespaceOption = WhitespaceOption.DEFAULT;
+
+ @Nullable
+ public TabPanel tabPanel;
+
+ @Nullable
+ public String pathFilter;
+
+ @Nullable
+ public String blameFile;
+
+ @Nullable
+ public Long commentId;
+
+ @Nullable
+ public CommentPos mark;
+
+ public State() {
+ }
+
+ public State(State state) {
+ leftSide = state.leftSide;
+ rightSide = state.rightSide;
+ compareWithMergeBase = state.compareWithMergeBase;
+ whitespaceOption = state.whitespaceOption;
+ pathFilter = state.pathFilter;
+ blameFile = state.blameFile;
+ commentId = state.commentId;
+ mark = state.mark;
+ tabPanel = state.tabPanel;
+ }
+
+ }
+
+ @Override
+ public CommentPos getMark() {
+ return state.mark;
+ }
+
+ @Override
+ public String getMarkUrl(CommentPos mark) {
+ State markState = new State();
+ markState.leftSide = new DepotAndRevision(state.rightSide.getDepot(),
+ state.compareWithMergeBase?mergeBaseModel.getObject().name():leftCommitId.name());
+ markState.rightSide = new DepotAndRevision(state.rightSide.getDepot(), rightCommitId.name());
+ markState.mark = mark;
+ markState.pathFilter = state.pathFilter;
+ markState.tabPanel = TabPanel.CHANGES;
+ markState.whitespaceOption = state.whitespaceOption;
+ markState.compareWithMergeBase = false;
+ return urlFor(RevisionComparePage.class, paramsOf(markState.rightSide.getDepot(), markState)).toString();
+ }
+
+ @Override
+ public String getCommentUrl(CodeComment comment) {
+ State commentState = new State();
+ commentState.leftSide = new DepotAndRevision(state.rightSide.getDepot(),
+ state.compareWithMergeBase?mergeBaseModel.getObject().name():leftCommitId.name());
+ commentState.rightSide = new DepotAndRevision(state.rightSide.getDepot(), rightCommitId.name());
+ commentState.mark = comment.getCommentPos();
+ commentState.commentId = comment.getId();
+ commentState.tabPanel = TabPanel.CHANGES;
+ commentState.pathFilter = state.pathFilter;
+ commentState.whitespaceOption = state.whitespaceOption;
+ commentState.compareWithMergeBase = false;
+ return urlFor(RevisionComparePage.class, paramsOf(commentState.rightSide.getDepot(), commentState)).toString();
+ }
+
+ @Override
+ public CodeComment getOpenComment() {
+ if (state.commentId != null)
+ return GitPlex.getInstance(CodeCommentManager.class).load(state.commentId);
+ else
+ return null;
+ }
+
+ @Override
+ public void onCommentOpened(AjaxRequestTarget target, CodeComment comment) {
+ if (comment != null) {
+ state.mark = comment.getCommentPos();
+ state.commentId = comment.getId();
+ } else {
+ state.commentId = null;
+ }
+ pushState(target);
+ GitPlex.getInstance(WebSocketManager.class).onRegionChange(this);
+ }
+
+ @Override
+ public void onMark(AjaxRequestTarget target, CommentPos mark) {
+ state.mark = mark;
+ pushState(target);
+ }
+
+ @Override
+ public void onAddComment(AjaxRequestTarget target, CommentPos mark) {
+ state.commentId = null;
+ state.mark = mark;
+ pushState(target);
+ GitPlex.getInstance(WebSocketManager.class).onRegionChange(this);
+ }
+
+ @Override
+ public Collection<WebSocketRegion> getWebSocketRegions() {
+ Collection<WebSocketRegion> regions = new ArrayList<>();
+ if (state.commentId != null)
+ regions.add(new CodeCommentChangedRegion(state.commentId));
+ return regions;
+ }
+
+}
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 6f6c0cf7fd..cc91ff319a 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
@@ -1,985 +1,989 @@
-package com.pmease.gitplex.web.page.depot.file;
-
-import java.io.IOException;
-import java.io.Serializable;
-import java.util.ArrayList;
-import java.util.Collection;
-import java.util.HashMap;
-import java.util.List;
-import java.util.Map;
-import java.util.concurrent.atomic.AtomicReference;
-
-import javax.annotation.Nullable;
-
-import org.apache.commons.lang3.StringUtils;
-import org.apache.shiro.subject.Subject;
-import org.apache.shiro.util.ThreadContext;
-import org.apache.wicket.Component;
-import org.apache.wicket.MetaDataKey;
-import org.apache.wicket.RestartResponseException;
-import org.apache.wicket.ajax.AbstractDefaultAjaxBehavior;
-import org.apache.wicket.ajax.AjaxRequestTarget;
-import org.apache.wicket.behavior.AttributeAppender;
-import org.apache.wicket.core.request.handler.IPartialPageRequestHandler;
-import org.apache.wicket.extensions.ajax.markup.html.AjaxLazyLoadPanel;
-import org.apache.wicket.markup.head.CssHeaderItem;
-import org.apache.wicket.markup.head.IHeaderResponse;
-import org.apache.wicket.markup.head.JavaScriptHeaderItem;
-import org.apache.wicket.markup.html.WebMarkupContainer;
-import org.apache.wicket.markup.html.basic.Label;
-import org.apache.wicket.markup.html.image.Image;
-import org.apache.wicket.model.AbstractReadOnlyModel;
-import org.apache.wicket.protocol.ws.api.WebSocketRequestHandler;
-import org.apache.wicket.request.IRequestHandler;
-import org.apache.wicket.request.cycle.RequestCycle;
-import org.apache.wicket.request.handler.resource.ResourceReferenceRequestHandler;
-import org.apache.wicket.request.mapper.parameter.PageParameters;
-import org.apache.wicket.request.resource.CssResourceReference;
-import org.apache.wicket.request.resource.JavaScriptResourceReference;
-import org.apache.wicket.request.resource.PackageResourceReference;
-import org.eclipse.jgit.lib.Constants;
-import org.eclipse.jgit.lib.FileMode;
-import org.eclipse.jgit.lib.ObjectId;
-import org.eclipse.jgit.revwalk.RevCommit;
-import org.eclipse.jgit.revwalk.RevTree;
-import org.eclipse.jgit.revwalk.RevWalk;
-import org.eclipse.jgit.treewalk.TreeWalk;
-
-import com.google.common.base.Objects;
-import com.pmease.commons.git.BlobIdent;
-import com.pmease.commons.git.GitUtils;
-import com.pmease.commons.git.exception.ObjectNotExistException;
-import com.pmease.commons.hibernate.UnitOfWork;
-import com.pmease.commons.lang.extractors.TokenPosition;
-import com.pmease.commons.loader.ListenerRegistry;
-import com.pmease.commons.wicket.assets.cookies.CookiesResourceReference;
-import com.pmease.commons.wicket.assets.jqueryui.JQueryUIResourceReference;
-import com.pmease.commons.wicket.component.menu.MenuItem;
-import com.pmease.commons.wicket.component.menu.MenuLink;
-import com.pmease.commons.wicket.component.modal.ModalLink;
-import com.pmease.commons.wicket.websocket.WebSocketManager;
-import com.pmease.commons.wicket.websocket.WebSocketRegion;
-import com.pmease.commons.wicket.websocket.WebSocketRenderBehavior;
-import com.pmease.gitplex.core.GitPlex;
-import com.pmease.gitplex.core.entity.CodeComment;
-import com.pmease.gitplex.core.entity.Depot;
-import com.pmease.gitplex.core.entity.support.TextRange;
-import com.pmease.gitplex.core.event.RefUpdated;
-import com.pmease.gitplex.core.manager.CodeCommentManager;
-import com.pmease.gitplex.core.manager.DepotManager;
-import com.pmease.gitplex.core.security.SecurityUtils;
-import com.pmease.gitplex.search.IndexManager;
-import com.pmease.gitplex.search.SearchManager;
-import com.pmease.gitplex.search.hit.QueryHit;
-import com.pmease.gitplex.search.query.BlobQuery;
-import com.pmease.gitplex.search.query.TextQuery;
-import com.pmease.gitplex.web.WebSession;
-import com.pmease.gitplex.web.component.archivemenulink.ArchiveMenuLink;
-import com.pmease.gitplex.web.component.depotfile.blobsearch.advanced.AdvancedSearchPanel;
-import com.pmease.gitplex.web.component.depotfile.blobsearch.instant.InstantSearchPanel;
-import com.pmease.gitplex.web.component.depotfile.blobsearch.result.SearchResultPanel;
-import com.pmease.gitplex.web.component.depotfile.blobview.BlobNameChangeCallback;
-import com.pmease.gitplex.web.component.depotfile.blobview.BlobRenderer;
-import com.pmease.gitplex.web.component.depotfile.blobview.BlobViewContext;
-import com.pmease.gitplex.web.component.depotfile.blobview.BlobViewPanel;
-import com.pmease.gitplex.web.component.depotfile.blobview.source.SourceViewPanel;
-import com.pmease.gitplex.web.component.depotfile.editsave.CancelListener;
-import com.pmease.gitplex.web.component.depotfile.editsave.EditSavePanel;
-import com.pmease.gitplex.web.component.depotfile.fileedit.FileEditPanel;
-import com.pmease.gitplex.web.component.depotfile.filelist.FileListPanel;
-import com.pmease.gitplex.web.component.depotfile.filenavigator.FileNavigator;
-import com.pmease.gitplex.web.component.revisionpicker.RevisionPicker;
-import com.pmease.gitplex.web.page.depot.DepotPage;
-import com.pmease.gitplex.web.page.depot.NoBranchesPage;
-import com.pmease.gitplex.web.websocket.CodeCommentChangedRegion;
-import com.pmease.gitplex.web.websocket.CommitIndexedRegion;
-
-@SuppressWarnings("serial")
-public class DepotFilePage extends DepotPage implements BlobViewContext {
-
- private static class SearchResultKey extends MetaDataKey<ArrayList<QueryHit>> {
- };
-
- public static final SearchResultKey SEARCH_RESULT_KEY = new SearchResultKey();
-
- private static class ViewStateKey extends MetaDataKey<String> {
- };
-
- public static final ViewStateKey VIEW_STATE_KEY = new ViewStateKey();
-
- private static final String PARAM_REVISION = "revision";
-
- private static final String PARAM_PATH = "path";
-
- private static final String PARAM_COMMENT = "comment";
-
- private static final String PARAM_MODE = "mode";
-
- private static final String PARAM_QUERY = "query";
-
- private static final String PARAM_VIEW_STATE = "view_state";
-
- private static final String PARAM_MARK = "mark";
-
- private static final String REVISION_PICKER_ID = "revisionPicker";
-
- private static final String FILE_NAVIGATOR_ID = "fileNavigator";
-
- private static final String CONTRIBUTION_ID = "contribution";
-
- private static final String FILE_VIEWER_ID = "fileViewer";
-
- private static final String SEARCH_RESULD_ID = "searchResult";
-
- private BlobIdent blobIdent = new BlobIdent();
-
- private ObjectId resolvedRevision;
-
- private TextRange mark;
-
- private Mode mode;
-
- private Long commentId;
-
- private Component revisionIndexing;
-
- private WebMarkupContainer searchResultContainer;
-
- private AtomicReference<String> newPathRef;
-
- private ObjectId commitId;
-
- private transient List<QueryHit> queryHits;
-
- public DepotFilePage(final PageParameters params) {
- super(params);
-
- if (getDepot().getDefaultBranch() == null)
- throw new RestartResponseException(NoBranchesPage.class, paramsOf(getDepot()));
-
- blobIdent.revision = params.get(PARAM_REVISION).toString();
- blobIdent.path = GitUtils.normalizePath(params.get(PARAM_PATH).toString());
-
- blobIdent.revision = GitUtils.normalizePath(params.get(PARAM_REVISION).toString());
- if (blobIdent.revision == null)
- blobIdent.revision = getDepot().getDefaultBranch();
-
- resolvedRevision = getDepot().getObjectId(blobIdent.revision);
-
- RevCommit commit = getDepot().getRevCommit(blobIdent.revision);
- commitId = commit.copy();
-
- if (blobIdent.path != null) {
- try (RevWalk revWalk = new RevWalk(getDepot().getRepository())) {
- RevTree revTree = commit.getTree();
- TreeWalk treeWalk = TreeWalk.forPath(getDepot().getRepository(), blobIdent.path, revTree);
- if (treeWalk == null) {
- throw new ObjectNotExistException("Unable to find blob path '" + blobIdent.path
- + "' in revision '" + blobIdent.revision + "'");
- }
- blobIdent.mode = treeWalk.getRawMode(0);
- } catch (IOException e) {
- throw new RuntimeException(e);
- }
- } else {
- blobIdent.mode = FileMode.TREE.getBits();
- }
-
- String modeStr = params.get(PARAM_MODE).toString();
- if (modeStr != null)
- mode = Mode.valueOf(modeStr.toUpperCase());
- mark = TextRange.of(params.get(PARAM_MARK).toString());
-
- String commentIdStr = params.get(PARAM_COMMENT).toString();
- if (commentIdStr != null)
- commentId = Long.valueOf(commentIdStr);
-
- queryHits = WebSession.get().getMetaData(SEARCH_RESULT_KEY);
- if (queryHits != null) {
- WebSession.get().setMetaData(SEARCH_RESULT_KEY, null);
- } else {
- String symbol = params.get(PARAM_QUERY).toString();
- if (symbol != null) {
- BlobQuery query = new TextQuery(symbol, false, true, true,
- null, null, SearchResultPanel.MAX_QUERY_ENTRIES);
- try {
- SearchManager searchManager = GitPlex.getInstance(SearchManager.class);
- queryHits = searchManager.search(depotModel.getObject(), commitId, query);
- } catch (InterruptedException e) {
- throw new RuntimeException(e);
- }
- }
- }
-
- RequestCycle.get().setMetaData(VIEW_STATE_KEY, params.get(PARAM_VIEW_STATE).toString());
-
- if (mode == Mode.EDIT || mode == Mode.DELETE) {
- if (!isOnBranch())
- throw new RuntimeException("Files can only be edited on branch");
-
- String path = blobIdent.path;
- if (path != null && blobIdent.isTree())
- path += "/";
- if (!SecurityUtils.canModify(getDepot(), blobIdent.revision, path))
- unauthorized();
- }
- }
-
- @Override
- protected void onInitialize() {
- super.onInitialize();
-
- add(new InstantSearchPanel("instantSearch", depotModel, new AbstractReadOnlyModel<String>() {
-
- @Override
- public String getObject() {
- return blobIdent.revision;
- }
-
- }) {
-
- @Override
- protected void onSelect(AjaxRequestTarget target, QueryHit hit) {
- BlobIdent selected = new BlobIdent(blobIdent.revision, hit.getBlobPath(),
- FileMode.REGULAR_FILE.getBits());
- DepotFilePage.this.onSelect(target, selected, hit.getTokenPos());
- }
-
- @Override
- protected void onMoreQueried(AjaxRequestTarget target, List<QueryHit> hits) {
- newSearchResult(target, hits);
- resizeWindow(target);
- }
-
- });
-
- add(new ModalLink("advancedSearch") {
-
- @Override
- protected Component newContent(String id) {
- return new AdvancedSearchPanel(id, depotModel, new AbstractReadOnlyModel<String>() {
-
- @Override
- public String getObject() {
- return blobIdent.revision;
- }
-
- }) {
-
- @Override
- protected void onSearchComplete(AjaxRequestTarget target, List<QueryHit> hits) {
- newSearchResult(target, hits);
- resizeWindow(target);
- close(target);
- }
-
- @Override
- protected void onCancel(AjaxRequestTarget target) {
- close(target);
- }
-
- @Override
- protected BlobIdent getCurrentBlob() {
- return blobIdent;
- }
-
- };
- }
-
- });
-
- add(new ArchiveMenuLink("download", depotModel) {
-
- @Override
- protected String getRevision() {
- return blobIdent.revision;
- }
-
- });
-
- newRevisionPicker(null);
-
- newFileNavigator(null);
-
- add(revisionIndexing = new WebMarkupContainer("revisionIndexing") {
-
- @Override
- protected void onInitialize() {
- super.onInitialize();
- add(new Image("icon", new PackageResourceReference(DepotFilePage.class, "indexing.gif")));
- setOutputMarkupPlaceholderTag(true);
- }
-
- @Override
- protected void onConfigure() {
- super.onConfigure();
-
- IndexManager indexManager = GitPlex.getInstance(IndexManager.class);
- if (!indexManager.isIndexed(getDepot(), commitId)) {
- GitPlex.getInstance(IndexManager.class).indexAsync(getDepot(), commitId);
- setVisible(true);
- } else {
- setVisible(false);
- }
- }
-
- });
-
- newContributionPanel(null);
- newFileViewer(null);
-
- add(searchResultContainer = new WebMarkupContainer("searchResultContainer"));
-
- newSearchResult(null, queryHits);
-
- add(new WebSocketRenderBehavior() {
-
- @Override
- protected void onRender(WebSocketRequestHandler handler) {
- handler.add(revisionIndexing);
- resizeWindow(handler);
- }
-
- });
- }
-
- /*
- * In case we are on a branch, this operation makes sure that the branch resolves
- * to a certain commit during the life cycle of our page, unless the page is
- * refreshed. This can avoid the issue that displayed file content and subsequent
- * operations encounters different commit if someone commits to the branch while
- * we are staying on the page.
- */
- @Override
- protected Map<String, ObjectId> getObjectIdCache() {
- Map<String, ObjectId> objectIdCache = new HashMap<>();
- if (resolvedRevision != null)
- objectIdCache.put(blobIdent.revision, resolvedRevision);
- return objectIdCache;
- }
-
- @Override
- public CodeComment getOpenComment() {
- if (commentId != null)
- return GitPlex.getInstance(CodeCommentManager.class).load(commentId);
- else
- return null;
- }
-
- private void newFileNavigator(@Nullable AjaxRequestTarget target) {
- final BlobNameChangeCallback callback;
-
- if (mode == Mode.EDIT) {
- callback = new BlobNameChangeCallback() {
-
- @Override
- public void onChange(AjaxRequestTarget target, String blobName) {
- String newPath;
- if (blobIdent.isTree()) {
- if (blobIdent.path != null)
- newPath = blobIdent.path + "/" + blobName;
- else
- newPath = blobName;
- } else {
- if (blobIdent.path.contains("/"))
- newPath = StringUtils.substringBeforeLast(blobIdent.path, "/") + "/" + blobName;
- else
- newPath = blobName;
- }
- newPathRef.set(GitUtils.normalizePath(newPath));
- ((FileEditPanel) get(FILE_VIEWER_ID)).onNewPathChange(target, newPathRef.get());
- }
-
- };
- } else {
- callback = null;
- }
-
- Component fileNavigator = new FileNavigator(FILE_NAVIGATOR_ID, this, callback) {
-
- @Override
- protected void onNewFile(AjaxRequestTarget target) {
- mode = Mode.EDIT;
-
- newFileNavigator(target);
- newContributionPanel(target);
- newFileViewer(target);
-
- pushState(target);
- resizeWindow(target);
- }
-
- };
- if (target != null) {
- replace(fileNavigator);
- target.add(fileNavigator);
- } else {
- add(fileNavigator);
- }
- }
-
- private void newContributionPanel(@Nullable AjaxRequestTarget target) {
- Component contributionPanel;
- if (mode != Mode.EDIT) {
- contributionPanel = new AjaxLazyLoadPanel(CONTRIBUTION_ID) {
-
- @Override
- public Component getLoadingComponent(String markupId) {
- IRequestHandler handler = new ResourceReferenceRequestHandler(AbstractDefaultAjaxBehavior.INDICATOR);
- String html = "<img src='" + RequestCycle.get().urlFor(handler) + "' class='loading'/> Loading latest commit...";
- return new Label(markupId, html).setEscapeModelStrings(false);
- }
-
- @Override
- protected void onComponentLoaded(Component component, AjaxRequestTarget target) {
- super.onComponentLoaded(component, target);
- resizeWindow(target);
- }
-
- @Override
- public Component getLazyLoadComponent(String markupId) {
- return new ContributionPanel(markupId, depotModel, blobIdent);
- }
-
- };
- } else {
- contributionPanel = new WebMarkupContainer(CONTRIBUTION_ID).setVisible(false);
- }
- contributionPanel.setOutputMarkupPlaceholderTag(true);
- if (target != null) {
- replace(contributionPanel);
- target.add(contributionPanel);
- } else {
- add(contributionPanel);
- }
- }
-
- private BlobViewPanel renderBlobViewer(String panelId) {
- for (BlobRenderer renderer: GitPlex.getExtensions(BlobRenderer.class)) {
- BlobViewPanel panel = renderer.render(panelId, this);
- if (panel != null)
- return panel;
- }
-
- throw new IllegalStateException("No applicable blob renderer found.");
- }
-
- private void newFileViewer(@Nullable AjaxRequestTarget target) {
- Component fileViewer;
- if (mode == Mode.EDIT) {
- final String refName = GitUtils.branch2ref(blobIdent.revision);
- newPathRef = new AtomicReference<>(blobIdent.isTree()?null:blobIdent.path);
- fileViewer = new FileEditPanel(
- FILE_VIEWER_ID, depotModel, refName,
- blobIdent.isTree()?null:blobIdent.path,
- blobIdent.isTree()?"":getDepot().getBlob(blobIdent).getText().getContent(),
- getDepot().getObjectId(blobIdent.revision), mark) {
-
- @Override
- protected void onCommitted(AjaxRequestTarget target, ObjectId oldCommit, ObjectId newCommit) {
- Depot depot = getDepot();
- String branch = blobIdent.revision;
- depot.cacheObjectId(branch, newCommit);
- resolvedRevision = newCommit;
- BlobIdent committed = new BlobIdent(
- branch, newPathRef.get(), FileMode.REGULAR_FILE.getBits());
-
- Subject subject = SecurityUtils.getSubject();
-
- Long depotId = depot.getId();
- GitPlex.getInstance(UnitOfWork.class).doAsync(new Runnable() {
-
- @Override
- public void run() {
- ThreadContext.bind(subject);
- try {
- Depot depot = GitPlex.getInstance(DepotManager.class).load(depotId);
- depot.cacheObjectId(branch, newCommit.copy());
- RefUpdated event = new RefUpdated(depot, refName, oldCommit.copy(), newCommit.copy());
- GitPlex.getInstance(ListenerRegistry.class).post(event);
- } finally {
- ThreadContext.unbindSubject();
- }
- }
-
- });
-
- State state = getState();
- state.blobIdent = committed;
- state.mode = null;
- applyState(target, state);
- pushState(target);
- resizeWindow(target);
- }
-
- @Override
- protected void onCancel(AjaxRequestTarget target) {
- mode = null;
- newFileNavigator(target);
- newContributionPanel(target);
- newFileViewer(target);
- pushState(target);
- resizeWindow(target);
- }
-
- };
- } else if (mode == Mode.DELETE) {
- final String refName = GitUtils.branch2ref(blobIdent.revision);
-
- CancelListener cancelListener = new CancelListener() {
-
- @Override
- public void onCancel(AjaxRequestTarget target) {
- mode = null;
- newFileViewer(target);
-
- pushState(target);
- resizeWindow(target);
- }
-
- };
-
- fileViewer = new EditSavePanel(FILE_VIEWER_ID, depotModel, refName, blobIdent.path,
- null, getDepot().getObjectId(blobIdent.revision), cancelListener) {
-
- @Override
- protected void onCommitted(AjaxRequestTarget target, ObjectId oldCommit, ObjectId newCommit) {
- Depot depot = getDepot();
- String branch = blobIdent.revision;
- depot.cacheObjectId(branch, newCommit);
- resolvedRevision = newCommit;
- try (RevWalk revWalk = new RevWalk(getDepot().getRepository())) {
- RevTree revTree = getDepot().getRevCommit(newCommit).getTree();
- String parentPath = StringUtils.substringBeforeLast(blobIdent.path, "/");
- while (TreeWalk.forPath(getDepot().getRepository(), parentPath, revTree) == null) {
- if (parentPath.contains("/")) {
- parentPath = StringUtils.substringBeforeLast(parentPath, "/");
- } else {
- parentPath = null;
- break;
- }
- }
-
- Long depotId = depot.getId();
- Subject subject = SecurityUtils.getSubject();
- GitPlex.getInstance(UnitOfWork.class).doAsync(new Runnable() {
-
- @Override
- public void run() {
- ThreadContext.bind(subject);
- try {
- Depot depot = GitPlex.getInstance(DepotManager.class).load(depotId);
- depot.cacheObjectId(branch, newCommit.copy());
- RefUpdated event = new RefUpdated(depot, refName, oldCommit.copy(), newCommit.copy());
- GitPlex.getInstance(ListenerRegistry.class).post(event);
- } finally {
- ThreadContext.unbindSubject();
- }
- }
-
- });
-
- BlobIdent parentBlobIdent = new BlobIdent(branch, parentPath, FileMode.TREE.getBits());
- State state = getState();
- state.blobIdent = parentBlobIdent;
- state.mode = null;
- applyState(target, state);
- pushState(target);
- resizeWindow(target);
- } catch (IOException e) {
- throw new RuntimeException(e);
- }
- }
-
- };
- } else if (blobIdent.path == null || blobIdent.isTree()) {
- fileViewer = new FileListPanel(FILE_VIEWER_ID, depotModel, blobIdent) {
-
- @Override
- protected void onSelect(AjaxRequestTarget target, BlobIdent blobIdent) {
- DepotFilePage.this.onSelect(target, blobIdent, null);
- }
-
- };
- } else {
- fileViewer = renderBlobViewer(FILE_VIEWER_ID);
- }
- if (target != null) {
- replace(fileViewer);
- target.add(fileViewer);
- } else {
- add(fileViewer);
- }
- }
-
- private void pushState(AjaxRequestTarget target) {
- PageParameters params = paramsOf(getDepot(), getState());
- CharSequence url = RequestCycle.get().urlFor(DepotFilePage.class, params);
- pushState(target, url.toString(), getState());
- }
-
- private State getState() {
- State state = new State();
- state.blobIdent = new BlobIdent(blobIdent);
- state.mark = mark;
- state.mode = mode;
- state.commentId = commentId;
- return state;
- }
-
- private void setState(State state) {
- if (!blobIdent.revision.equals(state.blobIdent.revision)) {
- blobIdent = new BlobIdent(state.blobIdent);
- /*
- * a hack to reset resolved revision to null to disable getObjectIdCache()
- * temporarily as otherwise getObjectId() method below will always
- * resolved to existing value of resolvedRevision
- */
- resolvedRevision = null;
- resolvedRevision = getDepot().getObjectId(blobIdent.revision);
- } else {
- blobIdent = new BlobIdent(state.blobIdent);
- }
- mark = state.mark;
- mode = state.mode;
- commentId = state.commentId;
- GitPlex.getInstance(WebSocketManager.class).onRegionChange(this);
- }
-
- private void onSelect(AjaxRequestTarget target, String revision) {
- State state = getState();
- state.blobIdent.revision = revision;
- state.commentId = null;
- state.mode = null;
- state.mark = null;
-
- if (state.blobIdent.path != null) {
- try (RevWalk revWalk = new RevWalk(getDepot().getRepository())) {
- RevTree revTree = getDepot().getRevCommit(revision, true).getTree();
- TreeWalk treeWalk = TreeWalk.forPath(getDepot().getRepository(), blobIdent.path, revTree);
- if (treeWalk != null) {
- state.blobIdent.mode = treeWalk.getRawMode(0);
- } else {
- state.blobIdent.path = null;
- state.blobIdent.mode = FileMode.TREE.getBits();
- }
- } catch (IOException e) {
- throw new RuntimeException(e);
- }
- }
-
- applyState(target, state);
- pushState(target);
- resizeWindow(target);
- }
-
- private void newRevisionPicker(@Nullable AjaxRequestTarget target) {
- Component revisionPicker = new RevisionPicker(REVISION_PICKER_ID, depotModel, blobIdent.revision, true) {
-
- @Override
- protected String getRevisionUrl(String revision) {
- State state = new State();
- state.blobIdent.revision = revision;
- PageParameters params = DepotFilePage.paramsOf(depotModel.getObject(), state);
- return urlFor(DepotFilePage.class, params).toString();
- }
-
- @Override
- protected void onSelect(AjaxRequestTarget target, String revision) {
- DepotFilePage.this.onSelect(target, revision);
- }
-
- };
- if (target != null) {
- replace(revisionPicker);
- target.add(revisionPicker);
- } else {
- add(revisionPicker);
- }
- }
-
- private void applyState(AjaxRequestTarget target, State state) {
- if (!state.blobIdent.revision.equals(blobIdent.revision))
- newSearchResult(target, null);
-
- setState(state);
- commitId = getDepot().getRevCommit(blobIdent.revision).copy();
- GitPlex.getInstance(WebSocketManager.class).onRegionChange(this);
-
- newRevisionPicker(target);
-
- newFileNavigator(target);
-
- target.add(revisionIndexing);
-
- newContributionPanel(target);
- newFileViewer(target);
- }
-
- @Override
- public void renderHead(IHeaderResponse response) {
- super.renderHead(response);
-
- response.render(JavaScriptHeaderItem.forReference(CookiesResourceReference.INSTANCE));
- response.render(JavaScriptHeaderItem.forReference(JQueryUIResourceReference.INSTANCE));
-
- response.render(JavaScriptHeaderItem.forReference(
- new JavaScriptResourceReference(DepotFilePage.class, "depot-file.js")));
- response.render(CssHeaderItem.forReference(
- new CssResourceReference(DepotFilePage.class, "depot-file.css")));
- }
-
- public static PageParameters paramsOf(Depot depot, CodeComment comment) {
- DepotFilePage.State state = new DepotFilePage.State();
- state.blobIdent.revision = comment.getCommentPos().getCommit();
- state.blobIdent.path = comment.getCommentPos().getPath();
- state.blobIdent.mode = FileMode.TYPE_FILE;
- state.commentId = comment.getId();
- state.mark = comment.getCommentPos().getRange();
- return paramsOf(depot, state);
- }
-
- public static PageParameters paramsOf(Depot depot, State state) {
- PageParameters params = paramsOf(depot);
- if (state.blobIdent.revision != null)
- params.set(PARAM_REVISION, state.blobIdent.revision);
- if (state.blobIdent.path != null)
- params.set(PARAM_PATH, state.blobIdent.path);
- if (state.mark != null)
- params.set(PARAM_MARK, state.mark.toString());
- if (state.commentId != null)
- params.set(PARAM_COMMENT, state.commentId);
- if (state.mode != null)
- params.set(PARAM_MODE, state.mode.name().toLowerCase());
- if (state.query != null)
- params.set(PARAM_QUERY, state.query);
- if (state.viewState != null)
- params.set(PARAM_VIEW_STATE, state.viewState);
- return params;
- }
-
- private void newSearchResult(@Nullable AjaxRequestTarget target, @Nullable List<QueryHit> hits) {
- Component searchResult;
- if (hits != null) {
- searchResult = new SearchResultPanel(SEARCH_RESULD_ID, this, hits) {
-
- @Override
- protected void onClose(AjaxRequestTarget target) {
- newSearchResult(target, null);
- resizeWindow(target);
- }
-
- };
- if (target != null) {
- target.appendJavaScript(""
- + "$('#repo-file>.search-result').show(); "
- + "$('#repo-file .search-result>.body').focus();");
- }
- } else {
- searchResult = new WebMarkupContainer(SEARCH_RESULD_ID).setOutputMarkupId(true);
- if (target != null)
- target.appendJavaScript("$('#repo-file>.search-result').hide();");
- else
- searchResultContainer.add(AttributeAppender.replace("style", "display: none;"));
- }
- if (target != null) {
- searchResultContainer.replace(searchResult);
- target.add(searchResult);
- } else {
- searchResultContainer.add(searchResult);
- }
- }
-
- @Override
- protected void onPopState(AjaxRequestTarget target, Serializable data) {
- super.onPopState(target, data);
-
- applyState(target, (State) data);
- resizeWindow(target);
- }
-
- private void resizeWindow(IPartialPageRequestHandler partialPageRequestHandler) {
- partialPageRequestHandler.appendJavaScript("$(window).resize();");
- }
-
- @Override
- protected void onSelect(AjaxRequestTarget target, Depot depot) {
- setResponsePage(DepotFilePage.class, paramsOf(depot));
- }
-
- @Override
- public BlobIdent getBlobIdent() {
- return blobIdent;
- }
-
- @Override
- public TextRange getMark() {
- return mark;
- }
-
- @Override
- public void onMark(AjaxRequestTarget target, TextRange mark) {
- this.mark = mark;
- pushState(target);
- }
-
- @Override
- public String getMarkUrl(TextRange mark) {
- State state = getState();
- state.blobIdent.revision = resolvedRevision.name();
- state.commentId = null;
- state.mark = mark;
- PageParameters params = paramsOf(getDepot(), state);
- return RequestCycle.get().urlFor(DepotFilePage.class, params).toString();
- }
-
- @Override
- public Mode getMode() {
- return mode;
- }
-
- @Override
- public void onSelect(AjaxRequestTarget target, BlobIdent blobIdent, @Nullable TokenPosition tokenPos) {
- mark = TextRange.of(tokenPos);
- if (Objects.equal(DepotFilePage.this.blobIdent.path, blobIdent.path)) {
- if (mark != null) {
- Component fileViewer = get(FILE_VIEWER_ID);
- if (fileViewer instanceof SourceViewPanel) {
- SourceViewPanel sourceViewer = (SourceViewPanel) fileViewer;
- sourceViewer.mark(target, mark, true);
- } else if (fileViewer instanceof FileEditPanel) {
- FileEditPanel fileEditor = (FileEditPanel) fileViewer;
- fileEditor.mark(target, mark);
- } else {
- newFileViewer(target);
- resizeWindow(target);
- }
- }
- } else {
- DepotFilePage.this.blobIdent.path = blobIdent.path;
- DepotFilePage.this.blobIdent.mode = blobIdent.mode;
-
- mode = null;
- commentId = null;
- GitPlex.getInstance(WebSocketManager.class).onRegionChange(this);
-
- newFileNavigator(target);
- newContributionPanel(target);
- newFileViewer(target);
-
- resizeWindow(target);
- }
- pushState(target);
- }
-
- @Override
- public void onSearchComplete(AjaxRequestTarget target, List<QueryHit> hits) {
- newSearchResult(target, hits);
- resizeWindow(target);
- }
-
- @Override
- public void onBlameChange(AjaxRequestTarget target, boolean blame) {
- mode = (blame?Mode.BLAME:null);
- Component fileViewer = get(FILE_VIEWER_ID);
- if (!(fileViewer instanceof SourceViewPanel)) {
- newFileViewer(target);
- resizeWindow(target);
- }
- pushState(target);
- }
-
- @Override
- public void onDelete(AjaxRequestTarget target) {
- mode = Mode.DELETE;
-
- newFileViewer(target);
- pushState(target);
- resizeWindow(target);
- }
-
- @Override
- public void onEdit(AjaxRequestTarget target) {
- mode = Mode.EDIT;
-
- newFileNavigator(target);
- newContributionPanel(target);
- newFileViewer(target);
- pushState(target);
- resizeWindow(target);
- }
-
- @Override
- public void onCommentOpened(AjaxRequestTarget target, CodeComment comment) {
- if (comment != null) {
- commentId = comment.getId();
- mark = comment.getCommentPos().getRange();
- } else {
- commentId = null;
- }
- GitPlex.getInstance(WebSocketManager.class).onRegionChange(this);
- pushState(target);
- }
-
- @Override
- public void onAddComment(AjaxRequestTarget target, TextRange mark) {
- commentId = null;
- GitPlex.getInstance(WebSocketManager.class).onRegionChange(this);
- this.mark = mark;
- pushState(target);
- }
-
- @Override
- public boolean isOnBranch() {
- return getDepot().getRefs(Constants.R_HEADS).containsKey(blobIdent.revision);
- }
-
- @Override
- public RevCommit getCommit() {
- return getDepot().getRevCommit(getBlobIdent().revision);
- }
-
- @Override
- protected boolean isFootVisible() {
- return false;
- }
-
- @Override
- public List<MenuItem> getMenuItems(MenuLink menuLink) {
- if (mode != Mode.EDIT && mode != Mode.DELETE) {
- Component fileViewer = get(FILE_VIEWER_ID);
- if (fileViewer instanceof BlobViewPanel) {
- BlobViewPanel blobViewPanel = (BlobViewPanel) fileViewer;
- return blobViewPanel.getMenuItems(menuLink);
- }
- }
- return new ArrayList<>();
- }
-
- @Override
- public Collection<WebSocketRegion> getWebSocketRegions() {
- List<WebSocketRegion> regions = new ArrayList<>();
- if (commentId != null)
- regions.add(new CodeCommentChangedRegion(commentId));
- regions.add(new CommitIndexedRegion(getDepot().getId(), commitId));
- return regions;
- }
-
- public static class State implements Serializable {
-
- private static final long serialVersionUID = 1L;
-
- public Long commentId;
-
- public BlobIdent blobIdent = new BlobIdent();
-
- public TextRange mark;
-
- public Mode mode;
-
- public transient String query;
-
- public transient String viewState;
- }
-
-}
+package com.pmease.gitplex.web.page.depot.file;
+
+import java.io.IOException;
+import java.io.Serializable;
+import java.util.ArrayList;
+import java.util.Collection;
+import java.util.HashMap;
+import java.util.List;
+import java.util.Map;
+import java.util.concurrent.atomic.AtomicReference;
+
+import javax.annotation.Nullable;
+
+import org.apache.commons.lang3.StringUtils;
+import org.apache.shiro.subject.Subject;
+import org.apache.shiro.util.ThreadContext;
+import org.apache.wicket.Component;
+import org.apache.wicket.MetaDataKey;
+import org.apache.wicket.RestartResponseException;
+import org.apache.wicket.ajax.AbstractDefaultAjaxBehavior;
+import org.apache.wicket.ajax.AjaxRequestTarget;
+import org.apache.wicket.behavior.AttributeAppender;
+import org.apache.wicket.core.request.handler.IPartialPageRequestHandler;
+import org.apache.wicket.extensions.ajax.markup.html.AjaxLazyLoadPanel;
+import org.apache.wicket.markup.head.CssHeaderItem;
+import org.apache.wicket.markup.head.IHeaderResponse;
+import org.apache.wicket.markup.head.JavaScriptHeaderItem;
+import org.apache.wicket.markup.html.WebMarkupContainer;
+import org.apache.wicket.markup.html.basic.Label;
+import org.apache.wicket.markup.html.image.Image;
+import org.apache.wicket.model.AbstractReadOnlyModel;
+import org.apache.wicket.protocol.ws.api.WebSocketRequestHandler;
+import org.apache.wicket.request.IRequestHandler;
+import org.apache.wicket.request.cycle.RequestCycle;
+import org.apache.wicket.request.handler.resource.ResourceReferenceRequestHandler;
+import org.apache.wicket.request.mapper.parameter.PageParameters;
+import org.apache.wicket.request.resource.CssResourceReference;
+import org.apache.wicket.request.resource.JavaScriptResourceReference;
+import org.apache.wicket.request.resource.PackageResourceReference;
+import org.eclipse.jgit.lib.Constants;
+import org.eclipse.jgit.lib.FileMode;
+import org.eclipse.jgit.lib.ObjectId;
+import org.eclipse.jgit.revwalk.RevCommit;
+import org.eclipse.jgit.revwalk.RevTree;
+import org.eclipse.jgit.revwalk.RevWalk;
+import org.eclipse.jgit.treewalk.TreeWalk;
+
+import com.google.common.base.Objects;
+import com.pmease.commons.git.BlobIdent;
+import com.pmease.commons.git.GitUtils;
+import com.pmease.commons.git.exception.ObjectNotExistException;
+import com.pmease.commons.hibernate.UnitOfWork;
+import com.pmease.commons.lang.extractors.TokenPosition;
+import com.pmease.commons.loader.ListenerRegistry;
+import com.pmease.commons.wicket.assets.cookies.CookiesResourceReference;
+import com.pmease.commons.wicket.assets.jqueryui.JQueryUIResourceReference;
+import com.pmease.commons.wicket.component.menu.MenuItem;
+import com.pmease.commons.wicket.component.menu.MenuLink;
+import com.pmease.commons.wicket.component.modal.ModalLink;
+import com.pmease.commons.wicket.websocket.WebSocketManager;
+import com.pmease.commons.wicket.websocket.WebSocketRegion;
+import com.pmease.commons.wicket.websocket.WebSocketRenderBehavior;
+import com.pmease.gitplex.core.GitPlex;
+import com.pmease.gitplex.core.entity.CodeComment;
+import com.pmease.gitplex.core.entity.Depot;
+import com.pmease.gitplex.core.entity.support.TextRange;
+import com.pmease.gitplex.core.event.RefUpdated;
+import com.pmease.gitplex.core.manager.CodeCommentManager;
+import com.pmease.gitplex.core.manager.DepotManager;
+import com.pmease.gitplex.core.security.SecurityUtils;
+import com.pmease.gitplex.search.IndexManager;
+import com.pmease.gitplex.search.SearchManager;
+import com.pmease.gitplex.search.hit.QueryHit;
+import com.pmease.gitplex.search.query.BlobQuery;
+import com.pmease.gitplex.search.query.TextQuery;
+import com.pmease.gitplex.web.WebSession;
+import com.pmease.gitplex.web.component.archivemenulink.ArchiveMenuLink;
+import com.pmease.gitplex.web.component.depotfile.blobsearch.advanced.AdvancedSearchPanel;
+import com.pmease.gitplex.web.component.depotfile.blobsearch.instant.InstantSearchPanel;
+import com.pmease.gitplex.web.component.depotfile.blobsearch.result.SearchResultPanel;
+import com.pmease.gitplex.web.component.depotfile.blobview.BlobNameChangeCallback;
+import com.pmease.gitplex.web.component.depotfile.blobview.BlobRenderer;
+import com.pmease.gitplex.web.component.depotfile.blobview.BlobViewContext;
+import com.pmease.gitplex.web.component.depotfile.blobview.BlobViewPanel;
+import com.pmease.gitplex.web.component.depotfile.blobview.source.SourceViewPanel;
+import com.pmease.gitplex.web.component.depotfile.editsave.CancelListener;
+import com.pmease.gitplex.web.component.depotfile.editsave.EditSavePanel;
+import com.pmease.gitplex.web.component.depotfile.fileedit.FileEditPanel;
+import com.pmease.gitplex.web.component.depotfile.filelist.FileListPanel;
+import com.pmease.gitplex.web.component.depotfile.filenavigator.FileNavigator;
+import com.pmease.gitplex.web.component.revisionpicker.RevisionPicker;
+import com.pmease.gitplex.web.page.depot.DepotPage;
+import com.pmease.gitplex.web.page.depot.NoBranchesPage;
+import com.pmease.gitplex.web.websocket.CodeCommentChangedRegion;
+import com.pmease.gitplex.web.websocket.CommitIndexedRegion;
+
+@SuppressWarnings("serial")
+public class DepotFilePage extends DepotPage implements BlobViewContext {
+
+ private static class SearchResultKey extends MetaDataKey<ArrayList<QueryHit>> {
+ };
+
+ public static final SearchResultKey SEARCH_RESULT_KEY = new SearchResultKey();
+
+ private static class ViewStateKey extends MetaDataKey<String> {
+ };
+
+ public static final ViewStateKey VIEW_STATE_KEY = new ViewStateKey();
+
+ private static final String PARAM_REVISION = "revision";
+
+ private static final String PARAM_PATH = "path";
+
+ private static final String PARAM_COMMENT = "comment";
+
+ private static final String PARAM_MODE = "mode";
+
+ private static final String PARAM_QUERY = "query";
+
+ private static final String PARAM_VIEW_STATE = "view_state";
+
+ private static final String PARAM_MARK = "mark";
+
+ private static final String REVISION_PICKER_ID = "revisionPicker";
+
+ private static final String FILE_NAVIGATOR_ID = "fileNavigator";
+
+ private static final String CONTRIBUTION_ID = "contribution";
+
+ private static final String FILE_VIEWER_ID = "fileViewer";
+
+ private static final String SEARCH_RESULD_ID = "searchResult";
+
+ private BlobIdent blobIdent = new BlobIdent();
+
+ private ObjectId resolvedRevision;
+
+ private TextRange mark;
+
+ private Mode mode;
+
+ private Long commentId;
+
+ private Component revisionIndexing;
+
+ private WebMarkupContainer searchResultContainer;
+
+ private AtomicReference<String> newPathRef;
+
+ private ObjectId commitId;
+
+ private transient List<QueryHit> queryHits;
+
+ public DepotFilePage(final PageParameters params) {
+ super(params);
+
+ if (getDepot().getDefaultBranch() == null)
+ throw new RestartResponseException(NoBranchesPage.class, paramsOf(getDepot()));
+
+ blobIdent.revision = params.get(PARAM_REVISION).toString();
+ blobIdent.path = GitUtils.normalizePath(params.get(PARAM_PATH).toString());
+
+ blobIdent.revision = GitUtils.normalizePath(params.get(PARAM_REVISION).toString());
+ if (blobIdent.revision == null)
+ blobIdent.revision = getDepot().getDefaultBranch();
+
+ resolvedRevision = getDepot().getObjectId(blobIdent.revision);
+
+ RevCommit commit = getDepot().getRevCommit(blobIdent.revision);
+ commitId = commit.copy();
+
+ if (blobIdent.path != null) {
+ try (RevWalk revWalk = new RevWalk(getDepot().getRepository())) {
+ RevTree revTree = commit.getTree();
+ TreeWalk treeWalk = TreeWalk.forPath(getDepot().getRepository(), blobIdent.path, revTree);
+ if (treeWalk == null) {
+ throw new ObjectNotExistException("Unable to find blob path '" + blobIdent.path
+ + "' in revision '" + blobIdent.revision + "'");
+ }
+ blobIdent.mode = treeWalk.getRawMode(0);
+ } catch (IOException e) {
+ throw new RuntimeException(e);
+ }
+ } else {
+ blobIdent.mode = FileMode.TREE.getBits();
+ }
+
+ String modeStr = params.get(PARAM_MODE).toString();
+ if (modeStr != null)
+ mode = Mode.valueOf(modeStr.toUpperCase());
+ mark = TextRange.of(params.get(PARAM_MARK).toString());
+
+ String commentIdStr = params.get(PARAM_COMMENT).toString();
+ if (commentIdStr != null)
+ commentId = Long.valueOf(commentIdStr);
+
+ queryHits = WebSession.get().getMetaData(SEARCH_RESULT_KEY);
+ if (queryHits != null) {
+ WebSession.get().setMetaData(SEARCH_RESULT_KEY, null);
+ } else {
+ String symbol = params.get(PARAM_QUERY).toString();
+ if (symbol != null) {
+ BlobQuery query = new TextQuery(symbol, false, true, true,
+ null, null, SearchResultPanel.MAX_QUERY_ENTRIES);
+ try {
+ SearchManager searchManager = GitPlex.getInstance(SearchManager.class);
+ queryHits = searchManager.search(depotModel.getObject(), commitId, query);
+ } catch (InterruptedException e) {
+ throw new RuntimeException(e);
+ }
+ }
+ }
+
+ RequestCycle.get().setMetaData(VIEW_STATE_KEY, params.get(PARAM_VIEW_STATE).toString());
+
+ if (mode == Mode.EDIT || mode == Mode.DELETE) {
+ if (!isOnBranch())
+ throw new RuntimeException("Files can only be edited on branch");
+
+ String path = blobIdent.path;
+ if (path != null && blobIdent.isTree())
+ path += "/";
+ if (!SecurityUtils.canModify(getDepot(), blobIdent.revision, path))
+ unauthorized();
+ }
+ }
+
+ @Override
+ protected void onInitialize() {
+ super.onInitialize();
+
+ add(new InstantSearchPanel("instantSearch", depotModel, new AbstractReadOnlyModel<String>() {
+
+ @Override
+ public String getObject() {
+ return blobIdent.revision;
+ }
+
+ }) {
+
+ @Override
+ protected void onSelect(AjaxRequestTarget target, QueryHit hit) {
+ BlobIdent selected = new BlobIdent(blobIdent.revision, hit.getBlobPath(),
+ FileMode.REGULAR_FILE.getBits());
+ DepotFilePage.this.onSelect(target, selected, hit.getTokenPos());
+ }
+
+ @Override
+ protected void onMoreQueried(AjaxRequestTarget target, List<QueryHit> hits) {
+ newSearchResult(target, hits);
+ resizeWindow(target);
+ }
+
+ });
+
+ add(new ModalLink("advancedSearch") {
+
+ @Override
+ protected Component newContent(String id) {
+ return new AdvancedSearchPanel(id, depotModel, new AbstractReadOnlyModel<String>() {
+
+ @Override
+ public String getObject() {
+ return blobIdent.revision;
+ }
+
+ }) {
+
+ @Override
+ protected void onSearchComplete(AjaxRequestTarget target, List<QueryHit> hits) {
+ newSearchResult(target, hits);
+ resizeWindow(target);
+ close(target);
+ }
+
+ @Override
+ protected void onCancel(AjaxRequestTarget target) {
+ close(target);
+ }
+
+ @Override
+ protected BlobIdent getCurrentBlob() {
+ return blobIdent;
+ }
+
+ };
+ }
+
+ });
+
+ add(new ArchiveMenuLink("download", depotModel) {
+
+ @Override
+ protected String getRevision() {
+ return blobIdent.revision;
+ }
+
+ });
+
+ newRevisionPicker(null);
+
+ newFileNavigator(null);
+
+ add(revisionIndexing = new WebMarkupContainer("revisionIndexing") {
+
+ @Override
+ protected void onInitialize() {
+ super.onInitialize();
+ add(new Image("icon", new PackageResourceReference(DepotFilePage.class, "indexing.gif")));
+ setOutputMarkupPlaceholderTag(true);
+ }
+
+ @Override
+ protected void onConfigure() {
+ super.onConfigure();
+
+ IndexManager indexManager = GitPlex.getInstance(IndexManager.class);
+ if (!indexManager.isIndexed(getDepot(), commitId)) {
+ GitPlex.getInstance(IndexManager.class).indexAsync(getDepot(), commitId);
+ setVisible(true);
+ } else {
+ setVisible(false);
+ }
+ }
+
+ });
+
+ newContributionPanel(null);
+ newFileViewer(null);
+
+ add(searchResultContainer = new WebMarkupContainer("searchResultContainer"));
+
+ newSearchResult(null, queryHits);
+
+ add(new WebSocketRenderBehavior() {
+
+ @Override
+ protected void onRender(WebSocketRequestHandler handler) {
+ handler.add(revisionIndexing);
+ resizeWindow(handler);
+ }
+
+ });
+ }
+
+ /*
+ * In case we are on a branch, this operation makes sure that the branch resolves
+ * to a certain commit during the life cycle of our page, unless the page is
+ * refreshed. This can avoid the issue that displayed file content and subsequent
+ * operations encounters different commit if someone commits to the branch while
+ * we are staying on the page.
+ */
+ @Override
+ protected Map<String, ObjectId> getObjectIdCache() {
+ Map<String, ObjectId> objectIdCache = new HashMap<>();
+ if (resolvedRevision != null)
+ objectIdCache.put(blobIdent.revision, resolvedRevision);
+ return objectIdCache;
+ }
+
+ @Override
+ public CodeComment getOpenComment() {
+ if (commentId != null)
+ return GitPlex.getInstance(CodeCommentManager.class).load(commentId);
+ else
+ return null;
+ }
+
+ private void newFileNavigator(@Nullable AjaxRequestTarget target) {
+ final BlobNameChangeCallback callback;
+
+ if (mode == Mode.EDIT) {
+ callback = new BlobNameChangeCallback() {
+
+ @Override
+ public void onChange(AjaxRequestTarget target, String blobName) {
+ String newPath;
+ if (blobIdent.isTree()) {
+ if (blobIdent.path != null)
+ newPath = blobIdent.path + "/" + blobName;
+ else
+ newPath = blobName;
+ } else {
+ if (blobIdent.path.contains("/"))
+ newPath = StringUtils.substringBeforeLast(blobIdent.path, "/") + "/" + blobName;
+ else
+ newPath = blobName;
+ }
+ newPathRef.set(GitUtils.normalizePath(newPath));
+ ((FileEditPanel) get(FILE_VIEWER_ID)).onNewPathChange(target, newPathRef.get());
+ }
+
+ };
+ } else {
+ callback = null;
+ }
+
+ Component fileNavigator = new FileNavigator(FILE_NAVIGATOR_ID, this, callback) {
+
+ @Override
+ protected void onNewFile(AjaxRequestTarget target) {
+ mode = Mode.EDIT;
+
+ newFileNavigator(target);
+ newContributionPanel(target);
+ newFileViewer(target);
+
+ pushState(target);
+ resizeWindow(target);
+ }
+
+ };
+ if (target != null) {
+ replace(fileNavigator);
+ target.add(fileNavigator);
+ } else {
+ add(fileNavigator);
+ }
+ }
+
+ private void newContributionPanel(@Nullable AjaxRequestTarget target) {
+ Component contributionPanel;
+ if (mode != Mode.EDIT) {
+ contributionPanel = new AjaxLazyLoadPanel(CONTRIBUTION_ID) {
+
+ @Override
+ public Component getLoadingComponent(String markupId) {
+ IRequestHandler handler = new ResourceReferenceRequestHandler(AbstractDefaultAjaxBehavior.INDICATOR);
+ String html = "<img src='" + RequestCycle.get().urlFor(handler) + "' class='loading'/> Loading latest commit...";
+ return new Label(markupId, html).setEscapeModelStrings(false);
+ }
+
+ @Override
+ protected void onComponentLoaded(Component component, AjaxRequestTarget target) {
+ super.onComponentLoaded(component, target);
+ resizeWindow(target);
+ }
+
+ @Override
+ public Component getLazyLoadComponent(String markupId) {
+ return new ContributionPanel(markupId, depotModel, blobIdent);
+ }
+
+ };
+ } else {
+ contributionPanel = new WebMarkupContainer(CONTRIBUTION_ID).setVisible(false);
+ }
+ contributionPanel.setOutputMarkupPlaceholderTag(true);
+ if (target != null) {
+ replace(contributionPanel);
+ target.add(contributionPanel);
+ } else {
+ add(contributionPanel);
+ }
+ }
+
+ private BlobViewPanel renderBlobViewer(String panelId) {
+ for (BlobRenderer renderer: GitPlex.getExtensions(BlobRenderer.class)) {
+ BlobViewPanel panel = renderer.render(panelId, this);
+ if (panel != null)
+ return panel;
+ }
+
+ throw new IllegalStateException("No applicable blob renderer found.");
+ }
+
+ private void newFileViewer(@Nullable AjaxRequestTarget target) {
+ Component fileViewer;
+ if (mode == Mode.EDIT) {
+ final String refName = GitUtils.branch2ref(blobIdent.revision);
+ newPathRef = new AtomicReference<>(blobIdent.isTree()?null:blobIdent.path);
+ fileViewer = new FileEditPanel(
+ FILE_VIEWER_ID, depotModel, refName,
+ blobIdent.isTree()?null:blobIdent.path,
+ blobIdent.isTree()?"":getDepot().getBlob(blobIdent).getText().getContent(),
+ getDepot().getObjectId(blobIdent.revision), mark) {
+
+ @Override
+ protected void onCommitted(AjaxRequestTarget target, ObjectId oldCommit, ObjectId newCommit) {
+ Depot depot = getDepot();
+ String branch = blobIdent.revision;
+ depot.cacheObjectId(branch, newCommit);
+ resolvedRevision = newCommit;
+ BlobIdent committed = new BlobIdent(
+ branch, newPathRef.get(), FileMode.REGULAR_FILE.getBits());
+
+ Subject subject = SecurityUtils.getSubject();
+
+ Long depotId = depot.getId();
+ ObjectId oldCommitId = oldCommit.copy();
+ ObjectId newCommitId = newCommit.copy();
+ GitPlex.getInstance(UnitOfWork.class).doAsync(new Runnable() {
+
+ @Override
+ public void run() {
+ ThreadContext.bind(subject);
+ try {
+ Depot depot = GitPlex.getInstance(DepotManager.class).load(depotId);
+ depot.cacheObjectId(branch, oldCommitId);
+ RefUpdated event = new RefUpdated(depot, refName, oldCommitId, newCommitId);
+ GitPlex.getInstance(ListenerRegistry.class).post(event);
+ } finally {
+ ThreadContext.unbindSubject();
+ }
+ }
+
+ });
+
+ State state = getState();
+ state.blobIdent = committed;
+ state.mode = null;
+ applyState(target, state);
+ pushState(target);
+ resizeWindow(target);
+ }
+
+ @Override
+ protected void onCancel(AjaxRequestTarget target) {
+ mode = null;
+ newFileNavigator(target);
+ newContributionPanel(target);
+ newFileViewer(target);
+ pushState(target);
+ resizeWindow(target);
+ }
+
+ };
+ } else if (mode == Mode.DELETE) {
+ final String refName = GitUtils.branch2ref(blobIdent.revision);
+
+ CancelListener cancelListener = new CancelListener() {
+
+ @Override
+ public void onCancel(AjaxRequestTarget target) {
+ mode = null;
+ newFileViewer(target);
+
+ pushState(target);
+ resizeWindow(target);
+ }
+
+ };
+
+ fileViewer = new EditSavePanel(FILE_VIEWER_ID, depotModel, refName, blobIdent.path,
+ null, getDepot().getObjectId(blobIdent.revision), cancelListener) {
+
+ @Override
+ protected void onCommitted(AjaxRequestTarget target, ObjectId oldCommit, ObjectId newCommit) {
+ Depot depot = getDepot();
+ String branch = blobIdent.revision;
+ depot.cacheObjectId(branch, newCommit);
+ resolvedRevision = newCommit;
+ try (RevWalk revWalk = new RevWalk(getDepot().getRepository())) {
+ RevTree revTree = getDepot().getRevCommit(newCommit).getTree();
+ String parentPath = StringUtils.substringBeforeLast(blobIdent.path, "/");
+ while (TreeWalk.forPath(getDepot().getRepository(), parentPath, revTree) == null) {
+ if (parentPath.contains("/")) {
+ parentPath = StringUtils.substringBeforeLast(parentPath, "/");
+ } else {
+ parentPath = null;
+ break;
+ }
+ }
+
+ Long depotId = depot.getId();
+ Subject subject = SecurityUtils.getSubject();
+ ObjectId oldCommitId = oldCommit.copy();
+ ObjectId newCommitId = newCommit.copy();
+ GitPlex.getInstance(UnitOfWork.class).doAsync(new Runnable() {
+
+ @Override
+ public void run() {
+ ThreadContext.bind(subject);
+ try {
+ Depot depot = GitPlex.getInstance(DepotManager.class).load(depotId);
+ depot.cacheObjectId(branch, newCommitId);
+ RefUpdated event = new RefUpdated(depot, refName, oldCommitId, newCommitId);
+ GitPlex.getInstance(ListenerRegistry.class).post(event);
+ } finally {
+ ThreadContext.unbindSubject();
+ }
+ }
+
+ });
+
+ BlobIdent parentBlobIdent = new BlobIdent(branch, parentPath, FileMode.TREE.getBits());
+ State state = getState();
+ state.blobIdent = parentBlobIdent;
+ state.mode = null;
+ applyState(target, state);
+ pushState(target);
+ resizeWindow(target);
+ } catch (IOException e) {
+ throw new RuntimeException(e);
+ }
+ }
+
+ };
+ } else if (blobIdent.path == null || blobIdent.isTree()) {
+ fileViewer = new FileListPanel(FILE_VIEWER_ID, depotModel, blobIdent) {
+
+ @Override
+ protected void onSelect(AjaxRequestTarget target, BlobIdent blobIdent) {
+ DepotFilePage.this.onSelect(target, blobIdent, null);
+ }
+
+ };
+ } else {
+ fileViewer = renderBlobViewer(FILE_VIEWER_ID);
+ }
+ if (target != null) {
+ replace(fileViewer);
+ target.add(fileViewer);
+ } else {
+ add(fileViewer);
+ }
+ }
+
+ private void pushState(AjaxRequestTarget target) {
+ PageParameters params = paramsOf(getDepot(), getState());
+ CharSequence url = RequestCycle.get().urlFor(DepotFilePage.class, params);
+ pushState(target, url.toString(), getState());
+ }
+
+ private State getState() {
+ State state = new State();
+ state.blobIdent = new BlobIdent(blobIdent);
+ state.mark = mark;
+ state.mode = mode;
+ state.commentId = commentId;
+ return state;
+ }
+
+ private void setState(State state) {
+ if (!blobIdent.revision.equals(state.blobIdent.revision)) {
+ blobIdent = new BlobIdent(state.blobIdent);
+ /*
+ * a hack to reset resolved revision to null to disable getObjectIdCache()
+ * temporarily as otherwise getObjectId() method below will always
+ * resolved to existing value of resolvedRevision
+ */
+ resolvedRevision = null;
+ resolvedRevision = getDepot().getObjectId(blobIdent.revision);
+ } else {
+ blobIdent = new BlobIdent(state.blobIdent);
+ }
+ mark = state.mark;
+ mode = state.mode;
+ commentId = state.commentId;
+ GitPlex.getInstance(WebSocketManager.class).onRegionChange(this);
+ }
+
+ private void onSelect(AjaxRequestTarget target, String revision) {
+ State state = getState();
+ state.blobIdent.revision = revision;
+ state.commentId = null;
+ state.mode = null;
+ state.mark = null;
+
+ if (state.blobIdent.path != null) {
+ try (RevWalk revWalk = new RevWalk(getDepot().getRepository())) {
+ RevTree revTree = getDepot().getRevCommit(revision, true).getTree();
+ TreeWalk treeWalk = TreeWalk.forPath(getDepot().getRepository(), blobIdent.path, revTree);
+ if (treeWalk != null) {
+ state.blobIdent.mode = treeWalk.getRawMode(0);
+ } else {
+ state.blobIdent.path = null;
+ state.blobIdent.mode = FileMode.TREE.getBits();
+ }
+ } catch (IOException e) {
+ throw new RuntimeException(e);
+ }
+ }
+
+ applyState(target, state);
+ pushState(target);
+ resizeWindow(target);
+ }
+
+ private void newRevisionPicker(@Nullable AjaxRequestTarget target) {
+ Component revisionPicker = new RevisionPicker(REVISION_PICKER_ID, depotModel, blobIdent.revision, true) {
+
+ @Override
+ protected String getRevisionUrl(String revision) {
+ State state = new State();
+ state.blobIdent.revision = revision;
+ PageParameters params = DepotFilePage.paramsOf(depotModel.getObject(), state);
+ return urlFor(DepotFilePage.class, params).toString();
+ }
+
+ @Override
+ protected void onSelect(AjaxRequestTarget target, String revision) {
+ DepotFilePage.this.onSelect(target, revision);
+ }
+
+ };
+ if (target != null) {
+ replace(revisionPicker);
+ target.add(revisionPicker);
+ } else {
+ add(revisionPicker);
+ }
+ }
+
+ private void applyState(AjaxRequestTarget target, State state) {
+ if (!state.blobIdent.revision.equals(blobIdent.revision))
+ newSearchResult(target, null);
+
+ setState(state);
+ commitId = getDepot().getRevCommit(blobIdent.revision).copy();
+ GitPlex.getInstance(WebSocketManager.class).onRegionChange(this);
+
+ newRevisionPicker(target);
+
+ newFileNavigator(target);
+
+ target.add(revisionIndexing);
+
+ newContributionPanel(target);
+ newFileViewer(target);
+ }
+
+ @Override
+ public void renderHead(IHeaderResponse response) {
+ super.renderHead(response);
+
+ response.render(JavaScriptHeaderItem.forReference(CookiesResourceReference.INSTANCE));
+ response.render(JavaScriptHeaderItem.forReference(JQueryUIResourceReference.INSTANCE));
+
+ response.render(JavaScriptHeaderItem.forReference(
+ new JavaScriptResourceReference(DepotFilePage.class, "depot-file.js")));
+ response.render(CssHeaderItem.forReference(
+ new CssResourceReference(DepotFilePage.class, "depot-file.css")));
+ }
+
+ public static PageParameters paramsOf(Depot depot, CodeComment comment) {
+ DepotFilePage.State state = new DepotFilePage.State();
+ state.blobIdent.revision = comment.getCommentPos().getCommit();
+ state.blobIdent.path = comment.getCommentPos().getPath();
+ state.blobIdent.mode = FileMode.TYPE_FILE;
+ state.commentId = comment.getId();
+ state.mark = comment.getCommentPos().getRange();
+ return paramsOf(depot, state);
+ }
+
+ public static PageParameters paramsOf(Depot depot, State state) {
+ PageParameters params = paramsOf(depot);
+ if (state.blobIdent.revision != null)
+ params.set(PARAM_REVISION, state.blobIdent.revision);
+ if (state.blobIdent.path != null)
+ params.set(PARAM_PATH, state.blobIdent.path);
+ if (state.mark != null)
+ params.set(PARAM_MARK, state.mark.toString());
+ if (state.commentId != null)
+ params.set(PARAM_COMMENT, state.commentId);
+ if (state.mode != null)
+ params.set(PARAM_MODE, state.mode.name().toLowerCase());
+ if (state.query != null)
+ params.set(PARAM_QUERY, state.query);
+ if (state.viewState != null)
+ params.set(PARAM_VIEW_STATE, state.viewState);
+ return params;
+ }
+
+ private void newSearchResult(@Nullable AjaxRequestTarget target, @Nullable List<QueryHit> hits) {
+ Component searchResult;
+ if (hits != null) {
+ searchResult = new SearchResultPanel(SEARCH_RESULD_ID, this, hits) {
+
+ @Override
+ protected void onClose(AjaxRequestTarget target) {
+ newSearchResult(target, null);
+ resizeWindow(target);
+ }
+
+ };
+ if (target != null) {
+ target.appendJavaScript(""
+ + "$('#repo-file>.search-result').show(); "
+ + "$('#repo-file .search-result>.body').focus();");
+ }
+ } else {
+ searchResult = new WebMarkupContainer(SEARCH_RESULD_ID).setOutputMarkupId(true);
+ if (target != null)
+ target.appendJavaScript("$('#repo-file>.search-result').hide();");
+ else
+ searchResultContainer.add(AttributeAppender.replace("style", "display: none;"));
+ }
+ if (target != null) {
+ searchResultContainer.replace(searchResult);
+ target.add(searchResult);
+ } else {
+ searchResultContainer.add(searchResult);
+ }
+ }
+
+ @Override
+ protected void onPopState(AjaxRequestTarget target, Serializable data) {
+ super.onPopState(target, data);
+
+ applyState(target, (State) data);
+ resizeWindow(target);
+ }
+
+ private void resizeWindow(IPartialPageRequestHandler partialPageRequestHandler) {
+ partialPageRequestHandler.appendJavaScript("$(window).resize();");
+ }
+
+ @Override
+ protected void onSelect(AjaxRequestTarget target, Depot depot) {
+ setResponsePage(DepotFilePage.class, paramsOf(depot));
+ }
+
+ @Override
+ public BlobIdent getBlobIdent() {
+ return blobIdent;
+ }
+
+ @Override
+ public TextRange getMark() {
+ return mark;
+ }
+
+ @Override
+ public void onMark(AjaxRequestTarget target, TextRange mark) {
+ this.mark = mark;
+ pushState(target);
+ }
+
+ @Override
+ public String getMarkUrl(TextRange mark) {
+ State state = getState();
+ state.blobIdent.revision = resolvedRevision.name();
+ state.commentId = null;
+ state.mark = mark;
+ PageParameters params = paramsOf(getDepot(), state);
+ return RequestCycle.get().urlFor(DepotFilePage.class, params).toString();
+ }
+
+ @Override
+ public Mode getMode() {
+ return mode;
+ }
+
+ @Override
+ public void onSelect(AjaxRequestTarget target, BlobIdent blobIdent, @Nullable TokenPosition tokenPos) {
+ mark = TextRange.of(tokenPos);
+ if (Objects.equal(DepotFilePage.this.blobIdent.path, blobIdent.path)) {
+ if (mark != null) {
+ Component fileViewer = get(FILE_VIEWER_ID);
+ if (fileViewer instanceof SourceViewPanel) {
+ SourceViewPanel sourceViewer = (SourceViewPanel) fileViewer;
+ sourceViewer.mark(target, mark, true);
+ } else if (fileViewer instanceof FileEditPanel) {
+ FileEditPanel fileEditor = (FileEditPanel) fileViewer;
+ fileEditor.mark(target, mark);
+ } else {
+ newFileViewer(target);
+ resizeWindow(target);
+ }
+ }
+ } else {
+ DepotFilePage.this.blobIdent.path = blobIdent.path;
+ DepotFilePage.this.blobIdent.mode = blobIdent.mode;
+
+ mode = null;
+ commentId = null;
+ GitPlex.getInstance(WebSocketManager.class).onRegionChange(this);
+
+ newFileNavigator(target);
+ newContributionPanel(target);
+ newFileViewer(target);
+
+ resizeWindow(target);
+ }
+ pushState(target);
+ }
+
+ @Override
+ public void onSearchComplete(AjaxRequestTarget target, List<QueryHit> hits) {
+ newSearchResult(target, hits);
+ resizeWindow(target);
+ }
+
+ @Override
+ public void onBlameChange(AjaxRequestTarget target, boolean blame) {
+ mode = (blame?Mode.BLAME:null);
+ Component fileViewer = get(FILE_VIEWER_ID);
+ if (!(fileViewer instanceof SourceViewPanel)) {
+ newFileViewer(target);
+ resizeWindow(target);
+ }
+ pushState(target);
+ }
+
+ @Override
+ public void onDelete(AjaxRequestTarget target) {
+ mode = Mode.DELETE;
+
+ newFileViewer(target);
+ pushState(target);
+ resizeWindow(target);
+ }
+
+ @Override
+ public void onEdit(AjaxRequestTarget target) {
+ mode = Mode.EDIT;
+
+ newFileNavigator(target);
+ newContributionPanel(target);
+ newFileViewer(target);
+ pushState(target);
+ resizeWindow(target);
+ }
+
+ @Override
+ public void onCommentOpened(AjaxRequestTarget target, CodeComment comment) {
+ if (comment != null) {
+ commentId = comment.getId();
+ mark = comment.getCommentPos().getRange();
+ } else {
+ commentId = null;
+ }
+ GitPlex.getInstance(WebSocketManager.class).onRegionChange(this);
+ pushState(target);
+ }
+
+ @Override
+ public void onAddComment(AjaxRequestTarget target, TextRange mark) {
+ commentId = null;
+ GitPlex.getInstance(WebSocketManager.class).onRegionChange(this);
+ this.mark = mark;
+ pushState(target);
+ }
+
+ @Override
+ public boolean isOnBranch() {
+ return getDepot().getRefs(Constants.R_HEADS).containsKey(blobIdent.revision);
+ }
+
+ @Override
+ public RevCommit getCommit() {
+ return getDepot().getRevCommit(getBlobIdent().revision);
+ }
+
+ @Override
+ protected boolean isFootVisible() {
+ return false;
+ }
+
+ @Override
+ public List<MenuItem> getMenuItems(MenuLink menuLink) {
+ if (mode != Mode.EDIT && mode != Mode.DELETE) {
+ Component fileViewer = get(FILE_VIEWER_ID);
+ if (fileViewer instanceof BlobViewPanel) {
+ BlobViewPanel blobViewPanel = (BlobViewPanel) fileViewer;
+ return blobViewPanel.getMenuItems(menuLink);
+ }
+ }
+ return new ArrayList<>();
+ }
+
+ @Override
+ public Collection<WebSocketRegion> getWebSocketRegions() {
+ List<WebSocketRegion> regions = new ArrayList<>();
+ if (commentId != null)
+ regions.add(new CodeCommentChangedRegion(commentId));
+ regions.add(new CommitIndexedRegion(getDepot().getId(), commitId));
+ return regions;
+ }
+
+ public static class State implements Serializable {
+
+ private static final long serialVersionUID = 1L;
+
+ public Long commentId;
+
+ public BlobIdent blobIdent = new BlobIdent();
+
+ public TextRange mark;
+
+ public Mode mode;
+
+ public transient String query;
+
+ public transient String viewState;
+ }
+
+}
diff --git a/gitplex.web/src/main/java/com/pmease/gitplex/web/page/depot/pullrequest/newrequest/NewRequestPage.java b/gitplex.web/src/main/java/com/pmease/gitplex/web/page/depot/pullrequest/newrequest/NewRequestPage.java
index 1811e251a5..2162c4d765 100644
--- a/gitplex.web/src/main/java/com/pmease/gitplex/web/page/depot/pullrequest/newrequest/NewRequestPage.java
+++ b/gitplex.web/src/main/java/com/pmease/gitplex/web/page/depot/pullrequest/newrequest/NewRequestPage.java
@@ -217,7 +217,7 @@ public class NewRequestPage extends PullRequestPage implements CommentSupport {
PullRequest request = getPullRequest();
List<RevCommit> commits = new ArrayList<>();
try (RevWalk revWalk = new RevWalk(getDepot().getRepository())) {
- ObjectId headId = ObjectId.fromString(request.getLatestUpdate().getHeadCommitHash());
+ ObjectId headId = ObjectId.fromString(request.getHeadCommitHash());
revWalk.markStart(revWalk.parseCommit(headId));
ObjectId baseId = ObjectId.fromString(request.getBaseCommitHash());
revWalk.markUninteresting(revWalk.parseCommit(baseId));
@@ -349,7 +349,7 @@ public class NewRequestPage extends PullRequestPage implements CommentSupport {
protected Depot load() {
Depot depot = source.getDepot();
depot.cacheObjectId(source.getRevision(),
- ObjectId.fromString(getPullRequest().getLatestUpdate().getHeadCommitHash()));
+ ObjectId.fromString(getPullRequest().getHeadCommitHash()));
return depot;
}
@@ -489,7 +489,7 @@ public class NewRequestPage extends PullRequestPage implements CommentSupport {
@Override
protected List<String> load() {
- return getPullRequest().checkGates(false).getReasons();
+ return getPullRequest().checkGates(false).getReasons();
}
}) {
@@ -711,7 +711,7 @@ public class NewRequestPage extends PullRequestPage implements CommentSupport {
RevisionComparePage.State state = new RevisionComparePage.State();
state.mark = mark;
state.leftSide = new DepotAndBranch(source.getDepot(), getPullRequest().getBaseCommitHash());
- state.rightSide = new DepotAndBranch(source.getDepot(), getPullRequest().getLatestUpdate().getHeadCommitHash());
+ state.rightSide = new DepotAndBranch(source.getDepot(), getPullRequest().getHeadCommitHash());
state.pathFilter = pathFilter;
state.tabPanel = RevisionComparePage.TabPanel.CHANGES;
state.whitespaceOption = whitespaceOption;
@@ -743,7 +743,7 @@ public class NewRequestPage extends PullRequestPage implements CommentSupport {
mark = comment.getCommentPos();
state.commentId = comment.getId();
state.leftSide = new DepotAndBranch(source.getDepot(), getPullRequest().getBaseCommitHash());
- state.rightSide = new DepotAndBranch(source.getDepot(), getPullRequest().getLatestUpdate().getHeadCommitHash());
+ state.rightSide = new DepotAndBranch(source.getDepot(), getPullRequest().getHeadCommitHash());
state.pathFilter = pathFilter;
state.tabPanel = RevisionComparePage.TabPanel.CHANGES;
state.whitespaceOption = whitespaceOption;
diff --git a/gitplex.web/src/main/java/com/pmease/gitplex/web/page/depot/pullrequest/requestdetail/PullRequestOperation.java b/gitplex.web/src/main/java/com/pmease/gitplex/web/page/depot/pullrequest/requestdetail/PullRequestOperation.java
index 8d864d4c57..417c9b2f57 100644
--- a/gitplex.web/src/main/java/com/pmease/gitplex/web/page/depot/pullrequest/requestdetail/PullRequestOperation.java
+++ b/gitplex.web/src/main/java/com/pmease/gitplex/web/page/depot/pullrequest/requestdetail/PullRequestOperation.java
@@ -1,5 +1,7 @@
package com.pmease.gitplex.web.page.depot.pullrequest.requestdetail;
+import static com.pmease.gitplex.core.entity.PullRequest.Status.PENDING_INTEGRATE;
+
import javax.annotation.Nullable;
import org.apache.wicket.Component;
@@ -26,11 +28,12 @@ public enum PullRequestOperation {
@Override
public boolean canOperate(PullRequest request) {
- if (!SecurityUtils.getSubject().isPermitted(
- ObjectPermission.ofDepotWrite(request.getTargetDepot()))) {
+ if (!SecurityUtils.getSubject().isPermitted(ObjectPermission.ofDepotWrite(request.getTargetDepot()))
+ || request.getStatus() != PENDING_INTEGRATE) {
return false;
} else {
- return GitPlex.getInstance(PullRequestManager.class).canIntegrate(request);
+ IntegrationPreview integrationPreview = request.getIntegrationPreview();
+ return integrationPreview != null && integrationPreview.getIntegrated() != null;
}
}
@@ -170,7 +173,7 @@ public enum PullRequestOperation {
return request.getSourceDepot() != null
&& request.getSource().getObjectName(false) == null
&& SecurityUtils.canModify(request)
- && SecurityUtils.canPushRef(request.getSourceDepot(), request.getSourceRef(), ObjectId.zeroId(), ObjectId.fromString(request.getLatestUpdate().getHeadCommitHash()));
+ && SecurityUtils.canPushRef(request.getSourceDepot(), request.getSourceRef(), ObjectId.zeroId(), ObjectId.fromString(request.getHeadCommitHash()));
}
};
diff --git a/gitplex.web/src/main/java/com/pmease/gitplex/web/page/depot/pullrequest/requestdetail/RequestDetailPage.java b/gitplex.web/src/main/java/com/pmease/gitplex/web/page/depot/pullrequest/requestdetail/RequestDetailPage.java
index 8317189ba1..1bdc83a3fc 100644
--- a/gitplex.web/src/main/java/com/pmease/gitplex/web/page/depot/pullrequest/requestdetail/RequestDetailPage.java
+++ b/gitplex.web/src/main/java/com/pmease/gitplex/web/page/depot/pullrequest/requestdetail/RequestDetailPage.java
@@ -51,8 +51,6 @@ import org.apache.wicket.request.mapper.parameter.PageParameters;
import org.apache.wicket.request.resource.CssResourceReference;
import org.apache.wicket.util.visit.IVisit;
import org.apache.wicket.util.visit.IVisitor;
-import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
import com.google.common.base.Preconditions;
import com.google.common.collect.Lists;
@@ -100,8 +98,6 @@ import de.agilecoders.wicket.core.markup.html.bootstrap.common.NotificationPanel
@SuppressWarnings("serial")
public abstract class RequestDetailPage extends PullRequestPage {
- private static final Logger logger = LoggerFactory.getLogger(RequestDetailPage.class);
-
protected IModel<PullRequest> requestModel;
private boolean editingTitle;
@@ -694,21 +690,9 @@ public abstract class RequestDetailPage extends PullRequestPage {
protected void onSubmit(AjaxRequestTarget target, Form<?> form) {
super.onSubmit(target, form);
- String actionName = operation.name().toLowerCase();
-
PullRequest request = getPullRequest();
- try {
- operation.operate(request, noteInput.getModelObject());
- setResponsePage(getPage().getClass(), paramsOf(getPullRequest()));
- } catch (Exception e) {
- if (e.getMessage() != null) {
- error("Unable to " + actionName + ": " + e.getMessage());
- logger.error("Error " + actionName, e);
- } else {
- error("Unable to " + actionName + ": check log for details");
- }
- target.add(operationsContainer);
- }
+ operation.operate(request, noteInput.getModelObject());
+ setResponsePage(getPage().getClass(), paramsOf(getPullRequest()));
}
}.add(AttributeModifier.replace("value", new AbstractReadOnlyModel<String>() {
@@ -896,7 +880,7 @@ public abstract class RequestDetailPage extends PullRequestPage {
@Override
public List<String> getObject() {
- return getPullRequest().checkGates(false).getReasons();
+ return getPullRequest().checkGates(false).getReasons();
}
}) {
diff --git a/gitplex.web/src/main/java/com/pmease/gitplex/web/page/depot/pullrequest/requestdetail/changes/RequestChangesPage.java b/gitplex.web/src/main/java/com/pmease/gitplex/web/page/depot/pullrequest/requestdetail/changes/RequestChangesPage.java
index fc97bf3bce..dd549e5954 100644
--- a/gitplex.web/src/main/java/com/pmease/gitplex/web/page/depot/pullrequest/requestdetail/changes/RequestChangesPage.java
+++ b/gitplex.web/src/main/java/com/pmease/gitplex/web/page/depot/pullrequest/requestdetail/changes/RequestChangesPage.java
@@ -1,574 +1,574 @@
-package com.pmease.gitplex.web.page.depot.pullrequest.requestdetail.changes;
-
-import static org.apache.wicket.ajax.attributes.CallbackParameter.explicit;
-
-import java.io.Serializable;
-import java.util.ArrayList;
-import java.util.Collection;
-import java.util.List;
-
-import javax.annotation.Nullable;
-
-import org.apache.wicket.Component;
-import org.apache.wicket.ajax.AbstractDefaultAjaxBehavior;
-import org.apache.wicket.ajax.AjaxRequestTarget;
-import org.apache.wicket.ajax.markup.html.AjaxLink;
-import org.apache.wicket.behavior.AttributeAppender;
-import org.apache.wicket.core.request.handler.IPartialPageRequestHandler;
-import org.apache.wicket.event.IEvent;
-import org.apache.wicket.markup.ComponentTag;
-import org.apache.wicket.markup.head.CssHeaderItem;
-import org.apache.wicket.markup.head.IHeaderResponse;
-import org.apache.wicket.markup.head.JavaScriptHeaderItem;
-import org.apache.wicket.markup.head.OnDomReadyHeaderItem;
-import org.apache.wicket.markup.html.WebMarkupContainer;
-import org.apache.wicket.markup.html.basic.Label;
-import org.apache.wicket.markup.html.list.ListItem;
-import org.apache.wicket.markup.html.list.ListView;
-import org.apache.wicket.markup.html.panel.Fragment;
-import org.apache.wicket.model.AbstractReadOnlyModel;
-import org.apache.wicket.model.IModel;
-import org.apache.wicket.model.LoadableDetachableModel;
-import org.apache.wicket.request.IRequestParameters;
-import org.apache.wicket.request.cycle.RequestCycle;
-import org.apache.wicket.request.mapper.parameter.PageParameters;
-import org.apache.wicket.request.resource.CssResourceReference;
-import org.apache.wicket.request.resource.JavaScriptResourceReference;
-import org.eclipse.jgit.revwalk.RevCommit;
-
-import com.google.common.base.Preconditions;
-import com.pmease.commons.git.GitUtils;
-import com.pmease.commons.lang.diff.WhitespaceOption;
-import com.pmease.commons.wicket.component.DropdownLink;
-import com.pmease.commons.wicket.websocket.WebSocketManager;
-import com.pmease.commons.wicket.websocket.WebSocketRegion;
-import com.pmease.gitplex.core.GitPlex;
-import com.pmease.gitplex.core.entity.CodeComment;
-import com.pmease.gitplex.core.entity.Depot;
-import com.pmease.gitplex.core.entity.PullRequest;
-import com.pmease.gitplex.core.entity.PullRequestUpdate;
-import com.pmease.gitplex.core.entity.support.CodeCommentActivity;
-import com.pmease.gitplex.core.entity.support.CommentPos;
-import com.pmease.gitplex.core.manager.CodeCommentManager;
-import com.pmease.gitplex.web.component.diff.revision.CommentSupport;
-import com.pmease.gitplex.web.component.diff.revision.RevisionDiffPanel;
-import com.pmease.gitplex.web.page.depot.pullrequest.requestdetail.RequestDetailPage;
-import com.pmease.gitplex.web.page.depot.pullrequest.requestlist.RequestListPage;
-import com.pmease.gitplex.web.websocket.CodeCommentChangedRegion;
-import com.pmease.gitplex.web.websocket.PullRequestChanged;
-import com.pmease.gitplex.web.websocket.PullRequestChangedRegion;
-
-@SuppressWarnings("serial")
-public class RequestChangesPage extends RequestDetailPage implements CommentSupport {
-
- private static final String PARAM_OLD_COMMIT = "old-commit";
-
- private static final String PARAM_NEW_COMMIT = "new-commit";
-
- private static final String PARAM_WHITESPACE_OPTION = "whitespace-option";
-
- private static final String PARAM_PATH_FILTER = "path-filter";
-
- private static final String PARAM_BLAME_FILE = "blame-file";
-
- private static final String PARAM_COMMENT = "comment";
-
- private static final String PARAM_MARK = "mark";
-
- private State state = new State();
-
- private WebMarkupContainer head;
-
- private final IModel<List<RevCommit>> commitsModel = new LoadableDetachableModel<List<RevCommit>>() {
-
- @Override
- protected List<RevCommit> load() {
- List<RevCommit> commits = new ArrayList<>();
- for (PullRequestUpdate update: getPullRequest().getSortedUpdates()) {
- commits.addAll(update.getCommits());
- }
- return commits;
- }
-
- };
-
- public RequestChangesPage(PageParameters params) {
- super(params);
-
- state.oldCommit = params.get(PARAM_OLD_COMMIT).toString();
- if (state.oldCommit == null)
- state.oldCommit = getPullRequest().getBaseCommitHash();
- state.newCommit = params.get(PARAM_NEW_COMMIT).toString();
- if (state.newCommit == null)
- state.newCommit = getPullRequest().getLatestUpdate().getHeadCommitHash();
- state.pathFilter = params.get(PARAM_PATH_FILTER).toString();
- state.blameFile = params.get(PARAM_BLAME_FILE).toString();
- state.whitespaceOption = WhitespaceOption.of(params.get(PARAM_WHITESPACE_OPTION).toString());
- state.commentId = params.get(PARAM_COMMENT).toOptionalLong();
- state.mark = CommentPos.of(params.get(PARAM_MARK).toString());
- }
-
- private int getCommitIndex(String commitHash) {
- int index = -1;
- for (int i=0; i<commitsModel.getObject().size(); i++) {
- RevCommit commit = commitsModel.getObject().get(i);
- if (commit.name().equals(commitHash)) {
- index = i;
- break;
- }
- }
- return index;
- }
-
- @Override
- protected void onInitialize() {
- super.onInitialize();
-
- add(head = new WebMarkupContainer("changesHead") {
-
- @Override
- public void onEvent(IEvent<?> event) {
- super.onEvent(event);
-
- if (event.getPayload() instanceof PullRequestChanged) {
- PullRequestChanged pullRequestChanged = (PullRequestChanged) event.getPayload();
- pullRequestChanged.getPartialPageRequestHandler().add(this);
- }
- }
-
- });
- head.setOutputMarkupId(true);
-
- head.add(new AjaxLink<Void>("prevCommitLink") {
-
- @Override
- protected void onComponentTag(ComponentTag tag) {
- super.onComponentTag(tag);
-
- configure();
- if (!isEnabled()) {
- tag.put("disabled", "disabled");
- }
- }
-
- @Override
- protected void onConfigure() {
- super.onConfigure();
- setEnabled(getCommitIndex(state.oldCommit) != -1 && getCommitIndex(state.newCommit) != -1);
- }
-
- @Override
- public void onClick(AjaxRequestTarget target) {
- int index = getCommitIndex(state.oldCommit);
- if (index != -1) {
- state.newCommit = commitsModel.getObject().get(index).name();
- index--;
- if (index == -1) {
- state.oldCommit = getPullRequest().getBaseCommitHash();
- } else {
- state.oldCommit = commitsModel.getObject().get(index).name();
- }
- newRevisionDiff(target);
- }
- target.add(head);
- pushState(target);
- }
-
- });
- head.add(new AjaxLink<Void>("nextCommitLink") {
-
- @Override
- protected void onConfigure() {
- super.onConfigure();
-
- int oldIndex = getCommitIndex(state.oldCommit);
- int newIndex = getCommitIndex(state.newCommit);
- if (!state.oldCommit.equals(getPullRequest().getBaseCommitHash()) && oldIndex == -1
- || newIndex == -1 || newIndex == commitsModel.getObject().size()-1) {
- setEnabled(false);
- } else {
- setEnabled(true);
- }
-
- }
-
- @Override
- protected void onComponentTag(ComponentTag tag) {
- super.onComponentTag(tag);
-
- configure();
- if (!isEnabled()) {
- tag.put("disabled", "disabled");
- }
- }
-
- @Override
- public void onClick(AjaxRequestTarget target) {
- int index = getCommitIndex(state.newCommit);
- if (index != -1 && index != commitsModel.getObject().size()-1) {
- CodeComment comment = getOpenComment();
-
- // we will not move old commit if an opened comment points to it
- if (comment == null || comment.getCommentPos().getCommit().equals(state.newCommit)) {
- state.oldCommit = state.newCommit;
- }
- index++;
- state.newCommit = commitsModel.getObject().get(index).name();
- newRevisionDiff(target);
- }
- target.add(head);
- pushState(target);
- }
-
- });
-
- DropdownLink selectedCommitsLink = new DropdownLink("comparingCommits") {
-
- @Override
- protected Component newContent(String id) {
- AbstractDefaultAjaxBehavior callbackBehavior = new AbstractDefaultAjaxBehavior() {
-
- @Override
- protected void respond(AjaxRequestTarget target) {
- IRequestParameters params = RequestCycle.get().getRequest().getRequestParameters();
- state.oldCommit = params.getParameterValue("oldCommit").toString();
- state.newCommit = params.getParameterValue("newCommit").toString();
- target.add(head);
- newRevisionDiff(target);
- pushState(target);
- close();
- }
-
- };
- Fragment fragment = new Fragment(id, "commitsFrag", RequestChangesPage.this) {
-
- @Override
- public void renderHead(IHeaderResponse response) {
- super.renderHead(response);
-
- String callback = callbackBehavior.getCallbackFunction(explicit("oldCommit"), explicit("newCommit")).toString();
- String script;
- int oldIndex = getCommitIndex(state.oldCommit);
- int newIndex = getCommitIndex(state.newCommit);
- if ((state.oldCommit.equals(getPullRequest().getBaseCommitHash()) || oldIndex != -1)
- && newIndex != -1) {
- script = String.format("gitplex.requestChanges.initCommitSelector(%s, '%s', %d, %d);",
- callback, getPullRequest().getBaseCommitHash(), oldIndex+1, newIndex);
- } else {
- script = String.format("gitplex.requestChanges.initCommitSelector(%s, '%s');",
- callback, getPullRequest().getBaseCommitHash());
- }
- response.render(OnDomReadyHeaderItem.forScript(script));
- }
-
- };
- fragment.add(callbackBehavior);
- fragment.add(new ListView<RevCommit>("commits", commitsModel) {
-
- @Override
- protected void populateItem(ListItem<RevCommit> item) {
- RevCommit commit = item.getModelObject();
- item.add(AttributeAppender.append("data-hash", commit.name()));
- item.add(new Label("hash", GitUtils.abbreviateSHA(commit.name())));
- item.add(new Label("subject", commit.getShortMessage()));
- }
-
- });
- return fragment;
- }
- };
- selectedCommitsLink.add(new Label("label", new AbstractReadOnlyModel<String>() {
-
- @Override
- public String getObject() {
- String oldName;
- if (state.oldCommit.equals(getPullRequest().getBaseCommitHash()))
- oldName = "base";
- else
- oldName = GitUtils.abbreviateSHA(state.oldCommit);
-
- String newName;
- if (state.newCommit.equals(getPullRequest().getLatestUpdate().getHeadCommitHash())) {
- newName = "head";
- } else {
- newName = GitUtils.abbreviateSHA(state.newCommit);
- }
-
- return oldName + " ... " + newName;
- }
-
- }));
-
- head.add(selectedCommitsLink);
-
- head.add(new AjaxLink<Void>("fullChanges") {
-
- @Override
- public void onClick(AjaxRequestTarget target) {
- state.oldCommit = getPullRequest().getBaseCommitHash();
- state.newCommit = getPullRequest().getLatestUpdate().getHeadCommitHash();
- target.add(head);
- newRevisionDiff(target);
- pushState(target);
- }
-
- @Override
- protected void onConfigure() {
- super.onConfigure();
- setVisible(!state.oldCommit.equals(getPullRequest().getBaseCommitHash())
- || !state.newCommit.equals(getPullRequest().getLatestUpdate().getHeadCommitHash()));
- }
-
- });
-
- newRevisionDiff(null);
- }
-
- @Override
- public void onDetach() {
- commitsModel.detach();
- super.onDetach();
- }
-
- public static PageParameters paramsOf(PullRequest request, String oldCommit, String newCommit) {
- State state = new State();
- state.oldCommit = oldCommit;
- state.newCommit = newCommit;
- return paramsOf(request, state);
- }
-
- public static PageParameters paramsOf(PullRequest request, CodeComment comment) {
- PullRequest.ComparingInfo comparingInfo = null;
- for (int i=comment.getActivities().size()-1; i>=0; i--) {
- CodeCommentActivity activity = comment.getActivities().get(i);
- comparingInfo = request.getRequestComparingInfo(activity.getComparingInfo());
- if (comparingInfo != null)
- break;
- }
- if (comparingInfo == null) {
- comparingInfo = Preconditions.checkNotNull(request.getRequestComparingInfo(comment.getComparingInfo()));
- }
- RequestChangesPage.State state = new RequestChangesPage.State();
- state.commentId = comment.getId();
- state.mark = comment.getCommentPos();
- state.oldCommit = comparingInfo.getOldCommit();
- state.newCommit = comparingInfo.getNewCommit();
- state.pathFilter = comparingInfo.getPathFilter();
- state.whitespaceOption = comparingInfo.getWhitespaceOption();
- return paramsOf(request, state);
- }
-
- public static PageParameters paramsOf(PullRequest request, State state) {
- PageParameters params = RequestDetailPage.paramsOf(request);
-
- if (state.oldCommit != null)
- params.set(PARAM_OLD_COMMIT, state.oldCommit);
- if (state.newCommit != null)
- params.set(PARAM_NEW_COMMIT, state.newCommit);
- if (state.whitespaceOption != WhitespaceOption.DEFAULT)
- params.set(PARAM_WHITESPACE_OPTION, state.whitespaceOption.name());
- if (state.pathFilter != null)
- params.set(PARAM_PATH_FILTER, state.pathFilter);
- if (state.blameFile != null)
- params.set(PARAM_BLAME_FILE, state.blameFile);
- if (state.commentId != null)
- params.set(PARAM_COMMENT, state.commentId);
- if (state.mark != null)
- params.set(PARAM_MARK, state.mark.toString());
- return params;
- }
-
- @Override
- protected void onPopState(AjaxRequestTarget target, Serializable data) {
- super.onPopState(target, data);
-
- state = (State) data;
- GitPlex.getInstance(WebSocketManager.class).onRegionChange(this);
-
- newRevisionDiff(target);
- }
-
- @Override
- protected void onSelect(AjaxRequestTarget target, Depot depot) {
- setResponsePage(RequestListPage.class, paramsOf(depot));
- }
-
- private void pushState(IPartialPageRequestHandler partialPageRequestHandler) {
- PageParameters params = paramsOf(getPullRequest(), state);
- CharSequence url = RequestCycle.get().urlFor(RequestChangesPage.class, params);
- pushState(partialPageRequestHandler, url.toString(), state);
- }
-
- private void newRevisionDiff(@Nullable AjaxRequestTarget target) {
- IModel<String> blameModel = new IModel<String>() {
-
- @Override
- public void detach() {
- }
-
- @Override
- public String getObject() {
- return state.blameFile;
- }
-
- @Override
- public void setObject(String object) {
- state.blameFile = object;
- pushState(RequestCycle.get().find(AjaxRequestTarget.class));
- }
-
- };
- IModel<String> pathFilterModel = new IModel<String>() {
-
- @Override
- public void detach() {
- }
-
- @Override
- public String getObject() {
- return state.pathFilter;
- }
-
- @Override
- public void setObject(String object) {
- state.pathFilter = object;
- pushState(RequestCycle.get().find(AjaxRequestTarget.class));
- }
-
- };
- IModel<WhitespaceOption> whitespaceOptionModel = new IModel<WhitespaceOption>() {
-
- @Override
- public void detach() {
- }
-
- @Override
- public WhitespaceOption getObject() {
- return state.whitespaceOption;
- }
-
- @Override
- public void setObject(WhitespaceOption object) {
- state.whitespaceOption = object;
- pushState(RequestCycle.get().find(AjaxRequestTarget.class));
- }
-
- };
-
- Component revisionDiff = new RevisionDiffPanel("revisionDiff", depotModel,
- requestModel, state.oldCommit, state.newCommit, pathFilterModel,
- whitespaceOptionModel, blameModel, this);
- revisionDiff.setOutputMarkupId(true);
- if (target != null) {
- replace(revisionDiff);
- target.add(revisionDiff);
- } else {
- add(revisionDiff);
- }
- }
-
- @Override
- public void renderHead(IHeaderResponse response) {
- super.renderHead(response);
- response.render(JavaScriptHeaderItem.forReference(
- new JavaScriptResourceReference(RequestChangesPage.class, "request-changes.js")));
- response.render(CssHeaderItem.forReference(
- new CssResourceReference(RequestChangesPage.class, "request-changes.css")));
- }
-
- @Override
- public CommentPos getMark() {
- return state.mark;
- }
-
- @Override
- public String getMarkUrl(CommentPos mark) {
- State markState = new State();
- markState.mark = mark;
- markState.oldCommit = state.oldCommit;
- markState.newCommit = state.newCommit;
- markState.pathFilter = state.pathFilter;
- markState.whitespaceOption = state.whitespaceOption;
- return urlFor(RequestChangesPage.class, paramsOf(getPullRequest(), markState)).toString();
- }
-
- @Override
- public String getCommentUrl(CodeComment comment) {
- State commentState = new State();
- commentState.mark = comment.getCommentPos();
- commentState.commentId = comment.getId();
- commentState.oldCommit = state.oldCommit;
- commentState.newCommit = state.newCommit;
- commentState.pathFilter = state.pathFilter;
- commentState.whitespaceOption = state.whitespaceOption;
- return urlFor(RequestChangesPage.class, paramsOf(getPullRequest(), commentState)).toString();
- }
-
- @Override
- public CodeComment getOpenComment() {
- if (state.commentId != null)
- return GitPlex.getInstance(CodeCommentManager.class).load(state.commentId);
- else
- return null;
- }
-
- @Override
- public void onCommentOpened(AjaxRequestTarget target, CodeComment comment) {
- if (comment != null) {
- state.commentId = comment.getId();
- state.mark = comment.getCommentPos();
- } else {
- state.commentId = null;
- }
- GitPlex.getInstance(WebSocketManager.class).onRegionChange(this);
- pushState(target);
- }
-
- @Override
- public void onMark(AjaxRequestTarget target, CommentPos mark) {
- state.mark = mark;
- pushState(target);
- }
-
- @Override
- public void onAddComment(AjaxRequestTarget target, CommentPos mark) {
- state.commentId = null;
- state.mark = mark;
- pushState(target);
- GitPlex.getInstance(WebSocketManager.class).onRegionChange(this);
- }
-
- @Override
- public Collection<WebSocketRegion> getWebSocketRegions() {
- Collection<WebSocketRegion> regions = new ArrayList<>();
- if (state.commentId != null)
- regions.add(new CodeCommentChangedRegion(state.commentId));
- regions.add(new PullRequestChangedRegion(getPullRequest().getId()));
- return regions;
- }
-
- public static class State implements Serializable {
-
- private static final long serialVersionUID = 1L;
-
- public String oldCommit;
-
- public String newCommit;
-
- public WhitespaceOption whitespaceOption = WhitespaceOption.DEFAULT;
-
- @Nullable
- public String pathFilter;
-
- @Nullable
- public String blameFile;
-
- @Nullable
- public Long commentId;
-
- @Nullable
- public CommentPos mark;
-
- }
-
-}
+package com.pmease.gitplex.web.page.depot.pullrequest.requestdetail.changes;
+
+import static org.apache.wicket.ajax.attributes.CallbackParameter.explicit;
+
+import java.io.Serializable;
+import java.util.ArrayList;
+import java.util.Collection;
+import java.util.List;
+
+import javax.annotation.Nullable;
+
+import org.apache.wicket.Component;
+import org.apache.wicket.ajax.AbstractDefaultAjaxBehavior;
+import org.apache.wicket.ajax.AjaxRequestTarget;
+import org.apache.wicket.ajax.markup.html.AjaxLink;
+import org.apache.wicket.behavior.AttributeAppender;
+import org.apache.wicket.core.request.handler.IPartialPageRequestHandler;
+import org.apache.wicket.event.IEvent;
+import org.apache.wicket.markup.ComponentTag;
+import org.apache.wicket.markup.head.CssHeaderItem;
+import org.apache.wicket.markup.head.IHeaderResponse;
+import org.apache.wicket.markup.head.JavaScriptHeaderItem;
+import org.apache.wicket.markup.head.OnDomReadyHeaderItem;
+import org.apache.wicket.markup.html.WebMarkupContainer;
+import org.apache.wicket.markup.html.basic.Label;
+import org.apache.wicket.markup.html.list.ListItem;
+import org.apache.wicket.markup.html.list.ListView;
+import org.apache.wicket.markup.html.panel.Fragment;
+import org.apache.wicket.model.AbstractReadOnlyModel;
+import org.apache.wicket.model.IModel;
+import org.apache.wicket.model.LoadableDetachableModel;
+import org.apache.wicket.request.IRequestParameters;
+import org.apache.wicket.request.cycle.RequestCycle;
+import org.apache.wicket.request.mapper.parameter.PageParameters;
+import org.apache.wicket.request.resource.CssResourceReference;
+import org.apache.wicket.request.resource.JavaScriptResourceReference;
+import org.eclipse.jgit.revwalk.RevCommit;
+
+import com.google.common.base.Preconditions;
+import com.pmease.commons.git.GitUtils;
+import com.pmease.commons.lang.diff.WhitespaceOption;
+import com.pmease.commons.wicket.component.DropdownLink;
+import com.pmease.commons.wicket.websocket.WebSocketManager;
+import com.pmease.commons.wicket.websocket.WebSocketRegion;
+import com.pmease.gitplex.core.GitPlex;
+import com.pmease.gitplex.core.entity.CodeComment;
+import com.pmease.gitplex.core.entity.Depot;
+import com.pmease.gitplex.core.entity.PullRequest;
+import com.pmease.gitplex.core.entity.PullRequestUpdate;
+import com.pmease.gitplex.core.entity.support.CodeCommentActivity;
+import com.pmease.gitplex.core.entity.support.CommentPos;
+import com.pmease.gitplex.core.manager.CodeCommentManager;
+import com.pmease.gitplex.web.component.diff.revision.CommentSupport;
+import com.pmease.gitplex.web.component.diff.revision.RevisionDiffPanel;
+import com.pmease.gitplex.web.page.depot.pullrequest.requestdetail.RequestDetailPage;
+import com.pmease.gitplex.web.page.depot.pullrequest.requestlist.RequestListPage;
+import com.pmease.gitplex.web.websocket.CodeCommentChangedRegion;
+import com.pmease.gitplex.web.websocket.PullRequestChanged;
+import com.pmease.gitplex.web.websocket.PullRequestChangedRegion;
+
+@SuppressWarnings("serial")
+public class RequestChangesPage extends RequestDetailPage implements CommentSupport {
+
+ private static final String PARAM_OLD_COMMIT = "old-commit";
+
+ private static final String PARAM_NEW_COMMIT = "new-commit";
+
+ private static final String PARAM_WHITESPACE_OPTION = "whitespace-option";
+
+ private static final String PARAM_PATH_FILTER = "path-filter";
+
+ private static final String PARAM_BLAME_FILE = "blame-file";
+
+ private static final String PARAM_COMMENT = "comment";
+
+ private static final String PARAM_MARK = "mark";
+
+ private State state = new State();
+
+ private WebMarkupContainer head;
+
+ private final IModel<List<RevCommit>> commitsModel = new LoadableDetachableModel<List<RevCommit>>() {
+
+ @Override
+ protected List<RevCommit> load() {
+ List<RevCommit> commits = new ArrayList<>();
+ for (PullRequestUpdate update: getPullRequest().getSortedUpdates()) {
+ commits.addAll(update.getCommits());
+ }
+ return commits;
+ }
+
+ };
+
+ public RequestChangesPage(PageParameters params) {
+ super(params);
+
+ state.oldCommit = params.get(PARAM_OLD_COMMIT).toString();
+ if (state.oldCommit == null)
+ state.oldCommit = getPullRequest().getBaseCommitHash();
+ state.newCommit = params.get(PARAM_NEW_COMMIT).toString();
+ if (state.newCommit == null)
+ state.newCommit = getPullRequest().getHeadCommitHash();
+ state.pathFilter = params.get(PARAM_PATH_FILTER).toString();
+ state.blameFile = params.get(PARAM_BLAME_FILE).toString();
+ state.whitespaceOption = WhitespaceOption.of(params.get(PARAM_WHITESPACE_OPTION).toString());
+ state.commentId = params.get(PARAM_COMMENT).toOptionalLong();
+ state.mark = CommentPos.of(params.get(PARAM_MARK).toString());
+ }
+
+ private int getCommitIndex(String commitHash) {
+ int index = -1;
+ for (int i=0; i<commitsModel.getObject().size(); i++) {
+ RevCommit commit = commitsModel.getObject().get(i);
+ if (commit.name().equals(commitHash)) {
+ index = i;
+ break;
+ }
+ }
+ return index;
+ }
+
+ @Override
+ protected void onInitialize() {
+ super.onInitialize();
+
+ add(head = new WebMarkupContainer("changesHead") {
+
+ @Override
+ public void onEvent(IEvent<?> event) {
+ super.onEvent(event);
+
+ if (event.getPayload() instanceof PullRequestChanged) {
+ PullRequestChanged pullRequestChanged = (PullRequestChanged) event.getPayload();
+ pullRequestChanged.getPartialPageRequestHandler().add(this);
+ }
+ }
+
+ });
+ head.setOutputMarkupId(true);
+
+ head.add(new AjaxLink<Void>("prevCommitLink") {
+
+ @Override
+ protected void onComponentTag(ComponentTag tag) {
+ super.onComponentTag(tag);
+
+ configure();
+ if (!isEnabled()) {
+ tag.put("disabled", "disabled");
+ }
+ }
+
+ @Override
+ protected void onConfigure() {
+ super.onConfigure();
+ setEnabled(getCommitIndex(state.oldCommit) != -1 && getCommitIndex(state.newCommit) != -1);
+ }
+
+ @Override
+ public void onClick(AjaxRequestTarget target) {
+ int index = getCommitIndex(state.oldCommit);
+ if (index != -1) {
+ state.newCommit = commitsModel.getObject().get(index).name();
+ index--;
+ if (index == -1) {
+ state.oldCommit = getPullRequest().getBaseCommitHash();
+ } else {
+ state.oldCommit = commitsModel.getObject().get(index).name();
+ }
+ newRevisionDiff(target);
+ }
+ target.add(head);
+ pushState(target);
+ }
+
+ });
+ head.add(new AjaxLink<Void>("nextCommitLink") {
+
+ @Override
+ protected void onConfigure() {
+ super.onConfigure();
+
+ int oldIndex = getCommitIndex(state.oldCommit);
+ int newIndex = getCommitIndex(state.newCommit);
+ if (!state.oldCommit.equals(getPullRequest().getBaseCommitHash()) && oldIndex == -1
+ || newIndex == -1 || newIndex == commitsModel.getObject().size()-1) {
+ setEnabled(false);
+ } else {
+ setEnabled(true);
+ }
+
+ }
+
+ @Override
+ protected void onComponentTag(ComponentTag tag) {
+ super.onComponentTag(tag);
+
+ configure();
+ if (!isEnabled()) {
+ tag.put("disabled", "disabled");
+ }
+ }
+
+ @Override
+ public void onClick(AjaxRequestTarget target) {
+ int index = getCommitIndex(state.newCommit);
+ if (index != -1 && index != commitsModel.getObject().size()-1) {
+ CodeComment comment = getOpenComment();
+
+ // we will not move old commit if an opened comment points to it
+ if (comment == null || comment.getCommentPos().getCommit().equals(state.newCommit)) {
+ state.oldCommit = state.newCommit;
+ }
+ index++;
+ state.newCommit = commitsModel.getObject().get(index).name();
+ newRevisionDiff(target);
+ }
+ target.add(head);
+ pushState(target);
+ }
+
+ });
+
+ DropdownLink selectedCommitsLink = new DropdownLink("comparingCommits") {
+
+ @Override
+ protected Component newContent(String id) {
+ AbstractDefaultAjaxBehavior callbackBehavior = new AbstractDefaultAjaxBehavior() {
+
+ @Override
+ protected void respond(AjaxRequestTarget target) {
+ IRequestParameters params = RequestCycle.get().getRequest().getRequestParameters();
+ state.oldCommit = params.getParameterValue("oldCommit").toString();
+ state.newCommit = params.getParameterValue("newCommit").toString();
+ target.add(head);
+ newRevisionDiff(target);
+ pushState(target);
+ close();
+ }
+
+ };
+ Fragment fragment = new Fragment(id, "commitsFrag", RequestChangesPage.this) {
+
+ @Override
+ public void renderHead(IHeaderResponse response) {
+ super.renderHead(response);
+
+ String callback = callbackBehavior.getCallbackFunction(explicit("oldCommit"), explicit("newCommit")).toString();
+ String script;
+ int oldIndex = getCommitIndex(state.oldCommit);
+ int newIndex = getCommitIndex(state.newCommit);
+ if ((state.oldCommit.equals(getPullRequest().getBaseCommitHash()) || oldIndex != -1)
+ && newIndex != -1) {
+ script = String.format("gitplex.requestChanges.initCommitSelector(%s, '%s', %d, %d);",
+ callback, getPullRequest().getBaseCommitHash(), oldIndex+1, newIndex);
+ } else {
+ script = String.format("gitplex.requestChanges.initCommitSelector(%s, '%s');",
+ callback, getPullRequest().getBaseCommitHash());
+ }
+ response.render(OnDomReadyHeaderItem.forScript(script));
+ }
+
+ };
+ fragment.add(callbackBehavior);
+ fragment.add(new ListView<RevCommit>("commits", commitsModel) {
+
+ @Override
+ protected void populateItem(ListItem<RevCommit> item) {
+ RevCommit commit = item.getModelObject();
+ item.add(AttributeAppender.append("data-hash", commit.name()));
+ item.add(new Label("hash", GitUtils.abbreviateSHA(commit.name())));
+ item.add(new Label("subject", commit.getShortMessage()));
+ }
+
+ });
+ return fragment;
+ }
+ };
+ selectedCommitsLink.add(new Label("label", new AbstractReadOnlyModel<String>() {
+
+ @Override
+ public String getObject() {
+ String oldName;
+ if (state.oldCommit.equals(getPullRequest().getBaseCommitHash()))
+ oldName = "base";
+ else
+ oldName = GitUtils.abbreviateSHA(state.oldCommit);
+
+ String newName;
+ if (state.newCommit.equals(getPullRequest().getHeadCommitHash())) {
+ newName = "head";
+ } else {
+ newName = GitUtils.abbreviateSHA(state.newCommit);
+ }
+
+ return oldName + " ... " + newName;
+ }
+
+ }));
+
+ head.add(selectedCommitsLink);
+
+ head.add(new AjaxLink<Void>("fullChanges") {
+
+ @Override
+ public void onClick(AjaxRequestTarget target) {
+ state.oldCommit = getPullRequest().getBaseCommitHash();
+ state.newCommit = getPullRequest().getHeadCommitHash();
+ target.add(head);
+ newRevisionDiff(target);
+ pushState(target);
+ }
+
+ @Override
+ protected void onConfigure() {
+ super.onConfigure();
+ setVisible(!state.oldCommit.equals(getPullRequest().getBaseCommitHash())
+ || !state.newCommit.equals(getPullRequest().getHeadCommitHash()));
+ }
+
+ });
+
+ newRevisionDiff(null);
+ }
+
+ @Override
+ public void onDetach() {
+ commitsModel.detach();
+ super.onDetach();
+ }
+
+ public static PageParameters paramsOf(PullRequest request, String oldCommit, String newCommit) {
+ State state = new State();
+ state.oldCommit = oldCommit;
+ state.newCommit = newCommit;
+ return paramsOf(request, state);
+ }
+
+ public static PageParameters paramsOf(PullRequest request, CodeComment comment) {
+ PullRequest.ComparingInfo comparingInfo = null;
+ for (int i=comment.getActivities().size()-1; i>=0; i--) {
+ CodeCommentActivity activity = comment.getActivities().get(i);
+ comparingInfo = request.getRequestComparingInfo(activity.getComparingInfo());
+ if (comparingInfo != null)
+ break;
+ }
+ if (comparingInfo == null) {
+ comparingInfo = Preconditions.checkNotNull(request.getRequestComparingInfo(comment.getComparingInfo()));
+ }
+ RequestChangesPage.State state = new RequestChangesPage.State();
+ state.commentId = comment.getId();
+ state.mark = comment.getCommentPos();
+ state.oldCommit = comparingInfo.getOldCommit();
+ state.newCommit = comparingInfo.getNewCommit();
+ state.pathFilter = comparingInfo.getPathFilter();
+ state.whitespaceOption = comparingInfo.getWhitespaceOption();
+ return paramsOf(request, state);
+ }
+
+ public static PageParameters paramsOf(PullRequest request, State state) {
+ PageParameters params = RequestDetailPage.paramsOf(request);
+
+ if (state.oldCommit != null)
+ params.set(PARAM_OLD_COMMIT, state.oldCommit);
+ if (state.newCommit != null)
+ params.set(PARAM_NEW_COMMIT, state.newCommit);
+ if (state.whitespaceOption != WhitespaceOption.DEFAULT)
+ params.set(PARAM_WHITESPACE_OPTION, state.whitespaceOption.name());
+ if (state.pathFilter != null)
+ params.set(PARAM_PATH_FILTER, state.pathFilter);
+ if (state.blameFile != null)
+ params.set(PARAM_BLAME_FILE, state.blameFile);
+ if (state.commentId != null)
+ params.set(PARAM_COMMENT, state.commentId);
+ if (state.mark != null)
+ params.set(PARAM_MARK, state.mark.toString());
+ return params;
+ }
+
+ @Override
+ protected void onPopState(AjaxRequestTarget target, Serializable data) {
+ super.onPopState(target, data);
+
+ state = (State) data;
+ GitPlex.getInstance(WebSocketManager.class).onRegionChange(this);
+
+ newRevisionDiff(target);
+ }
+
+ @Override
+ protected void onSelect(AjaxRequestTarget target, Depot depot) {
+ setResponsePage(RequestListPage.class, paramsOf(depot));
+ }
+
+ private void pushState(IPartialPageRequestHandler partialPageRequestHandler) {
+ PageParameters params = paramsOf(getPullRequest(), state);
+ CharSequence url = RequestCycle.get().urlFor(RequestChangesPage.class, params);
+ pushState(partialPageRequestHandler, url.toString(), state);
+ }
+
+ private void newRevisionDiff(@Nullable AjaxRequestTarget target) {
+ IModel<String> blameModel = new IModel<String>() {
+
+ @Override
+ public void detach() {
+ }
+
+ @Override
+ public String getObject() {
+ return state.blameFile;
+ }
+
+ @Override
+ public void setObject(String object) {
+ state.blameFile = object;
+ pushState(RequestCycle.get().find(AjaxRequestTarget.class));
+ }
+
+ };
+ IModel<String> pathFilterModel = new IModel<String>() {
+
+ @Override
+ public void detach() {
+ }
+
+ @Override
+ public String getObject() {
+ return state.pathFilter;
+ }
+
+ @Override
+ public void setObject(String object) {
+ state.pathFilter = object;
+ pushState(RequestCycle.get().find(AjaxRequestTarget.class));
+ }
+
+ };
+ IModel<WhitespaceOption> whitespaceOptionModel = new IModel<WhitespaceOption>() {
+
+ @Override
+ public void detach() {
+ }
+
+ @Override
+ public WhitespaceOption getObject() {
+ return state.whitespaceOption;
+ }
+
+ @Override
+ public void setObject(WhitespaceOption object) {
+ state.whitespaceOption = object;
+ pushState(RequestCycle.get().find(AjaxRequestTarget.class));
+ }
+
+ };
+
+ Component revisionDiff = new RevisionDiffPanel("revisionDiff", depotModel,
+ requestModel, state.oldCommit, state.newCommit, pathFilterModel,
+ whitespaceOptionModel, blameModel, this);
+ revisionDiff.setOutputMarkupId(true);
+ if (target != null) {
+ replace(revisionDiff);
+ target.add(revisionDiff);
+ } else {
+ add(revisionDiff);
+ }
+ }
+
+ @Override
+ public void renderHead(IHeaderResponse response) {
+ super.renderHead(response);
+ response.render(JavaScriptHeaderItem.forReference(
+ new JavaScriptResourceReference(RequestChangesPage.class, "request-changes.js")));
+ response.render(CssHeaderItem.forReference(
+ new CssResourceReference(RequestChangesPage.class, "request-changes.css")));
+ }
+
+ @Override
+ public CommentPos getMark() {
+ return state.mark;
+ }
+
+ @Override
+ public String getMarkUrl(CommentPos mark) {
+ State markState = new State();
+ markState.mark = mark;
+ markState.oldCommit = state.oldCommit;
+ markState.newCommit = state.newCommit;
+ markState.pathFilter = state.pathFilter;
+ markState.whitespaceOption = state.whitespaceOption;
+ return urlFor(RequestChangesPage.class, paramsOf(getPullRequest(), markState)).toString();
+ }
+
+ @Override
+ public String getCommentUrl(CodeComment comment) {
+ State commentState = new State();
+ commentState.mark = comment.getCommentPos();
+ commentState.commentId = comment.getId();
+ commentState.oldCommit = state.oldCommit;
+ commentState.newCommit = state.newCommit;
+ commentState.pathFilter = state.pathFilter;
+ commentState.whitespaceOption = state.whitespaceOption;
+ return urlFor(RequestChangesPage.class, paramsOf(getPullRequest(), commentState)).toString();
+ }
+
+ @Override
+ public CodeComment getOpenComment() {
+ if (state.commentId != null)
+ return GitPlex.getInstance(CodeCommentManager.class).load(state.commentId);
+ else
+ return null;
+ }
+
+ @Override
+ public void onCommentOpened(AjaxRequestTarget target, CodeComment comment) {
+ if (comment != null) {
+ state.commentId = comment.getId();
+ state.mark = comment.getCommentPos();
+ } else {
+ state.commentId = null;
+ }
+ GitPlex.getInstance(WebSocketManager.class).onRegionChange(this);
+ pushState(target);
+ }
+
+ @Override
+ public void onMark(AjaxRequestTarget target, CommentPos mark) {
+ state.mark = mark;
+ pushState(target);
+ }
+
+ @Override
+ public void onAddComment(AjaxRequestTarget target, CommentPos mark) {
+ state.commentId = null;
+ state.mark = mark;
+ pushState(target);
+ GitPlex.getInstance(WebSocketManager.class).onRegionChange(this);
+ }
+
+ @Override
+ public Collection<WebSocketRegion> getWebSocketRegions() {
+ Collection<WebSocketRegion> regions = new ArrayList<>();
+ if (state.commentId != null)
+ regions.add(new CodeCommentChangedRegion(state.commentId));
+ regions.add(new PullRequestChangedRegion(getPullRequest().getId()));
+ return regions;
+ }
+
+ public static class State implements Serializable {
+
+ private static final long serialVersionUID = 1L;
+
+ public String oldCommit;
+
+ public String newCommit;
+
+ public WhitespaceOption whitespaceOption = WhitespaceOption.DEFAULT;
+
+ @Nullable
+ public String pathFilter;
+
+ @Nullable
+ public String blameFile;
+
+ @Nullable
+ public Long commentId;
+
+ @Nullable
+ public CommentPos mark;
+
+ }
+
+}
diff --git a/gitplex.web/src/main/java/com/pmease/gitplex/web/page/depot/pullrequest/requestdetail/overview/SinceChangesLink.java b/gitplex.web/src/main/java/com/pmease/gitplex/web/page/depot/pullrequest/requestdetail/overview/SinceChangesLink.java
index 41607cc568..766244df26 100644
--- a/gitplex.web/src/main/java/com/pmease/gitplex/web/page/depot/pullrequest/requestdetail/overview/SinceChangesLink.java
+++ b/gitplex.web/src/main/java/com/pmease/gitplex/web/page/depot/pullrequest/requestdetail/overview/SinceChangesLink.java
@@ -1,86 +1,86 @@
-package com.pmease.gitplex.web.page.depot.pullrequest.requestdetail.overview;
-
-import java.util.Date;
-
-import org.apache.wicket.core.request.handler.IPartialPageRequestHandler;
-import org.apache.wicket.event.IEvent;
-import org.apache.wicket.markup.html.link.BookmarkablePageLink;
-import org.apache.wicket.model.IModel;
-import org.apache.wicket.model.LoadableDetachableModel;
-import org.apache.wicket.request.mapper.parameter.PageParameters;
-
-import com.pmease.gitplex.core.entity.PullRequest;
-import com.pmease.gitplex.core.entity.PullRequestUpdate;
-import com.pmease.gitplex.web.page.depot.pullrequest.requestdetail.changes.RequestChangesPage;
-import com.pmease.gitplex.web.websocket.PullRequestChanged;
-
-@SuppressWarnings("serial")
-public class SinceChangesLink extends BookmarkablePageLink<Void> {
-
- private final IModel<PullRequest> requestModel;
-
- private final Date sinceDate;
-
- private final IModel<String> oldCommitModel = new LoadableDetachableModel<String>() {
-
- @Override
- protected String load() {
- PullRequest request = requestModel.getObject();
- String commit = request.getBaseCommitHash();
- for (PullRequestUpdate update: request.getSortedUpdates()) {
- if (update.getDate().getTime()<sinceDate.getTime()) {
- commit = update.getHeadCommitHash();
- }
- }
- return commit;
- }
-
- };
-
- public SinceChangesLink(String id, IModel<PullRequest> requestModel, Date sinceDate) {
- super(id, RequestChangesPage.class);
- this.requestModel = requestModel;
- this.sinceDate = sinceDate;
- }
-
- @Override
- public PageParameters getPageParameters() {
- PullRequest request = requestModel.getObject();
- RequestChangesPage.State state = new RequestChangesPage.State();
- state.oldCommit = oldCommitModel.getObject();
- state.newCommit = request.getLatestUpdate().getHeadCommitHash();
- return RequestChangesPage.paramsOf(request, state);
- }
-
- @Override
- public void onEvent(IEvent<?> event) {
- super.onEvent(event);
-
- if (event.getPayload() instanceof PullRequestChanged) {
- PullRequestChanged pullRequestChanged = (PullRequestChanged) event.getPayload();
- IPartialPageRequestHandler partialPageRequestHandler = pullRequestChanged.getPartialPageRequestHandler();
- partialPageRequestHandler.add(this);
- }
- }
-
- @Override
- protected void onInitialize() {
- super.onInitialize();
- setOutputMarkupPlaceholderTag(true);
- }
-
- @Override
- protected void onConfigure() {
- super.onConfigure();
- setVisible(!oldCommitModel.getObject().equals(requestModel.getObject().getLatestUpdate().getHeadCommitHash()));
- }
-
- @Override
- protected void onDetach() {
- requestModel.detach();
- oldCommitModel.detach();
-
- super.onDetach();
- }
-
-}
+package com.pmease.gitplex.web.page.depot.pullrequest.requestdetail.overview;
+
+import java.util.Date;
+
+import org.apache.wicket.core.request.handler.IPartialPageRequestHandler;
+import org.apache.wicket.event.IEvent;
+import org.apache.wicket.markup.html.link.BookmarkablePageLink;
+import org.apache.wicket.model.IModel;
+import org.apache.wicket.model.LoadableDetachableModel;
+import org.apache.wicket.request.mapper.parameter.PageParameters;
+
+import com.pmease.gitplex.core.entity.PullRequest;
+import com.pmease.gitplex.core.entity.PullRequestUpdate;
+import com.pmease.gitplex.web.page.depot.pullrequest.requestdetail.changes.RequestChangesPage;
+import com.pmease.gitplex.web.websocket.PullRequestChanged;
+
+@SuppressWarnings("serial")
+public class SinceChangesLink extends BookmarkablePageLink<Void> {
+
+ private final IModel<PullRequest> requestModel;
+
+ private final Date sinceDate;
+
+ private final IModel<String> oldCommitModel = new LoadableDetachableModel<String>() {
+
+ @Override
+ protected String load() {
+ PullRequest request = requestModel.getObject();
+ String commit = request.getBaseCommitHash();
+ for (PullRequestUpdate update: request.getSortedUpdates()) {
+ if (update.getDate().getTime()<sinceDate.getTime()) {
+ commit = update.getHeadCommitHash();
+ }
+ }
+ return commit;
+ }
+
+ };
+
+ public SinceChangesLink(String id, IModel<PullRequest> requestModel, Date sinceDate) {
+ super(id, RequestChangesPage.class);
+ this.requestModel = requestModel;
+ this.sinceDate = sinceDate;
+ }
+
+ @Override
+ public PageParameters getPageParameters() {
+ PullRequest request = requestModel.getObject();
+ RequestChangesPage.State state = new RequestChangesPage.State();
+ state.oldCommit = oldCommitModel.getObject();
+ state.newCommit = request.getHeadCommitHash();
+ return RequestChangesPage.paramsOf(request, state);
+ }
+
+ @Override
+ public void onEvent(IEvent<?> event) {
+ super.onEvent(event);
+
+ if (event.getPayload() instanceof PullRequestChanged) {
+ PullRequestChanged pullRequestChanged = (PullRequestChanged) event.getPayload();
+ IPartialPageRequestHandler partialPageRequestHandler = pullRequestChanged.getPartialPageRequestHandler();
+ partialPageRequestHandler.add(this);
+ }
+ }
+
+ @Override
+ protected void onInitialize() {
+ super.onInitialize();
+ setOutputMarkupPlaceholderTag(true);
+ }
+
+ @Override
+ protected void onConfigure() {
+ super.onConfigure();
+ setVisible(!oldCommitModel.getObject().equals(requestModel.getObject().getHeadCommitHash()));
+ }
+
+ @Override
+ protected void onDetach() {
+ requestModel.detach();
+ oldCommitModel.detach();
+
+ super.onDetach();
+ }
+
+}
diff --git a/gitplex.web/src/main/java/com/pmease/gitplex/web/page/depot/pullrequest/requestdetail/overview/activity/CommentedPanel.java b/gitplex.web/src/main/java/com/pmease/gitplex/web/page/depot/pullrequest/requestdetail/overview/activity/CommentedPanel.java
index b685b320ac..fbab9b45b1 100644
--- a/gitplex.web/src/main/java/com/pmease/gitplex/web/page/depot/pullrequest/requestdetail/overview/activity/CommentedPanel.java
+++ b/gitplex.web/src/main/java/com/pmease/gitplex/web/page/depot/pullrequest/requestdetail/overview/activity/CommentedPanel.java
@@ -1,207 +1,207 @@
-package com.pmease.gitplex.web.page.depot.pullrequest.requestdetail.overview.activity;
-
-import org.apache.wicket.Component;
-import org.apache.wicket.ajax.AjaxRequestTarget;
-import org.apache.wicket.ajax.attributes.AjaxRequestAttributes;
-import org.apache.wicket.ajax.markup.html.AjaxLink;
-import org.apache.wicket.ajax.markup.html.form.AjaxSubmitLink;
-import org.apache.wicket.event.Broadcast;
-import org.apache.wicket.markup.html.WebMarkupContainer;
-import org.apache.wicket.markup.html.basic.Label;
-import org.apache.wicket.markup.html.form.Form;
-import org.apache.wicket.markup.html.panel.Fragment;
-import org.apache.wicket.markup.html.panel.GenericPanel;
-import org.apache.wicket.model.AbstractReadOnlyModel;
-import org.apache.wicket.model.IModel;
-import org.apache.wicket.model.Model;
-import org.hibernate.StaleObjectStateException;
-
-import com.pmease.commons.wicket.ajaxlistener.ConfirmLeaveListener;
-import com.pmease.commons.wicket.ajaxlistener.ConfirmListener;
-import com.pmease.commons.wicket.behavior.markdown.AttachmentSupport;
-import com.pmease.commons.wicket.component.markdown.MarkdownEditSupport;
-import com.pmease.commons.wicket.component.markdown.MarkdownPanel;
-import com.pmease.gitplex.core.GitPlex;
-import com.pmease.gitplex.core.entity.Depot;
-import com.pmease.gitplex.core.entity.PullRequest;
-import com.pmease.gitplex.core.entity.PullRequestComment;
-import com.pmease.gitplex.core.manager.PullRequestCommentManager;
-import com.pmease.gitplex.core.security.SecurityUtils;
-import com.pmease.gitplex.web.component.AccountLink;
-import com.pmease.gitplex.web.component.comment.CommentInput;
-import com.pmease.gitplex.web.component.comment.DepotAttachmentSupport;
-import com.pmease.gitplex.web.page.depot.pullrequest.requestdetail.overview.SinceChangesLink;
-import com.pmease.gitplex.web.util.DateUtils;
-
-import de.agilecoders.wicket.core.markup.html.bootstrap.common.NotificationPanel;
-
-@SuppressWarnings("serial")
-class CommentedPanel extends GenericPanel<PullRequestComment> {
-
- public CommentedPanel(String id, IModel<PullRequestComment> model) {
- super(id, model);
- }
-
- @Override
- protected void onInitialize() {
- super.onInitialize();
-
- add(new AccountLink("user", getComment().getUser()));
- add(new Label("age", DateUtils.formatAge(getComment().getDate())));
-
- add(new SinceChangesLink("changes", new AbstractReadOnlyModel<PullRequest>() {
-
- @Override
- public PullRequest getObject() {
- return getComment().getRequest();
- }
-
- }, getComment().getDate()));
-
- add(newViewer());
-
- setOutputMarkupId(true);
- }
-
- private Component newViewer() {
- Fragment viewer = new Fragment("body", "viewFrag", this);
-
- MarkdownEditSupport editSupport;
- if (SecurityUtils.canModify(getComment())) {
- editSupport = new MarkdownEditSupport() {
-
- @Override
- public void setContent(String content) {
- getComment().setContent(content);
- GitPlex.getInstance(PullRequestCommentManager.class).save(getComment());
- }
-
- @Override
- public long getVersion() {
- return getComment().getVersion();
- }
-
- };
- } else {
- editSupport = null;
- }
- viewer.add(new MarkdownPanel("content", new AbstractReadOnlyModel<String>() {
-
- @Override
- public String getObject() {
- return getComment().getContent();
- }
-
- }, editSupport));
-
- WebMarkupContainer actions = new WebMarkupContainer("actions");
- actions.setVisible(SecurityUtils.canModify(getComment()));
-
- actions.add(new AjaxLink<Void>("edit") {
-
- @Override
- public void onClick(AjaxRequestTarget target) {
- Fragment editor = new Fragment("body", "editFrag", CommentedPanel.this);
-
- Form<?> form = new Form<Void>("form");
- form.setOutputMarkupId(true);
- editor.add(form);
- NotificationPanel feedback = new NotificationPanel("feedback", form);
- feedback.setOutputMarkupPlaceholderTag(true);
- form.add(feedback);
- CommentInput input = new CommentInput("input", Model.of(getComment().getContent())) {
-
- @Override
- protected AttachmentSupport getAttachmentSupport() {
- return new DepotAttachmentSupport(getDepot(), getComment().getRequest().getUUID());
- }
-
- @Override
- protected Depot getDepot() {
- return getComment().getDepot();
- }
-
- };
- input.setRequired(true);
- form.add(input);
-
- final long lastVersion = getComment().getVersion();
- form.add(new AjaxSubmitLink("save") {
-
- @Override
- protected void onSubmit(AjaxRequestTarget target, Form<?> form) {
- PullRequestComment comment = getComment();
- try {
- if (comment.getVersion() != lastVersion)
- throw new StaleObjectStateException(PullRequestComment.class.getName(), comment.getId());
- comment.setContent(input.getModelObject());
- GitPlex.getInstance(PullRequestCommentManager.class).save(comment);
-
- Component viewer = newViewer();
- editor.replaceWith(viewer);
- target.add(viewer);
- } catch (StaleObjectStateException e) {
- error("Some one changed the content you are editing. Reload the page and try again.");
- target.add(feedback);
- }
- }
-
- @Override
- protected void onError(AjaxRequestTarget target, Form<?> form) {
- super.onError(target, form);
- target.add(feedback);
- }
-
- });
-
- form.add(new AjaxLink<Void>("cancel") {
-
- @Override
- protected void updateAjaxAttributes(AjaxRequestAttributes attributes) {
- super.updateAjaxAttributes(attributes);
- attributes.getAjaxCallListeners().add(new ConfirmLeaveListener(form));
- }
-
- @Override
- public void onClick(AjaxRequestTarget target) {
- Component viewer = newViewer();
- editor.replaceWith(viewer);
- target.add(viewer);
- }
-
- });
-
- editor.setOutputMarkupId(true);
- viewer.replaceWith(editor);
- target.add(editor);
- }
-
- });
-
- actions.add(new AjaxLink<Void>("delete") {
-
- @Override
- public void onClick(AjaxRequestTarget target) {
- GitPlex.getInstance(PullRequestCommentManager.class).delete(getComment());
- send(CommentedPanel.this, Broadcast.BUBBLE, new CommentRemoved(target, getComment()));
- }
-
- @Override
- protected void updateAjaxAttributes(AjaxRequestAttributes attributes) {
- super.updateAjaxAttributes(attributes);
- attributes.getAjaxCallListeners().add(new ConfirmListener("Do you really want to delete this comment?"));
- }
-
- });
-
- viewer.add(actions);
- viewer.setOutputMarkupId(true);
-
- return viewer;
- }
-
- private PullRequestComment getComment() {
- return getModelObject();
- }
-
-}
+package com.pmease.gitplex.web.page.depot.pullrequest.requestdetail.overview.activity;
+
+import org.apache.wicket.Component;
+import org.apache.wicket.ajax.AjaxRequestTarget;
+import org.apache.wicket.ajax.attributes.AjaxRequestAttributes;
+import org.apache.wicket.ajax.markup.html.AjaxLink;
+import org.apache.wicket.ajax.markup.html.form.AjaxSubmitLink;
+import org.apache.wicket.event.Broadcast;
+import org.apache.wicket.markup.html.WebMarkupContainer;
+import org.apache.wicket.markup.html.basic.Label;
+import org.apache.wicket.markup.html.form.Form;
+import org.apache.wicket.markup.html.panel.Fragment;
+import org.apache.wicket.markup.html.panel.GenericPanel;
+import org.apache.wicket.model.AbstractReadOnlyModel;
+import org.apache.wicket.model.IModel;
+import org.apache.wicket.model.Model;
+import org.hibernate.StaleStateException;
+
+import com.pmease.commons.wicket.ajaxlistener.ConfirmLeaveListener;
+import com.pmease.commons.wicket.ajaxlistener.ConfirmListener;
+import com.pmease.commons.wicket.behavior.markdown.AttachmentSupport;
+import com.pmease.commons.wicket.component.markdown.MarkdownEditSupport;
+import com.pmease.commons.wicket.component.markdown.MarkdownPanel;
+import com.pmease.gitplex.core.GitPlex;
+import com.pmease.gitplex.core.entity.Depot;
+import com.pmease.gitplex.core.entity.PullRequest;
+import com.pmease.gitplex.core.entity.PullRequestComment;
+import com.pmease.gitplex.core.manager.PullRequestCommentManager;
+import com.pmease.gitplex.core.security.SecurityUtils;
+import com.pmease.gitplex.web.component.AccountLink;
+import com.pmease.gitplex.web.component.comment.CommentInput;
+import com.pmease.gitplex.web.component.comment.DepotAttachmentSupport;
+import com.pmease.gitplex.web.page.depot.pullrequest.requestdetail.overview.SinceChangesLink;
+import com.pmease.gitplex.web.util.DateUtils;
+
+import de.agilecoders.wicket.core.markup.html.bootstrap.common.NotificationPanel;
+
+@SuppressWarnings("serial")
+class CommentedPanel extends GenericPanel<PullRequestComment> {
+
+ public CommentedPanel(String id, IModel<PullRequestComment> model) {
+ super(id, model);
+ }
+
+ @Override
+ protected void onInitialize() {
+ super.onInitialize();
+
+ add(new AccountLink("user", getComment().getUser()));
+ add(new Label("age", DateUtils.formatAge(getComment().getDate())));
+
+ add(new SinceChangesLink("changes", new AbstractReadOnlyModel<PullRequest>() {
+
+ @Override
+ public PullRequest getObject() {
+ return getComment().getRequest();
+ }
+
+ }, getComment().getDate()));
+
+ add(newViewer());
+
+ setOutputMarkupId(true);
+ }
+
+ private Component newViewer() {
+ Fragment viewer = new Fragment("body", "viewFrag", this);
+
+ MarkdownEditSupport editSupport;
+ if (SecurityUtils.canModify(getComment())) {
+ editSupport = new MarkdownEditSupport() {
+
+ @Override
+ public void setContent(String content) {
+ getComment().setContent(content);
+ GitPlex.getInstance(PullRequestCommentManager.class).save(getComment());
+ }
+
+ @Override
+ public long getVersion() {
+ return getComment().getVersion();
+ }
+
+ };
+ } else {
+ editSupport = null;
+ }
+ viewer.add(new MarkdownPanel("content", new AbstractReadOnlyModel<String>() {
+
+ @Override
+ public String getObject() {
+ return getComment().getContent();
+ }
+
+ }, editSupport));
+
+ WebMarkupContainer actions = new WebMarkupContainer("actions");
+ actions.setVisible(SecurityUtils.canModify(getComment()));
+
+ actions.add(new AjaxLink<Void>("edit") {
+
+ @Override
+ public void onClick(AjaxRequestTarget target) {
+ Fragment editor = new Fragment("body", "editFrag", CommentedPanel.this);
+
+ Form<?> form = new Form<Void>("form");
+ form.setOutputMarkupId(true);
+ editor.add(form);
+ NotificationPanel feedback = new NotificationPanel("feedback", form);
+ feedback.setOutputMarkupPlaceholderTag(true);
+ form.add(feedback);
+ CommentInput input = new CommentInput("input", Model.of(getComment().getContent())) {
+
+ @Override
+ protected AttachmentSupport getAttachmentSupport() {
+ return new DepotAttachmentSupport(getDepot(), getComment().getRequest().getUUID());
+ }
+
+ @Override
+ protected Depot getDepot() {
+ return getComment().getDepot();
+ }
+
+ };
+ input.setRequired(true);
+ form.add(input);
+
+ final long lastVersion = getComment().getVersion();
+ form.add(new AjaxSubmitLink("save") {
+
+ @Override
+ protected void onSubmit(AjaxRequestTarget target, Form<?> form) {
+ PullRequestComment comment = getComment();
+ try {
+ if (comment.getVersion() != lastVersion)
+ throw new StaleStateException("");
+ comment.setContent(input.getModelObject());
+ GitPlex.getInstance(PullRequestCommentManager.class).save(comment);
+
+ Component viewer = newViewer();
+ editor.replaceWith(viewer);
+ target.add(viewer);
+ } catch (StaleStateException e) {
+ error("Some one changed the content you are editing. Reload the page and try again.");
+ target.add(feedback);
+ }
+ }
+
+ @Override
+ protected void onError(AjaxRequestTarget target, Form<?> form) {
+ super.onError(target, form);
+ target.add(feedback);
+ }
+
+ });
+
+ form.add(new AjaxLink<Void>("cancel") {
+
+ @Override
+ protected void updateAjaxAttributes(AjaxRequestAttributes attributes) {
+ super.updateAjaxAttributes(attributes);
+ attributes.getAjaxCallListeners().add(new ConfirmLeaveListener(form));
+ }
+
+ @Override
+ public void onClick(AjaxRequestTarget target) {
+ Component viewer = newViewer();
+ editor.replaceWith(viewer);
+ target.add(viewer);
+ }
+
+ });
+
+ editor.setOutputMarkupId(true);
+ viewer.replaceWith(editor);
+ target.add(editor);
+ }
+
+ });
+
+ actions.add(new AjaxLink<Void>("delete") {
+
+ @Override
+ public void onClick(AjaxRequestTarget target) {
+ GitPlex.getInstance(PullRequestCommentManager.class).delete(getComment());
+ send(CommentedPanel.this, Broadcast.BUBBLE, new CommentRemoved(target, getComment()));
+ }
+
+ @Override
+ protected void updateAjaxAttributes(AjaxRequestAttributes attributes) {
+ super.updateAjaxAttributes(attributes);
+ attributes.getAjaxCallListeners().add(new ConfirmListener("Do you really want to delete this comment?"));
+ }
+
+ });
+
+ viewer.add(actions);
+ viewer.setOutputMarkupId(true);
+
+ return viewer;
+ }
+
+ private PullRequestComment getComment() {
+ return getModelObject();
+ }
+
+}
diff --git a/gitplex.web/src/main/java/com/pmease/gitplex/web/page/depot/pullrequest/requestdetail/overview/activity/OpenedPanel.java b/gitplex.web/src/main/java/com/pmease/gitplex/web/page/depot/pullrequest/requestdetail/overview/activity/OpenedPanel.java
index 61c89f744c..c5ee58c421 100644
--- a/gitplex.web/src/main/java/com/pmease/gitplex/web/page/depot/pullrequest/requestdetail/overview/activity/OpenedPanel.java
+++ b/gitplex.web/src/main/java/com/pmease/gitplex/web/page/depot/pullrequest/requestdetail/overview/activity/OpenedPanel.java
@@ -1,183 +1,183 @@
-package com.pmease.gitplex.web.page.depot.pullrequest.requestdetail.overview.activity;
-
-import org.apache.commons.lang3.StringUtils;
-import org.apache.wicket.Component;
-import org.apache.wicket.ajax.AjaxRequestTarget;
-import org.apache.wicket.ajax.attributes.AjaxRequestAttributes;
-import org.apache.wicket.ajax.markup.html.AjaxLink;
-import org.apache.wicket.ajax.markup.html.form.AjaxButton;
-import org.apache.wicket.markup.html.WebMarkupContainer;
-import org.apache.wicket.markup.html.basic.Label;
-import org.apache.wicket.markup.html.form.Form;
-import org.apache.wicket.markup.html.panel.Fragment;
-import org.apache.wicket.markup.html.panel.GenericPanel;
-import org.apache.wicket.model.AbstractReadOnlyModel;
-import org.apache.wicket.model.IModel;
-import org.apache.wicket.model.Model;
-import org.hibernate.StaleObjectStateException;
-
-import com.pmease.commons.hibernate.dao.Dao;
-import com.pmease.commons.wicket.ajaxlistener.ConfirmLeaveListener;
-import com.pmease.commons.wicket.behavior.markdown.AttachmentSupport;
-import com.pmease.commons.wicket.component.markdown.MarkdownEditSupport;
-import com.pmease.commons.wicket.component.markdown.MarkdownPanel;
-import com.pmease.gitplex.core.GitPlex;
-import com.pmease.gitplex.core.entity.Depot;
-import com.pmease.gitplex.core.entity.PullRequest;
-import com.pmease.gitplex.core.manager.PullRequestManager;
-import com.pmease.gitplex.core.security.SecurityUtils;
-import com.pmease.gitplex.web.component.AccountLink;
-import com.pmease.gitplex.web.component.comment.CommentInput;
-import com.pmease.gitplex.web.component.comment.DepotAttachmentSupport;
-import com.pmease.gitplex.web.util.DateUtils;
-
-import de.agilecoders.wicket.core.markup.html.bootstrap.common.NotificationPanel;
-
-@SuppressWarnings("serial")
-class OpenedPanel extends GenericPanel<PullRequest> {
-
- public OpenedPanel(String id, IModel<PullRequest> model) {
- super(id, model);
- }
-
- private Component newViewer() {
- Fragment viewer = new Fragment("body", "viewFrag", this);
-
- String description = getPullRequest().getDescription();
- if (StringUtils.isNotBlank(description)) {
- MarkdownEditSupport editSupport;
- if (SecurityUtils.canModify(getPullRequest())) {
- editSupport = new MarkdownEditSupport() {
-
- @Override
- public void setContent(String content) {
- getPullRequest().setDescription(content);
- GitPlex.getInstance(PullRequestManager.class).save(getPullRequest());
- }
-
- @Override
- public long getVersion() {
- return getPullRequest().getVersion();
- }
-
- };
- } else {
- editSupport = null;
- }
- viewer.add(new MarkdownPanel("content", new AbstractReadOnlyModel<String>() {
-
- @Override
- public String getObject() {
- return getPullRequest().getDescription();
- }
-
- }, editSupport));
- } else {
- viewer.add(new Label("content", "<i>No description</i>").setEscapeModelStrings(false));
- }
-
- WebMarkupContainer actions = new WebMarkupContainer("actions");
- actions.setVisible(SecurityUtils.canModify(getPullRequest()));
- actions.add(new AjaxLink<Void>("edit") {
-
- @Override
- public void onClick(AjaxRequestTarget target) {
- Fragment editor = new Fragment("body", "editFrag", OpenedPanel.this);
-
- Form<?> form = new Form<Void>("form");
- form.setOutputMarkupId(true);
- editor.add(form);
-
- NotificationPanel feedback = new NotificationPanel("feedback", form);
- feedback.setOutputMarkupPlaceholderTag(true);
- form.add(feedback);
-
- long lastVersion = getPullRequest().getVersion();
- CommentInput input = new CommentInput("input", Model.of(getPullRequest().getDescription())) {
-
- @Override
- protected AttachmentSupport getAttachmentSupport() {
- return new DepotAttachmentSupport(getPullRequest().getTargetDepot(),
- getPullRequest().getUUID());
- }
-
- @Override
- protected Depot getDepot() {
- return getPullRequest().getTargetDepot();
- }
-
- };
- form.add(input);
-
- form.add(new AjaxButton("save") {
-
- @Override
- protected void onError(AjaxRequestTarget target, Form<?> form) {
- super.onError(target, form);
- target.add(feedback);
- }
-
- @Override
- protected void onSubmit(AjaxRequestTarget target, Form<?> form) {
- try {
- if (getPullRequest().getVersion() != lastVersion)
- throw new StaleObjectStateException(PullRequest.class.getName(), getPullRequest().getId());
- getPullRequest().setDescription(input.getModelObject());
- GitPlex.getInstance(Dao.class).persist(getPullRequest());
-
- Component viewer = newViewer();
- editor.replaceWith(viewer);
- target.add(viewer);
- } catch (StaleObjectStateException e) {
- error("Some one changed the content you are editing. Reload the page and try again.");
- target.add(feedback);
- }
- }
-
- });
-
- form.add(new AjaxLink<Void>("cancel") {
-
- @Override
- protected void updateAjaxAttributes(AjaxRequestAttributes attributes) {
- super.updateAjaxAttributes(attributes);
- attributes.getAjaxCallListeners().add(new ConfirmLeaveListener(form));
- }
-
- @Override
- public void onClick(AjaxRequestTarget target) {
- Component viewer = newViewer();
- editor.replaceWith(viewer);
- target.add(viewer);
- }
-
- });
-
- editor.setOutputMarkupId(true);
- viewer.replaceWith(editor);
- target.add(editor);
- }
-
- });
-
- viewer.add(actions);
-
- viewer.setOutputMarkupId(true);
- return viewer;
- }
-
- @Override
- protected void onInitialize() {
- super.onInitialize();
-
- add(new AccountLink("user", getPullRequest().getSubmitter()));
- add(new Label("age", DateUtils.formatAge(getPullRequest().getSubmitDate())));
-
- add(newViewer());
- }
-
- private PullRequest getPullRequest() {
- return getModelObject();
- }
-
-}
+package com.pmease.gitplex.web.page.depot.pullrequest.requestdetail.overview.activity;
+
+import org.apache.commons.lang3.StringUtils;
+import org.apache.wicket.Component;
+import org.apache.wicket.ajax.AjaxRequestTarget;
+import org.apache.wicket.ajax.attributes.AjaxRequestAttributes;
+import org.apache.wicket.ajax.markup.html.AjaxLink;
+import org.apache.wicket.ajax.markup.html.form.AjaxButton;
+import org.apache.wicket.markup.html.WebMarkupContainer;
+import org.apache.wicket.markup.html.basic.Label;
+import org.apache.wicket.markup.html.form.Form;
+import org.apache.wicket.markup.html.panel.Fragment;
+import org.apache.wicket.markup.html.panel.GenericPanel;
+import org.apache.wicket.model.AbstractReadOnlyModel;
+import org.apache.wicket.model.IModel;
+import org.apache.wicket.model.Model;
+import org.hibernate.StaleStateException;
+
+import com.pmease.commons.hibernate.dao.Dao;
+import com.pmease.commons.wicket.ajaxlistener.ConfirmLeaveListener;
+import com.pmease.commons.wicket.behavior.markdown.AttachmentSupport;
+import com.pmease.commons.wicket.component.markdown.MarkdownEditSupport;
+import com.pmease.commons.wicket.component.markdown.MarkdownPanel;
+import com.pmease.gitplex.core.GitPlex;
+import com.pmease.gitplex.core.entity.Depot;
+import com.pmease.gitplex.core.entity.PullRequest;
+import com.pmease.gitplex.core.manager.PullRequestManager;
+import com.pmease.gitplex.core.security.SecurityUtils;
+import com.pmease.gitplex.web.component.AccountLink;
+import com.pmease.gitplex.web.component.comment.CommentInput;
+import com.pmease.gitplex.web.component.comment.DepotAttachmentSupport;
+import com.pmease.gitplex.web.util.DateUtils;
+
+import de.agilecoders.wicket.core.markup.html.bootstrap.common.NotificationPanel;
+
+@SuppressWarnings("serial")
+class OpenedPanel extends GenericPanel<PullRequest> {
+
+ public OpenedPanel(String id, IModel<PullRequest> model) {
+ super(id, model);
+ }
+
+ private Component newViewer() {
+ Fragment viewer = new Fragment("body", "viewFrag", this);
+
+ String description = getPullRequest().getDescription();
+ if (StringUtils.isNotBlank(description)) {
+ MarkdownEditSupport editSupport;
+ if (SecurityUtils.canModify(getPullRequest())) {
+ editSupport = new MarkdownEditSupport() {
+
+ @Override
+ public void setContent(String content) {
+ getPullRequest().setDescription(content);
+ GitPlex.getInstance(PullRequestManager.class).save(getPullRequest());
+ }
+
+ @Override
+ public long getVersion() {
+ return getPullRequest().getVersion();
+ }
+
+ };
+ } else {
+ editSupport = null;
+ }
+ viewer.add(new MarkdownPanel("content", new AbstractReadOnlyModel<String>() {
+
+ @Override
+ public String getObject() {
+ return getPullRequest().getDescription();
+ }
+
+ }, editSupport));
+ } else {
+ viewer.add(new Label("content", "<i>No description</i>").setEscapeModelStrings(false));
+ }
+
+ WebMarkupContainer actions = new WebMarkupContainer("actions");
+ actions.setVisible(SecurityUtils.canModify(getPullRequest()));
+ actions.add(new AjaxLink<Void>("edit") {
+
+ @Override
+ public void onClick(AjaxRequestTarget target) {
+ Fragment editor = new Fragment("body", "editFrag", OpenedPanel.this);
+
+ Form<?> form = new Form<Void>("form");
+ form.setOutputMarkupId(true);
+ editor.add(form);
+
+ NotificationPanel feedback = new NotificationPanel("feedback", form);
+ feedback.setOutputMarkupPlaceholderTag(true);
+ form.add(feedback);
+
+ long lastVersion = getPullRequest().getVersion();
+ CommentInput input = new CommentInput("input", Model.of(getPullRequest().getDescription())) {
+
+ @Override
+ protected AttachmentSupport getAttachmentSupport() {
+ return new DepotAttachmentSupport(getPullRequest().getTargetDepot(),
+ getPullRequest().getUUID());
+ }
+
+ @Override
+ protected Depot getDepot() {
+ return getPullRequest().getTargetDepot();
+ }
+
+ };
+ form.add(input);
+
+ form.add(new AjaxButton("save") {
+
+ @Override
+ protected void onError(AjaxRequestTarget target, Form<?> form) {
+ super.onError(target, form);
+ target.add(feedback);
+ }
+
+ @Override
+ protected void onSubmit(AjaxRequestTarget target, Form<?> form) {
+ try {
+ if (getPullRequest().getVersion() != lastVersion)
+ throw new StaleStateException("");
+ getPullRequest().setDescription(input.getModelObject());
+ GitPlex.getInstance(Dao.class).persist(getPullRequest());
+
+ Component viewer = newViewer();
+ editor.replaceWith(viewer);
+ target.add(viewer);
+ } catch (StaleStateException e) {
+ error("Some one changed the content you are editing. Reload the page and try again.");
+ target.add(feedback);
+ }
+ }
+
+ });
+
+ form.add(new AjaxLink<Void>("cancel") {
+
+ @Override
+ protected void updateAjaxAttributes(AjaxRequestAttributes attributes) {
+ super.updateAjaxAttributes(attributes);
+ attributes.getAjaxCallListeners().add(new ConfirmLeaveListener(form));
+ }
+
+ @Override
+ public void onClick(AjaxRequestTarget target) {
+ Component viewer = newViewer();
+ editor.replaceWith(viewer);
+ target.add(viewer);
+ }
+
+ });
+
+ editor.setOutputMarkupId(true);
+ viewer.replaceWith(editor);
+ target.add(editor);
+ }
+
+ });
+
+ viewer.add(actions);
+
+ viewer.setOutputMarkupId(true);
+ return viewer;
+ }
+
+ @Override
+ protected void onInitialize() {
+ super.onInitialize();
+
+ add(new AccountLink("user", getPullRequest().getSubmitter()));
+ add(new Label("age", DateUtils.formatAge(getPullRequest().getSubmitDate())));
+
+ add(newViewer());
+ }
+
+ private PullRequest getPullRequest() {
+ return getModelObject();
+ }
+
+}
diff --git a/gitplex.web/src/main/java/com/pmease/gitplex/web/page/depot/pullrequest/requestdetail/overview/activity/StatusChangePanel.java b/gitplex.web/src/main/java/com/pmease/gitplex/web/page/depot/pullrequest/requestdetail/overview/activity/StatusChangePanel.java
index 711378649d..46efcd10f5 100644
--- a/gitplex.web/src/main/java/com/pmease/gitplex/web/page/depot/pullrequest/requestdetail/overview/activity/StatusChangePanel.java
+++ b/gitplex.web/src/main/java/com/pmease/gitplex/web/page/depot/pullrequest/requestdetail/overview/activity/StatusChangePanel.java
@@ -1,211 +1,211 @@
-package com.pmease.gitplex.web.page.depot.pullrequest.requestdetail.overview.activity;
-
-import org.apache.commons.lang3.StringUtils;
-import org.apache.wicket.Component;
-import org.apache.wicket.ajax.AjaxRequestTarget;
-import org.apache.wicket.ajax.attributes.AjaxRequestAttributes;
-import org.apache.wicket.ajax.markup.html.AjaxLink;
-import org.apache.wicket.ajax.markup.html.form.AjaxButton;
-import org.apache.wicket.behavior.AttributeAppender;
-import org.apache.wicket.markup.html.WebMarkupContainer;
-import org.apache.wicket.markup.html.basic.Label;
-import org.apache.wicket.markup.html.form.Form;
-import org.apache.wicket.markup.html.panel.Fragment;
-import org.apache.wicket.markup.html.panel.GenericPanel;
-import org.apache.wicket.model.AbstractReadOnlyModel;
-import org.apache.wicket.model.IModel;
-import org.apache.wicket.model.LoadableDetachableModel;
-import org.apache.wicket.model.Model;
-import org.hibernate.StaleObjectStateException;
-
-import com.pmease.commons.wicket.ajaxlistener.ConfirmLeaveListener;
-import com.pmease.commons.wicket.behavior.markdown.AttachmentSupport;
-import com.pmease.commons.wicket.component.markdown.MarkdownEditSupport;
-import com.pmease.commons.wicket.component.markdown.MarkdownPanel;
-import com.pmease.commons.wicket.editable.EditableUtils;
-import com.pmease.gitplex.core.GitPlex;
-import com.pmease.gitplex.core.entity.Depot;
-import com.pmease.gitplex.core.entity.PullRequest;
-import com.pmease.gitplex.core.entity.PullRequestStatusChange;
-import com.pmease.gitplex.core.manager.PullRequestStatusChangeManager;
-import com.pmease.gitplex.core.security.SecurityUtils;
-import com.pmease.gitplex.web.component.AccountLink;
-import com.pmease.gitplex.web.component.avatar.AvatarLink;
-import com.pmease.gitplex.web.component.comment.CommentInput;
-import com.pmease.gitplex.web.component.comment.DepotAttachmentSupport;
-import com.pmease.gitplex.web.page.depot.pullrequest.requestdetail.overview.SinceChangesLink;
-import com.pmease.gitplex.web.util.DateUtils;
-
-import de.agilecoders.wicket.core.markup.html.bootstrap.common.NotificationPanel;
-
-@SuppressWarnings("serial")
-class StatusChangePanel extends GenericPanel<PullRequestStatusChange> {
-
- public StatusChangePanel(String id, IModel<PullRequestStatusChange> model) {
- super(id, model);
- }
-
- private Component newViewer() {
- Fragment viewer = new Fragment("body", "viewFrag", this);
-
- String note = getStatusChange().getNote();
- if (StringUtils.isNotBlank(note)) {
- MarkdownEditSupport editSupport;
- if (SecurityUtils.canModify(getStatusChange())) {
- editSupport = new MarkdownEditSupport() {
-
- @Override
- public void setContent(String content) {
- getStatusChange().setNote(content);
- GitPlex.getInstance(PullRequestStatusChangeManager.class).save(getStatusChange());
- }
-
- @Override
- public long getVersion() {
- return getStatusChange().getVersion();
- }
-
- };
- } else {
- editSupport = null;
- }
- viewer.add(new MarkdownPanel("content", new AbstractReadOnlyModel<String>() {
-
- @Override
- public String getObject() {
- return getStatusChange().getNote();
- }
-
- }, editSupport));
- } else {
- viewer.add(new Label("content", "<i>No note</i>").setEscapeModelStrings(false));
- }
-
- WebMarkupContainer actions = new WebMarkupContainer("actions");
- actions.setVisible(SecurityUtils.canModify(getStatusChange()));
- actions.add(new AjaxLink<Void>("edit") {
-
- @Override
- public void onClick(AjaxRequestTarget target) {
- Fragment editor = new Fragment("body", "editFrag", StatusChangePanel.this);
-
- Form<?> form = new Form<Void>("form");
- form.setOutputMarkupId(true);
- editor.add(form);
-
- NotificationPanel feedback = new NotificationPanel("feedback", form);
- feedback.setOutputMarkupPlaceholderTag(true);
- form.add(feedback);
-
- long lastVersion = getStatusChange().getVersion();
- CommentInput input = new CommentInput("input", Model.of(getStatusChange().getNote())) {
-
- @Override
- protected AttachmentSupport getAttachmentSupport() {
- return new DepotAttachmentSupport(getStatusChange().getRequest().getTargetDepot(),
- getStatusChange().getRequest().getUUID());
- }
-
- @Override
- protected Depot getDepot() {
- return getStatusChange().getRequest().getTargetDepot();
- }
-
- };
- form.add(input);
-
- form.add(new AjaxButton("save") {
-
- @Override
- protected void onError(AjaxRequestTarget target, Form<?> form) {
- super.onError(target, form);
- target.add(feedback);
- }
-
- @Override
- protected void onSubmit(AjaxRequestTarget target, Form<?> form) {
- try {
- if (getStatusChange().getVersion() != lastVersion)
- throw new StaleObjectStateException(PullRequestStatusChange.class.getName(), getStatusChange().getId());
- getStatusChange().setNote(input.getModelObject());
- GitPlex.getInstance(PullRequestStatusChangeManager.class).save(getStatusChange());
-
- Component viewer = newViewer();
- editor.replaceWith(viewer);
- target.add(viewer);
- } catch (StaleObjectStateException e) {
- error("Some one changed the content you are editing. Reload the page and try again.");
- target.add(feedback);
- }
- }
-
- });
-
- form.add(new AjaxLink<Void>("cancel") {
-
- @Override
- protected void updateAjaxAttributes(AjaxRequestAttributes attributes) {
- super.updateAjaxAttributes(attributes);
- attributes.getAjaxCallListeners().add(new ConfirmLeaveListener(form));
- }
-
- @Override
- public void onClick(AjaxRequestTarget target) {
- Component viewer = newViewer();
- editor.replaceWith(viewer);
- target.add(viewer);
- }
-
- });
-
- editor.setOutputMarkupId(true);
- viewer.replaceWith(editor);
- target.add(editor);
- }
-
- });
-
- viewer.add(actions);
-
- viewer.setOutputMarkupId(true);
- return viewer;
- }
-
- @Override
- protected void onInitialize() {
- super.onInitialize();
-
- PullRequestStatusChange statusChange = getModelObject();
-
- WebMarkupContainer container = new WebMarkupContainer("statusChange");
- String activityName = EditableUtils.getName(statusChange.getEventType());
- container.add(AttributeAppender.append("class", "activity " + activityName.replace(" ", "-").toLowerCase()));
-
- WebMarkupContainer icon = new WebMarkupContainer("icon");
- container.add(icon);
- String iconClass = EditableUtils.getIcon(statusChange.getEventType());
- if (iconClass != null)
- icon.add(AttributeAppender.append("class", iconClass));
-
- container.add(new AvatarLink("userAvatar", statusChange.getUser(), null));
- container.add(new AccountLink("userName", statusChange.getUser()));
- container.add(new Label("eventName", EditableUtils.getName(statusChange.getEventType())));
- container.add(new Label("eventDate", DateUtils.formatAge(statusChange.getDate())));
- container.add(new SinceChangesLink("changes", new LoadableDetachableModel<PullRequest>() {
-
- @Override
- protected PullRequest load() {
- return StatusChangePanel.this.getModelObject().getRequest();
- }
-
- }, statusChange.getDate()));
-
- container.add(newViewer());
-
- add(container);
- }
-
- private PullRequestStatusChange getStatusChange() {
- return getModelObject();
- }
-}
+package com.pmease.gitplex.web.page.depot.pullrequest.requestdetail.overview.activity;
+
+import org.apache.commons.lang3.StringUtils;
+import org.apache.wicket.Component;
+import org.apache.wicket.ajax.AjaxRequestTarget;
+import org.apache.wicket.ajax.attributes.AjaxRequestAttributes;
+import org.apache.wicket.ajax.markup.html.AjaxLink;
+import org.apache.wicket.ajax.markup.html.form.AjaxButton;
+import org.apache.wicket.behavior.AttributeAppender;
+import org.apache.wicket.markup.html.WebMarkupContainer;
+import org.apache.wicket.markup.html.basic.Label;
+import org.apache.wicket.markup.html.form.Form;
+import org.apache.wicket.markup.html.panel.Fragment;
+import org.apache.wicket.markup.html.panel.GenericPanel;
+import org.apache.wicket.model.AbstractReadOnlyModel;
+import org.apache.wicket.model.IModel;
+import org.apache.wicket.model.LoadableDetachableModel;
+import org.apache.wicket.model.Model;
+import org.hibernate.StaleStateException;
+
+import com.pmease.commons.wicket.ajaxlistener.ConfirmLeaveListener;
+import com.pmease.commons.wicket.behavior.markdown.AttachmentSupport;
+import com.pmease.commons.wicket.component.markdown.MarkdownEditSupport;
+import com.pmease.commons.wicket.component.markdown.MarkdownPanel;
+import com.pmease.commons.wicket.editable.EditableUtils;
+import com.pmease.gitplex.core.GitPlex;
+import com.pmease.gitplex.core.entity.Depot;
+import com.pmease.gitplex.core.entity.PullRequest;
+import com.pmease.gitplex.core.entity.PullRequestStatusChange;
+import com.pmease.gitplex.core.manager.PullRequestStatusChangeManager;
+import com.pmease.gitplex.core.security.SecurityUtils;
+import com.pmease.gitplex.web.component.AccountLink;
+import com.pmease.gitplex.web.component.avatar.AvatarLink;
+import com.pmease.gitplex.web.component.comment.CommentInput;
+import com.pmease.gitplex.web.component.comment.DepotAttachmentSupport;
+import com.pmease.gitplex.web.page.depot.pullrequest.requestdetail.overview.SinceChangesLink;
+import com.pmease.gitplex.web.util.DateUtils;
+
+import de.agilecoders.wicket.core.markup.html.bootstrap.common.NotificationPanel;
+
+@SuppressWarnings("serial")
+class StatusChangePanel extends GenericPanel<PullRequestStatusChange> {
+
+ public StatusChangePanel(String id, IModel<PullRequestStatusChange> model) {
+ super(id, model);
+ }
+
+ private Component newViewer() {
+ Fragment viewer = new Fragment("body", "viewFrag", this);
+
+ String note = getStatusChange().getNote();
+ if (StringUtils.isNotBlank(note)) {
+ MarkdownEditSupport editSupport;
+ if (SecurityUtils.canModify(getStatusChange())) {
+ editSupport = new MarkdownEditSupport() {
+
+ @Override
+ public void setContent(String content) {
+ getStatusChange().setNote(content);
+ GitPlex.getInstance(PullRequestStatusChangeManager.class).save(getStatusChange());
+ }
+
+ @Override
+ public long getVersion() {
+ return getStatusChange().getVersion();
+ }
+
+ };
+ } else {
+ editSupport = null;
+ }
+ viewer.add(new MarkdownPanel("content", new AbstractReadOnlyModel<String>() {
+
+ @Override
+ public String getObject() {
+ return getStatusChange().getNote();
+ }
+
+ }, editSupport));
+ } else {
+ viewer.add(new Label("content", "<i>No note</i>").setEscapeModelStrings(false));
+ }
+
+ WebMarkupContainer actions = new WebMarkupContainer("actions");
+ actions.setVisible(SecurityUtils.canModify(getStatusChange()));
+ actions.add(new AjaxLink<Void>("edit") {
+
+ @Override
+ public void onClick(AjaxRequestTarget target) {
+ Fragment editor = new Fragment("body", "editFrag", StatusChangePanel.this);
+
+ Form<?> form = new Form<Void>("form");
+ form.setOutputMarkupId(true);
+ editor.add(form);
+
+ NotificationPanel feedback = new NotificationPanel("feedback", form);
+ feedback.setOutputMarkupPlaceholderTag(true);
+ form.add(feedback);
+
+ long lastVersion = getStatusChange().getVersion();
+ CommentInput input = new CommentInput("input", Model.of(getStatusChange().getNote())) {
+
+ @Override
+ protected AttachmentSupport getAttachmentSupport() {
+ return new DepotAttachmentSupport(getStatusChange().getRequest().getTargetDepot(),
+ getStatusChange().getRequest().getUUID());
+ }
+
+ @Override
+ protected Depot getDepot() {
+ return getStatusChange().getRequest().getTargetDepot();
+ }
+
+ };
+ form.add(input);
+
+ form.add(new AjaxButton("save") {
+
+ @Override
+ protected void onError(AjaxRequestTarget target, Form<?> form) {
+ super.onError(target, form);
+ target.add(feedback);
+ }
+
+ @Override
+ protected void onSubmit(AjaxRequestTarget target, Form<?> form) {
+ try {
+ if (getStatusChange().getVersion() != lastVersion)
+ throw new StaleStateException("");
+ getStatusChange().setNote(input.getModelObject());
+ GitPlex.getInstance(PullRequestStatusChangeManager.class).save(getStatusChange());
+
+ Component viewer = newViewer();
+ editor.replaceWith(viewer);
+ target.add(viewer);
+ } catch (StaleStateException e) {
+ error("Some one changed the content you are editing. Reload the page and try again.");
+ target.add(feedback);
+ }
+ }
+
+ });
+
+ form.add(new AjaxLink<Void>("cancel") {
+
+ @Override
+ protected void updateAjaxAttributes(AjaxRequestAttributes attributes) {
+ super.updateAjaxAttributes(attributes);
+ attributes.getAjaxCallListeners().add(new ConfirmLeaveListener(form));
+ }
+
+ @Override
+ public void onClick(AjaxRequestTarget target) {
+ Component viewer = newViewer();
+ editor.replaceWith(viewer);
+ target.add(viewer);
+ }
+
+ });
+
+ editor.setOutputMarkupId(true);
+ viewer.replaceWith(editor);
+ target.add(editor);
+ }
+
+ });
+
+ viewer.add(actions);
+
+ viewer.setOutputMarkupId(true);
+ return viewer;
+ }
+
+ @Override
+ protected void onInitialize() {
+ super.onInitialize();
+
+ PullRequestStatusChange statusChange = getModelObject();
+
+ WebMarkupContainer container = new WebMarkupContainer("statusChange");
+ String activityName = EditableUtils.getName(statusChange.getEventType());
+ container.add(AttributeAppender.append("class", "activity " + activityName.replace(" ", "-").toLowerCase()));
+
+ WebMarkupContainer icon = new WebMarkupContainer("icon");
+ container.add(icon);
+ String iconClass = EditableUtils.getIcon(statusChange.getEventType());
+ if (iconClass != null)
+ icon.add(AttributeAppender.append("class", iconClass));
+
+ container.add(new AvatarLink("userAvatar", statusChange.getUser(), null));
+ container.add(new AccountLink("userName", statusChange.getUser()));
+ container.add(new Label("eventName", EditableUtils.getName(statusChange.getEventType())));
+ container.add(new Label("eventDate", DateUtils.formatAge(statusChange.getDate())));
+ container.add(new SinceChangesLink("changes", new LoadableDetachableModel<PullRequest>() {
+
+ @Override
+ protected PullRequest load() {
+ return StatusChangePanel.this.getModelObject().getRequest();
+ }
+
+ }, statusChange.getDate()));
+
+ container.add(newViewer());
+
+ add(container);
+ }
+
+ private PullRequestStatusChange getStatusChange() {
+ return getModelObject();
+ }
+}
diff --git a/gitplex.web/src/main/java/com/pmease/gitplex/web/page/test/TestPage.html b/gitplex.web/src/main/java/com/pmease/gitplex/web/page/test/TestPage.html
index 3c1c86ca7a..445cd0625f 100644
--- a/gitplex.web/src/main/java/com/pmease/gitplex/web/page/test/TestPage.html
+++ b/gitplex.web/src/main/java/com/pmease/gitplex/web/page/test/TestPage.html
@@ -1,6 +1,3 @@
<wicket:extend>
- <form wicket:id="form">
- <input wicket:id="name"></input>
- <input type="submit" wicket:id="submit" value="save"></input>
- </form>
+ <a wicket:id="link">test</a>
</wicket:extend>
\ No newline at end of file
diff --git a/gitplex.web/src/main/java/com/pmease/gitplex/web/page/test/TestPage.java b/gitplex.web/src/main/java/com/pmease/gitplex/web/page/test/TestPage.java
index e81d7a14d4..9a0b00d54d 100644
--- a/gitplex.web/src/main/java/com/pmease/gitplex/web/page/test/TestPage.java
+++ b/gitplex.web/src/main/java/com/pmease/gitplex/web/page/test/TestPage.java
@@ -1,11 +1,10 @@
package com.pmease.gitplex.web.page.test;
-import org.apache.wicket.ajax.AjaxRequestTarget;
-import org.apache.wicket.ajax.markup.html.form.AjaxButton;
-import org.apache.wicket.markup.html.form.Form;
-import org.apache.wicket.markup.html.form.TextField;
-import org.apache.wicket.model.Model;
+import org.apache.wicket.markup.html.link.Link;
+import com.pmease.gitplex.core.GitPlex;
+import com.pmease.gitplex.core.entity.PullRequest;
+import com.pmease.gitplex.core.manager.PullRequestManager;
import com.pmease.gitplex.web.page.base.BasePage;
@SuppressWarnings("serial")
@@ -15,17 +14,15 @@ public class TestPage extends BasePage {
protected void onInitialize() {
super.onInitialize();
- Form<?> form = new Form<Void>("form");
- form.add(new TextField<String>("name", Model.of("")));
- form.add(new AjaxButton("submit") {
+ add(new Link<Void>("link") {
@Override
- protected void onSubmit(AjaxRequestTarget target, Form<?> form) {
- super.onSubmit(target, form);
+ public void onClick() {
+ PullRequest request = GitPlex.getInstance(PullRequestManager.class).load(1L);
+ request.getLatestUpdate();
}
});
- add(form);
}
}
diff --git a/gitplex.web/src/main/java/com/pmease/gitplex/web/websocket/CodeCommentChangeBroadcaster.java b/gitplex.web/src/main/java/com/pmease/gitplex/web/websocket/CodeCommentChangeBroadcaster.java
index b039f68194..259461dfda 100644
--- a/gitplex.web/src/main/java/com/pmease/gitplex/web/websocket/CodeCommentChangeBroadcaster.java
+++ b/gitplex.web/src/main/java/com/pmease/gitplex/web/websocket/CodeCommentChangeBroadcaster.java
@@ -3,9 +3,6 @@ package com.pmease.gitplex.web.websocket;
import javax.inject.Inject;
import javax.inject.Singleton;
-import org.hibernate.resource.transaction.spi.TransactionStatus;
-
-import com.pmease.commons.hibernate.dao.Dao;
import com.pmease.commons.loader.Listen;
import com.pmease.commons.wicket.WicketUtils;
import com.pmease.commons.wicket.websocket.PageKey;
@@ -15,13 +12,10 @@ import com.pmease.gitplex.core.event.codecomment.CodeCommentEvent;
@Singleton
public class CodeCommentChangeBroadcaster {
- private final Dao dao;
-
private final WebSocketManager webSocketManager;
@Inject
- public CodeCommentChangeBroadcaster(Dao dao, WebSocketManager webSocketManager) {
- this.dao = dao;
+ public CodeCommentChangeBroadcaster(WebSocketManager webSocketManager) {
this.webSocketManager = webSocketManager;
}
@@ -29,24 +23,7 @@ public class CodeCommentChangeBroadcaster {
public void on(CodeCommentEvent event) {
CodeCommentChangedRegion region = new CodeCommentChangedRegion(event.getComment().getId());
PageKey sourcePageKey = WicketUtils.getPageKey();
- if (dao.getSession().getTransaction().getStatus() == TransactionStatus.ACTIVE) {
- /*
- * Make sure that code comment and associated objects are committed before
- * sending render request; otherwise rendering request may not reflect
- * expected status as rendering happens in another thread which may get
- * executed before code comment modification is committed.
- */
- dao.doAfterCommit(new Runnable() {
-
- @Override
- public void run() {
- webSocketManager.renderAsync(region, sourcePageKey);
- }
-
- });
- } else {
- webSocketManager.renderAsync(region, sourcePageKey);
- }
+ webSocketManager.renderAsync(region, sourcePageKey);
}
}
\ No newline at end of file
diff --git a/gitplex.web/src/main/java/com/pmease/gitplex/web/websocket/PullRequestChangeBroadcaster.java b/gitplex.web/src/main/java/com/pmease/gitplex/web/websocket/PullRequestChangeBroadcaster.java
index dc1c236fc9..1d37a53b30 100644
--- a/gitplex.web/src/main/java/com/pmease/gitplex/web/websocket/PullRequestChangeBroadcaster.java
+++ b/gitplex.web/src/main/java/com/pmease/gitplex/web/websocket/PullRequestChangeBroadcaster.java
@@ -3,9 +3,6 @@ package com.pmease.gitplex.web.websocket;
import javax.inject.Inject;
import javax.inject.Singleton;
-import org.hibernate.resource.transaction.spi.TransactionStatus;
-
-import com.pmease.commons.hibernate.dao.Dao;
import com.pmease.commons.loader.Listen;
import com.pmease.commons.wicket.WicketUtils;
import com.pmease.commons.wicket.websocket.PageKey;
@@ -15,13 +12,10 @@ import com.pmease.gitplex.core.event.pullrequest.PullRequestChangeEvent;
@Singleton
public class PullRequestChangeBroadcaster {
- private final Dao dao;
-
private final WebSocketManager webSocketManager;
@Inject
- public PullRequestChangeBroadcaster(Dao dao, WebSocketManager webSocketManager) {
- this.dao = dao;
+ public PullRequestChangeBroadcaster(WebSocketManager webSocketManager) {
this.webSocketManager = webSocketManager;
}
@@ -30,25 +24,7 @@ public class PullRequestChangeBroadcaster {
PullRequestChangedRegion region = new PullRequestChangedRegion(event.getRequest().getId());
PageKey sourcePageKey = WicketUtils.getPageKey();
- if (dao.getSession().getTransaction().getStatus() == TransactionStatus.ACTIVE) {
- /*
- * Make sure that pull request and associated objects are committed before
- * sending render request; otherwise rendering request may not reflect
- * expected status as rendering happens in another thread which may get
- * executed before pull request modification is committed.
- */
- dao.doAfterCommit(new Runnable() {
-
- @Override
- public void run() {
- webSocketManager.renderAsync(region, sourcePageKey);
- }
-
- });
- } else {
- webSocketManager.renderAsync(region, sourcePageKey);
- }
-
+ webSocketManager.renderAsync(region, sourcePageKey);
}
}
\ No newline at end of file