#!/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")
FLAGS = re.MULTILINE
args = list("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():
        # 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=FLAGS):
            if not field in entry.msgstr:
                print_error("Python string formatting mismatch", entry)
                raise SystemExit("FATAL ERROR")
        # Check that QML string formatting fields exists as-is
        # in the translation (order can vary, but not the field).
        for field in re.findall(r"%\d+", entry.msgid, flags=FLAGS):
            if not field in entry.msgstr:
                print_error("QML string formatting mismatch", entry)
                raise SystemExit("FATAL ERROR")
