如何检查Git克隆是否已经完成JGit

Izz*_*zza 3 java git git-clone jgit

我学习git并使用JGit从java代码访问Git repos.默认情况下,Git不允许克隆到非空目录.我们怎么知道在本地机器上已经为一个特定的git repo做了一个git clone,这样我们以后只能做一个Git pull?

目前我正在使用这种方法:

 if a root folder is existing in the specified location
     clone has been done
     pull 
 else
     clone
Run Code Online (Sandbox Code Playgroud)

不确定这是否正确.有更好的想法吗?

谢谢.

Izz*_*zza 7

这是我使用的方法,如Jgit邮件列表中所指定的:

检查是否存在git存储库:

if (RepositoryCache.FileKey.isGitRepository(new File(<path_to_repo>), FS.DETECTED)) {

     // Already cloned. Just need to open a repository here.
} else {

     // Not present or not a Git repository.
}
Run Code Online (Sandbox Code Playgroud)

但这不足以检查git克隆是否"成功".部分克隆可以使isGitRepository()计算为true.要检查git克隆是否成功完成,至少需要检查一个引用是否为null:

private static boolean hasAtLeastOneReference(Repository repo) {

    for (Ref ref : repo.getAllRefs().values()) {
        if (ref.getObjectId() == null)
            continue;
        return true;
    }

    return false;
}
Run Code Online (Sandbox Code Playgroud)

谢谢Shawn Pearce的答案!

  • 我觉得这个答案并不完全完整。&lt;path_to_repo&gt; 需要包含 .git 目录,最有可能是 &lt;&lt;path_to_repo_git_dir&gt; 或 &lt;path_to_repo&gt;/.git。你可以通过查看源码直接看到git是如何使用这个方法的,它们传入的是.git目录:https://github.com/eclipse/jgit/blob/master/org.eclipse.jgit/src/org/ eclipse/jgit/lib/BaseRepositoryBuilder.java#L540 (2认同)