1

As the title says, I use Runtime.getRuntime().exec to execute git commit -m XXX command.

Unfortunately, it returns the unmormal exitcode with 1 (btw,the right code is 0).

I try to type the command on the command line,the commit command is working OK.

Anybody knows where the problem is?

public static int commit(String dir,String commitMsg) {
    String command = "git commit -m " + commitMsg;
    exitCode = ProcessUtil.safeSyncRun(command, dir);
    System.out.println(command + " exitcode = " + exitCode);
    return exitCode;
}
public static int safeSyncRun(String command, String workingDir) {
    Process process;
    int exitValue = -1;
    try {
        process = Runtime.getRuntime().exec(command, null, new File(workingDir));
        process.waitFor();
        exitValue = process.exitValue();
    } catch (IOException | InterruptedException e) {
        System.out.println("exception : " + e);
    }finally{
        process = null;
    }
    return exitValue;
}

Outputs below:

git commit -m test commit msg 
exitcode = 1
VonC
  • 1,262,500
  • 529
  • 4,410
  • 5,250
Ben
  • 11
  • 1
  • Did the commit actually occur? Do you have a post-commit hook or other hooks installed? – torek Nov 01 '18 at 15:28
  • nope,there is not some hooks installed. – Ben Nov 02 '18 at 07:31
  • OH!!! i know why the commit not worked. because the commitMsg i assgned has space identifier.so the whole commit command like this,git commit -m test commit msg.I try to update my code as below, public static int commit(String dir,String commitMsg) { String command = "git commit -m \'" + commitMsg + "\'"; exitCode = ProcessUtil.safeSyncRun(command, dir); System.out.println(command + " exitcode = " + exitCode); return exitCode; } it doesn‘t work either. why? – Ben Nov 02 '18 at 07:37
  • Well, now you're getting into questions about your language (Csharp? I don't know, you did not specify) and its `safeSyncRun` command. – torek Nov 02 '18 at 15:28

1 Answers1

1

Assuming you are using a bash, try instead (using "How can I debug git/git-shell related problems?"):

String command = "bash -c 'export GIT_TRACE=true; export GIT_TRACE_SETUP =true; git commit -m \"" + commitMsg + "\"'";

Note the \" around your commitMsg: that can help git commit interpret correctly your commit message.

VonC
  • 1,262,500
  • 529
  • 4,410
  • 5,250