translations_map_to_csv.go 1.5 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273
  1. package csv
  2. import (
  3. "encoding/csv"
  4. "fmt"
  5. "log"
  6. "os"
  7. "sort"
  8. "time"
  9. )
  10. func TranslationsMapToCsv(translationsMap map[string]map[string]string) (err error) {
  11. var (
  12. locales []string
  13. translationKeys []string
  14. translationsKeysMap = map[string]bool{}
  15. now = time.Now().Format("20060102150405")
  16. filename = fmt.Sprintf("translations.%v.csv", now)
  17. )
  18. // Sort locales
  19. for locale := range translationsMap {
  20. locales = append(locales, locale)
  21. }
  22. sort.Strings(locales)
  23. csvFile, err := os.Create(filename)
  24. defer csvFile.Close()
  25. if err != nil {
  26. log.Fatalf("failed creating file: %s", err)
  27. }
  28. writer := csv.NewWriter(csvFile)
  29. // Append Headers
  30. if err = writer.Write(append([]string{"Translation Keys"}, locales...)); err != nil {
  31. log.Fatalln(err)
  32. }
  33. // Sort translation keys
  34. for _, locale := range locales {
  35. for key := range translationsMap[locale] {
  36. translationsKeysMap[key] = true
  37. }
  38. }
  39. for key := range translationsKeysMap {
  40. translationKeys = append(translationKeys, key)
  41. }
  42. sort.Strings(translationKeys)
  43. // Write CSV file
  44. var (
  45. index = 0
  46. )
  47. for _, translationKey := range translationKeys {
  48. // Filter out translation by scope
  49. index++
  50. var translations = []string{translationKey}
  51. for _, locale := range locales {
  52. translations = append(translations, translationsMap[locale][translationKey])
  53. }
  54. writer.Write(translations)
  55. }
  56. writer.Flush()
  57. fmt.Printf(`
  58. ----------------------------------------------
  59. generate translation csv:
  60. %s
  61. `, filename)
  62. return
  63. }