Skip to content

Instantly share code, notes, and snippets.

@rgpower
Created December 15, 2020 19:06
Show Gist options
  • Save rgpower/0c084ce4f64e878cb74cfd79fa2995b7 to your computer and use it in GitHub Desktop.
Save rgpower/0c084ce4f64e878cb74cfd79fa2995b7 to your computer and use it in GitHub Desktop.
Use JGit to grab latest commit from a git working directory, and detect local changes
package utils.git;
import org.eclipse.jgit.api.Git;
import org.eclipse.jgit.api.errors.GitAPIException;
import org.eclipse.jgit.lib.Repository;
import org.eclipse.jgit.lib.RepositoryBuilder;
import org.eclipse.jgit.revwalk.RevCommit;
import java.io.File;
import java.io.IOException;
public class GitUtils {
public static String getLatestCommitId(File workingDir) {
String latestCommitId;
try {
RepositoryBuilder repositoryBuilder = new RepositoryBuilder();
repositoryBuilder.setMustExist(true);
repositoryBuilder.setWorkTree(workingDir);
repositoryBuilder.setGitDir(new File(workingDir, ".git"));
Repository repository = repositoryBuilder.build();
Git git = Git.wrap(repository);
Iterable<RevCommit> commits = git.log().setMaxCount(1).call();
RevCommit headCommit = commits.iterator().next();
latestCommitId = headCommit.abbreviate(7).name();
if (!git.status().call().isClean()) {
latestCommitId += "-with-local-changes";
}
} catch (IOException | GitAPIException e) {
throw new RuntimeException(e);
}
return latestCommitId;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment