/
run.go
65 lines (58 loc) · 1.49 KB
/
run.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
package proj2aci
import (
"fmt"
"io"
"os"
"os/exec"
"strings"
)
type CmdFailedError struct {
Err error
}
func (e CmdFailedError) Error() string {
return fmt.Sprintf("CmdFailedError: %s", e.Err.Error())
}
type CmdNotFoundError struct {
Err error
}
func (e CmdNotFoundError) Error() string {
return fmt.Sprintf("CmdNotFoundError: %s", e.Err.Error())
}
// RunCmdFull runs given execProg. execProg should be an absolute path
// to a program or it can be an empty string. In the latter case first
// string in args is taken and searched for in $PATH.
//
// If execution fails then CmdFailedError is returned. This can be
// useful if we don't care if execution fails or not. CmdNotFoundError
// is returned if executable is not found.
func RunCmdFull(execProg string, args, env []string, cwd string, stdout, stderr io.Writer) error {
if len(args) < 1 {
return fmt.Errorf("No args to execute passed")
}
prog := execProg
if prog == "" {
pathProg, err := exec.LookPath(args[0])
if err != nil {
return CmdNotFoundError{err}
}
prog = pathProg
} else if _, err := os.Stat(prog); err != nil {
return CmdNotFoundError{err}
}
cmd := exec.Cmd{
Path: prog,
Args: args,
Env: env,
Dir: cwd,
Stdout: stdout,
Stderr: stderr,
}
Debug(`running command: "`, strings.Join(args, `" "`), `"`)
if err := cmd.Run(); err != nil {
return CmdFailedError{err}
}
return nil
}
func RunCmd(args, env []string, cwd string) error {
return RunCmdFull("", args, env, cwd, os.Stdout, os.Stderr)
}