From 5169b2d145b0086516491a35887bfc5eb07be2ae Mon Sep 17 00:00:00 2001 From: Stefan Majewsky Date: Tue, 4 Apr 2017 22:00:22 +0200 Subject: implement "index" subcommand --- util.go | 42 ++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 42 insertions(+) (limited to 'util.go') diff --git a/util.go b/util.go index 09f93be..a1cea5f 100644 --- a/util.go +++ b/util.go @@ -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(": ")) + } +} -- cgit v1.3.1