From 115f92b91ecb5cbc340bc0161dbe5c46c0a90afa Mon Sep 17 00:00:00 2001 From: Claudio Netto Date: Sat, 2 Dec 2017 14:54:56 -0200 Subject: [PATCH] Adding method for getting piped input data --- user_interface/default.go | 21 +++++++++++++++++++++ user_interface/default_test.go | 17 +++++++++++++++++ 2 files changed, 38 insertions(+) diff --git a/user_interface/default.go b/user_interface/default.go index f73b9fd..30ca2f7 100644 --- a/user_interface/default.go +++ b/user_interface/default.go @@ -1,6 +1,7 @@ package user_interface import ( + "bufio" "errors" "flag" "fmt" @@ -20,6 +21,8 @@ var ( programName string outputDefault io.Writer setup SetUp + + inputReader *bufio.Reader ) func init() { @@ -32,6 +35,8 @@ func init() { return inputInfo.Mode() } + inputReader = bufio.NewReader(os.Stdin) + flag.Usage = customUsage flag.BoolVar(&setup.ListSubfolders, "subfolders", false, "List all subfolders from a remote folder.") @@ -60,6 +65,22 @@ func HasPipedInput() bool { return getInputFileMode() & os.ModeNamedPipe != 0 } +func GetPipedInputData() string { + var data []rune + + for { + rune, _, err := inputReader.ReadRune() + + if err != nil && err == io.EOF { + break + } + + data = append(data, rune) + } + + return string(data) +} + func customUsage() { usageHeader := "Usage: %s \n" diff --git a/user_interface/default_test.go b/user_interface/default_test.go index 849a5e8..e00c402 100644 --- a/user_interface/default_test.go +++ b/user_interface/default_test.go @@ -1,6 +1,7 @@ package user_interface import ( + "bufio" "bytes" "flag" "os" @@ -174,3 +175,19 @@ func TestHasPipedInput_NotReceivedPipedInput_MustReturnFalse(t *testing.T) { t.Errorf("Expected [false] but got [true]") } } + +func TestGetPipedInputData_MustReturnExpectedInput(t *testing.T) { + oldInputReader := inputReader + + defer func() { inputReader = oldInputReader }() + + expectedInput := "Hello world" + + inputReader = bufio.NewReader(bytes.NewBufferString(expectedInput)) + + got := GetPipedInputData() + + if got != expectedInput { + t.Errorf("Expected [%s] but got [%s]", expectedInput, got); + } +}