export_to_translation_map.go 2.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104
  1. package parser
  2. import (
  3. "go/ast"
  4. go_parser "go/parser"
  5. "go/token"
  6. go_path "path"
  7. "strings"
  8. )
  9. // get translationsMap from projectPath
  10. func ExportToTranslationsMap(projectPath string) (translationsMap map[string]map[string]string, err error) {
  11. fset := token.NewFileSet()
  12. pkgs, err := ParseDir(fset, projectPath, nil, go_parser.AllErrors)
  13. if err != nil {
  14. return
  15. }
  16. v, err := newVisitorAndWalk(fset, pkgs, projectPath)
  17. if err != nil {
  18. return
  19. }
  20. return getTranslationsMapFromVistor(v), nil
  21. }
  22. // traverse all global variables and check if it is in v.RigisterMap
  23. // if true, transfer it into translationsMap
  24. func getTranslationsMapFromVistor(v *Visitor) map[string]map[string]string {
  25. translationsMap := make(map[string]map[string]string)
  26. for pkgName, structs := range v.Variables {
  27. for _, astruct := range structs {
  28. for _, spec := range astruct.Specs {
  29. if spec, ok := spec.(*ast.ValueSpec); ok {
  30. var locale string
  31. var translationMap = make(map[string]string)
  32. var isMessage bool
  33. for _, name := range spec.Names {
  34. if l, exist := v.LocalesMap[name.Name]; exist {
  35. locale = l
  36. for _, messageStructs := range v.RigisterMap[locale] {
  37. if messageStructs.PkgName == pkgName && messageStructs.StructName == name.Name {
  38. isMessage = true
  39. break
  40. }
  41. }
  42. break
  43. }
  44. }
  45. if !isMessage {
  46. continue
  47. }
  48. for _, values := range spec.Values {
  49. unaryExpr, ok := values.(*ast.UnaryExpr)
  50. if !ok {
  51. isMessage = false
  52. break
  53. }
  54. x, ok := unaryExpr.X.(*ast.CompositeLit)
  55. if !ok {
  56. isMessage = false
  57. break
  58. }
  59. for _, elt := range x.Elts {
  60. keyValueExpr, ok := elt.(*ast.KeyValueExpr)
  61. if !ok {
  62. isMessage = false
  63. break
  64. }
  65. key, ok := keyValueExpr.Key.(*ast.Ident)
  66. if !ok {
  67. isMessage = false
  68. break
  69. }
  70. value, ok := keyValueExpr.Value.(*ast.BasicLit)
  71. if !ok {
  72. isMessage = false
  73. break
  74. }
  75. if isMessage {
  76. translationMap[go_path.Join(pkgName, key.Name)] = strings.Trim(value.Value, "\"")
  77. }
  78. }
  79. }
  80. if isMessage {
  81. if translationsMap[locale] == nil {
  82. translationsMap[locale] = make(map[string]string)
  83. }
  84. for k, v := range translationMap {
  85. translationsMap[locale][k] = v
  86. }
  87. }
  88. }
  89. }
  90. }
  91. }
  92. return translationsMap
  93. }