forked from fujiwara/stretcher
-
Notifications
You must be signed in to change notification settings - Fork 0
/
command.go
98 lines (87 loc) · 1.66 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
package stretcher
import (
"bytes"
"fmt"
"io"
"log"
"os"
"os/exec"
)
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
}
cmdCh := make(chan error)
// src => stdin
go func() {
_, err := io.Copy(stdin, src)
if err != nil {
cmdCh <- err
}
stdin.Close()
}()
// wait for command exit
go func() {
cmdCh <- cmd.Wait()
}()
go io.Copy(os.Stdout, stdout)
go io.Copy(os.Stderr, stderr)
cmdErr := <-cmdCh
return cmdErr
}