#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Check translation files for common errors.
Usage: check-translations [XX[_YY[@ZZ]]...]
"""
import glob, polib, re, sys
def print_error(title, entry):
    print("\n{}:".format(title), entry, sep="\n")
args = ["po/{}.po".format(x) for x in sys.argv[1:]]
for name in args or sorted(glob.glob("po/*.po")):
    po = polib.pofile(name)
    print("{}: {}% translated".format(name, po.percent_translated()))
    for entry in po.translated_entries():
        translations = (
            list(entry.msgstr_plural.values())
            if entry.msgid_plural else [entry.msgstr])
        for translation in translations:
            # Check that Python string formatting fields exists as-is
            # in the translation (order can vary, but not the field).
            for field in re.findall(r"\{.*?\}", entry.msgid, flags=re.M):
                if not field in translation:
                    print_error("Python string formatting mismatch", entry)
                    raise SystemExit("FATAL ERROR")
            # Check that the translation of a label includes
            # a keyboard accelerator defined by an underscore.
            if "_" in entry.msgid:
                if not "_" in translation:
                    print_error("Missing accelerator", entry)
            # Check that the translation of a label includes
            # a terminating colon.
            if entry.msgid.endswith(":"):
                if not translation.endswith(":"):
                    print_error("Missing terminating colon", entry)
            # Check that the translation of a menu item includes
            # an ellipsis defined by the Unicode character.
            if "…" in entry.msgid:
                if not "…" in translation:
                    print_error("Missing ellipsis", entry)
