File: ui.go

package info (click to toggle)
golang-github-smallstep-cli 0.15.16%2Bds-3
  • links: PTS, VCS
  • area: main
  • in suites: bookworm
  • size: 4,404 kB
  • sloc: sh: 512; makefile: 99
file content (322 lines) | stat: -rw-r--r-- 7,934 bytes parent folder | download | duplicates (2)
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
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
package ui

import (
	"fmt"
	"os"
	"strings"
	"text/template"

	"github.com/chzyer/readline"
	"github.com/manifoldco/promptui"
	"github.com/pkg/errors"
	"github.com/smallstep/cli/crypto/randutil"
)

// stderr implements an io.WriteCloser that skips the terminal bell character
// (ASCII code 7), and writes the rest to os.Stderr. It's used to replace
// readline.Stdout, that is the package used by promptui to display the prompts.
type stderr struct{}

// Write implements an io.WriterCloser over os.Stderr, but it skips the terminal
// bell character.
func (s *stderr) Write(b []byte) (int, error) {
	if len(b) == 1 && b[0] == readline.CharBell {
		return 0, nil
	}
	return os.Stderr.Write(b)
}

// Close implements an io.WriterCloser over os.Stderr.
func (s *stderr) Close() error {
	return os.Stderr.Close()
}

func init() {
	readline.Stdout = &stderr{}
}

// Print uses templates to print the arguments formated to os.Stderr.
func Print(args ...interface{}) error {
	var o options
	opts, args := extractOptions(args)
	o.apply(opts)

	// Return with a default value. This is useful when we split the question
	// and the response in two lines.
	if o.value != "" && o.valid() {
		return nil
	}

	text := fmt.Sprint(args...)
	t, err := template.New("Print").Funcs(promptui.FuncMap).Parse(text)
	if err != nil {
		return errors.Wrap(err, "error parsing template")
	}
	if err := t.Execute(os.Stderr, nil); err != nil {
		return errors.Wrap(err, "error executing template")
	}
	return nil
}

// Printf uses templates to print the string formated to os.Stderr.
func Printf(format string, args ...interface{}) error {
	var o options
	opts, args := extractOptions(args)
	o.apply(opts)

	// Return with a default value. This is useful when we split the question
	// and the response in two lines.
	if o.value != "" && o.valid() {
		return nil
	}

	text := fmt.Sprintf(format, args...)
	t, err := template.New("Printf").Funcs(promptui.FuncMap).Parse(text)
	if err != nil {
		return errors.Wrap(err, "error parsing template")
	}
	if err := t.Execute(os.Stderr, nil); err != nil {
		return errors.Wrap(err, "error executing template")
	}
	return nil
}

// Println uses templates to print the given arguments to os.Stderr
func Println(args ...interface{}) error {
	var o options
	opts, args := extractOptions(args)
	o.apply(opts)

	// Return with a default value. This is useful when we split the question
	// and the response in two lines.
	if o.value != "" && o.valid() {
		return nil
	}

	text := fmt.Sprintln(args...)
	t, err := template.New("Println").Funcs(promptui.FuncMap).Parse(text)
	if err != nil {
		return errors.Wrap(err, "error parsing template")
	}
	if err := t.Execute(os.Stderr, nil); err != nil {
		return errors.Wrap(err, "error executing template")
	}
	return nil
}

// PrintSelected prints the given name and value as if they were selected from a
// promptui.Select.
func PrintSelected(name, value string, opts ...Option) error {
	o := &options{
		printTemplate: PrintSelectedTemplate(),
	}
	o.apply(opts)

	t, err := template.New(name).Funcs(promptui.FuncMap).Parse(o.printTemplate)
	if err != nil {
		return errors.Wrap(err, "error parsing template")
	}

	data := struct {
		Name  string
		Value string
	}{name, value}
	if err := t.Execute(os.Stderr, data); err != nil {
		return errors.Wrap(err, "error executing template")
	}

	return nil
}

// Prompt creates and runs a promptui.Prompt with the given label.
func Prompt(label string, opts ...Option) (string, error) {
	o := &options{
		promptTemplates: PromptTemplates(),
	}
	o.apply(opts)

	// Return value if set
	if o.value != "" {
		return o.getValue()
	}

	// Prompt using the terminal
	clean, err := preparePromptTerminal()
	if err != nil {
		return "", err
	}
	defer clean()

	prompt := &promptui.Prompt{
		Label:     label,
		Default:   o.defaultValue,
		AllowEdit: o.allowEdit,
		Validate:  o.validateFunc,
		Templates: o.promptTemplates,
	}
	value, err := prompt.Run()
	if err != nil {
		return "", errors.Wrap(err, "error running prompt")
	}
	return value, nil
}

// PromptPassword creates and runs a promptui.Prompt with the given label. This
// prompt will mask the key entries with \r.
func PromptPassword(label string, opts ...Option) ([]byte, error) {
	// Using a not printable character as they work better than \r
	o := &options{
		mask:            1,
		promptTemplates: SimplePromptTemplates(),
	}
	o.apply(opts)

	// Return value if set
	if o.value != "" {
		return o.getValueBytes()
	}

	// Prompt using the terminal
	clean, err := preparePromptTerminal()
	if err != nil {
		return nil, err
	}
	defer clean()

	prompt := &promptui.Prompt{
		Label:     label,
		Mask:      o.mask,
		Default:   o.defaultValue,
		AllowEdit: o.allowEdit,
		Validate:  o.validateFunc,
		Templates: o.promptTemplates,
	}
	pass, err := prompt.Run()
	if err != nil {
		return nil, errors.Wrap(err, "error reading password")
	}
	return []byte(pass), nil
}

// PromptPasswordGenerate creates and runs a promptui.Prompt with the given label.
// This prompt will mask the key entries with \r. If the result password length
// is 0, it will generate a new prompt with a generated password that can be
// edited.
func PromptPasswordGenerate(label string, opts ...Option) ([]byte, error) {
	pass, err := PromptPassword(label, opts...)
	if err != nil || len(pass) > 0 {
		return pass, err
	}
	passString, err := randutil.ASCII(32)
	if err != nil {
		return nil, err
	}
	passString, err = Prompt("Password", WithDefaultValue(passString), WithAllowEdit(true), WithValidateNotEmpty())
	if err != nil {
		return nil, err
	}
	return []byte(passString), nil
}

// PromptYesNo creates and runs a promptui.Prompt with the given label, and
// returns true if the answer is y/yes and false if the answer is n/no.
func PromptYesNo(label string, opts ...Option) (bool, error) {
	opts = append([]Option{WithValidateYesNo()}, opts...)
	s, err := Prompt(label, opts...)
	if err != nil {
		return false, err
	}
	switch strings.ToLower(strings.TrimSpace(s)) {
	case "y", "yes":
		return true, nil
	case "n", "no":
		return false, nil
	default:
		return false, fmt.Errorf("%s is not a valid answer", s)
	}
}

// Select creates and runs a promptui.Select with the given label and items.
func Select(label string, items interface{}, opts ...Option) (int, string, error) {
	o := &options{
		selectTemplates: SelectTemplates(label),
	}
	o.apply(opts)

	clean, err := prepareSelectTerminal()
	if err != nil {
		return 0, "", err
	}
	defer clean()

	prompt := &promptui.Select{
		Label:     label,
		Items:     items,
		Templates: o.selectTemplates,
	}
	n, s, err := prompt.Run()
	if err != nil {
		return 0, "", errors.Wrap(err, "error running prompt")
	}
	return n, s, nil
}

func preparePromptTerminal() (func(), error) {
	nothing := func() {}
	if !readline.DefaultIsTerminal() {
		tty, err := os.Open("/dev/tty")
		if err != nil {
			return nothing, errors.Wrap(err, "error allocating terminal")
		}
		clean := func() {
			tty.Close()
		}

		fd := int(tty.Fd())
		state, err := readline.MakeRaw(fd)
		if err != nil {
			defer clean()
			return nothing, errors.Wrap(err, "error making raw terminal")
		}
		stdin := readline.Stdin
		readline.Stdin = tty
		clean = func() {
			readline.Stdin = stdin
			readline.Restore(fd, state)
			tty.Close()
		}
		return clean, nil
	}

	return nothing, nil
}

func prepareSelectTerminal() (func(), error) {
	nothing := func() {}
	if !readline.DefaultIsTerminal() {
		tty, err := os.Open("/dev/tty")
		if err != nil {
			return nothing, errors.Wrap(err, "error allocating terminal")
		}
		clean := func() {
			tty.Close()
		}

		fd := int(tty.Fd())
		state, err := readline.MakeRaw(fd)
		if err != nil {
			defer clean()
			return nothing, errors.Wrap(err, "error making raw terminal")
		}
		stdin := os.Stdin
		os.Stdin = tty
		clean = func() {
			os.Stdin = stdin
			readline.Restore(fd, state)
			tty.Close()
		}
		return clean, nil
	}

	return nothing, nil
}