Debian Codegraph @

ui/ui.go

raw symbols SCIP
1 package ui
2
3 import (
4 "fmt"
5 "os"
6 "strings"
7 "text/template"
8
9 "github.com/chzyer/readline"
10 "github.com/manifoldco/promptui"
11 "github.com/pkg/errors"
12 "github.com/smallstep/cli/crypto/randutil"
13 )
14
15 // stderr implements an io.WriteCloser that skips the terminal bell character
16 // (ASCII code 7), and writes the rest to os.Stderr. It's used to replace
17 // readline.Stdout, that is the package used by promptui to display the prompts.
18 type stderr struct{}
19
20 // Write implements an io.WriterCloser over os.Stderr, but it skips the terminal
21 // bell character.
22 func (s *stderr) Write(b []byte) (int, error) {
23 if len(b) == 1 && b[0] == readline.CharBell {
24 return 0, nil
25 }
26 return os.Stderr.Write(b)
27 }
28
29 // Close implements an io.WriterCloser over os.Stderr.
30 func (s *stderr) Close() error {
31 return os.Stderr.Close()
32 }
33
34 func init() {
35 readline.Stdout = &stderr{}
36 }
37
38 // Print uses templates to print the arguments formated to os.Stderr.
39 func Print(args ...interface{}) error {
40 var o options
41 opts, args := extractOptions(args)
42 o.apply(opts)
43
44 // Return with a default value. This is useful when we split the question
45 // and the response in two lines.
46 if o.value != "" && o.valid() {
47 return nil
48 }
49
50 text := fmt.Sprint(args...)
51 t, err := template.New("Print").Funcs(promptui.FuncMap).Parse(text)
52 if err != nil {
53 return errors.Wrap(err, "error parsing template")
54 }
55 if err := t.Execute(os.Stderr, nil); err != nil {
56 return errors.Wrap(err, "error executing template")
57 }
58 return nil
59 }
60
61 // Printf uses templates to print the string formated to os.Stderr.
62 func Printf(format string, args ...interface{}) error {
63 var o options
64 opts, args := extractOptions(args)
65 o.apply(opts)
66
67 // Return with a default value. This is useful when we split the question
68 // and the response in two lines.
69 if o.value != "" && o.valid() {
70 return nil
71 }
72
73 text := fmt.Sprintf(format, args...)
74 t, err := template.New("Printf").Funcs(promptui.FuncMap).Parse(text)
75 if err != nil {
76 return errors.Wrap(err, "error parsing template")
77 }
78 if err := t.Execute(os.Stderr, nil); err != nil {
79 return errors.Wrap(err, "error executing template")
80 }
81 return nil
82 }
83
84 // Println uses templates to print the given arguments to os.Stderr
85 func Println(args ...interface{}) error {
86 var o options
87 opts, args := extractOptions(args)
88 o.apply(opts)
89
90 // Return with a default value. This is useful when we split the question
91 // and the response in two lines.
92 if o.value != "" && o.valid() {
93 return nil
94 }
95
96 text := fmt.Sprintln(args...)
97 t, err := template.New("Println").Funcs(promptui.FuncMap).Parse(text)
98 if err != nil {
99 return errors.Wrap(err, "error parsing template")
100 }
101 if err := t.Execute(os.Stderr, nil); err != nil {
102 return errors.Wrap(err, "error executing template")
103 }
104 return nil
105 }
106
107 // PrintSelected prints the given name and value as if they were selected from a
108 // promptui.Select.
109 func PrintSelected(name, value string, opts ...Option) error {
110 o := &options{
111 printTemplate: PrintSelectedTemplate(),
112 }
113 o.apply(opts)
114
115 t, err := template.New(name).Funcs(promptui.FuncMap).Parse(o.printTemplate)
116 if err != nil {
117 return errors.Wrap(err, "error parsing template")
118 }
119
120 data := struct {
121 Name string
122 Value string
123 }{name, value}
124 if err := t.Execute(os.Stderr, data); err != nil {
125 return errors.Wrap(err, "error executing template")
126 }
127
128 return nil
129 }
130
131 // Prompt creates and runs a promptui.Prompt with the given label.
132 func Prompt(label string, opts ...Option) (string, error) {
133 o := &options{
134 promptTemplates: PromptTemplates(),
135 }
136 o.apply(opts)
137
138 // Return value if set
139 if o.value != "" {
140 return o.getValue()
141 }
142
143 // Prompt using the terminal
144 clean, err := preparePromptTerminal()
145 if err != nil {
146 return "", err
147 }
148 defer clean()
149
150 prompt := &promptui.Prompt{
151 Label: label,
152 Default: o.defaultValue,
153 AllowEdit: o.allowEdit,
154 Validate: o.validateFunc,
155 Templates: o.promptTemplates,
156 }
157 value, err := prompt.Run()
158 if err != nil {
159 return "", errors.Wrap(err, "error running prompt")
160 }
161 return value, nil
162 }
163
164 // PromptPassword creates and runs a promptui.Prompt with the given label. This
165 // prompt will mask the key entries with \r.
166 func PromptPassword(label string, opts ...Option) ([]byte, error) {
167 // Using a not printable character as they work better than \r
168 o := &options{
169 mask: 1,
170 promptTemplates: SimplePromptTemplates(),
171 }
172 o.apply(opts)
173
174 // Return value if set
175 if o.value != "" {
176 return o.getValueBytes()
177 }
178
179 // Prompt using the terminal
180 clean, err := preparePromptTerminal()
181 if err != nil {
182 return nil, err
183 }
184 defer clean()
185
186 prompt := &promptui.Prompt{
187 Label: label,
188 Mask: o.mask,
189 Default: o.defaultValue,
190 AllowEdit: o.allowEdit,
191 Validate: o.validateFunc,
192 Templates: o.promptTemplates,
193 }
194 pass, err := prompt.Run()
195 if err != nil {
196 return nil, errors.Wrap(err, "error reading password")
197 }
198 return []byte(pass), nil
199 }
200
201 // PromptPasswordGenerate creates and runs a promptui.Prompt with the given label.
202 // This prompt will mask the key entries with \r. If the result password length
203 // is 0, it will generate a new prompt with a generated password that can be
204 // edited.
205 func PromptPasswordGenerate(label string, opts ...Option) ([]byte, error) {
206 pass, err := PromptPassword(label, opts...)
207 if err != nil || len(pass) > 0 {
208 return pass, err
209 }
210 passString, err := randutil.ASCII(32)
211 if err != nil {
212 return nil, err
213 }
214 passString, err = Prompt("Password", WithDefaultValue(passString), WithAllowEdit(true), WithValidateNotEmpty())
215 if err != nil {
216 return nil, err
217 }
218 return []byte(passString), nil
219 }
220
221 // PromptYesNo creates and runs a promptui.Prompt with the given label, and
222 // returns true if the answer is y/yes and false if the answer is n/no.
223 func PromptYesNo(label string, opts ...Option) (bool, error) {
224 opts = append([]Option{WithValidateYesNo()}, opts...)
225 s, err := Prompt(label, opts...)
226 if err != nil {
227 return false, err
228 }
229 switch strings.ToLower(strings.TrimSpace(s)) {
230 case "y", "yes":
231 return true, nil
232 case "n", "no":
233 return false, nil
234 default:
235 return false, fmt.Errorf("%s is not a valid answer", s)
236 }
237 }
238
239 // Select creates and runs a promptui.Select with the given label and items.
240 func Select(label string, items interface{}, opts ...Option) (int, string, error) {
241 o := &options{
242 selectTemplates: SelectTemplates(label),
243 }
244 o.apply(opts)
245
246 clean, err := prepareSelectTerminal()
247 if err != nil {
248 return 0, "", err
249 }
250 defer clean()
251
252 prompt := &promptui.Select{
253 Label: label,
254 Items: items,
255 Templates: o.selectTemplates,
256 }
257 n, s, err := prompt.Run()
258 if err != nil {
259 return 0, "", errors.Wrap(err, "error running prompt")
260 }
261 return n, s, nil
262 }
263
264 func preparePromptTerminal() (func(), error) {
265 nothing := func() {}
266 if !readline.DefaultIsTerminal() {
267 tty, err := os.Open("/dev/tty")
268 if err != nil {
269 return nothing, errors.Wrap(err, "error allocating terminal")
270 }
271 clean := func() {
272 tty.Close()
273 }
274
275 fd := int(tty.Fd())
276 state, err := readline.MakeRaw(fd)
277 if err != nil {
278 defer clean()
279 return nothing, errors.Wrap(err, "error making raw terminal")
280 }
281 stdin := readline.Stdin
282 readline.Stdin = tty
283 clean = func() {
284 readline.Stdin = stdin
285 readline.Restore(fd, state)
286 tty.Close()
287 }
288 return clean, nil
289 }
290
291 return nothing, nil
292 }
293
294 func prepareSelectTerminal() (func(), error) {
295 nothing := func() {}
296 if !readline.DefaultIsTerminal() {
297 tty, err := os.Open("/dev/tty")
298 if err != nil {
299 return nothing, errors.Wrap(err, "error allocating terminal")
300 }
301 clean := func() {
302 tty.Close()
303 }
304
305 fd := int(tty.Fd())
306 state, err := readline.MakeRaw(fd)
307 if err != nil {
308 defer clean()
309 return nothing, errors.Wrap(err, "error making raw terminal")
310 }
311 stdin := os.Stdin
312 os.Stdin = tty
313 clean = func() {
314 os.Stdin = stdin
315 readline.Restore(fd, state)
316 tty.Close()
317 }
318 return clean, nil
319 }
320
321 return nothing, nil
322 }