-
Notifications
You must be signed in to change notification settings - Fork 0
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
- Loading branch information
1 parent
78db369
commit 6533466
Showing
1 changed file
with
45 additions
and
0 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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 | ||
} |