From 61f49b170d062616ec3e0ac729c056327dad71c5 Mon Sep 17 00:00:00 2001 From: diffwireauto <330573775+diffwireauto@users.noreply.github.com> Date: Mon, 30 Nov 2026 18:23:19 -0500 Subject: [PATCH] build(#1323): check every translation in CI before the batches land The translation batches of #1322 are about to put roughly 470 strings into 17 languages by machine. Nothing stopped a translation that drops a placeholder, breaks a plural, or just stays English. tools/l10n/check_arb.py compares each app_.arb with app_en.arb and runs in the required analyze job. It fails on a dropped, renamed or added placeholder; a plural or select that is unbalanced, has no other case, repeats a case, uses an unknown category, or counts a placeholder English does not declare as a number; an empty translation; a key or @metadata English no longer has; a duplicate key; a wrong @@locale; and a translation identical to English unless allowlisted or still pending. Pending entries must leave the list once translated. Missing keys are reported until fail_on_missing is set at #1325. On its first run it found 13 locales whose contact search hint dropped the count and the "unread" marker, now fixed, and 17 locale files carrying keys English had dropped, now removed. The regenerated Dart changes only those 13 hints. Co-Authored-By: Claude Opus 5.5 --- .github/workflows/flutter_dart.yml | 8 + lib/l10n/app_bg.arb | 4 +- lib/l10n/app_de.arb | 4 +- lib/l10n/app_es.arb | 4 +- lib/l10n/app_fr.arb | 4 +- lib/l10n/app_hu.arb | 2 - lib/l10n/app_it.arb | 4 +- lib/l10n/app_ja.arb | 2 - lib/l10n/app_ko.arb | 2 - lib/l10n/app_localizations_bg.dart | 2 +- lib/l10n/app_localizations_de.dart | 2 +- lib/l10n/app_localizations_es.dart | 2 +- lib/l10n/app_localizations_fr.dart | 2 +- lib/l10n/app_localizations_it.dart | 2 +- lib/l10n/app_localizations_nl.dart | 2 +- lib/l10n/app_localizations_pt.dart | 2 +- lib/l10n/app_localizations_ru.dart | 2 +- lib/l10n/app_localizations_sk.dart | 2 +- lib/l10n/app_localizations_sl.dart | 2 +- lib/l10n/app_localizations_sv.dart | 2 +- lib/l10n/app_localizations_uk.dart | 2 +- lib/l10n/app_localizations_zh.dart | 2 +- lib/l10n/app_nl.arb | 4 +- lib/l10n/app_pl.arb | 2 - lib/l10n/app_pt.arb | 4 +- lib/l10n/app_ru.arb | 7 +- lib/l10n/app_sk.arb | 4 +- lib/l10n/app_sl.arb | 4 +- lib/l10n/app_sv.arb | 4 +- lib/l10n/app_uk.arb | 5 +- lib/l10n/app_zh.arb | 9 +- tools/l10n/check_arb.py | 342 +++++++++++++++++ tools/l10n/l10n_check.json | 589 +++++++++++++++++++++++++++++ tools/l10n/test_check_arb.py | 262 +++++++++++++ 34 files changed, 1227 insertions(+), 69 deletions(-) create mode 100644 tools/l10n/check_arb.py create mode 100644 tools/l10n/l10n_check.json create mode 100644 tools/l10n/test_check_arb.py diff --git a/.github/workflows/flutter_dart.yml b/.github/workflows/flutter_dart.yml index c0f5e490..a053c19e 100644 --- a/.github/workflows/flutter_dart.yml +++ b/.github/workflows/flutter_dart.yml @@ -77,6 +77,14 @@ jobs: if: needs.classify.outputs.docs_only != 'true' run: python3 .github/scripts/check_no_emdash.py + - name: Translation check tests (#1323) + if: needs.classify.outputs.docs_only != 'true' + run: python3 -m unittest discover -s tools/l10n -v + + - name: Translation check (#1323) + if: needs.classify.outputs.docs_only != 'true' + run: python3 tools/l10n/check_arb.py + - name: Play upload tool tests (#1084) if: needs.classify.outputs.docs_only != 'true' run: python3 -m unittest discover -s tools/play -v diff --git a/lib/l10n/app_bg.arb b/lib/l10n/app_bg.arb index a9f22724..dcbdc8b9 100644 --- a/lib/l10n/app_bg.arb +++ b/lib/l10n/app_bg.arb @@ -120,8 +120,6 @@ "settings_rebootDeviceSubtitle": "Рестартирайте устройството MeshCore", "settings_rebootDeviceConfirm": "Сигурни ли сте, че искате да рестартирате устройството? Ще бъдете откъснати.", "settings_debug": "Отстрани", - "settings_bleDebugLog": "Лог за отстраняване на грешки на BLE", - "settings_bleDebugLogSubtitle": "Команди, отговори и сурови данни BLE", "settings_appDebugLog": "Лог на отстраняване на грешки на приложението", "settings_appDebugLogSubtitle": "Съобщения за отстраняване на грешки на приложението", "settings_about": "За нас", @@ -263,7 +261,7 @@ "contacts_title": "Контакти", "contacts_noContacts": "Няма контакти към момента.", "contacts_contactsWillAppear": "Контактите ще се появят, когато устройствата рекламират.", - "contacts_searchContacts": "Търсене на контакти...", + "contacts_searchContacts": "Търсене на {number}{str} контакти...", "contacts_noUnreadContacts": "Няма непрочетени контакти", "contacts_noContactsFound": "Няма намерени контакти или групи.", "contacts_deleteContact": "Изтрий Контакт", diff --git a/lib/l10n/app_de.arb b/lib/l10n/app_de.arb index c82c59ed..c882b19d 100644 --- a/lib/l10n/app_de.arb +++ b/lib/l10n/app_de.arb @@ -120,8 +120,6 @@ "settings_rebootDeviceSubtitle": "MeshCore-Gerät neu starten", "settings_rebootDeviceConfirm": "Sind Sie sicher, dass Sie das Gerät neu starten möchten? Sie werden getrennt.", "settings_debug": "Fehlerbehebung", - "settings_bleDebugLog": "BLE-Debug-Protokoll", - "settings_bleDebugLogSubtitle": "BLE-Befehle, Antworten und Rohdaten", "settings_appDebugLog": "App-Debug-Protokoll", "settings_appDebugLogSubtitle": "Anwendung Debug-Nachrichten", "settings_about": "Über", @@ -263,7 +261,7 @@ "contacts_title": "Kontakte", "contacts_noContacts": "Noch keine Kontakte vorhanden.", "contacts_contactsWillAppear": "Kontakte werden angezeigt, wenn Geräte eine Ankündigung machen.", - "contacts_searchContacts": "Suche Kontakte...", + "contacts_searchContacts": "Suche {number}{str} Kontakte...", "contacts_noUnreadContacts": "Keine ungesehene Kontakte", "contacts_noContactsFound": "Keine Kontakte oder Gruppen gefunden.", "contacts_deleteContact": "Lösche den Kontakt", diff --git a/lib/l10n/app_es.arb b/lib/l10n/app_es.arb index 7e70c724..f7b27167 100644 --- a/lib/l10n/app_es.arb +++ b/lib/l10n/app_es.arb @@ -120,8 +120,6 @@ "settings_rebootDeviceSubtitle": "Reiniciar el dispositivo MeshCore", "settings_rebootDeviceConfirm": "¿Está seguro de que desea reiniciar el dispositivo? Se desconectará.", "settings_debug": "Depurar", - "settings_bleDebugLog": "Registro de Depuración BLE", - "settings_bleDebugLogSubtitle": "Comandos, respuestas y datos brutos de BLE", "settings_appDebugLog": "Registro de Depuración de la App", "settings_appDebugLogSubtitle": "Mensajes de depuración de la aplicación", "settings_about": "Acerca de", @@ -263,7 +261,7 @@ "contacts_title": "Contactos", "contacts_noContacts": "Aún no hay contactos.", "contacts_contactsWillAppear": "Los contactos aparecerán cuando los dispositivos anuncien.", - "contacts_searchContacts": "Buscar contactos...", + "contacts_searchContacts": "Buscar {number}{str} contactos...", "contacts_noUnreadContacts": "No contactos sin leer", "contacts_noContactsFound": "No se encontraron contactos ni grupos.", "contacts_deleteContact": "Eliminar Contacto", diff --git a/lib/l10n/app_fr.arb b/lib/l10n/app_fr.arb index e9589721..b64bfe3c 100644 --- a/lib/l10n/app_fr.arb +++ b/lib/l10n/app_fr.arb @@ -120,8 +120,6 @@ "settings_rebootDeviceSubtitle": "Redémarrer l'appareil MeshCore", "settings_rebootDeviceConfirm": "Êtes-vous sûr de vouloir redémarrer l'appareil ? Vous serez déconnecté.", "settings_debug": "Déboguer", - "settings_bleDebugLog": "Journal de débogage BLE", - "settings_bleDebugLogSubtitle": "Commandes BLE, réponses et données brutes", "settings_appDebugLog": "Journal de débogage de l'application", "settings_appDebugLogSubtitle": "Messages de débogage de l'application", "settings_about": "À propos", @@ -263,7 +261,7 @@ "contacts_title": "Coordonnées", "contacts_noContacts": "Aucun contact trouvé.", "contacts_contactsWillAppear": "Les contacts apparaîtront lorsque les appareils font leur annonce.", - "contacts_searchContacts": "Rechercher des contacts...", + "contacts_searchContacts": "Rechercher {number}{str} contacts...", "contacts_noUnreadContacts": "Aucun contact non lu", "contacts_noContactsFound": "Aucun contact ou groupe trouvé.", "contacts_deleteContact": "Supprimer le contact", diff --git a/lib/l10n/app_hu.arb b/lib/l10n/app_hu.arb index 2f3a9a37..2879766b 100644 --- a/lib/l10n/app_hu.arb +++ b/lib/l10n/app_hu.arb @@ -183,8 +183,6 @@ "settings_rebootDeviceSubtitle": "Indítsa újra a MeshCore eszközt.", "settings_rebootDeviceConfirm": "Biztosan szeretné újraindítani a készüléket? Ebben az esetben a kapcsolat megszűnik.", "settings_debug": "Hibakeresés", - "settings_bleDebugLog": "BLE hibaelhárítási napló", - "settings_bleDebugLogSubtitle": "BLE parancsok, válaszok és alapvető adatok", "settings_appDebugLog": "App-debug log", "settings_appDebugLogSubtitle": "Programozási hibajelzések", "settings_about": "Ról", diff --git a/lib/l10n/app_it.arb b/lib/l10n/app_it.arb index bce1a7dc..1bdc06df 100644 --- a/lib/l10n/app_it.arb +++ b/lib/l10n/app_it.arb @@ -120,8 +120,6 @@ "settings_rebootDeviceSubtitle": "Riavviare il dispositivo MeshCore", "settings_rebootDeviceConfirm": "Sei sicuro di voler riavviare il dispositivo? Sarai disconnesso.", "settings_debug": "Risoluzione dei problemi", - "settings_bleDebugLog": "Log di Debug BLE", - "settings_bleDebugLogSubtitle": "Comandi, risposte e dati grezzi BLE", "settings_appDebugLog": "Log di Debug dell'App", "settings_appDebugLogSubtitle": "Messaggi di debug dell'applicazione", "settings_about": "Informazioni", @@ -263,7 +261,7 @@ "contacts_title": "Contatti", "contacts_noContacts": "Nessun contatto ancora", "contacts_contactsWillAppear": "I contatti appariranno quando i dispositivi pubblicizzano.", - "contacts_searchContacts": "Cerca contatti...", + "contacts_searchContacts": "Cerca {number}{str} contatti...", "contacts_noUnreadContacts": "Nessun contatto non letto", "contacts_noContactsFound": "Nessun contatto o gruppo trovato.", "contacts_deleteContact": "Elimina Contatto", diff --git a/lib/l10n/app_ja.arb b/lib/l10n/app_ja.arb index 3aa8ac8a..0dd22090 100644 --- a/lib/l10n/app_ja.arb +++ b/lib/l10n/app_ja.arb @@ -183,8 +183,6 @@ "settings_rebootDeviceSubtitle": "MeshCore デバイスを再起動する", "settings_rebootDeviceConfirm": "本当にデバイスを再起動したいですか? その場合、接続が切断されます。", "settings_debug": "デバッグ", - "settings_bleDebugLog": "BLE デバッグログ", - "settings_bleDebugLogSubtitle": "BLEコマンド、応答、および生のデータ", "settings_appDebugLog": "アプリケーションのデバッグログ", "settings_appDebugLogSubtitle": "アプリケーションのデバッグメッセージ", "settings_about": "概要", diff --git a/lib/l10n/app_ko.arb b/lib/l10n/app_ko.arb index c04c3276..32c404a5 100644 --- a/lib/l10n/app_ko.arb +++ b/lib/l10n/app_ko.arb @@ -183,8 +183,6 @@ "settings_rebootDeviceSubtitle": "MeshCore 장치를 재부팅하세요.", "settings_rebootDeviceConfirm": "정말로 장치를 재부팅하시겠습니까? 이 경우 연결이 끊어집니다.", "settings_debug": "디버깅", - "settings_bleDebugLog": "BLE 디버그 로그", - "settings_bleDebugLogSubtitle": "BLE 명령어, 응답 및 원시 데이터", "settings_appDebugLog": "앱 디버깅 로그", "settings_appDebugLogSubtitle": "애플리케이션 디버깅 메시지", "settings_about": "소개", diff --git a/lib/l10n/app_localizations_bg.dart b/lib/l10n/app_localizations_bg.dart index a111d7f5..9e33ae65 100644 --- a/lib/l10n/app_localizations_bg.dart +++ b/lib/l10n/app_localizations_bg.dart @@ -1520,7 +1520,7 @@ class AppLocalizationsBg extends AppLocalizations { @override String contacts_searchContacts(int number, String str) { - return 'Търсене на контакти...'; + return 'Търсене на $number$str контакти...'; } @override diff --git a/lib/l10n/app_localizations_de.dart b/lib/l10n/app_localizations_de.dart index f3f5de92..c9e69c1a 100644 --- a/lib/l10n/app_localizations_de.dart +++ b/lib/l10n/app_localizations_de.dart @@ -1514,7 +1514,7 @@ class AppLocalizationsDe extends AppLocalizations { @override String contacts_searchContacts(int number, String str) { - return 'Suche Kontakte...'; + return 'Suche $number$str Kontakte...'; } @override diff --git a/lib/l10n/app_localizations_es.dart b/lib/l10n/app_localizations_es.dart index 0b113f6f..4d6a6b3d 100644 --- a/lib/l10n/app_localizations_es.dart +++ b/lib/l10n/app_localizations_es.dart @@ -1513,7 +1513,7 @@ class AppLocalizationsEs extends AppLocalizations { @override String contacts_searchContacts(int number, String str) { - return 'Buscar contactos...'; + return 'Buscar $number$str contactos...'; } @override diff --git a/lib/l10n/app_localizations_fr.dart b/lib/l10n/app_localizations_fr.dart index 90ec1839..728607a7 100644 --- a/lib/l10n/app_localizations_fr.dart +++ b/lib/l10n/app_localizations_fr.dart @@ -1520,7 +1520,7 @@ class AppLocalizationsFr extends AppLocalizations { @override String contacts_searchContacts(int number, String str) { - return 'Rechercher des contacts...'; + return 'Rechercher $number$str contacts...'; } @override diff --git a/lib/l10n/app_localizations_it.dart b/lib/l10n/app_localizations_it.dart index 839c4ac8..3fea12f6 100644 --- a/lib/l10n/app_localizations_it.dart +++ b/lib/l10n/app_localizations_it.dart @@ -1516,7 +1516,7 @@ class AppLocalizationsIt extends AppLocalizations { @override String contacts_searchContacts(int number, String str) { - return 'Cerca contatti...'; + return 'Cerca $number$str contatti...'; } @override diff --git a/lib/l10n/app_localizations_nl.dart b/lib/l10n/app_localizations_nl.dart index 60d7de26..d80dc6fa 100644 --- a/lib/l10n/app_localizations_nl.dart +++ b/lib/l10n/app_localizations_nl.dart @@ -1509,7 +1509,7 @@ class AppLocalizationsNl extends AppLocalizations { @override String contacts_searchContacts(int number, String str) { - return 'Zoek contacten...'; + return 'Zoek $number$str contacten...'; } @override diff --git a/lib/l10n/app_localizations_pt.dart b/lib/l10n/app_localizations_pt.dart index 202624f1..d4f40bd5 100644 --- a/lib/l10n/app_localizations_pt.dart +++ b/lib/l10n/app_localizations_pt.dart @@ -1515,7 +1515,7 @@ class AppLocalizationsPt extends AppLocalizations { @override String contacts_searchContacts(int number, String str) { - return 'Pesquisar contatos...'; + return 'Pesquisar $number$str contatos...'; } @override diff --git a/lib/l10n/app_localizations_ru.dart b/lib/l10n/app_localizations_ru.dart index a992595c..471fadcf 100644 --- a/lib/l10n/app_localizations_ru.dart +++ b/lib/l10n/app_localizations_ru.dart @@ -1517,7 +1517,7 @@ class AppLocalizationsRu extends AppLocalizations { @override String contacts_searchContacts(int number, String str) { - return 'Поиск контактов...'; + return 'Поиск $number$str контактов...'; } @override diff --git a/lib/l10n/app_localizations_sk.dart b/lib/l10n/app_localizations_sk.dart index a8c1ebfc..3a4e27e6 100644 --- a/lib/l10n/app_localizations_sk.dart +++ b/lib/l10n/app_localizations_sk.dart @@ -1505,7 +1505,7 @@ class AppLocalizationsSk extends AppLocalizations { @override String contacts_searchContacts(int number, String str) { - return 'Vyhľadávajte kontakty...'; + return 'Hľadať $number$str kontaktov...'; } @override diff --git a/lib/l10n/app_localizations_sl.dart b/lib/l10n/app_localizations_sl.dart index 2b3b3f48..1c674546 100644 --- a/lib/l10n/app_localizations_sl.dart +++ b/lib/l10n/app_localizations_sl.dart @@ -1505,7 +1505,7 @@ class AppLocalizationsSl extends AppLocalizations { @override String contacts_searchContacts(int number, String str) { - return 'Iskanje stikov...'; + return 'Išči $number$str stikov...'; } @override diff --git a/lib/l10n/app_localizations_sv.dart b/lib/l10n/app_localizations_sv.dart index 7740d3f5..65fa2362 100644 --- a/lib/l10n/app_localizations_sv.dart +++ b/lib/l10n/app_localizations_sv.dart @@ -1499,7 +1499,7 @@ class AppLocalizationsSv extends AppLocalizations { @override String contacts_searchContacts(int number, String str) { - return 'Sök kontakter...'; + return 'Sök $number$str kontakter...'; } @override diff --git a/lib/l10n/app_localizations_uk.dart b/lib/l10n/app_localizations_uk.dart index 3b31ece6..1a79563b 100644 --- a/lib/l10n/app_localizations_uk.dart +++ b/lib/l10n/app_localizations_uk.dart @@ -1512,7 +1512,7 @@ class AppLocalizationsUk extends AppLocalizations { @override String contacts_searchContacts(int number, String str) { - return 'Пошук контактів...'; + return 'Пошук $number$str контактів...'; } @override diff --git a/lib/l10n/app_localizations_zh.dart b/lib/l10n/app_localizations_zh.dart index f1f40342..48d1c20f 100644 --- a/lib/l10n/app_localizations_zh.dart +++ b/lib/l10n/app_localizations_zh.dart @@ -1449,7 +1449,7 @@ class AppLocalizationsZh extends AppLocalizations { @override String contacts_searchContacts(int number, String str) { - return '搜索联系人...'; + return '搜索 $number$str 个联系人...'; } @override diff --git a/lib/l10n/app_nl.arb b/lib/l10n/app_nl.arb index c207124b..4c99410f 100644 --- a/lib/l10n/app_nl.arb +++ b/lib/l10n/app_nl.arb @@ -120,8 +120,6 @@ "settings_rebootDeviceSubtitle": "Herstart het MeshCore-apparaat", "settings_rebootDeviceConfirm": "Ben je er zeker van dat je het apparaat opnieuw wilt opstarten? Je wordt losgekoppeld.", "settings_debug": "Foutopsporing", - "settings_bleDebugLog": "BLE Debug Log", - "settings_bleDebugLogSubtitle": "BLE commando's, antwoorden en ruwe data", "settings_appDebugLog": "Debuglog van de app", "settings_appDebugLogSubtitle": "Toepassingsdebugberichten", "settings_about": "Over", @@ -263,7 +261,7 @@ "contacts_title": "Contacten", "contacts_noContacts": "Nog geen contacten.", "contacts_contactsWillAppear": "Contacten verschijnen wanneer apparaten zich aanbieden.", - "contacts_searchContacts": "Zoek contacten...", + "contacts_searchContacts": "Zoek {number}{str} contacten...", "contacts_noUnreadContacts": "Geen ongelezen contacten", "contacts_noContactsFound": "Geen contacten of groepen gevonden.", "contacts_deleteContact": "Verwijder Contact", diff --git a/lib/l10n/app_pl.arb b/lib/l10n/app_pl.arb index 0ca1c6a5..c8c55376 100644 --- a/lib/l10n/app_pl.arb +++ b/lib/l10n/app_pl.arb @@ -120,8 +120,6 @@ "settings_rebootDeviceSubtitle": "Zrestartuj urządzenie MeshCore", "settings_rebootDeviceConfirm": "Czy na pewno chcesz zrestartować urządzenie? Będziesz odłączony.", "settings_debug": "Naprawianie błędów", - "settings_bleDebugLog": "Dziennik debugowania BLE", - "settings_bleDebugLogSubtitle": "Polecenia BLE, odpowiedzi i surowe dane", "settings_appDebugLog": "Dziennik debugowania aplikacji", "settings_appDebugLogSubtitle": "Komunikaty debugowania aplikacji", "settings_about": "O aplikacji", diff --git a/lib/l10n/app_pt.arb b/lib/l10n/app_pt.arb index fa491e53..aa82d85b 100644 --- a/lib/l10n/app_pt.arb +++ b/lib/l10n/app_pt.arb @@ -120,8 +120,6 @@ "settings_rebootDeviceSubtitle": "Reiniciar o dispositivo MeshCore", "settings_rebootDeviceConfirm": "Tem certeza de que deseja reiniciar o dispositivo? Você será desconectado.", "settings_debug": "Depurar", - "settings_bleDebugLog": "Log de Depuração BLE", - "settings_bleDebugLogSubtitle": "Comandos, respostas e dados brutos do BLE", "settings_appDebugLog": "Log de Depuração do Aplicativo", "settings_appDebugLogSubtitle": "Mensagens de depuração do aplicativo", "settings_about": "Sobre", @@ -263,7 +261,7 @@ "contacts_title": "Contactos", "contacts_noContacts": "Ainda não existem contatos.", "contacts_contactsWillAppear": "Os contatos serão exibidos quando os dispositivos anunciarem.", - "contacts_searchContacts": "Pesquisar contatos...", + "contacts_searchContacts": "Pesquisar {number}{str} contatos...", "contacts_noUnreadContacts": "Sem contatos não lidos.", "contacts_noContactsFound": "Não foram encontrados contatos ou grupos.", "contacts_deleteContact": "Excluir Contato", diff --git a/lib/l10n/app_ru.arb b/lib/l10n/app_ru.arb index 047bbcbd..54dcce6d 100644 --- a/lib/l10n/app_ru.arb +++ b/lib/l10n/app_ru.arb @@ -97,8 +97,6 @@ "settings_rebootDeviceSubtitle": "Перезапустить устройство MeshCore", "settings_rebootDeviceConfirm": "Вы уверены, что хотите перезагрузить устройство? Вы будете отключены.", "settings_debug": "Отладка", - "settings_bleDebugLog": "Журнал отладки BLE", - "settings_bleDebugLogSubtitle": "Команды BLE, ответы и сырые данные", "settings_appDebugLog": "Журнал отладки приложения", "settings_appDebugLogSubtitle": "Сообщения отладки приложения", "settings_about": "О программе", @@ -203,7 +201,7 @@ "contacts_title": "Контакты", "contacts_noContacts": "Контактов пока нет", "contacts_contactsWillAppear": "Контакты появятся, когда устройства начнут рассылать оповещения", - "contacts_searchContacts": "Поиск контактов...", + "contacts_searchContacts": "Поиск {number}{str} контактов...", "contacts_noUnreadContacts": "Нет непрочитанных контактов", "contacts_noContactsFound": "Контакты или группы не найдены", "contacts_deleteContact": "Удалить контакт", @@ -583,11 +581,9 @@ "repeater_refreshBasicSettings": "Обновить основные настройки", "repeater_refreshRadioSettings": "Обновить настройки радио", "repeater_refreshTxPower": "Обновить мощность передачи", - "repeater_refreshLocationSettings": "Обновить настройки местоположения", "repeater_refreshPacketForwarding": "Обновить пересылку пакетов", "repeater_refreshGuestAccess": "Обновить гостевой доступ", "repeater_refreshPrivacyMode": "Обновить режим конфиденциальности", - "repeater_refreshAdvertisementSettings": "Обновить настройки анонсирований", "repeater_refreshed": "{label} обновлён", "repeater_errorRefreshing": "Ошибка обновления {label}", "repeater_cliTitle": "CLI репитера", @@ -731,7 +727,6 @@ "neighbors_repeatersNeighbors": "Соседи репитеров", "neighbors_noData": "Данные о соседях недоступны.", "neighbors_unknownContact": "Неизвестный {pubkey}", - "neighbors_heardA ago": "Слышали: {time} назад", "channelPath_title": "Путь пакета", "channelPath_viewMap": "Посмотреть на карте", "channelPath_otherObservedPaths": "Другие наблюдаемые пути", diff --git a/lib/l10n/app_sk.arb b/lib/l10n/app_sk.arb index 0efdbb15..33263a3e 100644 --- a/lib/l10n/app_sk.arb +++ b/lib/l10n/app_sk.arb @@ -120,8 +120,6 @@ "settings_rebootDeviceSubtitle": "Restartujte zariadenie MeshCore.", "settings_rebootDeviceConfirm": "Ste si istý, že chcete zariadenie reštartovať? Budete odpojení.", "settings_debug": "Ladenie", - "settings_bleDebugLog": "Log BLE Debug", - "settings_bleDebugLogSubtitle": "Príkazy BLE, odpovede a surové dáta", "settings_appDebugLog": "Záznam ladenia aplikácie", "settings_appDebugLogSubtitle": "Správy z ladenia aplikácie", "settings_about": "O nás", @@ -263,7 +261,7 @@ "contacts_title": "Kontakty", "contacts_noContacts": "Zatiaľ žiadne kontakty.", "contacts_contactsWillAppear": "Kontakty sa zobrazia, keď zariadenia spúšťajú reklamu.", - "contacts_searchContacts": "Vyhľadávajte kontakty...", + "contacts_searchContacts": "Hľadať {number}{str} kontaktov...", "contacts_noUnreadContacts": "Žiadne neprečítané kontakty", "contacts_noContactsFound": "Neboli nájdených žiadnych kontaktov ani skupiny.", "contacts_deleteContact": "Odstrániť kontakt", diff --git a/lib/l10n/app_sl.arb b/lib/l10n/app_sl.arb index d2a9902d..16c956d8 100644 --- a/lib/l10n/app_sl.arb +++ b/lib/l10n/app_sl.arb @@ -120,8 +120,6 @@ "settings_rebootDeviceSubtitle": "Ponovno zaženi MeshCore napravo", "settings_rebootDeviceConfirm": "Ste prepričani, da želite ponovno zagnati napravo? Povezava bo prekinjena.", "settings_debug": "Odpravljanje napak", - "settings_bleDebugLog": "BLE debug log (razhroščevanje)", - "settings_bleDebugLogSubtitle": "BLE ukazi, odgovori in surovi podatki", "settings_appDebugLog": "Logi aplikacije", "settings_appDebugLogSubtitle": "Debug sporočila aplikacije", "settings_about": "Oglejte si", @@ -263,7 +261,7 @@ "contacts_title": "Stiki", "contacts_noContacts": "Ni stikov.", "contacts_contactsWillAppear": "Stiki se bodo prikazali, ko se naprave oglasijo.", - "contacts_searchContacts": "Iskanje stikov...", + "contacts_searchContacts": "Išči {number}{str} stikov...", "contacts_noUnreadContacts": "Ne prebrani stiki.", "contacts_noContactsFound": "Stiki niso najdeni.", "contacts_deleteContact": "Izbriši stik", diff --git a/lib/l10n/app_sv.arb b/lib/l10n/app_sv.arb index 56f34641..9262b002 100644 --- a/lib/l10n/app_sv.arb +++ b/lib/l10n/app_sv.arb @@ -120,8 +120,6 @@ "settings_rebootDeviceSubtitle": "Starta MeshCore-enheten", "settings_rebootDeviceConfirm": "Är du säker på att du vill starta om enheten? Du kommer att bli avkopplad.", "settings_debug": "Felsök", - "settings_bleDebugLog": "BLE-felsökning", - "settings_bleDebugLogSubtitle": "BLE-kommandon, svar och rådata", "settings_appDebugLog": "Appfelsökning", "settings_appDebugLogSubtitle": "Applikations felsökningsmeddelanden", "settings_about": "Om", @@ -263,7 +261,7 @@ "contacts_title": "Kontakter", "contacts_noContacts": "Inga kontakter ännu", "contacts_contactsWillAppear": "Kontakter kommer att visas när enheter annonserar.", - "contacts_searchContacts": "Sök kontakter...", + "contacts_searchContacts": "Sök {number}{str} kontakter...", "contacts_noUnreadContacts": "Inga oinlästa kontakter", "contacts_noContactsFound": "Inga kontakter eller grupper hittades.", "contacts_deleteContact": "Ta bort Kontakt", diff --git a/lib/l10n/app_uk.arb b/lib/l10n/app_uk.arb index 07e5a127..43fe60ed 100644 --- a/lib/l10n/app_uk.arb +++ b/lib/l10n/app_uk.arb @@ -121,8 +121,6 @@ "settings_rebootDeviceSubtitle": "Перезавантажити пристрій MeshCore", "settings_rebootDeviceConfirm": "Ви впевнені, що хочете перезавантажити пристрій? Вас буде відключено.", "settings_debug": "Налагодження", - "settings_bleDebugLog": "Журнал налагодження BLE", - "settings_bleDebugLogSubtitle": "Команди BLE, відповіді та необроблені дані", "settings_appDebugLog": "Журнал налагодження застосунку", "settings_appDebugLogSubtitle": "Повідомлення налагодження застосунку", "settings_about": "Про застосунок", @@ -265,7 +263,7 @@ "contacts_title": "Контакти", "contacts_noContacts": "Контактів не знайдено.", "contacts_contactsWillAppear": "Контакти з'являться, коли пристрої надішлють оголошення.", - "contacts_searchContacts": "Пошук контактів...", + "contacts_searchContacts": "Пошук {number}{str} контактів...", "contacts_noUnreadContacts": "Немає непрочитаних контактів", "contacts_noContactsFound": "Контактів або груп не знайдено.", "contacts_deleteContact": "Видалити контакт", @@ -1172,7 +1170,6 @@ "repeater_refreshBasicSettings": "Оновити основні налаштування", "repeater_refreshRadioSettings": "Оновити налаштування радіо", "repeater_refreshTxPower": "Оновити потужність TX", - "repeater_refreshLocationSettings": "Оновити налаштування геопозиції", "repeater_refreshPacketForwarding": "Оновити пересилання пакетів", "repeater_refreshGuestAccess": "Оновити гостьовий доступ", "repeater_refreshPrivacyMode": "Оновити режим приватності", diff --git a/lib/l10n/app_zh.arb b/lib/l10n/app_zh.arb index b41d73a6..b2f3244c 100644 --- a/lib/l10n/app_zh.arb +++ b/lib/l10n/app_zh.arb @@ -125,8 +125,6 @@ "settings_rebootDeviceSubtitle": "重启 MeshCore 设备", "settings_rebootDeviceConfirm": "确定要重启设备吗?这将断开与设备的连接。", "settings_debug": "调试", - "settings_bleDebugLog": "BLE 调试日志", - "settings_bleDebugLogSubtitle": "BLE 命令、响应和原始数据", "settings_appDebugLog": "应用调试日志", "settings_appDebugLogSubtitle": "应用调试消息", "settings_about": "关于", @@ -148,9 +146,6 @@ "settings_infoContactsCount": "联系人数量", "settings_infoChannelCount": "频道数量", "settings_presets": "预设", - "settings_preset915Mhz": "915 MHz", - "settings_preset868Mhz": "868 MHz", - "settings_preset433Mhz": "433 MHz", "settings_frequency": "频率 (MHz)", "settings_frequencyHelper": "300.0 - 2500.0", "settings_frequencyInvalid": "无效频率范围(300-2500 MHz)", @@ -160,8 +155,6 @@ "settings_txPower": "TX 功率 (dBm)", "settings_txPowerHelper": "0 - 22", "settings_txPowerInvalid": "无效的发射功率(0-22 dBm)", - "settings_longRange": "远距离", - "settings_fastSpeed": "高速", "settings_error": "错误:{message}", "@settings_error": { "placeholders": { @@ -277,7 +270,7 @@ "contacts_title": "联系人", "contacts_noContacts": "暂无联系人", "contacts_contactsWillAppear": "当设备发送广播时,联系人将显示。", - "contacts_searchContacts": "搜索联系人...", + "contacts_searchContacts": "搜索 {number}{str} 个联系人...", "contacts_noUnreadContacts": "没有未读内容", "contacts_noContactsFound": "未找到任何联系人或群聊", "contacts_deleteContact": "删除联系人", diff --git a/tools/l10n/check_arb.py b/tools/l10n/check_arb.py new file mode 100644 index 00000000..d0c0a66c --- /dev/null +++ b/tools/l10n/check_arb.py @@ -0,0 +1,342 @@ +#!/usr/bin/env python3 +"""Fail the build when a translation would break or show the wrong text (#1323). + +Compares every lib/l10n/app_.arb with the template, app_en.arb. + +Fails on: + - a placeholder dropped, renamed or added compared with English; + - a broken plural or select (unbalanced braces, no `other` case, a repeated + case, an unknown plural category, or a plural over a placeholder English + does not declare as a number); + - an empty translation of a non-empty English string; + - a key, or its @metadata, that app_en.arb no longer has; + - a duplicate key, or an @@locale that does not match the file name; + - a translation identical to English (ignoring spacing), unless + it is allowed by + tools/l10n/l10n_check.json: `allow_identical` (reviewed, permanent) or + `pending_identical` (known untranslated, for the language batches of #1322). + A pending entry that is no longer identical fails too, so the list only + shrinks. + +Reports, without failing, keys missing from a locale. `fail_on_missing` in the +config turns that into a failure once every locale is complete. + +Parses messages the way `flutter gen-l10n` does with `use-escaping` off (the +l10n.yaml default): every brace is syntax. Fails outright if l10n.yaml turns +escaping on, rather than misreading quoted text. + +Exit status: 0 when clean, 1 on any failure. +""" + +from __future__ import annotations + +import json +import os +import sys +from dataclasses import dataclass, field + +L10N_DIR = os.path.join("lib", "l10n") +TEMPLATE = "app_en.arb" +CONFIG = os.path.join(os.path.dirname(os.path.abspath(__file__)), "l10n_check.json") +ICU_TYPES = ("plural", "select", "selectordinal") +PLURAL_CATEGORIES = {"zero", "one", "two", "few", "many", "other"} +NUMBER_TYPES = {"int", "num", "double"} + + +class MessageError(ValueError): + pass + + +@dataclass +class Message: + """What a message references: every argument name, and its ICU blocks.""" + + names: set[str] = field(default_factory=set) + blocks: list[tuple[str, str, list[str]]] = field(default_factory=list) + text: str = "" + + +def parse_message(source: str) -> Message: + """Parses one ARB message, raising MessageError when it is malformed.""" + msg = Message() + end = _parse_body(source, 0, msg, nested=False) + if end != len(source): + raise MessageError(f"unexpected '}}' at {end}") + return msg + + +def _parse_body(s: str, i: int, msg: Message, nested: bool) -> int: + while i < len(s): + c = s[i] + if c == "{": + i = _parse_argument(s, i, msg) + elif c == "}": + if nested: + return i + raise MessageError(f"unexpected '}}' at {i}") + else: + msg.text += c + i += 1 + if nested: + raise MessageError("unclosed '{'") + return i + + +def _skip_ws(s: str, i: int) -> int: + while i < len(s) and s[i].isspace(): + i += 1 + return i + + +def _read_word(s: str, i: int) -> tuple[str, int]: + start = i + while i < len(s) and (s[i].isalnum() or s[i] in "_="): + i += 1 + return s[start:i], i + + +def _parse_argument(s: str, i: int, msg: Message) -> int: + open_at = i + i = _skip_ws(s, i + 1) + name, i = _read_word(s, i) + if not name or not (name[0].isalpha() or name[0] == "_"): + raise MessageError(f"bad argument name at {open_at}") + msg.names.add(name) + i = _skip_ws(s, i) + if i < len(s) and s[i] == "}": + return i + 1 + if i >= len(s) or s[i] != ",": + raise MessageError(f"unclosed '{{{name}'") + i = _skip_ws(s, i + 1) + kind, i = _read_word(s, i) + if kind not in ICU_TYPES: + raise MessageError(f"'{{{name}, {kind}' is not plural, select or selectordinal") + i = _skip_ws(s, i) + if i >= len(s) or s[i] != ",": + raise MessageError(f"'{{{name}, {kind}' needs a ',' before its cases") + i += 1 + cases: list[str] = [] + while True: + i = _skip_ws(s, i) + if i >= len(s): + raise MessageError(f"unclosed '{{{name}, {kind}'") + if s[i] == "}": + i += 1 + break + case, i = _read_word(s, i) + if not case: + raise MessageError(f"'{{{name}, {kind}' has a case with no name") + i = _skip_ws(s, i) + if i >= len(s) or s[i] != "{": + raise MessageError(f"case '{case}' of '{{{name}' has no '{{'") + i = _parse_body(s, i + 1, msg, nested=True) + 1 + cases.append(case) + msg.blocks.append((name, kind, cases)) + return i + + +def check_message(english: str, translated: str, placeholder_types: dict | None = None) -> list[str]: + """Problems with one translated message, compared with its English source. + + `placeholder_types` maps a placeholder to its type in app_en.arb's metadata. + """ + if english and not translated: + return ["empty translation"] + try: + en = parse_message(english) + except MessageError as e: + return [f"English message itself does not parse: {e}"] + try: + tr = parse_message(translated) + except MessageError as e: + return [f"does not parse: {e}"] + problems = [] + dropped = sorted(en.names - tr.names) + added = sorted(tr.names - en.names) + if dropped: + problems.append("drops " + ", ".join("{" + n + "}" for n in dropped)) + if added: + problems.append("adds " + ", ".join("{" + n + "}" for n in added)) + english_blocks = {(name, kind) for name, kind, _ in en.blocks} + types = placeholder_types or {} + for name, kind, cases in tr.blocks: + if "other" not in cases: + problems.append(f"'{{{name}, {kind}' has no 'other' case") + repeated = sorted({c for c in cases if cases.count(c) > 1}) + if repeated: + problems.append(f"'{{{name}, {kind}' repeats cases: {', '.join(repeated)}") + if kind != "select": + bad = [c for c in cases if c not in PLURAL_CATEGORIES and not _is_exact(c)] + if bad: + problems.append(f"'{{{name}, {kind}' has unknown cases: {', '.join(bad)}") + if (name, kind) not in english_blocks and types.get(name) not in NUMBER_TYPES: + problems.append( + f"'{{{name}, {kind}' counts a placeholder English does not declare as a number" + ) + return problems + + +def same_text(a: str, b: str) -> bool: + """True if two strings differ only in spacing. Case counts: German + capitalizes nouns, so "Min." can be the right translation of "min.".""" + return " ".join(a.split()) == " ".join(b.split()) + + +def _is_exact(case: str) -> bool: + return case.startswith("=") and case[1:].isdigit() + + +def has_words(message: str) -> bool: + """True if the message has text a translator could change.""" + try: + msg = parse_message(message) + except MessageError: + return True + return any(c.isalpha() for c in msg.text) + + +def load_arb(path: str) -> tuple[dict, list[str]]: + """Loads an ARB, returning its entries and any duplicate keys.""" + duplicates: list[str] = [] + + def pairs(items): + seen: dict = {} + for k, v in items: + if k in seen: + duplicates.append(k) + seen[k] = v + return seen + + with open(path, encoding="utf-8") as fh: + return json.load(fh, object_pairs_hook=pairs), duplicates + + +def load_config(path: str = CONFIG) -> dict: + with open(path, encoding="utf-8") as fh: + config = json.load(fh) + return { + "allow_identical": config.get("allow_identical", {}), + "pending_identical": config.get("pending_identical", {}), + "fail_on_missing": bool(config.get("fail_on_missing", False)), + } + + +def _placeholder_types(template: dict, key: str) -> dict: + meta = template.get("@" + key) + placeholders = meta.get("placeholders", {}) if isinstance(meta, dict) else {} + return {name: spec.get("type") for name, spec in placeholders.items() if isinstance(spec, dict)} + + +def escaping_is_on(l10n_yaml: str) -> bool: + """True if l10n.yaml turns on use-escaping, which this parser does not model.""" + if not os.path.exists(l10n_yaml): + return False + with open(l10n_yaml, encoding="utf-8") as fh: + for line in fh: + key, _, value = line.partition(":") + setting = value.split("#")[0].strip().strip("'\"").lower() + if key.strip() == "use-escaping" and setting == "true": + return True + return False + + +def _allowed(table: dict, key: str, locale: str) -> bool: + locales = table.get(key) + return locales == "*" or (isinstance(locales, list) and locale in locales) + + +def check_locale(locale: str, data: dict, duplicates: list[str], template: dict, config: dict): + """Returns (failures, missing keys) for one locale.""" + failures = [f"duplicate key '{k}'" for k in duplicates] + if data.get("@@locale") != locale: + failures.append(f"@@locale is {data.get('@@locale')!r}, the file name says {locale!r}") + + pending = set(config["pending_identical"].get(locale, [])) + for key, value in data.items(): + if key == "@@locale": + continue + if key.startswith("@"): + if key[1:] not in template: + failures.append(f"'{key}' is metadata for a key app_en.arb no longer has") + continue + if key not in template: + failures.append(f"'{key}' is not in app_en.arb") + continue + english = template[key] + if not isinstance(english, str): + continue + if not isinstance(value, str): + failures.append(f"'{key}' is not a string") + continue + for problem in check_message(english, value, _placeholder_types(template, key)): + failures.append(f"'{key}': {problem}") + if same_text(value, english) and has_words(english): + if key in pending: + continue + if not _allowed(config["allow_identical"], key, locale): + failures.append( + f"'{key}' is identical to English ({english!r}). Translate it, or add it " + "to allow_identical in tools/l10n/l10n_check.json if English is right here" + ) + + for key in sorted(pending): + if not isinstance(data.get(key), str) or not same_text(data[key], template.get(key, "")): + failures.append( + f"'{key}' is listed in pending_identical but is no longer identical to " + "English: remove it from tools/l10n/l10n_check.json" + ) + + missing = [k for k in template if not k.startswith("@") and k not in data] + return failures, missing + + +def run(l10n_dir: str = L10N_DIR, config_path: str = CONFIG, out=sys.stdout) -> int: + l10n_yaml = os.path.join(os.path.dirname(os.path.dirname(os.path.abspath(l10n_dir))), "l10n.yaml") + if escaping_is_on(l10n_yaml): + print( + "FAIL l10n.yaml: use-escaping is on, and this check parses messages as if it " + "were off. Teach tools/l10n/check_arb.py about quoted text first.", + file=out, + ) + return 1 + config = load_config(config_path) + template, template_dups = load_arb(os.path.join(l10n_dir, TEMPLATE)) + failed = False + if template_dups: + failed = True + print(f"FAIL {TEMPLATE}: duplicate keys {', '.join(template_dups)}", file=out) + for key, value in template.items(): + if key.startswith("@"): + continue + if not isinstance(value, str): + failed = True + print(f"FAIL {TEMPLATE}: '{key}' is not a string", file=out) + continue + try: + parse_message(value) + except MessageError as e: + failed = True + print(f"FAIL {TEMPLATE}: '{key}' does not parse: {e}", file=out) + + names = sorted(f for f in os.listdir(l10n_dir) if f.startswith("app_") and f.endswith(".arb")) + for name in names: + if name == TEMPLATE: + continue + locale = name[len("app_") : -len(".arb")] + data, dups = load_arb(os.path.join(l10n_dir, name)) + failures, missing = check_locale(locale, data, dups, template, config) + if missing and config["fail_on_missing"]: + failures.append(f"{len(missing)} keys missing: {', '.join(missing[:10])}") + for f in failures: + print(f"FAIL {name}: {f}", file=out) + failed = failed or bool(failures) + if missing and not config["fail_on_missing"]: + print(f"note {name}: {len(missing)} keys not translated yet", file=out) + + print("check_arb: FAILED" if failed else "check_arb: OK", file=out) + return 1 if failed else 0 + + +if __name__ == "__main__": + sys.stdout.reconfigure(encoding="utf-8") + raise SystemExit(run(*sys.argv[1:2])) diff --git a/tools/l10n/l10n_check.json b/tools/l10n/l10n_check.json new file mode 100644 index 00000000..6e168124 --- /dev/null +++ b/tools/l10n/l10n_check.json @@ -0,0 +1,589 @@ +{ + "fail_on_missing": false, + "allow_identical": { + "appTitle": "*", + "scanner_title": "*", + "settings_aboutVersion": "*", + "device_meshcore": "*", + "connectionChoiceBluetoothLabel": "*", + "connectionChoiceTcpLabel": "*", + "connectionChoiceUsbLabel": "*", + "telemetry_gpsLabel": "*", + "debugFrame_textTypeCli": "*", + "repeater_cli": "*", + "channels_pskHex": "*", + "settings_infoId": "*", + "common_voltageValue": "*", + "telemetry_altitudeValue": "*", + "telemetry_batteryValue": "*", + "telemetry_concentrationValue": "*", + "telemetry_currentValue": "*", + "telemetry_distanceValue": "*", + "telemetry_energyValue": "*", + "telemetry_frequencyValue": "*", + "telemetry_luminosityValue": "*", + "telemetry_powerValue": "*", + "telemetry_pressureValue": "*", + "telemetry_temperatureValue": "*", + "telemetry_voltageValue": "*", + "repeater_txPowerHelper": "*", + "repeater_frequencyHelper": "*", + "appSettings_batteryLifepo4": "*", + "appSettings_batteryLipo": "*", + "appSettings_batteryNmc": "*", + "appSettings_languageBg": "*", + "appSettings_languageDe": "*", + "appSettings_languageEn": "*", + "appSettings_languageEs": "*", + "appSettings_languageFr": "*", + "appSettings_languageHu": "*", + "appSettings_languageIt": "*", + "appSettings_languageJa": "*", + "appSettings_languageKo": "*", + "appSettings_languageNl": "*", + "appSettings_languagePl": "*", + "appSettings_languagePt": "*", + "appSettings_languageRu": "*", + "appSettings_languageSk": "*", + "appSettings_languageSl": "*", + "appSettings_languageSv": "*", + "appSettings_languageUk": "*", + "appSettings_languageZh": "*" + }, + "pending_identical": { + "bg": [ + "appSettings_translationModelDeleteFailed", + "appSettings_translationModelDeleted", + "background_serviceText", + "background_serviceTitle", + "channels_channelUpdateFailed", + "channels_via", + "chat_score", + "common_done", + "contact_typeChat", + "contact_typeRepeater", + "contact_typeRoom", + "contact_typeSensor", + "contact_typeUnknown", + "losSelectedObstructionDetails", + "map_estLocation", + "map_location", + "map_path", + "map_publicKey", + "map_publicKeyPrefixHint", + "map_type", + "repeater_actionFailed", + "repeater_actionSucceeded", + "repeater_rxAirtime", + "repeater_txAirtime", + "repeater_txPower", + "settings_deleteAllPaths", + "settings_deleteAllPathsSubtitle" + ], + "de": [ + "appSettings_translationModelDeleteFailed", + "appSettings_translationModelDeleted", + "background_serviceText", + "background_serviceTitle", + "channelPath_senderLabel", + "channels_channelUpdateFailed", + "channels_via", + "chat_score", + "common_done", + "contact_typeChat", + "contact_typeRepeater", + "contact_typeRoom", + "contact_typeSensor", + "contact_typeUnknown", + "debugFrame_text", + "mapCache_boundsLabel", + "map_estLocation", + "map_location", + "map_path", + "map_publicKey", + "map_publicKeyPrefixHint", + "map_sensor", + "map_type", + "repeater_cliQuickVersion", + "repeater_loopDetectMinimal", + "repeater_rxAirtime", + "repeater_status", + "repeater_txAirtime", + "repeater_txPower", + "settings_deleteAllPaths", + "settings_deleteAllPathsSubtitle", + "settings_infoName", + "settings_infoStatus" + ], + "es": [ + "appSettings_translationModelDeleteFailed", + "appSettings_translationModelDeleted", + "background_serviceText", + "background_serviceTitle", + "channels_channelUpdateFailed", + "channels_sortManual", + "channels_via", + "chat_score", + "common_done", + "contact_typeChat", + "contact_typeRepeater", + "contact_typeRoom", + "contact_typeSensor", + "contact_typeUnknown", + "contacts_ping", + "mapCache_boundsLabel", + "map_chat", + "map_estLocation", + "map_location", + "map_path", + "map_publicKey", + "map_publicKeyPrefixHint", + "map_sensor", + "map_type", + "repeater_actionFailed", + "repeater_actionSucceeded", + "repeater_cliCommandError", + "repeater_duplicatesTotal", + "repeater_general", + "repeater_rxAirtime", + "repeater_txAirtime", + "settings_deleteAllPaths", + "settings_deleteAllPathsSubtitle", + "settings_error" + ], + "fr": [ + "appSettings_notifications", + "appSettings_translationModelDeleteFailed", + "appSettings_translationModelDeleted", + "background_serviceText", + "background_serviceTitle", + "channels_channelUpdateFailed", + "channels_public", + "channels_via", + "chat_score", + "common_done", + "contact_typeChat", + "contact_typeRepeater", + "contact_typeRoom", + "contact_typeSensor", + "contact_typeUnknown", + "contacts_ping", + "losLegendTerrain", + "losPointA", + "losPointB", + "map_estLocation", + "map_location", + "map_path", + "map_publicKey", + "map_publicKeyPrefixHint", + "map_source", + "map_type", + "notification_messagesCount", + "repeater_actionsTitle", + "repeater_cliQuickVersion", + "repeater_latitude", + "repeater_localAdvertIntervalMinutes", + "repeater_longitude", + "repeater_loopDetectMinimal", + "repeater_loopDetectStrict", + "repeater_rxAirtime", + "repeater_txAirtime", + "settings_actions", + "settings_deleteAllPaths", + "settings_deleteAllPathsSubtitle", + "settings_latitude", + "settings_longitude", + "tcpPortLabel", + "telemetry_altitudeLabel", + "telemetry_concentrationLabel", + "telemetry_directionLabel", + "telemetry_distanceLabel", + "time_minutes" + ], + "hu": [ + "appSettings_translationModelDeleteFailed", + "appSettings_translationModelDeleted", + "background_serviceText", + "background_serviceTitle", + "channelPath_observedSomeOf", + "channels_channelUpdateFailed", + "channels_sortAZ", + "channels_via", + "chat_pathSetHops", + "chat_replyTo", + "chat_replyingTo", + "chat_score", + "common_done", + "contact_typeChat", + "contact_typeRepeater", + "contact_typeRoom", + "contact_typeSensor", + "contact_typeUnknown", + "contacts_lastSeenDaysAgo", + "contacts_ping", + "contacts_searchUsers", + "listFilter_az", + "losAntennaA", + "losAntennaB", + "losProfileClear", + "mapCache_boundsLabel", + "mapCache_cachedTilesWithFailed", + "map_estLocation", + "map_location", + "map_path", + "map_publicKey", + "map_publicKeyPrefixHint", + "map_type", + "repeater_daysHoursMinsSecs", + "repeater_rxAirtime", + "repeater_txAirtime", + "repeater_txPower", + "settings_deleteAllPaths", + "settings_deleteAllPathsSubtitle", + "time_daysAgo" + ], + "it": [ + "appSettings_translationModelDeleteFailed", + "appSettings_translationModelDeleted", + "background_serviceText", + "background_serviceTitle", + "channels_channelUpdateFailed", + "channels_via", + "chat_score", + "common_done", + "contact_typeChat", + "contact_typeRepeater", + "contact_typeRoom", + "contact_typeSensor", + "contact_typeUnknown", + "contacts_ping", + "login_password", + "losAntennaA", + "losAntennaB", + "losSelectedObstructionDetails", + "mapCache_boundsLabel", + "map_chat", + "map_estLocation", + "map_location", + "map_path", + "map_publicKey", + "map_publicKeyPrefixHint", + "map_type", + "repeater_actionFailed", + "repeater_rxAirtime", + "repeater_txAirtime", + "settings_deleteAllPaths", + "settings_deleteAllPathsSubtitle" + ], + "ja": [ + "appSettings_translationModelDeleteFailed", + "appSettings_translationModelDeleted", + "background_serviceText", + "background_serviceTitle", + "channelPath_observedSomeOf", + "channels_channelUpdateFailed", + "channels_via", + "chat_pathSetHops", + "chat_score", + "common_done", + "contact_typeChat", + "contact_typeRepeater", + "contact_typeRoom", + "contact_typeSensor", + "contact_typeUnknown", + "losProfileBlocked", + "losProfileClear", + "losStatusSummary", + "mapCache_boundsLabel", + "mapCache_cachedTilesWithFailed", + "mapCache_downloadedTiles", + "map_estLocation", + "map_location", + "map_path", + "map_publicKey", + "map_publicKeyPrefixHint", + "map_type", + "notification_messagesCount", + "settings_deleteAllPaths", + "settings_deleteAllPathsSubtitle" + ], + "ko": [ + "appSettings_translationModelDeleteFailed", + "appSettings_translationModelDeleted", + "background_serviceText", + "background_serviceTitle", + "channelPath_observedSomeOf", + "channels_channelUpdateFailed", + "channels_via", + "chat_pathSetHops", + "chat_score", + "common_done", + "contact_typeChat", + "contact_typeRepeater", + "contact_typeRoom", + "contact_typeSensor", + "contact_typeUnknown", + "contacts_lastSeenHoursAgo", + "contacts_lastSeenMinsAgo", + "losAntennaB", + "losProfileBlocked", + "losProfileClear", + "losSelectedObstructionDetails", + "mapCache_boundsLabel", + "mapCache_cachedTilesWithFailed", + "mapCache_downloadedTiles", + "map_estLocation", + "map_location", + "map_path", + "map_publicKey", + "map_publicKeyPrefixHint", + "map_type", + "neighbors_heardAgo", + "path_usingHopsPath", + "settings_deleteAllPaths", + "settings_deleteAllPathsSubtitle", + "time_hoursAgo" + ], + "nl": [ + "appSettings_translationModelDeleteFailed", + "appSettings_translationModelDeleted", + "background_serviceText", + "background_serviceTitle", + "channelPath_directPath", + "channels_channelUpdateFailed", + "channels_via", + "chat_direct", + "chat_hopsCount", + "chat_score", + "common_done", + "contact_typeChat", + "contact_typeRepeater", + "contact_typeRoom", + "contact_typeSensor", + "contact_typeUnknown", + "debugLog_bleTitle", + "listFilter_filters", + "losSelectedObstructionDetails", + "mapCache_boundsLabel", + "map_chat", + "map_estLocation", + "map_location", + "map_path", + "map_publicKey", + "map_publicKeyPrefixHint", + "map_sensor", + "map_type", + "repeater_actionFailed", + "repeater_status", + "repeater_txPower", + "settings_deleteAllPaths", + "settings_deleteAllPathsSubtitle", + "settings_infoStatus", + "telemetry_gyrometerLabel", + "telemetry_percentageLabel", + "time_week" + ], + "pl": [ + "appSettings_translationModelDeleteFailed", + "appSettings_translationModelDeleted", + "background_serviceText", + "background_serviceTitle", + "channels_channelUpdateFailed", + "channels_via", + "chat_score", + "common_done", + "contact_typeChat", + "contact_typeRepeater", + "contact_typeRoom", + "contact_typeSensor", + "contact_typeUnknown", + "losSelectedObstructionDetails", + "mapCache_boundsLabel", + "map_estLocation", + "map_location", + "map_path", + "map_publicKey", + "map_publicKeyPrefixHint", + "map_type", + "repeater_actionFailed", + "settings_deleteAllPaths", + "settings_deleteAllPathsSubtitle", + "tcpPortLabel" + ], + "pt": [ + "appSettings_translationModelDeleteFailed", + "appSettings_translationModelDeleted", + "background_serviceText", + "background_serviceTitle", + "channels_channelUpdateFailed", + "channels_sortManual", + "channels_via", + "chat_score", + "common_done", + "contact_typeChat", + "contact_typeRepeater", + "contact_typeRoom", + "contact_typeSensor", + "contact_typeUnknown", + "losSelectedObstructionDetails", + "mapCache_boundsLabel", + "map_chat", + "map_estLocation", + "map_location", + "map_path", + "map_publicKey", + "map_publicKeyPrefixHint", + "map_sensor", + "map_type", + "repeater_actionFailed", + "repeater_actionSucceeded", + "repeater_duplicatesTotal", + "repeater_latitude", + "repeater_longitude", + "repeater_rxAirtime", + "repeater_txAirtime", + "settings_deleteAllPaths", + "settings_deleteAllPathsSubtitle", + "settings_latitude", + "settings_longitude", + "settings_multiAck", + "telemetry_altitudeLabel" + ], + "ru": [ + "common_ok", + "losSelectedObstructionDetails", + "repeater_actionFailed", + "repeater_actionSucceeded", + "settings_deleteAllPaths", + "settings_deleteAllPathsSubtitle" + ], + "sk": [ + "appSettings_translationModelDeleteFailed", + "appSettings_translationModelDeleted", + "background_serviceText", + "background_serviceTitle", + "channels_channelUpdateFailed", + "channels_via", + "chat_score", + "common_done", + "contact_typeChat", + "contact_typeRepeater", + "contact_typeRoom", + "contact_typeSensor", + "contact_typeUnknown", + "debugFrame_text", + "losSelectedObstructionDetails", + "mapCache_boundsLabel", + "map_estLocation", + "map_location", + "map_path", + "map_publicKey", + "map_publicKeyPrefixHint", + "map_type", + "repeater_actionFailed", + "repeater_actionSucceeded", + "repeater_rxAirtime", + "repeater_txAirtime", + "repeater_txPower", + "settings_deleteAllPaths", + "settings_deleteAllPathsSubtitle", + "telemetry_gyrometerLabel" + ], + "sl": [ + "appSettings_translationModelDeleteFailed", + "appSettings_translationModelDeleted", + "background_serviceText", + "background_serviceTitle", + "channels_channelUpdateFailed", + "channels_via", + "chat_score", + "common_done", + "contact_typeChat", + "contact_typeRepeater", + "contact_typeRoom", + "contact_typeSensor", + "contact_typeUnknown", + "contacts_pathTraceTo", + "losSelectedObstructionDetails", + "mapCache_boundsLabel", + "map_estLocation", + "map_location", + "map_path", + "map_publicKey", + "map_publicKeyPrefixHint", + "map_type", + "repeater_rxAirtime", + "repeater_txAirtime", + "settings_deleteAllPaths", + "settings_deleteAllPathsSubtitle" + ], + "sv": [ + "appSettings_translationModelDeleteFailed", + "appSettings_translationModelDeleted", + "background_serviceText", + "background_serviceTitle", + "channels_channelUpdateFailed", + "channels_sortAZ", + "channels_via", + "chat_score", + "common_done", + "contact_typeChat", + "contact_typeRepeater", + "contact_typeRoom", + "contact_typeSensor", + "contact_typeUnknown", + "contacts_ping", + "debugFrame_text", + "listFilter_az", + "losSelectedObstructionDetails", + "mapCache_boundsLabel", + "map_chat", + "map_estLocation", + "map_location", + "map_path", + "map_publicKey", + "map_publicKeyPrefixHint", + "map_sensor", + "map_type", + "repeater_cliQuickVersion", + "repeater_loopDetectMinimal", + "repeater_rxAirtime", + "repeater_status", + "repeater_txAirtime", + "settings_deleteAllPaths", + "settings_deleteAllPathsSubtitle", + "settings_infoStatus", + "telemetry_accelerometerLabel", + "telemetry_gyrometerLabel" + ], + "uk": [ + "losSelectedObstructionDetails", + "repeater_actionFailed", + "repeater_actionSucceeded" + ], + "zh": [ + "appSettings_translationModelDeleteFailed", + "appSettings_translationModelDeleted", + "background_serviceText", + "background_serviceTitle", + "channels_channelUpdateFailed", + "channels_via", + "chat_score", + "common_done", + "contact_typeChat", + "contact_typeRepeater", + "contact_typeRoom", + "contact_typeSensor", + "contact_typeUnknown", + "losSelectedObstructionDetails", + "map_estLocation", + "map_location", + "map_path", + "map_publicKey", + "map_publicKeyPrefixHint", + "map_type", + "settings_deleteAllPaths", + "settings_deleteAllPathsSubtitle" + ] + } +} diff --git a/tools/l10n/test_check_arb.py b/tools/l10n/test_check_arb.py new file mode 100644 index 00000000..55a0a750 --- /dev/null +++ b/tools/l10n/test_check_arb.py @@ -0,0 +1,262 @@ +"""Tests for check_arb.py (#1323): one deliberately broken string per rule.""" + +import io +import json +import os +import sys +import tempfile +import unittest + +sys.path.insert(0, os.path.dirname(os.path.abspath(__file__))) + +import check_arb # noqa: E402 + +REPO = os.path.dirname(os.path.dirname(os.path.dirname(os.path.abspath(__file__)))) + +ENGLISH = { + "@@locale": "en", + "greeting": "Hello {name}", + "@greeting": {"placeholders": {"name": {"type": "String"}}}, + "hops": "{count} {count, plural, =1{hop} other{hops}}", + "minutes": "{minutes} min", + "@minutes": {"placeholders": {"minutes": {"type": "int"}}}, + "pronoun": "{gender, select, male{He} female{She} other{They}}", + "percent": "{percent}%", + "chat": "Chat", + "title": "Offband MeshCore", + "untranslated": "Delete All Paths", +} + +GERMAN = { + "@@locale": "de", + "greeting": "Hallo {name}", + "hops": "{count} {count, plural, =1{Hop} other{Hops}}", + "minutes": "{minutes} Min.", + "pronoun": "{gender, select, male{Er} female{Sie} other{Sie}}", + "percent": "{percent}%", + "chat": "Unterhaltung", + "title": "Offband MeshCore", + "untranslated": "Alle Pfade löschen", +} + +CONFIG = { + "fail_on_missing": False, + "allow_identical": {"title": "*"}, + "pending_identical": {}, +} + + +class CheckArbTest(unittest.TestCase): + def run_check(self, german=None, config=None, raw_german=None, english=None, l10n_yaml=None): + with tempfile.TemporaryDirectory() as tmp: + l10n_dir = os.path.join(tmp, "lib", "l10n") + os.makedirs(l10n_dir) + if l10n_yaml is not None: + with open(os.path.join(tmp, "l10n.yaml"), "w", encoding="utf-8") as fh: + fh.write(l10n_yaml) + with open(os.path.join(l10n_dir, "app_en.arb"), "w", encoding="utf-8") as fh: + json.dump(english or ENGLISH, fh, ensure_ascii=False) + with open(os.path.join(l10n_dir, "app_de.arb"), "w", encoding="utf-8") as fh: + fh.write(raw_german if raw_german is not None else json.dumps(german or GERMAN, ensure_ascii=False)) + config_path = os.path.join(tmp, "config.json") + with open(config_path, "w", encoding="utf-8") as fh: + json.dump(config or CONFIG, fh) + out = io.StringIO() + code = check_arb.run(l10n_dir, config_path, out) + return code, out.getvalue() + + def assert_fails(self, german, expected, config=None): + code, out = self.run_check(german, config) + self.assertEqual(code, 1, out) + self.assertIn(expected, out) + + def with_german(self, **changes): + german = dict(GERMAN) + for key, value in changes.items(): + if value is None: + german.pop(key) + else: + german[key] = value + return german + + def test_a_correct_translation_passes(self): + code, out = self.run_check() + self.assertEqual(code, 0, out) + self.assertIn("check_arb: OK", out) + + def test_dropped_placeholder_fails(self): + self.assert_fails(self.with_german(greeting="Hallo"), "'greeting': drops {name}") + + def test_renamed_placeholder_fails(self): + code, out = self.run_check(self.with_german(greeting="Hallo {nmae}")) + self.assertEqual(code, 1, out) + self.assertIn("'greeting': drops {name}", out) + self.assertIn("'greeting': adds {nmae}", out) + + def test_added_placeholder_fails(self): + self.assert_fails(self.with_german(greeting="Hallo {name} {extra}"), "'greeting': adds {extra}") + + def test_plural_without_other_fails(self): + self.assert_fails( + self.with_german(hops="{count} {count, plural, =1{Hop}}"), + "'{count, plural' has no 'other' case", + ) + + def test_unknown_plural_category_fails(self): + self.assert_fails( + self.with_german(hops="{count} {count, plural, =1{Hop} several{Hops} other{Hops}}"), + "unknown cases: several", + ) + + def test_unclosed_brace_fails(self): + self.assert_fails(self.with_german(greeting="Hallo {name"), "'greeting': does not parse") + + def test_stray_closing_brace_fails(self): + self.assert_fails(self.with_german(greeting="Hallo {name}}"), "'greeting': does not parse") + + def test_unbalanced_plural_fails(self): + self.assert_fails( + self.with_german(hops="{count} {count, plural, =1{Hop other{Hops}}"), + "'hops': does not parse", + ) + + def test_renamed_selector_variable_fails(self): + self.assert_fails( + self.with_german(hops="{count} {anzahl, plural, =1{Hop} other{Hops}}"), + "'hops': adds {anzahl}", + ) + + def test_select_without_other_fails(self): + self.assert_fails( + self.with_german(pronoun="{gender, select, male{Er} female{Sie}}"), + "'{gender, select' has no 'other' case", + ) + + def test_repeated_case_fails(self): + self.assert_fails( + self.with_german(hops="{count} {count, plural, one{Hop} one{Sprung} other{Hops}}"), + "repeats cases: one", + ) + + def test_plural_over_a_text_placeholder_fails(self): + self.assert_fails( + self.with_german(greeting="Hallo {name, plural, one{du} other{ihr}}"), + "'{name, plural' counts a placeholder English does not declare as a number", + ) + + def test_plural_over_a_number_placeholder_passes(self): + code, out = self.run_check( + self.with_german(minutes="{minutes} {minutes, plural, one{Minute} other{Minuten}}") + ) + self.assertEqual(code, 0, out) + + def test_malformed_english_fails(self): + english = dict(ENGLISH, greeting="Hello {name") + code, out = self.run_check(english=english) + self.assertEqual(code, 1, out) + self.assertIn("FAIL app_en.arb: 'greeting' does not parse", out) + + def test_escaping_turned_on_fails(self): + code, out = self.run_check(l10n_yaml="arb-dir: lib/l10n\nuse-escaping: true\n") + self.assertEqual(code, 1, out) + self.assertIn("use-escaping is on", out) + + def test_escaping_turned_on_with_a_quoted_value_fails(self): + code, out = self.run_check(l10n_yaml='use-escaping: "true"\n') + self.assertEqual(code, 1, out) + self.assertIn("use-escaping is on", out) + + def test_english_value_that_is_not_a_string_fails(self): + english = dict(ENGLISH, chat=123) + code, out = self.run_check(english=english) + self.assertEqual(code, 1, out) + self.assertIn("FAIL app_en.arb: 'chat' is not a string", out) + + def test_escaping_left_off_passes(self): + code, out = self.run_check(l10n_yaml="arb-dir: lib/l10n\nuse-escaping: false\n") + self.assertEqual(code, 0, out) + + def test_dropping_a_plural_block_but_keeping_the_count_passes(self): + code, out = self.run_check(self.with_german(hops="{count} Hops")) + self.assertEqual(code, 0, out) + + def test_empty_translation_fails(self): + self.assert_fails(self.with_german(chat=""), "'chat': empty translation") + + def test_identical_to_english_fails(self): + self.assert_fails(self.with_german(chat="Chat"), "'chat' is identical to English") + + def test_identical_apart_from_spacing_fails(self): + self.assert_fails(self.with_german(chat=" Chat "), "'chat' is identical to English") + + def test_a_change_of_case_alone_is_a_translation(self): + english = dict(ENGLISH, minutes="{minutes} min.") + code, out = self.run_check(self.with_german(minutes="{minutes} Min."), english=english) + self.assertEqual(code, 0, out) + + def test_identical_to_english_is_allowed_when_allowlisted(self): + config = dict(CONFIG, allow_identical={"title": "*", "chat": ["de"]}) + code, out = self.run_check(self.with_german(chat="Chat"), config) + self.assertEqual(code, 0, out) + + def test_allowlist_for_another_locale_does_not_cover_this_one(self): + config = dict(CONFIG, allow_identical={"title": "*", "chat": ["fr"]}) + self.assert_fails(self.with_german(chat="Chat"), "'chat' is identical to English", config) + + def test_identical_to_english_is_allowed_while_pending(self): + config = dict(CONFIG, pending_identical={"de": ["untranslated"]}) + code, out = self.run_check(self.with_german(untranslated="Delete All Paths"), config) + self.assertEqual(code, 0, out) + + def test_pending_entry_that_is_now_translated_fails(self): + config = dict(CONFIG, pending_identical={"de": ["untranslated"]}) + self.assert_fails(GERMAN, "'untranslated' is listed in pending_identical", config) + + def test_text_with_no_words_may_match_english(self): + code, out = self.run_check(self.with_german(percent="{percent}%")) + self.assertEqual(code, 0, out) + + def test_key_missing_from_english_fails(self): + self.assert_fails(self.with_german(gone="Weg"), "'gone' is not in app_en.arb") + + def test_metadata_for_a_key_missing_from_english_fails(self): + self.assert_fails(self.with_german(**{"@gone": {}}), "'@gone' is metadata") + + def test_missing_key_is_reported_not_failed(self): + code, out = self.run_check(self.with_german(chat=None)) + self.assertEqual(code, 0, out) + self.assertIn("note app_de.arb: 1 keys not translated yet", out) + + def test_missing_key_fails_once_fail_on_missing_is_set(self): + config = dict(CONFIG, fail_on_missing=True) + self.assert_fails(self.with_german(chat=None), "1 keys missing: chat", config) + + def test_duplicate_key_fails(self): + raw = json.dumps(GERMAN, ensure_ascii=False)[:-1] + ', "chat": "Plaudern"}' + code, out = self.run_check(raw_german=raw) + self.assertEqual(code, 1, out) + self.assertIn("duplicate key 'chat'", out) + + def test_locale_that_does_not_match_the_file_name_fails(self): + self.assert_fails(self.with_german(**{"@@locale": "fr"}), "@@locale is 'fr'") + + +class RepositoryTest(unittest.TestCase): + def test_the_repository_passes(self): + out = io.StringIO() + code = check_arb.run( + os.path.join(REPO, "lib", "l10n"), + os.path.join(REPO, "tools", "l10n", "l10n_check.json"), + out, + ) + self.assertEqual(code, 0, out.getvalue()) + + def test_every_allowlisted_key_exists(self): + template, _ = check_arb.load_arb(os.path.join(REPO, "lib", "l10n", "app_en.arb")) + config = check_arb.load_config(os.path.join(REPO, "tools", "l10n", "l10n_check.json")) + stale = [k for k in config["allow_identical"] if k not in template] + self.assertEqual(stale, []) + + +if __name__ == "__main__": + unittest.main()