Skip to content

Instantly share code, notes, and snippets.

@Crydust
Last active November 8, 2023 16:40
Show Gist options
  • Star 20 You must be signed in to star a gist
  • Fork 7 You must be signed in to fork a gist
  • Save Crydust/fd1b94afc52cd0f7dd4c to your computer and use it in GitHub Desktop.
Save Crydust/fd1b94afc52cd0f7dd4c to your computer and use it in GitHub Desktop.
run git commands from java
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.Objects;
public class Git {
// example of usage
private static void initAndAddFile() throws IOException, InterruptedException {
Path directory = Paths.get("c:\\temp\\example");
Files.createDirectories(directory);
gitInit(directory);
Files.write(directory.resolve("example.txt"), new byte[0]);
gitStage(directory);
gitCommit(directory, "Add example.txt");
}
// example of usage
private static void cloneAndAddFile() throws IOException, InterruptedException {
String originUrl = "https://github.com/Crydust/TokenReplacer.git";
Path directory = Paths.get("c:\\temp\\TokenReplacer");
gitClone(directory, originUrl);
Files.write(directory.resolve("example.txt"), new byte[0]);
gitStage(directory);
gitCommit(directory, "Add example.txt");
gitPush(directory);
}
public static void gitInit(Path directory) throws IOException, InterruptedException {
runCommand(directory, "git", "init");
}
public static void gitStage(Path directory) throws IOException, InterruptedException {
runCommand(directory, "git", "add", "-A");
}
public static void gitCommit(Path directory, String message) throws IOException, InterruptedException {
runCommand(directory, "git", "commit", "-m", message);
}
public static void gitPush(Path directory) throws IOException, InterruptedException {
runCommand(directory, "git", "push");
}
public static void gitClone(Path directory, String originUrl) throws IOException, InterruptedException {
runCommand(directory.getParent(), "git", "clone", originUrl, directory.getFileName().toString());
}
public static void runCommand(Path directory, String... command) throws IOException, InterruptedException {
Objects.requireNonNull(directory, "directory");
if (!Files.exists(directory)) {
throw new RuntimeException("can't run command in non-existing directory '" + directory + "'");
}
ProcessBuilder pb = new ProcessBuilder()
.command(command)
.directory(directory.toFile());
Process p = pb.start();
StreamGobbler errorGobbler = new StreamGobbler(p.getErrorStream(), "ERROR");
StreamGobbler outputGobbler = new StreamGobbler(p.getInputStream(), "OUTPUT");
outputGobbler.start();
errorGobbler.start();
int exit = p.waitFor();
errorGobbler.join();
outputGobbler.join();
if (exit != 0) {
throw new AssertionError(String.format("runCommand returned %d", exit));
}
}
private static class StreamGobbler extends Thread {
private final InputStream is;
private final String type;
private StreamGobbler(InputStream is, String type) {
this.is = is;
this.type = type;
}
@Override
public void run() {
try (BufferedReader br = new BufferedReader(new InputStreamReader(is));) {
String line;
while ((line = br.readLine()) != null) {
System.out.println(type + "> " + line);
}
} catch (IOException ioe) {
ioe.printStackTrace();
}
}
}
}
@bhaskara1017
Copy link

Can you send me what is Path directory variable data?
If possible Can you please give the git clone commands, when in the command line it asks me password
command line command example : git clone http://username@bitbucket/scm/cicd/bitbucketprereceiveplugin.git
I need to execute above command using the processBuilder

@mrobiramapulana
Copy link

Hey. i want to use this code but i dnt know where is the git clone part

@mrobiramapulana
Copy link

How to i use this code

@s5ujit
Copy link

s5ujit commented Apr 8, 2020

While calling any method (gitInit,gitPsuh,gitCommit etc) getting below error : Direct is already present in system
CreateProcess error=2, The system cannot find the file specified

@WemersonThayne
Copy link

Can you send me what is Path directory variable data? If possible Can you please give the git clone commands, when in the command line it asks me password command line command example : git clone http://username@bitbucket/scm/cicd/bitbucketprereceiveplugin.git I need to execute above command using the processBuilder

I create method like this for push when need authenticate in repository

public static void gitPushWithTokenAuth(Path directory,String remoteRepository, String userName, String acessToken) throws IOException, InterruptedException { runCommand(directory, "git", "push", "https://"+userName+":"+acessToken+"@"+remoteRepository, "--all"); }

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment