Accessing commit details of a specific file using jgit in springboot

Viewed 23

I have been trying to get git comit log for a specific file in git repo, but after multiple attempts I am failing to identify the source of the problem.

Here is the link to my github code.

PS: The files Folder needs to be deleted everytime the app needs to start again. Any tips on that would be also helpful.

To put it in short, I tried the below piece of code to get the commit log, but I am getting a null RevCommit.

Repository repository = git.getRepository();

//Approach 1
    RevCommit commits = git.log().addPath("D:/Code_downloads/fileaccess/files/dev/Doc2.csv").call().iterator().next();
    


//Approach 2
    RevWalk revWalk = new RevWalk( repository );
       revWalk.markStart( revWalk.parseCommit( repository.resolve( Constants.HEAD ) ) );
       revWalk.setTreeFilter(PathFilter.create( "D:/Code_downloads/fileaccess/files/dev/Doc2.csv" ) );
       revWalk.sort( RevSort.COMMIT_TIME_DESC );
       revWalk.sort( RevSort.REVERSE, true );
       RevCommit commit = revWalk.next();

Referred multiple documentations and stackoverflow posts. no luck. https://archive.eclipse.org/jgit/site/4.5.0.201609210915-r/apidocs/org/eclipse/jgit/api/LogCommand.html

Any help will be appreciated.

1 Answers

It should work to use addPath() and then iterate over the RevCommits.

But you should not use the "absoulte path" to the file, but rather only the relative path inside your repository.

E.g.

Iterable<RevCommit logs = git.log().addPath("README.md").call();
for (RevCommit rev : logs) {
    System.out.println("Commit: " + rev + ", name: " + rev.getName() + ", id: " + rev.getId().getName());
}

There is a ready-to-run snippet in the jgit-cookbook which shows a few more ways to iterate commits.

Related