如何在Golang中创建交互式命令执行?

时间:2015-12-09 22:21:16

标签: git go exec

我正在尝试从Golang程序中自动执行git push。有什么办法可以将父程序中的用户名和密码传递给exec-command吗?

func gitPush(gitExeLocation string, currentDir string) {

    fmt.Println("Pushing ...")
    args  := []string{"push", "-f", "origin", "HEAD"}

    cmd := exec.Command(gitExeLocation, args...)
    cmd.Dir = currentDir
    cmd.Stdout = os.Stdout
    cmd.Stderr = os.Stderr

    stdin, err := cmd.StdinPipe()
    if err != nil {
        fmt.Println(err) 
    }
    defer stdin.Close()
    err = cmd.Start()
    if err != nil {
        fmt.Println(err) 
        return
    }

    time.Sleep(5 * time.Second)
    io.WriteString(stdin, "<Username>\n")
    time.Sleep(3 * time.Second)
    io.WriteString(stdin, "<Password>\n")

    err = cmd.Wait()
    if err != nil {
        fmt.Println(err) 
        return
    }

    fmt.Println("Succeeded.\n")

}

0 个答案:

没有答案