How to Check if A Git Clone Has Been Done Already with JGit

白昼怎懂夜的黑 提交于 2019-12-22 10:58:43

问题


I learning git and using JGit to access Git repos from java code. Git by default does not allow to clone to a non-empty directory. How do we figure out that a git clone has already been done for a particular git repo in the local machine so that we can only do a Git pull subsequently?

Currently I'm using this approach:

 if a root folder is existing in the specified location
     clone has been done
     pull 
 else
     clone

Not sure if this is correct though. Any better ideas?

Thank you.


回答1:


This is the approach I used, as specified in the Jgit mailing list:

Check if a git repository is existing:

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.
}

But this is insufficient to check if the git clone was 'successful'. A partial clone could make isGitRepository() evaluate to true. To check if the git clone was done successfully, need to check at least if one reference is not null:

private static boolean hasAtLeastOneReference(Repository repo) {

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

    return false;
}

Thanks Shawn Pearce for the answer!



来源:https://stackoverflow.com/questions/13586502/how-to-check-if-a-git-clone-has-been-done-already-with-jgit

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!