This repository has been archived by the owner on Jun 16, 2019. It is now read-only.
/
execCommand.go
86 lines (72 loc) · 2.15 KB
/
execCommand.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
76
77
78
79
80
81
82
83
84
85
86
package utility
import (
"os/exec"
"strings"
"io"
"os"
"log"
"path/filepath"
)
/**
* Execute a command and return the output as string
*/
func ExecCommand(commandParts ...string) string {
return execCommandInternal(nil, commandParts...)
}
func ExecCommandWithStdIn(stdin io.Reader, commandParts ...string) string {
return execCommandInternal(stdin, commandParts...)
}
func ExecCommandAndFailWithFatalErrorOnError(commandParts ...string) {
command := commandParts[0]
commandArgs := commandParts[1:]
cmd := exec.Command(command, commandArgs...)
_, err := cmd.CombinedOutput()
if err != nil {
log.Fatalf("FATAL: There was an error running command %v; error was: %v", commandParts, err)
}
}
/**
* Execute a command and return the output as string
*/
func execCommandInternal(stdin io.Reader, commandParts ...string) string {
command := commandParts[0]
commandArgs := commandParts[1:]
cmd := exec.Command(command, commandArgs...)
if stdin != nil {
cmd.Stdin = stdin
}
output, err := cmd.CombinedOutput()
if err != nil {
return "ERROR running command: " + strings.Join(commandParts, " ") + " - " + strings.TrimSpace(string(output[:]))
} else {
return strings.TrimSpace(string(output[:]))
}
}
func ExecCommandAndDumpResultToFile(resultFile string, commandParts ...string) {
command := commandParts[0]
commandArgs := commandParts[1:]
cmd := exec.Command(command, commandArgs...)
stdout, err := cmd.StdoutPipe()
if err != nil {
log.Fatalf("ERROR: Stdout Pipe could not be redirected: %v", err)
}
os.MkdirAll(filepath.Dir(resultFile), os.ModePerm)
resultFileHandle, err := os.Create(resultFile)
if err != nil {
log.Fatalf("ERROR: Result file %s could not be created: %v", resultFile, err)
}
cmd.Start()
_, err = io.Copy(resultFileHandle, stdout)
if err != nil {
log.Fatalf("ERROR: Result file %s could not be copied to: %v", resultFile, err)
}
cmd.Wait()
stat, err := resultFileHandle.Stat()
if err != nil {
log.Fatalf("ERROR: Result file stats for %s could not be obtained: %v", resultFile, err)
}
if stat.Size() == 0 {
log.Fatalf("ERROR: File %s is empty! Something has gone wrong!!", resultFile)
}
resultFileHandle.Close()
}