prompt.go 1.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081
  1. package utils
  2. import (
  3. "bufio"
  4. "errors"
  5. "fmt"
  6. "os"
  7. "strings"
  8. "github.com/AlecAivazis/survey/v2"
  9. "golang.org/x/crypto/ssh/terminal"
  10. )
  11. // PromptPlaintext prompts a user to input plain text
  12. func PromptPlaintext(prompt string) (string, error) {
  13. reader := bufio.NewReader(os.Stdin)
  14. fmt.Print(prompt)
  15. text, err := reader.ReadString('\n')
  16. if err != nil {
  17. return "", err
  18. }
  19. return strings.TrimSpace(text), nil
  20. }
  21. // PromptPassword prompts a user to input a hidden field
  22. func PromptPassword(prompt string) (string, error) {
  23. fmt.Print(prompt)
  24. pw, err := terminal.ReadPassword(0)
  25. fmt.Print("\r")
  26. if err != nil {
  27. return "", err
  28. }
  29. return strings.TrimSpace(string(pw)), nil
  30. }
  31. // PromptPasswordWithConfirmation is a helper function to prompt
  32. // for a password twice
  33. func PromptPasswordWithConfirmation() (string, error) {
  34. pw, err := PromptPassword("Password: ")
  35. if err != nil {
  36. return "", err
  37. }
  38. confirmPw, err := PromptPassword("Confirm password: ")
  39. if err != nil {
  40. return "", err
  41. }
  42. if pw != confirmPw {
  43. return "", errors.New("Passwords do not match")
  44. }
  45. return pw, nil
  46. }
  47. type selectAnswer struct {
  48. Response string `survey:"response"`
  49. }
  50. func PromptSelect(prompt string, options []string) (string, error) {
  51. var qs = []*survey.Question{
  52. {
  53. Name: "response",
  54. Prompt: &survey.Select{
  55. Message: prompt,
  56. Options: options,
  57. Default: options[0],
  58. },
  59. },
  60. }
  61. ans := &selectAnswer{}
  62. err := survey.Ask(qs, ans)
  63. return ans.Response, err
  64. }