File commit date in JGit

1.1k views Asked by At

Is it possible to resolve the date and time when a certain file was committed for the first time using JGit?

Git equivalent would be listing the first commit, like:

git log --format=%aD <FILE> | tail -1
1

There are 1 answers

2
RĂ¼diger Herrmann On BEST ANSWER

A RevWalk can be used as follows to obtain the first commit that contains 'file.txt'

RevWalk revWalk = new RevWalk( repository );
revWalk.markStart( revWalk.parseCommit( repository.resolve( Constants.HEAD ) ) );
revWalk.setTreeFilter( PathFilter.create( "path/to/file.txt" ) );
revWalk.sort( RevSort.COMMIT_TIME_DESC );
revWalk.sort( RevSort.REVERSE, true );
RevCommit commit = revWalk.next();
...
revWalk.dispose();

In the example the history starts at HEAD. Adjust the markStart() call the start from somewhere else or call markStart() multiple times to include several start points.

The PathFilter excludes commits that do not contain the given repository-relative path name. And finally the two sort() calls take care that commits are ordered by their time stamp (newest first) in reverse order. Hence the oldest commit that contains the given file is returned by next().

Be aware that the commit passed to markStart() must be from the same revision walker, i.e. it must be obtained with a call to parseCommit() from the same revWalk instance. See also this thread for more details.