Sirim
Sirim

Reputation: 182

How to find who last changed a file with JGit

I need the user who last changed/committed a file in our GIT repository.

The project consists of many subfolders, and the master branch has many merged commits.

I tried :

File gitWorkDir = new File("D:/gitfolder/");
Git git = Git.open(gitWorkDir);
RevCommit latestCommit;
String path = "test.txt";
try( RevWalk revWalk = new RevWalk( git.getRepository() ) ) {
    Ref headRef = git.getRepository().exactRef( Constants.HEAD );
    RevCommit headCommit = revWalk.parseCommit( headRef.getObjectId());
    revWalk.markStart( headCommit );
    revWalk.sort( RevSort.COMMIT_TIME_DESC );
    TreeFilter filter = AndTreeFilter.create( PathFilter.create( path ), TreeFilter.ANY_DIFF );
    revWalk.setTreeFilter(filter);
    latestCommit = revWalk.next();
    git.close();
}

the Repository and HEAD commit are there, but latestCommit is always null.

Do I have to define the whole path to my file? Is it a problem that the master branch is so "branched out" so maybe the commit cannot be found, or what else could be the problem?

Upvotes: 1

Views: 1772

Answers (1)

clinical
clinical

Reputation: 588

In git I would use git log --follow path/to/your/file. It gives you the full git history of a specific file (including commit author even if the file name was changed or file was moved to another folder).

For doing this with JGit check out this stackoverflow question.

Espacially this part should be intresting (taken from above answer):

 /**
 * Returns the result of a git log --follow -- < path >
 * @return
 * @throws IOException
 * @throws MissingObjectException
 * @throws GitAPIException
 */
public ArrayList<RevCommit> call() throws IOException, MissingObjectException, GitAPIException {
    ArrayList<RevCommit> commits = new ArrayList<RevCommit>();
    git = new Git(repository);
    RevCommit start = null;
    do {
        Iterable<RevCommit> log = git.log().addPath(path).call();
        for (RevCommit commit : log) {
            if (commits.contains(commit)) {
                start = null;
            } else {
                start = commit;
                commits.add(commit);
            }
        }
        if (start == null) return commits;
    }
    while ((path = getRenamedPath( start)) != null);

    return commits;
}

Upvotes: 1

Related Questions