2019-11-21 17:38:27 +00:00
|
|
|
package main
|
|
|
|
|
|
|
|
import (
|
2019-11-21 17:47:40 +00:00
|
|
|
"os"
|
2019-11-21 17:38:27 +00:00
|
|
|
"os/exec"
|
|
|
|
|
2020-04-17 17:34:44 +00:00
|
|
|
"github.com/Luzifer/go_helpers/v2/env"
|
2019-11-21 17:38:27 +00:00
|
|
|
"github.com/pkg/errors"
|
|
|
|
)
|
|
|
|
|
|
|
|
func init() {
|
|
|
|
registerAction("exec", actionExec{})
|
|
|
|
}
|
|
|
|
|
|
|
|
type actionExec struct{}
|
|
|
|
|
|
|
|
func (actionExec) Execute(attributes map[string]interface{}) error {
|
|
|
|
cmd, ok := attributes["command"].([]interface{})
|
|
|
|
if !ok {
|
|
|
|
return errors.New("No command supplied")
|
|
|
|
}
|
|
|
|
|
|
|
|
var args []string
|
|
|
|
for _, c := range cmd {
|
|
|
|
if v, ok := c.(string); ok {
|
|
|
|
args = append(args, v)
|
|
|
|
continue
|
|
|
|
}
|
|
|
|
return errors.New("Command conatins non-string argument")
|
|
|
|
}
|
|
|
|
|
2020-04-17 17:34:44 +00:00
|
|
|
processEnv := env.ListToMap(os.Environ())
|
|
|
|
|
2020-06-06 21:17:16 +00:00
|
|
|
if e, ok := attributes["env"].(map[interface{}]interface{}); ok {
|
2020-04-17 17:34:44 +00:00
|
|
|
for k, v := range e {
|
2020-06-06 21:17:16 +00:00
|
|
|
key, ok := k.(string)
|
|
|
|
if !ok {
|
|
|
|
continue
|
|
|
|
}
|
|
|
|
value, ok := v.(string)
|
|
|
|
if !ok {
|
|
|
|
continue
|
|
|
|
}
|
|
|
|
|
|
|
|
processEnv[key] = value
|
2020-04-17 17:34:44 +00:00
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2019-11-21 17:38:27 +00:00
|
|
|
command := exec.Command(args[0], args[1:]...)
|
2020-04-17 17:34:44 +00:00
|
|
|
command.Env = env.MapToList(processEnv)
|
|
|
|
|
|
|
|
if v, ok := attributes["attach_stdout"].(bool); ok && v {
|
|
|
|
command.Stdout = os.Stdout
|
|
|
|
}
|
|
|
|
|
|
|
|
if v, ok := attributes["attach_stderr"].(bool); ok && v {
|
|
|
|
command.Stdout = os.Stderr
|
|
|
|
}
|
2019-11-21 17:47:40 +00:00
|
|
|
|
2019-11-21 17:38:27 +00:00
|
|
|
if err := command.Start(); err != nil {
|
|
|
|
return errors.Wrap(err, "Unable to start command")
|
|
|
|
}
|
|
|
|
|
2020-04-17 17:15:42 +00:00
|
|
|
// If "wait" is set and set to true start command and wait for execution
|
|
|
|
if v, ok := attributes["wait"].(bool); ok && v {
|
2020-04-17 17:34:44 +00:00
|
|
|
return errors.Wrap(command.Wait(), "Command was not successful")
|
2020-04-17 17:15:42 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
// We don't wait so we release the process and don't care anymore
|
2019-11-21 17:38:27 +00:00
|
|
|
return errors.Wrap(command.Process.Release(), "Unable to release process")
|
|
|
|
}
|