forked from wailsapp/wails
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathprompt.go
80 lines (65 loc) · 1.52 KB
/
prompt.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
package cmd
import (
"bufio"
"fmt"
"os"
"strconv"
"strings"
)
// Prompt asks the user for a value
func Prompt(question string, defaultValue ...string) string {
var answer string
if len(defaultValue) > 0 {
answer = defaultValue[0]
question = fmt.Sprintf("%s (%s)", question, answer)
}
fmt.Printf(question + ": ")
reader := bufio.NewReader(os.Stdin)
input, _ := reader.ReadString('\n')
input = strings.TrimSpace(input)
if input != "" {
answer = input
}
return answer
}
// PromptRequired calls Prompt repeatedly until a value is given
func PromptRequired(question string, defaultValue ...string) string {
for {
result := Prompt(question, defaultValue...)
if result != "" {
return result
}
}
}
// PromptSelection asks the user to choose an option
func PromptSelection(question string, options []string, optionalDefaultValue ...int) int {
defaultValue := -1
message := "Please choose an option"
fmt.Println(question + ":")
if len(optionalDefaultValue) > 0 {
defaultValue = optionalDefaultValue[0] + 1
message = fmt.Sprintf("%s [%d]", message, defaultValue)
}
for index, option := range options {
fmt.Printf(" %d: %s\n", index+1, option)
}
selectedValue := -1
for {
choice := Prompt(message)
if choice == "" && defaultValue > -1 {
selectedValue = defaultValue - 1
break
}
// index
number, err := strconv.Atoi(choice)
if err == nil {
if number > 0 && number <= len(options) {
selectedValue = number - 1
break
} else {
continue
}
}
}
return selectedValue
}