/
prompt.go
55 lines (47 loc) · 1.29 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
package operations
import (
"bufio"
"fmt"
"os"
"strings"
"github.com/evergreen-ci/utility"
)
// prompt writes a prompt to the user on stdout, reads a newline-terminated response from stdin,
// and returns the result as a string.
func prompt(message string) string {
reader := bufio.NewReader(os.Stdin)
fmt.Print(message + " ")
text, _ := reader.ReadString('\n')
return strings.TrimSpace(text)
}
// confirm asks the user a yes/no question and returns true/false if they reply with y/yes/n/no.
// if defaultYes is true, allows user to just hit enter without typing an explicit yes.
// Otherwise we default no.
func confirm(message string, defaultYes bool) bool {
var reply string
yes := []string{"y", "yes"}
no := []string{"n", "no"}
if defaultYes {
yes = append(yes, "")
message = fmt.Sprintf("%s (Y/n)", message)
} else {
no = append(no, "")
message = fmt.Sprintf("%s (y/N)", message)
}
for {
reply = prompt(message)
if utility.StringSliceContains(yes, strings.ToLower(reply)) {
return true
}
if utility.StringSliceContains(no, strings.ToLower(reply)) {
return false
}
}
}
func confirmWithMatchingString(message string, confirmation string) bool {
var reply string
for {
reply = prompt(message)
return confirmation == strings.TrimSpace(strings.ToLower(reply))
}
}