Search code examples
gitkotlinjgitblame

JGit BlameCommand keeps returning null


For my current project I need to find out which users have last modified a range of lines in a given file. For this, and other tasks I have been using JGit and I wrote my code in Kotlin. So good so far, I have realised that when I try to use JGit blame command, it keeps returning null, even though it doesn't throw an exception. Here is the prototype function I have at the moment which would print the last committers email line by line in the range of interest (nevermind the LocationInfo class, it's a custom data class that holds files paths and ranges that I want to inspect):

fun getContributors(location: LocationInfo, git: Git, commitID: ObjectId)  {
    val blamer = BlameCommand(git.repository)
    blamer.setFilePath(location.path.substringAfter(git.repository.directory.parent)) 
    blamer.setStartCommit(commitID)
    val blameResult = blamer.call() // blameResult is always null!
    println("Blaming: ${location.path.substringAfter(git.repository.directory.parent + "/")}")
    for (line in location.range.start..location.range.end) {
        println(blameResult.getSourceCommitter(line).emailAddress)
    }
}

When I navigate to the repository in terminal, checkout an old commit (same commit ID as in my code) and run git blame command on the same files (same paths as in my code) it does indeed what it's meant to do and provide me with the info that I need. What could be the cause of this problem? I am pretty sure that I supply legit arguments to the function as well. Is my handling of BlameCommand incorrect somehow?


Solution

  • You can compare your handling of this command with org.eclipse.jgit.test/tst/org/eclipse/jgit/api/BlameCommandTest.java like here

    BlameCommand command = new BlameCommand(db);
    command.setFilePath("file.txt");
    BlameResult lines = command.call();
    

    So make sure the location.path.substringAfter(git.repository.directory.parent) actually references a file, not a folder.