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.
Open Github, find your repo, click on it. Then click on Insights and finally click on Traffic. Github shows a graph Traffic including git clones.
Cloning an entire repo is standard operating procedure using Git. Each clone usually includes everything in a repository. That means when you clone, you get not only the files, but every revision of every file ever committed, plus the history of each commit.
build(); Git git = new Git(repository); CloneCommand clone = git. cloneRepository(); clone. setBare(false); clone. setCloneAllBranches(true); clone.
When you clone a repository, you copy the repository from GitHub.com to your local machine. Cloning a repository pulls down a full copy of all the repository data that GitHub.com has at that point in time, including all versions of every file and folder for the project.
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!
A different approach would be to use the JGit FileRepositoryBuilder class.
public boolean repositoryExists(File directory) {
boolean gitDirExists = false;
FileRepositoryBuilder repositoryBuilder = new FileRepositoryBuilder();
repositoryBuilder.findGitDir(directory);
if (repositoryBuilder.getGitDir() != null) {
gitDirExists = true;
}
return gitDirExists;
}
This solution indirectly uses the same solution as the accepted answer, but it removes the direct usage of the RepositoryCache, FileKey and FS (FileSystem). While those classes are public in scope, they feel fairly low level and personally make me feel uneasy to use.
I do not remember exactly we came up with this solution. It might be from How to Access a Git Repository with JGit.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With