簡體   English   中英

如何使用 JGit 檢查 Git 克隆是否已經完成

[英]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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM