Issue
I want to use/access/read file contents of files (excel, properties file, etc.) placed in a private gitlab repository in my java code, which would be creating a CSV file as output using the contents of the files from the private gitlab repository.
Solution
If the purpose of your Java application is to analyze/control git repositories, then it would make sense to perform the git operations in the JAR. Otherwise, consider calling a simple bash script from a CI/CD pipeline or user.
JGit
If your application will need to perform many git operations, JGit is a good option. You can include the dependency in maven or gradle.
Here's a simple code example to clone a specific branch:
import org.eclipse.jgit.api.Git;
import org.eclipse.jgit.api.errors.GitAPIException;
try {
Git.cloneRepository()
.setURI("https://github.com/account/repo.git")
.setDirectory(new File("/path/to/target_directory"))
.setBranchesToClone(Arrays.asList("refs/heads/branch-name"))
.setBranch("refs/heads/branch-name")
.call();
} catch (GitAPIException e) {
System.err.println("Exception occurred while cloning repo.");
e.printStackTrace();
}
Runtime exec
If you don't want the learning curve of using JGit, or don't want the external dependency, you can also call git commands using the Runtime exec
method. This requires that git be installed, accessible and authenticated on the host OS. Here's an example:
import java.io.*;
try {
String cmd = "git clone https://github.com/account/repo.git";
Process p = Runtime.getRuntime().exec(cmd);
}
catch(IOException e)
{
System.err.println("Exception occurred while executing command.");
e.printStackTrace();
}
Additional References:
- Looking for decent Git libraries for Java
- https://www.vogella.com/tutorials/JGit/article.html
- https://www.codeaffine.com/2014/12/09/jgit-authentication/
- https://github.com/centic9/jgit-cookbook/
- https://www.infoworld.com/article/2071275/when-runtime-exec---won-t.html
Answered By - DV82XL
Answer Checked By - Gilberto Lyons (JavaFixing Admin)