Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JGit Clone and get the revision hash

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?

like image 988
Upen Avatar asked Oct 13 '15 18:10

Upen


People also ask

How difficult is it to clone a git repository with JGit?

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.

How to get the latest commit hash in Git?

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:

How do I clone a specific commit in Git?

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.

Does JGit support mirror clones?

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.


1 Answers

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.

like image 85
centic Avatar answered Oct 19 '22 09:10

centic