GIT Commands Using Java APIs

In previous posts, I’ve covered an Java API called JGIT for working with GIT. Besides the low level APIs, JGIT also supports high level command line like interfaces. If you know how to use the GIT command line, you can use the APIs. Note that it’s different from calling GIT commands or any other commands from Java code.

Here is a sample code I wrote to try out the APIs. Give it a try and you will like these high level APIs.

Bothered by SLOW Web UI to manage vSphere? Want to manage ALL your VMware vCenters, AWS, Azure, Openstack, container behind a SINGLE pane of glass? Want to search, analyze, report, visualize VMs, hosts, networks, datastores, events as easily as Google the Web? Find out more about vSearch 3.0: the search engine for all your private and public clouds.

import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.util.Collection;
import java.util.Iterator;

import org.eclipse.jgit.api.AddCommand;
import org.eclipse.jgit.api.CommitCommand;
import org.eclipse.jgit.api.Git;
import org.eclipse.jgit.api.InitCommand;
import org.eclipse.jgit.api.ReflogCommand;
import org.eclipse.jgit.api.errors.ConcurrentRefUpdateException;
import org.eclipse.jgit.api.errors.GitAPIException;
import org.eclipse.jgit.api.errors.NoHeadException;
import org.eclipse.jgit.api.errors.NoMessageException;
import org.eclipse.jgit.api.errors.UnmergedPathsException;
import org.eclipse.jgit.api.errors.WrongRepositoryStateException;
import org.eclipse.jgit.revwalk.RevCommit;
import org.eclipse.jgit.storage.file.ReflogEntry;

public class JGitSample
{
  public static void main(String[] args) throws Exception
  {
    File gitWorkDir = new File("C:/temp/gittest/");
    Git git = null;

    InitCommand initCommand = Git.init();
    initCommand.setDirectory(gitWorkDir);
    git = initCommand.call();

    git = Git.open(gitWorkDir); // not necessary, but show how to open an existing repo
	
    changeContentAndCommit(git, "DoubleCloud.org rocks!", "first commit");
    changeContentAndCommit(git, "DoubleCloud.org really rocks!", "second commit");
    changeContentAndCommit(git, "DoubleCloud.org really really rocks!", "third commit");
	
    Iterator<RevCommit> iterator = git.log().call().iterator();

    RevCommit rc2 = iterator.next();
    System.out.println("msg2:" + rc2.getFullMessage());
    System.out.println("con2:" + new String(rc2.getRawBuffer()));
    System.out.println("msg1:" + iterator.next().getFullMessage());
	
    ReflogCommand reflogCmd = git.reflog();
    Collection<ReflogEntry> reflogs = reflogCmd.call();
    System.out.println("size of reflogs:" + reflogs.size());
  }

  private static void changeContentAndCommit(Git git, String content, String message) throws NoHeadException, NoMessageException, UnmergedPathsException, ConcurrentRefUpdateException, WrongRepositoryStateException, GitAPIException 
  {
    File workDir = git.getRepository().getWorkTree();
    File myfile = new File(workDir, "file1.txt");
    writeToFile(myfile, content);

    AddCommand add = git.add();
    add.addFilepattern(".").call();

    CommitCommand commit = git.commit();
    commit.setMessage(message).call();
  }


  public static void writeToFile(File file, String text)
  {
    FileWriter writer;
    try
    {
	    writer = new FileWriter(file);
	    writer.write(text);
	    writer.close();
    }
    catch (IOException e)
    {
      e.printStackTrace();
    }
  }
}

This entry was posted in Software Development and tagged , . Bookmark the permalink. Post a comment or leave a trackback: Trackback URL.

9 Comments

  1. Posted March 26, 2013 at 1:30 am | Permalink

    GIT Commands Using Java APIs (DoubleCloud) http://t.co/5hEqD4liTq

  2. shasu
    Posted July 18, 2013 at 7:35 am | Permalink

    While i am reading from a Repository using JGIT me getting following error.

    Exception in thread “main” java.lang.ArrayIndexOutOfBoundsException: -20
    at org.eclipse.jgit.util.NB.decodeInt32(NB.java:96)
    at org.eclipse.jgit.lib.ObjectId.fromRaw(ObjectId.java:175)
    at org.eclipse.jgit.treewalk.AbstractTreeIterator.getEntryObjectId(AbstractTreeIterator.java:400)
    at org.eclipse.jgit.treewalk.TreeWalk.getObjectId(TreeWalk.java:654)
    at JGitPrintContent2.main(JGitPrintContent2.java:72)

    could you help

  3. shasu
    Posted July 18, 2013 at 7:37 am | Permalink

    Where can i get some good number of documentations or samples of JGIT .
    Can you please suggest me ?

    Thank you.

  4. Posted July 18, 2013 at 1:38 pm | Permalink

    I guess the index used to get element of an array is out of range. You may want to check the value passed in.

    Steve

  5. Posted July 18, 2013 at 1:40 pm | Permalink

    It’s pretty hard to find samples and docs. I remember there are some unit test code that can serve as samples. You can search them over the Internet.
    Steve

  6. Jgit API User
    Posted July 29, 2013 at 4:19 am | Permalink

    Hi ,
    the example above commits a file , recommits it and we get the UID . the content can be accessed withthe corresponding UID . but i have to commit more than 1 file at a time . the respective UId are also obtaine d. but while reading the repository to retrieve the files , even on giving different UId’s i am getting the same file . to be correct the first file only. please help .

  7. sashu
    Posted July 29, 2013 at 7:24 am | Permalink

    how to commit more than 1 file in the repository. and retrieve the files by their individual commit ids.

  8. michael
    Posted August 5, 2013 at 1:58 am | Permalink

    hi Steve Jin,
    waiting for your help . please let us know how to commit more than 1 file at a time in the repository.and retrieve them individually by respective commit id’s

  9. Posted August 12, 2013 at 2:05 am | Permalink

    Hi Michael,

    I think committing more than one file has its corresponding command and thus Java APIs. To retrieve individually you may want to do more research. I haven’t touched the API for a while.

    Steve

One Trackback

  • By Tofa IT » GIT Commands Using Java APIs on March 26, 2013 at 11:19 am

    […] can use the APIs. Note that it’s different from calling GIT commands or any other commands […]GIT Commands Using Java APIs originally appeared on DoubleCloud by Steve Jin, author of VMware VI and vSphere SDK (Prentice […]

Post a Comment

Your email is never published nor shared. Required fields are marked *

*
*

You may use these HTML tags and attributes <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <s> <strike> <strong>

  • NEED HELP?


    My company has created products like vSearch ("Super vCenter"), vijavaNG APIs, EAM APIs, ICE tool. We also help clients with virtualization and cloud computing on customized development, training. Should you, or someone you know, need these products and services, please feel free to contact me: steve __AT__ doublecloud.org.

    Me: Steve Jin, VMware vExpert who authored the VMware VI and vSphere SDK by Prentice Hall, and created the de factor open source vSphere Java API while working at VMware engineering. Companies like Cisco, EMC, NetApp, HP, Dell, VMware, are among the users of the API and other tools I developed for their products, internal IT orchestration, and test automation.