You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

makemessages.py 27KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687
  1. import fnmatch
  2. import glob
  3. import os
  4. import re
  5. import sys
  6. from functools import total_ordering
  7. from itertools import dropwhile
  8. import django
  9. from django.conf import settings
  10. from django.core.exceptions import ImproperlyConfigured
  11. from django.core.files.temp import NamedTemporaryFile
  12. from django.core.management.base import BaseCommand, CommandError
  13. from django.core.management.utils import (
  14. find_command, handle_extensions, popen_wrapper,
  15. )
  16. from django.utils.encoding import DEFAULT_LOCALE_ENCODING
  17. from django.utils.functional import cached_property
  18. from django.utils.jslex import prepare_js_for_gettext
  19. from django.utils.text import get_text_list
  20. from django.utils.translation import templatize
  21. plural_forms_re = re.compile(r'^(?P<value>"Plural-Forms.+?\\n")\s*$', re.MULTILINE | re.DOTALL)
  22. STATUS_OK = 0
  23. NO_LOCALE_DIR = object()
  24. def check_programs(*programs):
  25. for program in programs:
  26. if find_command(program) is None:
  27. raise CommandError(
  28. "Can't find %s. Make sure you have GNU gettext tools 0.15 or "
  29. "newer installed." % program
  30. )
  31. @total_ordering
  32. class TranslatableFile:
  33. def __init__(self, dirpath, file_name, locale_dir):
  34. self.file = file_name
  35. self.dirpath = dirpath
  36. self.locale_dir = locale_dir
  37. def __repr__(self):
  38. return "<%s: %s>" % (
  39. self.__class__.__name__,
  40. os.sep.join([self.dirpath, self.file]),
  41. )
  42. def __eq__(self, other):
  43. return self.path == other.path
  44. def __lt__(self, other):
  45. return self.path < other.path
  46. @property
  47. def path(self):
  48. return os.path.join(self.dirpath, self.file)
  49. class BuildFile:
  50. """
  51. Represent the state of a translatable file during the build process.
  52. """
  53. def __init__(self, command, domain, translatable):
  54. self.command = command
  55. self.domain = domain
  56. self.translatable = translatable
  57. @cached_property
  58. def is_templatized(self):
  59. if self.domain == 'djangojs':
  60. return self.command.gettext_version < (0, 18, 3)
  61. elif self.domain == 'django':
  62. file_ext = os.path.splitext(self.translatable.file)[1]
  63. return file_ext != '.py'
  64. return False
  65. @cached_property
  66. def path(self):
  67. return self.translatable.path
  68. @cached_property
  69. def work_path(self):
  70. """
  71. Path to a file which is being fed into GNU gettext pipeline. This may
  72. be either a translatable or its preprocessed version.
  73. """
  74. if not self.is_templatized:
  75. return self.path
  76. extension = {
  77. 'djangojs': 'c',
  78. 'django': 'py',
  79. }.get(self.domain)
  80. filename = '%s.%s' % (self.translatable.file, extension)
  81. return os.path.join(self.translatable.dirpath, filename)
  82. def preprocess(self):
  83. """
  84. Preprocess (if necessary) a translatable file before passing it to
  85. xgettext GNU gettext utility.
  86. """
  87. if not self.is_templatized:
  88. return
  89. encoding = settings.FILE_CHARSET if self.command.settings_available else 'utf-8'
  90. with open(self.path, 'r', encoding=encoding) as fp:
  91. src_data = fp.read()
  92. if self.domain == 'djangojs':
  93. content = prepare_js_for_gettext(src_data)
  94. elif self.domain == 'django':
  95. content = templatize(src_data, origin=self.path[2:])
  96. with open(self.work_path, 'w', encoding='utf-8') as fp:
  97. fp.write(content)
  98. def postprocess_messages(self, msgs):
  99. """
  100. Postprocess messages generated by xgettext GNU gettext utility.
  101. Transform paths as if these messages were generated from original
  102. translatable files rather than from preprocessed versions.
  103. """
  104. if not self.is_templatized:
  105. return msgs
  106. # Remove '.py' suffix
  107. if os.name == 'nt':
  108. # Preserve '.\' prefix on Windows to respect gettext behavior
  109. old_path = self.work_path
  110. new_path = self.path
  111. else:
  112. old_path = self.work_path[2:]
  113. new_path = self.path[2:]
  114. return re.sub(
  115. r'^(#: .*)(' + re.escape(old_path) + r')',
  116. lambda match: match.group().replace(old_path, new_path),
  117. msgs,
  118. flags=re.MULTILINE
  119. )
  120. def cleanup(self):
  121. """
  122. Remove a preprocessed copy of a translatable file (if any).
  123. """
  124. if self.is_templatized:
  125. # This check is needed for the case of a symlinked file and its
  126. # source being processed inside a single group (locale dir);
  127. # removing either of those two removes both.
  128. if os.path.exists(self.work_path):
  129. os.unlink(self.work_path)
  130. def normalize_eols(raw_contents):
  131. """
  132. Take a block of raw text that will be passed through str.splitlines() to
  133. get universal newlines treatment.
  134. Return the resulting block of text with normalized `\n` EOL sequences ready
  135. to be written to disk using current platform's native EOLs.
  136. """
  137. lines_list = raw_contents.splitlines()
  138. # Ensure last line has its EOL
  139. if lines_list and lines_list[-1]:
  140. lines_list.append('')
  141. return '\n'.join(lines_list)
  142. def write_pot_file(potfile, msgs):
  143. """
  144. Write the `potfile` with the `msgs` contents, making sure its format is
  145. valid.
  146. """
  147. pot_lines = msgs.splitlines()
  148. if os.path.exists(potfile):
  149. # Strip the header
  150. lines = dropwhile(len, pot_lines)
  151. else:
  152. lines = []
  153. found, header_read = False, False
  154. for line in pot_lines:
  155. if not found and not header_read:
  156. if 'charset=CHARSET' in line:
  157. found = True
  158. line = line.replace('charset=CHARSET', 'charset=UTF-8')
  159. if not line and not found:
  160. header_read = True
  161. lines.append(line)
  162. msgs = '\n'.join(lines)
  163. # Force newlines of POT files to '\n' to work around
  164. # https://savannah.gnu.org/bugs/index.php?52395
  165. with open(potfile, 'a', encoding='utf-8', newline='\n') as fp:
  166. fp.write(msgs)
  167. class Command(BaseCommand):
  168. help = (
  169. "Runs over the entire source tree of the current directory and "
  170. "pulls out all strings marked for translation. It creates (or updates) a message "
  171. "file in the conf/locale (in the django tree) or locale (for projects and "
  172. "applications) directory.\n\nYou must run this command with one of either the "
  173. "--locale, --exclude, or --all options."
  174. )
  175. translatable_file_class = TranslatableFile
  176. build_file_class = BuildFile
  177. requires_system_checks = False
  178. msgmerge_options = ['-q', '--previous']
  179. msguniq_options = ['--to-code=utf-8']
  180. msgattrib_options = ['--no-obsolete']
  181. xgettext_options = ['--from-code=UTF-8', '--add-comments=Translators']
  182. def add_arguments(self, parser):
  183. parser.add_argument(
  184. '--locale', '-l', default=[], action='append',
  185. help='Creates or updates the message files for the given locale(s) (e.g. pt_BR). '
  186. 'Can be used multiple times.',
  187. )
  188. parser.add_argument(
  189. '--exclude', '-x', default=[], action='append',
  190. help='Locales to exclude. Default is none. Can be used multiple times.',
  191. )
  192. parser.add_argument(
  193. '--domain', '-d', default='django',
  194. help='The domain of the message files (default: "django").',
  195. )
  196. parser.add_argument(
  197. '--all', '-a', action='store_true',
  198. help='Updates the message files for all existing locales.',
  199. )
  200. parser.add_argument(
  201. '--extension', '-e', dest='extensions', action='append',
  202. help='The file extension(s) to examine (default: "html,txt,py", or "js" '
  203. 'if the domain is "djangojs"). Separate multiple extensions with '
  204. 'commas, or use -e multiple times.',
  205. )
  206. parser.add_argument(
  207. '--symlinks', '-s', action='store_true',
  208. help='Follows symlinks to directories when examining source code '
  209. 'and templates for translation strings.',
  210. )
  211. parser.add_argument(
  212. '--ignore', '-i', action='append', dest='ignore_patterns',
  213. default=[], metavar='PATTERN',
  214. help='Ignore files or directories matching this glob-style pattern. '
  215. 'Use multiple times to ignore more.',
  216. )
  217. parser.add_argument(
  218. '--no-default-ignore', action='store_false', dest='use_default_ignore_patterns',
  219. help="Don't ignore the common glob-style patterns 'CVS', '.*', '*~' and '*.pyc'.",
  220. )
  221. parser.add_argument(
  222. '--no-wrap', action='store_true',
  223. help="Don't break long message lines into several lines.",
  224. )
  225. parser.add_argument(
  226. '--no-location', action='store_true',
  227. help="Don't write '#: filename:line' lines.",
  228. )
  229. parser.add_argument(
  230. '--add-location',
  231. choices=('full', 'file', 'never'), const='full', nargs='?',
  232. help=(
  233. "Controls '#: filename:line' lines. If the option is 'full' "
  234. "(the default if not given), the lines include both file name "
  235. "and line number. If it's 'file', the line number is omitted. If "
  236. "it's 'never', the lines are suppressed (same as --no-location). "
  237. "--add-location requires gettext 0.19 or newer."
  238. ),
  239. )
  240. parser.add_argument(
  241. '--no-obsolete', action='store_true',
  242. help="Remove obsolete message strings.",
  243. )
  244. parser.add_argument(
  245. '--keep-pot', action='store_true',
  246. help="Keep .pot file after making messages. Useful when debugging.",
  247. )
  248. def handle(self, *args, **options):
  249. locale = options['locale']
  250. exclude = options['exclude']
  251. self.domain = options['domain']
  252. self.verbosity = options['verbosity']
  253. process_all = options['all']
  254. extensions = options['extensions']
  255. self.symlinks = options['symlinks']
  256. ignore_patterns = options['ignore_patterns']
  257. if options['use_default_ignore_patterns']:
  258. ignore_patterns += ['CVS', '.*', '*~', '*.pyc']
  259. self.ignore_patterns = list(set(ignore_patterns))
  260. # Avoid messing with mutable class variables
  261. if options['no_wrap']:
  262. self.msgmerge_options = self.msgmerge_options[:] + ['--no-wrap']
  263. self.msguniq_options = self.msguniq_options[:] + ['--no-wrap']
  264. self.msgattrib_options = self.msgattrib_options[:] + ['--no-wrap']
  265. self.xgettext_options = self.xgettext_options[:] + ['--no-wrap']
  266. if options['no_location']:
  267. self.msgmerge_options = self.msgmerge_options[:] + ['--no-location']
  268. self.msguniq_options = self.msguniq_options[:] + ['--no-location']
  269. self.msgattrib_options = self.msgattrib_options[:] + ['--no-location']
  270. self.xgettext_options = self.xgettext_options[:] + ['--no-location']
  271. if options['add_location']:
  272. if self.gettext_version < (0, 19):
  273. raise CommandError(
  274. "The --add-location option requires gettext 0.19 or later. "
  275. "You have %s." % '.'.join(str(x) for x in self.gettext_version)
  276. )
  277. arg_add_location = "--add-location=%s" % options['add_location']
  278. self.msgmerge_options = self.msgmerge_options[:] + [arg_add_location]
  279. self.msguniq_options = self.msguniq_options[:] + [arg_add_location]
  280. self.msgattrib_options = self.msgattrib_options[:] + [arg_add_location]
  281. self.xgettext_options = self.xgettext_options[:] + [arg_add_location]
  282. self.no_obsolete = options['no_obsolete']
  283. self.keep_pot = options['keep_pot']
  284. if self.domain not in ('django', 'djangojs'):
  285. raise CommandError("currently makemessages only supports domains "
  286. "'django' and 'djangojs'")
  287. if self.domain == 'djangojs':
  288. exts = extensions or ['js']
  289. else:
  290. exts = extensions or ['html', 'txt', 'py']
  291. self.extensions = handle_extensions(exts)
  292. if (locale is None and not exclude and not process_all) or self.domain is None:
  293. raise CommandError(
  294. "Type '%s help %s' for usage information."
  295. % (os.path.basename(sys.argv[0]), sys.argv[1])
  296. )
  297. if self.verbosity > 1:
  298. self.stdout.write(
  299. 'examining files with the extensions: %s\n'
  300. % get_text_list(list(self.extensions), 'and')
  301. )
  302. self.invoked_for_django = False
  303. self.locale_paths = []
  304. self.default_locale_path = None
  305. if os.path.isdir(os.path.join('conf', 'locale')):
  306. self.locale_paths = [os.path.abspath(os.path.join('conf', 'locale'))]
  307. self.default_locale_path = self.locale_paths[0]
  308. self.invoked_for_django = True
  309. else:
  310. if self.settings_available:
  311. self.locale_paths.extend(settings.LOCALE_PATHS)
  312. # Allow to run makemessages inside an app dir
  313. if os.path.isdir('locale'):
  314. self.locale_paths.append(os.path.abspath('locale'))
  315. if self.locale_paths:
  316. self.default_locale_path = self.locale_paths[0]
  317. if not os.path.exists(self.default_locale_path):
  318. os.makedirs(self.default_locale_path)
  319. # Build locale list
  320. looks_like_locale = re.compile(r'[a-z]{2}')
  321. locale_dirs = filter(os.path.isdir, glob.glob('%s/*' % self.default_locale_path))
  322. all_locales = [
  323. lang_code for lang_code in map(os.path.basename, locale_dirs)
  324. if looks_like_locale.match(lang_code)
  325. ]
  326. # Account for excluded locales
  327. if process_all:
  328. locales = all_locales
  329. else:
  330. locales = locale or all_locales
  331. locales = set(locales).difference(exclude)
  332. if locales:
  333. check_programs('msguniq', 'msgmerge', 'msgattrib')
  334. check_programs('xgettext')
  335. try:
  336. potfiles = self.build_potfiles()
  337. # Build po files for each selected locale
  338. for locale in locales:
  339. if self.verbosity > 0:
  340. self.stdout.write("processing locale %s\n" % locale)
  341. for potfile in potfiles:
  342. self.write_po_file(potfile, locale)
  343. finally:
  344. if not self.keep_pot:
  345. self.remove_potfiles()
  346. @cached_property
  347. def gettext_version(self):
  348. # Gettext tools will output system-encoded bytestrings instead of UTF-8,
  349. # when looking up the version. It's especially a problem on Windows.
  350. out, err, status = popen_wrapper(
  351. ['xgettext', '--version'],
  352. stdout_encoding=DEFAULT_LOCALE_ENCODING,
  353. )
  354. m = re.search(r'(\d+)\.(\d+)\.?(\d+)?', out)
  355. if m:
  356. return tuple(int(d) for d in m.groups() if d is not None)
  357. else:
  358. raise CommandError("Unable to get gettext version. Is it installed?")
  359. @cached_property
  360. def settings_available(self):
  361. try:
  362. settings.LOCALE_PATHS
  363. except ImproperlyConfigured:
  364. if self.verbosity > 1:
  365. self.stderr.write("Running without configured settings.")
  366. return False
  367. return True
  368. def build_potfiles(self):
  369. """
  370. Build pot files and apply msguniq to them.
  371. """
  372. file_list = self.find_files(".")
  373. self.remove_potfiles()
  374. self.process_files(file_list)
  375. potfiles = []
  376. for path in self.locale_paths:
  377. potfile = os.path.join(path, '%s.pot' % self.domain)
  378. if not os.path.exists(potfile):
  379. continue
  380. args = ['msguniq'] + self.msguniq_options + [potfile]
  381. msgs, errors, status = popen_wrapper(args)
  382. if errors:
  383. if status != STATUS_OK:
  384. raise CommandError(
  385. "errors happened while running msguniq\n%s" % errors)
  386. elif self.verbosity > 0:
  387. self.stdout.write(errors)
  388. msgs = normalize_eols(msgs)
  389. with open(potfile, 'w', encoding='utf-8') as fp:
  390. fp.write(msgs)
  391. potfiles.append(potfile)
  392. return potfiles
  393. def remove_potfiles(self):
  394. for path in self.locale_paths:
  395. pot_path = os.path.join(path, '%s.pot' % self.domain)
  396. if os.path.exists(pot_path):
  397. os.unlink(pot_path)
  398. def find_files(self, root):
  399. """
  400. Get all files in the given root. Also check that there is a matching
  401. locale dir for each file.
  402. """
  403. def is_ignored(path, ignore_patterns):
  404. """
  405. Check if the given path should be ignored or not.
  406. """
  407. filename = os.path.basename(path)
  408. def ignore(pattern):
  409. return fnmatch.fnmatchcase(filename, pattern) or fnmatch.fnmatchcase(path, pattern)
  410. return any(ignore(pattern) for pattern in ignore_patterns)
  411. ignore_patterns = [os.path.normcase(p) for p in self.ignore_patterns]
  412. dir_suffixes = {'%s*' % path_sep for path_sep in {'/', os.sep}}
  413. norm_patterns = []
  414. for p in ignore_patterns:
  415. for dir_suffix in dir_suffixes:
  416. if p.endswith(dir_suffix):
  417. norm_patterns.append(p[:-len(dir_suffix)])
  418. break
  419. else:
  420. norm_patterns.append(p)
  421. all_files = []
  422. ignored_roots = []
  423. if self.settings_available:
  424. ignored_roots = [os.path.normpath(p) for p in (settings.MEDIA_ROOT, settings.STATIC_ROOT) if p]
  425. for dirpath, dirnames, filenames in os.walk(root, topdown=True, followlinks=self.symlinks):
  426. for dirname in dirnames[:]:
  427. if (is_ignored(os.path.normpath(os.path.join(dirpath, dirname)), norm_patterns) or
  428. os.path.join(os.path.abspath(dirpath), dirname) in ignored_roots):
  429. dirnames.remove(dirname)
  430. if self.verbosity > 1:
  431. self.stdout.write('ignoring directory %s\n' % dirname)
  432. elif dirname == 'locale':
  433. dirnames.remove(dirname)
  434. self.locale_paths.insert(0, os.path.join(os.path.abspath(dirpath), dirname))
  435. for filename in filenames:
  436. file_path = os.path.normpath(os.path.join(dirpath, filename))
  437. file_ext = os.path.splitext(filename)[1]
  438. if file_ext not in self.extensions or is_ignored(file_path, self.ignore_patterns):
  439. if self.verbosity > 1:
  440. self.stdout.write('ignoring file %s in %s\n' % (filename, dirpath))
  441. else:
  442. locale_dir = None
  443. for path in self.locale_paths:
  444. if os.path.abspath(dirpath).startswith(os.path.dirname(path)):
  445. locale_dir = path
  446. break
  447. locale_dir = locale_dir or self.default_locale_path or NO_LOCALE_DIR
  448. all_files.append(self.translatable_file_class(dirpath, filename, locale_dir))
  449. return sorted(all_files)
  450. def process_files(self, file_list):
  451. """
  452. Group translatable files by locale directory and run pot file build
  453. process for each group.
  454. """
  455. file_groups = {}
  456. for translatable in file_list:
  457. file_group = file_groups.setdefault(translatable.locale_dir, [])
  458. file_group.append(translatable)
  459. for locale_dir, files in file_groups.items():
  460. self.process_locale_dir(locale_dir, files)
  461. def process_locale_dir(self, locale_dir, files):
  462. """
  463. Extract translatable literals from the specified files, creating or
  464. updating the POT file for a given locale directory.
  465. Use the xgettext GNU gettext utility.
  466. """
  467. build_files = []
  468. for translatable in files:
  469. if self.verbosity > 1:
  470. self.stdout.write('processing file %s in %s\n' % (
  471. translatable.file, translatable.dirpath
  472. ))
  473. if self.domain not in ('djangojs', 'django'):
  474. continue
  475. build_file = self.build_file_class(self, self.domain, translatable)
  476. try:
  477. build_file.preprocess()
  478. except UnicodeDecodeError as e:
  479. self.stdout.write(
  480. 'UnicodeDecodeError: skipped file %s in %s (reason: %s)' % (
  481. translatable.file, translatable.dirpath, e,
  482. )
  483. )
  484. continue
  485. build_files.append(build_file)
  486. if self.domain == 'djangojs':
  487. is_templatized = build_file.is_templatized
  488. args = [
  489. 'xgettext',
  490. '-d', self.domain,
  491. '--language=%s' % ('C' if is_templatized else 'JavaScript',),
  492. '--keyword=gettext_noop',
  493. '--keyword=gettext_lazy',
  494. '--keyword=ngettext_lazy:1,2',
  495. '--keyword=pgettext:1c,2',
  496. '--keyword=npgettext:1c,2,3',
  497. '--output=-',
  498. ]
  499. elif self.domain == 'django':
  500. args = [
  501. 'xgettext',
  502. '-d', self.domain,
  503. '--language=Python',
  504. '--keyword=gettext_noop',
  505. '--keyword=gettext_lazy',
  506. '--keyword=ngettext_lazy:1,2',
  507. '--keyword=ugettext_noop',
  508. '--keyword=ugettext_lazy',
  509. '--keyword=ungettext_lazy:1,2',
  510. '--keyword=pgettext:1c,2',
  511. '--keyword=npgettext:1c,2,3',
  512. '--keyword=pgettext_lazy:1c,2',
  513. '--keyword=npgettext_lazy:1c,2,3',
  514. '--output=-',
  515. ]
  516. else:
  517. return
  518. input_files = [bf.work_path for bf in build_files]
  519. with NamedTemporaryFile(mode='w+') as input_files_list:
  520. input_files_list.write(('\n'.join(input_files)))
  521. input_files_list.flush()
  522. args.extend(['--files-from', input_files_list.name])
  523. args.extend(self.xgettext_options)
  524. msgs, errors, status = popen_wrapper(args)
  525. if errors:
  526. if status != STATUS_OK:
  527. for build_file in build_files:
  528. build_file.cleanup()
  529. raise CommandError(
  530. 'errors happened while running xgettext on %s\n%s' %
  531. ('\n'.join(input_files), errors)
  532. )
  533. elif self.verbosity > 0:
  534. # Print warnings
  535. self.stdout.write(errors)
  536. if msgs:
  537. if locale_dir is NO_LOCALE_DIR:
  538. file_path = os.path.normpath(build_files[0].path)
  539. raise CommandError(
  540. 'Unable to find a locale path to store translations for '
  541. 'file %s' % file_path
  542. )
  543. for build_file in build_files:
  544. msgs = build_file.postprocess_messages(msgs)
  545. potfile = os.path.join(locale_dir, '%s.pot' % self.domain)
  546. write_pot_file(potfile, msgs)
  547. for build_file in build_files:
  548. build_file.cleanup()
  549. def write_po_file(self, potfile, locale):
  550. """
  551. Create or update the PO file for self.domain and `locale`.
  552. Use contents of the existing `potfile`.
  553. Use msgmerge and msgattrib GNU gettext utilities.
  554. """
  555. basedir = os.path.join(os.path.dirname(potfile), locale, 'LC_MESSAGES')
  556. if not os.path.isdir(basedir):
  557. os.makedirs(basedir)
  558. pofile = os.path.join(basedir, '%s.po' % self.domain)
  559. if os.path.exists(pofile):
  560. args = ['msgmerge'] + self.msgmerge_options + [pofile, potfile]
  561. msgs, errors, status = popen_wrapper(args)
  562. if errors:
  563. if status != STATUS_OK:
  564. raise CommandError(
  565. "errors happened while running msgmerge\n%s" % errors)
  566. elif self.verbosity > 0:
  567. self.stdout.write(errors)
  568. else:
  569. with open(potfile, 'r', encoding='utf-8') as fp:
  570. msgs = fp.read()
  571. if not self.invoked_for_django:
  572. msgs = self.copy_plural_forms(msgs, locale)
  573. msgs = normalize_eols(msgs)
  574. msgs = msgs.replace(
  575. "#. #-#-#-#-# %s.pot (PACKAGE VERSION) #-#-#-#-#\n" % self.domain, "")
  576. with open(pofile, 'w', encoding='utf-8') as fp:
  577. fp.write(msgs)
  578. if self.no_obsolete:
  579. args = ['msgattrib'] + self.msgattrib_options + ['-o', pofile, pofile]
  580. msgs, errors, status = popen_wrapper(args)
  581. if errors:
  582. if status != STATUS_OK:
  583. raise CommandError(
  584. "errors happened while running msgattrib\n%s" % errors)
  585. elif self.verbosity > 0:
  586. self.stdout.write(errors)
  587. def copy_plural_forms(self, msgs, locale):
  588. """
  589. Copy plural forms header contents from a Django catalog of locale to
  590. the msgs string, inserting it at the right place. msgs should be the
  591. contents of a newly created .po file.
  592. """
  593. django_dir = os.path.normpath(os.path.join(os.path.dirname(django.__file__)))
  594. if self.domain == 'djangojs':
  595. domains = ('djangojs', 'django')
  596. else:
  597. domains = ('django',)
  598. for domain in domains:
  599. django_po = os.path.join(django_dir, 'conf', 'locale', locale, 'LC_MESSAGES', '%s.po' % domain)
  600. if os.path.exists(django_po):
  601. with open(django_po, 'r', encoding='utf-8') as fp:
  602. m = plural_forms_re.search(fp.read())
  603. if m:
  604. plural_form_line = m.group('value')
  605. if self.verbosity > 1:
  606. self.stdout.write("copying plural forms: %s\n" % plural_form_line)
  607. lines = []
  608. found = False
  609. for line in msgs.splitlines():
  610. if not found and (not line or plural_forms_re.search(line)):
  611. line = plural_form_line
  612. found = True
  613. lines.append(line)
  614. msgs = '\n'.join(lines)
  615. break
  616. return msgs