Update translate develop to substitute references (#41445)

This commit is contained in:
Tobias Efinger 2020-10-09 11:51:05 +02:00 committed by GitHub
parent 58ede21f39
commit f101d9cddb
No known key found for this signature in database
GPG key ID: 4AEE18F83AFDEB23

View file

@ -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))