-
-
Notifications
You must be signed in to change notification settings - Fork 424
Expand file tree
/
Copy pathcompare-translations.ts
More file actions
425 lines (371 loc) · 12.9 KB
/
compare-translations.ts
File metadata and controls
425 lines (371 loc) · 12.9 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
/* eslint-disable no-console */
import type { LocaleObject } from '@nuxtjs/i18n'
import * as process from 'node:process'
import { existsSync, readdirSync, readFileSync, writeFileSync } from 'node:fs'
import { basename, join, resolve } from 'node:path'
import { deepCopy } from '@intlify/shared'
import { countryLocaleVariants, currentLocales } from '../config/i18n.ts'
import { COLORS } from './utils.ts'
const LOCALES_DIRECTORY = join(import.meta.dirname, '../i18n/locales')
const REFERENCE_FILE_NAME = 'en.json'
type NestedObject = { [key: string]: unknown }
interface LocaleInfo {
filePath: string
locale: string
lang: string
country?: string
forCountry?: boolean
mergeLocale?: boolean
}
const countries = new Map<string, Map<string, LocaleInfo>>()
const availableLocales = new Map<string, LocaleObject>()
function extractLocalInfo(filePath: string): LocaleInfo {
const locale = basename(filePath, '.json')
const [lang, country] = locale.split('-')
return { filePath, locale, lang, country }
}
function createVariantInfo(
code: string,
options: { forCountry: boolean; mergeLocale: boolean },
): LocaleInfo {
const [lang, country] = code.split('-')
return { filePath: '', locale: code, lang, country, ...options }
}
const populateLocaleCountries = (): void => {
for (const lang of Object.keys(countryLocaleVariants)) {
const variants = countryLocaleVariants[lang]
for (const variant of variants) {
if (!countries.has(lang)) {
countries.set(lang, new Map())
}
if (variant.country) {
countries
.get(lang)!
.set(lang, createVariantInfo(lang, { forCountry: true, mergeLocale: false }))
countries
.get(lang)!
.set(
variant.code,
createVariantInfo(variant.code, { forCountry: true, mergeLocale: true }),
)
} else {
countries
.get(lang)!
.set(
variant.code,
createVariantInfo(variant.code, { forCountry: false, mergeLocale: true }),
)
}
}
}
for (const localeData of currentLocales) {
availableLocales.set(localeData.code, localeData)
}
}
/**
* We use ISO 639-1 for the language and ISO 3166-1 for the country (e.g. es-ES), we're preventing here:
* using the language as the JSON file name when there is no country variant.
*
* For example, `az.json` is wrong, should be `az-AZ.json` since it is not included at `countryLocaleVariants`.
*/
const checkCountryVariant = (localeInfo: LocaleInfo): void => {
const { locale, lang, country } = localeInfo
const countryVariant = countries.get(lang)
if (countryVariant) {
if (country) {
const found = countryVariant.get(locale)
if (!found) {
console.error(
`${COLORS.red}Error: Invalid locale file "${locale}", it should be included at "countryLocaleVariants" in config/i18n.ts"${COLORS.reset}`,
)
process.exit(1)
}
localeInfo.forCountry = found.forCountry
localeInfo.mergeLocale = found.mergeLocale
} else {
localeInfo.forCountry = false
localeInfo.mergeLocale = false
}
} else {
if (!country) {
console.error(
`${COLORS.red}Error: Invalid locale file "${locale}", it should be included at "countryLocaleVariants" in config/i18n.ts, or change the name to include country name "${lang}-<country-name>"${COLORS.reset}`,
)
process.exit(1)
}
}
}
const checkJsonName = (filePath: string): LocaleInfo => {
const info = extractLocalInfo(filePath)
checkCountryVariant(info)
return info
}
const loadJson = async ({ filePath, mergeLocale, locale }: LocaleInfo): Promise<NestedObject> => {
if (!existsSync(filePath)) {
console.error(`${COLORS.red}Error: File not found at ${filePath}${COLORS.reset}`)
process.exit(1)
}
if (!mergeLocale) {
return JSON.parse(readFileSync(filePath, 'utf-8')) as NestedObject
}
const localeObject = availableLocales.get(locale)
if (!localeObject) {
console.error(
`${COLORS.red}Error: Locale "${locale}" not found in currentLocales${COLORS.reset}`,
)
process.exit(1)
}
// Merge multi-file locale: load base file, then overlay variant file on top
const localesFolder = resolve('i18n/locales')
const files = localeObject.files ?? []
if (localeObject.file || files.length === 1) {
const fileName =
(localeObject.file ? getFileName(localeObject.file) : undefined) ??
(files[0] ? getFileName(files[0]) : undefined)
if (!fileName) return {}
return JSON.parse(readFileSync(join(localesFolder, fileName), 'utf-8')) as NestedObject
}
const firstFile = files[0]
if (!firstFile) return {}
const source = JSON.parse(
readFileSync(join(localesFolder, getFileName(firstFile)), 'utf-8'),
) as NestedObject
for (let i = 1; i < files.length; i++) {
const file = files[i]
if (!file) continue
const overlay = JSON.parse(readFileSync(join(localesFolder, getFileName(file)), 'utf-8'))
deepCopy(overlay, source)
}
return source
}
function getFileName(file: string | { path: string }): string {
return typeof file === 'string' ? file : file.path
}
type SyncStats = {
missing: string[]
extra: string[]
referenceKeys: string[]
}
// Check if value is a non-null object and not array
const isNested = (val: unknown): val is NestedObject =>
val !== null && typeof val === 'object' && !Array.isArray(val)
const syncLocaleData = (
reference: NestedObject,
target: NestedObject,
stats: SyncStats,
fix: boolean,
prefix = '',
): NestedObject => {
const result: NestedObject = {}
for (const key of Object.keys(reference)) {
const propertyPath = prefix ? `${prefix}.${key}` : key
const refValue = reference[key]
if (isNested(refValue)) {
const nextTarget = isNested(target[key]) ? target[key] : {}
const data = syncLocaleData(refValue, nextTarget, stats, fix, propertyPath)
// When fixing, empty objects won't occur since missing keys get placeholders.
// Without --fix, keep empty objects to preserve structural parity with the reference.
if (fix && Object.keys(data).length === 0) {
delete result[key]
} else {
result[key] = data
}
} else {
stats.referenceKeys.push(propertyPath)
if (key in target) {
result[key] = target[key]
} else {
stats.missing.push(propertyPath)
if (fix) {
result[key] = `EN TEXT TO REPLACE: ${refValue}`
}
}
}
}
for (const key of Object.keys(target)) {
const propertyPath = prefix ? `${prefix}.${key}` : key
if (!(key in reference)) {
stats.extra.push(propertyPath)
}
}
return result
}
const logSection = (
title: string,
keys: string[],
color: string,
icon: string,
emptyMessage: string,
): void => {
console.log(`\n${color}${icon} ${title}${COLORS.reset}`)
if (keys.length === 0) {
console.log(` ${COLORS.green}${emptyMessage}${COLORS.reset}`)
return
}
keys.forEach(key => console.log(` - ${key}`))
}
const processLocale = async (
singleLocale: boolean,
localeFile: string,
referenceContent: NestedObject,
fix = false,
): Promise<SyncStats> => {
const filePath = join(LOCALES_DIRECTORY, localeFile)
const localeInfo = checkJsonName(filePath)
// prevent updating wrong locale file:
// - language locale files at countries allowed: e.g. es.json
// - country locale file forbidden: e.g. es-ES.json
// - target locale file forbidden: e.g. es-419.json
if (fix && localeInfo.mergeLocale && singleLocale) {
console.error(
`${COLORS.red}Error: Locale "${localeInfo.locale}" cannot be fixed, fix the ${localeInfo.lang} locale instead!${COLORS.reset}`,
)
process.exit(1)
}
const targetContent = await loadJson(localeInfo)
// $schema is a JSON Schema reference, not a translation key — preserve it but exclude from comparison
const { $schema: targetSchema, ...targetWithoutSchema } = targetContent
const stats: SyncStats = {
missing: [],
extra: [],
referenceKeys: [],
}
const newContent = syncLocaleData(referenceContent, targetWithoutSchema, stats, fix)
// Write if there are removals (always) or we are in fix mode
if (!localeInfo.mergeLocale && (stats.extra.length > 0 || fix)) {
const output = targetSchema ? { $schema: targetSchema, ...newContent } : newContent
writeFileSync(filePath, JSON.stringify(output, null, 2) + '\n', 'utf-8')
}
return stats
}
const runSingleLocale = async (
locale: string,
referenceContent: NestedObject,
fix = false,
): Promise<void> => {
const localeFile = locale.endsWith('.json') ? locale : `${locale}.json`
const filePath = join(LOCALES_DIRECTORY, localeFile)
if (!existsSync(filePath)) {
console.error(`${COLORS.red}Error: Locale file not found: ${localeFile}${COLORS.reset}`)
process.exit(1)
}
const { missing, extra, referenceKeys } = await processLocale(
true,
localeFile,
referenceContent,
fix,
)
console.log(
`${COLORS.cyan}=== Missing keys for ${localeFile}${fix ? ' (with --fix)' : ''} ===${COLORS.reset}`,
)
console.log(`Reference: ${REFERENCE_FILE_NAME} (${referenceKeys.length} keys)`)
if (missing.length > 0) {
if (fix) {
console.log(
`\n${COLORS.green}Added ${missing.length} missing key(s) with EN placeholder:${COLORS.reset}`,
)
missing.forEach(key => console.log(` - ${key}`))
} else {
console.log(`\n${COLORS.yellow}Missing ${missing.length} key(s):${COLORS.reset}`)
missing.forEach(key => console.log(` - ${key}`))
}
} else {
console.log(`\n${COLORS.green}No missing keys!${COLORS.reset}`)
}
if (extra.length > 0) {
console.log(`\n${COLORS.magenta}Removed ${extra.length} extra key(s):${COLORS.reset}`)
extra.forEach(key => console.log(` - ${key}`))
}
console.log('')
}
const runAllLocales = async (referenceContent: NestedObject, fix = false): Promise<void> => {
const localeFiles = readdirSync(LOCALES_DIRECTORY).filter(
file => file.endsWith('.json') && file !== REFERENCE_FILE_NAME,
)
const results: (SyncStats & { file: string })[] = []
let totalMissing = 0
let totalRemoved = 0
let totalAdded = 0
for (const localeFile of localeFiles) {
const stats = await processLocale(false, localeFile, referenceContent, fix)
results.push({
file: localeFile,
...stats,
})
if (fix) {
if (stats.missing.length > 0) totalAdded += stats.missing.length
} else {
if (stats.missing.length > 0) totalMissing += stats.missing.length
}
if (stats.extra.length > 0) totalRemoved += stats.extra.length
}
const referenceKeysCount = results.length > 0 ? results[0]!.referenceKeys.length : 0
console.log(`${COLORS.cyan}=== Translation Audit${fix ? ' (with --fix)' : ''} ===${COLORS.reset}`)
console.log(`Reference: ${REFERENCE_FILE_NAME} (${referenceKeysCount} keys)`)
console.log(`Checking ${localeFiles.length} locale(s)...`)
for (const res of results) {
if (res.missing.length > 0 || res.extra.length > 0) {
console.log(`\n${COLORS.cyan}--- ${res.file} ---${COLORS.reset}`)
if (res.missing.length > 0) {
if (fix) {
logSection('ADDED MISSING KEYS (with EN placeholder)', res.missing, COLORS.green, '', '')
} else {
logSection(
'MISSING KEYS (in en.json but not in this locale)',
res.missing,
COLORS.yellow,
'',
'',
)
}
}
if (res.extra.length > 0) {
logSection(
'REMOVED EXTRA KEYS (were in this locale but not in en.json)',
res.extra,
COLORS.magenta,
'',
'',
)
}
}
}
console.log(`\n${COLORS.cyan}=== Summary ===${COLORS.reset}`)
if (totalAdded > 0) {
console.log(
`${COLORS.green} Added missing keys (EN placeholder): ${totalAdded}${COLORS.reset}`,
)
}
if (totalMissing > 0) {
console.log(`${COLORS.yellow} Missing keys across all locales: ${totalMissing}${COLORS.reset}`)
}
if (totalRemoved > 0) {
console.log(`${COLORS.magenta} Removed extra keys: ${totalRemoved}${COLORS.reset}`)
}
if (totalMissing === 0 && totalRemoved === 0 && totalAdded === 0) {
console.log(`${COLORS.green} All locales are in sync!${COLORS.reset}`)
}
console.log('')
}
const run = async (): Promise<void> => {
populateLocaleCountries()
const referenceFilePath = join(LOCALES_DIRECTORY, REFERENCE_FILE_NAME)
const referenceContent = await loadJson({
filePath: referenceFilePath,
locale: 'en',
lang: 'en',
})
// $schema is a JSON Schema reference, not a translation key
delete referenceContent.$schema
const args = process.argv.slice(2)
const fix = args.includes('--fix')
const targetLocale = args.find(arg => !arg.startsWith('--'))
if (targetLocale) {
// Single locale mode
await runSingleLocale(targetLocale, referenceContent, fix)
} else {
// All locales mode: check all and remove extraneous keys
await runAllLocales(referenceContent, fix)
}
}
await run()