main.go 7.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281
  1. package main
  2. import (
  3. "encoding/json"
  4. "errors"
  5. "fmt"
  6. "os"
  7. "path/filepath"
  8. "sort"
  9. "strings"
  10. "gopkg.in/yaml.v3"
  11. "github.com/jamesread/golure/pkg/dirs"
  12. log "github.com/sirupsen/logrus"
  13. )
  14. type LanguageFilev1 struct {
  15. SchemaVersion yaml.Node `json:"schemaVersion" yaml:"schemaVersion"`
  16. Translations map[string]string `json:"translations" yaml:"translations"`
  17. }
  18. type CombinedTranslationsOutput struct {
  19. Comment string `json:"_comment"`
  20. Messages map[string]map[string]string `json:"messages"`
  21. }
  22. func main() {
  23. combinedContent, err := getCombinedLanguageContent()
  24. if err != nil {
  25. log.Fatalf("Error loading language files: %v", err)
  26. }
  27. sortedContent := sortTranslations(combinedContent)
  28. err = writeTranslationFiles(sortedContent.Messages)
  29. if err != nil {
  30. log.Fatalf("Error writing language content: %v", err)
  31. }
  32. }
  33. func writeTranslationFiles(messages map[string]map[string]string) error {
  34. err := os.RemoveAll("generated")
  35. if err != nil {
  36. return err
  37. }
  38. err = os.Mkdir("generated", 0o755)
  39. if err != nil {
  40. return err
  41. }
  42. for languageName, translations := range messages {
  43. err = writeTranslationFile(languageName, translations)
  44. if err != nil {
  45. return err
  46. }
  47. }
  48. log.Infof("Language content saved to generated/")
  49. return nil
  50. }
  51. func writeTranslationFile(languageName string, translations map[string]string) error {
  52. jsonData, err := json.MarshalIndent(translations, "", " ")
  53. if err != nil {
  54. return err
  55. }
  56. jsonData = append(jsonData, '\n')
  57. filename := filepath.Join("generated", languageName+".json")
  58. return os.WriteFile(filename, jsonData, 0o644)
  59. }
  60. // sortTranslations creates a new structure with sorted keys for deterministic output.
  61. func sortTranslations(input *CombinedTranslationsOutput) *CombinedTranslationsOutput {
  62. sorted := &CombinedTranslationsOutput{
  63. Comment: input.Comment,
  64. Messages: make(map[string]map[string]string),
  65. }
  66. // Sort language names
  67. langNames := make([]string, 0, len(input.Messages))
  68. for langName := range input.Messages {
  69. langNames = append(langNames, langName)
  70. }
  71. sort.Strings(langNames)
  72. // For each language, sort the translation keys
  73. for _, langName := range langNames {
  74. translations := input.Messages[langName]
  75. sortedTranslations := make(map[string]string)
  76. keys := make([]string, 0, len(translations))
  77. for key := range translations {
  78. keys = append(keys, key)
  79. }
  80. sort.Strings(keys)
  81. for _, key := range keys {
  82. sortedTranslations[key] = translations[key]
  83. }
  84. sorted.Messages[langName] = sortedTranslations
  85. }
  86. return sorted
  87. }
  88. func getLanguageDir() string {
  89. dirsToSearch := []string{
  90. "../lang",
  91. "../../../../lang/", // Relative to this file, for unit tests
  92. "/app/lang/",
  93. }
  94. dir, _ := dirs.GetFirstExistingDirectory("lang", dirsToSearch)
  95. return dir
  96. }
  97. func getCombinedLanguageContent() (*CombinedTranslationsOutput, error) {
  98. output := &CombinedTranslationsOutput{
  99. Comment: "This file is generated. Please re-generate this file using 'make' when you update a translation.",
  100. Messages: make(map[string]map[string]string),
  101. }
  102. languageDir := getLanguageDir()
  103. files, err := os.ReadDir(languageDir)
  104. if err != nil {
  105. return nil, fmt.Errorf("reading language directory %s: %w", languageDir, err)
  106. }
  107. for _, file := range filterLanguageFiles(files) {
  108. languageName := strings.TrimSuffix(file.Name(), ".yaml")
  109. translations, err := loadLanguageFile(filepath.Join(languageDir, file.Name()))
  110. if err != nil {
  111. return nil, err
  112. }
  113. output.Messages[languageName] = translations
  114. }
  115. return output, validateTranslations(output)
  116. }
  117. func loadLanguageFile(fullPath string) (map[string]string, error) {
  118. log.Infof("Loading language file: %s", fullPath)
  119. content, err := os.ReadFile(fullPath)
  120. if err != nil {
  121. return nil, fmt.Errorf("reading language file %s: %w", fullPath, err)
  122. }
  123. var yamlData LanguageFilev1
  124. err = yaml.Unmarshal(content, &yamlData)
  125. if err != nil {
  126. return nil, fmt.Errorf("parsing language file %s: %w", fullPath, err)
  127. }
  128. err = validateSchemaVersion(&yamlData.SchemaVersion)
  129. if err != nil {
  130. return nil, fmt.Errorf("language file %s: %w", fullPath, err)
  131. }
  132. if len(yamlData.Translations) == 0 {
  133. return nil, fmt.Errorf("language file %s has no translations", fullPath)
  134. }
  135. return yamlData.Translations, nil
  136. }
  137. // validateSchemaVersion checks the raw YAML scalar, because decoding straight
  138. // into an int silently truncates values such as 1.5 to 1.
  139. func validateSchemaVersion(node *yaml.Node) error {
  140. if node.Kind != yaml.ScalarNode || node.ShortTag() != "!!int" || node.Value != "1" {
  141. return fmt.Errorf("schemaVersion is %q, expected 1", node.Value)
  142. }
  143. return nil
  144. }
  145. // getReferenceKeys returns the keys from the "en" translation as the reference set.
  146. func getReferenceKeys(messages map[string]map[string]string) map[string]bool {
  147. enTranslations, exists := messages["en"]
  148. if !exists {
  149. return nil
  150. }
  151. referenceKeys := make(map[string]bool, len(enTranslations))
  152. for key := range enTranslations {
  153. referenceKeys[key] = true
  154. }
  155. return referenceKeys
  156. }
  157. // findMissingKeys returns the keys that are in referenceKeys but not in translations.
  158. func findMissingKeys(referenceKeys map[string]bool, translations map[string]string) []string {
  159. missing := make([]string, 0)
  160. for key := range referenceKeys {
  161. if _, exists := translations[key]; !exists {
  162. missing = append(missing, key)
  163. }
  164. }
  165. return missing
  166. }
  167. // findExtraKeys returns the keys that are in translations but not in referenceKeys.
  168. func findExtraKeys(referenceKeys map[string]bool, translations map[string]string) []string {
  169. extra := make([]string, 0)
  170. for key := range translations {
  171. if !referenceKeys[key] {
  172. extra = append(extra, key)
  173. }
  174. }
  175. return extra
  176. }
  177. // validateTranslations checks all translations against the "en" reference.
  178. // Missing keys are only warnings, so that new English strings can be merged
  179. // before every language has been translated. Extra keys are errors, as they
  180. // are usually typos and are never displayed.
  181. func validateTranslations(output *CombinedTranslationsOutput) error {
  182. referenceKeys := getReferenceKeys(output.Messages)
  183. if referenceKeys == nil {
  184. return errors.New("no 'en' translation found to validate against")
  185. }
  186. invalidLanguages := make([]string, 0)
  187. for langName, translations := range output.Messages {
  188. if !checkLanguageKeys(langName, referenceKeys, translations) {
  189. invalidLanguages = append(invalidLanguages, langName)
  190. }
  191. }
  192. if len(invalidLanguages) > 0 {
  193. sort.Strings(invalidLanguages)
  194. return fmt.Errorf("translations with keys that are not in 'en': %v", invalidLanguages)
  195. }
  196. return nil
  197. }
  198. func checkLanguageKeys(langName string, referenceKeys map[string]bool, translations map[string]string) bool {
  199. missing := findMissingKeys(referenceKeys, translations)
  200. if len(missing) > 0 {
  201. log.Warnf("Translation '%s' is missing %d key(s): %v", langName, len(missing), missing)
  202. }
  203. extra := findExtraKeys(referenceKeys, translations)
  204. if len(extra) > 0 {
  205. log.Errorf("Translation '%s' has %d extra key(s) not in 'en': %v", langName, len(extra), extra)
  206. return false
  207. }
  208. return true
  209. }
  210. func filterLanguageFiles(files []os.DirEntry) []os.DirEntry {
  211. ret := make([]os.DirEntry, 0)
  212. for _, file := range files {
  213. if file.IsDir() {
  214. continue
  215. }
  216. if !strings.HasSuffix(file.Name(), ".yaml") {
  217. continue
  218. }
  219. ret = append(ret, file)
  220. }
  221. return ret
  222. }