prompt.go 1.7 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394
  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. }
  65. func PromptMultiselect(prompt string, options []string) ([]string, error) {
  66. query := &survey.MultiSelect{
  67. Message: prompt,
  68. Options: options,
  69. }
  70. var ans []string
  71. err := survey.AskOne(query, &ans)
  72. return ans, err
  73. }