-
Notifications
You must be signed in to change notification settings - Fork 13
/
executor.go
86 lines (67 loc) · 1.73 KB
/
executor.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 main
import (
"fmt"
"io"
"log"
"os"
"os/exec"
"path/filepath"
"strings"
)
type Executor interface {
Run(command ...string) error
}
func newExecutor(in io.Reader, out, err io.Writer, baseDirectory string, dryRun bool) Executor {
return &CommandExecutor{
in: in,
out: out,
err: err,
baseDirectory: baseDirectory,
dryRun: dryRun,
}
}
type CommandExecutor struct {
in io.Reader
out io.Writer
err io.Writer
baseDirectory string
dryRun bool
}
func (executor *CommandExecutor) InDirectory(directory string) CommandExecutor {
newWorkingDirectory := filepath.Join(executor.baseDirectory, directory)
expandedWorkingDirectory := os.ExpandEnv(newWorkingDirectory)
return CommandExecutor{
in: executor.in,
out: executor.out,
err: executor.err,
baseDirectory: expandedWorkingDirectory,
dryRun: executor.dryRun,
}
}
func (executor *CommandExecutor) Run(command ...string) error {
if len(command) == 0 {
return fmt.Errorf("No command given")
}
workingDirectory := executor.baseDirectory
expandedWorkingDirectory := os.ExpandEnv(workingDirectory)
expandedCommandName := os.ExpandEnv(command[0])
var expandedArguments []string
for _, argument := range command[1:] {
expandedArguments = append(expandedArguments, os.ExpandEnv(argument))
}
cmd := exec.Command(expandedCommandName, expandedArguments...)
cmd.Dir = expandedWorkingDirectory
cmd.Env = os.Environ()
cmd.Stdout = executor.out
cmd.Stderr = executor.err
cmd.Stdin = executor.in
log.Printf("%s: %s %s", expandedWorkingDirectory, command[0], strings.Join(command[1:], " "))
if !executor.dryRun {
err := cmd.Run()
if err != nil {
log.Printf("Error running %s: %v", command, err)
return err
}
}
return nil
}