manage_translations.py 7.0 KB

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