-
Notifications
You must be signed in to change notification settings - Fork 3
/
index.js
390 lines (307 loc) · 10.8 KB
/
index.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
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
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
/**
* @author Stanislav Kalashnik <[email protected]>
* @license GNU GENERAL PUBLIC LICENSE Version 3
*/
'use strict';
const
fs = require('fs'),
path = require('path'),
exec = require('child_process').exec,
serial = require('cjs-async/serial'),
name = 'gettext',
log = require('runner-logger').wrap(name),
tools = require('runner-tools');
function standardChannelsHandle ( stdout, stderr ) {
(stdout + stderr).trim().split('\n').forEach(function ( line ) {
if ( line.length !== 0 ) {
log.info(line);
}
});
}
function po2js ( poFile, jsonFile, compact, callback ) {
const
po = require('gettext-parser').po.parse(fs.readFileSync(poFile, {encoding: 'utf8'})),
contexts = po.translations,
result = {
meta: {
charset: po.charset,
project: po.headers['Project-Id-Version'],
language: po.headers.language,
plural: ''
},
data: {}
};
if ( po.headers['Plural-Forms'] ) {
result.meta.plural = po.headers['Plural-Forms'].split('plural=').pop().replace(';', '');
}
// fill items
Object.keys(contexts).sort().forEach(function ( contextName ) {
result.data[contextName] = result.data[contextName] || {};
Object.keys(contexts[contextName]).sort().forEach(function ( msgId ) {
if ( msgId ) {
if ( contexts[contextName][msgId].msgid_plural ) {
result.data[contextName][msgId] = contexts[contextName][msgId].msgstr;
} else {
result.data[contextName][msgId] = contexts[contextName][msgId].msgstr[0];
}
}
});
});
if ( compact ) {
tools.write([{name: jsonFile, data: JSON.stringify(result)}], log, callback);
} else {
tools.write([{name: jsonFile, data: JSON.stringify(result, null, ' ')}], log, callback);
}
}
function msginit ( config, potFile, poFile, language, callback ) {
let command = [
'msginit',
'--input="' + potFile + '"',
'--output="' + poFile + '"',
'--locale="' + language + '"',
'--no-translator'
];
// optional flags
config.noWrap && command.push('--no-wrap');
// final exec line
command = command.join(' ');
if ( config.verbose ) {
log.info('exec', command);
}
exec(command, function ( error, stdout, stderr ) {
if ( error ) {
log.fail(error.toString());
}
standardChannelsHandle(stdout, stderr);
/* eslint-disable-next-line handle-callback-err */
tools.read(poFile, log, function ( error, data ) {
data.toString().replace(
'Content-Type: text/plain; charset=ASCII',
'Content-Type: text/plain; charset=UTF-8'
);
tools.write([{name: poFile, data: data}], log, callback);
});
});
}
function msgmerge ( config, potFile, poFile, callback ) {
let command = [
'msgmerge',
'--update',
'--quiet',
'--verbose',
'--backup="off"'
];
// optional flags
config.indent && command.push('--indent');
config.noLocation && command.push('--no-location');
config.noWrap && command.push('--no-wrap');
config.sortOutput && command.push('--sort-output');
config.sortByFile && command.push('--sort-by-file');
config.noFuzzyMatching && command.push('--no-fuzzy-matching');
// merge
command.push(poFile);
command.push(potFile);
// final exec line
command = command.join(' ');
if ( config.verbose ) {
log.info('exec', command);
}
exec(command, function ( error, stdout, stderr ) {
if ( error ) {
log.fail(error.toString());
}
standardChannelsHandle(stdout, stderr);
callback();
});
}
function xgettext ( config, callback ) {
const
dstFile = path.join(config.source, 'messages.pot'),
pkgPath = path.join(process.cwd(), 'package.json');
let pkgInfo, command;
function scanPath ( fsPath ) {
if ( fs.statSync(fsPath).isDirectory() ) {
fs.readdirSync(fsPath).forEach(function ( item ) {
scanPath(path.join(fsPath, item));
});
} else {
command.push(fsPath);
}
}
delete require.cache[pkgPath];
pkgInfo = require(pkgPath);
command = [
'xgettext',
'--force-po',
'--output="' + dstFile + '"',
'--language="JavaScript"',
'--from-code="' + config.fromCode + '"',
'--package-name="' + pkgInfo.name + '"',
'--package-version="' + pkgInfo.version + '"',
'--msgid-bugs-address="' + (pkgInfo.author.email ? pkgInfo.author.email : pkgInfo.author) + '"'
];
// optional flags
config.indent && command.push('--indent');
config.noLocation && command.push('--no-location');
config.addLocation && command.push('--add-location=' + config.addLocation);
config.noWrap && command.push('--no-wrap');
config.sortOutput && command.push('--sort-output');
config.sortByFile && command.push('--sort-by-file');
config.addComments && command.push('--add-comments="' + config.addComments + '"');
// add input files to the params
config.jsData.forEach(scanPath);
// final exec line
command = command.join(' ');
if ( config.verbose ) {
log.info('exec', command);
}
exec(command, function ( error, stdout, stderr ) {
if ( error ) {
callback(error);
return;
}
standardChannelsHandle(stdout, stderr);
callback(error, dstFile);
});
}
function execPo ( config, done ) {
if (
Array.isArray(config.languages) && config.languages.length &&
Array.isArray(config.jsData) && config.jsData.length
) {
xgettext(config, function ( error, potFile ) {
if ( error ) {
log.fail(error.toString());
done();
return;
}
serial(config.languages.map(function ( language ) {
const poFile = path.join(config.source, language + '.po');
return function ( result ) {
fs.exists(poFile, function ( exists ) {
if ( exists ) {
// merge existing pot and po files
msgmerge(config, potFile, poFile, function () {
result(null);
});
} else {
// create a new lang file
msginit(config, potFile, poFile, language, function () {
result(null);
});
}
});
};
}), done);
});
} else {
log.info('no valid config options (check generator configuration)');
done();
}
}
function json ( config, done ) {
serial(config.languages.map(function ( language ) {
const
poFile = path.join(config.source, language + '.po'),
jsonFile = path.join(config.target, language + '.json');
return function ( result ) {
fs.exists(poFile, function ( exists ) {
if ( exists ) {
po2js(poFile, jsonFile, config.compact, function () {
result(null);
});
} else {
log.warn('doesn\'t exists: %s', log.colors.bold(poFile));
result(true);
}
});
};
}), function ( error ) {
done(error);
});
}
function build ( config, done ) {
execPo(config, function () {
json(config, done);
});
}
function clear ( config, done ) {
const files = [];
config.languages.forEach(function ( language ) {
files.push(path.join(config.target, language + '.json'));
});
tools.unlink(files, log, done);
}
function generator ( config = {}, options = {} ) {
const
tasks = {},
{prefix = name + ':', suffix = ''} = options;
// sanitize and extend defaults
config = Object.assign({
// dir with po and pot files
source: '.',
// directory with generated localization json files
target: '.',
// javascript source files
jsData: [],
// list of language codes in ISO 639-1 format to generate localization files for
languages: [],
// Specifies the encoding of the input files.
// This option is needed only if some untranslated message strings or their corresponding comments
// contain non-ASCII characters.
// @flag --from-code=name
fromCode: 'UTF-8',
// Place comment blocks starting with tag and preceding keyword lines in the output file.
// Without a tag, the option means to put all comment blocks preceding keyword lines in the output file.
// Note that comment blocks supposed to be extracted must be adjacent to keyword lines.
// @flag --add-comments[=tag]
addComments: 'gettext',
// Write the .po file using indented style.
// @flag --indent
indent: false,
// Write "#: filename:line" lines.
// @flag --no-location
noLocation: true,
// @flag --add-location
addLocation: 'file',
// Do not break long message lines.
// Message lines whose width exceeds the output page width will not be split into several lines.
// Only file reference lines which are wider than the output page width will be split.
// @flag --no-wrap
noWrap: true,
// Generate sorted output.
// Note that using this option makes it much harder for the translator to understand each message’s context.
// @flag --sort-output
sortOutput: true,
// Sort output by file location.
// @flag --sort-by-file
sortByFile: false,
// Increase verbosity level.
// @flag --verbose
verbose: false,
// generated json file mode
compact: false
}, config);
tasks[prefix + 'config' + suffix] = function () {
log.inspect(config, log);
};
tasks[prefix + 'build' + suffix] = function ( done ) {
build(config, done);
};
tasks[prefix + 'exec' + suffix] = function ( done ) {
execPo(config, done);
};
tasks[prefix + 'json' + suffix] = function ( done ) {
json(config, done);
};
tasks[prefix + 'clear' + suffix] = function ( done ) {
clear(config, done);
};
return tasks;
}
// export main actions
generator.methods = {
build: build
};
// public
module.exports = generator;