Skip to content
This repository has been archived by the owner on Jul 22, 2024. It is now read-only.

Allow the cli to accpect single lined interactivity #54

Open
wants to merge 1 commit into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
8 changes: 6 additions & 2 deletions ui.go
Original file line number Diff line number Diff line change
Expand Up @@ -49,6 +49,7 @@ type BasicUi struct {
Reader io.Reader
Writer io.Writer
ErrorWriter io.Writer
RichReader *bufio.Reader
}

func (u *BasicUi) Ask(query string) (string, error) {
Expand All @@ -60,6 +61,10 @@ func (u *BasicUi) AskSecret(query string) (string, error) {
}

func (u *BasicUi) ask(query string, secret bool) (string, error) {
if u.RichReader == nil {
u.RichReader = bufio.NewReader(u.Reader)
}

if _, err := fmt.Fprint(u.Writer, query+" "); err != nil {
return "", err
}
Expand All @@ -79,8 +84,7 @@ func (u *BasicUi) ask(query string, secret bool) (string, error) {
if secret && isatty.IsTerminal(os.Stdin.Fd()) {
line, err = speakeasy.Ask("")
} else {
r := bufio.NewReader(u.Reader)
line, err = r.ReadString('\n')
line, err = u.RichReader.ReadString('\n')
}
if err != nil {
errCh <- err
Expand Down
36 changes: 36 additions & 0 deletions ui_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -64,6 +64,42 @@ func TestBasicUi_AskSecret(t *testing.T) {
}
}

func TestBasicUi_Ask_And_AskSecret(t *testing.T) {
in_r, in_w := io.Pipe()
defer in_r.Close()
defer in_w.Close()

writer := new(bytes.Buffer)
ui := &BasicUi{
Reader: in_r,
Writer: writer,
}

go in_w.Write([]byte("foo bar\nbaz\n"))

name, err := ui.Ask("Name?")
if err != nil {
t.Fatalf("err: %s", err)
}

password, err := ui.AskSecret("Password?")
if err != nil {
t.Fatalf("err: %s", err)
}

if writer.String() != "Name? Password? " {
t.Fatalf("bad: %#v", writer.String())
}

if name != "foo bar" {
t.Fatalf("bad: %#v", name)
}

if password != "baz" {
t.Fatalf("bad: %#v", password)
}
}

func TestBasicUi_Error(t *testing.T) {
writer := new(bytes.Buffer)
ui := &BasicUi{Writer: writer}
Expand Down