rpaste/modules/utility/pipes.go

54 lines
981 B
Go
Raw Normal View History

package utility
import (
"bytes"
"io"
"log"
"os/exec"
)
func ExecutePipe(outbuffer *bytes.Buffer, stack ...*exec.Cmd) (err error) {
var errbuffer bytes.Buffer
pipestack := make([]*io.PipeWriter, len(stack)-1)
i := 0
for ; i < len(stack)-1; i++ {
2021-12-28 04:27:10 +00:00
stdinpipe, stdoutpipe := io.Pipe()
stack[i].Stdout = stdoutpipe
stack[i].Stderr = &errbuffer
2021-12-28 04:27:10 +00:00
stack[i+1].Stdin = stdinpipe
pipestack[i] = stdoutpipe
}
stack[i].Stdout = outbuffer
stack[i].Stderr = &errbuffer
if err := callpipe(stack, pipestack); err != nil {
log.Fatalln(string(errbuffer.Bytes()), err)
}
return err
}
func callpipe(stack []*exec.Cmd, pipes []*io.PipeWriter) (err error) {
if stack[0].Process == nil {
if err = stack[0].Start(); err != nil {
return err
}
}
if len(stack) > 1 {
if err = stack[1].Start(); err != nil {
return err
}
defer func() {
if err == nil {
pipes[0].Close()
err = callpipe(stack[1:], pipes[1:])
}
}()
}
return stack[0].Wait()
}