import json import os import re from typing import Any import click from fansifter_common.adapters.poeditor import POEditorClient from fansifter_common.translation.services import ExportTranslationService DEFAULT_DESTINATION = "locale/" @click.group() def cli() -> None: pass @click.command(name="export") @click.option("-t", "--token", required=True, help="API Token") @click.option("-p", "--project-id", required=True, help="Project ID", type=int) @click.option( "-d", "--destination", default=DEFAULT_DESTINATION, help="Destination path for export", type=click.Path(), ) def export_translations(token: str, project_id: int, destination: str) -> None: """ CLI tool for exporting POEditor translations to json file. """ substitutions_pattern = r"\{([^}]*)\}" def get_substitutions_for_lang(terms: dict[str, str]) -> dict[str, set[Any]]: result = {} for term_name, value in terms.items(): result[term_name] = set(re.findall(substitutions_pattern, value)) return result with POEditorClient(api_token=token) as poeditor_client: service = ExportTranslationService(poeditor_client) translations: dict[str, dict[str, str]] = service.get_project_translations( project_id ) missing_values_langs = [] missing_substitutions_terms = [] default_lang_substitutions = get_substitutions_for_lang( translations[service.default_language_code[0]] ) for lang, terms in translations.items(): lang_substitutions = get_substitutions_for_lang(translations[lang]) for term, value in terms.items(): if not value: missing_values_langs.append(lang) break if lang_substitutions[term] != default_lang_substitutions[term]: missing_substitutions_terms.append(f"{lang}:{term}") if missing_values_langs: raise ValueError( f"Translations missing values for languages: {missing_values_langs}" ) if missing_substitutions_terms: raise ValueError( f"Translations missing values for substitutions: {missing_substitutions_terms}" ) with open(os.path.join(destination, "translations.json"), "w") as file: json.dump(translations, file, ensure_ascii=False, indent=4) cli.add_command(export_translations) if __name__ == "__main__": cli()