/
command.go
115 lines (105 loc) · 2.03 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
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
package stretcher
import (
"bytes"
"fmt"
"io"
"log"
"os"
"os/exec"
"sync"
"syscall"
)
type Commands struct {
Pre CommandLines `yaml:"pre"`
Post CommandLines `yaml:"post"`
Success CommandLines `yaml:"success"`
Failure CommandLines `yaml:"failure"`
}
type CommandLines []CommandLine
func (cs CommandLines) Invoke() error {
for _, c := range cs {
err := c.Invoke()
if err != nil {
return err
}
}
return nil
}
func (cs CommandLines) InvokePipe(src *bytes.Buffer) error {
for _, c := range cs {
buf := bytes.NewBuffer(src.Bytes())
err := c.InvokePipe(buf)
if err != nil {
return err
}
}
return nil
}
type CommandLine string
func (c CommandLine) String() string {
return string(c)
}
func (c CommandLine) Invoke() error {
log.Println("invoking command:", c.String())
out, err := exec.Command("sh", "-c", c.String()).CombinedOutput()
if len(out) > 0 {
log.Println(string(out))
}
if err != nil {
return fmt.Errorf("failed: %v %v", c, err)
}
return nil
}
func (c CommandLine) InvokePipe(src io.Reader) error {
log.Println("invoking command:", c.String())
cmd := exec.Command("sh", "-c", c.String())
stdin, err := cmd.StdinPipe()
if err != nil {
return err
}
stdout, err := cmd.StdoutPipe()
if err != nil {
return err
}
stderr, err := cmd.StderrPipe()
if err != nil {
return err
}
err = cmd.Start()
if err != nil {
return err
}
var wg sync.WaitGroup
wg.Add(3)
// src => cmd.stdin
go func() {
_, err := io.Copy(stdin, src)
if e, ok := err.(*os.PathError); ok && e.Err == syscall.EPIPE {
// ignore EPIPE
} else if err != nil {
log.Println("failed to write to STDIN of", c.String(), ":", err)
}
stdin.Close()
wg.Done()
}()
// cmd.stdout => stretcher.stdout
go func() {
_, err := io.Copy(os.Stdout, stdout)
if err != nil {
log.Println(err)
}
stdout.Close()
wg.Done()
}()
// cmd.stderr => stretcher.stderr
go func() {
_, err := io.Copy(os.Stderr, stderr)
if err != nil {
log.Println(err)
}
stderr.Close()
wg.Done()
}()
wg.Wait()
return cmd.Wait()
}