password.go 2.0 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586
  1. package survey
  2. import (
  3. "fmt"
  4. "gopkg.in/AlecAivazis/survey.v1/core"
  5. "gopkg.in/AlecAivazis/survey.v1/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. fmt.Fprint(terminal.NewAnsiStdout(p.Stdio().Out), out)
  36. if err != nil {
  37. return "", err
  38. }
  39. rr := p.NewRuneReader()
  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. cursor := p.NewCursor()
  48. // process answers looking for help prompt answer
  49. for {
  50. line, err := rr.ReadLine('*')
  51. if err != nil {
  52. return string(line), err
  53. }
  54. if string(line) == string(core.HelpInputRune) {
  55. // terminal will echo the \n so we need to jump back up one row
  56. cursor.PreviousLine(1)
  57. err = p.Render(
  58. PasswordQuestionTemplate,
  59. PasswordTemplateData{Password: *p, ShowHelp: true},
  60. )
  61. if err != nil {
  62. return "", err
  63. }
  64. continue
  65. }
  66. return string(line), err
  67. }
  68. }
  69. // Cleanup hides the string with a fixed number of characters.
  70. func (prompt *Password) Cleanup(val interface{}) error {
  71. return nil
  72. }