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 https://github.com 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.
Dependency – To execute example in this article you will need maven dependency which you can refer from here.
<!-- https://mvnrepository.com/artifact/org.eclipse.jgit/org.eclipse.jgit --> <dependency> <groupId>org.eclipse.jgit</groupId> <artifactId>org.eclipse.jgit</artifactId> <version>5.10.0.202012080955-r</version> </dependency>
The remote repository used in example – This code uses this testing repository for example purposes.
deepanshujain92/test_git
import java.io.File; import java.io.IOException; import java.io.PrintWriter; 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; import com.google.common.io.FileWriteMode; import com.google.common.io.Files; 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 https://github.com/deepanshujain92/test_git.git */ System.out.println("\n>>> Cloning repository\n"); Repository repo = Git.cloneRepository().setProgressMonitor(consoleProgressMonitor).setDirectory(localRepoDir) .setURI("https://github.com/deepanshujain92/test_git").call().getRepository(); 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"); git.checkout().setProgressMonitor(consoleProgressMonitor).setCreateBranch(true).setName("local-develop") .setStartPoint(developBranch.get()).call(); } // Modify one file & append a line System.out.println("\n>>> Modifying test.txt\n"); File fileInDevelop = Arrays.stream(localRepoDir.listFiles()) .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 refs/heads/master refs/remotes/origin/develop refs/remotes/origin/master >>> 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.