-
Notifications
You must be signed in to change notification settings - Fork 0
/
script.go
85 lines (68 loc) · 1.69 KB
/
script.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
package push
import (
"context"
"errors"
"os/exec"
"strings"
"time"
"github.com/kballard/go-shellquote"
"github.com/thommyho/robotui/util"
"github.com/thommyho/robotui/util/request"
)
func init() {
registry.Add("script", NewScriptFromConfig)
}
// Script implements shell script-based message service and setters
type Script struct {
log *util.Logger
script string
timeout time.Duration
}
// NewScriptFromConfig creates a Script messenger. Script execution is aborted after given timeout.
func NewScriptFromConfig(other map[string]interface{}) (Messenger, error) {
cc := struct {
CmdLine string
Timeout time.Duration
}{
Timeout: request.Timeout,
}
if err := util.DecodeOther(other, &cc); err != nil {
return nil, err
}
s := &Script{
log: util.NewLogger("script"),
script: cc.CmdLine,
timeout: cc.Timeout,
}
return s, nil
}
// Send calls the script
func (m *Script) Send(title, msg string) {
_, err := m.exec(m.script, title, msg)
if err != nil {
m.log.ERROR.Printf("exec: %v", err)
}
}
func (m *Script) exec(script, title, msg string) (string, error) {
args, err := shellquote.Split(script)
if err != nil {
return "", err
}
ctx, cancel := context.WithTimeout(context.Background(), m.timeout)
defer cancel()
args = append(args, title, msg)
cmd := exec.CommandContext(ctx, args[0], args[1:]...)
b, err := cmd.Output()
s := strings.TrimSpace(string(b))
if err != nil {
// use STDOUT if available
var ee *exec.ExitError
if errors.As(err, &ee) {
s = strings.TrimSpace(string(ee.Stderr))
}
m.log.ERROR.Printf("%s: %s", strings.Join(args, " "), s)
return "", err
}
m.log.DEBUG.Printf("%s: %s", strings.Join(args, " "), s)
return s, nil
}