JGit and finding the Head

戏子无情 提交于 2019-11-30 01:02:26

问题


I'm trying to get my hands on the HEAD commit with JGit:

val builder = new FileRepositoryBuilder()
val repo = builder.setGitDir(new File("/www/test-repo"))
  .readEnvironment()
  .findGitDir()
  .build()

val walk: RevWalk = new RevWalk(repo, 100)

val head: ObjectId = repo.resolve(Constants.HEAD)
val headCommit: RevCommit = walk.parseCommit(head)

I find that it opens the repo fine, but head value is set to null. I wonder why it can't find HEAD?

I'm reading this documentation: http://wiki.eclipse.org/JGit/User_Guide

The repository is constructed just like the doc says, and the RevWalk as well. I'm using the latest version of JGit which is 2.0.0.201206130900-r from http://download.eclipse.org/jgit/maven.

My question: what do I need to change in my code to get JGit to return actual instances of RevCommit instead of null like it now does?

Update: This code:

val git = new Git(repo)
val logs: Iterable[RevCommit] = git.log().call().asInstanceOf[Iterable[RevCommit]]

Gives me this exception: No HEAD exists and no explicit starting revision was specified

The exception is odd, because a simple git rev-parse HEAD tells me 0b0e8bf2cae9201f30833d93cc248986276a4d75, which means there is a HEAD in the repository. I've tried different repositories, mine and from other people.


回答1:


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.




回答2:


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();



回答3:


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.




回答4:


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;
}


来源:https://stackoverflow.com/questions/12342152/jgit-and-finding-the-head

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!