1package input
2
3import (
4 "bufio"
5 "fmt"
6 "os"
7 "strings"
8)
9
10func PromptValue(name string, preValue string) (string, error) {
11 return promptValue(name, preValue, false)
12}
13
14func PromptValueRequired(name string, preValue string) (string, error) {
15 return promptValue(name, preValue, true)
16}
17
18func promptValue(name string, preValue string, required bool) (string, error) {
19 for {
20 if preValue != "" {
21 _, _ = fmt.Fprintf(os.Stderr, "%s [%s]: ", name, preValue)
22 } else {
23 _, _ = fmt.Fprintf(os.Stderr, "%s: ", name)
24 }
25
26 line, err := bufio.NewReader(os.Stdin).ReadString('\n')
27 if err != nil {
28 return "", err
29 }
30
31 line = strings.TrimSpace(line)
32
33 if preValue != "" && line == "" {
34 return preValue, nil
35 }
36
37 if required && line == "" {
38 _, _ = fmt.Fprintf(os.Stderr, "%s is empty\n", name)
39 continue
40 }
41
42 return line, nil
43 }
44}