1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41
|
package main
import (
"bufio"
"bytes"
"fmt"
"io"
"os/exec"
"strings"
)
type runCommandType func(args []string) ([]string, error)
func runCommand(args []string) ([]string, error) {
cmd := exec.Command(args[0], args[1:]...)
cmd.Dir = "/" // to not be affected if the current directory is removed
out, err := cmd.CombinedOutput()
lines := strings.Split(string(out), "\n")
if err != nil {
return lines, fmt.Errorf("%q failed: %w", strings.Join(args, " "), err)
}
lines, err = readLines(bytes.NewReader(out))
if err != nil {
return lines, fmt.Errorf("failed to read the output of %q: %w", args, err)
}
return lines, nil
}
func readLines(r io.Reader) ([]string, error) {
var lines []string
scanner := bufio.NewScanner(r)
for scanner.Scan() {
lines = append(lines, scanner.Text())
}
if err := scanner.Err(); err != nil {
return nil, err
}
return lines, nil
}
|