-
Notifications
You must be signed in to change notification settings - Fork 2
/
exec_log.go
75 lines (66 loc) · 1.52 KB
/
exec_log.go
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
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
package main
import (
"bufio"
"bytes"
"log"
"os/exec"
"strings"
)
func scanCarriageReturns(data []byte, atEOF bool) (advance int, token []byte, err error) {
if atEOF && len(data) == 0 {
return 0, nil, nil
}
if i := bytes.IndexByte(data, '\r'); i >= 0 {
// We have a full newline-terminated line.
return i + 1, data[0:i], nil
}
// If we're at EOF, we have a final, non-terminated line. Return it.
if atEOF {
return len(data), data, nil
}
// Request more data.
return 0, nil, nil
}
/// Executes, logging lines as they come in, returning all stdin/err output.
func execLog(command string, args []string) (string, error) {
cmd := exec.Command(command, args...)
output := ""
// Stdout.
stdout, err := cmd.StdoutPipe()
if err != nil {
log.Println("StdoutPipe error:", err)
return "", err
}
stdoutScanner := bufio.NewScanner(stdout)
stdoutScanner.Split(scanCarriageReturns)
go func() {
for stdoutScanner.Scan() {
text := stdoutScanner.Text()
output = output + text
log.Println(strings.TrimSpace(text))
}
}()
// Stderr.
stderr, err := cmd.StderrPipe()
if err != nil {
log.Println("StderrPipe error:", err)
return "", err
}
stderrScanner := bufio.NewScanner(stderr)
stderrScanner.Split(scanCarriageReturns)
go func() {
for stderrScanner.Scan() {
text := stderrScanner.Text()
output = output + text
log.Println(strings.TrimSpace(text))
}
}()
// Run.
err = cmd.Start()
if err != nil {
log.Println("Start error:", err)
return "", err
}
err = cmd.Wait()
return output, err
}