jGit - pure Java library implementing Git

Today we have a quick glimpse at JGit.

JGit is an EDL (new-style BSD) licensed, lightweight, pure Java library implementing the Git version control system:

  • repository access routines
  • network protocols
  • core version control algorithms

Let's create a local directory to work with:

File workingDir = File.createTempFile("GitWorkingDirectory", "");

and clone (without checkout - we want to grab single files later)

try (Git git = Git.cloneRepository()
    .setURI("git://git.eclipse.org/gitroot/virgo/org.eclipse.virgo.root.git")
    .setNoCheckout(true)
    .setDirectory(workingDir)
    .call()) {

  ... work with the Git repository
}

As mentioned above we want the content of a single file as OutputStream:

private static void streamRemoteFile(OutputStream outStream, Git git) {
  try (TreeWalk walk = new TreeWalk(git.getRepository());
  RevWalk rw = new RevWalk(walk.getObjectReader())) {

    walk.reset(rw.parseTree(git.getRepository().resolve("origin/master")));
    walk.setFilter(createFromStrings(singletonList("README.md")));

    while (walk.next()) {
      String name = walk.getPathString();
      FileMode mode = walk.getFileMode(0);

      if (walk.isSubtree())
        walk.enterSubtree();

      if (mode == FileMode.TREE) {
        continue;  // skip directories
      }

      MutableObjectId idBuf = new MutableObjectId();
      ObjectReader reader = walk.getObjectReader();

      walk.getObjectId(idBuf, 0);
      reader.open(idBuf).copyTo(outStream);
    }
  } catch (IOException e) {
      throw new RuntimeException("Failed to open remote stream...");
  }
}

With the ArchiveCommand available via Git.archive we can get the content as archive:

try (Git git = new Git( repository )) {
  git.archive()
    .setPaths( "README.md" )
    .setTree( git.getRepository()
    .resolve( "origin/" + context.getJobConfiguration().getGitConfiguration().getBranch() ) )
    .setOutputStream( createTempFile("archive", ".zip") )
    .setFormat( "zip" )
    .call();
  ....
}

For more examples see centic9/jgit-cookbook.