JGit并找到了头

我正试图通过JGit获取HEAD提交:

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) 

我发现它打开了repo罚款,但是head值设置为null 。 我想知道为什么它找不到HEAD?

我正在阅读此文档: http : //wiki.eclipse.org/JGit/User_Guide

存储库的构造与doc所说的一样,以及RevWalk 。 我正在使用最新版本的JGit,它是来自http://download.eclipse.org/jgit/maven的 2.0.0.201206130900-r

我的问题:我需要在代码中进行哪些更改才能让JGit返回RevCommit实际实例,而不是像现在这样返回null

更新:此代码:

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

给我这个例外: No HEAD exists and no explicit starting revision was specified

exception是奇怪的,因为简单的git rev-parse HEAD告诉我0b0e8bf2cae9201f30833d93cc248986276a4d75 ,这意味着存储库中有一个HEAD。 我尝试了不同的存储库,我和其他人。

调用setGitDir ,需要指向Git元数据目录(可能是/www/test-repo/.git ),而不是工作目录( /www/test-repo )。

我不得不承认我不确定findGitDir应该做什么,但我之前遇到过这个问题并且指定了.git目录。

对我来说(使用4.5.0.201609210915-r)解决方案是仅使用RepositoryBuilder而不是FileRepositoryBuilder 。 在我进行此更改之前,所有方法都返回null

 rb = new org.eclipse.jgit.lib.RepositoryBuilder() .readEnvironment() .findGitDir() .build(); headRef = rb.getRef(rb.getFullBranch()); headHash = headRef.getObjectId().name(); 

你也可以使用val git: Git = Git.open( new File( "/www/test-repo" ) ) 。 然后,JGit将扫描给定文件夹中的git元目录(通常为.git )。 如果找不到此文件夹,将抛出IOException

为了完整起见,这里有一个完整的工作示例如何获取HEAD提交的哈希:

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