Start GitLog with Java Process Builder

蹲街弑〆低调 提交于 2019-12-13 17:18:36

问题


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:


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/"))


来源:https://stackoverflow.com/questions/44407664/start-gitlog-with-java-process-builder

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!