我只想从Git存储库中检索commitlog,该存储库包含您在特定repopsitory上完成的所有提交的消息。我找到了一些用于实现此目的的代码片段,并以异常结束。
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<RevCommit> gitLog = git.log().call();
Iterator<RevCommit> 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
答案 0 :(得分:4)
这是正确的一段代码将做上述..
FileRepositoryBuilder builder = new FileRepositoryBuilder();
Repository repo = builder.setGitDir(new File("localrepositary"+"\\.git")).setMustExist(true).build();
Git git = new Git(repo);
Iterable<RevCommit> log = git.log().call();
for (Iterator<RevCommit> iterator = log.iterator(); iterator.hasNext();) {
RevCommit rev = iterator.next();
logMessages.add(rev.getFullMessage());
}
答案 1 :(得分:0)
如果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()
检查此存储库。
确保在完成使用后关闭存储库以避免泄漏文件句柄。