Git commands from Java | Java code to run git bash commands

Git is the version control utility used by a developer. Usually, we perform these commands using terminal or command prompt, but when we need to execute these commands in Java code or program? In this article, we will go through very simple basic examples of the JGIT library which is a fully-featured library to use GIT from within Java code programmatically.

Example in this article :

We will do all below steps programmatically through Java main code using JGIT.

  • Clone remote repository from into a local directory.
  • List all remote branches.
  • Checkout remote ‘develop’ branch into local directory repository.
  • Modify one file in local & verify git status.
  • Commit changes & verify commit log.
Git commands from Java

Dependency – To execute example in this article you will need maven dependency which you can refer from here.

<!-- -->

The remote repository used in example – This code uses this testing repository for example purposes. 

import java.nio.charset.Charset;
import java.util.Arrays;
import java.util.Optional;

import org.eclipse.jgit.api.Git;
import org.eclipse.jgit.api.ListBranchCommand.ListMode;
import org.eclipse.jgit.api.Status;
import org.eclipse.jgit.api.errors.GitAPIException;
import org.eclipse.jgit.api.errors.InvalidRemoteException;
import org.eclipse.jgit.api.errors.TransportException;
import org.eclipse.jgit.lib.Repository;
import org.eclipse.jgit.lib.TextProgressMonitor;
import org.eclipse.jgit.revwalk.RevCommit;


public class JGITExamples {

	public static void main(String[] args)
			throws IOException, InvalidRemoteException, TransportException, GitAPIException {

		// Local directory on this machine where we will clone remote repo.
		File localRepoDir = new File("C:\\Users\\Public\\JGIT_TESTING\\test");

		// Monitor to get git command progress printed on java System.out console
		TextProgressMonitor consoleProgressMonitor = new TextProgressMonitor(new PrintWriter(System.out));

		 * Git clone remote repo into local directory.
		 * Equivalent of --> $ git clone
		System.out.println("\n>>> Cloning repository\n");
		Repository repo = Git.cloneRepository().setProgressMonitor(consoleProgressMonitor).setDirectory(localRepoDir)

		try (Git git = new Git(repo)) {
			 * Get list of all branches (including remote) & print
			 * Equivalent of --> $ git branch -a
			System.out.println("\n>>> Listing all branches\n");
			git.branchList().setListMode(ListMode.ALL).call().stream().forEach(r  -> System.out.println(r.getName()));

			// Find develop branch from remote repo.
			Optional<String> developBranch = git.branchList().setListMode(ListMode.REMOTE).call().stream()
					.map(r -> r.getName()).filter(n -> n.contains("develop")).findAny();

			 * If develop branch present then checkout.
			 * Equivalent of --> $ git checkout -b local-develop /remotes/origin/develop
			if (developBranch.isPresent()) {
				System.out.println("\n>>> Checking out develop branch\n");

			// Modify one file & append a line
			System.out.println("\n>>> Modifying test.txt\n");
			File fileInDevelop =
					.filter(f -> f.getName().contains("test.txt")).findFirst().get();
			Files.asCharSink(fileInDevelop, Charset.defaultCharset(), FileWriteMode.APPEND).write("Added by Program");

			 * Check status of modified file.
			 * Equivalent of --> $ git status
			System.out.println("\n>>> Printing status of local repository\n");
			Status status = git.status().setProgressMonitor(consoleProgressMonitor).call();
			System.out.println("Modified file = " + status.getModified());

			 * Stage modified files and Commit changes .
			 * Equivalent of --> $ git commit -a
			System.out.println("\n>>> Committing changes\n");
			RevCommit revCommit = git.commit().setAll(true).setMessage("Adding commit from JGIT").call();
			System.out.println("Commit = " + revCommit.getFullMessage());

			 * Verify commit log
			 * Equivalent of --> $ git log
			System.out.println("\n>>> Printing commit log\n");
			Iterable<RevCommit> commitLog = git.log().call();
			commitLog.forEach(r -> System.out.println(r.getFullMessage()));



>>> Cloning repository
remote: Enumerating objects: 10
remote: Enumerating objects: 10
remote: Counting objects:  10% ( 1/10)
remote: Counting objects:  20% ( 2/10)
... Skipping logs for this article ...
Checking out files:     100% (3/3)
Checking out files:     100% (3/3)
>>> Listing all branches
>>> Checking out develop branch
Checking out files:     100% (1/1)
Checking out files:     100% (1/1)
>>> Modifying fileInDevelop.txt
>>> Printing status of local repository
Modified file = [test.txt]
>>> Committing changes
Commit = Adding commit from JGIT
>>> Printing commit log
Adding commit from JGIT
Create fileInDevelop.txt
Create fileInMaster.txt
Initial commit

Reference: Link

How to run git bash commands from Java?

To execute the git bash command from java you will need maven dependency org.eclipse.jgit which you can refer to here. This library is capable of performing all the git commands.


Leave a Reply

Your email address will not be published. Required fields are marked *

four × three =