|
| 1 | +"use strict"; |
| 2 | + |
| 3 | +const fs = require("fs"); |
| 4 | +const path = require("path"); |
| 5 | +const { parse } = require("@babel/parser"); |
| 6 | + |
| 7 | +module.exports = { |
| 8 | + meta: { |
| 9 | + name: "check-i18n-keys", |
| 10 | + type: "suggestion", |
| 11 | + docs: { |
| 12 | + description: |
| 13 | + "Ensure translation keys in other language files match the keys in the English translation file.", |
| 14 | + category: "Best Practices", |
| 15 | + recommended: true |
| 16 | + }, |
| 17 | + fixable: null, |
| 18 | + schema: [] |
| 19 | + }, |
| 20 | + create: function (context) { |
| 21 | + function extractKeys(node, parentKey = "") { |
| 22 | + const keys = []; |
| 23 | + let properties = node.properties; |
| 24 | + |
| 25 | + if (typeof node === "string") { |
| 26 | + const fileContent = fs.readFileSync(node, "utf8"); |
| 27 | + const ast = parse(fileContent, { |
| 28 | + sourceType: "module", |
| 29 | + plugins: ["typescript", "jsx"] |
| 30 | + }); |
| 31 | + properties = |
| 32 | + !!ast && ast.program.body[0].declaration.properties; |
| 33 | + } |
| 34 | + |
| 35 | + function traverseProperties(properties, parentKey) { |
| 36 | + properties.forEach((property) => { |
| 37 | + if ( |
| 38 | + (property.type === "ObjectProperty" || |
| 39 | + property.type === "Property") && |
| 40 | + property.key.type === "Identifier" |
| 41 | + ) { |
| 42 | + const currentKey = parentKey |
| 43 | + ? `${parentKey}.${property.key.name}` |
| 44 | + : property.key.name; |
| 45 | + keys.push(currentKey); |
| 46 | + if (property.value.type === "ObjectExpression") { |
| 47 | + traverseProperties( |
| 48 | + property.value.properties, |
| 49 | + currentKey |
| 50 | + ); |
| 51 | + } |
| 52 | + } |
| 53 | + }); |
| 54 | + } |
| 55 | + |
| 56 | + traverseProperties(properties, parentKey); |
| 57 | + |
| 58 | + return keys; |
| 59 | + } |
| 60 | + |
| 61 | + return { |
| 62 | + Program(node) { |
| 63 | + for (const statement of node.body) { |
| 64 | + const fallbackFilePath = path |
| 65 | + .relative(process.cwd(), context.getFilename()) |
| 66 | + .replace( |
| 67 | + /\/i18n\/\w+\/translations\.ts$/, |
| 68 | + "/i18n/en/translations.ts" |
| 69 | + ); |
| 70 | + |
| 71 | + const keys = extractKeys(statement.declaration); |
| 72 | + |
| 73 | + const enKeys = extractKeys(fallbackFilePath); |
| 74 | + |
| 75 | + // Report missing keys |
| 76 | + enKeys.forEach((enKey) => { |
| 77 | + if (!keys.includes(enKey)) { |
| 78 | + context.report({ |
| 79 | + node: node, |
| 80 | + message: `missing key '${enKey}'` |
| 81 | + }); |
| 82 | + } |
| 83 | + }); |
| 84 | + |
| 85 | + // Report extra keys |
| 86 | + keys.forEach((key) => { |
| 87 | + if (!enKeys.includes(key)) { |
| 88 | + context.report({ |
| 89 | + node: node, |
| 90 | + message: `extra key '${key}'` |
| 91 | + }); |
| 92 | + } |
| 93 | + }); |
| 94 | + } |
| 95 | + } |
| 96 | + }; |
| 97 | + } |
| 98 | +}; |
0 commit comments