Skip to content

Commit

Permalink
executil pipeline function
Browse files Browse the repository at this point in the history
  • Loading branch information
hans-m-song committed Oct 28, 2023
1 parent 78db369 commit 6533466
Showing 1 changed file with 45 additions and 0 deletions.
45 changes: 45 additions & 0 deletions executil/pipeline.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,45 @@
package executil

import (
"errors"
"fmt"
"io"
"os/exec"
)

func Pipeline(cmds ...*exec.Cmd) (output []byte, err error) {
var stdout io.ReadCloser

// build up stdin->stdout connections
for _, cmd := range cmds {
if stdout != nil {
cmd.Stdin = stdout
}

if stdout, err = cmd.StdoutPipe(); err != nil {
return nil, fmt.Errorf("failed to get stdout for %s: %s", cmd.String(), err)
}
}

// start commands
for _, cmd := range cmds {
if err = cmd.Start(); err != nil {
return nil, fmt.Errorf("failed to start cmd %s: %s", cmd.String(), err)
}
}

// read final output
if output, err = io.ReadAll(stdout); err != nil {
err = errors.Join(err, fmt.Errorf("failed to get pipeline tail stdout: %s", err))
}

// wait for commands to finish in reverse
for i := len(cmds) - 1; i > -1; i-- {
cmd := cmds[i]
if err := cmd.Wait(); err != nil {
return nil, fmt.Errorf("failed to wait for cmd %s: %s", cmd.String(), err)
}
}

return output, err
}

0 comments on commit 6533466

Please sign in to comment.