input.go 1.7 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879
  1. package text
  2. import (
  3. "bufio"
  4. "fmt"
  5. "strings"
  6. "unicode"
  7. "unicode/utf8"
  8. "github.com/leonelquinteros/gotext"
  9. )
  10. func (l *Logger) GetInput(defaultValue string, noConfirm bool) (string, error) {
  11. l.Info()
  12. if defaultValue != "" || noConfirm {
  13. l.Println(defaultValue)
  14. return defaultValue, nil
  15. }
  16. reader := bufio.NewReader(l.r)
  17. buf, overflow, err := reader.ReadLine()
  18. if err != nil {
  19. return "", err
  20. }
  21. if overflow {
  22. return "", ErrInputOverflow{}
  23. }
  24. return string(buf), nil
  25. }
  26. // ContinueTask prompts if user wants to continue task.
  27. // If NoConfirm is set the action will continue without user input.
  28. func (l *Logger) ContinueTask(s string, preset, noConfirm bool) bool {
  29. if noConfirm {
  30. return preset
  31. }
  32. var (
  33. response string
  34. postFix string
  35. n string
  36. y string
  37. yes = gotext.Get("yes")
  38. no = gotext.Get("no")
  39. )
  40. // Only use localized "y" and "n" if they are latin characters.
  41. if nRune, _ := utf8.DecodeRuneInString(no); unicode.Is(unicode.Latin, nRune) {
  42. n = string(nRune)
  43. } else {
  44. n = nDefault
  45. }
  46. if yRune, _ := utf8.DecodeRuneInString(yes); unicode.Is(unicode.Latin, yRune) {
  47. y = string(yRune)
  48. } else {
  49. y = yDefault
  50. }
  51. if preset { // If default behavior is true, use y as default.
  52. postFix = fmt.Sprintf(" [%s/%s] ", strings.ToUpper(y), n)
  53. } else { // If default behavior is anything else, use n as default.
  54. postFix = fmt.Sprintf(" [%s/%s] ", y, strings.ToUpper(n))
  55. }
  56. l.OperationInfo(Bold(s), Bold(postFix))
  57. if _, err := fmt.Fscanln(l.r, &response); err != nil {
  58. return preset
  59. }
  60. return strings.EqualFold(response, yes) ||
  61. strings.EqualFold(response, y) ||
  62. (!strings.EqualFold(yDefault, n) && strings.EqualFold(response, yDefault))
  63. }