-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathprompt.go
92 lines (80 loc) · 1.9 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
81
82
83
84
85
86
87
88
89
90
91
92
package skeletonkit
import (
"fmt"
"io"
"os"
"strconv"
"strings"
)
// DefaultPrompt is default Prompt.
var DefaultPrompt = &Prompt{
Input: os.Stdin,
Output: os.Stdout,
ErrOutput: os.Stderr,
}
// Prompt receive input from a user.
type Prompt struct {
Input io.Reader
Output io.Writer
ErrOutput io.Writer
}
// Choose shows options and user would select a option from these options.
// Choose returns index of the selected option.
func (p *Prompt) Choose(description string, opts []string, prompt string) (int, error) {
if _, err := fmt.Fprintln(p.Output, description); err != nil {
return 0, err
}
optfmt := fmt.Sprintf("[%%%dd] %%s\n", len(strconv.Itoa(len(opts))))
for i, opt := range opts {
if opt != "" {
if _, err := fmt.Fprintf(p.Output, optfmt, i, opt); err != nil {
return 0, err
}
}
}
for {
if _, err := fmt.Fprint(p.Output, prompt); err != nil {
return 0, err
}
var s string
if _, err := fmt.Fscanln(p.Input, &s); err != nil {
return 0, err
}
n, err := strconv.Atoi(s)
if err == nil && n >= 0 && n < len(opts) && opts[n] != "" {
return n, nil
}
if _, err := fmt.Fprintf(p.ErrOutput, "%s is invalid option\n", s); err != nil {
return 0, err
}
}
}
func (p *Prompt) YesNo(description string, defaultVal bool, prompt rune) (bool, error) {
if _, err := fmt.Fprintln(p.Output, description); err != nil {
return false, err
}
for {
ynfmt := "[y/N]%c"
if defaultVal {
ynfmt = "[Y/n]%c"
}
if _, err := fmt.Fprintf(p.Output, ynfmt, prompt); err != nil {
return false, err
}
var s string
if _, err := fmt.Fscanln(p.Input, &s); err != nil {
return false, err
}
switch strings.ToUpper(s) {
case "Y", "YES", "OK":
return true, nil
case "N", "NO":
return false, nil
case "":
return defaultVal, nil
}
if _, err := fmt.Fprintf(p.ErrOutput, "%s is invalid option", s); err != nil {
return false, err
}
}
}