11

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?

Upen
  • 1,388
  • 1
  • 22
  • 49
  • Do you mean the revision hash of the `master` branch? – Rüdiger Herrmann Oct 14 '15 at 08:30
  • Yes Rudiger. The latest cloned hash, like we see in jenkins. – Upen Oct 14 '15 at 17:29
  • There is no such thing as the 'latest cloned hash'. A repository may have many _refs_ (branches, tags, etc.) that all point to a commit. To get the commit hash of a ref, refer to the answer given by [centic](http://stackoverflow.com/users/411846/centic). Usally you would want to get the commit hash of `HEAD`. If you need to know the hash of the _youngest_ commit in a repository, let me know and I will assemble an answer of how to find the newest commit among the known refs. – Rüdiger Herrmann Oct 14 '15 at 19:31
  • I would always be cloning the master. So guess I can use "refs/heads/master". Tried out centric's answer. Head is showing up as null. Appreciate if you could show me a way to get the hash of the youngest commit. I am using this for a release management process. Hash would help me identify the present production code. – Upen Oct 14 '15 at 20:49
  • The 'present production code' should always be referenced through a distinct ref, e.g. `refs/heads/master`. Or whatever the designated target is that developers push to when they want to release something. Hence [centic](http://stackoverflow.com/users/411846/centic)s answer should do. – Rüdiger Herrmann Oct 14 '15 at 20:57

1 Answers1

11

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.

tlevasseur
  • 15
  • 1
  • 8
centic
  • 15,565
  • 9
  • 68
  • 125
  • localRepo = new FileRepository(path); git = new Git(localRepo); Git clone = Git.cloneRepository().setURI(url).setBranch(branch) .setDirectory(new File(path)).call(); Ref head = localRepo.getRef("refs/heads/master");Head is null showing up as null. Am I doing something wrong? – Upen Oct 14 '15 at 19:14
  • works now. I made a mistake constructing the repository. – Upen Oct 14 '15 at 21:09