From 8f8b7f0fbf59099dcb6549b2edc713943954801a Mon Sep 17 00:00:00 2001 From: Sam Atkins Date: Mon, 1 Apr 2024 12:12:31 +0100 Subject: [PATCH] Check that all uses of i18n() use keys that exist If code uses `i18n('foo')` and 'foo' is not in the dictionary for the en translation, then this script will now report it as an error. This has already helped catch a few mistakes. --- tools/check-translations.js | 33 +++++++++++++++++++++++++++++++++ 1 file changed, 33 insertions(+) diff --git a/tools/check-translations.js b/tools/check-translations.js index b718ec63..f5f45b38 100644 --- a/tools/check-translations.js +++ b/tools/check-translations.js @@ -53,6 +53,7 @@ async function checkTranslationRegistrations() { } } +// Ensure that translations only contain keys that exist in the en dictionary function checkTranslationKeys() { const enDictionary = translations.en.dictionary; @@ -71,8 +72,40 @@ function checkTranslationKeys() { } } +// Ensure that all keys passed to i18n() exist in the en dictionary +async function checkTranslationUsage() { + const enDictionary = translations.en.dictionary; + + const sourceDirectories = [ + './src/helpers', + './src/UI', + ]; + + // Looks for i18n() calls using either ' or " for the key string. + // The key itself is at index 2 of the result. + const i18nRegex = /i18n\((['"])(.*?)\1\)/g; + + for (const dir of sourceDirectories) { + const files = await fs.promises.readdir(dir, { recursive: true }); + for (const relativeFileName of files) { + if (!relativeFileName.endsWith('.js')) continue; + const fileName = `${dir}/${relativeFileName}`; + + const fileContents = await fs.promises.readFile(fileName, { encoding: 'utf8' }); + const i18nUses = fileContents.matchAll(i18nRegex); + for (const use of i18nUses) { + const key = use[2]; + if (!enDictionary.hasOwnProperty(key)) { + reportError(`Unrecognized i18n key: call ${use[0]} in ${fileName}`); + } + } + } + } +} + await checkTranslationRegistrations(); checkTranslationKeys(); +await checkTranslationUsage(); if (hadError) { process.stdout.write('Errors were found in translation files.\n');