Skip to content

The Unified and Autonomous Development Platform

Cache blame results if it runs for more than 1 sec.

robin shineb90aedd539de
diff --git a/commons.git/src/main/java/com/pmease/commons/git/Blame.java b/commons.git/src/main/java/com/pmease/commons/git/Blame.java
index 82a7d271e7..ea50dd84f4 100644
--- a/commons.git/src/main/java/com/pmease/commons/git/Blame.java
+++ b/commons.git/src/main/java/com/pmease/commons/git/Blame.java
@@ -1,38 +1,61 @@
package com.pmease.commons.git;
-import java.util.ArrayList;
-import java.util.Collections;
import java.util.List;
+import org.apache.commons.lang3.StringUtils;
+
public class Blame {
private final BriefCommit commit;
+
+ private final List<Range> ranges;
- private final List<String> lines;
-
- public Blame(BriefCommit commit, List<String> lines) {
+ public Blame(BriefCommit commit, List<Range> ranges) {
this.commit = commit;
- this.lines = new ArrayList<>(lines);
+ this.ranges = ranges;
}
public BriefCommit getCommit() {
return commit;
}
- public List<String> getLines() {
- return Collections.unmodifiableList(lines);
+ public List<Range> getRanges() {
+ return ranges;
}
@Override
public String toString() {
- StringBuffer buffer = new StringBuffer();
- buffer.append(commit);
- buffer.append("\n========================================================================\n");
+ StringBuilder builder = new StringBuilder();
+ builder.append(commit.getHash()).append(": ");
+ for (Range range: ranges)
+ builder.append(range).append(", ");
+
+ return StringUtils.stripEnd(builder.toString(), ", ");
+ }
+
+ public static class Range {
- for (String line: getLines())
- buffer.append(line).append("\n");
+ private final int beginLine; // 0-indexed, inclusive
+
+ private final int endLine; // 0-indexed, exclusive
+
+ public Range(int beginLine, int endLine) {
+ this.beginLine = beginLine;
+ this.endLine = endLine;
+ }
+
+ public int getBeginLine() {
+ return beginLine;
+ }
+
+ public int getEndLine() {
+ return endLine;
+ }
+
+ @Override
+ public String toString() {
+ return beginLine + "-" + endLine;
+ }
- return buffer.toString();
}
-
}
diff --git a/commons.git/src/main/java/com/pmease/commons/git/Git.java b/commons.git/src/main/java/com/pmease/commons/git/Git.java
index 5a66a49d57..02fc063f22 100644
--- a/commons.git/src/main/java/com/pmease/commons/git/Git.java
+++ b/commons.git/src/main/java/com/pmease/commons/git/Git.java
@@ -535,25 +535,17 @@ public class Git implements Serializable {
}
/**
- * Display commit information for every region of specified file and revision.
+ * Display commit information for every region of specified commit and file.
*
* @param file
* file for blame
- * @param revision
- * revision of the file for blame
- * @param start
- * specify start line to be included in the blame. Use <tt>-1</tt>
- * to blame from start of the file
- * @param end
- * specify end line to be included in the blame. Use <tt>-1</tt> to
- * blame to the end of file
+ * @param commitHash
+ * commit hash of the file for blame
* @return
- * list of blame objects. The blame object consists of commit information
- * and lines associated with this commit. All lines of all blame objects
- * consist the whole file.
+ * map of commit hash to commit blame
*/
- public List<Blame> blame(String file, String revision, int start, int end) {
- return new BlameCommand(repoDir).file(file).revision(revision).start(start).end(end).call();
+ public Map<String, Blame> blame(String commitHash, String file) {
+ return new BlameCommand(repoDir).commitHash(commitHash).file(file).call();
}
public boolean isBinary(String file, String revision) {
diff --git a/commons.git/src/main/java/com/pmease/commons/git/command/BlameCommand.java b/commons.git/src/main/java/com/pmease/commons/git/command/BlameCommand.java
index 099710cd82..55e4306f05 100644
--- a/commons.git/src/main/java/com/pmease/commons/git/command/BlameCommand.java
+++ b/commons.git/src/main/java/com/pmease/commons/git/command/BlameCommand.java
@@ -4,9 +4,13 @@ import java.io.File;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
-import java.util.List;
import java.util.Map;
+import java.util.concurrent.atomic.AtomicBoolean;
+import java.util.concurrent.atomic.AtomicInteger;
+import java.util.concurrent.atomic.AtomicReference;
+import org.apache.commons.collections.map.AbstractReferenceMap;
+import org.apache.commons.collections.map.ReferenceMap;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
@@ -19,24 +23,24 @@ import com.pmease.commons.util.execution.Commandline;
import com.pmease.commons.util.execution.ExecuteResult;
import com.pmease.commons.util.execution.LineConsumer;
-public class BlameCommand extends GitCommand<List<Blame>> {
+public class BlameCommand extends GitCommand<Map<String, Blame>> {
private static final Logger logger = LoggerFactory.getLogger(BlameCommand.class);
- private String revision;
+ private static final ReferenceMap cache = new ReferenceMap(AbstractReferenceMap.HARD, AbstractReferenceMap.WEAK);
- private String file;
+ private static final int CACHE_THRESHOLD = 1000;
- private int start = -1;
+ private String commitHash;
- private int end = -1;
+ private String file;
public BlameCommand(File repoDir) {
super(repoDir);
}
- public BlameCommand revision(String revision) {
- this.revision = revision;
+ public BlameCommand commitHash(String commitHash) {
+ this.commitHash = commitHash;
return this;
}
@@ -45,125 +49,111 @@ public class BlameCommand extends GitCommand<List<Blame>> {
return this;
}
- public BlameCommand start(int start) {
- this.start = start;
- return this;
- }
-
- public BlameCommand end(int end) {
- this.end = end;
- return this;
- }
-
private Commandline buildCmd() {
Commandline cmd = cmd().addArgs("blame", "--porcelain");
- if (start != -1) {
- if (end != -1)
- cmd.addArgs("-L", "" + start + "," + end);
- else
- cmd.addArgs("-L", "" + start);
- } else if (end != -1) {
- cmd.addArgs("-L", "," + end);
- }
-
- cmd.addArgs(revision, "--", file);
+ cmd.addArgs(commitHash, "--", file);
return cmd;
}
@Override
- public List<Blame> call() {
+ public Map<String, Blame> call() {
+ Preconditions.checkArgument(commitHash!=null && GitUtils.isHash(commitHash), "commit hash has to be specified.");
Preconditions.checkNotNull(file, "file parameter has to be specified.");
- Preconditions.checkNotNull(revision, "revision has to be specified.");
+
+ String cacheKey = commitHash + ":" + file;
+
+ @SuppressWarnings("unchecked")
+ Map<String, Blame> cached = (Map<String, Blame>) cache.get(cacheKey);
+ if (cached != null)
+ return cached;
Commandline cmd = buildCmd();
- final List<Blame> blames = new ArrayList<>();
+ final Map<String, Blame> blames = new HashMap<>();
final Map<String, BriefCommit> commitMap = new HashMap<>();
- final BlameBuilder blameBuilder = new BlameBuilder();
+ final AtomicReference<BriefCommit> commitRef = new AtomicReference<>(null);
final BriefCommitBuilder commitBuilder = new BriefCommitBuilder();
- final boolean endOfFile[] = new boolean[]{false};
+ final AtomicBoolean endOfFile = new AtomicBoolean(false);
+ final AtomicInteger beginLine = new AtomicInteger(0);
+ final AtomicInteger endLine = new AtomicInteger(0);
- while (true) {
- ExecuteResult result = cmd.execute(new LineConsumer() {
-
- @Override
- public void consume(String line) {
- if (line.startsWith("\t")) {
- if (blameBuilder.commit == null)
- blameBuilder.commit = commitMap.get(commitBuilder.hash);
- blameBuilder.lines.add(line.substring(1));
- commitBuilder.hash = null;
- } else if (commitBuilder.hash == null) {
- commitBuilder.hash = StringUtils.substringBefore(line, " ");
- if (blameBuilder.commit != null && !commitBuilder.hash.equals(blameBuilder.commit.getHash())) {
- blames.add(blameBuilder.build());
- blameBuilder.commit = null;
- blameBuilder.lines.clear();
+ long time = System.currentTimeMillis();
+
+ ExecuteResult result = cmd.execute(new LineConsumer() {
+
+ @Override
+ public void consume(String line) {
+ if (line.startsWith("\t")) {
+ if (commitRef.get() == null)
+ commitRef.set(commitMap.get(commitBuilder.hash));
+ endLine.getAndIncrement();
+ commitBuilder.hash = null;
+ } else if (commitBuilder.hash == null) {
+ commitBuilder.hash = StringUtils.substringBefore(line, " ");
+ BriefCommit commit = commitRef.get();
+ if (commit != null && !commitBuilder.hash.equals(commit.getHash())) {
+ Blame blame = blames.get(commit.getHash());
+ if (blame == null) {
+ blame = new Blame(commit, new ArrayList<Blame.Range>());
+ blames.put(commit.getHash(), blame);
}
- } else if (line.startsWith("author ")) {
- commitBuilder.author = line.substring("author ".length());
- } else if (line.startsWith("author-mail ")) {
- line = StringUtils.substringAfter(line, "<");
- commitBuilder.authorEmail = StringUtils.substringBeforeLast(line, ">");
- } else if (line.startsWith("author-time ")) {
- commitBuilder.authorDate = new Date(1000L * Long.parseLong(line.substring("author-time ".length())));
- } else if (line.startsWith("committer ")) {
- commitBuilder.committer = line.substring("committer ".length());
- } else if (line.startsWith("committer-mail ")) {
- line = StringUtils.substringAfter(line, "<");
- commitBuilder.committerEmail = StringUtils.substringBeforeLast(line, ">");
- } else if (line.startsWith("committer-time ")) {
- commitBuilder.committerDate = new Date(1000L * Long.parseLong(line.substring("committer-time ".length())));
- } else if (line.startsWith("summary ")) {
- commitBuilder.summary = line.substring("summary ".length());
- commitMap.put(commitBuilder.hash, commitBuilder.build());
- }
- }
-
- }, new LineConsumer() {
-
- @Override
- public void consume(String line) {
- if (line.startsWith("fatal: file ") && line.contains("has only ")) {
- endOfFile[0] = true;
- logger.debug(line.substring("fatal: ".length()));
- } else {
- logger.error(line);
+ blame.getRanges().add(new Blame.Range(beginLine.get(), endLine.get()));
+ commitRef.set(null);
+ beginLine.set(endLine.get());
}
- }
-
- });
+ } else if (line.startsWith("author ")) {
+ commitBuilder.author = line.substring("author ".length());
+ } else if (line.startsWith("author-mail ")) {
+ line = StringUtils.substringAfter(line, "<");
+ commitBuilder.authorEmail = StringUtils.substringBeforeLast(line, ">");
+ } else if (line.startsWith("author-time ")) {
+ commitBuilder.authorDate = new Date(1000L * Long.parseLong(line.substring("author-time ".length())));
+ } else if (line.startsWith("committer ")) {
+ commitBuilder.committer = line.substring("committer ".length());
+ } else if (line.startsWith("committer-mail ")) {
+ line = StringUtils.substringAfter(line, "<");
+ commitBuilder.committerEmail = StringUtils.substringBeforeLast(line, ">");
+ } else if (line.startsWith("committer-time ")) {
+ commitBuilder.committerDate = new Date(1000L * Long.parseLong(line.substring("committer-time ".length())));
+ } else if (line.startsWith("summary ")) {
+ commitBuilder.summary = line.substring("summary ".length());
+ commitMap.put(commitBuilder.hash, commitBuilder.build());
+ }
+ }
- if (endOfFile[0]) {
- if (end != -1) {
- end = -1;
- endOfFile[0] = false;
- cmd = buildCmd();
+ }, new LineConsumer() {
+
+ @Override
+ public void consume(String line) {
+ if (line.startsWith("fatal: file ") && line.contains("has only ")) {
+ endOfFile.set(true);
+ logger.debug(line.substring("fatal: ".length()));
} else {
- break;
+ logger.error(line);
}
- } else {
- result.checkReturnCode();
- break;
}
- }
+
+ });
- if (!blameBuilder.lines.isEmpty())
- blames.add(blameBuilder.build());
+ if (!endOfFile.get())
+ result.checkReturnCode();
- return blames;
- }
-
- private static class BlameBuilder {
- private BriefCommit commit;
+ if (endLine.get() > beginLine.get()) {
+ BriefCommit commit = commitRef.get();
+ Blame blame = blames.get(commit.getHash());
+ if (blame == null) {
+ blame = new Blame(commit, new ArrayList<Blame.Range>());
+ blames.put(commit.getHash(), blame);
+ }
+ blame.getRanges().add(new Blame.Range(beginLine.get(), endLine.get()));
+ }
- private List<String> lines = new ArrayList<>();
+ if (System.currentTimeMillis()-time > CACHE_THRESHOLD)
+ cache.put(cacheKey, blames);
- private Blame build() {
- return new Blame(commit, lines);
- }
+ return blames;
}
private static class BriefCommitBuilder {
diff --git a/commons.git/src/test/java/com/pmease/commons/git/command/BlameCommandTest.java b/commons.git/src/test/java/com/pmease/commons/git/command/BlameCommandTest.java
index a4abc04eb8..f48c525b6b 100644
--- a/commons.git/src/test/java/com/pmease/commons/git/command/BlameCommandTest.java
+++ b/commons.git/src/test/java/com/pmease/commons/git/command/BlameCommandTest.java
@@ -3,7 +3,7 @@ package com.pmease.commons.git.command;
import static org.junit.Assert.assertEquals;
import java.io.File;
-import java.util.List;
+import java.util.Map;
import org.junit.Test;
@@ -28,9 +28,10 @@ public class BlameCommandTest extends AbstractGitTest {
+ "9th line\n",
"initial commit");
- List<Blame> blames = git.blame("file", "master", 3, -1);
+ String commitHash = git.parseRevision("master", true);
+ Map<String, Blame> blames = git.blame(commitHash, "file");
assertEquals(1, blames.size());
- assertEquals(7, blames.get(0).getLines().size());
+ assertEquals(commitHash + ": 0-9", blames.get(commitHash).toString());
addFileAndCommit(
"file",
@@ -45,26 +46,14 @@ public class BlameCommandTest extends AbstractGitTest {
+ "nineth line\n",
"second commit");
- blames = git.blame("file", "master", -1, -1);
- assertEquals(3, blames.size());
- assertEquals(1, blames.get(0).getLines().size());
- assertEquals(7, blames.get(1).getLines().size());
- assertEquals(1, blames.get(2).getLines().size());
- assertEquals(blames.get(0).getCommit().getHash(), blames.get(2).getCommit().getHash());
-
- blames = git.blame("file", "master", 5, 9);
+ commitHash = git.parseRevision("master", true);
+ blames = git.blame(commitHash, "file");
assertEquals(2, blames.size());
- assertEquals(4, blames.get(0).getLines().size());
-
- blames = git.blame("file", "master", 10, 9);
- assertEquals(0, blames.size());
-
- blames = git.blame("file", "master", 8, 100);
- assertEquals(2, blames.size());
-
- blames = git.blame("file", "master", 80, 100);
- assertEquals(0, blames.size());
-
+
+ assertEquals(commitHash + ": 0-1, 8-9", blames.get(commitHash).toString());
+ commitHash = git.parseRevision("master~1", true);
+ assertEquals(commitHash + ": 1-8", blames.get(commitHash).toString());
+
addFileAndCommit(
"file",
"first line\n"
@@ -73,9 +62,13 @@ public class BlameCommandTest extends AbstractGitTest {
Git bareGit = new Git(new File(tempDir, "bare"));
bareGit.clone(git, true, false, false, null);
- blames = bareGit.blame("file", "master", -1, -1);
+ commitHash = bareGit.parseRevision("master", true);
+ blames = bareGit.blame(commitHash, "file");
+
+ commitHash = bareGit.parseRevision("master~1", true);
assertEquals(1, blames.size());
+ assertEquals(commitHash + ": 0-2", blames.get(commitHash).toString());
}
}
diff --git a/gitplex.core/src/main/java/com/pmease/gitplex/core/model/Repository.java b/gitplex.core/src/main/java/com/pmease/gitplex/core/model/Repository.java
index 176cfb782a..963df13dec 100644
--- a/gitplex.core/src/main/java/com/pmease/gitplex/core/model/Repository.java
+++ b/gitplex.core/src/main/java/com/pmease/gitplex/core/model/Repository.java
@@ -84,7 +84,7 @@ public class Repository extends AbstractEntity implements UserBelonging {
public static final String REFS_GITPLEX = "refs/gitplex/";
- private static final int LAST_COMMITS_CACHE_THRESHOLD = 500;
+ private static final int LAST_COMMITS_CACHE_THRESHOLD = 1000;
private static final int MAX_READ_BLOB_SIZE = 5*1024*1024;
diff --git a/gitplex.web/src/main/java/com/pmease/gitplex/web/WebSession.java b/gitplex.web/src/main/java/com/pmease/gitplex/web/WebSession.java
index e3ad69d9f7..b9a454ec3a 100644
--- a/gitplex.web/src/main/java/com/pmease/gitplex/web/WebSession.java
+++ b/gitplex.web/src/main/java/com/pmease/gitplex/web/WebSession.java
@@ -7,7 +7,7 @@ import org.apache.wicket.request.Request;
public class WebSession extends org.apache.wicket.protocol.http.WebSession {
- private static final long serialVersionUID = 1L;
+ private static final long serialVersionUID = 1L;
public WebSession(Request request) {
super(request);
diff --git a/gitplex.web/src/main/java/com/pmease/gitplex/web/component/blobview/source/SourceViewPanel.java b/gitplex.web/src/main/java/com/pmease/gitplex/web/component/blobview/source/SourceViewPanel.java
index a5d5669d00..466edadd6f 100644
--- a/gitplex.web/src/main/java/com/pmease/gitplex/web/component/blobview/source/SourceViewPanel.java
+++ b/gitplex.web/src/main/java/com/pmease/gitplex/web/component/blobview/source/SourceViewPanel.java
@@ -280,24 +280,23 @@ public class SourceViewPanel extends BlobViewPanel {
private String getBlameBlocks() {
if (context.isBlame()) {
- int fromLine = 0;
- List<BlameBlock> blocks = new ArrayList<>();
- for (Blame blame: context.getRepository().git().blame(
- context.getBlobIdent().path, context.getBlobIdent().revision, -1, -1)) {
- BlameBlock block = new BlameBlock();
- block.authorDate = DateUtils.formatDate(blame.getCommit().getAuthor().getWhen());
- block.authorName = StringEscapeUtils.escapeHtml4(blame.getCommit().getAuthor().getName());
- block.commitHash = GitUtils.abbreviateSHA(blame.getCommit().getHash(), 7);
- block.commitMessage = blame.getCommit().getSubject();
+ List<BlameCommit> commits = new ArrayList<>();
+
+ String commitHash = context.getRepository().getObjectId(context.getBlobIdent().revision, true).name();
+
+ for (Blame blame: context.getRepository().git().blame(commitHash, context.getBlobIdent().path).values()) {
+ BlameCommit commit = new BlameCommit();
+ commit.authorDate = DateUtils.formatDate(blame.getCommit().getAuthor().getWhen());
+ commit.authorName = StringEscapeUtils.escapeHtml4(blame.getCommit().getAuthor().getName());
+ commit.hash = GitUtils.abbreviateSHA(blame.getCommit().getHash(), 7);
+ commit.message = blame.getCommit().getSubject();
PageParameters params = RepoCommitPage.paramsOf(context.getRepository(), blame.getCommit().getHash());
- block.commitUrl = RequestCycle.get().urlFor(RepoCommitPage.class, params).toString();
- block.fromLine = fromLine;
- block.toLine = fromLine + blame.getLines().size();
- fromLine = block.toLine;
- blocks.add(block);
+ commit.url = RequestCycle.get().urlFor(RepoCommitPage.class, params).toString();
+ commit.ranges = blame.getRanges();
+ commits.add(commit);
}
try {
- return GitPlex.getInstance(ObjectMapper.class).writeValueAsString(blocks);
+ return GitPlex.getInstance(ObjectMapper.class).writeValueAsString(commits);
} catch (JsonProcessingException e) {
throw new RuntimeException(e);
}
@@ -307,21 +306,19 @@ public class SourceViewPanel extends BlobViewPanel {
}
@SuppressWarnings("unused")
- private static class BlameBlock {
+ private static class BlameCommit {
- String commitMessage;
+ String hash;
- String commitHash;
+ String message;
- String commitUrl;
+ String url;
String authorName;
String authorDate;
- int fromLine;
-
- int toLine;
+ List<Blame.Range> ranges;
}
}
diff --git a/gitplex.web/src/main/java/com/pmease/gitplex/web/component/blobview/source/source-view.js b/gitplex.web/src/main/java/com/pmease/gitplex/web/component/blobview/source/source-view.js
index b47cd368be..6852d95901 100644
--- a/gitplex.web/src/main/java/com/pmease/gitplex/web/component/blobview/source/source-view.js
+++ b/gitplex.web/src/main/java/com/pmease/gitplex/web/component/blobview/source/source-view.js
@@ -1,5 +1,5 @@
gitplex.sourceview = {
- init: function(codeId, fileContent, filePath, tokenPos, ajaxIndicatorUrl, symbolQuery, blameBlocks) {
+ init: function(codeId, fileContent, filePath, tokenPos, ajaxIndicatorUrl, symbolQuery, blames) {
var cm;
var $code = $("#" + codeId);
@@ -100,11 +100,11 @@ gitplex.sourceview = {
if (scrollPos)
cm.scrollTo(scrollPos.left, scrollPos.top);
- if (blameBlocks) {
+ if (blames) {
// render blame blocks with a timer to avoid the issue that occasionally
// blame gutter becomes much wider than expected
setTimeout(function() {
- gitplex.sourceview.blame(cm, blameBlocks);
+ gitplex.sourceview.blame(cm, blames);
}, 10);
}
}
@@ -138,20 +138,23 @@ gitplex.sourceview = {
},
- blame: function(cm, blocks) {
+ blame: function(cm, blames) {
if (typeof cm === "string")
cm = $("#"+ cm + ">.CodeMirror")[0].CodeMirror;
- if (blocks) {
+ if (blames) {
cm.setOption("gutters", ["CodeMirror-annotations", "CodeMirror-linenumbers", "CodeMirror-foldgutter"]);
- for (var i in blocks) {
- var block = blocks[i];
+ for (var i in blames) {
+ var blame = blames[i];
var $ele = $(document.createElement("div"));
$ele.addClass("CodeMirror-annotation");
- $("<a class='hash'>" + block.commitHash + "</a>").appendTo($ele).attr("href", block.commitUrl).attr("title", block.commitMessage);
- $ele.append("<span class='date'>" + block.authorDate + "</span>");
- $ele.append("<span class='author'>" + block.authorName + "</span>");
- cm.setGutterMarker(block.fromLine, "CodeMirror-annotations", $ele[0]);
+ $("<a class='hash'>" + blame.hash + "</a>").appendTo($ele).attr("href", blame.url).attr("title", blame.message);
+ $ele.append("<span class='date'>" + blame.authorDate + "</span>");
+ $ele.append("<span class='author'>" + blame.authorName + "</span>");
+ for (var j in blame.ranges) {
+ var range = blame.ranges[j];
+ cm.setGutterMarker(range.beginLine, "CodeMirror-annotations", $ele[0]);
+ }
}
} else {
cm.clearGutter("CodeMirror-annotations");