From f101d9cddb20ee1c9646ca6cd905fd7a2d39e088 Mon Sep 17 00:00:00 2001 From: Tobias Efinger Date: Fri, 9 Oct 2020 11:51:05 +0200 Subject: [PATCH] Update translate develop to substitute references (#41445) --- script/translations/develop.py | 61 ++++++++++++++++++++++++++++++++++ 1 file changed, 61 insertions(+) diff --git a/script/translations/develop.py b/script/translations/develop.py index 8886debd555..f59b9b9c7cb 100644 --- a/script/translations/develop.py +++ b/script/translations/develop.py @@ -2,6 +2,7 @@ import argparse import json from pathlib import Path +import re from shutil import rmtree import sys @@ -29,6 +30,59 @@ def get_arguments() -> argparse.Namespace: return parser.parse_args() +def flatten_translations(translations): + """Flatten all translations.""" + stack = [iter(translations.items())] + key_stack = [] + flattened_translations = {} + while stack: + for k, v in stack[-1]: + key_stack.append(k) + if isinstance(v, dict): + stack.append(iter(v.items())) + break + elif isinstance(v, str): + common_key = "::".join(key_stack) + flattened_translations[common_key] = v + key_stack.pop() + else: + stack.pop() + if len(key_stack) > 0: + key_stack.pop() + + return flattened_translations + + +def substitute_translation_references(integration_strings, flattened_translations): + """Recursively processes all translation strings for the integration.""" + result = {} + for key, value in integration_strings.items(): + if isinstance(value, dict): + sub_dict = substitute_translation_references(value, flattened_translations) + result[key] = sub_dict + elif isinstance(value, str): + result[key] = substitute_reference(value, flattened_translations) + + return result + + +def substitute_reference(value, flattened_translations): + """Substitute localization key references in a translation string.""" + matches = re.findall(r"\[\%key:((?:[\w]+|[:]{2})*)\%\]", value) + if not matches: + return value + + new = value + for key in matches: + if key in flattened_translations: + new = new.replace(f"[%key:{key}%]", flattened_translations[key]) + else: + print(f"Invalid substitution key '{key}' found in string '{value}'") + sys.exit(1) + + return new + + def run(): """Run the script.""" args = get_arguments() @@ -51,6 +105,13 @@ def run(): print("Integration has no strings.json") sys.exit(1) + flattened_translations = flatten_translations(translations) + integration_strings = translations["component"][integration] + + translations["component"][integration] = substitute_translation_references( + integration_strings, flattened_translations + ) + if download.DOWNLOAD_DIR.is_dir(): rmtree(str(download.DOWNLOAD_DIR))