-
Notifications
You must be signed in to change notification settings - Fork 4
/
Copy pathcompile-translations.js
113 lines (100 loc) · 2.62 KB
/
compile-translations.js
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
const Papa = require('papaparse')
const fs = require('fs')
const path = require('path')
const root = path.join(__dirname, './src/i18n')
const source = fs.readFileSync(path.join(root, 'translations.csv'), 'utf8')
function loadTranslations () {
const translations = Papa.parse(source, {
delimiter: ',',
newline: '\n',
skipEmptyLines: true,
fastMode: false,
}).data
// Trim empty space from each item
for (const row of translations) {
for (let i = 0; i < row.length; i++) {
row[i] = row[i].trim()
if (row[i].startsWith('\"')) {
row[i] = row[i].substr(1)
}
}
}
const locales = translations.shift().filter(t => t !== 'key' && t !== 'comment')
return {
translations,
locales,
}
}
function cleanExisting () {
const existing = fs.readdirSync(root).filter(fn => fn.endsWith('.json'))
for (const p of existing) {
const f = path.join(root, p)
console.log('removing', f)
fs.unlinkSync(f)
}
}
function transform ({ translations, locales }) {
console.log('compiling locales', locales)
// Transform the translations into this format
/**
* {
* en: {
* title: 'Trellis'
* },
* es: {
* title: 'Trellis'
* }
* }
*/
const errors = {
size: [],
duplicates: [],
missing: [],
}
let messages = locales.reduce((agg, l) => {
agg[l] = {}
return agg
}, {})
messages = translations.reduce((coll, t) => {
for (let i = 0; i < locales.length; i++) {
if (t[i + 1]) {
const l = locales[i]
const key = t[0]
const msg = t[i + 1]
// Simple length check to identify errors
if (msg.length < 2) {
errors.size.push({ locale: l, key, msg, line: i })
}
if (key in coll[l]) {
const dup = coll[l][key]
errors.duplicates.push({ locale: l, key, msg, dup, line: i })
}
coll[l][key] = msg
} else {
errors.missing.push({ locale: locales[i], key: t[0], line: i })
}
}
return coll
}, messages)
// Write the files
for (const l of locales) {
const data = messages[l]
const f = path.join(root, `${l}.json`)
console.log('writing file', f)
fs.writeFileSync(f, JSON.stringify(data, null, 2), 'utf8')
}
// Write any discovered errors
if (errors.duplicates.length || errors.general.length) {
f = path.join(root, 'errors.json')
console.log('writing errors', f)
fs.writeFileSync(f, JSON.stringify(errors, null, 2), 'utf8')
}
}
if (require.main === module) {
cleanExisting()
const data = loadTranslations()
transform(data)
}
module.exports = {
loadTranslations,
}