-
Notifications
You must be signed in to change notification settings - Fork 53
/
Copy pathui.go
105 lines (89 loc) · 1.78 KB
/
ui.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
93
94
95
96
97
98
99
100
101
102
103
104
105
package main
import (
"fmt"
"strconv"
"strings"
"time"
"github.com/briandowns/spinner"
"github.com/urfave/cli"
)
func ask(question string) string {
var answer string
fmt.Printf("%s: ", question)
fmt.Scanln(&answer)
return answer
}
func askString(question, def string) string {
prompt := question
if def != "" {
prompt += fmt.Sprintf(" [%s]", def)
}
res := ask(prompt)
if res == "" {
return def
}
return res
}
func askInt(question string, def int) int {
prompt := fmt.Sprintf("%s [%d]", question, def)
res := ask(prompt)
if res == "" {
return def
}
i, err := strconv.Atoi(res)
if err != nil {
return askInt(question, def)
}
return i
}
func askBool(question string, def bool) bool {
defString := "yes"
if !def {
defString = "no"
}
prompt := fmt.Sprintf("%s [%v]", question, defString)
res := ask(prompt)
switch strings.ToLower(res) {
case "yes", "y":
return true
case "no", "n":
return false
case "":
return def
default:
return askBool(question, def)
}
}
func confirm(question string) bool {
answer := ask(question)
switch strings.ToLower(answer) {
case "yes", "y":
return true
case "no", "n":
return false
default:
return confirm(question)
}
}
func spin(prefix string, f func() error) *cli.ExitError {
spin := spinner.New(spinner.CharSets[9], time.Millisecond*100)
spin.Prefix = fmt.Sprintf("%s: ", prefix)
spin.Start()
err := f()
spin.Stop()
if err != nil {
cliError, ok := err.(*cli.ExitError)
if ok {
if cliError.ExitCode() != 0 {
fmt.Printf("\r%s: ERROR!\n", prefix)
return cliError
}
fmt.Printf("\r%s: done\n", prefix)
return cli.NewExitError("", 0)
}
fmt.Printf("\r%s: ERROR!\n", prefix)
return cli.NewExitError(err.Error(), 1)
}
fmt.Printf("\r%s: done\n", prefix)
return cli.NewExitError("", 0)
}