translator.go 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420
  1. package ut
  2. import (
  3. "fmt"
  4. "strconv"
  5. "strings"
  6. "github.com/go-playground/locales"
  7. )
  8. const (
  9. paramZero = "{0}"
  10. paramOne = "{1}"
  11. unknownTranslation = ""
  12. )
  13. // Translator is universal translators
  14. // translator instance which is a thin wrapper
  15. // around locales.Translator instance providing
  16. // some extra functionality
  17. type Translator interface {
  18. locales.Translator
  19. // adds a normal translation for a particular language/locale
  20. // {#} is the only replacement type accepted and are ad infinitum
  21. // eg. one: '{0} day left' other: '{0} days left'
  22. Add(key interface{}, text string, override bool) error
  23. // adds a cardinal plural translation for a particular language/locale
  24. // {0} is the only replacement type accepted and only one variable is accepted as
  25. // multiple cannot be used for a plural rule determination, unless it is a range;
  26. // see AddRange below.
  27. // eg. in locale 'en' one: '{0} day left' other: '{0} days left'
  28. AddCardinal(key interface{}, text string, rule locales.PluralRule, override bool) error
  29. // adds an ordinal plural translation for a particular language/locale
  30. // {0} is the only replacement type accepted and only one variable is accepted as
  31. // multiple cannot be used for a plural rule determination, unless it is a range;
  32. // see AddRange below.
  33. // eg. in locale 'en' one: '{0}st day of spring' other: '{0}nd day of spring'
  34. // - 1st, 2nd, 3rd...
  35. AddOrdinal(key interface{}, text string, rule locales.PluralRule, override bool) error
  36. // adds a range plural translation for a particular language/locale
  37. // {0} and {1} are the only replacement types accepted and only these are accepted.
  38. // eg. in locale 'nl' one: '{0}-{1} day left' other: '{0}-{1} days left'
  39. AddRange(key interface{}, text string, rule locales.PluralRule, override bool) error
  40. // creates the translation for the locale given the 'key' and params passed in
  41. T(key interface{}, params ...string) (string, error)
  42. // creates the cardinal translation for the locale given the 'key', 'num' and 'digit' arguments
  43. // and param passed in
  44. C(key interface{}, num float64, digits uint64, param string) (string, error)
  45. // creates the ordinal translation for the locale given the 'key', 'num' and 'digit' arguments
  46. // and param passed in
  47. O(key interface{}, num float64, digits uint64, param string) (string, error)
  48. // creates the range translation for the locale given the 'key', 'num1', 'digit1', 'num2' and
  49. // 'digit2' arguments and 'param1' and 'param2' passed in
  50. R(key interface{}, num1 float64, digits1 uint64, num2 float64, digits2 uint64, param1, param2 string) (string, error)
  51. // VerifyTranslations checks to ensures that no plural rules have been
  52. // missed within the translations.
  53. VerifyTranslations() error
  54. }
  55. var _ Translator = new(translator)
  56. var _ locales.Translator = new(translator)
  57. type translator struct {
  58. locales.Translator
  59. translations map[interface{}]*transText
  60. cardinalTanslations map[interface{}][]*transText // array index is mapped to locales.PluralRule index + the locales.PluralRuleUnknown
  61. ordinalTanslations map[interface{}][]*transText
  62. rangeTanslations map[interface{}][]*transText
  63. }
  64. type transText struct {
  65. text string
  66. indexes []int
  67. }
  68. func newTranslator(trans locales.Translator) Translator {
  69. return &translator{
  70. Translator: trans,
  71. translations: make(map[interface{}]*transText), // translation text broken up by byte index
  72. cardinalTanslations: make(map[interface{}][]*transText),
  73. ordinalTanslations: make(map[interface{}][]*transText),
  74. rangeTanslations: make(map[interface{}][]*transText),
  75. }
  76. }
  77. // Add adds a normal translation for a particular language/locale
  78. // {#} is the only replacement type accepted and are ad infinitum
  79. // eg. one: '{0} day left' other: '{0} days left'
  80. func (t *translator) Add(key interface{}, text string, override bool) error {
  81. if _, ok := t.translations[key]; ok && !override {
  82. return &ErrConflictingTranslation{locale: t.Locale(), key: key, text: text}
  83. }
  84. lb := strings.Count(text, "{")
  85. rb := strings.Count(text, "}")
  86. if lb != rb {
  87. return &ErrMissingBracket{locale: t.Locale(), key: key, text: text}
  88. }
  89. trans := &transText{
  90. text: text,
  91. }
  92. var idx int
  93. for i := 0; i < lb; i++ {
  94. s := "{" + strconv.Itoa(i) + "}"
  95. idx = strings.Index(text, s)
  96. if idx == -1 {
  97. return &ErrBadParamSyntax{locale: t.Locale(), param: s, key: key, text: text}
  98. }
  99. trans.indexes = append(trans.indexes, idx)
  100. trans.indexes = append(trans.indexes, idx+len(s))
  101. }
  102. t.translations[key] = trans
  103. return nil
  104. }
  105. // AddCardinal adds a cardinal plural translation for a particular language/locale
  106. // {0} is the only replacement type accepted and only one variable is accepted as
  107. // multiple cannot be used for a plural rule determination, unless it is a range;
  108. // see AddRange below.
  109. // eg. in locale 'en' one: '{0} day left' other: '{0} days left'
  110. func (t *translator) AddCardinal(key interface{}, text string, rule locales.PluralRule, override bool) error {
  111. var verified bool
  112. // verify plural rule exists for locale
  113. for _, pr := range t.PluralsCardinal() {
  114. if pr == rule {
  115. verified = true
  116. break
  117. }
  118. }
  119. if !verified {
  120. return &ErrCardinalTranslation{text: fmt.Sprintf("error: cardinal plural rule '%s' does not exist for locale '%s' key: '%v' text: '%s'", rule, t.Locale(), key, text)}
  121. }
  122. tarr, ok := t.cardinalTanslations[key]
  123. if ok {
  124. // verify not adding a conflicting record
  125. if len(tarr) > 0 && tarr[rule] != nil && !override {
  126. return &ErrConflictingTranslation{locale: t.Locale(), key: key, rule: rule, text: text}
  127. }
  128. } else {
  129. tarr = make([]*transText, 7, 7)
  130. t.cardinalTanslations[key] = tarr
  131. }
  132. trans := &transText{
  133. text: text,
  134. indexes: make([]int, 2, 2),
  135. }
  136. tarr[rule] = trans
  137. idx := strings.Index(text, paramZero)
  138. if idx == -1 {
  139. tarr[rule] = nil
  140. return &ErrCardinalTranslation{text: fmt.Sprintf("error: parameter '%s' not found, may want to use 'Add' instead of 'AddCardinal'. locale: '%s' key: '%v' text: '%s'", paramZero, t.Locale(), key, text)}
  141. }
  142. trans.indexes[0] = idx
  143. trans.indexes[1] = idx + len(paramZero)
  144. return nil
  145. }
  146. // AddOrdinal adds an ordinal plural translation for a particular language/locale
  147. // {0} is the only replacement type accepted and only one variable is accepted as
  148. // multiple cannot be used for a plural rule determination, unless it is a range;
  149. // see AddRange below.
  150. // eg. in locale 'en' one: '{0}st day of spring' other: '{0}nd day of spring' - 1st, 2nd, 3rd...
  151. func (t *translator) AddOrdinal(key interface{}, text string, rule locales.PluralRule, override bool) error {
  152. var verified bool
  153. // verify plural rule exists for locale
  154. for _, pr := range t.PluralsOrdinal() {
  155. if pr == rule {
  156. verified = true
  157. break
  158. }
  159. }
  160. if !verified {
  161. return &ErrOrdinalTranslation{text: fmt.Sprintf("error: ordinal plural rule '%s' does not exist for locale '%s' key: '%v' text: '%s'", rule, t.Locale(), key, text)}
  162. }
  163. tarr, ok := t.ordinalTanslations[key]
  164. if ok {
  165. // verify not adding a conflicting record
  166. if len(tarr) > 0 && tarr[rule] != nil && !override {
  167. return &ErrConflictingTranslation{locale: t.Locale(), key: key, rule: rule, text: text}
  168. }
  169. } else {
  170. tarr = make([]*transText, 7, 7)
  171. t.ordinalTanslations[key] = tarr
  172. }
  173. trans := &transText{
  174. text: text,
  175. indexes: make([]int, 2, 2),
  176. }
  177. tarr[rule] = trans
  178. idx := strings.Index(text, paramZero)
  179. if idx == -1 {
  180. tarr[rule] = nil
  181. return &ErrOrdinalTranslation{text: fmt.Sprintf("error: parameter '%s' not found, may want to use 'Add' instead of 'AddOrdinal'. locale: '%s' key: '%v' text: '%s'", paramZero, t.Locale(), key, text)}
  182. }
  183. trans.indexes[0] = idx
  184. trans.indexes[1] = idx + len(paramZero)
  185. return nil
  186. }
  187. // AddRange adds a range plural translation for a particular language/locale
  188. // {0} and {1} are the only replacement types accepted and only these are accepted.
  189. // eg. in locale 'nl' one: '{0}-{1} day left' other: '{0}-{1} days left'
  190. func (t *translator) AddRange(key interface{}, text string, rule locales.PluralRule, override bool) error {
  191. var verified bool
  192. // verify plural rule exists for locale
  193. for _, pr := range t.PluralsRange() {
  194. if pr == rule {
  195. verified = true
  196. break
  197. }
  198. }
  199. if !verified {
  200. return &ErrRangeTranslation{text: fmt.Sprintf("error: range plural rule '%s' does not exist for locale '%s' key: '%v' text: '%s'", rule, t.Locale(), key, text)}
  201. }
  202. tarr, ok := t.rangeTanslations[key]
  203. if ok {
  204. // verify not adding a conflicting record
  205. if len(tarr) > 0 && tarr[rule] != nil && !override {
  206. return &ErrConflictingTranslation{locale: t.Locale(), key: key, rule: rule, text: text}
  207. }
  208. } else {
  209. tarr = make([]*transText, 7, 7)
  210. t.rangeTanslations[key] = tarr
  211. }
  212. trans := &transText{
  213. text: text,
  214. indexes: make([]int, 4, 4),
  215. }
  216. tarr[rule] = trans
  217. idx := strings.Index(text, paramZero)
  218. if idx == -1 {
  219. tarr[rule] = nil
  220. return &ErrRangeTranslation{text: fmt.Sprintf("error: parameter '%s' not found, are you sure you're adding a Range Translation? locale: '%s' key: '%v' text: '%s'", paramZero, t.Locale(), key, text)}
  221. }
  222. trans.indexes[0] = idx
  223. trans.indexes[1] = idx + len(paramZero)
  224. idx = strings.Index(text, paramOne)
  225. if idx == -1 {
  226. tarr[rule] = nil
  227. return &ErrRangeTranslation{text: fmt.Sprintf("error: parameter '%s' not found, a Range Translation requires two parameters. locale: '%s' key: '%v' text: '%s'", paramOne, t.Locale(), key, text)}
  228. }
  229. trans.indexes[2] = idx
  230. trans.indexes[3] = idx + len(paramOne)
  231. return nil
  232. }
  233. // T creates the translation for the locale given the 'key' and params passed in
  234. func (t *translator) T(key interface{}, params ...string) (string, error) {
  235. trans, ok := t.translations[key]
  236. if !ok {
  237. return unknownTranslation, ErrUnknowTranslation
  238. }
  239. b := make([]byte, 0, 64)
  240. var start, end, count int
  241. for i := 0; i < len(trans.indexes); i++ {
  242. end = trans.indexes[i]
  243. b = append(b, trans.text[start:end]...)
  244. b = append(b, params[count]...)
  245. i++
  246. start = trans.indexes[i]
  247. count++
  248. }
  249. b = append(b, trans.text[start:]...)
  250. return string(b), nil
  251. }
  252. // C creates the cardinal translation for the locale given the 'key', 'num' and 'digit' arguments and param passed in
  253. func (t *translator) C(key interface{}, num float64, digits uint64, param string) (string, error) {
  254. tarr, ok := t.cardinalTanslations[key]
  255. if !ok {
  256. return unknownTranslation, ErrUnknowTranslation
  257. }
  258. rule := t.CardinalPluralRule(num, digits)
  259. trans := tarr[rule]
  260. b := make([]byte, 0, 64)
  261. b = append(b, trans.text[:trans.indexes[0]]...)
  262. b = append(b, param...)
  263. b = append(b, trans.text[trans.indexes[1]:]...)
  264. return string(b), nil
  265. }
  266. // O creates the ordinal translation for the locale given the 'key', 'num' and 'digit' arguments and param passed in
  267. func (t *translator) O(key interface{}, num float64, digits uint64, param string) (string, error) {
  268. tarr, ok := t.ordinalTanslations[key]
  269. if !ok {
  270. return unknownTranslation, ErrUnknowTranslation
  271. }
  272. rule := t.OrdinalPluralRule(num, digits)
  273. trans := tarr[rule]
  274. b := make([]byte, 0, 64)
  275. b = append(b, trans.text[:trans.indexes[0]]...)
  276. b = append(b, param...)
  277. b = append(b, trans.text[trans.indexes[1]:]...)
  278. return string(b), nil
  279. }
  280. // R creates the range translation for the locale given the 'key', 'num1', 'digit1', 'num2' and 'digit2' arguments
  281. // and 'param1' and 'param2' passed in
  282. func (t *translator) R(key interface{}, num1 float64, digits1 uint64, num2 float64, digits2 uint64, param1, param2 string) (string, error) {
  283. tarr, ok := t.rangeTanslations[key]
  284. if !ok {
  285. return unknownTranslation, ErrUnknowTranslation
  286. }
  287. rule := t.RangePluralRule(num1, digits1, num2, digits2)
  288. trans := tarr[rule]
  289. b := make([]byte, 0, 64)
  290. b = append(b, trans.text[:trans.indexes[0]]...)
  291. b = append(b, param1...)
  292. b = append(b, trans.text[trans.indexes[1]:trans.indexes[2]]...)
  293. b = append(b, param2...)
  294. b = append(b, trans.text[trans.indexes[3]:]...)
  295. return string(b), nil
  296. }
  297. // VerifyTranslations checks to ensures that no plural rules have been
  298. // missed within the translations.
  299. func (t *translator) VerifyTranslations() error {
  300. for k, v := range t.cardinalTanslations {
  301. for _, rule := range t.PluralsCardinal() {
  302. if v[rule] == nil {
  303. return &ErrMissingPluralTranslation{locale: t.Locale(), translationType: "plural", rule: rule, key: k}
  304. }
  305. }
  306. }
  307. for k, v := range t.ordinalTanslations {
  308. for _, rule := range t.PluralsOrdinal() {
  309. if v[rule] == nil {
  310. return &ErrMissingPluralTranslation{locale: t.Locale(), translationType: "ordinal", rule: rule, key: k}
  311. }
  312. }
  313. }
  314. for k, v := range t.rangeTanslations {
  315. for _, rule := range t.PluralsRange() {
  316. if v[rule] == nil {
  317. return &ErrMissingPluralTranslation{locale: t.Locale(), translationType: "range", rule: rule, key: k}
  318. }
  319. }
  320. }
  321. return nil
  322. }