JGit and finding the Head

北城余情 提交于 2019-11-30 17:19:16

You need to point to the Git metadata directory (probably /www/test-repo/.git) when you call setGitDir, not to the working directory (/www/test-repo).

I have to admit I'm not sure what findGitDir is supposed to do, but I've run into this problem before and specifying the .git directory worked.

Ed Randall

For me (using 4.5.0.201609210915-r) the solution was to use just RepositoryBuilder instead of FileRepositoryBuilder. Until I made this change all methods were returning null.

rb = new org.eclipse.jgit.lib.RepositoryBuilder()
    .readEnvironment()
    .findGitDir()
    .build();

headRef = rb.getRef(rb.getFullBranch());
headHash = headRef.getObjectId().name();

You can also use val git: Git = Git.open( new File( "/www/test-repo" ) ). JGit will then scan the given folder for the git meta directory (usually .git). If it fails to find this folder, an IOException will be thrown.

For the completeness sake, here is a fully working example how to get the hash for the HEAD commit:

public String getHeadName(Repository repo) {
  String result = null;
  try {
    ObjectId id = repo.resolve(Constants.HEAD);
    result = id.getName();
  } catch (IOException e) {
    e.printStackTrace();
  }
  return result;
}
标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!