Skip to content

Commit

Permalink
fix: exec pipe error (#6)
Browse files Browse the repository at this point in the history
* fix exec pipe error

* fix exec pipe error

* fix exec pipe error

* ShellExecPipe

* ShellExecPipe
  • Loading branch information
shipengqi authored Feb 20, 2022
1 parent 887a509 commit dde3d89
Show file tree
Hide file tree
Showing 2 changed files with 6 additions and 35 deletions.
34 changes: 2 additions & 32 deletions cliutil/cli_linux.go
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,6 @@ import (
"context"
"io"
"os/exec"
"sync"
)

// LoggingFunc callback function for logging command output
Expand Down Expand Up @@ -74,50 +73,21 @@ func ExecPipe(ctx context.Context, fn LoggingFunc, command string, args ...strin
if err != nil {
return err
}
stderr, err := cmd.StderrPipe()
if err != nil {
return err
}
defer func() {
_ = stdout.Close()
_ = stderr.Close()
}()
if err = cmd.Start(); err != nil {
return err
}
err = readPipe(stdout, stderr, fn)
reader := bufio.NewReader(stdout)
err = readBuf(reader, fn)
if err != nil {
return err
}

return cmd.Wait()
}

func readPipe(stdout, stderr io.ReadCloser, fn LoggingFunc) error {
oReader := bufio.NewReader(stdout)
eReader := bufio.NewReader(stderr)
wg := &sync.WaitGroup{}

wg.Add(2)
var oErr, eErr error
go func() {
defer wg.Done()
oErr = readBuf(oReader, fn)
}()
go func() {
defer wg.Done()
eErr = readBuf(eReader, fn)
}()
wg.Wait()
if oErr != nil {
return eErr
}
if eErr != nil {
return eErr
}
return nil
}

func readBuf(r *bufio.Reader, fn LoggingFunc) error {
for {
if line, _, err := r.ReadLine(); err == nil {
Expand Down
7 changes: 4 additions & 3 deletions cliutil/cli_linux_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -52,9 +52,11 @@ func TestShellExec(t *testing.T) {

func TestShellExecPipe(t *testing.T) {
testcmd := "echo hello, world!;sleep 1;exit 1"
testcmd2 := "n=1;while [ $n -le 4 ];do echo $n;((n++));done"
if os.Getenv("CI") == "true" {
testcmd = "echo hello, world!;exit 1"
t.Skip("Skipped")
testcmd2 = "echo 1;echo 2;echo 3;echo 4"
// t.Skip("Skipped")
}
t.Run("exec pipe err", func(t *testing.T) {
var lines []string
Expand All @@ -70,10 +72,9 @@ func TestShellExecPipe(t *testing.T) {
t.Run("exec pipe", func(t *testing.T) {
var lines []string
err := ShellExecPipe(context.TODO(), func(line []byte) error {
// t.Log(line)
lines = append(lines, string(line))
return nil
}, "n=1;while [ $n -le 4 ];do echo $n;((n++));done")
}, testcmd2)
assert.NoError(t, err)
assert.Equal(t, []string{"1", "2", "3", "4"}, lines)
})
Expand Down

0 comments on commit dde3d89

Please sign in to comment.