sync_i18n.py 1.9 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455
  1. #!/usr/bin/env python3
  2. # Sync Language Packs
  3. # Script to synchronize each language pack's items against Wowchemy's master pack (English).
  4. # https://wowchemy.com
  5. #
  6. # Prerequisites: pip3 install PyYAML
  7. #
  8. # TODO: Switch from PyYAML to Ruamel in order to load/dump comments -
  9. # see https://stackoverflow.com/questions/47382227/python-yaml-update-preserving-order-and-comments
  10. import copy
  11. from pathlib import Path
  12. import yaml
  13. I18N_PATH = Path(__file__).resolve().parent.parent.joinpath('wowchemy').joinpath('i18n')
  14. MASTER_PACK = I18N_PATH.joinpath('en.yaml')
  15. # Load master language pack (English).
  16. with open(MASTER_PACK) as f:
  17. master_map = yaml.safe_load(f)
  18. # if (DEBUG)
  19. # print(master_map)
  20. # Iterate over each child language pack.
  21. cnt = 0
  22. for filename in Path(I18N_PATH).glob("*.yaml"):
  23. if filename.stem != 'en':
  24. i18n_file = I18N_PATH.joinpath(filename)
  25. print(f"Processing {i18n_file} ...")
  26. # Load a child language pack.
  27. with open(i18n_file) as f:
  28. child_map = yaml.safe_load(f)
  29. # Synchronize the language pack's structure against the master language pack.
  30. tmp_map = copy.deepcopy(master_map) # Make a temporary deep copy of the master map (list of objects).
  31. master_index = 0
  32. for master_item in master_map:
  33. translation = next((item['translation'] for item in child_map if item['id'] == master_item['id']),
  34. master_item['translation'])
  35. tmp_map[master_index]['translation'] = translation
  36. master_index += 1
  37. # Write the synced language pack to file.
  38. with open(i18n_file, 'w') as f:
  39. # PyYAML will break lines unless a large column `width` is set.
  40. # To standardise with single quotes, add: `, default_style='\''`.
  41. # No option to only enforce single quotes when YAML string wrapped in quotes?
  42. yaml.dump(tmp_map, f, allow_unicode=True, width=float("inf"))
  43. cnt += 1
  44. # Print results.
  45. print(f"{cnt} child language packs successfully synchronized!")