I am using the below code to clone a git repo from Java. I need to store the cloned latest revision hash.
localRepo = new FileRepository(path);
git = new Git(localRepo);
Git.cloneRepository().setURI(url).setBranch("master")
.setDirectory(new File(path)).call();
git.close();
Any clue on getting the revision hash here?
While cloning a repository with JGit isn’t particularly difficult, there are a few details that might be worth noting. And because there are few online resources on the subject, this article summarizes how to use the JGit API to clone from an existing Git repository.
A better method for getting the latest commit’s hash in Git is using the --format option of git log: Here, “%H” means “commit hash”. To get the latest git commit SHA-1 hash ID, use the git-rev-parse command like this:
There is no direct way to clone directly using the commit ID. But you can clone from a git tag. However, you can do the following workaround to perform a clone if it is really necessary. The above steps will make your current HEAD pointing to the specific commit id SHA.
And for the missing mirror option apparently a workaround exists. Only the often asked for shallow clones (e.g. git clone --depth 2) aren’t yet supported by JGit. The snippets shown throughout this article are excerpts from a learning test that illustrates the common use cases of the CloneCommand.
You can get a Ref
which contains the ObjectId
of HEAD
with the following:
Ref head = repository.getAllRefs().get("HEAD");
System.out.println("Ref of HEAD: " + head + ": " + head.getName() + " - " + head.getObjectId().getName());
This prints out something like this
Ref of HEAD: SymbolicRef[HEAD -> refs/heads/master=f37549b02d33486714d81c753a0bf2142eddba16]: HEAD - f37549b02d33486714d81c753a0bf2142eddba16
See also the related snippet in the jgit-cookbook
Instead of HEAD
, you can also use things like refs/heads/master
to get the HEAD
of the branch master
even if a different branch is checked out currently.
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