Start GitLog with Java Process Builder

2019-07-27 02:11发布

I try to start a GitLog command via Processbuilder in Java.

GitLog Command :

git --git-dir=C:/Users/User/Code/code1/git/.git log --pretty=format:"%H \"%an\" %ad \"%s\"" --numstat --date=short

This is my code. The Path is the path to the git dir. I hardcoded the gitpath to the git dir for testing.

public void createGitLog( Path path ) {
            try
            {          
                String gitpath = "--git-dir=C:/Users/User/Code/code1/git/.git";
                String options = "--pretty=format:\"%H \\\"%an\\\" %ad \\\"%s\\\"\" --numstat --date=short";

                ProcessBuilder builder = new ProcessBuilder("git", gitpath, "log", options );
                Process process = builder.start();

                builder.redirectOutput(ProcessBuilder.Redirect.to( path.resolve("gitlog.dat").toFile() ) );

                int exitValue = process.waitFor();

                if ( exitValue != 0 )
                {
                    // throw
                }
            }
            catch (IOException e) {

            } 
}

If i try this command in the cmd it works, but in Java I get always the exitcode 128.

What is the Problem with this process ?

1条回答
地球回转人心会变
2楼-- · 2019-07-27 02:52

That what works in my case to run commands in terminal:

"/bin/bash" - path to your bash

"-c" - states that next param is command

"command" - full command you want to execute from terminal (like git log --pretty=format:"%H \"%an\" %ad \"%s\"" --numstat --date=short)

String command = "git " + gitpath + " log " + options;
ProcessBuilder builder = new ProcessBuilder("/bin/bash" , "-c" , command);

you can also use on ProcessBuilder directory() if you want to start process from specific dir;

 .directory(new File("C:/Users/User/Code/code1/git/"))
查看更多
登录 后发表回答