[英]How to Check if A Git Clone Has Been Done Already with JGit
我学习 git 并使用 JGit 从 Java 代码访问 Git 存储库。 Git 默认不允许克隆到非空目录。 我们如何确定本地机器中的特定 git repo 已经完成了 git clone,以便我们随后只能进行 Git pull?
目前我正在使用这种方法:
if a root folder is existing in the specified location
clone has been done
pull
else
clone
虽然不确定这是否正确。 有什么更好的想法吗?
谢谢你。
这是我使用的方法,如 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.
}
但这不足以检查 git clone 是否“成功”。 部分克隆可能会使 isGitRepository() 评估为真。 要检查 git clone 是否成功完成,至少需要检查一个引用是否不为空:
private static boolean hasAtLeastOneReference(Repository repo) {
for (Ref ref : repo.getAllRefs().values()) {
if (ref.getObjectId() == null)
continue;
return true;
}
return false;
}
感谢肖恩皮尔斯的回答!
另一种方法是使用 JGit FileRepositoryBuilder 类。
public boolean repositoryExists(File directory) {
boolean gitDirExists = false;
FileRepositoryBuilder repositoryBuilder = new FileRepositoryBuilder();
repositoryBuilder.findGitDir(directory);
if (repositoryBuilder.getGitDir() != null) {
gitDirExists = true;
}
return gitDirExists;
}
该解决方案间接使用与接受的答案相同的解决方案,但它删除了 RepositoryCache、FileKey 和 FS(文件系统)的直接使用。 虽然这些类在范围内是公开的,但它们感觉相当低级,并且个人让我感到不舒服。
我不记得我们想出了这个解决方案。 它可能来自How to Access a Git Repository with JGit 。
@Izza 的回答中提到的技巧对我不起作用。 我宁愿这样做:
Java示例:
import org.eclipse.jgit.api.Git
import org.eclipse.jgit.lib.Repository
boolean isRepo(String fileDir) {
try {
Git Git = Git.open(new File(fileDir));
Repository repo = jGIt.getRepository();
for (Ref ref : repo.getAllRefs().values()) {
if (ref.getObjectId() == null)
continue;
return true;
}
return false;
} catch(Exception e) {
return false;
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.