使用JGit从Git检索提交消息日志
我只想从Git存储库中检索commitlog,该存储库包含您在特定repopsitory上完成的所有提交的消息。 我找到了一些用于实现此目的的代码片段,并以exception结束。
try { FileRepositoryBuilder builder = new FileRepositoryBuilder(); Repository repo = builder.setGitDir(new File("https://github.com/name/repository.git")).readEnvironment().findGitDir().build(); RevWalk walk =new RevWalk(repo); ObjectId head = repo.resolve(Constants.HEAD); RevCommit commit =walk.parseCommit(head); Git git =new Git(repo); Iterable gitLog = git.log().call(); Iterator it = gitLog.iterator(); while(it.hasNext()) { RevCommit logMessage = it.next(); System.out.println(logMessage.getFullMessage()); } } catch(Exception e) { e.printStackTrace(); }
但它给了我:
org.eclipse.jgit.api.errors.NoHeadException: No HEAD exists and no explicit starting revision was specified exception.
我怎么摆脱这个? 我正在使用org.eclipse.jgit JAR版本2.0.0.201206130900-r
这是正确的一段代码将做上述..
FileRepositoryBuilder builder = new FileRepositoryBuilder(); Repository repo = builder.setGitDir(new File("localrepositary"+"\\.git")).setMustExist(true).build(); Git git = new Git(repo); Iterable log = git.log().call(); for (Iterator iterator = log.iterator(); iterator.hasNext();) { RevCommit rev = iterator.next(); logMessages.add(rev.getFullMessage()); }
如果https://github.com/name/repository.git
是您要从中获取日志的存储库的URL,则必须首先克隆它:
CloneCommand cloneCommand = Git.cloneRepository(); cloneCommand.setDirectory( new File( "/path/to/local/repo" ) ); cloneCommand.setURI( "https://github.com/name/repository.git" ); Git git = cloneCommand.call(); ... git.getRepository().close();
这将在/path/to/local/repo
创建远程存储库的本地克隆。 请注意,在调用cloneCommand之前, repo
目录必须不存在或为空。 然后可以使用git.log()
检查此存储库。
完成使用后,请务必关闭存储库以避免泄漏文件句柄。