| 1 |
#!/usr/bin/python3 |
| 2 |
|
| 3 |
import re |
| 4 |
import os |
| 5 |
import yaml |
| 6 |
|
| 7 |
INFILE = 'messages.in.py' |
| 8 |
OUTFILE = '../crazy_complete/messages.py' |
| 9 |
TRANSLATIONS_INFILE = 'translations.yaml' |
| 10 |
|
| 11 |
os.chdir(os.path.dirname(os.path.abspath(__file__))) |
| 12 |
|
| 13 |
|
| 14 |
def get_fstring(translation, params): |
| 15 |
if not params: |
| 16 |
return f"'{translation}'" |
| 17 |
|
| 18 |
return f"f'{translation}'" |
| 19 |
|
| 20 |
|
| 21 |
def make_function(args): |
| 22 |
msgid = args.pop('msgid') |
| 23 |
params = ', '.join(args.pop('parameters')) |
| 24 |
en = args.pop('en') |
| 25 |
|
| 26 |
r = f'def {msgid}({params}):\n' |
| 27 |
for lang, translation in args.items(): |
| 28 |
r += f" if LANG == '{lang}':\n" |
| 29 |
r += f" return {get_fstring(translation, params)}\n" |
| 30 |
r += f" return {get_fstring(en, params)}" |
| 31 |
return r |
| 32 |
|
| 33 |
|
| 34 |
def make_functions(): |
| 35 |
with open(TRANSLATIONS_INFILE, 'r', encoding='UTF-8') as fh: |
| 36 |
all_definitions = list(yaml.safe_load_all(fh)) |
| 37 |
|
| 38 |
by_lang = {} |
| 39 |
|
| 40 |
for definition in all_definitions: |
| 41 |
by_lang[definition.pop('lang')] = definition |
| 42 |
|
| 43 |
specification = by_lang.pop('spec') |
| 44 |
|
| 45 |
for lang, defintions in by_lang.items(): |
| 46 |
for key, translation in defintions.items(): |
| 47 |
if not key in specification: |
| 48 |
raise Exception(f'{lang}: Invalid key: {key}') |
| 49 |
|
| 50 |
functions = [] |
| 51 |
|
| 52 |
for msgid in sorted(specification.keys()): |
| 53 |
args = {'msgid': msgid, 'parameters': specification[msgid]} |
| 54 |
|
| 55 |
for lang, defintion in by_lang.items(): |
| 56 |
try: |
| 57 |
args[lang] = defintion[msgid] |
| 58 |
except KeyError: |
| 59 |
raise Exception(f'{lang}: Missing translation: {msgid}') |
| 60 |
|
| 61 |
functions.append(make_function(args)) |
| 62 |
|
| 63 |
return '\n\n\n'.join(functions) |
| 64 |
|
| 65 |
|
| 66 |
with open(INFILE, 'r', encoding='UTF-8') as fh: |
| 67 |
content = fh.read() |
| 68 |
|
| 69 |
with open(OUTFILE, 'w', encoding='UTF-8') as fh: |
| 70 |
fh.write(content) |
| 71 |
fh.write('\n') |
| 72 |
fh.write(make_functions()) |
| 73 |
fh.write('\n') |