forked from yeatmanlab/roar-dashboard
-
Notifications
You must be signed in to change notification settings - Fork 4
Expand file tree
/
Copy pathadd-locale-column.js
More file actions
84 lines (73 loc) · 2.41 KB
/
Copy pathadd-locale-column.js
File metadata and controls
84 lines (73 loc) · 2.41 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
#!/usr/bin/env node
import fs from 'node:fs';
import path from 'node:path';
import Papa from 'papaparse';
const consolidatedRoot = path.join('src', 'translations', 'consolidated');
function listCsvFiles() {
const roots = [consolidatedRoot, path.join(consolidatedRoot, 'components')];
const files = [];
for (const root of roots) {
if (!fs.existsSync(root)) continue;
for (const entry of fs.readdirSync(root)) {
const fp = path.join(root, entry);
if (fs.statSync(fp).isFile() && fp.toLowerCase().endsWith('.csv')) files.push(fp);
}
}
return files;
}
function parseCsv(text) {
const { data } = Papa.parse(text, { header: true, skipEmptyLines: true });
return Array.isArray(data) ? data : [];
}
function toCsvLine(values) {
return values
.map((v) => {
const s = v == null ? '' : String(v);
const escaped = s.replace(/\r?\n/g, '\\n').replace(/\r/g, '\\r');
return escaped.includes(',') || escaped.includes('"') || s.includes('\n') || s.includes('\r')
? `"${escaped.replace(/"/g, '""')}"`
: escaped;
})
.join(',');
}
function writeCsv(filePath, rows) {
if (!rows.length) return;
const headers = Object.keys(rows[0]);
const out = [toCsvLine(headers)];
rows.forEach((r) => {
out.push(toCsvLine(headers.map((h) => r[h] ?? '')));
});
fs.writeFileSync(filePath, out.join('\n'));
}
function main() {
const targetLocale = (process.env.I18N_NEW_LOCALE || '').trim();
const seedFrom = (process.env.I18N_SEED_FROM || '').trim();
if (!targetLocale) {
console.error('Usage: I18N_NEW_LOCALE=<locale> [I18N_SEED_FROM=<base>] node add-locale-column.js');
process.exit(1);
}
const files = listCsvFiles();
if (!files.length) {
console.log('No CSV files found.');
process.exit(0);
}
for (const file of files) {
const raw = fs.readFileSync(file, 'utf8');
const rows = parseCsv(raw);
if (!rows.length) continue;
const headers = Object.keys(rows[0]);
if (headers.includes(targetLocale)) {
console.log(`⏭ ${file} already has column ${targetLocale}`);
continue;
}
const seeded = rows.map((r) => {
const clone = { ...r };
if (seedFrom && seedFrom in r) clone[targetLocale] = r[seedFrom];
else clone[targetLocale] = '';
return clone;
});
writeCsv(file, seeded);
console.log(`✅ Added ${targetLocale} to ${file}${seedFrom ? ` (seeded from ${seedFrom})` : ''}`);
}
}
main();