Skip to content

Instantly share code, notes, and snippets.

@krinnewitz
Created September 16, 2019 09:20
Show Gist options
  • Save krinnewitz/8d4581ca32989e20771c300ab07d88f1 to your computer and use it in GitHub Desktop.
Save krinnewitz/8d4581ca32989e20771c300ab07d88f1 to your computer and use it in GitHub Desktop.
python-i18n pylint check
import os
import astroid
import i18n
from pylint.checkers import BaseChecker
from pylint.interfaces import IAstroidChecker
class I18nChecker(BaseChecker):
"""check for wrong translation keys"""
__implements__ = IAstroidChecker
name = "i18n_check"
msgs = {
"W9901": (
"Invalid translation key",
"invalid-translation-key",
"The translation key does not exist.",
),
"W9902": (
"Non-final translation key",
"nonfinal-translation-key",
"Only constants are allowed as translation keys.",
),
}
options = ()
def visit_call(self, node):
if (
isinstance(node.func, astroid.Attribute)
and isinstance(node.func.expr, astroid.Name)
and node.func.expr.name == "i18n"
and node.func.attrname == "t"
):
if isinstance(node.args[0], astroid.Const):
val = node.args[0].value
kwargs = (
{kw.arg: 0 for kw in node.keywords}
if node.keywords is not None
else {}
)
i18n.t(val, **kwargs) # trigger lazy loading of translations
if not i18n.translations.has(val):
self.add_message(
"invalid-translation-key", line=node.args[0].lineno, node=node
)
else:
self.add_message(
"nonfinal-translation-key", line=node.args[0].lineno, node=node
)
def register(linter):
translations_path = os.path.join(
os.path.dirname(__file__), "..", "resources", "translations"
)
i18n.set("file_format", "json")
i18n.load_path.append(translations_path)
i18n.set("fallback", "en")
linter.register_checker(I18nChecker(linter))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment