How to clone a Git repository programmatically using Java

Views: 384   

JGit (https://eclipse.org/jgit/) is a library developed by Eclipse team and it implements the Git version control system. So let's start with adding the JGit dependency.

Dependencies

If you are using Gradle you can add the following into dependencies section of your build.gradle file

// https://mvnrepository.com/artifact/org.eclipse.jgit/org.eclipse.jgit
compile group: 'org.eclipse.jgit', name: 'org.eclipse.jgit', version: '4.8.0.201706111038-r'

If you are using maven add the following dependency to your pon.xml

<!-- https://mvnrepository.com/artifact/org.eclipse.jgit/org.eclipse.jgit -->
<dependency>
    <groupId>org.eclipse.jgit</groupId>
    <artifactId>org.eclipse.jgit</artifactId>
    <version>4.8.0.201706111038-r</version>
</dependency>

Using JGit to checkout code

Now using the following code you can checkout a repository

String repoUrl = "https://github.com/fastfoodcoding/SpringBootMongoDbCRUD.git";
String cloneDirectoryPath = "/path/to/directory/"; // Ex.in windows c:\\gitProjects\SpringBootMongoDbCRUD\
try {
    System.out.println("Cloning "+repoUrl+" into "+repoUrl);
    Git.cloneRepository()
        .setURI(repoUrl)
        .setDirectory(Paths.get(cloneDirectoryPath).toFile())
        .call();
    System.out.println("Completed Cloning");
} catch (GitAPIException e) {
    System.out.println("Exception occurred while cloning repo");
    e.printStackTrace();
}
On By