/
cli_extension.go
68 lines (60 loc) · 1.4 KB
/
cli_extension.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
package common
import (
"fmt"
"os"
"strings"
input "github.com/tcnksm/go-input"
)
// CliExtension is an interface for defining extended cli actions
type CliExtension interface {
Prompt(message string, def bool) (bool, error)
}
// CliAdditions exposes methods to prompt the user for cli input
type CliAdditions struct{}
// Prompt prompts the user to answer a yes/no question
func (cli *CliAdditions) Prompt(message string, def bool) (bool, error) {
ui := NewUI()
defPrompt := "no"
if def {
defPrompt = "yes"
}
answer, err := ui.Ask(message, &input.Options{
Default: defPrompt,
Required: true,
Loop: true,
ValidateFunc: func(s string) error {
if s != "yes" && s != "no" {
return fmt.Errorf("input must be yes or no")
}
return nil
},
HideOrder: true,
})
line := strings.ToLower(answer)
if line == "yes" {
return true, err
}
if line == "no" {
return false, err
}
return def, err
}
// GetPasswdPrompt prompts the user to enter a password
func (cli *CliAdditions) GetPasswdPrompt(message string) (string, error) {
ui := NewUI()
password, err := ui.Ask(message, &input.Options{
Required: true,
Loop: true,
Mask: true,
MaskDefault: true,
HideOrder: true,
})
return strings.TrimSpace(password), err
}
// NewUI returns a new input.UI bound to Std(in/out)
func NewUI() *input.UI {
return &input.UI{
Writer: os.Stdout,
Reader: os.Stdin,
}
}