Skip to content

Commit

Permalink
SimpleShellReader prints a newline when it reads EOF
Browse files Browse the repository at this point in the history
  • Loading branch information
bmatsuo committed Jun 30, 2014
1 parent c3a3d32 commit 7f557c0
Show file tree
Hide file tree
Showing 2 changed files with 30 additions and 4 deletions.
26 changes: 23 additions & 3 deletions shell.go
Original file line number Diff line number Diff line change
Expand Up @@ -64,6 +64,7 @@ type ShellReader interface {
type SimpleShellReader struct {
r io.Reader
br *bufio.Reader
out io.Writer
prompt string
}

Expand All @@ -72,15 +73,34 @@ func NewShellReader(r io.Reader, prompt string) *SimpleShellReader {
r = os.Stdin
}
br := bufio.NewReader(r)
return &SimpleShellReader{r, br, prompt}
return &SimpleShellReader{r, br, os.Stdout, prompt}
}

func (s *SimpleShellReader) SetOutput(w io.Writer) {
s.out = w
}

func (s *SimpleShellReader) print(v ...interface{}) {
if s.out != nil {
fmt.Fprint(s.out, v...)
}
}

func (s *SimpleShellReader) println(v ...interface{}) {
if s.out != nil {
fmt.Fprintln(s.out, v...)
}
}

func (s *SimpleShellReader) ReadCommand() (cmd []string, eof bool, err error) {
fmt.Print(s.prompt)
s.print(s.prompt)
bs, err := s.br.ReadBytes('\n')
eof = err == io.EOF
if eof {
s.println()
}
if err != nil {
if err == io.EOF && len(bs) > 0 {
if eof && len(bs) > 0 {
// this is ok
} else {
return nil, eof, err
Expand Down
8 changes: 7 additions & 1 deletion shell_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@ package main

import (
"io"
"io/ioutil"
"reflect"
"strings"
"testing"
Expand All @@ -15,6 +16,7 @@ func StringShellReader(lines string) *SimpleShellReader {

func TestShellReaderReadCommand_eof(t *testing.T) {
sh := StringShellReader("")
sh.SetOutput(ioutil.Discard)
_, eof, err := sh.ReadCommand()
if err != io.EOF {
t.Fatal("non-eof error returned")
Expand All @@ -24,6 +26,7 @@ func TestShellReaderReadCommand_eof(t *testing.T) {
}

sh = StringShellReader(":hello shell")
sh.SetOutput(ioutil.Discard)
_, eof, err = sh.ReadCommand()
if err != nil {
t.Fatal("error returned")
Expand All @@ -35,6 +38,7 @@ func TestShellReaderReadCommand_eof(t *testing.T) {

func TestShellReaderReadCommand_multi(t *testing.T) {
sh := StringShellReader(":hello\n:shell\n")
sh.SetOutput(ioutil.Discard)
cmd, eof, err := sh.ReadCommand()
if err != nil {
t.Fatalf("error returned")
Expand Down Expand Up @@ -81,7 +85,9 @@ func TestShellReaderReadCommand_single(t *testing.T) {
{".items | .[]", cmd("push", ".items | .[]")},
{"\n", cmd("write")},
} {
cmd, _, err := StringShellReader(test.str).ReadCommand()
sh := StringShellReader(test.str)
sh.SetOutput(ioutil.Discard)
cmd, _, err := sh.ReadCommand()
if err != nil {
t.Errorf("command %d (%q) %v", i, test.str, err)
continue
Expand Down

0 comments on commit 7f557c0

Please sign in to comment.