-
Notifications
You must be signed in to change notification settings - Fork 24
/
command.go
80 lines (63 loc) · 1.62 KB
/
command.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
package clients
import (
"os"
"os/exec"
"time"
"github.com/hashicorp/go-hclog"
)
type CommandConfig struct {
Command string
Args []string
Env []string
WorkingDirectory string
}
type Command interface {
Execute(config CommandConfig) error
}
// Command executes local commands
type CommandImpl struct {
timeout time.Duration
log hclog.Logger
}
// NewCommand creates a new command with the given logger and maximum command time
func NewCommand(maxCommandTime time.Duration, l hclog.Logger) Command {
return &CommandImpl{maxCommandTime, l}
}
// Execute the given command
func (c *CommandImpl) Execute(config CommandConfig) error {
cmd := exec.Command(
config.Command,
config.Args...,
)
// add the default environment variables
cmd.Env = os.Environ()
if config.Env != nil {
cmd.Env = append(cmd.Env, config.Args...)
}
if config.WorkingDirectory != "" {
cmd.Dir = config.WorkingDirectory
}
c.log.Debug("Running command", "cmd", config.Command, "args", config.Args, "dir", config.WorkingDirectory, "env", config.Env)
// set the standard out and error to the logger
cmd.Stdout = c.log.StandardWriter(&hclog.StandardLoggerOptions{InferLevels: true})
cmd.Stderr = c.log.StandardWriter(&hclog.StandardLoggerOptions{InferLevels: true})
/*
// wait for timeout
t := time.AfterFunc(c.timeout, func() {
// kill the running process
cmd.Process.Kill()
return fmt.Errorf("Command timed out before completing")
})
*/
err := cmd.Run()
if err != nil {
return err
}
// command has completed clear the timeout timer
/*
if t!= nil {
t.Stop()
}
*/
return nil
}