password.go 2.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384
  1. package survey
  2. import (
  3. "os"
  4. "github.com/kataras/survey/core"
  5. "github.com/kataras/survey/terminal"
  6. )
  7. /*
  8. Password is like a normal Input but the text shows up as *'s and there is no default. Response
  9. type is a string.
  10. password := ""
  11. prompt := &survey.Password{ Message: "Please type your password" }
  12. survey.AskOne(prompt, &password, nil)
  13. */
  14. type Password struct {
  15. core.Renderer
  16. Message string
  17. Help string
  18. }
  19. type PasswordTemplateData struct {
  20. Password
  21. ShowHelp bool
  22. }
  23. // Templates with Color formatting. See Documentation: https://github.com/mgutz/ansi#style-format
  24. var PasswordQuestionTemplate = `
  25. {{- if .ShowHelp }}{{- color "cyan"}}{{ HelpIcon }} {{ .Help }}{{color "reset"}}{{"\n"}}{{end}}
  26. {{- color "green+hb"}}{{ QuestionIcon }} {{color "reset"}}
  27. {{- color "default+hb"}}{{ .Message }} {{color "reset"}}
  28. {{- if and .Help (not .ShowHelp)}}{{color "cyan"}}[{{ HelpInputRune }} for help]{{color "reset"}} {{end}}`
  29. func (p *Password) Prompt() (line interface{}, err error) {
  30. // render the question template
  31. out, err := core.RunTemplate(
  32. PasswordQuestionTemplate,
  33. PasswordTemplateData{Password: *p},
  34. )
  35. terminal.Print(out)
  36. if err != nil {
  37. return "", err
  38. }
  39. rr := terminal.NewRuneReader(os.Stdin)
  40. rr.SetTermMode()
  41. defer rr.RestoreTermMode()
  42. // no help msg? Just return any response
  43. if p.Help == "" {
  44. line, err := rr.ReadLine('*')
  45. return string(line), err
  46. }
  47. // process answers looking for help prompt answer
  48. for {
  49. line, err := rr.ReadLine('*')
  50. if err != nil {
  51. return string(line), err
  52. }
  53. if string(line) == string(core.HelpInputRune) {
  54. // terminal will echo the \n so we need to jump back up one row
  55. terminal.CursorPreviousLine(1)
  56. err = p.Render(
  57. PasswordQuestionTemplate,
  58. PasswordTemplateData{Password: *p, ShowHelp: true},
  59. )
  60. if err != nil {
  61. return "", err
  62. }
  63. continue
  64. }
  65. return string(line), err
  66. }
  67. }
  68. // Cleanup hides the string with a fixed number of characters.
  69. func (prompt *Password) Cleanup(val interface{}) error {
  70. return nil
  71. }