Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JGit detect rename in working copy

Tags:

java

git

jgit

Contex

I'm trying to detect possible file rename that occurred after last commit, in a working copy. On my example, I have a clean working copy and I do that:

git mv old.txt new.txt

Running $ git status shows the expected result:

# Changes to be committed:
#   (use "git reset HEAD <file>..." to unstage)
#
#       renamed:    old.txt -> new.txt

I tried

Using a StatusCommand, I can see old.txt in the removed list, and new.txt in the added list. But I can't find a way to link them together.

I'm aware of the existence of RenameDetector, but it works using DiffEntry, and I don't know how to get DiffEntries between HEAD and the Working Copy.

like image 258
Serge Farny Avatar asked Jun 25 '13 11:06

Serge Farny


1 Answers

Never mind, found the answer. JGit's API is very complicated..

TreeWalk tw = new TreeWalk(repository);
tw.setRecursive(true);
tw.addTree(CommitUtils.getHead(repository).getTree());
tw.addTree(new FileTreeIterator(repository));

RenameDetector rd = new RenameDetector(repository);
rd.addAll(DiffEntry.scan(tw));

List<DiffEntry> lde = rd.compute(tw.getObjectReader(), null);
for (DiffEntry de : lde) {
    if (de.getScore() >= rd.getRenameScore()) {
        System.out.println("file: " + de.getOldPath() + " copied/moved to: " + de.getNewPath());
    }
}

(This snippet also use Gitective library)

like image 121
Serge Farny Avatar answered Sep 28 '22 17:09

Serge Farny