Skip to content

Commit

Permalink
refactor: run commands natively
Browse files Browse the repository at this point in the history
  • Loading branch information
JanDeDobbeleer committed Jan 8, 2021
1 parent 598984b commit 836763c
Showing 1 changed file with 3 additions and 56 deletions.
59 changes: 3 additions & 56 deletions src/environment.go
@@ -1,10 +1,7 @@
package main

import (
"bufio"
"bytes"
"context"
"io"
"io/ioutil"
"log"
"net/http"
Expand Down Expand Up @@ -155,61 +152,11 @@ func (env *environment) getPlatform() string {
}

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...)
stdout, err := cmd.StdoutPipe()
if err != nil {
return "", &commandError{
err: err.Error(),
exitCode: 666,
}
}
stderr, err := cmd.StderrPipe()
if err != nil {
return "", &commandError{
err: err.Error(),
exitCode: 667,
}
}
err = cmd.Start()
out, err := exec.Command(command, args...).Output()
if err != nil {
return "", &commandError{
err: err.Error(),
exitCode: 668,
}
}
defer func() {
_ = cmd.Process.Kill()
}()
stdoutString := getOutputString(stdout)
stderrString := getOutputString(stderr)
if stderrString != "" {
// only wait in case of error reduces the lead time on successful
// commands on windows due to not calling process.Wait()
_ = cmd.Wait()
return "", &commandError{
err: stderrString,
exitCode: cmd.ProcessState.ExitCode(),
}
return "", err
}
return stdoutString, nil
return strings.TrimSpace(string(out)), nil
}

func (env *environment) runShellCommand(shell, command string) string {
Expand Down

0 comments on commit 836763c

Please sign in to comment.