-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathexecutor.go
46 lines (41 loc) · 918 Bytes
/
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
package main
import (
"os/exec"
"strings"
"unicode"
)
type Executor struct {
cmd string
}
func NewExecutor(cmd string) *Executor {
return &Executor{cmd: cmd}
}
// Exec invokes the executor and feed input to
// stdin, and then return the stdout as a string
func (e *Executor) Exec(input string) (string, error) {
args := splitQuoted(e.cmd)
cmd := exec.Command(args[0], args[1:]...)
cmd.Stdin = strings.NewReader(input)
output, err := cmd.CombinedOutput()
if err != nil {
return "", err
}
return string(output), nil
}
// splitQuoted split s by spaces with keeping
// untouch on quoted fields
func splitQuoted(s string) []string {
return strings.FieldsFunc(s, func() func(r rune) bool {
arounded := false
return func(r rune) bool {
if r == '\'' || r == '"' {
arounded = !arounded
return true
}
if unicode.IsSpace(r) && !arounded {
return true
}
return false
}
}())
}