forked from eshaan-test-org/demo-go
-
Notifications
You must be signed in to change notification settings - Fork 0
/
cmd.go
118 lines (83 loc) · 2.2 KB
/
cmd.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
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
package main
import (
"bytes"
"io"
"io/ioutil"
"log"
"os"
"os/exec"
"strings"
"sync"
"time"
)
func runCmd(command string, args []string, env []string, cmdDir string) (string, string, error) {
a := 1
cmd := exec.Command(command, args...)
cmd.Dir = cmdDir
cmd.Env = os.Environ()
cmd.Env = append(cmd.Env, env...)
var stdoutBuf, stderrBuf bytes.Buffer
stdoutIn, _ := cmd.StdoutPipe()
stderrIn, _ := cmd.StderrPipe()
stdout := io.MultiWriter(os.Stdout, &stdoutBuf)
stderr := io.MultiWriter(os.Stderr, &stderrBuf)
startTime := time.Now()
err := cmd.Start()
if err != nil {
return string(stdoutBuf.Bytes()), string(stderrBuf.Bytes()), err
}
log.Println("==> EXEC COMMAND " + command)
log.Println("-> ARGS: " + strings.Join(args[:], " "))
log.Println("-> DIR: " + cmdDir)
log.Println("-> STDOUT/STDERR: ..")
var wg sync.WaitGroup
wg.Add(1)
go func() {
_, _ = io.Copy(stdout, stdoutIn)
wg.Done()
}()
_, _ = io.Copy(stderr, stderrIn)
wg.Wait()
err = cmd.Wait()
if err != nil {
log.Println("-> ERROR: ", err.Error())
if exitError, ok := err.(*exec.ExitError); ok {
log.Println("-> EXIT CODE: ", exitError.ExitCode())
log.Println("-> TIME TAKEN: ", time.Since(startTime)/time.Millisecond)
log.Println("==> END EXEC COMMAND " + command + "\n")
return string(stdoutBuf.Bytes()), string(stderrBuf.Bytes()), err
}
}
log.Println("-> TIME TAKEN: ", time.Now().Sub(startTime)/time.Millisecond)
log.Println("=> END EXEC COMMAND " + command + "\n")
if bytes.Compare(stdoutBuf.Bytes(), stderrBuf.Bytes()) == 0 {
log.Println("Both stdout and stderr have same value")
}
return string(stdoutBuf.Bytes()), string(stderrBuf.Bytes()), nil
}
func ExampleOpenFile() {
f, err := os.OpenFile("notes.txt", os.O_RDWR|os.O_CREATE, 0755)
if err != nil {
log.Fatal(err)
}
if err := f.Close(); err != nil {
log.Fatal(err)
}
}
func createTempFile() {
tmpFile, _ := os.Create("emptyFile.txt")
log.Println(tmpFile)
}
func ExampleTempFile() {
err := ioutil.WriteFile("/tmp/demo-go", []byte("deepsource-for-go"), 0644)
if err != nil {
panic(err)
}
}
func ExampleCreate() {
f, _ := os.Create("exampe.txt")
f.Close()
}
func EmptyPath(path string) bool {
return path == ""
}