runner: pipe commands together

This commit is contained in:
Sam Hoffman
2026-01-31 00:29:33 -05:00
parent 1f1e2db229
commit d6a01c4ee2
2 changed files with 42 additions and 0 deletions

View File

@@ -1,6 +1,7 @@
package runner
import (
"bytes"
"context"
"fmt"
"os/exec"
@@ -26,3 +27,33 @@ func (runner *ZRunner) Run(ctx context.Context, command string, formatArgs ...an
cmd := exec.Command(runner.Prog, args...)
return cmd.CombinedOutput()
}
func Pipeline(cmds ...*exec.Cmd) ([]byte, error) {
for i := 0; i < len(cmds)-1; i++ {
stdout, err := cmds[i].StdoutPipe()
if err != nil {
return nil, err
}
cmds[i+1].Stdin = stdout
}
out := bytes.Buffer{}
cmds[len(cmds)-1].Stdout = &out
for _, cmd := range cmds {
err := cmd.Start()
if err != nil {
return out.Bytes(), err
}
}
for _, cmd := range cmds {
err := cmd.Wait()
if err != nil {
return out.Bytes(), err
}
}
return out.Bytes(), nil
}

View File

@@ -2,9 +2,11 @@ package runner_test
import (
"context"
"os/exec"
"testing"
"git.gentoo.party/sam/thanks/internal/runner"
"github.com/stretchr/testify/assert"
)
func Test_ZCommand(t *testing.T) {
@@ -19,3 +21,12 @@ func Test_ZCommand(t *testing.T) {
t.Errorf("localRunner failed: %s\n\n%s", err.Error(), out)
}
}
func Test_Pipelie(t *testing.T) {
c1 := exec.Command("echo", "-n", "foo")
c2 := exec.Command("rev")
out, err := runner.Pipeline(c1, c2)
assert.Equal(t, "oof", string(out))
assert.Nil(t, err)
}