Search code examples
javagitcommandprocessbuilder

How to feed in the password while executing "git fetch -v --progress <baseURL> <releaseBranch>" from ProcessBuilder in java


This program doesn't allow to enter the password, it basically hangs while reading commands output through Scanner. Basically I am trying to fetch a branch from git repository.

    ProcessBuilder builder = new ProcessBuilder( "cmd" );
    builder.redirectErrorStream(true);
    Process process = null;
    try {
        process = builder.start();
    } catch (IOException e) {
        e.printStackTrace();
    }

    //get stdin of cmd
    BufferedWriter p_stdin = new BufferedWriter(new OutputStreamWriter(process.getOutputStream()));

    // execute the desired command from list
    List<String> cmdList = new ArrayList<String>();
    String baseURL= "abc@xyz.com/a/b";
    cmdList.add("cd c:\rep\project");
    cmdList.add(String.format("git fetch -v --progress %s releaseBranch", baseURL));
    cmdList.add("exit");

    for (String cmd : cmdList) {
        try {
            //single execution
            p_stdin.write(cmd);
            p_stdin.newLine();
            p_stdin.flush();

            if(cmd.startsWith("git fetch")) {
                //process.waitFor();
                //p_stdin.wait();
                p_stdin.write("XXXXX@xxx");             
                p_stdin.newLine();
                p_stdin.flush();
            }

        } catch (IOException e) {
            System.out.println(e);
        }
    }
    Scanner scanner = new Scanner(process.getInputStream());
    while ( scanner.hasNextLine()) {
        System.out.println(scanner.nextLine()); //Process hangs at this point
    }
    process.getInputStream().close();
    scanner.close();

Solution

  • but console hangs at C:\rep\project>git fetch -v --progress abc@xyz.com/a/b releaseBranch point

    abc@xyz.com looks like an SSH URL, which means you need a private key:

    If you were using an HTTPS URL, you could consider caching the password (password this time, not passphrase) if the account in credential helper.

    The point being: it is best letting Git itself looking for the passphrase/password (in an ssh-agent, or a credential helper) than trying to feed that same sensitive date through a program console.