string.go 2.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113
  1. package util
  2. import (
  3. "strings"
  4. "github.com/tal-tech/go-zero/tools/goctl/util/console"
  5. )
  6. var goKeyword = map[string]string{
  7. "var": "variable",
  8. "const": "constant",
  9. "package": "pkg",
  10. "func": "function",
  11. "return": "rtn",
  12. "defer": "dfr",
  13. "go": "goo",
  14. "select": "slt",
  15. "struct": "structure",
  16. "interface": "itf",
  17. "chan": "channel",
  18. "type": "tp",
  19. "map": "mp",
  20. "range": "rg",
  21. "break": "brk",
  22. "case": "caz",
  23. "continue": "ctn",
  24. "for": "fr",
  25. "fallthrough": "fth",
  26. "else": "es",
  27. "if": "ef",
  28. "switch": "swt",
  29. "goto": "gt",
  30. "default": "dft",
  31. }
  32. // Title returns a string value with s[0] which has been convert into upper case that
  33. // there are not empty input text
  34. func Title(s string) string {
  35. if len(s) == 0 {
  36. return s
  37. }
  38. return strings.ToUpper(s[:1]) + s[1:]
  39. }
  40. // Untitle returns a string value with s[0] which has been convert into lower case that
  41. // there are not empty input text
  42. func Untitle(s string) string {
  43. if len(s) == 0 {
  44. return s
  45. }
  46. return strings.ToLower(s[:1]) + s[1:]
  47. }
  48. // Index returns the index where the item equal,it will return -1 if mismatched
  49. func Index(slice []string, item string) int {
  50. for i := range slice {
  51. if slice[i] == item {
  52. return i
  53. }
  54. }
  55. return -1
  56. }
  57. // SafeString converts the input string into a safe naming style in golang
  58. func SafeString(in string) string {
  59. if len(in) == 0 {
  60. return in
  61. }
  62. data := strings.Map(func(r rune) rune {
  63. if isSafeRune(r) {
  64. return r
  65. }
  66. return '_'
  67. }, in)
  68. headRune := rune(data[0])
  69. if isNumber(headRune) {
  70. return "_" + data
  71. }
  72. return data
  73. }
  74. func isSafeRune(r rune) bool {
  75. return isLetter(r) || isNumber(r) || r == '_'
  76. }
  77. func isLetter(r rune) bool {
  78. return 'A' <= r && r <= 'z'
  79. }
  80. func isNumber(r rune) bool {
  81. return '0' <= r && r <= '9'
  82. }
  83. // EscapeGolangKeyword escapes the golang keywords.
  84. func EscapeGolangKeyword(s string) string {
  85. if !isGolangKeyword(s) {
  86. return s
  87. }
  88. r := goKeyword[s]
  89. console.Info("[EscapeGolangKeyword]: go keyword is forbidden %q, converted into %q", s, r)
  90. return r
  91. }
  92. func isGolangKeyword(s string) bool {
  93. _, ok := goKeyword[s]
  94. return ok
  95. }