text.go 2.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100
  1. package text
  2. import (
  3. "fmt"
  4. "io"
  5. "strings"
  6. "unicode"
  7. "unicode/utf8"
  8. "github.com/leonelquinteros/gotext"
  9. )
  10. const (
  11. yDefault = "y"
  12. nDefault = "n"
  13. )
  14. // SplitDBFromName split apart db/package to db and package.
  15. func SplitDBFromName(pkg string) (db, name string) {
  16. split := strings.SplitN(pkg, "/", 2)
  17. if len(split) == 2 {
  18. return split[0], split[1]
  19. }
  20. return "", split[0]
  21. }
  22. // LessRunes compares two rune values, and returns true if the first argument is lexicographicaly smaller.
  23. func LessRunes(iRunes, jRunes []rune) bool {
  24. max := len(iRunes)
  25. if max > len(jRunes) {
  26. max = len(jRunes)
  27. }
  28. for idx := 0; idx < max; idx++ {
  29. ir := iRunes[idx]
  30. jr := jRunes[idx]
  31. lir := unicode.ToLower(ir)
  32. ljr := unicode.ToLower(jr)
  33. if lir != ljr {
  34. return lir < ljr
  35. }
  36. // the lowercase runes are the same, so compare the original
  37. if ir != jr {
  38. return ir < jr
  39. }
  40. }
  41. return len(iRunes) < len(jRunes)
  42. }
  43. // ContinueTask prompts if user wants to continue task.
  44. // If NoConfirm is set the action will continue without user input.
  45. func ContinueTask(input io.Reader, s string, preset, noConfirm bool) bool {
  46. if noConfirm {
  47. return preset
  48. }
  49. var (
  50. response string
  51. postFix string
  52. n string
  53. y string
  54. yes = gotext.Get("yes")
  55. no = gotext.Get("no")
  56. )
  57. // Only use localized "y" and "n" if they are latin characters.
  58. if nRune, _ := utf8.DecodeRuneInString(no); unicode.Is(unicode.Latin, nRune) {
  59. n = string(nRune)
  60. } else {
  61. n = nDefault
  62. }
  63. if yRune, _ := utf8.DecodeRuneInString(yes); unicode.Is(unicode.Latin, yRune) {
  64. y = string(yRune)
  65. } else {
  66. y = yDefault
  67. }
  68. if preset { // If default behavior is true, use y as default.
  69. postFix = fmt.Sprintf(" [%s/%s] ", strings.ToUpper(y), n)
  70. } else { // If default behavior is anything else, use n as default.
  71. postFix = fmt.Sprintf(" [%s/%s] ", y, strings.ToUpper(n))
  72. }
  73. OperationInfo(Bold(s), Bold(postFix))
  74. if _, err := fmt.Fscanln(input, &response); err != nil {
  75. return preset
  76. }
  77. return strings.EqualFold(response, yes) ||
  78. strings.EqualFold(response, y) ||
  79. (!strings.EqualFold(yDefault, n) && strings.EqualFold(response, yDefault))
  80. }