Home > OS >  Collect git command's output with Go exec
Collect git command's output with Go exec

Time:08-03

I am extremely new to Go; as part of some innovation time, I decided to play around a bit with it. What I'd like to do is run some commands, and process their output.

I came up with this function to run commands:

func IssueCommand(command string, args []string) ([]string, error) {
    cmd := exec.Command(command, args[0:len(args)]...)

    stdout, err := cmd.StdoutPipe()
    err = cmd.Start()

    if err != nil {
        return nil, err
    }

    defer cmd.Wait()
    buff := bufio.NewScanner(stdout)

    var returnText []string

    for buff.Scan() {
        returnText = append(returnText, buff.Text())
    }

    return returnText, nil
}

I wanted to run this git command:

 git -C /something/something rev-list --count --date=local --all --no-merges

However, I keep getting an empty array as a result. I tried calling the function like this:

args := [7]string{"-C ", path, "rev-list", "--count", "--date=local", "--all", "--no-merges"}
result, err := IssueCommand("git", args[0:len(args)])

Also tried modifying the IssueCommand function to take a string for arguments; I called it like this:

cmd := "-C "   path   " rev-list --count --date=local --all --no-merges"
result, err := IssueCommand("git", cmd)

I got an empty array both times. It did capture output from commands like ls or pwd.

Again I am just trying to get a feel for Go, I will RTFM, but I have limited time for now.

CodePudding user response:

If your intention is to run that command synchronously and get its output, the easiest way is to use cmd.Output() (run command and collect stdout) or cmd.CombinedOutput() (run command and collect stderr stdout)

func IssueCommand(command string, args []string) ([]string, error) {
    cmd := exec.Command(command, args...)

    out, err := cmd.Output()
    if err != nil {
        return nil, err
    }

    lines := strings.Split(string(out), "\n")
    return lines, nil
}
  •  Tags:  
  • go
  • Related