In this article we will go through very simple basic examples of JGIT library which is 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 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.
Remote repository used in example – This code uses this test repository for example purposes. Ravikharatmal/test
JGIT Examples code
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 |
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/Ravikharatmal/test.git */ System.out.println("\n>>> Cloning repository\n"); Repository repo = Git.cloneRepository().setProgressMonitor(consoleProgressMonitor).setDirectory(localRepoDir) .setURI("https://github.com/Ravikharatmal/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 fileInDevelop.txt\n"); File fileInDevelop = Arrays.stream(localRepoDir.listFiles()) .filter(f -> f.getName().contains("fileInDevelop.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())); } } } |
Console Output
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 |
>>> 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 = [fileInDevelop.txt] >>> Committing changes Commit = Adding commit from JGIT >>> Printing commit log Adding commit from JGIT Create fileInDevelop.txt Create fileInMaster.txt Initial commit |
Verification
As you can see here, we can see repository has been cloned. There are no uncommitted files which means JGIT commit is successful. (Green checkmark icons are added by Tortoise Git).
Here is a quick verification from command line in this directory and you can see the modified file content from code. You can also see that recent commit has been made from JGIT code.
Interesting. If it is a private repo then how do we pass the SSH_KEY or personal access token during a checkout/checkin – Could you also include details around this?
Hi,
How to commit to an existing branch instead of creating new branch and push to repo??