forked from cjpais/Handy
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathcheck-translations.ts
More file actions
224 lines (189 loc) · 5.64 KB
/
check-translations.ts
File metadata and controls
224 lines (189 loc) · 5.64 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
import fs from "fs";
import path from "path";
import { fileURLToPath } from "url";
const __dirname = path.dirname(fileURLToPath(import.meta.url));
// Configuration
const LOCALES_DIR = path.join(__dirname, "..", "src", "i18n", "locales");
const REFERENCE_LANG = "en";
type TranslationData = Record<string, unknown>;
interface ValidationResult {
valid: boolean;
missing: string[][];
extra: string[][];
}
function getLanguages(): string[] {
const entries = fs.readdirSync(LOCALES_DIR, { withFileTypes: true });
return entries
.filter((entry) => entry.isDirectory() && entry.name !== REFERENCE_LANG)
.map((entry) => entry.name)
.sort();
}
const LANGUAGES = getLanguages();
// Colors for terminal output
const colors: Record<string, string> = {
reset: "\x1b[0m",
red: "\x1b[31m",
green: "\x1b[32m",
yellow: "\x1b[33m",
blue: "\x1b[34m",
};
function colorize(text: string, color: string): string {
return `${colors[color]}${text}${colors.reset}`;
}
function getAllKeyPaths(
obj: TranslationData,
prefix: string[] = [],
): string[][] {
let paths: string[][] = [];
for (const key in obj) {
if (!Object.hasOwn(obj, key)) continue;
const currentPath = prefix.concat([key]);
const value = obj[key];
if (typeof value === "object" && value !== null && !Array.isArray(value)) {
paths = paths.concat(
getAllKeyPaths(value as TranslationData, currentPath),
);
} else {
paths.push(currentPath);
}
}
return paths;
}
function hasKeyPath(obj: TranslationData, keyPath: string[]): boolean {
let current: unknown = obj;
for (const key of keyPath) {
if (
typeof current !== "object" ||
current === null ||
(current as Record<string, unknown>)[key] === undefined
) {
return false;
}
current = (current as Record<string, unknown>)[key];
}
return true;
}
function loadTranslationFile(lang: string): TranslationData | null {
const filePath = path.join(LOCALES_DIR, lang, "translation.json");
try {
const content = fs.readFileSync(filePath, "utf8");
return JSON.parse(content) as TranslationData;
} catch (error) {
console.error(colorize(`✗ Error loading ${lang}/translation.json:`, "red"));
console.error(` ${(error as Error).message}`);
return null;
}
}
function validateTranslations(): void {
console.log(colorize("\n🌍 Translation Consistency Check\n", "blue"));
// Load reference file
console.log(`Loading reference language: ${REFERENCE_LANG}`);
const referenceData = loadTranslationFile(REFERENCE_LANG);
if (!referenceData) {
console.error(
colorize(`\n✗ Failed to load reference file (${REFERENCE_LANG})`, "red"),
);
process.exit(1);
}
// Get all key paths from reference
const referenceKeyPaths = getAllKeyPaths(referenceData);
console.log(`Reference has ${referenceKeyPaths.length} keys\n`);
// Track validation results
let hasErrors = false;
const results: Record<string, ValidationResult> = {};
// Validate each language
for (const lang of LANGUAGES) {
const langData = loadTranslationFile(lang);
if (!langData) {
hasErrors = true;
results[lang] = { valid: false, missing: [], extra: [] };
continue;
}
// Find missing keys
const missing = referenceKeyPaths.filter(
(keyPath) => !hasKeyPath(langData, keyPath),
);
// Find extra keys (keys in language but not in reference)
const langKeyPaths = getAllKeyPaths(langData);
const extra = langKeyPaths.filter(
(keyPath) => !hasKeyPath(referenceData, keyPath),
);
results[lang] = {
valid: missing.length === 0 && extra.length === 0,
missing,
extra,
};
if (missing.length > 0 || extra.length > 0) {
hasErrors = true;
}
}
// Print results
console.log(colorize("Results:", "blue"));
console.log("─".repeat(60));
for (const lang of LANGUAGES) {
const result = results[lang];
if (result.valid) {
console.log(
colorize(`✓ ${lang.toUpperCase()}: All keys present`, "green"),
);
} else {
console.log(colorize(`✗ ${lang.toUpperCase()}: Issues found`, "red"));
if (result.missing.length > 0) {
console.log(
colorize(` Missing ${result.missing.length} keys:`, "yellow"),
);
result.missing.slice(0, 10).forEach((keyPath) => {
console.log(` - ${keyPath.join(".")}`);
});
if (result.missing.length > 10) {
console.log(
colorize(
` ... and ${result.missing.length - 10} more`,
"yellow",
),
);
}
}
if (result.extra.length > 0) {
console.log(
colorize(
` Extra ${result.extra.length} keys (not in reference):`,
"yellow",
),
);
result.extra.slice(0, 10).forEach((keyPath) => {
console.log(` - ${keyPath.join(".")}`);
});
if (result.extra.length > 10) {
console.log(
colorize(` ... and ${result.extra.length - 10} more`, "yellow"),
);
}
}
console.log("");
}
}
console.log("─".repeat(60));
// Summary
const validCount = Object.values(results).filter((r) => r.valid).length;
const totalCount = LANGUAGES.length;
if (hasErrors) {
console.log(
colorize(
`\n✗ Validation failed: ${validCount}/${totalCount} languages passed`,
"red",
),
);
process.exit(1);
} else {
console.log(
colorize(
`\n✓ All ${totalCount} languages have complete translations!`,
"green",
),
);
process.exit(0);
}
}
// Run validation
validateTranslations();