1
0

compile-translation-catalogs 2.1 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879
  1. #!/usr/bin/env python
  2. # -*- coding: utf-8 -*-
  3. '''
  4. :codeauthor: Pedro Algarvio (pedro@algarvio.me)
  5. compile-translation-catalogs
  6. ~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  7. Compile the existing translation catalogs.
  8. '''
  9. # Import python libs
  10. import os
  11. import sys
  12. import fnmatch
  13. # Import 3rd-party libs
  14. HAS_BABEL = False
  15. try:
  16. from babel.messages import mofile, pofile
  17. HAS_BABEL = True
  18. except ImportError:
  19. try:
  20. import polib
  21. except ImportError:
  22. print(
  23. 'You need to install either babel or pofile in order to compile '
  24. 'the message catalogs. One of:\n'
  25. ' pip install babel\n'
  26. ' pip install polib'
  27. )
  28. sys.exit(1)
  29. DOC_DIR = os.path.abspath(os.path.dirname(os.path.dirname(__file__)))
  30. LOCALES_DIR = os.path.join(DOC_DIR, 'locale')
  31. def main():
  32. '''
  33. Run the compile code
  34. '''
  35. print('Gathering the translation catalogs to compile...'),
  36. sys.stdout.flush()
  37. entries = {}
  38. for locale in os.listdir(os.path.join(LOCALES_DIR)):
  39. if locale == 'pot':
  40. continue
  41. locale_path = os.path.join(LOCALES_DIR, locale)
  42. entries[locale] = []
  43. for dirpath, _, filenames in os.walk(locale_path):
  44. for filename in fnmatch.filter(filenames, '*.po'):
  45. entries[locale].append(os.path.join(dirpath, filename))
  46. print('DONE')
  47. for locale, po_files in sorted(entries.items()):
  48. lc_messages_path = os.path.join(LOCALES_DIR, locale, 'LC_MESSAGES')
  49. print('\nCompiling the \'{0}\' locale:'.format(locale))
  50. for po_file in sorted(po_files):
  51. relpath = os.path.relpath(po_file, lc_messages_path)
  52. print ' {0}.po -> {0}.mo'.format(relpath.split('.po', 1)[0])
  53. if HAS_BABEL:
  54. catalog = pofile.read_po(open(po_file))
  55. mofile.write_mo(
  56. open(po_file.replace('.po', '.mo'), 'wb'), catalog
  57. )
  58. continue
  59. catalog = polib.pofile(po_file)
  60. catalog.save_as_mofile(fpath=po_file.replace('.po', '.mo'))
  61. print('Done')
  62. if __name__ == '__main__':
  63. main()