-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathpo2json.js
45 lines (42 loc) · 1.32 KB
/
po2json.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
/* eslint-disable require-jsdoc */
import fs from 'fs';
import path from 'path';
import {po} from 'gettext-parser';
for (const arg of process.argv.slice(2)) {
const outpath = './src/' + path.basename(arg) + '.ts';
console.log(`${arg} => ${outpath}`);
writePoFile(arg, outpath);
}
function assertHeader(name, value) {
if (!value) {
throw new Error(`Bad .po file. "${name}" header is missing`);
}
}
function writePoFile(inpath, outpath) {
const input = fs.readFileSync(inpath).toString().normalize();
const poData = po.parse(input);
const pluralHeader =
poData.headers['plural-forms'] || poData.headers['Plural-Forms'];
const language = poData.headers.language || poData.headers.Language;
assertHeader('Plural-Forms', pluralHeader);
assertHeader('Language', language);
const dict = {};
for (const msg of Object.values(poData.translations[''])) {
const msgid = msg.msgid;
const msgstr = msg.msgstr;
if (msgid && msgid.length && msgstr && msgstr.length) {
dict[msgid] = msgstr;
}
}
const compactPo = {
headers: {
'plural-forms': pluralHeader,
language: language,
},
contexts: {'': dict},
};
const outstream = fs.createWriteStream(outpath, {flags: 'w'});
outstream.write('export default ');
outstream.write(JSON.stringify(compactPo, null, 0));
outstream.end();
}