generated from eea/volto-addon-template
-
Notifications
You must be signed in to change notification settings - Fork 0
/
i18n.cjs
executable file
·351 lines (326 loc) · 10 KB
/
i18n.cjs
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
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
#!/usr/bin/env node
/* eslint no-console: 0 */
/**
* i18n script.
* @module scripts/i18n
*/
const { find, keys, map, concat, reduce } = require('lodash');
const glob = require('glob').sync;
const fs = require('fs');
const Pofile = require('pofile');
const babel = require('@babel/core');
const path = require('path');
const projectRootPath = path.resolve('.');
const packageJson = require(path.join(projectRootPath, 'package.json'));
const { program } = require('commander');
const chalk = require('chalk');
/**
* Extract messages into separate JSON files
* @function extractMessages
* @return {undefined}
*/
function extractMessages() {
map(
// We ignore the existing customized shadowed components ones, since most
// probably we won't be overriding them
// If so, we should do it in the config object or somewhere else
// We also ignore the addons folder since they are populated using
// their own locales files and taken care separatedly in this script
glob('src/**/*.{js,jsx,ts,tsx}', {
ignore: ['src/customizations/**', 'src/addons/**'],
}),
(filename) => {
babel.transformFileSync(filename, {}, (err) => {
if (err) {
console.log(err);
}
});
},
);
}
/**
* Get messages from separate JSON files
* @function getMessages
* @return {Object} Object with messages
*/
function getMessages() {
return reduce(
concat(
{},
...map(
// We ignore the existing customized shadowed components ones, since most
// probably we won't be overriding them
// If so, we should do it in the config object or somewhere else
// We also ignore the addons folder since they are populated using
// their own locales files and taken care separatedly in this script
glob('build/messages/src/**/*.json', {
ignore: [
'build/messages/src/customizations/**',
'build/messages/src/addons/**',
],
}),
(filename) =>
map(JSON.parse(fs.readFileSync(filename, 'utf8')), (message) => ({
...message,
filename: filename.match(/build\/messages\/src\/(.*).json$/)[1],
})),
),
),
(current, value) => {
let result = current;
if (current.id) {
result = {
[current.id]: {
defaultMessage: current.defaultMessage,
filenames: [current.filename],
},
};
}
if (result[value.id]) {
result[value.id].filenames.push(value.filename);
} else {
result[value.id] = {
defaultMessage: value.defaultMessage,
filenames: [value.filename],
};
}
return result;
},
);
}
/**
* Convert messages to pot format
* @function messagesToPot
* @param {Object} messages Messages
* @return {string} Formatted pot string
*/
function messagesToPot(messages) {
return map(keys(messages).sort(), (key) =>
[
`#. Default: "${messages[key].defaultMessage.trim()}"`,
...map(messages[key].filenames, (filename) => `#: ${filename}`),
`msgid "${key}"`,
'msgstr ""',
].join('\n'),
).join('\n\n');
}
/**
* Pot header
* @function potHeader
* @return {string} Formatted pot header
*/
function potHeader() {
return `msgid ""
msgstr ""
"Project-Id-Version: Plone\\n"
"POT-Creation-Date: ${new Date().toISOString()}\\n"
"Last-Translator: Plone i18n <[email protected]>\\n"
"Language-Team: Plone i18n <[email protected]>\\n"
"Content-Type: text/plain; charset=utf-8\\n"
"Content-Transfer-Encoding: 8bit\\n"
"Plural-Forms: nplurals=1; plural=0;\\n"
"MIME-Version: 1.0\\n"
"Language-Code: en\\n"
"Language-Name: English\\n"
"Preferred-Encodings: utf-8\\n"
"Domain: volto\\n"
`;
}
/**
* Convert po files into json
* @function poToJson
* @return {undefined}
*/
function poToJson({ registry, addonMode }) {
const mergeMessages = (result, items, language) => {
items.forEach((item) => {
if (item.msgid in result) {
if (item.msgstr[0] !== '') {
result[item.msgid] = item.msgstr[0];
}
} else {
result[item.msgid] =
language === 'en'
? item.msgstr[0] ||
(item.comments[0] && item.comments[0].startsWith('. Default: ')
? item.comments[0].replace('. Default: ', '')
: item.comments[0] &&
item.comments[0].startsWith('defaultMessage:')
? item.comments[0].replace('defaultMessage: ', '')
: '')
: item.msgstr[0];
}
});
return result;
};
map(glob('locales/**/*.po'), (filename) => {
let { items } = Pofile.parse(fs.readFileSync(filename, 'utf8'));
const projectLocalesItems = Pofile.parse(fs.readFileSync(filename, 'utf8'))
.items;
const lang = filename.match(/locales\/(.*)\/LC_MESSAGES\//)[1];
const result = {};
// Merge volto core locales
const lib = `node_modules/@plone/volto/${filename}`;
if (fs.existsSync(lib)) {
const libItems = Pofile.parse(fs.readFileSync(lib, 'utf8')).items;
items = [...libItems, ...items];
mergeMessages(result, items, lang);
}
if (!addonMode) {
// Merge addons locales
if (packageJson.addons) {
registry.getAddonDependencies().forEach((addon) => {
const addonlocale = `${registry.packages[addon].modulePath}/../${filename}`;
if (fs.existsSync(addonlocale)) {
const addonItems = Pofile.parse(
fs.readFileSync(addonlocale, 'utf8'),
).items;
mergeMessages(result, addonItems, lang);
if (require.main === module) {
// We only log it if called as script
console.log(`Merging ${addon} locales for ${lang}`);
}
}
});
}
}
// Merge project locales, the project customization wins
mergeMessages(result, projectLocalesItems, lang);
fs.writeFileSync(`locales/${lang}.json`, JSON.stringify(result));
});
}
/**
* Format header
* @function formatHeader
* @param {Array} comments Array of comments
* @param {Object} headers Object of header items
* @return {string} Formatted header
*/
function formatHeader(comments, headers) {
return [
...map(comments, (comment) => `#. ${comment}`),
'msgid ""',
'msgstr ""',
...map(keys(headers), (key) => `"${key}: ${headers[key]}\\n"`),
'',
].join('\n');
}
/**
* Sync po by the pot file
* @function syncPoByPot
* @return {undefined}
*/
function syncPoByPot() {
const pot = Pofile.parse(fs.readFileSync('locales/volto.pot', 'utf8'));
const msgIds = pot.items.map((a) => a.msgid);
const localeFiles = fs.readdirSync('./locales');
const extraPots = localeFiles.filter(
(filename) => filename.endsWith('.pot') && filename !== 'volto.pot',
);
extraPots.forEach((potFileName) => {
let extraPot = Pofile.parse(
fs.readFileSync('locales/' + potFileName, 'utf8'),
);
extraPot.items.forEach((item) => {
if (!msgIds.includes(item.msgid)) {
msgIds.push(item.msgid);
pot.items.push(item);
}
});
});
map(glob('locales/**/*.po'), (filename) => {
const po = Pofile.parse(fs.readFileSync(filename, 'utf8'));
fs.writeFileSync(
filename,
`${formatHeader(po.comments, po.headers)}
${map(pot.items, (item) => {
const poItem = find(po.items, { msgid: item.msgid });
return [
`#. ${item.extractedComments[0]}`,
`${map(item.references, (ref) => `#: ${ref}`).join('\n')}`,
`msgid "${item.msgid}"`,
`msgstr "${poItem ? poItem.msgstr : ''}"`,
].join('\n');
}).join('\n\n')}\n`,
);
});
}
function main({ addonMode }) {
console.log('Extracting messages from source files...');
extractMessages();
console.log('Synchronizing messages to pot file...');
// We only write the pot file if it's really different
const newPot = `${potHeader()}${messagesToPot(getMessages())}\n`.replace(
/"POT-Creation-Date:(.*)\\n"/,
'',
);
const oldPot = fs
.readFileSync('locales/volto.pot', 'utf8')
.replace(/"POT-Creation-Date:(.*)\\n"/, '');
if (newPot !== oldPot) {
fs.writeFileSync(
'locales/volto.pot',
`${potHeader()}${messagesToPot(getMessages())}\n`,
);
}
console.log('Synchronizing messages to po files...');
syncPoByPot();
if (!addonMode) {
let AddonConfigurationRegistry;
try {
// Detect where is the registry (if we are in Volto 18 or above for either core and projects)
if (
fs.existsSync(
path.join(
projectRootPath,
'/node_modules/@plone/registry/src/addon-registry.js',
),
)
) {
AddonConfigurationRegistry = require(path.join(
projectRootPath,
'/node_modules/@plone/registry/src/addon-registry',
));
} else {
// We are in Volto 17 or below
// Check if core Volto or project
if (
fs.existsSync(
path.join(projectRootPath, '/node_modules/@plone/volto'),
)
) {
// We are in a project
AddonConfigurationRegistry = require(path.join(
projectRootPath,
'/node_modules/@plone/volto/addon-registry',
));
} else {
// We are in core (17 or below)
AddonConfigurationRegistry = require(path.join(
projectRootPath,
'addon-registry',
));
}
}
} catch {
console.log(
chalk.red(
'Getting the addon registry failed. Are you executing i18n from inside an addon? Try the -a flag.',
),
);
process.exit();
}
console.log('Generating the language JSON files...');
const registry = new AddonConfigurationRegistry(projectRootPath);
poToJson({ registry, addonMode });
}
console.log('done!');
}
// This is the equivalent of `if __name__ == '__main__'` in Python :)
if (require.main === module) {
program.option('-a, --addon', 'run i18n script for addons');
program.parse(process.argv);
const options = program.opts();
main({ addonMode: options.addon });
}
module.exports = { poToJson };