Skip to content

Commit

Permalink
Handle Required option
Browse files Browse the repository at this point in the history
  • Loading branch information
tcnksm committed Jan 6, 2016
1 parent dc5d52d commit 5da1aae
Show file tree
Hide file tree
Showing 2 changed files with 33 additions and 5 deletions.
28 changes: 23 additions & 5 deletions ask.go
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,9 @@ import (
"os/signal"
)

// Ask asks user to input an answer about query. It shows query to user
// and ask input. It returns answer as string. If it catches the SIGINT
// stops reading user input and returns error.
func (i *UI) Ask(query string, opts *Options) (string, error) {

// Set the default writer & reader if not provided
Expand All @@ -18,13 +21,22 @@ func (i *UI) Ask(query string, opts *Options) (string, error) {
rd = defaultReader
}

// Construct the query to the user
// Construct the query to the user and show it.
var buf bytes.Buffer
buf.WriteString(fmt.Sprintf("%s\n", query))
fmt.Fprintf(wr, buf.String())

// resultCh is channel receives result string from user input.
resultCh := make(chan string, 1)

// errCh is channel receives error while reading user input.
errCh := make(chan error, 1)

// sigCh is channel which is watch Interruptted signal (SIGINT)
sigCh := make(chan os.Signal, 1)
signal.Notify(sigCh, os.Interrupt)
defer signal.Stop(sigCh)

go func() {
// Loop only when error by invalid user input and opts.Loop is true.
for {
Expand Down Expand Up @@ -56,15 +68,21 @@ func (i *UI) Ask(query string, opts *Options) (string, error) {
return
}

if line == "" && opts.Required {
if !opts.Loop {
errCh <- ErrEmpty
return
}

fmt.Fprintf(wr, "Input must not be empty.\n\n")
continue
}

resultCh <- line
return
}
}()

sigCh := make(chan os.Signal, 1)
signal.Notify(sigCh, os.Interrupt)
defer signal.Stop(sigCh)

select {
case result := <-resultCh:
// Insert the new line for next output
Expand Down
10 changes: 10 additions & 0 deletions ask_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -26,6 +26,16 @@ func TestAsk(t *testing.T) {
userInput: bytes.NewBufferString("\n"),
expect: "Nakashima",
},

// Loop & Required
{
opts: &Options{
Required: true,
Loop: true,
},
userInput: bytes.NewBufferString("\nNakashima\n"),
expect: "Nakashima",
},
}

for i, c := range cases {
Expand Down

0 comments on commit 5da1aae

Please sign in to comment.