/
confirm.go
93 lines (78 loc) · 2.64 KB
/
confirm.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
package prompts
import (
"fmt"
"github.com/manifoldco/promptui"
"github.com/manifoldco/torus-cli/errs"
"github.com/manifoldco/torus-cli/prefs"
"github.com/manifoldco/torus-cli/ui"
"github.com/manifoldco/torus-cli/validate"
)
// Confirm prompts the user to perform an action, accepting optional
// labels and a preamble warning.
//
// If no warning is provided, a warning will not be displayed. If no label is
// provided, a default label will be used.
//
// A confirm prompt should be defaultYes if the user has asked for this
// explicit action (e.g. we want to destroy a machine). If this prompt is due
// to a possible side effect (e.g. changing a password while updating a profie)
// then defaultYes should be false.
//
// Similar to defaultYes, defaultValue should be true in situations where the
// user is explicitly asking to do something. This way, when we're not attached
// to a terminal we won't ask the user to confirm they want to perform the
// action, we'll just do it. In these situations where scripting is expected,
// defaultValue can be set by the value of a `--yes` flag.
func Confirm(labelOverride, warning *string, defaultValue bool, defaultYes bool) (bool, error) {
preferences, err := prefs.NewPreferences()
if err != nil {
return false, nil
}
if preferences.Core.AutoConfirm {
return true, nil
}
if defaultValue && !ui.Attached() {
return true, nil
}
if !ui.Attached() {
return false, errs.ErrTerminalRequired
}
label := "Do you wish to continue"
if labelOverride != nil {
label = *labelOverride
}
if warning != nil {
ui.Warn(*warning)
}
options := "(Y/n)"
if defaultYes {
options = "(y/N)"
}
questionTmpl := `%s {{ . | bold }} {{ "` + options + `" | faint }}? `
confirmer := validate.Confirmer(defaultYes)
tmpl := &promptui.PromptTemplates{
Confirm: fmt.Sprintf(questionTmpl, ui.BoldString(promptui.IconInitial)),
Prompt: fmt.Sprintf(questionTmpl, ui.BoldString(promptui.IconGood)),
Valid: fmt.Sprintf(questionTmpl, ui.BoldString(promptui.IconGood)),
Success: "", // promptui doesnt use this right now
Invalid: fmt.Sprintf(questionTmpl, ui.BoldString(promptui.IconBad)),
ValidationError: validationErrorTmpl,
}
// Use a template to clean up the actual prompts. error state and finish
// state
prompt := promptui.Prompt{
Label: label,
IsConfirm: true,
IsVimMode: preferences.Core.Vim,
Validate: promptui.ValidateFunc(confirmer),
Templates: tmpl,
}
_, err = prompt.Run()
if err == promptui.ErrAbort || err == promptui.ErrEOF || err == promptui.ErrInterrupt {
return false, nil
}
if err == nil {
return true, nil
}
return false, err
}