-
Notifications
You must be signed in to change notification settings - Fork 0
/
gommando.go
112 lines (91 loc) · 1.84 KB
/
gommando.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
package gommando
import (
"io"
"os"
"os/exec"
"syscall"
"github.com/matti/dynamicmultiwriter"
"github.com/matti/gommando/internal/chain"
)
// Gommando ...
type Gommando struct {
chains []*chain.Chain
out *dynamicmultiwriter.DynamicMultiWriter
err *dynamicmultiwriter.DynamicMultiWriter
both *dynamicmultiwriter.DynamicMultiWriter
in io.WriteCloser
cmd *exec.Cmd
}
// New ...
func New(cmd string) *Gommando {
g := &Gommando{}
g.out = dynamicmultiwriter.New()
g.err = dynamicmultiwriter.New()
g.Output(true)
g.cmd = exec.Command("/usr/bin/env", "sh", "-c", cmd)
g.cmd.Stdout = g.out
g.cmd.Stderr = g.err
stdin, err := g.cmd.StdinPipe()
if err != nil {
panic(err)
}
g.in = stdin
return g
}
// Output ...
func (g *Gommando) Output(enabled bool) {
if enabled {
g.out.Add(os.Stdout)
g.err.Add(os.Stderr)
} else {
g.out.Remove(os.Stdout)
g.err.Remove(os.Stderr)
}
}
// Stdout ...
func (g *Gommando) Stdout() *chain.Chain {
c := chain.New(g.out, nil, nil)
g.chains = append(g.chains, c)
return c
}
// Stderr ...
func (g *Gommando) Stderr() *chain.Chain {
c := chain.New(g.err, nil, nil)
g.chains = append(g.chains, c)
return c
}
// Stdboth ...
func (g *Gommando) Stdboth() *chain.Chain {
both := dynamicmultiwriter.New()
g.err.Add(both)
g.out.Add(both)
c := chain.New(both, nil, nil)
g.chains = append(g.chains, c)
return c
}
// Stdin ...
func (g *Gommando) Stdin() io.WriteCloser {
return g.in
}
// Run ...
func (g *Gommando) Run() {
for _, c := range g.chains {
c.Start()
}
g.cmd.Run()
for _, c := range g.chains {
c.Close()
}
}
// ProcessState ...
func (g *Gommando) ProcessState() *os.ProcessState {
return g.cmd.ProcessState
}
// Signal ...
func (g *Gommando) Signal(signal syscall.Signal) {
syscall.Kill(g.cmd.Process.Pid, signal)
}
// Wait ...
func (g *Gommando) Wait() {
g.cmd.Wait()
}