diff options
| author | Stefan Majewsky <majewsky@gmx.net> | 2017-04-04 22:00:22 +0200 |
|---|---|---|
| committer | Stefan Majewsky <majewsky@gmx.net> | 2017-04-04 22:00:22 +0200 |
| commit | 5169b2d145b0086516491a35887bfc5eb07be2ae (patch) | |
| tree | 1d667534b898103b682cf23479ff7494527a7656 /util.go | |
| parent | b422f498bf3053bdc69c62a9946f047dfb09e125 (diff) | |
| download | gofu-5169b2d145b0086516491a35887bfc5eb07be2ae.tar.gz | |
implement "index" subcommand
Diffstat (limited to 'util.go')
| -rw-r--r-- | util.go | 42 |
1 files changed, 42 insertions, 0 deletions
@@ -19,8 +19,10 @@ package main import ( + "bufio" "fmt" "os" + "strings" ) //ShowError prints the given error on stderr if it is non-nil, or returns false otherwise. @@ -39,3 +41,43 @@ func FatalIfError(err error) { os.Exit(255) } } + +var stdin = bufio.NewReader(os.Stdin) + +//Prompt prints the question, then waits for the user to press one of the +//possible answer keys. Answer keys will automatically be converted to lower +//case and returned as such. +// +// choice := Prompt("(y)es or (n)o", []string{"y","n"}) +// //choice is either "y" or "n" +func Prompt(question string, answers []string) string { + for idx, answer := range answers { + answers[idx] = strings.ToLower(answer) + } + + os.Stdout.Write([]byte(">> " + strings.TrimSpace(question) + " ")) + for { + input, err := stdin.ReadString('\n') + FatalIfError(err) + input = strings.TrimSpace(input) + for _, answer := range answers { + if strings.ToLower(input) == answer { + return answer + } + } + + //user typed gibberish - ask again + os.Stdout.Write([]byte("Please type ")) + for idx, answer := range answers { + if idx > 0 { + if idx == len(answers)-1 { + os.Stdout.Write([]byte(" or ")) + } else { + os.Stdout.Write([]byte(", ")) + } + } + os.Stdout.Write([]byte("'" + answer + "'")) + } + os.Stdout.Write([]byte(": ")) + } +} |
