Skip to content

Commit

Permalink
fix: add PipeToFile func
Browse files Browse the repository at this point in the history
  • Loading branch information
Deny Prasetyo committed Oct 12, 2021
1 parent ece3a97 commit 8325c41
Show file tree
Hide file tree
Showing 2 changed files with 29 additions and 2 deletions.
13 changes: 13 additions & 0 deletions pkg/cmd/command.go
Original file line number Diff line number Diff line change
Expand Up @@ -79,6 +79,19 @@ func (c *command) Exec(command string, arg ...string) (cmd *exec.Cmd, stdOut io.
return c.Execute(map[string]string{}, "", command, arg...)
}

//PipeToFile create or truncate file
func PipeToFile(out io.ReadCloser, path string) (err error) {
defer out.Close()
openFile, err := os.OpenFile(path, os.O_RDWR|os.O_CREATE|os.O_TRUNC, 0755)
if err != nil {
return
}
defer openFile.Close()
_, err = openFile.ReadFrom(out)
return
}


func ScanAndClose(out io.ReadCloser, ops func(string)) {
defer out.Close()

Expand Down
18 changes: 16 additions & 2 deletions pkg/cmd/command_test.go
Original file line number Diff line number Diff line change
@@ -1,6 +1,9 @@
package cmd

import (
"fmt"
"github.com/gopaytech/go-commons/pkg/strings"
"os"
"testing"
"time"

Expand All @@ -20,7 +23,7 @@ func TestExecuteAndWaitFailed(t *testing.T) {
}

func TestExecute(t *testing.T) {
_,stdOut, stdErr, err := Command.Exec("/usr/bin/bash", "cmd_loop_test.sh")
_, stdOut, stdErr, err := Command.Exec("/usr/bin/bash", "cmd_loop_test.sh")
assert.Nil(t, err)
assert.NotNil(t, stdOut)
assert.NotNil(t, stdErr)
Expand All @@ -30,11 +33,22 @@ func TestExecute(t *testing.T) {
}

func TestExecuteSuccess(t *testing.T) {
_,stdOut, stdErr, err := Command.Exec("/usr/bin/bash", "cmd_loop_test.sh")
_, stdOut, stdErr, err := Command.Exec("/usr/bin/bash", "cmd_loop_test.sh")
assert.Nil(t, err)
assert.NotNil(t, stdOut)
assert.NotNil(t, stdErr)
ScanAndClose(stdOut, func(s string) {
t.Logf(s)
})
}

func TestExecuteToFile(t *testing.T) {
_, stdOut, stdErr, err := Command.Exec("/usr/bin/bash", "cmd_loop_test.sh")
assert.Nil(t, err)
assert.NotNil(t, stdOut)
assert.NotNil(t, stdErr)
path := fmt.Sprintf("%s/%s", os.TempDir(), strings.RandomAlphanumeric(13))
err = PipeToFile(stdOut, path)
assert.NoError(t, err)
assert.FileExists(t, path)
}

0 comments on commit 8325c41

Please sign in to comment.