PageRenderTime 47ms CodeModel.GetById 23ms RepoModel.GetById 0ms app.codeStats 0ms

/lib/google_appengine/lib/django_1_2/django/core/management/commands/makemessages.py

https://github.com/andrewxhill/MOL
Python | 321 lines | 259 code | 30 blank | 32 comment | 89 complexity | 10e261985091ecdbd11c728e25381d25 MD5 | raw file
  1. import fnmatch
  2. import glob
  3. import os
  4. import re
  5. import sys
  6. from itertools import dropwhile
  7. from optparse import make_option
  8. from subprocess import PIPE, Popen
  9. from django.core.management.base import CommandError, BaseCommand
  10. from django.utils.text import get_text_list
  11. pythonize_re = re.compile(r'(?:^|\n)\s*//')
  12. plural_forms_re = re.compile(r'^(?P<value>"Plural-Forms.+?\\n")\s*$', re.MULTILINE | re.DOTALL)
  13. def handle_extensions(extensions=('html',)):
  14. """
  15. organizes multiple extensions that are separated with commas or passed by
  16. using --extension/-e multiple times.
  17. for example: running 'django-admin makemessages -e js,txt -e xhtml -a'
  18. would result in a extension list: ['.js', '.txt', '.xhtml']
  19. >>> handle_extensions(['.html', 'html,js,py,py,py,.py', 'py,.py'])
  20. ['.html', '.js']
  21. >>> handle_extensions(['.html, txt,.tpl'])
  22. ['.html', '.tpl', '.txt']
  23. """
  24. ext_list = []
  25. for ext in extensions:
  26. ext_list.extend(ext.replace(' ','').split(','))
  27. for i, ext in enumerate(ext_list):
  28. if not ext.startswith('.'):
  29. ext_list[i] = '.%s' % ext_list[i]
  30. # we don't want *.py files here because of the way non-*.py files
  31. # are handled in make_messages() (they are copied to file.ext.py files to
  32. # trick xgettext to parse them as Python files)
  33. return set([x for x in ext_list if x != '.py'])
  34. def _popen(cmd):
  35. """
  36. Friendly wrapper around Popen for Windows
  37. """
  38. p = Popen(cmd, shell=True, stdout=PIPE, stderr=PIPE, close_fds=os.name != 'nt', universal_newlines=True)
  39. return p.communicate()
  40. def walk(root, topdown=True, onerror=None, followlinks=False):
  41. """
  42. A version of os.walk that can follow symlinks for Python < 2.6
  43. """
  44. for dirpath, dirnames, filenames in os.walk(root, topdown, onerror):
  45. yield (dirpath, dirnames, filenames)
  46. if followlinks:
  47. for d in dirnames:
  48. p = os.path.join(dirpath, d)
  49. if os.path.islink(p):
  50. for link_dirpath, link_dirnames, link_filenames in walk(p):
  51. yield (link_dirpath, link_dirnames, link_filenames)
  52. def is_ignored(path, ignore_patterns):
  53. """
  54. Helper function to check if the given path should be ignored or not.
  55. """
  56. for pattern in ignore_patterns:
  57. if fnmatch.fnmatchcase(path, pattern):
  58. return True
  59. return False
  60. def find_files(root, ignore_patterns, verbosity, symlinks=False):
  61. """
  62. Helper function to get all files in the given root.
  63. """
  64. all_files = []
  65. for (dirpath, dirnames, filenames) in walk(".", followlinks=symlinks):
  66. for f in filenames:
  67. norm_filepath = os.path.normpath(os.path.join(dirpath, f))
  68. if is_ignored(norm_filepath, ignore_patterns):
  69. if verbosity > 1:
  70. sys.stdout.write('ignoring file %s in %s\n' % (f, dirpath))
  71. else:
  72. all_files.extend([(dirpath, f)])
  73. all_files.sort()
  74. return all_files
  75. def copy_plural_forms(msgs, locale, domain, verbosity):
  76. """
  77. Copies plural forms header contents from a Django catalog of locale to
  78. the msgs string, inserting it at the right place. msgs should be the
  79. contents of a newly created .po file.
  80. """
  81. import django
  82. django_dir = os.path.normpath(os.path.join(os.path.dirname(django.__file__)))
  83. if domain == 'djangojs':
  84. domains = ('djangojs', 'django')
  85. else:
  86. domains = ('django',)
  87. for domain in domains:
  88. django_po = os.path.join(django_dir, 'conf', 'locale', locale, 'LC_MESSAGES', '%s.po' % domain)
  89. if os.path.exists(django_po):
  90. m = plural_forms_re.search(open(django_po, 'rU').read())
  91. if m:
  92. if verbosity > 1:
  93. sys.stderr.write("copying plural forms: %s\n" % m.group('value'))
  94. lines = []
  95. seen = False
  96. for line in msgs.split('\n'):
  97. if not line and not seen:
  98. line = '%s\n' % m.group('value')
  99. seen = True
  100. lines.append(line)
  101. msgs = '\n'.join(lines)
  102. break
  103. return msgs
  104. def make_messages(locale=None, domain='django', verbosity='1', all=False,
  105. extensions=None, symlinks=False, ignore_patterns=[]):
  106. """
  107. Uses the locale directory from the Django SVN tree or an application/
  108. project to process all
  109. """
  110. # Need to ensure that the i18n framework is enabled
  111. from django.conf import settings
  112. if settings.configured:
  113. settings.USE_I18N = True
  114. else:
  115. settings.configure(USE_I18N = True)
  116. from django.utils.translation import templatize
  117. invoked_for_django = False
  118. if os.path.isdir(os.path.join('conf', 'locale')):
  119. localedir = os.path.abspath(os.path.join('conf', 'locale'))
  120. invoked_for_django = True
  121. elif os.path.isdir('locale'):
  122. localedir = os.path.abspath('locale')
  123. else:
  124. raise CommandError("This script should be run from the Django SVN tree or your project or app tree. If you did indeed run it from the SVN checkout or your project or application, maybe you are just missing the conf/locale (in the django tree) or locale (for project and application) directory? It is not created automatically, you have to create it by hand if you want to enable i18n for your project or application.")
  125. if domain not in ('django', 'djangojs'):
  126. raise CommandError("currently makemessages only supports domains 'django' and 'djangojs'")
  127. if (locale is None and not all) or domain is None:
  128. # backwards compatible error message
  129. if not sys.argv[0].endswith("make-messages.py"):
  130. message = "Type '%s help %s' for usage.\n" % (os.path.basename(sys.argv[0]), sys.argv[1])
  131. else:
  132. message = "usage: make-messages.py -l <language>\n or: make-messages.py -a\n"
  133. raise CommandError(message)
  134. # We require gettext version 0.15 or newer.
  135. output = _popen('xgettext --version')[0]
  136. match = re.search(r'(?P<major>\d+)\.(?P<minor>\d+)', output)
  137. if match:
  138. xversion = (int(match.group('major')), int(match.group('minor')))
  139. if xversion < (0, 15):
  140. raise CommandError("Django internationalization requires GNU gettext 0.15 or newer. You are using version %s, please upgrade your gettext toolset." % match.group())
  141. languages = []
  142. if locale is not None:
  143. languages.append(locale)
  144. elif all:
  145. locale_dirs = filter(os.path.isdir, glob.glob('%s/*' % localedir))
  146. languages = [os.path.basename(l) for l in locale_dirs]
  147. for locale in languages:
  148. if verbosity > 0:
  149. print "processing language", locale
  150. basedir = os.path.join(localedir, locale, 'LC_MESSAGES')
  151. if not os.path.isdir(basedir):
  152. os.makedirs(basedir)
  153. pofile = os.path.join(basedir, '%s.po' % domain)
  154. potfile = os.path.join(basedir, '%s.pot' % domain)
  155. if os.path.exists(potfile):
  156. os.unlink(potfile)
  157. for dirpath, file in find_files(".", ignore_patterns, verbosity, symlinks=symlinks):
  158. file_base, file_ext = os.path.splitext(file)
  159. if domain == 'djangojs' and file_ext in extensions:
  160. if verbosity > 1:
  161. sys.stdout.write('processing file %s in %s\n' % (file, dirpath))
  162. src = open(os.path.join(dirpath, file), "rU").read()
  163. src = pythonize_re.sub('\n#', src)
  164. thefile = '%s.py' % file
  165. f = open(os.path.join(dirpath, thefile), "w")
  166. try:
  167. f.write(src)
  168. finally:
  169. f.close()
  170. cmd = 'xgettext -d %s -L Perl --keyword=gettext_noop --keyword=gettext_lazy --keyword=ngettext_lazy:1,2 --from-code UTF-8 -o - "%s"' % (domain, os.path.join(dirpath, thefile))
  171. msgs, errors = _popen(cmd)
  172. if errors:
  173. raise CommandError("errors happened while running xgettext on %s\n%s" % (file, errors))
  174. old = '#: '+os.path.join(dirpath, thefile)[2:]
  175. new = '#: '+os.path.join(dirpath, file)[2:]
  176. msgs = msgs.replace(old, new)
  177. if os.path.exists(potfile):
  178. # Strip the header
  179. msgs = '\n'.join(dropwhile(len, msgs.split('\n')))
  180. else:
  181. msgs = msgs.replace('charset=CHARSET', 'charset=UTF-8')
  182. if msgs:
  183. f = open(potfile, 'ab')
  184. try:
  185. f.write(msgs)
  186. finally:
  187. f.close()
  188. os.unlink(os.path.join(dirpath, thefile))
  189. elif domain == 'django' and (file_ext == '.py' or file_ext in extensions):
  190. thefile = file
  191. if file_ext in extensions:
  192. src = open(os.path.join(dirpath, file), "rU").read()
  193. thefile = '%s.py' % file
  194. try:
  195. f = open(os.path.join(dirpath, thefile), "w")
  196. try:
  197. f.write(templatize(src))
  198. finally:
  199. f.close()
  200. except SyntaxError, msg:
  201. msg = "%s (file: %s)" % (msg, os.path.join(dirpath, file))
  202. raise SyntaxError(msg)
  203. if verbosity > 1:
  204. sys.stdout.write('processing file %s in %s\n' % (file, dirpath))
  205. cmd = 'xgettext -d %s -L Python --keyword=gettext_noop --keyword=gettext_lazy --keyword=ngettext_lazy:1,2 --keyword=ugettext_noop --keyword=ugettext_lazy --keyword=ungettext_lazy:1,2 --from-code UTF-8 -o - "%s"' % (
  206. domain, os.path.join(dirpath, thefile))
  207. msgs, errors = _popen(cmd)
  208. if errors:
  209. raise CommandError("errors happened while running xgettext on %s\n%s" % (file, errors))
  210. if thefile != file:
  211. old = '#: '+os.path.join(dirpath, thefile)[2:]
  212. new = '#: '+os.path.join(dirpath, file)[2:]
  213. msgs = msgs.replace(old, new)
  214. if os.path.exists(potfile):
  215. # Strip the header
  216. msgs = '\n'.join(dropwhile(len, msgs.split('\n')))
  217. else:
  218. msgs = msgs.replace('charset=CHARSET', 'charset=UTF-8')
  219. if msgs:
  220. f = open(potfile, 'ab')
  221. try:
  222. f.write(msgs)
  223. finally:
  224. f.close()
  225. if thefile != file:
  226. os.unlink(os.path.join(dirpath, thefile))
  227. if os.path.exists(potfile):
  228. msgs, errors = _popen('msguniq --to-code=utf-8 "%s"' % potfile)
  229. if errors:
  230. raise CommandError("errors happened while running msguniq\n%s" % errors)
  231. f = open(potfile, 'w')
  232. try:
  233. f.write(msgs)
  234. finally:
  235. f.close()
  236. if os.path.exists(pofile):
  237. msgs, errors = _popen('msgmerge -q "%s" "%s"' % (pofile, potfile))
  238. if errors:
  239. raise CommandError("errors happened while running msgmerge\n%s" % errors)
  240. elif not invoked_for_django:
  241. msgs = copy_plural_forms(msgs, locale, domain, verbosity)
  242. f = open(pofile, 'wb')
  243. try:
  244. f.write(msgs)
  245. finally:
  246. f.close()
  247. os.unlink(potfile)
  248. class Command(BaseCommand):
  249. option_list = BaseCommand.option_list + (
  250. make_option('--locale', '-l', default=None, dest='locale',
  251. help='Creates or updates the message files only for the given locale (e.g. pt_BR).'),
  252. make_option('--domain', '-d', default='django', dest='domain',
  253. help='The domain of the message files (default: "django").'),
  254. make_option('--all', '-a', action='store_true', dest='all',
  255. default=False, help='Reexamines all source code and templates for new translation strings and updates all message files for all available languages.'),
  256. make_option('--extension', '-e', dest='extensions',
  257. help='The file extension(s) to examine (default: ".html", separate multiple extensions with commas, or use -e multiple times)',
  258. action='append'),
  259. make_option('--symlinks', '-s', action='store_true', dest='symlinks',
  260. default=False, help='Follows symlinks to directories when examining source code and templates for translation strings.'),
  261. make_option('--ignore', '-i', action='append', dest='ignore_patterns',
  262. default=[], metavar='PATTERN', help='Ignore files or directories matching this glob-style pattern. Use multiple times to ignore more.'),
  263. make_option('--no-default-ignore', action='store_false', dest='use_default_ignore_patterns',
  264. default=True, help="Don't ignore the common glob-style patterns 'CVS', '.*' and '*~'."),
  265. )
  266. help = "Runs over the entire source tree of the current directory and pulls out all strings marked for translation. It creates (or updates) a message file in the conf/locale (in the django tree) or locale (for project and application) directory."
  267. requires_model_validation = False
  268. can_import_settings = False
  269. def handle(self, *args, **options):
  270. if len(args) != 0:
  271. raise CommandError("Command doesn't accept any arguments")
  272. locale = options.get('locale')
  273. domain = options.get('domain')
  274. verbosity = int(options.get('verbosity'))
  275. process_all = options.get('all')
  276. extensions = options.get('extensions')
  277. symlinks = options.get('symlinks')
  278. ignore_patterns = options.get('ignore_patterns')
  279. if options.get('use_default_ignore_patterns'):
  280. ignore_patterns += ['CVS', '.*', '*~']
  281. ignore_patterns = list(set(ignore_patterns))
  282. if domain == 'djangojs':
  283. extensions = handle_extensions(extensions or ['js'])
  284. else:
  285. extensions = handle_extensions(extensions or ['html'])
  286. if verbosity > 1:
  287. sys.stdout.write('examining files with the extensions: %s\n' % get_text_list(list(extensions), 'and'))
  288. make_messages(locale, domain, verbosity, process_all, extensions, symlinks, ignore_patterns)