trans_real.py 28 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751
  1. """Translation helper functions."""
  2. from __future__ import unicode_literals
  3. from collections import OrderedDict
  4. import os
  5. import re
  6. import sys
  7. import gettext as gettext_module
  8. from threading import local
  9. import warnings
  10. from django.apps import apps
  11. from django.conf import settings
  12. from django.conf.locale import LANG_INFO
  13. from django.core.exceptions import AppRegistryNotReady
  14. from django.core.signals import setting_changed
  15. from django.dispatch import receiver
  16. from django.utils.deprecation import RemovedInDjango19Warning
  17. from django.utils.encoding import force_text
  18. from django.utils._os import upath
  19. from django.utils.safestring import mark_safe, SafeData
  20. from django.utils import six, lru_cache
  21. from django.utils.six import StringIO
  22. from django.utils.translation import TranslatorCommentWarning, trim_whitespace, LANGUAGE_SESSION_KEY
  23. # Translations are cached in a dictionary for every language.
  24. # The active translations are stored by threadid to make them thread local.
  25. _translations = {}
  26. _active = local()
  27. # The default translation is based on the settings file.
  28. _default = None
  29. # magic gettext number to separate context from message
  30. CONTEXT_SEPARATOR = "\x04"
  31. # Format of Accept-Language header values. From RFC 2616, section 14.4 and 3.9
  32. # and RFC 3066, section 2.1
  33. accept_language_re = re.compile(r'''
  34. ([A-Za-z]{1,8}(?:-[A-Za-z0-9]{1,8})*|\*) # "en", "en-au", "x-y-z", "es-419", "*"
  35. (?:\s*;\s*q=(0(?:\.\d{,3})?|1(?:.0{,3})?))? # Optional "q=1.00", "q=0.8"
  36. (?:\s*,\s*|$) # Multiple accepts per header.
  37. ''', re.VERBOSE)
  38. language_code_re = re.compile(r'^[a-z]{1,8}(?:-[a-z0-9]{1,8})*$', re.IGNORECASE)
  39. language_code_prefix_re = re.compile(r'^/([\w-]+)(/|$)')
  40. # some browsers use deprecated locales. refs #18419
  41. _DJANGO_DEPRECATED_LOCALES = {
  42. 'zh-cn': 'zh-hans',
  43. 'zh-tw': 'zh-hant',
  44. }
  45. @receiver(setting_changed)
  46. def reset_cache(**kwargs):
  47. """
  48. Reset global state when LANGUAGES setting has been changed, as some
  49. languages should no longer be accepted.
  50. """
  51. if kwargs['setting'] in ('LANGUAGES', 'LANGUAGE_CODE'):
  52. check_for_language.cache_clear()
  53. get_languages.cache_clear()
  54. get_supported_language_variant.cache_clear()
  55. def to_locale(language, to_lower=False):
  56. """
  57. Turns a language name (en-us) into a locale name (en_US). If 'to_lower' is
  58. True, the last component is lower-cased (en_us).
  59. """
  60. p = language.find('-')
  61. if p >= 0:
  62. if to_lower:
  63. return language[:p].lower() + '_' + language[p + 1:].lower()
  64. else:
  65. # Get correct locale for sr-latn
  66. if len(language[p + 1:]) > 2:
  67. return language[:p].lower() + '_' + language[p + 1].upper() + language[p + 2:].lower()
  68. return language[:p].lower() + '_' + language[p + 1:].upper()
  69. else:
  70. return language.lower()
  71. def to_language(locale):
  72. """Turns a locale name (en_US) into a language name (en-us)."""
  73. p = locale.find('_')
  74. if p >= 0:
  75. return locale[:p].lower() + '-' + locale[p + 1:].lower()
  76. else:
  77. return locale.lower()
  78. class DjangoTranslation(gettext_module.GNUTranslations):
  79. """
  80. This class sets up the GNUTranslations context with regard to output
  81. charset.
  82. This translation object will be constructed out of multiple GNUTranslations
  83. objects by merging their catalogs. It will construct an object for the
  84. requested language and add a fallback to the default language, if it's
  85. different from the requested language.
  86. """
  87. def __init__(self, language):
  88. """Create a GNUTranslations() using many locale directories"""
  89. gettext_module.GNUTranslations.__init__(self)
  90. self.__language = language
  91. self.__to_language = to_language(language)
  92. self.__locale = to_locale(language)
  93. self.plural = lambda n: int(n != 1)
  94. self._init_translation_catalog()
  95. self._add_installed_apps_translations()
  96. self._add_local_translations()
  97. self._add_fallback()
  98. def __repr__(self):
  99. return "<DjangoTranslation lang:%s>" % self.__language
  100. def _new_gnu_trans(self, localedir, use_null_fallback=True):
  101. """
  102. Returns a mergeable gettext.GNUTranslations instance.
  103. A convenience wrapper. By default gettext uses 'fallback=False'.
  104. Using param `use_null_fallback` to avoid confusion with any other
  105. references to 'fallback'.
  106. """
  107. translation = gettext_module.translation(
  108. domain='django',
  109. localedir=localedir,
  110. languages=[self.__locale],
  111. codeset='utf-8',
  112. fallback=use_null_fallback)
  113. if not hasattr(translation, '_catalog'):
  114. # provides merge support for NullTranslations()
  115. translation._catalog = {}
  116. translation._info = {}
  117. return translation
  118. def _init_translation_catalog(self):
  119. """Creates a base catalog using global django translations."""
  120. settingsfile = upath(sys.modules[settings.__module__].__file__)
  121. localedir = os.path.join(os.path.dirname(settingsfile), 'locale')
  122. use_null_fallback = True
  123. if self.__language == settings.LANGUAGE_CODE:
  124. # default lang should be present and parseable, if not
  125. # gettext will raise an IOError (refs #18192).
  126. use_null_fallback = False
  127. translation = self._new_gnu_trans(localedir, use_null_fallback)
  128. self._info = translation._info.copy()
  129. self._catalog = translation._catalog.copy()
  130. def _add_installed_apps_translations(self):
  131. """Merges translations from each installed app."""
  132. try:
  133. app_configs = reversed(list(apps.get_app_configs()))
  134. except AppRegistryNotReady:
  135. raise AppRegistryNotReady(
  136. "The translation infrastructure cannot be initialized before the "
  137. "apps registry is ready. Check that you don't make non-lazy "
  138. "gettext calls at import time.")
  139. for app_config in app_configs:
  140. localedir = os.path.join(app_config.path, 'locale')
  141. translation = self._new_gnu_trans(localedir)
  142. self.merge(translation)
  143. def _add_local_translations(self):
  144. """Merges translations defined in LOCALE_PATHS."""
  145. for localedir in reversed(settings.LOCALE_PATHS):
  146. translation = self._new_gnu_trans(localedir)
  147. self.merge(translation)
  148. def _add_fallback(self):
  149. """Sets the GNUTranslations() fallback with the default language."""
  150. # Don't set a fallback for the default language or for
  151. # en-us (as it's empty, so it'll ALWAYS fall back to the default
  152. # language; found this as part of #21498, as we set en-us for
  153. # management commands)
  154. if self.__language == settings.LANGUAGE_CODE or self.__language == "en-us":
  155. return
  156. default_translation = translation(settings.LANGUAGE_CODE)
  157. self.add_fallback(default_translation)
  158. def merge(self, other):
  159. """Merge another translation into this catalog."""
  160. self._catalog.update(other._catalog)
  161. def language(self):
  162. """Returns the translation language."""
  163. return self.__language
  164. def to_language(self):
  165. """Returns the translation language name."""
  166. return self.__to_language
  167. def translation(language):
  168. """
  169. Returns a translation object.
  170. """
  171. global _translations
  172. if language not in _translations:
  173. _translations[language] = DjangoTranslation(language)
  174. return _translations[language]
  175. def activate(language):
  176. """
  177. Fetches the translation object for a given language and installs it as the
  178. current translation object for the current thread.
  179. """
  180. if language in _DJANGO_DEPRECATED_LOCALES:
  181. msg = ("The use of the language code '%s' is deprecated. "
  182. "Please use the '%s' translation instead.")
  183. warnings.warn(msg % (language, _DJANGO_DEPRECATED_LOCALES[language]),
  184. RemovedInDjango19Warning, stacklevel=2)
  185. _active.value = translation(language)
  186. def deactivate():
  187. """
  188. Deinstalls the currently active translation object so that further _ calls
  189. will resolve against the default translation object, again.
  190. """
  191. if hasattr(_active, "value"):
  192. del _active.value
  193. def deactivate_all():
  194. """
  195. Makes the active translation object a NullTranslations() instance. This is
  196. useful when we want delayed translations to appear as the original string
  197. for some reason.
  198. """
  199. _active.value = gettext_module.NullTranslations()
  200. def get_language():
  201. """Returns the currently selected language."""
  202. t = getattr(_active, "value", None)
  203. if t is not None:
  204. try:
  205. return t.to_language()
  206. except AttributeError:
  207. pass
  208. # If we don't have a real translation object, assume it's the default language.
  209. return settings.LANGUAGE_CODE
  210. def get_language_bidi():
  211. """
  212. Returns selected language's BiDi layout.
  213. * False = left-to-right layout
  214. * True = right-to-left layout
  215. """
  216. base_lang = get_language().split('-')[0]
  217. return base_lang in settings.LANGUAGES_BIDI
  218. def catalog():
  219. """
  220. Returns the current active catalog for further processing.
  221. This can be used if you need to modify the catalog or want to access the
  222. whole message catalog instead of just translating one string.
  223. """
  224. global _default
  225. t = getattr(_active, "value", None)
  226. if t is not None:
  227. return t
  228. if _default is None:
  229. _default = translation(settings.LANGUAGE_CODE)
  230. return _default
  231. def do_translate(message, translation_function):
  232. """
  233. Translates 'message' using the given 'translation_function' name -- which
  234. will be either gettext or ugettext. It uses the current thread to find the
  235. translation object to use. If no current translation is activated, the
  236. message will be run through the default translation object.
  237. """
  238. global _default
  239. # str() is allowing a bytestring message to remain bytestring on Python 2
  240. eol_message = message.replace(str('\r\n'), str('\n')).replace(str('\r'), str('\n'))
  241. if len(eol_message) == 0:
  242. # Returns an empty value of the corresponding type if an empty message
  243. # is given, instead of metadata, which is the default gettext behavior.
  244. result = type(message)("")
  245. else:
  246. _default = _default or translation(settings.LANGUAGE_CODE)
  247. translation_object = getattr(_active, "value", _default)
  248. result = getattr(translation_object, translation_function)(eol_message)
  249. if isinstance(message, SafeData):
  250. return mark_safe(result)
  251. return result
  252. def gettext(message):
  253. """
  254. Returns a string of the translation of the message.
  255. Returns a string on Python 3 and an UTF-8-encoded bytestring on Python 2.
  256. """
  257. return do_translate(message, 'gettext')
  258. if six.PY3:
  259. ugettext = gettext
  260. else:
  261. def ugettext(message):
  262. return do_translate(message, 'ugettext')
  263. def pgettext(context, message):
  264. msg_with_ctxt = "%s%s%s" % (context, CONTEXT_SEPARATOR, message)
  265. result = ugettext(msg_with_ctxt)
  266. if CONTEXT_SEPARATOR in result:
  267. # Translation not found
  268. # force unicode, because lazy version expects unicode
  269. result = force_text(message)
  270. return result
  271. def gettext_noop(message):
  272. """
  273. Marks strings for translation but doesn't translate them now. This can be
  274. used to store strings in global variables that should stay in the base
  275. language (because they might be used externally) and will be translated
  276. later.
  277. """
  278. return message
  279. def do_ntranslate(singular, plural, number, translation_function):
  280. global _default
  281. t = getattr(_active, "value", None)
  282. if t is not None:
  283. return getattr(t, translation_function)(singular, plural, number)
  284. if _default is None:
  285. _default = translation(settings.LANGUAGE_CODE)
  286. return getattr(_default, translation_function)(singular, plural, number)
  287. def ngettext(singular, plural, number):
  288. """
  289. Returns a string of the translation of either the singular or plural,
  290. based on the number.
  291. Returns a string on Python 3 and an UTF-8-encoded bytestring on Python 2.
  292. """
  293. return do_ntranslate(singular, plural, number, 'ngettext')
  294. if six.PY3:
  295. ungettext = ngettext
  296. else:
  297. def ungettext(singular, plural, number):
  298. """
  299. Returns a unicode strings of the translation of either the singular or
  300. plural, based on the number.
  301. """
  302. return do_ntranslate(singular, plural, number, 'ungettext')
  303. def npgettext(context, singular, plural, number):
  304. msgs_with_ctxt = ("%s%s%s" % (context, CONTEXT_SEPARATOR, singular),
  305. "%s%s%s" % (context, CONTEXT_SEPARATOR, plural),
  306. number)
  307. result = ungettext(*msgs_with_ctxt)
  308. if CONTEXT_SEPARATOR in result:
  309. # Translation not found
  310. result = ungettext(singular, plural, number)
  311. return result
  312. def all_locale_paths():
  313. """
  314. Returns a list of paths to user-provides languages files.
  315. """
  316. globalpath = os.path.join(
  317. os.path.dirname(upath(sys.modules[settings.__module__].__file__)), 'locale')
  318. return [globalpath] + list(settings.LOCALE_PATHS)
  319. @lru_cache.lru_cache(maxsize=1000)
  320. def check_for_language(lang_code):
  321. """
  322. Checks whether there is a global language file for the given language
  323. code. This is used to decide whether a user-provided language is
  324. available.
  325. lru_cache should have a maxsize to prevent from memory exhaustion attacks,
  326. as the provided language codes are taken from the HTTP request. See also
  327. <https://www.djangoproject.com/weblog/2007/oct/26/security-fix/>.
  328. """
  329. # First, a quick check to make sure lang_code is well-formed (#21458)
  330. if not language_code_re.search(lang_code):
  331. return False
  332. for path in all_locale_paths():
  333. if gettext_module.find('django', path, [to_locale(lang_code)]) is not None:
  334. return True
  335. return False
  336. @lru_cache.lru_cache()
  337. def get_languages():
  338. """
  339. Cache of settings.LANGUAGES in an OrderedDict for easy lookups by key.
  340. """
  341. return OrderedDict(settings.LANGUAGES)
  342. @lru_cache.lru_cache(maxsize=1000)
  343. def get_supported_language_variant(lang_code, strict=False):
  344. """
  345. Returns the language-code that's listed in supported languages, possibly
  346. selecting a more generic variant. Raises LookupError if nothing found.
  347. If `strict` is False (the default), the function will look for an alternative
  348. country-specific variant when the currently checked is not found.
  349. lru_cache should have a maxsize to prevent from memory exhaustion attacks,
  350. as the provided language codes are taken from the HTTP request. See also
  351. <https://www.djangoproject.com/weblog/2007/oct/26/security-fix/>.
  352. """
  353. if lang_code:
  354. # If 'fr-ca' is not supported, try special fallback or language-only 'fr'.
  355. possible_lang_codes = [lang_code]
  356. try:
  357. possible_lang_codes.extend(LANG_INFO[lang_code]['fallback'])
  358. except KeyError:
  359. pass
  360. generic_lang_code = lang_code.split('-')[0]
  361. possible_lang_codes.append(generic_lang_code)
  362. supported_lang_codes = get_languages()
  363. for code in possible_lang_codes:
  364. if code in supported_lang_codes and check_for_language(code):
  365. return code
  366. if not strict:
  367. # if fr-fr is not supported, try fr-ca.
  368. for supported_code in supported_lang_codes:
  369. if supported_code.startswith(generic_lang_code + '-'):
  370. return supported_code
  371. raise LookupError(lang_code)
  372. def get_language_from_path(path, strict=False):
  373. """
  374. Returns the language-code if there is a valid language-code
  375. found in the `path`.
  376. If `strict` is False (the default), the function will look for an alternative
  377. country-specific variant when the currently checked is not found.
  378. """
  379. regex_match = language_code_prefix_re.match(path)
  380. if not regex_match:
  381. return None
  382. lang_code = regex_match.group(1)
  383. try:
  384. return get_supported_language_variant(lang_code, strict=strict)
  385. except LookupError:
  386. return None
  387. def get_language_from_request(request, check_path=False):
  388. """
  389. Analyzes the request to find what language the user wants the system to
  390. show. Only languages listed in settings.LANGUAGES are taken into account.
  391. If the user requests a sublanguage where we have a main language, we send
  392. out the main language.
  393. If check_path is True, the URL path prefix will be checked for a language
  394. code, otherwise this is skipped for backwards compatibility.
  395. """
  396. if check_path:
  397. lang_code = get_language_from_path(request.path_info)
  398. if lang_code is not None:
  399. return lang_code
  400. supported_lang_codes = get_languages()
  401. if hasattr(request, 'session'):
  402. lang_code = request.session.get(LANGUAGE_SESSION_KEY)
  403. if lang_code in supported_lang_codes and lang_code is not None and check_for_language(lang_code):
  404. return lang_code
  405. lang_code = request.COOKIES.get(settings.LANGUAGE_COOKIE_NAME)
  406. try:
  407. return get_supported_language_variant(lang_code)
  408. except LookupError:
  409. pass
  410. accept = request.META.get('HTTP_ACCEPT_LANGUAGE', '')
  411. for accept_lang, unused in parse_accept_lang_header(accept):
  412. if accept_lang == '*':
  413. break
  414. if not language_code_re.search(accept_lang):
  415. continue
  416. try:
  417. return get_supported_language_variant(accept_lang)
  418. except LookupError:
  419. continue
  420. try:
  421. return get_supported_language_variant(settings.LANGUAGE_CODE)
  422. except LookupError:
  423. return settings.LANGUAGE_CODE
  424. dot_re = re.compile(r'\S')
  425. def blankout(src, char):
  426. """
  427. Changes every non-whitespace character to the given char.
  428. Used in the templatize function.
  429. """
  430. return dot_re.sub(char, src)
  431. context_re = re.compile(r"""^\s+.*context\s+((?:"[^"]*?")|(?:'[^']*?'))\s*""")
  432. inline_re = re.compile(r"""^\s*trans\s+((?:"[^"]*?")|(?:'[^']*?'))(\s+.*context\s+((?:"[^"]*?")|(?:'[^']*?')))?\s*""")
  433. block_re = re.compile(r"""^\s*blocktrans(\s+.*context\s+((?:"[^"]*?")|(?:'[^']*?')))?(?:\s+|$)""")
  434. endblock_re = re.compile(r"""^\s*endblocktrans$""")
  435. plural_re = re.compile(r"""^\s*plural$""")
  436. constant_re = re.compile(r"""_\(((?:".*?")|(?:'.*?'))\)""")
  437. one_percent_re = re.compile(r"""(?<!%)%(?!%)""")
  438. def templatize(src, origin=None):
  439. """
  440. Turns a Django template into something that is understood by xgettext. It
  441. does so by translating the Django translation tags into standard gettext
  442. function invocations.
  443. """
  444. from django.template import (Lexer, TOKEN_TEXT, TOKEN_VAR, TOKEN_BLOCK,
  445. TOKEN_COMMENT, TRANSLATOR_COMMENT_MARK)
  446. src = force_text(src, settings.FILE_CHARSET)
  447. out = StringIO('')
  448. message_context = None
  449. intrans = False
  450. inplural = False
  451. trimmed = False
  452. singular = []
  453. plural = []
  454. incomment = False
  455. comment = []
  456. lineno_comment_map = {}
  457. comment_lineno_cache = None
  458. def join_tokens(tokens, trim=False):
  459. message = ''.join(tokens)
  460. if trim:
  461. message = trim_whitespace(message)
  462. return message
  463. for t in Lexer(src, origin).tokenize():
  464. if incomment:
  465. if t.token_type == TOKEN_BLOCK and t.contents == 'endcomment':
  466. content = ''.join(comment)
  467. translators_comment_start = None
  468. for lineno, line in enumerate(content.splitlines(True)):
  469. if line.lstrip().startswith(TRANSLATOR_COMMENT_MARK):
  470. translators_comment_start = lineno
  471. for lineno, line in enumerate(content.splitlines(True)):
  472. if translators_comment_start is not None and lineno >= translators_comment_start:
  473. out.write(' # %s' % line)
  474. else:
  475. out.write(' #\n')
  476. incomment = False
  477. comment = []
  478. else:
  479. comment.append(t.contents)
  480. elif intrans:
  481. if t.token_type == TOKEN_BLOCK:
  482. endbmatch = endblock_re.match(t.contents)
  483. pluralmatch = plural_re.match(t.contents)
  484. if endbmatch:
  485. if inplural:
  486. if message_context:
  487. out.write(' npgettext(%r, %r, %r,count) ' % (
  488. message_context,
  489. join_tokens(singular, trimmed),
  490. join_tokens(plural, trimmed)))
  491. else:
  492. out.write(' ngettext(%r, %r, count) ' % (
  493. join_tokens(singular, trimmed),
  494. join_tokens(plural, trimmed)))
  495. for part in singular:
  496. out.write(blankout(part, 'S'))
  497. for part in plural:
  498. out.write(blankout(part, 'P'))
  499. else:
  500. if message_context:
  501. out.write(' pgettext(%r, %r) ' % (
  502. message_context,
  503. join_tokens(singular, trimmed)))
  504. else:
  505. out.write(' gettext(%r) ' % join_tokens(singular,
  506. trimmed))
  507. for part in singular:
  508. out.write(blankout(part, 'S'))
  509. message_context = None
  510. intrans = False
  511. inplural = False
  512. singular = []
  513. plural = []
  514. elif pluralmatch:
  515. inplural = True
  516. else:
  517. filemsg = ''
  518. if origin:
  519. filemsg = 'file %s, ' % origin
  520. raise SyntaxError(
  521. "Translation blocks must not include other block tags: "
  522. "%s (%sline %d)" % (t.contents, filemsg, t.lineno)
  523. )
  524. elif t.token_type == TOKEN_VAR:
  525. if inplural:
  526. plural.append('%%(%s)s' % t.contents)
  527. else:
  528. singular.append('%%(%s)s' % t.contents)
  529. elif t.token_type == TOKEN_TEXT:
  530. contents = one_percent_re.sub('%%', t.contents)
  531. if inplural:
  532. plural.append(contents)
  533. else:
  534. singular.append(contents)
  535. else:
  536. # Handle comment tokens (`{# ... #}`) plus other constructs on
  537. # the same line:
  538. if comment_lineno_cache is not None:
  539. cur_lineno = t.lineno + t.contents.count('\n')
  540. if comment_lineno_cache == cur_lineno:
  541. if t.token_type != TOKEN_COMMENT:
  542. for c in lineno_comment_map[comment_lineno_cache]:
  543. filemsg = ''
  544. if origin:
  545. filemsg = 'file %s, ' % origin
  546. warn_msg = ("The translator-targeted comment '%s' "
  547. "(%sline %d) was ignored, because it wasn't the last item "
  548. "on the line.") % (c, filemsg, comment_lineno_cache)
  549. warnings.warn(warn_msg, TranslatorCommentWarning)
  550. lineno_comment_map[comment_lineno_cache] = []
  551. else:
  552. out.write('# %s' % ' | '.join(lineno_comment_map[comment_lineno_cache]))
  553. comment_lineno_cache = None
  554. if t.token_type == TOKEN_BLOCK:
  555. imatch = inline_re.match(t.contents)
  556. bmatch = block_re.match(t.contents)
  557. cmatches = constant_re.findall(t.contents)
  558. if imatch:
  559. g = imatch.group(1)
  560. if g[0] == '"':
  561. g = g.strip('"')
  562. elif g[0] == "'":
  563. g = g.strip("'")
  564. g = one_percent_re.sub('%%', g)
  565. if imatch.group(2):
  566. # A context is provided
  567. context_match = context_re.match(imatch.group(2))
  568. message_context = context_match.group(1)
  569. if message_context[0] == '"':
  570. message_context = message_context.strip('"')
  571. elif message_context[0] == "'":
  572. message_context = message_context.strip("'")
  573. out.write(' pgettext(%r, %r) ' % (message_context, g))
  574. message_context = None
  575. else:
  576. out.write(' gettext(%r) ' % g)
  577. elif bmatch:
  578. for fmatch in constant_re.findall(t.contents):
  579. out.write(' _(%s) ' % fmatch)
  580. if bmatch.group(1):
  581. # A context is provided
  582. context_match = context_re.match(bmatch.group(1))
  583. message_context = context_match.group(1)
  584. if message_context[0] == '"':
  585. message_context = message_context.strip('"')
  586. elif message_context[0] == "'":
  587. message_context = message_context.strip("'")
  588. intrans = True
  589. inplural = False
  590. trimmed = 'trimmed' in t.split_contents()
  591. singular = []
  592. plural = []
  593. elif cmatches:
  594. for cmatch in cmatches:
  595. out.write(' _(%s) ' % cmatch)
  596. elif t.contents == 'comment':
  597. incomment = True
  598. else:
  599. out.write(blankout(t.contents, 'B'))
  600. elif t.token_type == TOKEN_VAR:
  601. parts = t.contents.split('|')
  602. cmatch = constant_re.match(parts[0])
  603. if cmatch:
  604. out.write(' _(%s) ' % cmatch.group(1))
  605. for p in parts[1:]:
  606. if p.find(':_(') >= 0:
  607. out.write(' %s ' % p.split(':', 1)[1])
  608. else:
  609. out.write(blankout(p, 'F'))
  610. elif t.token_type == TOKEN_COMMENT:
  611. if t.contents.lstrip().startswith(TRANSLATOR_COMMENT_MARK):
  612. lineno_comment_map.setdefault(t.lineno,
  613. []).append(t.contents)
  614. comment_lineno_cache = t.lineno
  615. else:
  616. out.write(blankout(t.contents, 'X'))
  617. return out.getvalue()
  618. def parse_accept_lang_header(lang_string):
  619. """
  620. Parses the lang_string, which is the body of an HTTP Accept-Language
  621. header, and returns a list of (lang, q-value), ordered by 'q' values.
  622. Any format errors in lang_string results in an empty list being returned.
  623. """
  624. result = []
  625. pieces = accept_language_re.split(lang_string.lower())
  626. if pieces[-1]:
  627. return []
  628. for i in range(0, len(pieces) - 1, 3):
  629. first, lang, priority = pieces[i:i + 3]
  630. if first:
  631. return []
  632. if priority:
  633. try:
  634. priority = float(priority)
  635. except ValueError:
  636. return []
  637. if not priority: # if priority is 0.0 at this point make it 1.0
  638. priority = 1.0
  639. result.append((lang, priority))
  640. result.sort(key=lambda k: k[1], reverse=True)
  641. return result