fix: parse error message when running command

This commit is contained in:
Jan De Dobbeleer 2020-12-30 20:01:22 +01:00 committed by Jan De Dobbeleer
parent 23eb73cd69
commit e0a4482d4b

View file

@ -4,7 +4,9 @@ import (
"bufio" "bufio"
"bytes" "bytes"
"context" "context"
"errors"
"fmt" "fmt"
"io"
"io/ioutil" "io/ioutil"
"log" "log"
"net/http" "net/http"
@ -153,11 +155,33 @@ func (env *environment) getPlatform() string {
} }
func (env *environment) runCommand(command string, args ...string) (string, error) { func (env *environment) runCommand(command string, args ...string) (string, error) {
getOutputString := func(io io.ReadCloser) string {
output := new(bytes.Buffer)
defer output.Reset()
buf := bufio.NewReader(io)
multiline := false
for {
line, _, _ := buf.ReadLine()
if line == nil {
break
}
if multiline {
output.WriteString("\n")
}
output.Write(line)
multiline = true
}
return output.String()
}
cmd := exec.Command(command, args...) cmd := exec.Command(command, args...)
stdout, err := cmd.StdoutPipe() stdout, err := cmd.StdoutPipe()
if err != nil { if err != nil {
log.Fatal(err) log.Fatal(err)
} }
stderr, err := cmd.StderrPipe()
if err != nil {
log.Fatal(err)
}
err = cmd.Start() err = cmd.Start()
if err != nil { if err != nil {
return "", err return "", err
@ -165,22 +189,12 @@ func (env *environment) runCommand(command string, args ...string) (string, erro
defer func() { defer func() {
_ = cmd.Process.Kill() _ = cmd.Process.Kill()
}() }()
output := new(bytes.Buffer) stdoutString := getOutputString(stdout)
defer output.Reset() stderrString := getOutputString(stderr)
buf := bufio.NewReader(stdout) if stderrString != "" {
multiline := false return "", errors.New(stderrString)
for {
line, _, _ := buf.ReadLine()
if line == nil {
break
}
if multiline {
output.WriteString("\n")
}
output.Write(line)
multiline = true
} }
return output.String(), nil return stdoutString, nil
} }
func (env *environment) runShellCommand(shell, command string) string { func (env *environment) runShellCommand(shell, command string) string {