manage_translations.py 6.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180
  1. #!/usr/bin/env python
  2. #
  3. # This python file contains utility scripts to manage Django translations.
  4. # It has to be run inside the django git root directory.
  5. #
  6. # The following commands are available:
  7. #
  8. # * update_catalogs: check for new strings in core and contrib catalogs, and
  9. # output how much strings are new/changed.
  10. #
  11. # * lang_stats: output statistics for each catalog/language combination
  12. #
  13. # * fetch: fetch translations from transifex.com
  14. #
  15. # Each command support the --languages and --resources options to limit their
  16. # operation to the specified language or resource. For example, to get stats
  17. # for Spanish in contrib.admin, run:
  18. #
  19. # $ python scripts/manage_translations.py lang_stats --language=es --resources=admin
  20. import os
  21. from argparse import ArgumentParser
  22. from subprocess import PIPE, Popen, call
  23. import django
  24. from django.conf import settings
  25. from django.core.management import call_command
  26. HAVE_JS = ['admin']
  27. def _get_locale_dirs(resources, include_core=True):
  28. """
  29. Return a tuple (contrib name, absolute path) for all locale directories,
  30. optionally including the django core catalog.
  31. If resources list is not None, filter directories matching resources content.
  32. """
  33. contrib_dir = os.path.join(os.getcwd(), 'django', 'contrib')
  34. dirs = []
  35. # Collect all locale directories
  36. for contrib_name in os.listdir(contrib_dir):
  37. path = os.path.join(contrib_dir, contrib_name, 'locale')
  38. if os.path.isdir(path):
  39. dirs.append((contrib_name, path))
  40. if contrib_name in HAVE_JS:
  41. dirs.append(("%s-js" % contrib_name, path))
  42. if include_core:
  43. dirs.insert(0, ('core', os.path.join(os.getcwd(), 'django', 'conf', 'locale')))
  44. # Filter by resources, if any
  45. if resources is not None:
  46. res_names = [d[0] for d in dirs]
  47. dirs = [ld for ld in dirs if ld[0] in resources]
  48. if len(resources) > len(dirs):
  49. print("You have specified some unknown resources. "
  50. "Available resource names are: %s" % (', '.join(res_names),))
  51. exit(1)
  52. return dirs
  53. def _tx_resource_for_name(name):
  54. """ Return the Transifex resource name """
  55. if name == 'core':
  56. return "django.core"
  57. else:
  58. return "django.contrib-%s" % name
  59. def _check_diff(cat_name, base_path):
  60. """
  61. Output the approximate number of changed/added strings in the en catalog.
  62. """
  63. po_path = '%(path)s/en/LC_MESSAGES/django%(ext)s.po' % {
  64. 'path': base_path, 'ext': 'js' if cat_name.endswith('-js') else ''}
  65. p = Popen("git diff -U0 %s | egrep '^[-+]msgid' | wc -l" % po_path,
  66. stdout=PIPE, stderr=PIPE, shell=True)
  67. output, errors = p.communicate()
  68. num_changes = int(output.strip())
  69. print("%d changed/added messages in '%s' catalog." % (num_changes, cat_name))
  70. def update_catalogs(resources=None, languages=None):
  71. """
  72. Update the en/LC_MESSAGES/django.po (main and contrib) files with
  73. new/updated translatable strings.
  74. """
  75. settings.configure()
  76. django.setup()
  77. if resources is not None:
  78. print("`update_catalogs` will always process all resources.")
  79. contrib_dirs = _get_locale_dirs(None, include_core=False)
  80. os.chdir(os.path.join(os.getcwd(), 'django'))
  81. print("Updating en catalogs for Django and contrib apps...")
  82. call_command('makemessages', locale=['en'])
  83. print("Updating en JS catalogs for Django and contrib apps...")
  84. call_command('makemessages', locale=['en'], domain='djangojs')
  85. # Output changed stats
  86. _check_diff('core', os.path.join(os.getcwd(), 'conf', 'locale'))
  87. for name, dir_ in contrib_dirs:
  88. _check_diff(name, dir_)
  89. def lang_stats(resources=None, languages=None):
  90. """
  91. Output language statistics of committed translation files for each
  92. Django catalog.
  93. If resources is provided, it should be a list of translation resource to
  94. limit the output (e.g. ['core', 'gis']).
  95. """
  96. locale_dirs = _get_locale_dirs(resources)
  97. for name, dir_ in locale_dirs:
  98. print("\nShowing translations stats for '%s':" % name)
  99. langs = sorted([d for d in os.listdir(dir_) if not d.startswith('_')])
  100. for lang in langs:
  101. if languages and lang not in languages:
  102. continue
  103. # TODO: merge first with the latest en catalog
  104. p = Popen("msgfmt -vc -o /dev/null %(path)s/%(lang)s/LC_MESSAGES/django%(ext)s.po" % {
  105. 'path': dir_, 'lang': lang, 'ext': 'js' if name.endswith('-js') else ''},
  106. stdout=PIPE, stderr=PIPE, shell=True)
  107. output, errors = p.communicate()
  108. if p.returncode == 0:
  109. # msgfmt output stats on stderr
  110. print("%s: %s" % (lang, errors.strip()))
  111. else:
  112. print("Errors happened when checking %s translation for %s:\n%s" % (
  113. lang, name, errors))
  114. def fetch(resources=None, languages=None):
  115. """
  116. Fetch translations from Transifex, wrap long lines, generate mo files.
  117. """
  118. locale_dirs = _get_locale_dirs(resources)
  119. errors = []
  120. for name, dir_ in locale_dirs:
  121. # Transifex pull
  122. if languages is None:
  123. call('tx pull -r %(res)s -a -f --minimum-perc=5' % {'res': _tx_resource_for_name(name)}, shell=True)
  124. target_langs = sorted([d for d in os.listdir(dir_) if not d.startswith('_') and d != 'en'])
  125. else:
  126. for lang in languages:
  127. call('tx pull -r %(res)s -f -l %(lang)s' % {
  128. 'res': _tx_resource_for_name(name), 'lang': lang}, shell=True)
  129. target_langs = languages
  130. # msgcat to wrap lines and msgfmt for compilation of .mo file
  131. for lang in target_langs:
  132. po_path = '%(path)s/%(lang)s/LC_MESSAGES/django%(ext)s.po' % {
  133. 'path': dir_, 'lang': lang, 'ext': 'js' if name.endswith('-js') else ''}
  134. if not os.path.exists(po_path):
  135. print("No %(lang)s translation for resource %(name)s" % {
  136. 'lang': lang, 'name': name})
  137. continue
  138. call('msgcat --no-location -o %s %s' % (po_path, po_path), shell=True)
  139. res = call('msgfmt -c -o %s.mo %s' % (po_path[:-3], po_path), shell=True)
  140. if res != 0:
  141. errors.append((name, lang))
  142. if errors:
  143. print("\nWARNING: Errors have occurred in following cases:")
  144. for resource, lang in errors:
  145. print("\tResource %s for language %s" % (resource, lang))
  146. exit(1)
  147. if __name__ == "__main__":
  148. RUNABLE_SCRIPTS = ('update_catalogs', 'lang_stats', 'fetch')
  149. parser = ArgumentParser()
  150. parser.add_argument('cmd', nargs=1, choices=RUNABLE_SCRIPTS)
  151. parser.add_argument("-r", "--resources", action='append', help="limit operation to the specified resources")
  152. parser.add_argument("-l", "--languages", action='append', help="limit operation to the specified languages")
  153. options = parser.parse_args()
  154. eval(options.cmd[0])(options.resources, options.languages)