-
Notifications
You must be signed in to change notification settings - Fork 7
/
exec.go
82 lines (68 loc) · 1.72 KB
/
exec.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
package oswrap
import (
"os"
)
// ExecWrap wraps exec calls
type ExecWrap interface {
RunCommandDirect(command []string) error
RunCommandStdoutToFile(outfileName string, command []string) error
RunSyscallExec(args []string) error
}
type execWrap struct{}
//todo use oswrap.Instance() instead of package local ow?
var ew ExecWrap = execWrap{}
// ExecWrapInstance gets the execution wrapper interface
func ExecWrapInstance() ExecWrap {
return ew
}
// RunCommandDirect runs a command, redirecting 0/1/2 to the caller
func (ew execWrap) RunCommandDirect(command []string) error {
cmd := ow.Command(command[0], command[1:]...)
cmd.Stdin = os.Stdin
cmd.Stderr = os.Stderr
cmd.Stdout = os.Stdout
err := cmd.Start()
if err != nil {
return err
}
return cmd.Wait()
}
// RunCommandStdoutToFile runs a command, redirecting Stdout to a file, the rest to caller
func (ew execWrap) RunCommandStdoutToFile(outfileName string, command []string) error {
cmd := ow.Command(command[0], command[1:]...)
cmd.Stdin = os.Stdin
cmd.Stderr = os.Stderr
// open the out file for writing
outfile, err := ow.Create(outfileName)
if err != nil {
return err
}
cmd.Stdout = outfile
err = cmd.Start()
if err != nil {
// todo defer?
outfile.Close()
// todo defer?
ow.Remove(outfileName)
return err
}
ret := cmd.Wait()
err = outfile.Close()
if err != nil {
return err
}
if ret != nil {
// todo defer?
ow.Remove(outfileName)
}
return ret
}
// RunSyscallExec runs exec which fully takes over the process.
// the return here never really fires unless the exec fails
func (ew execWrap) RunSyscallExec(args []string) error {
path, err := ow.LookPath(args[0])
if err != nil {
return err
}
return ow.Exec(path, args, ow.Environ())
}