From 2a14c1d3173a5dff8b73d2fed569b85007cc2a56 Mon Sep 17 00:00:00 2001 From: Stanislav Lysak Date: Wed, 11 Sep 2024 11:26:47 +0300 Subject: [PATCH] script enhancements --- scripts/scan-locales.mjs | 26 ++++++++++++++++++-------- 1 file changed, 18 insertions(+), 8 deletions(-) diff --git a/scripts/scan-locales.mjs b/scripts/scan-locales.mjs index ad05da669..5089c79ee 100644 --- a/scripts/scan-locales.mjs +++ b/scripts/scan-locales.mjs @@ -8,23 +8,35 @@ const baseLocale = getLocalePaths(BASE_LOCALE) const { keys: translationKeys, namespaces } = getLocaleData(baseLocale) -// Path to your source code -const sourceCodePath = './src/**/*.{js,jsx,ts,tsx}' // adjust for relevant file types +const translationKeysWoNs = translationKeys.map((key) => + key.replace(new RegExp(`^(${namespaces.join('|')}).`), ''), +) // Search for translation keys in the source code -function searchForTranslationKeysInCode(pattern) { +function searchForTranslationKeysInCode() { const regex = /t[cs]?\(['"`]([a-zA-Z0-9_.]+)['"`]\s*,?\s*{?/g // = /t\(['"`]([a-zA-Z0-9_.]+)['"`]\s*,?\s*{?/g // /t\(['"`]([a-zA-Z0-9_.]+)['"`]\)/g // regex to match t('key') - const files = glob.sync(pattern) + const files = [ + ...glob.sync(`./src/**/*.{js,jsx,ts,tsx}`), + ...glob.sync(`./src/*.{js,jsx,ts,tsx}`), + ] + const foundKeys = new Set() files.forEach((file) => { const content = fs.readFileSync(file, 'utf-8') let match + while ((match = regex.exec(content)) !== null) { foundKeys.add(match[1]) // Add the matched key } + + const keys = translationKeysWoNs.filter((key) => new RegExp(`['"\`]${key}['"\`]`).test(content)) + + for (const key of keys) { + foundKeys.add(key) + } }) return foundKeys @@ -32,13 +44,11 @@ function searchForTranslationKeysInCode(pattern) { // Find unused translation keys function findUnusedKeys() { - const usedKeys = searchForTranslationKeysInCode(sourceCodePath) + const usedKeys = searchForTranslationKeysInCode() const unusedKeys = [] - const regex = new RegExp(`^(${namespaces.join('|')}).`) - - for (const key of translationKeys.map((key) => key.replace(regex, ''))) { + for (const key of translationKeysWoNs) { if (!usedKeys.has(key)) { unusedKeys.push(key) }