From baf23b9bc3268a2928b18911e383f95cceef24dd Mon Sep 17 00:00:00 2001 From: Franck Trouillez Date: Thu, 20 Jun 2024 20:24:28 +0200 Subject: [PATCH] Automatically convert different schemas into the source one --- src/files/base.py | 29 ++++++++++++++++++++++++++++- src/main.py | 2 ++ 2 files changed, 30 insertions(+), 1 deletion(-) diff --git a/src/files/base.py b/src/files/base.py index bde84ff..6279543 100644 --- a/src/files/base.py +++ b/src/files/base.py @@ -64,14 +64,22 @@ def find_missing_keys(source_dict: dict, target_dict: dict, current_key_path: li :return: A list of keys that are missing in the target dictionary. """ missing_keys = [] + if type(target_dict) != dict: + for nested_key in BaseFile.__get_nested_keys(source_dict): + missing_keys.append(current_key_path + nested_key) + return missing_keys for key, value in source_dict.items(): if value is None: continue + if type(value) == dict: - missing_keys.extend(BaseFile.find_missing_keys(value, target_dict.get(key, {}), current_key_path + [key])) + missing_keys.extend(BaseFile.find_missing_keys(value, target_dict.get(key, {}), current_key_path + [key])) else: if key not in target_dict: missing_keys.append(current_key_path + [key]) + else: + if type(value) != type(target_dict[key]): + missing_keys.append(current_key_path + [key]) return missing_keys # --- Protected methods --- @@ -91,3 +99,22 @@ def _ensure_directories_exist(file_path: str) -> None: if directories: directories = "/".join(directories) os.makedirs(directories, exist_ok=True) + + @staticmethod + def __get_nested_keys(object: dict) -> list[str]: + """ + Get the nested keys for a dictionary. + + :param object: The dictionary to get the nested keys for. + :return: A list of nested keys. + """ + keys = [] + if type(object) != dict: + return keys + for key, value in object.items(): + if type(value) == dict: + for nested_key in BaseFile.__get_nested_keys(value): + keys.append([key, *nested_key]) + else: + keys.append([key]) + return keys diff --git a/src/main.py b/src/main.py index 5dca30f..ceab991 100644 --- a/src/main.py +++ b/src/main.py @@ -49,6 +49,8 @@ ) target_translation_data = target_data for key in keys[:-1]: + if type(target_translation_data.get(key)) != dict: + target_translation_data[key] = {} target_translation_data = target_translation_data.setdefault(key, {}) target_translation_data[keys[-1]] = target_translation print(f"[{source_file} - {target_language}] Writing translations to '{target_file}'")