You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

87 lines
2.2KB

  1. /*
  2. * Copyright (c) 2018 DeineAgentur UG https://www.deineagentur.com. All rights reserved.
  3. * Licensed under the MIT License. See LICENSE file in the project root for full license information.
  4. */
  5. package gotext
  6. import (
  7. "fmt"
  8. "regexp"
  9. "strings"
  10. )
  11. var re = regexp.MustCompile(`%\(([a-zA-Z0-9_]+)\)[.0-9]*[svTtbcdoqXxUeEfFgGp]`)
  12. // SimplifiedLocale simplified locale like " en_US"/"de_DE "/en_US.UTF-8/zh_CN/zh_TW/el_GR@euro/... to en_US, de_DE, zh_CN, el_GR...
  13. func SimplifiedLocale(lang string) string {
  14. // en_US/en_US.UTF-8/zh_CN/zh_TW/el_GR@euro/...
  15. if idx := strings.Index(lang, ":"); idx != -1 {
  16. lang = lang[:idx]
  17. }
  18. if idx := strings.Index(lang, "@"); idx != -1 {
  19. lang = lang[:idx]
  20. }
  21. if idx := strings.Index(lang, "."); idx != -1 {
  22. lang = lang[:idx]
  23. }
  24. return strings.TrimSpace(lang)
  25. }
  26. // Printf applies text formatting only when needed to parse variables.
  27. func Printf(str string, vars ...interface{}) string {
  28. if len(vars) > 0 {
  29. return fmt.Sprintf(str, vars...)
  30. }
  31. return str
  32. }
  33. // NPrintf support named format
  34. // NPrintf("%(name)s is Type %(type)s", map[string]interface{}{"name": "Gotext", "type": "struct"})
  35. func NPrintf(format string, params map[string]interface{}) {
  36. f, p := parseSprintf(format, params)
  37. fmt.Printf(f, p...)
  38. }
  39. // Sprintf support named format
  40. // Sprintf("%(name)s is Type %(type)s", map[string]interface{}{"name": "Gotext", "type": "struct"})
  41. func Sprintf(format string, params map[string]interface{}) string {
  42. f, p := parseSprintf(format, params)
  43. return fmt.Sprintf(f, p...)
  44. }
  45. func parseSprintf(format string, params map[string]interface{}) (string, []interface{}) {
  46. f, n := reformatSprintf(format)
  47. var p []interface{}
  48. for _, v := range n {
  49. p = append(p, params[v])
  50. }
  51. return f, p
  52. }
  53. func reformatSprintf(f string) (string, []string) {
  54. m := re.FindAllStringSubmatch(f, -1)
  55. i := re.FindAllStringSubmatchIndex(f, -1)
  56. ord := []string{}
  57. for _, v := range m {
  58. ord = append(ord, v[1])
  59. }
  60. pair := []int{0}
  61. for _, v := range i {
  62. pair = append(pair, v[2]-1)
  63. pair = append(pair, v[3]+1)
  64. }
  65. pair = append(pair, len(f))
  66. plen := len(pair)
  67. out := ""
  68. for n := 0; n < plen; n += 2 {
  69. out += f[pair[n]:pair[n+1]]
  70. }
  71. return out, ord
  72. }